At the documentation for QGraphicsScene, there is a simple example that does not work as written. I've written a fix that does work, and am curious if it could be improved.

From the docs (does not work as is):

scene = QGraphicsScene()
scene.addText("Hello, world!")
view = QGraphicsView(&scene)

Fixed version that does work:

from PySide import QtGui
import sys

class MyFirstScene(QtGui.QWidget):
    def __init__(self):
        self.scene.addText("Hello, world!")
        self.view = QtGui.QGraphicsView(self.scene, self)

if __name__=="__main__":
    firstScene = MyFirstScene()

My question is whether I can simplify this more, making it more like the example in the documentation. I tried doing it without making the scene an attribute of QWidget, which breaks it. But perhaps I'm missing a simpler working implementation of the documentation's skeleton?

  • \$\begingroup\$ Did you try simply to omit the &? Works for me in PyQt, don't know about PySide. \$\endgroup\$ – Janne Karila Sep 15 '14 at 8:33
  • \$\begingroup\$ @JanneKarila That was the first thing I tried, and Python crashed (this was both PySide and PyQt). If you got that four-liner from the docs to work, I'd really like to see the code! \$\endgroup\$ – neuronet Sep 15 '14 at 16:15

This complete script works for me with PyQt on Windows, displays a small window and waits for me to close it.

from PyQt4 import QtGui

app = QtGui.QApplication([])

scene = QtGui.QGraphicsScene()
scene.addText("Hello, world!")
view = QtGui.QGraphicsView(scene)


A QApplication object must be created before any other GUI objects.

  • \$\begingroup\$ Nice! This is a definite improvement on my example. Follows the spirit of the documentation, and also the output looks nicer because the scene is not wrapped in a QWidget. \$\endgroup\$ – neuronet Sep 16 '14 at 13:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.