How to assign a shortcut to QPushButton?

The label assignment documentation for QPushButton is as follows:


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

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

In this example, the shortcut is Alt + D.


What should I do if I do not need the Alt+[AZ] shortcut? For example, in my case, I want my button to be triggered when the TAB button is pressed. How can I achieve this effect?

+5
source share
4 answers

You can use setShortcut , for example:

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

Then, the slots assigned to the clicked() signal will be split

+7
source

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

+3
source

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

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

You can define the key, target, and corresponding slot in the QShortcut constructor:

 QShortcut * shortcut = new QShortcut(QKeySequence(Qt::Key_Tab),button,SLOT(click())); shortcut->setAutoRepeat(false); 
0
source

Source: https://habr.com/ru/post/1203146/


All Articles