自定义 QGraphicsItem 删除自身 [英] Custom QGraphicsItem deletes itself
问题描述
我正在使用 PyQt 5.我有一个 QGraphicsScene,它有一个要显示的 QGraphicsObject 列表.我对 QRectF 和其他类型没有问题.但是我实现了一个自定义类,如下所示:
I am using PyQt 5. I have a QGraphicsScene that has a list with QGraphicsObject's to show. I have no problem with QRectF and other types. However I implemented a custom class as follows:
class RobotPathItem(QGraphicsItem):
def __init__(self, path):
super().__init__()
qpath = []
for xy in path:
qpath.append(QPoint(xy[0],xy[1]))
self.path = QPolygon(qpath)
def paint(self, painter, option, qwidget = None):
painter.drawPoints(self.path)
def boundingRect(self):
return QRectF(0,0,520,520)
然后我将它添加到场景中:
I then add it to the scene:
self.objects[model_obj.id].append(self.scene.addItem(RobotPathItem(model_obj.actuator.get_current_path())))
这里 self.objects[model_obj.id] 是合适的列表.它确实会出现在现场.
Here self.objects[model_obj.id] is the appropriate list. It does get shown on the scene.
问题在于,在下一次迭代中,它出于某种原因从列表中删除.如果我检查
The problem is that on the very next iteration it is for some reason deleted from the list. If I check
print(self.objects[model_obj.id][-1])
我得到无"(NoneType).所有其他对象仍在列表中.错误在哪里?
I get "None" (NoneType). All other objects are still in the list. Where is the error?
推荐答案
事实证明 addItem 不像 addRect 或其他函数那样返回指针.相反,它返回 None.
Turns out addItem does not return a pointer like addRect or other functions do. Instead it returns None.
为了让上面的代码正常工作:
So for the above code to work properly:
robot_path = RobotPathItem(model_obj.actuator.get_current_path())self.scene.addItem(robot_path)self.objects[model_obj.id].append(robot_path)
而不是
self.objects[model_obj.id].append(RobotPathItem(model_obj.actuator.get_current_path()))
然后执行
self.objects[model_obj.id][2].set_path(model_obj.actuator.get_current_path())
更新它
这篇关于自定义 QGraphicsItem 删除自身的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!