Evgenii Legotckoi
Evgenii LegotckoiAug. 30, 2015, 10:33 a.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.

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QShortcut>
#include <QMessageBox>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private slots:
    // slots for handlers of hotkeys
    void slotShortcutF11();
    void slotShortcutCtrlD();

private:
    Ui::MainWindow  *ui;
    QShortcut       *keyF11;    // Entity of F11 hotkey
    QShortcut       *keyCtrlD;  // Entity of Ctrl + D hotkeys
};

#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.
#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    keyF11 = new QShortcut(this);   // Initialize the object
    keyF11->setKey(Qt::Key_F11);    // Set the key code
    // connect handler to keypress
    connect(keyF11, SIGNAL(activated()), this, SLOT(slotShortcutF11()));

    keyCtrlD = new QShortcut(this); // Initialize the object
    keyCtrlD->setKey(Qt::CTRL + Qt::Key_D); // Set the key code
    // connect handler to keypress
    connect(keyCtrlD, SIGNAL(activated()), this, SLOT(slotShortcutCtrlD()));
}

MainWindow::~MainWindow()
{
    delete ui;
}

/* Slot handler of F11
 * */
void MainWindow::slotShortcutF11()
{
    /* This handler will make switching applications in full screen mode
     * and back to normal window mode
     * */
    if(this->isFullScreen()){
        this->showNormal();
    } else {
        this->showFullScreen();
    }
}

/* Slot handler for Ctrl + D
 * */
void MainWindow::slotShortcutCtrlD()
{
    /* For the treatment of a combination of keys Ctrl + D
     * will do the Message Box ,
     * which will signal that has been pressed a hotkey
     * */
    QMessageBox::information(this,
                             "Горячая клавиша",
                             "Мои поздравления!!! Горячая клавиша работает",
                             QMessageBox::Ok);
}

Result

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

setKey(0);                  // signal is not invoked
setKey(QKeySequence());     // signal is not invoked
setKey(0x3b1);              // Set up of key code
setKey(Qt::Key_D);          // 'd', specify the key code via the directive 'define'
setKey('q');                // 'q', specify the key code via the symbol
setKey(Qt::CTRL + Qt::Key_P);       // Ctrl+P, specify the hotkeys via the directive define
setKey("Ctrl+P");           // Ctrl+P, direct writing shortcuts

/* 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

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
AD

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:50points,
  • Rating points-4
m

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:80points,
  • Rating points4
m

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:20points,
  • Rating points-10
Last comments
i
innorwallNov. 15, 2024, 2:30 p.m.
Qt/C++ - Lesson 065. The correspondence of HTTP errors to server response errors in QNetworkAccessManager s Midsummer Classic in Kansas City priligy online pharmacy
i
innorwallNov. 15, 2024, 1:44 p.m.
Qt/C++ - Lesson 039. How to paint stroke in QSqlTableModel by value in the column? Many OPKs would advise users to start using the test strips around day 9 of your cycle, considering day 1 to be the first day of full menstrual flow buy priligy australia
i
innorwallNov. 15, 2024, 10:27 a.m.
Release of C++/Qt and QML application deployment utility CQtDeployer v1.4.0 (Binary Box) optionally substituted alkoxy, optionally substituted alkenyloxy, optionally substituted alkynyloxy, optionally substituted aryloxy, OCH, OC H, OC H, OC H, OC H, OC H, OC H, O C CH, OCH CH OH, O…
i
innorwallNov. 15, 2024, 5:26 a.m.
Qt/C++ - Lesson 031. QCustomPlot – The build of charts with time buy generic priligy We can just chat, and we will not lose too much time anyway
i
innorwallNov. 15, 2024, 3:03 a.m.
Qt/C++ - Lesson 060. Configuring the appearance of the application in runtime I didnt have an issue work colors priligy dapoxetine 60mg revia cost uk August 3, 2022 Reply
Now discuss on the forum
t
tonypeachey1Nov. 15, 2024, 2:04 p.m.
google domain [url=https://google.com/]domain[/url] domain [http://www.example.com link title]
i
innorwallNov. 15, 2024, 1:50 p.m.
добавить qlineseries в функции priligy for sale Gently flush using an ear syringe
i
innorwallNov. 11, 2024, 6:55 p.m.
Всё ещё разбираюсь с кешем. priligy walgreens levitra dulcolax carbs The third ring was found to be made up of ultra relativistic electrons, which are also present in both the outer and inner rings
9
9AnonimOct. 25, 2024, 4:10 p.m.
Машина тьюринга // Начальное состояние 0 0, ,<,1 // Переход в состояние 1 при пустом символе 0,0,>,0 // Остаемся в состоянии 0, двигаясь вправо при встрече 0 0,1,>…

Follow us in social networks