Privacy policyContactsAbout siteOpinionsGitHubDonate
© EVILEG 2015-2018
Recommend hosting
TIMEWEB

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.

Comments

Only authorized users can post comments.
Please, Log in or Sign up
P
Feb. 18, 2019, 3:39 p.m.
Poyar

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

  • Result:73points,
  • Rating points1
НБ
Feb. 15, 2019, 1:03 p.m.
Николай Булахтин

C++ - Test 002. Constants

  • Result:25points,
  • Rating points-10
Last comments
V
Feb. 14, 2019, 6:41 p.m.
Vlad15007

Спасибо огромное! Заработало!
А
Feb. 12, 2019, 9:26 a.m.
Александр90

Сам разборался, спасибо.
А
Feb. 12, 2019, 8:19 a.m.
Александр90

День добрый! Можешь выложить форму mainwindow.ui от урока? Заранее спасибо
Feb. 11, 2019, 10:51 a.m.
Евгений Легоцкой

Нет, у меня проблема с жёстким диском случилась, занимался восстановлением ПК, ещё пару вечеров придётся этим заниматься, увы.
Now discuss on the forum
Feb. 17, 2019, 5:28 p.m.
Евгений Легоцкой

Добрый день. Очень извиняюсь за долгий ответ Первое, что нашёл, так это необходимость перерисовать чекбокс. void CheckBoxDelegate::paint(QPainter *painter, const QStyleOptionViewItem ...
Feb. 15, 2019, 3:36 p.m.
Евгений Легоцкой

Ну я тут нашёл одно решение, но сам его не проверял. Вам нужно помещать фамилии скорее всего в ячейки заголовка, и потом просто перерисовывать их QHeaderView * header = m_ui->tableWidget...
Feb. 15, 2019, 7:53 a.m.
Евгений Легоцкой

Добрый день! Не работал с remoteobjects, поэтому глянул документацию, чтобы рассмотреть, что это за зверь. После просмотра документации сложилось стойкой впечатление, что это вполне возм...
m
Feb. 14, 2019, 6:28 p.m.
mr_roman

Нашел решение на Java. Удалось интегрировать в проект сервиса на Qt, теперь из Qt запускаю Java-код акселерометра.
Join us in social networks

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