L.V.A
L.V.A

Reputation: 184

Simulate mouse click for QWebEngineView

I want to write a program to automate testing the web size for different screen sizes. I create window using QWebEngineView and I need to simulate user mouse to click and drag a drop elements in web page. I have tried qApp->sendEvent and qApp->postEvent but nothink work.

QMouseEvent *event1 = new QMouseEvent (QEvent::MouseButtonPress, point,
Qt::LeftButton,
Qt::LeftButton,
Qt::NoModifier);

qDebug() << qApp->sendEvent (driver, static_cast <QEvent *> ( event1 ) );

QMouseEvent *event2 = new QMouseEvent (QEvent::MouseButtonRelease, point,
Qt::LeftButton,
Qt::LeftButton,
Qt::NoModifier);

qDebug() << qApp->sendEvent (driver, static_cast <QEvent *> ( event2 ));

Both class return true but the event in the web page is not triggered. Need I to focus first the view? It has no parent and it's a window. No more graphical elements are used. Can you help me?

Ps: The javascript i don't want to use beacause: I can not focus a input using javascript simulated click, it has no coords to test a canvas for drag and drop.

Upvotes: 3

Views: 2833

Answers (1)

Bob Kimani
Bob Kimani

Reputation: 1164

It seems that you have to access a child object of the QWebEngineView and then send events to it.The following is an implementation of a left mouse click.You can change the postions clickPos for release and press simulating a drag.

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

Borrowing from the following answers Qt WebEngine simulate Mouse Event How to send artificial QKeyEvent to QWebEngineView?

Upvotes: 3

Related Questions