You can use QxtGlobalShortcut
which is a class in Qxt. It provides a global shortcut aka "hotkey" and triggers even if the application is not active :
#include <QApplication>
#include <QxtGlobalShortcut>
#include <QTimer>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QEventLoop loop;
QxtGlobalShortcut* shortcut = new QxtGlobalShortcut();
shortcut->setShortcut(QKeySequence("R"));
QObject::connect(shortcut, SIGNAL(activated()), shortcut, SLOT(setDisabled()));
QObject::connect(shortcut, SIGNAL(activated()), &loop,SLOT(quit()));
QTimer::singleShot(300,&loop,SLOT(quit()));
loop.exec();
if(!shortcut->isEnabled())
{
//R is pressed
}
...
return a.exec();
}
Here we wait for maximum 300 milliseconds to check if the key is pressed. When the activated()
signal is emitted, the shortcut is disabled and the event loop gets quit. Otherwise the timeout for the timer is activated and the event loop quits.
After getting the source for Qxt and compiling, you should add these to your .pro file :
CONFIG += qxt
QXT += core gui