如何将鼠标事件传播到 QGraphicsItemGroup 中的 QGraphicsItem? [英] How to propagate mouse events to a QGraphicsItem in a QGraphicsItemGroup?
问题描述
我想为某些 QGraphicsItem
捕捉鼠标事件.当项目直接添加到 QGraphicsScene
时,一切都按预期进行:使用下面的选项 1 时,当用户在矩形内单击时,控制台会打印foo".
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.
但是,如果项目是通过组间接添加的,则它不再接收事件(下面的选项 2).事件链似乎以这种方式被打破了.我试图将 scene
设置为 QGraphicsItem
的父项以恢复链,但结果是错误,显然我没有以正确的方式做?
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?
将 QGraphicsItem
添加到组并仍然接收鼠标事件的正确方法是什么?
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()
推荐答案
如果使用 QGraphicsItemGroup 的唯一目的是启用一组项目的移动,那么过程就是选择项目,将它们添加到组中, 移动项目并在任何操作之前从组中删除项目.因此,项目不需要永久属于该组,而仅在必要时避免副作用,例如不传输事件.
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.
这篇关于如何将鼠标事件传播到 QGraphicsItemGroup 中的 QGraphicsItem?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!