本文共 1575 字,大约阅读时间需要 5 分钟。
关于搜索框,大家都经常接触。例如:浏览器搜索、Windows资源管理器搜索等。
当然,这些对于Qt实现来说毫无压力,只要思路清晰,分分钟搞定。
实现细节需要如下步骤:
为了更人性、易用,这里有一些细节需要注意:
这些都想清楚了,我们就能快速实现一个搜索框了。
搜索框实现
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)); }}