RodericDay
RodericDay

Reputation: 1292

Deleting/Destroying/Removing a QGraphicsItem from a QGraphicsScene

I feel like this question has been answered somewhere before, but I cannot find the answer for the life of me (particularly because of the synonyms in the title spreading the solutions around). I want a definitive answer to which is the best way to delete a QGraphicsItem from a scene. Let's take the simplest scenario: A simple "rubberband" rectangle.

from PyQt4 import QtGui, QtCore

class Rubbery(QtGui.QGraphicsScene):

  def mousePressEvent(self, event):
    self.origin = event.scenePos()
    self.rect = QtGui.QGraphicsRectItem(self.origin.x(), self.origin.y(), 0, 0, None, self)

  def mouseMoveEvent(self, event):
    self.rect.setRect(QtCore.QRectF(self.origin, event.scenePos()).normalized())

  def mouseReleaseEvent(self, event):
    self.rect.setParentItem(None)

app = QtGui.QApplication([])

scene = Rubbery()
scene.setSceneRect(0,0,500,500)
view = QtGui.QGraphicsView(scene)
view.show()

app.exec()

If you look at the mouseReleaseEvent, that's where I'm having my issues. I want to completely and utterly remove it from the scene and update it immediately, but calling self.update() does nothing. I want this change to be reflected immediately. In PySide it seems del took care of things well, but here's it's unclear.

Options: del setParent(None) setParentItem(None) hide() + deleteLater()

Upvotes: 0

Views: 4523

Answers (1)

Radio-
Radio-

Reputation: 3171

QGraphicsScene has a removeItem() method:

def mouseReleaseEvent(self, event):
    self.removeItem(self.rect)

The rectangle will be removed immediately when the mouse is released.

Upvotes: 2

Related Questions