Search code examples
pyqtadditionselecteditemscene

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_)

It tells me that NoneType object has no attribute addItem (it's about self.scene() in the last row of the code). How come it recognizes the self.scene.removeItem() and executes it but there is no addItem?


Solution

  • 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

    If you're calling removeItem() first then it will return None when calling addItem(). You can always store your QGraphicsScene instance in the item itself during its constructor method. That way it doesn't matter if the item belongs to the scene or not.