Assign shortcut keys to buttons - Qt C++

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 do that? Thank you in advance.


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.

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 &&.

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.

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.

Need Your Help

Downloading large files reliably in PHP

php download

I have a php script on a server to send files to recipents: they get a unique link and then they can download large files. Sometimes there is a problem with the transfer and the file is corrupted or

What's the difference between Show(), ShowDialog() and Application.Run() functions?

c# winforms

What's the difference between new Show(), ShowDialog() and Application.Run() functions?