I want to catch mouse events for some QGraphicsItem
. When the item is added directly to a QGraphicsScene
, everything works as expected: when using option 1 below, the console prints "foo" when the user clicks within the rectangle.
However, if the item is added indirectly via a group, it does not receive events anymore (option 2 below). It seems the event chain is broken that way. I tried to set scene
as the parent to the QGraphicsItem
to restore the chain but it results in an error, obviously I am not doing it the right way?
What is the correct way to add a QGraphicsItem
to a group and still receive mouse events?
from PyQt5.QtWidgets import QApplication, QGraphicsRectItem, QGraphicsScene, QGraphicsView, QMainWindow
class Rect(QGraphicsRectItem):
def mousePressEvent(self, event):
print("foo")
app = QApplication([])
window = QMainWindow()
window.setGeometry(100, 100, 400, 400)
view = QGraphicsView()
scene = QGraphicsScene()
rect = Rect(0, 0, 150, 150)
# Option 1.
# scene.addItem(rect) # works fine, prints 'foo' when clicked
# Option 2.
group = scene.createItemGroup([rect]) # no mouse event received by rect
view.setScene(scene)
window.setCentralWidget(view)
window.show()
app.exec()