QGlobalShortcut - Global hotkeys

HotKey, linux, QGlobalShortcut, Qt, Windows

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.
Support the author Donate

Comments

Only authorized users can post comments.
Please, Log in or Sign up
Looking for a Job?
25,000.00 руб. - 30,000.00 руб.
Разработчик Qt/C++
Barnaul, Altai Krai, Russia

For registered users on the site there is a minimum amount of advertising

e
Oct. 14, 2019, 2:59 p.m.
erina_m

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

  • Result:78points,
  • Rating points2
S
Oct. 14, 2019, 4:09 a.m.
Sergey1985

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

  • Result:80points,
  • Rating points4
AM
Oct. 12, 2019, 5:24 p.m.
Arshak Martirosyan

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

  • Result:66points,
  • Rating points-1
Last comments
Oct. 14, 2019, 7:48 a.m.
Evgenij Legotskoj

Добрый день. Нет, если сами по себе координаты при ресайзе все подсчитываются правильно, то это уже проблема графической подсистемы в ОС и работы с X11, если вы конечно под Linux собирали проект…
m
Oct. 13, 2019, 9:17 a.m.
magrif

Здравствуйте. Сделал подобным образом ресайз и в Qt Widgets, и в QML. Везде получаю, что при изменении размера через левую или верхннюю границы проихсодит мерцание подобно как на этом виде…
Oct. 6, 2019, 1:44 p.m.
Evgenij Legotskoj

Может база не открылась в прошлый раз. Либо пересобрали проект. хз, если честно ))
s
Oct. 6, 2019, 11:27 a.m.
sander-007

Добрый день Евгений. Спасибо за пример, все понятно. Попытался сделать по аналогии сохранение в базе MySQL заготовок отчетов excel, но MySQL ругается на нарушение в строке запроса. Я подозреваю,…
Sept. 30, 2019, 3:33 a.m.
Evgenij Legotskoj

Если честно то с авторизацией в мобильном приложении я не работал. Знаю, что для таких вещей используют батарейку Django Rest Framework, с помощью которого можно получить токена для самого сайта…
Now discuss on the forum
Oct. 14, 2019, 2:51 p.m.
Evgenij Legotskoj

Добрый день. Первое, что приходит на ум, то можно подружить это дело через веб сокеты. Со стороны Django - это использование батарейки django-channels, а со стороны это QtWebSockets. …
Oct. 11, 2019, 3:11 a.m.
Evgenij Legotskoj

Понятно. Мне нужен пример вашего кода с проблемой. Если сможете накидать вырезку из вашего проекта, которую можно будет скомпилировать и посмотреть, что там происходит, то попробую помочь. Но бы…
t
Oct. 10, 2019, 10:58 a.m.
tantrido

Вот ответ на мой вопрос: https://doc.qt.io/qt-5/qtvirtualkeyboard-deployment-guide.html#creating-inputpanel The input panel must be a sibling element next to the application conta…
Oct. 9, 2019, 3:45 p.m.
Evgenij Legotskoj

Добрый день. Нет, я таким не сталкивался, но вот таким образом вы можете разбить тот тег, на ноды, и забрать текст в нормально порядке, а потом вам уже не составит труда, как я думаю, запи…
Oct. 9, 2019, 12:04 p.m.
Vadim Polshkov

Здравствуйте. Все получилось, только редирект сделал по другому redirect(price.file.url) Спасибо вам за помощь!
EVILEG
About
Services
© EVILEG 2015-2019
Recommend hosting TIMEWEB