Qt WebEngine simulate Mouse Event

女生的网名这么多〃 提交于 2020-01-20 09:00:49

问题


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:


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


来源:https://stackoverflow.com/questions/43067680/qt-webengine-simulate-mouse-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!