1. 程式人生 > >Qt:給QLineEdit加上一個搜尋按鈕

Qt:給QLineEdit加上一個搜尋按鈕

原文地址:原文連結

效果圖如下:

 

 

工程檔案:/Files/biao/SearchButton.7z

 

/**********************************************

 *                 SearchButton.h

 *********************************************/

 

#ifndef SEARCHBUTTON_H

#define SEARCHBUTTON_H

 

#include <QPushButton>

 

class QLineEdit;

class QString;

 

class SearchButton : public QPushButton {

    Q_OBJECT

public:

    SearchButton(const QString &text, QLineEdit *edit);

};

 

#endif // SEARCHBUTTON_H

 

 

/**********************************************

 *                  SearchButton.cpp

 *********************************************/

#include "SearchButton.h"

#include <QtGui/QLineEdit>

#include <QtGui/QHBoxLayout>

 

SearchButton::SearchButton(const QString &text, QLineEdit *edit)

    : QPushButton(text, edit) {

    QSize size = QSize(40, edit->sizeHint().height());

    setMinimumSize(size);

    setMaximumSize(size);           // 設定按鈕的大小為圖片的大小

    setFocusPolicy(Qt::NoFocus);    // 得到焦點時,不顯示虛線框

    setFlat(true);

    setText(text);

    setCursor(QCursor(Qt::PointingHandCursor));

 

    QHBoxLayout *buttonLayout = new QHBoxLayout();

    buttonLayout->setContentsMargins(0, 0, 0, 0);

    buttonLayout->addStretch();

    buttonLayout->addWidget(this);

    edit->setLayout(buttonLayout);

 

    // 設定輸入框中檔案輸入區,不讓輸入的文字在被隱藏在按鈕下

    edit->setTextMargins(0, 1, size.width(), 1);

 

    // 設定style sheet

    /*.SearchButton {

        background: gray; color: white; border: 1 solid gray;

        min-width: 40px;

    }

 

    .SearchButton:hover {

        background: black; color: white; border: 1 solid black;

    }

 

    .SearchButton:pressed {

        background: white;

        color: black;

    }*/

 

    // 為了方便起見, 幫把 style sheet 寫到程式碼裡, 實際工作中應該放到專用的style sheet裡, 方便修改

    QString qss = QString(".SearchButton {background: gray; color: white; border: 1 solid gray;min-width: 40px;}")

            + QString(".SearchButton:hover {background: black; color: white; border: 1 solid black;}")

            + QString(".SearchButton:pressed {background: white;color: black;}");

    setStyleSheet(qss);

}

 

/**********************************************

 *                  Widget.cpp

 *********************************************/

#include "Widget.h"

#include "ui_Widget.h"

#include "SearchButton.h"

 

Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget) {

    ui->setupUi(this);

    new SearchButton(tr("搜尋"), ui->lineEdit_1); // 使用方法

    new SearchButton(tr("搜尋"), ui->lineEdit_2);

}

 

Widget::~Widget() {

    delete ui;

}