How to propagate mouse events to a QGraphicsItem in a QGraphicsItemGroup?

喜夏-厌秋 提交于 2020-04-15 06:49:49

问题


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()

回答1:


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.



来源:https://stackoverflow.com/questions/60476803/how-to-propagate-mouse-events-to-a-qgraphicsitem-in-a-qgraphicsitemgroup

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!