如何使用QCoreApplication::postEvent注入合成输入事件

How to use QCoreApplication::postEvent to inject synthetic input events

本文关键字:输入 入事件 postEvent 何使用 QCoreApplication 注入      更新时间:2023-10-16

我正在注入键盘和鼠标事件,这些事件正在通过网络进入我的Qt应用程序,并使用QCoreApplication::postEvent为此。鼠标坐标为绝对屏幕像素坐标。

QMouseEvent *event = new QMouseEvent(type, QPoint(x, y), mouse_button, mouse_buttons,
    Qt::NoModifier);
QCoreApplication::postEvent(g_qtdraw.main.widget, event);

最初我只有一个小部件(由g_qtdraw.main.widget引用),所以我简单地使用它作为postEvent的接收器参数。现在我的应用程序有多个小部件,上面的代码不再做我想要的了。

第二个小部件以全屏模式显示,我知道所有鼠标事件都必须转到这个窗口,但使用上面的代码,它们仍然路由到主小部件。

我如何选择正确的小部件作为接收器(鼠标x,y轴下的那个)?是否有一个标准的方法,让Qt选择正确的小部件,或者我必须自己跟踪这个?

您可以使用QApplication::widgetAt()在该位置找到正确的小部件,然后发布到该位置吗?

QPoint pos(x, y);
QMouseEvent *event = new QMouseEvent(type, pos, mouse_button, mouse_buttons,  Qt::NoModifier);
QWidget *receiver = QApplication::widgetAt(pos);
QCoreApplication::postEvent(receiver, event);

我不希望您必须为关键事件这样做。它们应该被发送到被聚焦的小部件(QApplication::focusWidget())。

不幸的是,我还没有测试这些

我建议张贴一些代码,根据文档的签名是:

void QCoreApplication::postEvent ( QObject * receiver, QEvent * event ) [static]

你有没有试过给一个指针到相应的QObject作为receiver参数?

编辑:

(注意QWidget继承QObject)

下面是问题的答案:

我现在使用下面的工作很好(非常感谢Dusty Campbell):

QPoint pos(x, y);
QWidget *receiver = QApplication::widgetAt(pos);
if (receiver) {
    QMouseEvent *event = new QMouseEvent(type, receiver->mapFromGlobal(pos),
        mouse_button, mouse_buttons, Qt::NoModifier);
    QCoreApplication::postEvent(receiver, event);
}