# Simple QGraphicsScene program

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()
view = QGraphicsView(&scene)
view.show()


Fixed version that does work:

from PySide import QtGui
import sys

class MyFirstScene(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self)
self.scene=QtGui.QGraphicsScene(self)
self.view = QtGui.QGraphicsView(self.scene, self)
self.show()

if __name__=="__main__":
app=QtGui.QApplication(sys.argv)
firstScene = MyFirstScene()
sys.exit(app.exec_())


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?

• Did you try simply to omit the &? Works for me in PyQt, don't know about PySide. – Janne Karila Sep 15 '14 at 8:33
• @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! – 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()
view = QtGui.QGraphicsView(scene)
view.show()

app.exec_()


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

• 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. – neuronet Sep 16 '14 at 13:22