PyQt: place scaled image in centre of label

sundar_ima picture sundar_ima · Dec 28, 2014 · Viewed 9.2k times · Source

I am using QPixmap for displaying images of different sizes on a label. I have used the following code to display the image(s):

myPixmap = QtGui.QPixmap(os.path.join("data", "images", image_name))
myScaledPixmap = myPixmap.scaled(self.ui.label.size(), QtCore.Qt.KeepAspectRatio)

The above code works fine without any issue. However, the images are displayed on the left side of the label instead of the centre. Also, the scaling reduces the images further down, instead of filling the entire label.

Is it possible to display the image at the centre of label?

Answer

ekhumoro picture ekhumoro · Dec 28, 2014

If you just want the image to fill the whole label, no matter what its size is:

    self.ui.label.setScaledContents(True)
    self.ui.label.setPixmap(myPixmap)

However, this won't keep the aspect ratio of the image. To do that, you need to re-scale the pixmap every time the label changes size:

    self.pixmap = QtGui.QPixmap(os.path.join("data", "images", image_name))
    self.ui.label.setPixmap(self.pixmap)
    # this ensures the label can also re-size downwards
    self.ui.label.setMinimumSize(1, 1)
    # get resize events for the label
    self.ui.label.installEventFilter(self)
    ...

def eventFilter(self, source, event):
    if (source is self.ui.label and event.type() == QtCore.QEvent.Resize):
        # re-scale the pixmap when the label resizes
        self.ui.label.setPixmap(self.pixmap.scaled(
            self.ui.label.size(), QtCore.Qt.KeepAspectRatio,
            QtCore.Qt.SmoothTransformation))
    return super(MainWindow, self).eventFilter(source, event)

(NB: you may need to change MainWindow in the last line).

PS:

To guarantee that the image is always centred, you will also need this:

    self.ui.label.setAlignment(QtCore.Qt.AlignCenter)