【问题标题】:Resize images inside qt-label调整 qt-label 中的图像大小
【发布时间】:2012-10-18 15:27:11
【问题描述】:

我有一个 qt 标签,默认情况下其中有一个占位符图像:

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

有一个功能可以更新标签中包含的图像:

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

这工作正常(图像已更新),但如果用于更新标签的图像与占位符图像的大小不同,它也会变形。

有没有办法解决这个问题?我的意思是调整图像并保持标签的大小不变?

【问题讨论】:

  • Is there any way to fix this? 您的问题含糊不清...您更喜欢哪种解决方法?将标签调整为新的图像大小?保持旧图像的纵横比等...
  • 我的意思是调整图像并保持标签的大小

标签: qt qt4 pyqt


【解决方案1】:

你可以尝试设置scaledContents property:

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

对我来说很好用。

请注意,这会缩放图像以填充所有可用空间。这意味着除非标签大小和图像具有相同的纵横比,否则不会保留图像的纵横比。使用QPixmap.scale 方法也会遇到同样的问题,正如您在图片here 中看到的那样。

【讨论】:

  • 是的,但是图像没有失真吗?
  • 我认为扭曲意味着不保留纵横比。我已经更新了我的答案,试图解释它发生的原因。
【解决方案2】:

Scale the image 每次导入时。如果您已经为标签确定了尺寸,您甚至可以缩放占位符。 试试 (c++)

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

每次选择文件时:

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

【讨论】:

  • 另外请看一下 QLabel 的 setScaledContents() 方法(doc.qt.digia.com/qt/qlabel.html#scaledContents-prop)。
  • 我试过: self.label.setPixmap(QtGui.QPixmap(_fromUtf8(image))) 然后 self.label.pixmap().scaled(QtCore.QSize(self.label.size() ), QtCore.Qt.KeepAspectRatio, QtCore.Qt.FastTransformation) 但它不起作用
猜你喜欢
  • 1970-01-01
  • 2014-05-04
  • 1970-01-01
  • 2013-07-15
  • 2020-05-10
  • 2011-10-24
  • 2010-11-20
  • 1970-01-01
相关资源
最近更新 更多