在Qt中模拟全局按键 [英] Emulate a global keypress in Qt

查看:361
本文介绍了在Qt中模拟全局按键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为连接到旋转编码器的树莓派构建Qt应用程序.当用户按下旋转编码器按钮时,应用程序会从该按钮注册硬件中断,并发出一个可以被应用程序拦截的信号.

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?

到目前为止,我有以下代码片段,尽管它需要引用特定的QObject才能将按键定向到:

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);

其中,receiver也是引导按键的对象.有什么想法吗?

where receiver is the object to direct the keypress too. Any ideas?

推荐答案

要将关键事件广播到所有顶级窗口小部件(即Windows):

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));

这篇关于在Qt中模拟全局按键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆