如何在QGraphicsView的滚动条区域放置图像?

时间:2018-04-05 06:52:21

标签: python qt pyqt qgraphicsview qmainwindow

由于某些限制,图像必须在QMainWindow类中,滚动条必须是QGraphicsView类。

这意味着我必须通过QMainWindow类在QGraphicsView类中添加图像。 “exit.png”存在于运行此代码的文件夹中。

添加此图片的正确方法是什么?

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)

        print "sdsads"


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

        QtGui.QMainWindow.__init__(self, parent)
        centralwidget = Window()
        self.setCentralWidget(centralwidget) 

        centralwidget.scene.image = QtGui.QImage("exit.png")


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

1 个答案:

答案 0 :(得分:1)

对于这种情况,解决方案是使用QGraphicsPixmapItem

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

        QtGui.QMainWindow.__init__(self, parent)
        centralwidget = Window()
        self.setCentralWidget(centralwidget) 

        centralwidget.scene.addPixmap(QtGui.QPixmap("exit.png"))
        # or
        # item = QtGui.QGraphicsPixmapItem(QtGui.QPixmap("exit.png"))
        # centralwidget.scene.addItem(item)