Reputation: 29441
I need to know if a key (let's say r
) is pressed when the main()
start. See :
int main(int argc, char *argv[])
{
if(R is pressed)
{} // Do a few things
// Do amazing stuff whatever happened
return a.exec();
}
But I can't find a way to do it for all platforms (win, mac, lin), the only thing I found is a trick for windows : Using GetKeyState() which is not very satisfying...
Upvotes: 2
Views: 757
Reputation: 11780
If you want to check modifier keys (shift, control, alt) you can use QGuiApplication::queryKeyboardModifiers()
:
int main(int argc, char *argv[])
{
if(QGuiApplication::queryKeyboardModifiers().testFlag(Qt::ShiftModifier))
{} // Do a few things
// Do amazing stuff whatever happened
return a.exec();
}
Upvotes: 2
Reputation: 32655
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
Upvotes: 1