【Qt】Qt之自定義搜索框【轉】

簡述

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

這裏寫圖片描述

這裏寫圖片描述

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

效果

這裏寫圖片描述

細節分析

實現細節須要以下步驟:函數

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

爲了更人性、易用,這裏有一些細節須要注意:ui

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

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

Coding

搜索框實現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));
    }
}

源碼下載


原文做者:一去丶二三裏
做者博客:去做者博客空間
相關文章
相關標籤/搜索