QGraphicsView not displaying in QMainWindow
I'm not sure why this application is not displaying anything. I'll reproduce in a few lines to provide the gist of the issue. Using PyQt4
class SomeScene(QtGui.QGraphicsScene):
def __init__(self, parent = None):
QtGui.QGraphicsScene.__init__(self, parent)
pixmap = QtGui.QPixmap('someIma开发者_StackOverflow社区ge') # 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_())
This would just show a blank space.
The view is blank because the scene has been destroyed. The scene is destroyed if it is not stored in a member variable. The view does not take ownership of the scene since a scene can have multiple views. With the example below, the tmpScene will be destroyed (causing a "tmpScene destroyed" message to be printed), but the self.scene will be used in the view and the pixmap item will be displayed.
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_())
精彩评论