2017-09-24 60 views
0

我正在使用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。

+0

在遍歷它們的同時刪除項目似乎不是一個好主意。或者是縮進錯誤? – ekhumoro

+0

我明白你在說什麼了。我試圖將它移動到'for item in item'循環之外,但程序仍然崩潰。 –

+0

我認爲您的發佈代碼中的縮進是錯誤的。 – strubbly

回答

0

因此,對於任何對我有類似問題的人,我找到了一個解決辦法。這與植物和生物的界限有關。當它們的QRectF()被改變時,場景在改變之前仍然使用先前的boundingRect()。此修復程序,即製備現場做時,他們改變更新每個項目的新QRectF(),代碼這樣做是:

item.prepareGeometryChange() 

item1.prepareGeometryChange() 

根據該生物體已經改變。這行代碼在QRectF()更改之前添加。

非常感謝@strubbly提及有關物品的boundingRect。