2
\$\begingroup\$

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)
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.scene.addText("Hello, world!")
        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?

\$\endgroup\$
  • \$\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
3
\$\begingroup\$

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)
view.show()

app.exec_()

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

\$\endgroup\$
  • \$\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.