从场景中删除 QGraphicsItem 时出现分段错误
Segmentation fault while deleting QGraphicsItem from scene
我正在使用 PyQt4 编写进化模拟器应用程序。我在 QGraphics 场景中有 'creatures' 和 'vegetation'。这些生物吃植物,植物在被吃的同时缩小,当它缩小到一定尺寸时,它就会死亡并从场景中删除。饿死的生物也会在死亡时被删除。
问题是,当我从场景中删除植被项时,出现分割错误(不是立即发生,需要不同的时间)。这并没有发生在生物身上,只有当我添加植被时才会发生,尽管它们在概念上与生物相同(class 个实例)。
我删除项目的具体循环如下(代码已简化,大量代码被注释替换):
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 行,程序就不会崩溃。
似乎程序正在调用不再有效的内存地址,但我不知道是什么原因造成的。
整个申请很长,所以我没有放在这里,但如果需要我可以添加。
我 运行 Python 3.4.3 在 Windows 上使用 PyQt4。
因此,对于遇到与我类似问题的任何人,我已经找到了解决方法。它与植被和生物的边界矩形有关。当他们的QRectF()被改变时,场景仍然使用改变前的boundingRect()。修复是通过准备场景在每个项目发生变化时更新新的 QRectF() 来完成的,这样做的代码是:
item.prepareGeometryChange()
或
item1.prepareGeometryChange()
取决于哪个有机体发生了变化。这行代码是在他们的 QRectF() 被更改之前添加的。
感谢@strubbly 提及项目的 boundingRect。
我正在使用 PyQt4 编写进化模拟器应用程序。我在 QGraphics 场景中有 'creatures' 和 'vegetation'。这些生物吃植物,植物在被吃的同时缩小,当它缩小到一定尺寸时,它就会死亡并从场景中删除。饿死的生物也会在死亡时被删除。
问题是,当我从场景中删除植被项时,出现分割错误(不是立即发生,需要不同的时间)。这并没有发生在生物身上,只有当我添加植被时才会发生,尽管它们在概念上与生物相同(class 个实例)。
我删除项目的具体循环如下(代码已简化,大量代码被注释替换):
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 行,程序就不会崩溃。
似乎程序正在调用不再有效的内存地址,但我不知道是什么原因造成的。
整个申请很长,所以我没有放在这里,但如果需要我可以添加。
我 运行 Python 3.4.3 在 Windows 上使用 PyQt4。
因此,对于遇到与我类似问题的任何人,我已经找到了解决方法。它与植被和生物的边界矩形有关。当他们的QRectF()被改变时,场景仍然使用改变前的boundingRect()。修复是通过准备场景在每个项目发生变化时更新新的 QRectF() 来完成的,这样做的代码是:
item.prepareGeometryChange()
或
item1.prepareGeometryChange()
取决于哪个有机体发生了变化。这行代码是在他们的 QRectF() 被更改之前添加的。
感谢@strubbly 提及项目的 boundingRect。