QT中在label中插入图片自适应label大小等比缩放

一、代码如下

    QImage *img_mainicon;//主图标显示在右上角lable中
    img_mainicon =new QImage;//新建一个image对象
    img_mainicon->load(":/image/images/haiyan.jpg"); //载入图片到img对象中
    img_mainicon->scaled(ui->label_mainicon->size(),Qt::KeepAspectRatio);//把图片
    ui->label_mainicon->setScaledContents(true);
    ui->label_mainicon->setPixmap(QPixmap::fromImage(*img_mainicon)); //将图片放入label,使用setPixmap,注意指针*img
    //ui->label_mainicon->setAlignment(Qt::AlignCenter); //将图片放在label中心,用缩放了就不需要了

二、详解

其中第一,第二,第三行代码可以整合成一行

QPixmap *pixmap = new QPixmap(":/images/welcome_tlauto.png");

其中路径可以由资源文件得到

第四条语句:设置图片缩放到label尺寸

这个是帮助中函数解释

QImage QImage::scaled(const QSize &size, Qt::AspectRatioMode aspectRatioMode = Qt::IgnoreAspectRatio, Qt::TransformationMode transformMode = Qt::FastTransformation) const

Returns a copy of the image scaled to a rectangle defined by the given size according to the given aspectRatioMode and transformMode.

返回按给定aspectRatioMode和transformMode将图像缩放到由给定大小定义的矩形的副本

  • If aspectRatioMode is Qt::IgnoreAspectRatio, the image is scaled to size. 图像按比例缩小。
  • If aspectRatioMode is Qt::KeepAspectRatio, the image is scaled to a rectangle as large as possible inside size, preserving the aspect ratio.图像被缩放到一个尽可能大的矩形内尺寸,保持高宽比。
  • If aspectRatioMode is Qt::KeepAspectRatioByExpanding, the image is scaled to a rectangle as small as possible outside size, preserving the aspect ratio.图像被缩放到一个尽可能小的矩形尺寸,保持高宽比。

If the given size is empty, this function returns a null image.如果给定的大小为空,则此函数返回空图像。

See also isNull() and Image Transformations.

扫描二维码关注公众号,回复: 8540396 查看本文章

第五条语句:它的作用是设置label的属性scaledContents,这个属性的作用是允许(禁止)label缩放它的内容充满整个可用的空间。特别说明的一点是当使能该属性并且label显示pixmap时,它能够缩放pixmap充满整个可用的空间。

scaledContents : bool

This property holds whether the label will scale its contents to fill all available space.

此属性保存标签是否会缩放其内容以填充所有可用空间。

When enabled and the label shows a pixmap, it will scale the pixmap to fill the available space.

当启用时,标签显示一个像素图,它将缩放像素图来填充可用空间。

This property's default is false.

此属性的默认值为false。

Access functions:

bool

hasScaledContents() const

void

setScaledContents(bool)

发布了27 篇原创文章 · 获赞 6 · 访问量 5053

猜你喜欢

转载自blog.csdn.net/qq_21449473/article/details/103820668