我在网上搜索了答案,但我找不到能解决问题的答案。我的问题是:我有一个QComboBox
,让我说我添加了三个项目:
ui->comboBox->addItem("First");
ui->comboBox->addItem("Second");
ui->comboBox->addItem("Third");
然后,如果我按下键盘上的S
,项目将更改为Second
,如果我按T
,则项目将更改为Third
。
如何禁用此功能?
答案 0 :(得分:2)
一种可能的解决方案是实施eventfilter
,以防止在QComboBox
中使用这些字母:
#include <QApplication>
#include <QComboBox>
#include <QKeyEvent>
class Helper: public QObject{
QComboBox *m_combo;
public:
using QObject::QObject;
void setComboBox(QComboBox *combo){
m_combo = combo;
m_combo->installEventFilter(this);
}
bool eventFilter(QObject *watched, QEvent *event){
if(m_combo){
if(m_combo == watched && event->type() == QEvent::KeyPress){
QKeyEvent *ke = static_cast<QKeyEvent *>(event);
if(!ke->text().isEmpty())
return true;
}
}
return QObject::eventFilter(watched, event);
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QComboBox w;
w.addItems({"First", "Second","Third"});
Helper helper;
helper.setComboBox(&w);
w.show();
return a.exec();
}