从场景中删除QGraphicsItem时出现分段错误
问题描述:
我正在使用PyQt4编写进化模拟器应用程序。我在QGraphics场景中有'生物'和'植物'。这些生物吃的植物会随着它被吃掉而萎缩,当它下降到一定的大小时,它就会死亡并被从现场中删除。饥饿的生物在死后也会被删除。从场景中删除QGraphicsItem时出现分段错误
问题是,当我从场景中删除植被项目时,出现了分段错误(不是立即需要花费不同的时间)。这只在我加入植物的时候才会发生,尽管它们在概念上与生物(类别实例)相同。
的具体循环,我删除的项目如下(代码简化与评论替代的代码显著量):
dead = set()
items = self.scene.items()
for item in items:
if isinstance(item, Creature):
# Do some calculation to specify what creature does
for item1 in self.scene.items():
# Look through other items on scene and define interactions
if isinstance(item1, Creature):
# Specify what to do if current item is being compared to another creature
if isinstance(item1, Vegetation):
# Specify what to do if current item is being compared to vegetation
# If creature dies, add to dead set
dead.add(item)
elif isinstance(item, Vegetation):
# Do same as for creature (see above)
# If vegetation dies, add to dead set
dead.add(item)
# Get rid of all dead items from scene
while dead:
deadItem = dead.pop()
self.scene.removeItem(deadItem)
del deadItem
如果我注释掉self.scene.removeItem线,那么程序不会崩溃。
看来程序正在调用一个不再有效的内存地址,但我不知道是什么导致它。
整个应用程序很长,这就是为什么我没有把它放在这里,但如果有必要,我可以添加它。
我在Windows上使用PyQt4运行Python 3.4.3。
答
因此,对于任何对我有类似问题的人,我找到了一个解决办法。这与植物和生物的界限有关。当它们的QRectF()被改变时,场景在改变之前仍然使用先前的boundingRect()。此修复程序,即制备现场做时,他们改变更新每个项目的新QRectF(),代码这样做是:
item.prepareGeometryChange()
或
item1.prepareGeometryChange()
根据该生物体已经改变。这行代码在QRectF()更改之前添加。
非常感谢@strubbly提及有关物品的boundingRect。
在遍历它们的同时删除项目似乎不是一个好主意。或者是缩进错误? – ekhumoro
我明白你在说什么了。我试图将它移动到'for item in item'循环之外,但程序仍然崩溃。 –
我认为您的发布代码中的缩进是错误的。 – strubbly