pyqt5pyside2pyside6pyqt6eventfilter

PyQt5 eventFilter not capturing QEvent.MouseButtonRelease


I am trying to capture MouseButtonRelease after installing an eventFilter. The correctly captures the MouseButtonPress but not MouseButtonRelease.

Am I missing something or is this not possible ?

Minimum working example :

import sys
from PySide6.QtWidgets import QGraphicsScene, QGraphicsView, QApplication
from PySide6.QtCore import QObject, QEvent


class FilterFunction(QObject):
    def __init__(self, parent: QObject) -> None:
        super().__init__(parent)

    def eventFilter(self, watched: QObject, event: QEvent) -> bool:
        if event.type() == QEvent.MouseButtonRelease:
            print(" QEvent.MouseButtonRelease")
        elif event.type() == QEvent.MouseButtonPress:
            print(" QEvent.MouseButtonPress")
        return super().eventFilter(watched, event)


app = QApplication(sys.argv)

scene = QGraphicsScene(0, 0, 400, 200)
view = QGraphicsView(scene)
view.setMouseTracking(True)
filterFunciton = FilterFunction(view)
view.installEventFilter(filterFunciton)
view.show()
app.exec()


Solution

  • To get the correct events for a view, you must monitor its viewport:

    view.viewport().installEventFilter(filterFunciton)
    

    The viewport is the area that renders the contents of the view, so events must be routed relative to that in order to ensure e.g. the correct co-ordinates are delivered. The view itself may include other components, such as a frame, scrollbars, headers etc, which aren't considered part of the contents, and therefore must be handled separately. Also, the viewport widget itself can be set independently of the view.