Evgenii Legotckoi
Aug. 30, 2015, 8:33 p.m.

Qt/C++ - Lesson 012. QShortcut – How to work with Hot Keys in Qt?

Even in the official documentation on the topic QShortcut written not so much, so it's probably a note not to forget, not a full-fledged article. Just a few words about how to connect QShortcut entity that will be responsible for processing pressing a hotkey or keyboard shortcuts, such as Ctrl + D .

Project structure for QShortcut

The project structure is so trivial that I will not even bring it in this article. I shall confine myself to only those words that we will work with two files:

  • mainwindow.h
  • mainwindow.cpp

And even mainwindow.ui file will not touch this project. As it will be created by default, so it and leave.


mainwindow.h

The header file is required to declare two objects QShortcut, as well as for the treatment of hot keystrokes methods.

  1. #ifndef MAINWINDOW_H
  2. #define MAINWINDOW_H
  3.  
  4. #include <QMainWindow>
  5. #include <QShortcut>
  6. #include <QMessageBox>
  7.  
  8. namespace Ui {
  9. class MainWindow;
  10. }
  11.  
  12. class MainWindow : public QMainWindow
  13. {
  14. Q_OBJECT
  15.  
  16. public:
  17. explicit MainWindow(QWidget *parent = 0);
  18. ~MainWindow();
  19.  
  20. private slots:
  21. // slots for handlers of hotkeys
  22. void slotShortcutF11();
  23. void slotShortcutCtrlD();
  24.  
  25. private:
  26. Ui::MainWindow *ui;
  27. QShortcut *keyF11; // Entity of F11 hotkey
  28. QShortcut *keyCtrlD; // Entity of Ctrl + D hotkeys
  29. };
  30.  
  31. #endif // MAINWINDOW_H

mainwindow.cpp

Minimal setup a hotkey is:

  • to initialize the object, which will be responsible for the hot key or shortcut;
  • transfer of hot keys code into object;
  • connecting slot handler to signal of QShortcut object.
  1. #include "mainwindow.h"
  2. #include "ui_mainwindow.h"
  3.  
  4. MainWindow::MainWindow(QWidget *parent) :
  5. QMainWindow(parent),
  6. ui(new Ui::MainWindow)
  7. {
  8. ui->setupUi(this);
  9.  
  10. keyF11 = new QShortcut(this); // Initialize the object
  11. keyF11->setKey(Qt::Key_F11); // Set the key code
  12. // connect handler to keypress
  13. connect(keyF11, SIGNAL(activated()), this, SLOT(slotShortcutF11()));
  14.  
  15. keyCtrlD = new QShortcut(this); // Initialize the object
  16. keyCtrlD->setKey(Qt::CTRL + Qt::Key_D); // Set the key code
  17. // connect handler to keypress
  18. connect(keyCtrlD, SIGNAL(activated()), this, SLOT(slotShortcutCtrlD()));
  19. }
  20.  
  21. MainWindow::~MainWindow()
  22. {
  23. delete ui;
  24. }
  25.  
  26. /* Slot handler of F11
  27. * */
  28. void MainWindow::slotShortcutF11()
  29. {
  30. /* This handler will make switching applications in full screen mode
  31. * and back to normal window mode
  32. * */
  33. if(this->isFullScreen()){
  34. this->showNormal();
  35. } else {
  36. this->showFullScreen();
  37. }
  38. }
  39.  
  40. /* Slot handler for Ctrl + D
  41. * */
  42. void MainWindow::slotShortcutCtrlD()
  43. {
  44. /* For the treatment of a combination of keys Ctrl + D
  45. * will do the Message Box ,
  46. * which will signal that has been pressed a hotkey
  47. * */
  48. QMessageBox::information(this,
  49. "Горячая клавиша",
  50. "Мои поздравления!!! Горячая клавиша работает",
  51. QMessageBox::Ok);
  52. }

Result

This example shows one way to specify keyboard shortcuts, while the official documentation gives examples of several ways:

  1. setKey(0); // signal is not invoked
  2. setKey(QKeySequence()); // signal is not invoked
  3. setKey(0x3b1); // Set up of key code
  4. setKey(Qt::Key_D); // 'd', specify the key code via the directive 'define'
  5. setKey('q'); // 'q', specify the key code via the symbol
  6. setKey(Qt::CTRL + Qt::Key_P); // Ctrl+P, specify the hotkeys via the directive define
  7. setKey("Ctrl+P"); // Ctrl+P, direct writing shortcuts
  8.  
  9. /* Keyboard shortcuts necessary to register through the sign "+" */

As a result, you should have an application that by pressing the F11 key is set to full screen mode and rolled back into the normal display window and by pressing the key combination Ctrl + D is the MessageBox, which indicates that you press a combination of keys.

Application with using QShortcut

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
  • A
    Oct. 19, 2024, 5:19 p.m.
    Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html