Application wide shortcuts in QML (this time without QShortcut)

by markg85


In my previous post i was using QShortcut to get application wide shortcuts. I didn’t like that route because it depends on QWidget, but i didn’t see any other option back then. After a little bit of discussion on how to get the same stuff working without QShortcut (thus no QWidget dependency) i started trying the same using Qt’s event filter system. That turned out to work rather nice! Because there is no more need for QWidget, the somewhat ugly trick to put the QWidget based mainwindow in a global class isn’t needed anymore. The C++ side looks as follows:


And the header, shortcut.h:

Making it available in QML is done the same way as in the previous post:

The reason that this works is because of the re-implemented eventFilter function. That filter listens for key events and if it finds one (and if that one matches the one we registered) then a signal is emitted to indicate the application that the registered key has been pressed. It’s really that simple. The filter is registered in the class constructor through qApp->installEventFilter(this); That’s all i needed to do to get is working.

In QML it still looks as simple as this:

Right now this is not part of any KDE QML imports, but i do want to try and get this specific component in QML. It will help other applications as well if they happen to need this functionality.


Updated the code to reflect all the suggestions from the comments. The QML side still works exactly the same, but has an additional signal that will let you know when the key has been changed. Changed! not triggered! That is still a separate signal. Also added a bool: m_keypressAlreadySend in an attempt to prevent double signals which was happening all the time.