0

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?

4

1 回答 1

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);
于 2017-04-10T05:57:21.090 回答