Qt设置图片

一、设置图片

(一)setIcon

以QPushButton为例,设置按钮的图标可以使用函数setIcon,设置图标大小使用setIconSize。

QPixmap pix;
//设置图片固定大小
this->setFixedSize(pix.width(),pix.height());
//设置不规则图片样式
this->setStyleSheet("QPushButton{border:0px;}");
//设置图标
this->setIcon(pix);
//设置图标大小
this->setIconSize(QSize(pix.width(),pix.height()));

(二)drawPixmap

QPainter的drawPixmap(),QLabel

QPainter painter(this);
painter.drawPixmap(0, 0, m_pic);

(三)setPixmap

使用QLabel的setPixmap()就可以将图片显示出来

//绘制背景图片
QLabel* label = new QLabel;
label->setGeometry(57 + i * 50, 200 + j * 50, 50, 50);
label->setPixmap(QPixmap("res/BoardNode.png"));
label->setParent(this);

(四)setWindowIcon

//设置固定大小
this->setFixedSize(320,588);
//设置图标
this->setWindowIcon(QPixmap("res/Coin0001.png"));
//设置窗口标题
this->setWindowTitle("翻金币主场景");

二、scaled

(一)scaled函数

图像缩放采用scaled函数。(也可以放大)

//qpixmap.h
inline QPixmap scaled(int w, int h, Qt::AspectRatioMode aspectMode = Qt::IgnoreAspectRatio,
                          Qt::TransformationMode mode = Qt::FastTransformation) const
        { return scaled(QSize(w, h), aspectMode, mode); }

(二)用法

scaled函数中width和height表示缩放后图像的宽和高,即将原图像缩放到(width,height)大小。

scaled()函数是返回一个新的QPixmap的

QImage* imgScaled = new QImage;
*imgScaled=img->scaled(width,height,Qt::KeepAspectRatio);
ui->label->setPixmap(QPixmap::fromImage(*imgScaled));

(三)例子

//加载标题
QPainter painter(this);
QPixmap pix;
pix.load("res/Title.png");
pix = pix.scaled(pix.width()*0.5,pix.height()*0.5);
painter.drawPixmap( 10,30,pix.width(),pix.height(),pix);

 

posted @ 2023-02-08 14:13  ImreW  阅读(617)  评论(0编辑  收藏  举报