PyQt: place scaled image in centre of label
Asked Answered
S

2

5

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?

Syzygy answered 28/12, 2014 at 11:37 Comment(0)
I
11

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)
Insulation answered 28/12, 2014 at 19:12 Comment(2)
Will this display the pixmap centered in the label?Phina
@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.Insulation
K
0

I think your issue with downsampling of the image results from using label.size()

Try using your mainWindow.size() instead

Kalli answered 26/7, 2017 at 7:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.