Emulate a global keypress in Qt

╄→гoц情女王★ 提交于 2021-02-04 21:13:37

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!