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大小变化,图像不能随着变化,不知道是什么原因.