All I want to do is write "hello world" to a QGraphicsScene
in a QGraphicsView
. What am I doing wrong? I created a QGraphicsView
in Designer, and then in my __init__
I create a QGraphicsScene
and add some text to it... but all I get is a black window.
import sys
from PySide import QtCore, QtGui
from PySide.QtGui import *
class MyDialog(QDialog):
def __init__(self):
super(MyDialog, self).__init__()
self.ui = Ui_Dialog()
self.ui.setupUi(self)
self.scene = QGraphicsScene()
self.ui.graphicsView.setScene(self.scene)
self.scene.setSceneRect(0,0,100,100)
self.scene.addText('hello')
def main(argv):
app = QApplication(sys.argv)
myapp = MyDialog()
myapp.show()
app.exec_()
sys.exit()
if __name__ == "__main__":
main(sys.argv)
The following is the UI code from Designer:
# everything from here down was created by Designer
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(400, 300)
self.buttonBox = QtGui.QDialogButtonBox(Dialog)
self.buttonBox.setGeometry(QtCore.QRect(30, 240, 341, 32))
self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Cancel|QtGui.QDialogButtonBox.Ok)
self.buttonBox.setObjectName("buttonBox")
self.graphicsView = QtGui.QGraphicsView(Dialog)
self.graphicsView.setGeometry(QtCore.QRect(50, 30, 256, 192))
self.graphicsView.setMouseTracking(False)
self.graphicsView.setFrameShadow(QtGui.QFrame.Sunken)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
self.graphicsView.setForegroundBrush(brush)
self.graphicsView.setObjectName("graphicsView")
self.retranslateUi(Dialog)
QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL("accepted()"), Dialog.accept)
QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL("rejected()"), Dialog.reject)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
Dialog.setWindowTitle(QtGui.QApplication.translate("Dialog", "Dialog", None, QtGui.QApplication.UnicodeUTF8))
All I get is this, with a blank black canvas:
There are two problems...
First, you set your Foreground brush to black in your QGraphicsView. That means all children will inherit that unless they specify otherwise.
ui
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
#self.graphicsView.setForegroundBrush(brush)
self.graphicsView.setBackgroundBrush(brush)
Also, since you changed the background to black, you should set your text to a color you can see. Because it will be black by default:
main
text = self.scene.addText('hello')
text.setDefaultTextColor(QtGui.QColor(QtCore.Qt.red))
If you don't care about the black background and just simply want to see it work, just comment out this line in your UI (or unset the brush setting in Designer) and change nothing else:
# self.graphicsView.setForegroundBrush(brush)