1. 效果
2. 代码
2.1 头文件
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
void initGif(QString prefix, int sumCnt);
void start();
void stop();
private:
Ui::Widget *ui;
int curIndex;
QString prefix;
int sumCnt;
int timeID;
// QObject interface
protected:
void timerEvent(QTimerEvent *event) override;
};
#endif // WIDGET_H
2.2 cpp文件
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
//资源文件:/img/p1 ~ :/img/p11
initGif(":/img/p", 11);
start();
}
Widget::~Widget()
{
delete ui;
}
void Widget::initGif(QString prefix, int sumCnt)
{
this->prefix = prefix;
this->sumCnt = sumCnt;
//QString(this->prefix+%1.png").arg("10");
QString fileName = this->prefix + "1" + ".png";
ui->label->setPixmap(QPixmap(fileName));
}
void Widget::start()
{
timeID = startTimer(100);
}
void Widget::stop()
{
killTimer(timeID);
QString fileName = this->prefix + "1" + ".png";
ui->label->setPixmap(QPixmap(fileName));
}
void Widget::timerEvent(QTimerEvent *event)
{
curIndex++;
if(curIndex > this->sumCnt)
curIndex = 1;
QString fileName = this->prefix + QString("%1.png").arg(QString::number(curIndex));
ui->label->setPixmap(QPixmap(fileName));
}
3. 参考
QT:利用计时器连续播放图片组成动图效果