PyQt / Qt:如何在Qlabel小部件中拉伸图像?

时间:2012-06-06 13:29:18

标签: qt pyqt

我想在我的应用中显示图片。我使用QtDesigner设计UI,然后使用pyqt进行编码。问题是将显示的图像比UI上的窗口小部件大。我参考官方演示: QT - Widget Image Viewer Demo

添加imagelabel和scrollArea,代码如下:

---- UI init ----
self.label = QtGui.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(40, 140, 361, 511))
self.label.setSizePolicy(QtGui.QSizePolicy.Preferred,QtGui.QSizePolicy.Preferred)
self.label.setObjectName(_fromUtf8("label"))
self.scrollArea = QtGui.QScrollArea(self.centralwidget)
self.scrollArea.setGeometry(QtCore.QRect(40, 140, 361, 511))
self.scrollArea.setWidget(self.label)
self.scrollArea.setObjectName(_fromUtf8("scrollArea"))

---- function ----
filename = "./Penguins.jpg"
image = QtGui.QImage(filename)
pp = QtGui.QPixmap.fromImage(image)
lbl = QtGui.QLabel(self.label)
lbl.setPixmap(pp)
self.scrollArea.setWidgetResizable(True)
lbl.show()

但它不会拉伸图像,甚至不会出现滚动条!

3 个答案:

答案 0 :(得分:14)

您需要致电self.label.setScaledContents(true);。这样QLabel会将自身调整为pixmap / image的大小,滚动条将变为可见。请参阅此documentation

答案 1 :(得分:4)

QLabel :: setScaledContents的默认实现对我来说不起作用,因为当图像大于标签时,它不允许我保持纵横比 最大尺寸。

这个小助手会缩小图像以适应标签的最大尺寸(如果需要)(但不是向上),始终保持纵横比:

/**
 * Fill a QLabel widget with an image file, respecting the widget's maximum sizes,
 * while scaling the image down if needed (but not up), and keeping the aspect ratio
 * Returns false if image loading failed
 ****************************************************************************/
static bool SetLabelImage(QLabel *label, QString imageFileName)
{
    QPixmap pixmap(imageFileName);
    if (pixmap.isNull()) return false;

    int w = std::min(pixmap.width(),  label->maximumWidth());
    int h = std::min(pixmap.height(), label->maximumHeight());
    pixmap = pixmap.scaled(QSize(w, h), Qt::KeepAspectRatio, Qt::SmoothTransformation);
    label->setPixmap(pixmap);
    return true;
}

答案 2 :(得分:0)

我不使用PyQt,但QtPixmap控件具有scaled()函数。您可以在放入标签之前调整图像大小:

  • 缩放()
  • scaledToHeight()
  • scaledToWidth()

这是我在C ++中使用的示例代码,用于将图像大小调整为QLabel大小:

imatge.load("sprite.png");
QPixmap imatge2 = imatge.scaled(ui->label->width(),ui->label->height());