views:

14

answers:

1

How can I create a class that extend QGraphicsItem to define a new kind of Item?

I'm trying to do that

#!/usr/bin/python

import sys
from PyQt4 import QtGui

class Node(QtGui.QGraphicsItem):
    def __init__(self, parent = 0):
        self.setFlag(QtGui.QGraphicsItem.ItemIsMovable)


app = QtGui.QApplication(sys.argv)

scene = QtGui.QGraphicsScene()
scene.addText("test")

scene.addItem(Node())

view = QtGui.QGraphicsView(scene)
view.show()

sys.exit(app.exec_())

but i get this error

Traceback (most recent call last):
  File "primo.py", line 15, in <module>
    scene.addItem(Node())
  File "primo.py", line 8, in __init__
    self.setFlag(QtGui.QGraphicsItem.ItemIsMovable)
RuntimeError: underlying C/C++ object has been deleted    

What am I doing wrong? I can't call QGraphicsItem constructor inside the init method of Node because QGraphicsItem it's an abstract class

+1  A: 

The solution is this

#!/usr/bin/python

import sys
from PyQt4 import QtGui

class Node(QtGui.QGraphicsItem):
    def __init__(self, parent = None):
        QtGui.QGraphicsItem.__init__(self,parent)
        self.setFlag(QtGui.QGraphicsItem.ItemIsMovable)

app = QtGui.QApplication(sys.argv)

scene = QtGui.QGraphicsScene()
scene.addText("test")

scene.addItem(Node())

view = QtGui.QGraphicsView(scene)
view.show()

sys.exit(app.exec_())
mambro