Qt: Force QWebView to click on a web element, even one not visible on the window

Posted by Pirate for Profit on Stack Overflow See other posts from Stack Overflow or by Pirate for Profit
Published on 2010-04-16T18:52:14Z Indexed on 2010/04/17 1:23 UTC
Read the original article Hit count: 571

Filed under:
|
|
|

So let's say I'm trying to click a link in the QWebView, here is what I have:

// extending QWebView
void MyWebView::click(const QString &selectorQuery)
{
    QWebElement el = this->page()->mainFrame()->findFirstElement(selectorQuery);
    if (!el)
         return;

    el.setFocus();

    QMouseEvent pressEvent(QMouseEvent::MouseButtonPress, el.geometry().center(), 
                    Qt::MouseButton::LeftButton, Qt::LeftButton, Qt::NoModifier);
    QCoreApplication::sendEvent(this, &pressEvent);

    QMouseEvent releaseEvent(QMouseEvent::MouseButtonRelease, 
                             el.geometry().center(), Qt::MouseButton::LeftButton,
                             Qt::LeftButton, Qt::NoModifier);
    QCoreApplication::sendEvent(this, &releaseEvent);
}

And you call it as so:

myWebView->click("a[href]");  // will click first link on page
myWebView->click("input[type=submit]"); // submits a form

THE ONLY PROBLEM IS: if the element is not visible in the window, it is impossible to click. What I mean is if you have to scroll down to see it, you can't click it. I imagine this has to do with the geometry, since the element doesn't show up on the screen it can't do the math to click it right.

Any ideas to get around this? Maybe some way to make the window behave like a billion x billion pixels but still look 200x200?

© Stack Overflow or respective owner

Related posts about qwebview

Related posts about qt