关于搜索框,你们都常常接触。例如:浏览器搜索、Windows资源管理器搜索等。浏览器
固然,这些对于Qt实现来讲毫无压力,只要思路清晰,分分钟搞定。函数
方案一:调用QLineEdit现有接口布局
void addAction(QAction * action, ActionPosition position)
在QLineEdit的前/后添加部件,ActionPosition表示部件所在方位。ui
QAction * addAction(const QIcon & icon, ActionPosition position)
重载函数。this
枚举:QLineEdit::ActionPositionurl
常量 | 值 | 描述 |
---|---|---|
QLineEdit::LeadingPosition | 0 | 当使用布局方向Qt::LeftToRight时,部件显示在文本左侧,使用Qt::RightToLeft则显示在右侧。 |
QLineEdit::TrailingPosition | 1 | 当使用布局方向Qt::LeftToRight时,部件显示在文本右侧,使用Qt::RightToLeft则显示在左侧。 |
下面,咱们来针对自定义进行讲解。spa
实现细节须要以下步骤:.net
为了更人性、易用,这里有一些细节须要注意:code
这些都想清楚了,咱们就能快速实现一个搜索框了。orm
搜索框实现
m_pSearchLineEdit = new QLineEdit(); QPushButton *pSearchButton = new QPushButton(this); pSearchButton->setCursor(Qt::PointingHandCursor); pSearchButton->setFixedSize(22, 22); pSearchButton->setToolTip(QStringLiteral("搜索")); pSearchButton->setStyleSheet("QPushButton{border-image:url(:/images/icon_search_normal); background:transparent;} \ QPushButton:hover{border-image:url(:/images/icon_search_hover)} \ QPushButton:pressed{border-image:url(:/images/icon_search_press)}"); //防止文本框输入内容位于按钮之下 QMargins margins = m_pSearchLineEdit->textMargins(); m_pSearchLineEdit->setTextMargins(margins.left(), margins.top(), pSearchButton->width(), margins.bottom()); m_pSearchLineEdit->setPlaceholderText(QStringLiteral("请输入搜索内容")); QHBoxLayout *pSearchLayout = new QHBoxLayout(); pSearchLayout->addStretch(); pSearchLayout->addWidget(pSearchButton); pSearchLayout->setSpacing(0); pSearchLayout->setContentsMargins(0, 0, 0, 0); m_pSearchLineEdit->setLayout(pSearchLayout); connect(pSearchButton, SIGNAL(clicked(bool)), this, SLOT(search()));
槽函数实现
void Widget::search() { QString strText = m_pSearchLineEdit->text(); if (!strText.isEmpty()) { QMessageBox::information(this, QStringLiteral("搜索"), QStringLiteral("搜索内容为%1").arg(strText)); } }
http://blog.csdn.net/liang19890820/article/details/50357523