##Qt之自制小动画##
三两闲语
人类具有“视觉暂留”的特性,人的眼睛看到一幅画或者一个物体后,在0.34秒以内不会消失。利用这一特性,我们可以将定时器调到恰当的时间,再结合QPixmap类就可以使一组图流畅地展示在人们面前,形成一个小动画
准备工作
- 一组连续的图
- 了解QPixmap、QTimer的一些基本用法
- 新建一个dialog项目文件
功能实现
1、dialog.h
在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 t; //定时器变量
void INitPixmap(); //将整个图片资源导入
private:
QPixmap pixmap[11];
Ui::Dialog *ui;
};
#endif // DIALOG_H
2、dialog.cpp
(1)头文件以及dialog类
#include "dialog.h"
#include "ui_dialog.h"
#include<QPainter>
#include<QPixmap>
Dialog::Dialog(QWidget *parent)
: QDialog(parent)
, ui(new Ui::Dialog)
{
ui->setupUi(this);
startTimer(100); //每隔100毫秒调动一次定时器
t=0;
INitPixmap();
}
Dialog::~Dialog()
{
delete ui;
}
(2)将资源图片一张张导入对应的pixmap数组成员中
void Dialog::INitPixmap()
{
for(int i=0;i<11;i++)
{
//arg(int a,int min-fieldwidth,base,QLatin1Char(char c))
QString fileName=QString(":/ling/feng/%1.png").arg(i+1,2,10,QLatin1Char('0'));
QPixmap map(fileName);
pixmap[i]=map;
}
}
(3)实例化定时器事件,为后面的绘图事件做准备
void Dialog::timerEvent(QTimerEvent *event)
{
t++;
//防止t的数值超过图片的数量,不能达到理想效果
if(t>=11)
t=0;
repaint(); //重绘
}
(4)实例化绘图事件,利用定时器事件里面的变量来改变QPixmap展示的图片
void Dialog::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
QRect q(0,0,500,281);
painter.drawPixmap(q,pixmap[t],q);
}
运行效果
知识补充
arg()函数的用法:用%1—%99来填充字符串中的给定的参数(填充式,应按1—99从小到大的顺序来填充,且变量应为int型);
- 参数:
arg(int a,int fieldwidth,base,QLatin1Char(char c))
- 对应变量的具体意思:
- int a:指定的变量
- int fieldwidth:变量最小宽度
- base:变量的进制
- QLatin1Char(char c):当原始数字长度不足最小宽度时用于填充的字符