Assign shortcut keys to buttons - Qt C++

前端 未结 4 2007
野趣味
野趣味 2021-01-31 18:17

I have created a GUI using Qt Creator. That is by drag and drop the widgets. Now I want to assign shortcut keys for all of the buttons. Can anyone here please let me know how to

4条回答
  •  佛祖请我去吃肉
    2021-01-31 19:09

    From a good UI/UX perspective, what you actually what you want is not just to trigger the same slot as the button triggers (which is the solution suggested by the accepted answer) but you also want to visually animate the button being pressed to make sure the user clearly can visually notice the action being triggered. The following is what I use for example for my 'confirm' QPushButtons.

    // I have this function in my 'utils' module.
    void bindShortcut(QAbstractButton *button, const QKeySequence &shortcut)  
    {
        QObject::connect(new QShortcut(shortcut, button), &QShortcut::activated, [button](){ button->animateClick(); });
    }
    
    // and then I use it like this
    auto *confirmButton = new QPushButton(tr("Confirm"));
    connect(confirmButton, &QPushButton::clicked, ... some slot of yours to do the actual work);
    bindShortcut(confirmButton, Qt::Key_Enter);
    bindShortcut(confirmButton, Qt::Key_Return);
    

    This is I think the best answer if you are not using QtDesigner. Otherwise you can set the shortcuts in the designer easily as another answer suggests.

提交回复
热议问题