【问题标题】:How to disable shortcuts for QComboBox in qt?如何在 qt 中禁用 QComboBox 的快捷方式?
【发布时间】:2018-05-17 08:38:45
【问题描述】:

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

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

然后如果我按键盘上的S,项目将更改为Second,如果我按T,项目将更改为Third

如何禁用此功能?

【问题讨论】:

    标签: c++ qt qt5 qcombobox


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2018-11-25
      • 1970-01-01
      • 1970-01-01
      • 2021-11-19
      • 2018-02-11
      • 1970-01-01
      • 1970-01-01
      • 2011-08-03
      • 1970-01-01
      相关资源
      最近更新 更多