我正在使用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。
在遍歷它們的同時刪除項目似乎不是一個好主意。或者是縮進錯誤? – ekhumoro
我明白你在說什麼了。我試圖將它移動到'for item in item'循環之外,但程序仍然崩潰。 –
我認爲您的發佈代碼中的縮進是錯誤的。 – strubbly