user601836
user601836

Reputation: 3235

Resize images inside qt-label

I have a qt label which by default has a place holder image in it:

self.label.setPixmap(QtGui.QPixmap(_fromUtf8("place_holder.jpg")))

There is a function to update the image contained in the label which is:

def selectFile(self):
image = QtGui.QFileDialog.getOpenFileName(None, 'Select Reference Image', '', '*.jpg')
self.label.setPixmap(QtGui.QPixmap(_fromUtf8(image)))

This works fine (the image is updated), but it is also deformed if the image used to update the label has different size from the place holder image.

Is there any way to fix this? I mean to adapt the image and to keep fix the size of the label?

Upvotes: 2

Views: 8768

Answers (3)

cibimanoharan
cibimanoharan

Reputation: 1

try this, this helped me for scaling the image to fit the label while maintaining the aspect ratio. Will also help to resize the image based on the label size.

pixmap = QPixmap(x)

pixmap = pixmap.scaled(self.label.size().width(),self.ui.label_4.size().height(), Qt.KeepAspectRatio)         

self.label.setPixmap(QPixmap(pixmap))

Upvotes: 0

Vicent
Vicent

Reputation: 5452

You can try to set the scaledContents property:

self.label.setScaledContents(True)
self.label.setPixmap(QPixmap("your_image.jpeg"))

It works fine for me.

Beware that this scale the image to fill all available space. It means that the aspect ratio of the image wont be preserved unless the label size and the image have the same aspect ratio. You will have the same problem using the QPixmap.scale method as you can see in the images here.

Upvotes: 3

UmNyobe
UmNyobe

Reputation: 22890

Scale the image each time you import it. If you already have a size in mind for your label, you can even scale the place holder. try (c++)

//initial setup
QPixmap pixPlaceHolder = QPixmap(_fromUtf8("place_holder.jpg");
QSize desiredsize = pixPlaceHolder.size(); // or any of the size you want

Each time you select a file:

 label.setPixmap(QPixmap(_fromUtf8(image).scaled(desiredsize));

Upvotes: 2

Related Questions