一、简述
在QT中利用pixmap将已有的静态图素材在运行窗口实现动态化。
二、实现效果
三、工程文件
四、代码实现
1、设置定时器间隔,即进行设定组成动图的每帧的时间间隔
startTimer(200);
2、在头文件中创建一个pixmap数组用于存放动图的分解图,在cpp文件中将资源文件图片加载进pixmap数组中。
- 利用QString构造资源文件名fileName
- 定义map获取该文件名所指的图片
- 将map写入定义好的pixmap数组
void Dialog::InitPixmap()
{//将资源文件加载进pixmap数组中
for(int i=0;i<12;i++)
{
QString fileName=QString(":/new/prefix1/sn/IMG000%0.bmp").arg(i+1,2,10,QLatin1Char('0'));//构造资源文件名
QPixmap map(fileName);//将资源文件名传给map
pixmap[i]=map;//map传入pixmap数组
}
}
3、定义绘制图片事件函数
- 构造素材图片大小的矩形
- 构造窗口大小的矩形(如果不需要实现结果的动图填满整个窗口,此步可忽略)
- 利用drawPixmap将pixmap数组中的图片画出
void Dialog::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
QRect q1(0,0,500,281);//构造图片大小的矩形
QRect q2(0,0,width(),height());//构造窗口大小的矩形
painter.drawPixmap(q2,pixmap[curIndex],q1);//实现将q1画入q2,画的内容为pixmap中对应的图片
}
4、定义时间事件函数,利用该函数实现每次时间间隔后pixmap地址的加1和重绘。
void Dialog::timerEvent(QTimerEvent *event)
{
curIndex++;//计时器每计时一次,curIndex+1
if(curIndex>=12)
curIndex=0;//当curIndex的值等于图片的总张数之后,将curIndex归零
repaint();//计时器每计时一次进行一次重绘
}
五、完整代码
头文件 dialog.h
#ifndef DIALOG_H
#define DIALOG_H
#include <QDialog>
QT_BEGIN_NAMESPACE
namespace Ui { class Dialog; }
QT_END_NAMESPACE
class Dialog : public QDialog
{
Q_OBJECT
public:
Dialog(QWidget *parent = nullptr);
~Dialog();
//头文件中进行声明
void paintEvent(QPaintEvent* event);
void timerEvent(QTimerEvent* event);
int curIndex;
void InitPixmap();
private:
QPixmap pixmap[12];
Ui::Dialog *ui;
};
#endif // DIALOG_H
源文件
- dialog.cpp
#include "dialog.h"
#include "ui_dialog.h"
#include"qpainter.h"
#include"qpixmap.h"
Dialog::Dialog(QWidget *parent)
: QDialog(parent)
, ui(new Ui::Dialog)
{
ui->setupUi(this);
startTimer(200);//设置定时器间隔为200毫秒
InitPixmap();
curIndex=0;//curIndex用于记录当前处于第几张图片
}
Dialog::~Dialog()
{
delete ui;
}
void Dialog::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
QRect q1(0,0,500,281);//构造图片大小的矩形
QRect q2(0,0,width(),height());//构造窗口大小的矩形
painter.drawPixmap(q2,pixmap[curIndex],q1);//实现将q1画入q2,画的内容为pixmap中对应的图片
}
void Dialog::timerEvent(QTimerEvent *event)
{//时间事件函数
curIndex++;//计时器每计时一次,curIndex+1
if(curIndex>=12)
curIndex=0;//当curIndex的值等于图片的总张数之后,将curIndex归零
repaint();//计时器每计时一次进行一次重绘
}
void Dialog::InitPixmap()
{//将资源文件加载进pixmap数组中
for(int i=0;i<12;i++)
{
QString fileName=QString(":/new/prefix1/sn/IMG000%0.bmp").arg(i+1,2,10,QLatin1Char('0'));//构造资源文件名
QPixmap map(fileName);//将资源文件名传给map
pixmap[i]=map;//map传入pixmap数组
}
}
- main.cpp
#include "dialog.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Dialog w;
w.show();
return a.exec();
}