1. 程式人生 > >Qt之自定義搜索框——QLineEdit裏增加一個Layout,還不影響正常輸入文字(好像是一種比較通吃的方法)

Qt之自定義搜索框——QLineEdit裏增加一個Layout,還不影響正常輸入文字(好像是一種比較通吃的方法)

too 步驟 set box 文本 csdn sub void 鼠標

簡述

關於搜索框,大家都經常接觸。例如:瀏覽器搜索、Windows資源管理器搜索等。

技術分享

技術分享

當然,這些對於Qt實現來說毫無壓力,只要思路清晰,分分鐘搞定。

  • 方案一:調用QLineEdit現有接口

    • void addAction(QAction * action, ActionPosition position)
      在QLineEdit的前/後添加部件,ActionPosition表示部件所在方位。

    • QAction * addAction(const QIcon & icon, ActionPosition position)
      重載函數。

枚舉:QLineEdit::ActionPosition

常量描述
QLineEdit::LeadingPosition 0 當使用布局方向Qt::LeftToRight時,部件顯示在文本左側,使用Qt::RightToLeft則顯示在右側。
QLineEdit::TrailingPosition 1 當使用布局方向Qt::LeftToRight時,部件顯示在文本右側,使用Qt::RightToLeft則顯示在左側。
  • 方案二:自定義(可以實現任何組合)

下面,我們來針對自定義進行講解。

  • 簡述
  • 效果
  • 細節分析
  • Coding
  • 源碼下載

效果

技術分享

細節分析

實現細節需要如下步驟:

  1. 組合實現,輸入框+按鈕
  2. 事件關聯
  3. 獲取輸入文本,進行文本搜索

為了更人性、易用,這裏有一些細節需要註意:

  1. 輸入框的文本不能處於按鈕之下
  2. 輸入框無文本時必須給與友好性提示
  3. 按鈕無文本描述,一般需要給予ToolTip提示
  4. 按鈕樣式-正常、滑過、按下,以及鼠標滑過鼠標樣式手型,

這些都想清楚了,我們就能快速實現一個搜索框了。

Coding

搜索框實現

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));
    }
}

源碼下載

  • Qt之自定義搜索框
  • Qt之QLineEdit

http://blog.csdn.net/liang19890820/article/details/50357523

Qt之自定義搜索框——QLineEdit裏增加一個Layout,還不影響正常輸入文字(好像是一種比較通吃的方法)