1
votes

I have a QLabel which displays an image. Currently, I have the image set to keep it's aspect ratio, and grow as big as it can within the QLabel.

Is there any way I can also set the QLabel to maintain the image's aspect ratio? I do not want to have "blank" QLabel space either side of the image when the label is wider than the image.

I have been looking for any sort of QLabel property that would allow me to set the aspect ratio of the label, but have not managed to get anything to do what I wanted to do.

All the answers I have seen relate to keeping the aspect ratio of a resized QPixmap image, but not of the QLabel containing it.

Any help would be great!

Cheers

FP

1
You could use setMaximumSize on the QLabel, setting it to the size of the image. You would have to call it every time there is a resize event. I don't know if there is an easier way.Mel
Thanks tmoreau, that seems to have worked okay after some thought :)fp1991

1 Answers

4
votes

I seem to have cracked it, so incase anyone else was wondering how to do this:

I took tmoreau's solution and modified it slightly. For it to work, you need to set the QLabel's maximum size to the image's new size prior to the paint event. Immediately afterwards, you need to set the maximum size for the QLabel to something very large, otherwise, you will not be able to enlarge the image at all as you will have specified the maximum size to be that of the current image.

def paintEvent(self, event):
        size = self.size()
        painter = QtGui.QPainter(self)
        point = QtCore.QPoint(0,0)
        scaledPix = self.pixmap.scaled(size, Qt.KeepAspectRatio, transformMode = Qt.SmoothTransformation)
        self.setMaximumSize(scaledPix.size())
        point.setX(0)
        point.setY(0)
        #print (point.x(), ' ', point.y())
        painter.drawPixmap(point, scaledPix)
        self.setMaximumSize(QtCore.QSize(4000,5000))

If anyone has a better solution, by all means please let me know!