關於搜索框,你們都常常接觸。例如:瀏覽器搜索、Windows資源管理器搜索等。瀏覽器
固然,這些對於Qt實現來講毫無壓力,只要思路清晰,分分鐘搞定。markdown
實現細節須要以下步驟:函數
爲了更人性、易用,這裏有一些細節須要注意:ui
這些都想清楚了,咱們就能快速實現一個搜索框了。this
搜索框實現url
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()));
槽函數實現spa
void Widget::search()
{
QString strText = m_pSearchLineEdit->text();
if (!strText.isEmpty())
{
QMessageBox::information(this, QStringLiteral("搜索"), QStringLiteral("搜索內容爲%1").arg(strText));
}
}
原文做者:一去丶二三裏
做者博客:去做者博客空間