PyQt: place scaled image in centre of label

10,864

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)
Share:
10,864
sundar_ima
Author by

sundar_ima

Updated on June 19, 2022

Comments

  • sundar_ima
    sundar_ima about 2 years

    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?

  • Trilarion
    Trilarion over 9 years
    Will this display the pixmap centered in the label?
  • ekhumoro
    ekhumoro over 9 years
    @Trilarion. Possibly, but it depends on the dimensions of the image and the parent window. I've added a refinement that will guarantee that it is always centred.