QGraphicsView不在QMainWindow中显示

时间:2010-09-08 01:59:11

标签: python user-interface qt frameworks pyqt

我不确定为什么这个应用程序没有显示任何内容。我将在几行中重现,以提供问题的要点。使用PyQt4

class SomeScene(QtGui.QGraphicsScene):
    def __init__(self, parent = None):
        QtGui.QGraphicsScene.__init__(self, parent)

        pixmap = QtGui.QPixmap('someImage') # path is DEFINITELY valid
        item = QGraphicsPixmapItem(pixmap)
        self.addItem(item)


class MainWindow(QtGui.QMainWindow):
    def __init__(self, parent = None):
        QtGui.QMainWindow.__init__(self, parent)
        ... # code to set up window

        scene = SomeScene()
        view = QtGui.QGraphicsView(scene)

        hbox = QtGui.QHBoxLayout()
        hbox.addWidget(view)

        mainWidget = QtGui.QWidget()
        mainWidget.setLayout(hbox)

        self.setCentralWidget(mainWidget)


app = QtGui.QApplication(sys.argv)
mainWindow = MainWindow()
mainWindow.show()
sys.exit(app.exec_())

这只会显示一个空格。

1 个答案:

答案 0 :(得分:2)

视图为空白,因为场景已被破坏。如果场景未存储在成员变量中,则场景将被销毁。视图不占用场景的所有权,因为场景可以具有多个视图。通过下面的示例,tmpScene将被销毁(导致打印“tmpScene destroyed”消息),但是self.scene将在视图中使用,并且将显示pixmap项目。

import sys
from PyQt4 import QtGui
import sip

class SomeScene(QtGui.QGraphicsScene):
    def __init__(self, parent = None):
        QtGui.QGraphicsScene.__init__(self, parent)

        pixmap = QtGui.QPixmap('someImage')
        item = QtGui.QGraphicsPixmapItem(pixmap)
        self.addItem(item)


class MainWindow(QtGui.QMainWindow):
    def __init__(self, parent = None):
        QtGui.QMainWindow.__init__(self, parent)

        # This scene will be destroyed because it is local.
        tmpScene = SomeScene()
        tmpScene.destroyed.connect(self.onSceneDestroyed)

        self.scene = SomeScene()
        view = QtGui.QGraphicsView(self.scene)

        hbox = QtGui.QHBoxLayout()
        hbox.addWidget(view)

        mainWidget = QtGui.QWidget()
        mainWidget.setLayout(hbox)

        self.setCentralWidget(mainWidget)

    def onSceneDestroyed(self, obj):
        print 'tmpScene destroyed'

app = QtGui.QApplication(sys.argv)
mainWindow = MainWindow()
mainWindow.show()
sys.exit(app.exec_())