QT中实现类似网页搜索的自动出现下拉提示

来源:互联网 发布:海南知和行书局 编辑:程序博客网 时间:2024/06/05 16:30

要实现一个在输入框中输入字时,自动出现一个下拉框提示相关的搜索词语。在网上搜了一下,没搜到有QT中相关的实现,就自己动手实现了一个。

class HintList : public QListWidget 
#include "HintList.h"HintList::HintList(QWidget *parent) : QListWidget(parent){    myTimer=new QTimer();    myTimer->start(2000);    connect(myTimer,SIGNAL(timeout()),this,SLOT(checkSlots()));}HintList::~HintList(){}void HintList::ShowUI(){    this->show();    myTimer->stop();    myTimer->start();}void HintList::keyPressEvent(QKeyEvent *event){    if(event->key() == Qt::Key_Down)    {        this->setCurrentRow(this->currentRow()+1);        myTimer->stop();        myTimer->start();    }    else if(event->key() == Qt::Key_Up)    {        this->setCurrentRow(this->currentRow()-1);        myTimer->stop();        myTimer->start();    }    else if(event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return)    {        emit choiceStr(this->currentItem()->text());        this->close();    }}void HintList::checkSlots(){    myTimer->stop();    this->close();}

实现:

m_list_hint= new HintList(this);m_list_hint->hide();connect(ui->lineEdit_fromStation,SIGNAL(textChanged(QString)),this,SLOT(flushFromStationListWidget(QString)));connect(m_list_hint,SIGNAL(clicked(QModelIndex)),this,SLOT(onClickedListWidget(QModelIndex)));connect(m_list_hint,SIGNAL(choiceStr(QString)),this,SLOT(changeFromStationText(QString)));……void Sale::flushFromStationListWidget(QString str){    m_list_hint->clear();    m_list_hint->addItem("dsa");    m_list_hint->addItem("eea");    m_list_hint->addItem("武汉a");    int x = ui->lineEdit_fromStation->x() + 4;    int y = ui->lineEdit_fromStation->y() + 44;    int w = ui->lineEdit_fromStation->width();    int h = m_list_hint->count() * 20 ;    m_list_hint->setGeometry(x,y,w,h);    m_list_hint->setCurrentRow(0);    m_list_hint->ShowUI();}void Sale::keyPressEvent(QKeyEvent *event){    if(event->key() == Qt::Key_Down)    {        if(this->focusWidget() == ui->lineEdit_fromStation)        {            m_list_hint->setFocus();            m_list_hint->setCurrentRow(0);        }    }}void Sale::onClickedListWidget(QModelIndex index){    ui->lineEdit_fromStation->setText(m_list_hint->item(index.row())->text());    m_list_hint->hide();}void Sale::changeFromStationText(QString text){    ui->lineEdit_fromStation->setText(text);}
0 0
原创粉丝点击