Qt QComboBox+QCompleter實現搜索自動匹配


搜索框默認隱藏起來,在界面上按Ctrl+F的時候打開搜索匹配輸入框

 1     m_speedSearch = new SpeedSearch(this);  2     m_speedSearch->initData(QStringList() << "123" << "124" << "110" << "111");  3     m_speedSearch->hide();  4 
 5     QShortcut *shortcut = new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_F), this);  6     connect(shortcut, SIGNAL(activated()), this, SLOT(slotSpeedSearch()));  7 
 8     void MainWindow::slotSpeedSearch()  9  { 10         m_speedSearch->move(100, 50); 11         m_speedSearch->show(); 12     }

打開后清空之前的顯示並且將焦點設置到編輯框

1 void SpeedSearch::showEvent(QShowEvent *event) 2 { 3     QWidget::showEvent(event); 4     m_comboBox->setCurrentText(""); 5     m_comboBox->setFocus(); 6 }

數據初始化

 1 void SpeedSearch::initData(const QStringList &strList)  2 {  3     if (m_completer) {  4         delete m_completer;  5  }  6     m_completer = new QCompleter(strList, this);  7     m_completer->setFilterMode(Qt::MatchContains);  8     m_comboBox->setCompleter(m_completer);  9     m_comboBox->clear(); 10     m_comboBox->addItems(strList); 11 }

匹配規則設置為contains否則從第一個字符開始匹配,中間的匹配不了。給ComboBox也初始化數據這樣點擊彈出按鈕后列表框也有數據

speed_search.h

 1 #pragma once
 2 
 3 #include <QWidget>
 4 
 5 class QComboBox;  6 class QCompleter;  7 class SpeedSearch : public QWidget  8 {  9  Q_OBJECT 10 public: 11     explicit SpeedSearch(QWidget *parent = 0); 12     void initData(const QStringList &strList); 13 
14 public slots: 15     void slotCurrentIndexChanged(const QString &str); 16 
17 protected: 18     void showEvent(QShowEvent *event); 19 
20 private: 21     QComboBox *m_comboBox; 22     QCompleter *m_completer; 23 };

speed_search.cpp

 1 #include "speed_search.h"
 2 #include <QtWidgets>
 3 
 4 SpeedSearch::SpeedSearch(QWidget *parent)  5  : QWidget(parent)  6  , m_completer(nullptr)  7 {  8     m_comboBox = new QComboBox(this);  9     m_comboBox->setEditable(true); 10     connect(m_comboBox, SIGNAL(currentIndexChanged(QString)), this, SLOT(slotCurrentIndexChanged(QString))); 11 
12     QVBoxLayout *vLayout = new QVBoxLayout(this); 13     vLayout->setContentsMargins(0, 0, 0, 0); 14     vLayout->setSpacing(0); 15     vLayout->addWidget(m_comboBox); 16 
17     this->setFixedSize(150, 24); 18 } 19 
20 void SpeedSearch::initData(const QStringList &strList) 21 { 22     if (m_completer) { 23         delete m_completer; 24  } 25     m_completer = new QCompleter(strList, this); 26     m_completer->setFilterMode(Qt::MatchContains); 27     m_comboBox->setCompleter(m_completer); 28     m_comboBox->clear(); 29     m_comboBox->addItems(strList); 30 } 31 
32 void SpeedSearch::slotCurrentIndexChanged(const QString &str) 33 { 34     qDebug() << str; 35  hide(); 36 } 37 
38 void SpeedSearch::showEvent(QShowEvent *event) 39 { 40     QWidget::showEvent(event); 41     m_comboBox->setCurrentText(""); 42     m_comboBox->setFocus(); 43 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM