2

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?

user601836
  • 3,215
  • 4
  • 38
  • 48
  • `Is there any way to fix this?` your question is vague... Which fix do you prefer? resize the label to the new image size? keep the aspect ratio of the old image etc... – UmNyobe Oct 29 '12 at 10:30
  • i mean to adapt the image and to keep fix the size of the label – user601836 Oct 29 '12 at 10:37

3 Answers3

2

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));
UmNyobe
  • 22,539
  • 9
  • 61
  • 90
  • Also please take a look at QLabel's setScaledContents() method(http://doc.qt.digia.com/qt/qlabel.html#scaledContents-prop). – Joonhwan Oct 29 '12 at 11:24
  • i tried: self.label.setPixmap(QtGui.QPixmap(_fromUtf8(image))) and then self.label.pixmap().scaled(QtCore.QSize(self.label.size()), QtCore.Qt.KeepAspectRatio, QtCore.Qt.FastTransformation) but it does not work – user601836 Oct 29 '12 at 12:36
2

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.

Vicent
  • 5,322
  • 2
  • 28
  • 36
0

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))
shaun_m
  • 1,213
  • 3
  • 13