Ericson Willians Ericson Willians - 2 years ago 160
Python Question

Is it possible to trigger a mousePressEvent artificially on a QWebView?

Due to an astronomically atrocious bug on PyQt4, I need to fire a mousePressEvent artificially on a QWebView as a last breath of hope. For some obscure reason, QWebView's linkClicked and urlChanged signals do not pass a QUrl when the clicked link has Javascript involved (It does not work on Youtube videos, for example) and when the link was clicked with the left mouse button. The QUrl can be perfectly accessed when the link was clicked with the middle and right buttons.

class CQWebView(QtWebKit.QWebView):

def mousePressEvent(self, event):
if type(event) == QtGui.QMouseEvent:
if event.button() == QtCore.Qt.LeftButton:
# FIRE A QtCore.Qt.MiddleButton EVENT HERE,
elif event.button() == QtCore.Qt.MiddleButton:
self.emit(QtCore.SIGNAL("OPEN_IN_NEW_TAB")) # Example
elif event.button() == QtCore.Qt.RightButton:
self.emit(QtCore.SIGNAL("XXX")) # Example

So, I literally want to "click artificially", click without clicking, just trigger the event of clicking with the middle right button on a link, so that I can catch the QUrl correctly.

Answer Source

You can do it using the QtTest module as well. Set an event filter on your web view and check for left click mouse events and send a middle mouse click

def __init__(...)

def eventFilter(self, obj, event):
    if obj == self.ui_web_view:
        if event.type() == QtCore.QEvent.MouseButtonPress:
            if event.button() == QtCore.Qt.LeftButton:
                print 'Handled'
                QtTest.QTest.mouseClick(self.ui_web_view, QtCore.Qt.MiddleButton, QtCore.Qt.NoModifier, event.pos())
                return True
    return False
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download