Assign shortcut keys to buttons - Qt C++

前端 未结 4 1999
野趣味
野趣味 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 18:51

    Today (Qt5.7), we can assign shortcuts directly in Qt Designer using the shortcut property:

    Pretty handy.. Even if a bit buggy: I have to "validate" the shortcut by clicking on another property of the same widget before switching to another widget!

    But it works.

    0 讨论(0)
  • 2021-01-31 18:58

    Alternatively, if the shortcut key corresponds to some character in the text of the button, you can preped & to that character. If you want a literal &, use &&.

    0 讨论(0)
  • 2021-01-31 19:09

    Your buttons probably have a slot connected to their clicked() signal.

    To add shortcut keys, you simply connect a shortcut key's activated() signal to the same slot.

    In your code, #include <QShortcut> and then you will be able to add a shortcut key for a slot like this:

    QShortcut *shortcut = new QShortcut(QKeySequence("Ctrl+O"), parent);
    QObject::connect(shortcut, SIGNAL(activated()), receiver, SLOT(yourSlotHere()));
    

    Where parent is the parent of your shortcut (for example the main window), yourSlotHere() is the name of the slot you want the shortcut to call, and receiver the object where yourSlotHere() is.

    Replace "Ctrl+O" with whatever shortcut you want to assign.

    You can also find more information on the documentation page for QShortcut.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题