How do I assign a shortcut to a QPushButton?
Asked Answered
N

4

11

The documentation on assigning a shortcut to a QPushButton is as follows:


A shortcut key can be specified by preceding the preferred character with an ampersand in the text. For example:

QPushButton *button = new QPushButton("&Download", this);

In this example the shortcut is Alt+D.


What do I do if I don't want an Alt+[A-Z] shortcut? For example, in my case I want my button to be fired when the TAB button is pressed. How can I achieve this effect?

Nicky answered 22/9, 2014 at 15:3 Comment(0)
U
17

You can use setShortcut method, eg:

pushButton->setShortcut(QKeySequence(Qt::Key_Tab));

It will fire then slots assigned to the clicked() signal

Unexceptional answered 22/9, 2014 at 15:15 Comment(0)
O
3

You can use a QShortcut. Another tip: Qt signal / slots mechanism allows you to connect a signal to a signal.

Offertory answered 22/9, 2014 at 15:10 Comment(0)
I
0

You can overload QWidget::keyPressEvent and trigger your button click directly or through previously specially connected signal

void MainWindow::keyPressEvent(QKeyEvent * pEvent)
{
    if (Qt::Key_Tab == pEvent->key())
    {
        ui->button->click();
    }

    QMainWindow::keyPressEvent(pEvent);
}
Infantile answered 22/9, 2014 at 15:11 Comment(0)
D
0

You can define the key, the target object and it's relevant slot in the constructor of QShortcut :

QShortcut * shortcut = new QShortcut(QKeySequence(Qt::Key_Tab),button,SLOT(click()));
shortcut->setAutoRepeat(false);
Darkling answered 22/9, 2014 at 15:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.