How to put an image in QGraphicsView's scrollb

2019-08-02 17:38发布

问题:

Due to some restrictions image has to be in the class QMainWindow and scrollbars have to be the QGraphicsView class.

This means that I have to add image in QGraphicsView class through QMainWindow class. "exit.png" exists in the folder from where I run this code.

What is the proper way to add this picture?

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:

For this case the solution is to use a 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)