Qt WebEngine模拟鼠标事件

时间:2017-03-28 10:54:35

标签: qt qtwebengine qmouseevent

我想在 Qt WebEngine 应用中模拟鼠标事件。

我使用 PyQt5.8,QT5.8

这是我的代码:

    def mouse_click(self, x, y):
        point = QPoint(int(x),
                    int(y))
        eventp = QMouseEvent(QMouseEvent.MouseButtonPress,point,Qt.LeftButton,Qt.LeftButton,Qt.NoModifier)
        self.sendEvent(eventp)
        eventp = QMouseEvent(QMouseEvent.MouseButtonRelease,point,Qt.LeftButton,Qt.LeftButton,Qt.NoModifier)
        self.sendEvent(eventp)


     def sendEvent(self, event):
         recipient = self.webpage.view().focusProxy()
         recipient.grabKeyboard()
         self.application.sendEvent(recipient, event)
         recipient.releaseKeyboard()

我测试它,但它不起作用。我可以在元素上确认鼠标光标,但不会发生鼠标点击事件。任何人都可以帮助我吗?

我使用Mac OS 10.12.4,我使用另一个演示测试它,我发现我无法捕捉鼠标事件,但我可以捕获其他事件。有什么建议?

1 个答案:

答案 0 :(得分:4)

对于Qt 5.8,运行以下代码:

void LeftMouseClick(QWidget* eventsReciverWidget, QPoint clickPos)
{
    QMouseEvent *press = new QMouseEvent(QEvent::MouseButtonPress,
                                            clickPos,
                                            Qt::LeftButton,
                                            Qt::MouseButton::NoButton,
                                            Qt::NoModifier);
    QCoreApplication::postEvent(eventsReciverWidget, press);
    // Some delay
    QTimer::singleShot(300, [clickPos, eventsReciverWidget]() {
        QMouseEvent *release = new QMouseEvent(QEvent::MouseButtonRelease,
                                                clickPos,
                                                Qt::LeftButton,
                                                Qt::MouseButton::NoButton,
                                                Qt::NoModifier);
        QCoreApplication::postEvent(eventsReciverWidget, release);
    }));
}
QWebEngineView webView = new QWebEngineView();
// You need to find the first child widget of QWebEngineView. It can accept user input events.
QWidget* eventsReciverWidget = nullptr;
foreach(QObject* obj, webView->children())
{
    QWidget* wgt = qobject_cast<QWidget*>(obj);
    if (wgt)
    {
        eventsReciverWidget = wgt;
        break;
    }
}
QPoint clickPos(100, 100);
LeftMouseClick(eventsReciverWidget, clickPos);