Search code examples
c++qtwebkitqtwebkit

QtWebkit resolving event dispatcher


i'm playing around with QtWebkit lately and i was wondering if it is possible to resolve the element displayed in the QWebView which is responsible for an event, e.g. a MouseEvent.

I've installed an EventFilter function at the WebView Object with a function like this:

bool WebKitManager::eventFilter(QObject *obj, QEvent *event)
{
    if(event->type() == QEvent::MouseButtonRelease)
    {
        QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);
        if(mouseEvent->button() == Qt::LeftButton)
        {
            // what now?!
        }

    }
    return false;
}

Is there any way to get a reference to the clicked element that is displayed in the QWebView? As far as i can tell, the passed QObject equals the WebView object and the event doesn't seem to hold reference to its dispatcher.

Since i'm far away from beeing a c++ professional i sincerely hope i missed something and you guys can help me out :)

Thanks in advance Timo


Solution

  • I believe what you could do is:

    1. cast object parameter to QWebView
    2. get QWebFrame under mouse via vebView->page()->frameAt() method
    3. use hitTestContent method of the returned frame to detect the element for the given mouse position

    Below is an example:

    bool WebKitManager::eventFilter(QObject *object, QEvent *event)
    {
        if (event->type() == QEvent::MouseButtonRelease)
        {
            QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);
            if (mouseEvent->button() == Qt::LeftButton)
            {
                QWebView *view = dynamic_cast<QWebView*>(object);
    
                QPoint pos = view->mapFromGlobal(mouseEvent->globalPos());
                qDebug() << view->url().toString() << " clicked at x:" << pos.x() << " y:" << pos.y();
    
                QWebFrame *frame = view->page()->frameAt(mouseEvent->pos());
                if (frame!=NULL)
                {
                    QWebHitTestResult hitTestResult = frame->hitTestContent(pos);
                    qDebug() << "element" << hitTestResult.element().localName();
                }
            }
        }
        return false;
    }
    

    hope this helps, regards