1. 什么也不要说,先上效果图:
2. 代码
头文件:
#ifndef APPSEARCHLINE_H #define APPSEARCHLINE_H #include <QLineEdit> class AppSearchLine : public QLineEdit { Q_OBJECT public: AppSearchLine(QWidget *parent = 0); }; #endif // APPSEARCHLINE_H源文件
#include "appsearchline.h" #include <QHBoxLayout> #include <QPushButton> AppSearchLine::AppSearchLine(QWidget *parent) :QLineEdit(parent) { QHBoxLayout *mainLayout = new QHBoxLayout; QPushButton *searchBtn = new QPushButton; searchBtn->setFixedSize(13,13); searchBtn->setCursor(Qt::PointingHandCursor); searchBtn->setToolTip(tr("搜索")); searchBtn->setStyleSheet("QPushButton{border-image:url(:/image/resources/image/search-icon.png);" "background:transparent;cursor:pointer;}"); setPlaceholderText(tr("搜索")); mainLayout->addWidget(searchBtn); mainLayout->addStretch(); //mainLayout->setContentsMargins(8,8,8,8); mainLayout->setContentsMargins(8,0,0,0); setTextMargins(13+8+2,0,0,0); setContentsMargins(0,0,0,0); setLayout(mainLayout); setStyleSheet("height:29px;border:1px solid #eaeaea;border-radius:14px;"); }
简单讲一下代码,这里用到的搜索图标大小为13*13,所以那个搜索按钮设置为固定大小13*13,代码中的
mainLayout->setContentsMargins(8,0,0,0);这里设置的8个长度是图标左边的宽度,这样图标就不会紧挨着搜索框的边框了。还有一句
setTextMargins(13+8+2,0,0,0);这里13是图标的宽度,8是布局的left margin,也就是上面设置的那个,2是额外的留白,主要是为了美观。
好了,代码就是那么简单。