4

How can I detect mouse clicks in QWebEngineView widget?

I tried this but doesn't work:

class MyWin(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        QtWidgets.QWidget.__init__(self, parent)

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.view.installEventFilter(self)

    def eventFilter(self, obj, event):
        if event.type() == event.MouseButtonPress:
             print ("Widget click")
        return super(QtWidgets.QMainWindow, self).eventFilter(obj, event)
eyllanesc
  • 235,170
  • 19
  • 170
  • 241

1 Answers1

5

Assuming that the view is the QWebEngineView object and you want to track its mouse event then you should use the focusProxy which is an internal widget that handles these types of events. On the other hand you must correctly apply inheritance.

class MyWin(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(MyWin, self).__init__(parent)

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.view.focusProxy().installEventFilter(self)

    def eventFilter(self, obj, event):
        if obj is self.ui.view.focusProxy() and event.type() == event.MouseButtonPress:
            print("Widget click")
        return super(MyWin, self).eventFilter(obj, event)
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • I got this error: AttributeError: 'NoneType' object has no attribute 'installEventFilter' – Cliffhanger Jan 10 '21 at 15:01
  • 1
    @Cliffhanger mmm, try add `self.show()` and `self.ui.view.show()` before `self.ui.view.focusProxy().installEventFilter(self)`. If it doesn't work then you need to provide the code for the Ui_MainWindow class to analyze the cause of the error – eyllanesc Jan 10 '21 at 15:03
  • Thanks for help. I found the error in UI_MainWindow class, i don't load page in self.view. I added this line: self.view.load(url) after i created QWebEngineWiev in UI_MainWindow class and now it work. Thanks and sorry for bad english. – Cliffhanger Jan 10 '21 at 15:19
  • I also got error: AttributeError: 'NoneType' object has no attribute 'installEventFilter'. so is there any other workaround here except using focusProxy()? – iMath Mar 18 '21 at 16:07
  • @iMath try add self.show() and self.ui.view.show() before self.ui.view.focusProxy().installEventFilter(self) – eyllanesc Mar 18 '21 at 17:28
  • Thanks ! I found a workaround, but still have minor issues , any solutions ?https://stackoverflow.com/questions/40696183/pyqt5-mouseclick-and-source-code-in-qwebengineview#comment117914212_40697097 – iMath Mar 19 '21 at 13:53
  • in PyQt6: `event.type() == event.Type.MouseButtonPress` – cards Jun 05 '22 at 13:34