PyQt4 - self.scene() - addItem() 和 removeItem()

PyQt4 - self.scene() - addItem() and removeItem()

import functools
from code.ghosts import Ghosts


class Pacman(QtGui.QGraphicsPixmapItem):
    def __init__(self):
        super(Pacman, self).__init__()
        self.setPixmap(QtGui.QPixmap("pacman.png"))

    def game_continue(self):
        objects = list(self.scene().items())
        for i in range(objects.__len__()):
            if type(objects[i]) is Ghosts:
            self.scene().removeItem(objects[i])
        func = functools.partial(self.show_again, objects)
        QtCore.QTimer.singleShot(100, func)

    def show_again(self, objects):
        for object_ in objects:
            if type(object_) is Ghosts:
                self.scene().addItem(object_)

它告诉我 NoneType 对象没有属性 addItem(它是关于代码最后一行中的 self.scene())。为什么它识别 self.scene.removeItem() 并执行它但没有 addItem?

QGraphicsScene QGraphicsItem.scene (self)

Returns the current scene for the item, or 0 if the item is not stored in a scene.

http://pyqt.sourceforge.net/Docs/PyQt4/qgraphicsitem.html#scene

如果您先调用 removeItem(),那么它将在调用 addItem() 时 return None。您始终可以在其构造方法期间将 QGraphicsScene 实例存储在项目本身中。这样物品是否属于场景就无所谓了