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()
If the only objective of the use of QGraphicsItemGroup is to enable the movement of a group of items then the procedure is to select the items, add them to the group, move the items and before any action remove the items from the group. Thus, it will not be necessary for the items to permanently belong to the group but only when necessary avoiding side effects such as the non-transmission of events.