问题
I am building a Qt Application for a raspberry pi, which is connected to a rotary encoder. When the user presses the rotary encoder button, the application registers the hardware interrupt from the button and emits a signal which the application can intercept.
The challenge is that the application has multiple windows that can be displayed, and I would like to simply have a function which translates the button press signal into a global key press that can be registered by any active window in the application, without having to add extra logic to determine which window is active to send the key press directly to it. Is there a way to simulate a system-wide key press so that whatever window is in focus will get it?
So far, I have the following snippet of code, though it requires a reference to a specific QObject to direct the keypress to:
QKeyEvent *event = new QKeyEvent(QEvent::KeyPress, Qt::Key_Enter);
QCoreApplication::postEvent (receiver, event);
where receiver
is the object to direct the keypress too. Any ideas?
回答1:
To broadcast a key event to all top-level widgets (i.e. windows):
for(auto w : qApp->allWidgets())
{
if(w->isTopLevel())
{
qApp->postEvent(w, new QKeyEvent(QEvent::KeyPress, Qt::Key_Enter, Qt::NoModifier));
}
}
To directly send the event to the active window (the foremost one):
qApp->postEvent(qApp->activeWindow(), new QKeyEvent(QEvent::KeyPress, Qt::Key_Enter, Qt::NoModifier));
来源:https://stackoverflow.com/questions/59759576/emulate-a-global-keypress-in-qt