Search code examples
pythonpyqtbackgroundpyqt5qgraphicsscene

QGraphicScene Background


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?


Solution

  • 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)