How to create custom shortcut with Qt?

Viewed 69

In my app there is button that when you click on it the main window will be hid then if you type a shortcut the main window will show again.

But the shortcut doesn't work.

Here's my code for the shortcut:

QShortcut *shortcut = new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_K), this);

QObject::connect(shortcut, &QShortcut::activated, this, &MainWindow::openWindow);
1 Answers

For adding shortcut you set its parent this. If you close or hide MainWindow means that the shortcut couldn't work because its parent was not called or found. When you close or hide the window, another screen like your desktop is displayed, so the shortcut does not work.

For example if you write this code :

 shortcut = new QShortcut(QKeySequence(tr("Ctrl+k", "Open/Close window")), this);
 connect(shortcut, &QShortcut::activated, this, &MainWindow::hide);

when you press Ctrl+k you see that your main window will hide and the shortcut works correctly. but after that, your desktop will appear and its shortcut will work.

Related