Evgenii Legotckoi
Evgenii LegotckoiFeb. 28, 2016, 10:45 a.m.

QGlobalShortcut - Global hotkeys

In the process of studying the issues with global hotkeys for Linux and Windows, I wrote my library for quick registration hotkeys. The resulting library is called QGlobalShortcut and is available at GitHub under license LGPLv2. The library supports the Windows platform and Linux / Unix (which use X11)

The logic of class QGlobalShortcut, which provides this library, similar to the logic of the class QShortcut, although clearly not up to this class on a number of parameters, but the main thing that fulfills its basic function. Namely, global HotKey register and send a signal to activate it.

At this point it is necessary to use the library to put the header files and source files in your project, as well as to prescribe additional information in the project profile.


Getting library

Download QGlobalShortcut

Configuration of project

The library consists of a single header file and two source code files, depending on the platform (Windows, X11). Not counting the README etc.

The library uses the C ++ 11 language standard, so be sure you need to configure the project on the standard or higher. For linux / unix you must use x11extras module that will likely need to be installed separately, since Qt default does not in the delivery of this module. You will also need to configure the project to use the library to work with and XLib XCB.

CONFIG += c++11

linux {
    QT       += x11extras
    CONFIG   += link_pkgconfig
    PKGCONFIG += x11
}

win32: SOURCES += win/qglobalshortcut.cpp
linux: SOURCES += x11/qglobalshortcut.cpp

HEADERS  += qglobalshortcut.h

Public functions

QKeySequence shortcut()

The method returns a set sequence of hotkeys QKeySequence. If the sequence is not found, it returns an empty sequence QKeySequence ("").

bool isEmpty()

The method checks whether the hot key sequence is set or not.

bool isEnabled()

The method tests whether or not the hotkey enabled. The combination of hot keys can be set, then the isEmpty () returns true, but the operation can be switched off. That is a signal activating hotkey will not be generated.

bool setShortcut(const QKeySequence &keySequence)

The method is a slot and sets a sequence of keyboard shortcuts. At the same time, if QKeySequence contains several shortcut keys, they will all be registered.

bool unsetShortcut()

The method is a slot and remove hotkeys if it was installed.

void setEnabled(bool enable)

The method is a slot and is used to turn on and off activation of keyboard shortcuts.

Signals

void activated()

The activation signal though, triggered when the hotkey is installed and enabled.

Using

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include "qglobalshortcut.h"

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

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

public slots:
    void slotFirst();
    void slotSecond();

private:
    Ui::MainWindow *ui;
    QGlobalShortcut *shortcutFirst;
    QGlobalShortcut *shortcutSecond;
};

#endif // MAINWINDOW_H
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    shortcutFirst = new QGlobalShortcut(this);
    connect(shortcutFirst, &QGlobalShortcut::activated, this, &MainWindow::slotFirst);
    shortcutFirst->setShortcut(QKeySequence("Ctrl+E"));

    shortcutSecond = new QGlobalShortcut(this);
    connect(shortcutSecond, &QGlobalShortcut::activated, this, &MainWindow::slotSecond);
    shortcutSecond->setShortcut(QKeySequence("Ctrl+G"));

}

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

void MainWindow::slotFirst()
{
    qDebug() << "First";
}

void MainWindow::slotSecond()
{
    qDebug() << "Second";
}

Recommended application

When you create an instance of the class is created QGlobalShortcut nativeEventFilter, which is installed on all application. The number of filters in the application is not restricted (ie you can create any number of global hotkeys with this class), but the filter installed last will be triggered first. Thus, this class can be used elsewhere in the application.

It is important to understand that when you use this class, all filters that can affect the performance of the application, which uses a test other operating system events can not be sure exactly what kind of sequence will be installed, not just the global hotkeys. That is, if you are already using a class that derives from QAbstractNativeEventFilter, and set the filter to the application for the treatment of a number of events system using it, then it may make sense not to use the library in the forehead, and use of the software library of code in your already existing class.

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
e
  • ehot
  • April 1, 2024, 12:29 a.m.

C++ - Тест 003. Условия и циклы

  • Result:78points,
  • Rating points2
B

C++ - Test 002. Constants

  • Result:16points,
  • Rating points-10
B

C++ - Test 001. The first program and data types

  • Result:46points,
  • Rating points-6
Last comments
k
kmssrFeb. 9, 2024, 5:43 a.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
EVA
EVADec. 25, 2023, 9:30 p.m.
Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
J
JonnyJoDec. 25, 2023, 7:38 p.m.
Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
G
GvozdikDec. 19, 2023, 8:01 a.m.
Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
Now discuss on the forum
a
a_vlasovApril 14, 2024, 4:41 p.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Евгений, добрый день! Такой вопрос. Верно ли следующее утверждение: Любое Android-приложение, написанное на Java/Kotlin чисто теоретически (пусть и с большими трудностями) можно написать и на C+…
Павел Дорофеев
Павел ДорофеевApril 14, 2024, 12:35 p.m.
QTableWidget с 2 заголовками Вот тут есть кастомный QTableView с многорядностью проект поддерживается, обращайтесь
Mm
Mind minglesApril 12, 2024, 10:42 a.m.
ASO Service Forum: Enhancing App Visibility and Reach Welcome to the ASO Service Forum, your ultimate destination for insights, discussions, and strategies revolving around App Store Optimization. ASO (App Store Optimization) is paramoun…
f
fastrexApril 4, 2024, 2:47 p.m.
Вернуть старое поведение QComboBox, не менять индекс при resetModel Добрый день! У нас много проектов в которых используется QComboBox, в версии 5.5.1, когда модель испускает сигнал resetModel, currentIndex не менялся. В версии 5.15 при resetModel происходит try…

Follow us in social networks