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
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
ИМ
Игорь МаксимовNov. 22, 2024, 10:51 p.m.
Django - Tutorial 017. Customize the login page to Django Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
Evgenii Legotckoi
Evgenii LegotckoiNov. 1, 2024, 12:37 a.m.
Django - Lesson 064. How to write a Python Markdown extension Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
A
ALO1ZEOct. 19, 2024, 6:19 p.m.
Fb3 file reader on Qt Creator Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html
ИМ
Игорь МаксимовOct. 5, 2024, 5:51 p.m.
Django - Lesson 064. How to write a Python Markdown extension Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
d
dblas5July 5, 2024, 9:02 p.m.
QML - Lesson 016. SQLite database and the working with it in QML Qt Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
Now discuss on the forum
Evgenii Legotckoi
Evgenii LegotckoiJune 25, 2024, 1:11 a.m.
добавить qlineseries в функции Я тут. Работы оень много. Отправил его в бан.
t
tonypeachey1Nov. 15, 2024, 5:04 p.m.
google domain [url=https://google.com/]domain[/url] domain [http://www.example.com link title]
NSProject
NSProjectJune 4, 2022, 1:49 p.m.
Всё ещё разбираюсь с кешем. В следствии прочтения данной статьи. Я принял для себя решение сделать кеширование свойств менеджера модели LikeDislike. И так как установка evileg_core для меня не была возможна, ибо он писался…
9
9AnonimOct. 25, 2024, 7:10 p.m.
Машина тьюринга // Начальное состояние 0 0, ,<,1 // Переход в состояние 1 при пустом символе 0,0,>,0 // Остаемся в состоянии 0, двигаясь вправо при встрече 0 0,1,>…

Follow us in social networks