给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(0000);

    buttonLayout->addStretch();

    buttonLayout->addWidget(this);

    edit->setLayout(buttonLayout);


    // 设置输入框中文件输入区,不让输入的文字在被隐藏在按钮下

    edit->setTextMargins(01, 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;

}


  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值