QLabel添加背景图片,并且适应QLabel大小

1、    QLabel添加背景图片,并且适应QLabel大小

QImage Image;
    Image.load("d:/test.jpg");
    QPixmap pixmap = QPixmap::fromImage(Image);
    int with = ui->labPic->width();
    int height = ui->labPic->height();
    QPixmap fitpixmap = pixmap.scaled(with, height, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);  // 饱满填充
    //QPixmap fitpixmap = pixmap.scaled(with, height, Qt::KeepAspectRatio, Qt::SmoothTransformation);  // 按比例缩放
    ui->labPic->setPixmap(fitpixmap);

使用aspectRatioMode和transformMode指定的宽高比和变换模式将像素图缩放到给定大小。
如果aspectRatioMode是Qt :: IgnoreAspectRatio,则矩形框有多大,图片就缩放成多大,不限制原图片的长宽比
如果aspectRatioMode是Qt :: KeepAspectRatio,则pixmap将缩放为内部大小尽可能大的矩形,从而保留纵横比。
如果aspectRatioMode是Qt :: KeepAspectRatioByExpanding,则像素图缩放为尽可能小的外部尺寸的矩形,保留纵横比。
如果给定大小为空,则此函数返回空像素图。

2、QPixmap scaled函数

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

 根据给定的尺寸来放大缩小QPixmap

IgnoreAspectRatio  矩形框有多大,图片就缩放成多大,不限制原图片的长宽比

KeepAspectRatio    保持原图片的长宽比,且不超过矩形框的大小

KeepAspectRatioByExpanding   根据矩形框的大小最大缩放图片

 

QPixmap::scaled(int width, int height, Qt::AspectRatioMode aspectRatioMode = Qt::IgnoreAspectRatio, Qt::TransformationMode transformMode = Qt::FastTransformation) const

返回匹配目标设置后的QPixmap,宽高为给定值

 

加入QLable的大小是变化的,图片仍然要保持比例或填充,那么需要用:

    QImage img; 
    img.load ("E:/QT_Company/Client/images/demo/0.png");    
    QPixmap pixmap(QPixmap::fromImage(img));    
    ui->label->setMinimumSize(ui->label->size());    
    pixmap.scaled(ui->label->size(), Qt::KeepAspectRatio);    
    //ui->label->setScaledContents(true);         
      ui->label->setAlignment(Qt::AlignCenter);
    ui->label->setPixmap(pixmap);

我用第一种方式测试,发现随着QLable大小变化,图像不能随着变化,不知道是什么原因.

  • 2
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值