QGraphicScene Background

风流意气都作罢 提交于 2021-01-28 19:22:46

问题


I'm learning PyQt5 to develop a small academy project. I need to set a background for the QGraphicScene, but I'm not able to make the image fit well into the scene. It is sometimes repeaded or too large depending on the scale I apply. Here is my code:

class MainWindow(QWidget):

    def __init__(self):
        super().__init__()

        self.title = "title";
        self.top = 100
        self.left = 100
        self.width = 1500
        self.height = 900
        self.initUI()

    def initUI(self):

        scene = QGraphicsScene(0, 0, width, heigth)
        view  = QGraphicsView(scene, self)
        image = QImage('pathToImage')
        scene.setBackgroundBrush(QBrush(image))

        self.setWindowTitle(self.title)
        self.setGeometry(self.top, self.left, self.width, self.height)
        self.show()

I've tried to rescale the image with

image.scaled(scene.width(), scene.height(), Qt.KeepAspectRatio)

but it does not fit well, in fact there are scrollbars because the image is too large. Anyone knows where the problem is?


回答1:


If you want the image to scale then you must override the drawBackground() method:

class GraphicsScene(QGraphicsScene):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._image = QImage()

    @property
    def image(self):
        return self._image

    @image.setter
    def image(self, img):
        if img != self.image:
            self._image = img
            self.update()

    def drawBackground(self, painter, rect):
        if self.image.isNull():
            super().drawBackground(painter, rect)
        else:
            painter.drawImage(rect, self.image)
scene = GraphicsScene(self)
scene.image = QImage("pathToImage")
view = QGraphicsView(scene)


来源:https://stackoverflow.com/questions/61458100/qgraphicscene-background

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!