[PyQt] Subclass of QGraphicsObject does not have the correct class name listed in QGraphicsScene.items()

Phil Thompson phil at riverbankcomputing.com
Fri May 20 16:46:14 BST 2011


On Thu, 19 May 2011 14:42:47 -0700, Selim Tuvi
<Selim.Tuvi at pdi.dreamworks.com> wrote:
> The code below outputs:
> 
> [<__main__.Edge object at 0x2aaab0395830>, <PyQt4.QtGui.QGraphicsItem 
> object at 0x2aaab03958c0>]
> 
> which lists the Node instance as having the class QGraphicsItem when it 
> should say <__main__.Node object at ...>.
> 
> Tested on (Qt 4.7.2, PyQt 4.8.3) and (Qt 4.6.1, PyQt 4.7.2)
> 
> Thanks
> -Selim
> 
> from PyQt4 import QtGui, QtCore
> 
> class Node(QtGui.QGraphicsObject):
>     def __init__(self):
>         QtGui.QGraphicsObject.__init__(self)
>        
>     def paint(self, painter, option, widget):
>         pass
>        
>     def boundingRect(self):
>         return QtCore.QRectF()
> 
> class Edge(QtGui.QGraphicsItem):
>     def __init__(self):
>         QtGui.QGraphicsItem.__init__(self)
> 
>     def paint(self, painter, option, widget):
>         pass
> 
>     def boundingRect(self):
>         return QtCore.QRectF()
> 
> if __name__ == '__main__':
>     import sys
>     app = QtGui.QApplication(sys.argv)
>     print QtCore.QT_VERSION_STR, QtCore.PYQT_VERSION_STR
>     view = QtGui.QGraphicsView()
>     scene = QtGui.QGraphicsScene()
>     view.setScene(scene)
>     scene.addItem(Node())
>     scene.addItem(Edge())
>     print scene.items()
>     view.show()
>     sys.exit(app.exec_())

It's because QGraphicsObject inherits both QObject and QGraphicsItem.
items() returns a list of QGraphicsItems which, for a QGraphicsObject, has
a different C++ address than the original QGraphicsObject. PyQt doesn't
recognise that the QGraphicsItem is a cast of the QGraphicsObject. I don't
think there is anything I can (sensibly) do about this.

Phil


More information about the PyQt mailing list