PyQt:Scrollbars不显示,QGraphicsView类嵌套在QMainWindow下

时间:2018-04-05 05:15:54

标签: python pyqt pyqt5 qgraphicsview qmainwindow

我应该在屏幕上添加滚动条。下面显示的类设计是我应该修改并添加滚动条的软件的一部分。我已经添加了Window类中的滚动条代码。

运行程序时没有显示。我应该纠正什么?

import sys

from PyQt4 import QtGui
from PyQt4 import QtCore

class Window(QtGui.QGraphicsView):

  def __init__(self, parent=None):

        QtGui.QGraphicsView.__init__(self, parent)
        self.scene = QtGui.QGraphicsScene(self)
        self.scene.setBackgroundBrush(QtGui.QBrush(QtCore.Qt.darkGray, QtCore.Qt.SolidPattern))
        self.setScene(self.scene)

        self.setDragMode(QtGui.QGraphicsView.ScrollHandDrag)
        self.setTransformationAnchor(QtGui.QGraphicsView.AnchorUnderMouse)
        self.viewport().setCursor(QtCore.Qt.CrossCursor)
        self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
        self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)


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

        QtGui.QMainWindow.__init__(self, parent)

        Window()

app = QtGui.QApplication(sys.argv)
GUI = CityscapesLabelTool()
GUI.show()
sys.exit(app.exec_())

1 个答案:

答案 0 :(得分:1)

当程序离开其作用域时,将删除局部变量,在您的情况下,Window()是一个局部变量,当它完成执行构造函数时,将被删除。对于不被销毁的变量,它必须与另一个具有更大范围的变量相关。在这种情况下,使用Window()的centralWidget设置QMainWindow是合适的。

import sys

from PyQt4 import QtGui
from PyQt4 import QtCore

class Window(QtGui.QGraphicsView):
  def __init__(self, parent=None):
        QtGui.QGraphicsView.__init__(self, parent)
        self.scene = QtGui.QGraphicsScene(self)
        self.scene.setBackgroundBrush(QtGui.QBrush(QtCore.Qt.darkGray, QtCore.Qt.SolidPattern))
        self.setScene(self.scene)

        self.setDragMode(QtGui.QGraphicsView.ScrollHandDrag)
        self.setTransformationAnchor(QtGui.QGraphicsView.AnchorUnderMouse)
        self.viewport().setCursor(QtCore.Qt.CrossCursor)
        self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
        self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)


class CityscapesLabelTool(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QMainWindow.__init__(self, parent)
        centralwidget = Window()
        self.setCentralWidget(centralwidget)

app = QtGui.QApplication(sys.argv)
GUI = CityscapesLabelTool()
GUI.show()
sys.exit(app.exec_())