PySide + QGraphicsScene只是显示为黑色

时间:2012-06-23 19:22:26

标签: python pyqt pyside qgraphicsview

我想要做的就是将“hello world”写入QGraphicsScene中的QGraphicsView。我究竟做错了什么?我在Designer中创建了一个QGraphicsView,然后在我的__init__中创建了一个QGraphicsScene并添加了一些文本...但我得到的只是一个黑色的窗口。

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)

以下是Designer的UI代码:

# 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))

我得到的只是一个空白的黑色画布:

screenshot

1 个答案:

答案 0 :(得分:3)

有两个问题......

首先,在QGraphicsView中将Foreground画笔设置为黑色。这意味着除非另有说明,否则所有孩子都将继承。

UI

    brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
    brush.setStyle(QtCore.Qt.SolidPattern)
    #self.graphicsView.setForegroundBrush(brush)
    self.graphicsView.setBackgroundBrush(brush)

此外,由于您将背景更改为黑色,因此应将文本设置为您可以看到的颜色。因为默认情况下它会是黑色的:

    text = self.scene.addText('hello')
    text.setDefaultTextColor(QtGui.QColor(QtCore.Qt.red))

如果你不关心黑色背景而只是想看到它的工作原理,只需在你的UI中注释掉这一行(或者在Designer中取消设置画笔设置),不做其他改动:

    # self.graphicsView.setForegroundBrush(brush)