如何在 qt 中禁用 QComboBox 的快捷方式?

How to disable shortcuts for QComboBox in qt?

我在网上搜索了答案,但没有找到真正解决我问题的答案。我的问题是:我有一个 QComboBox,假设我向其中添加了三个项目:

ui->comboBox->addItem("First");
ui->comboBox->addItem("Second");
ui->comboBox->addItem("Third");

然后如果我按键盘上的S,项目就会变成Second,如果我按T,那么项目就会变成Third .

如何禁用它?

一个可能的解决方案是实现一个 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();
}