Qt WebEngine simulate Mouse Event

2019-01-29 11:08发布

I want to simulate mouse Event in my Qt WebEngine app.

I use PyQt5.8 , QT5.8.

This is my code:

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

I test it, but it does not worked. I can confirm mouse cursor on the element, but no mouse click event happend. Can anyone help me?

I use Mac OS 10.12.4, I test it using another demo, I find I can not catch Mouse Event, but I can catch other events. Any suggestions?

1条回答
乱世女痞
2楼-- · 2019-01-29 11:24

For Qt 5.8 running the following code:

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);
查看更多
登录 后发表回答