Home > Back-end >  Allow window to be resized to make expanding pixmap smaller in PyQt
Allow window to be resized to make expanding pixmap smaller in PyQt

Time:07-07

I have a QLabel showing a QPixmap that has both horizontal and vertical policies set to expanding. I have written separate code to automatically scale the pixmap according to the size of the widget, but the window cannot be resized to make the image smaller than it is, and it results in it not being able to be made smaller. How do I allow the window to be resized freely?

Resizing code:

def resizeEvent(self, a0: QtGui.QResizeEvent):
    self.page.setPixmap(
        self.loader.img.scaled(
        self.page.width(), self.page.height(), QtCore.Qt.KeepAspectRatio
        )
    )

CodePudding user response:

The easiest way is to inherit from QWidget override paintEvent and use QTransform to scale image to fit.

from PyQt5 import QtWidgets, QtGui, QtCore

class ImageLabel(QtWidgets.QWidget):
    def __init__(self, parent = None):
        super().__init__(parent)
        self._image = None

    def setImage(self, image):
        self._image = image
        self.update()

    def paintEvent(self, event):
        if self._image is None or self._image.isNull():
            return
        painter = QtGui.QPainter(self)
        width = self.width()
        height = self.height()
        imageWidth = self._image.width()
        imageHeight = self._image.height()
        r1 = width / imageWidth
        r2 = height / imageHeight
        r = min(r1, r2)
        x = (width - imageWidth * r) / 2
        y = (height - imageHeight * r) / 2
        painter.setTransform(QtGui.QTransform().translate(x, y).scale(r,r))
        painter.drawImage(QtCore.QPointF(0,0), self._image)

if __name__ == "__main__":
    app = QtWidgets.QApplication([])
    label = ImageLabel()
    label.setImage(QtGui.QImage("path/to/image.jpg"))
    label.show()
    app.exec()

  • Related