pyside QGraphicsScene:为什么不工作?

2 投票
1 回答
1923 浏览
提问于 2025-04-17 11:17

我刚接触Qt和PySide,想做一个小应用程序来展示一些简单的线条图。为此,我尝试使用QGraphicsView和QGraphicsScene。我做了一个测试来学习它是如何工作的,但结果并不如我所愿。我在网上查了很多资料,但还是不明白为什么它不工作。有没有人能告诉我原因,让我明白一下?

我的代码(只是想在场景上放一条线和一些示例文本):

#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
from PySide import QtGui, QtCore

class Example(QtGui.QWidget):

    def __init__(self):
        super(Example, self).__init__()
        self.initUI()

    def initUI(self):

        hbox=QtGui.QHBoxLayout()
        leftpanel=QtGui.QFrame()
        leftpanel.setGeometry(0,0,300,400)
        scene=QtGui.QGraphicsScene()
        scene.addText("Hello, world!")
        view=QtGui.QGraphicsView(scene,leftpanel)
        view.setSceneRect(0,0,300,400)
        pen=QtGui.QPen(QtCore.Qt.black,2)
        scene.addLine(0,0,200,200,pen)
        hbox.addWidget(leftpanel)
        rightpanel=QtGui.QFrame()
        hbox.addWidget(rightpanel)
        szoveg=QtGui.QLabel(rightpanel)
        szoveg.setText(u"Hello World!")
        self.setLayout(hbox)
        self.resize(500,500)
        self.setWindowTitle('blabla')
        self.show()


def main():

    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

1 个回答

2

你需要在某个地方保存对场景的引用,比如在Example这个实例里:

def initUI(self):
    # ...
    scene = QtGui.QGraphicsScene()
    self.scene = scene  # save reference to scene, or it will be destroyed
    scene.addText("Hello, world!")
    # ...

在另一个函数里,你就可以往场景里添加更多的项目了:

def anotherFunction(self):     
    self.scene.addText("Another Hello, world!")

撰写回答