1
votes

It is a common problem to display a QImage in a widget. While this can be done using QLabel.setPixmap, the resulting QLabel will have a fixed size equal to the size of the pixmap. It is possible to use setScaledContents to make QLabel scale the pixmap and allow for resizing. However, this will ignore the aspect ratio of the image and scale the pixmap to fill the whole label.

Several other questions on StackOverflow ask for solutions to that problem, and the typical solution given is to re-scale the pixmap using QPixmap.scaled() depending on the size of the widget:

Is there a different, more "native" way to achieve this?

1

1 Answers

2
votes

The following QLabel-based widget that will preserve the aspect ratio of a pixmap assigned to it. It uses the heighForWidth method to return the preferred height of the widget given its width. This way, the widget naturally respects the aspect ratio of the pixmap when resized and scales it accordingly. Tested in PyQt5.

class ImageWidget(QLabel):

    def __init__(self, parent=None):
        super().__init__(parent)
        self.setScaledContents(True)

    def hasHeightForWidth(self):
        return self.pixmap() is not None

    def heightForWidth(self, w):
        if self.pixmap():
            return int(w * (self.pixmap().height() / self.pixmap().width()))