Qt——原地奔跑的小人

原理:

原理比较简单,是通过不断地更换导入的资源从而实现让小人原地奔跑并且换方向。

Qt——原地奔跑的小人

dialog.h

#ifndef DIALOG_H
#define DIALOG_H

#include

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 eventID1,eventID2;
int curIndex;
void InitPixmap();
private:
QPixmap pixmap[64];
Ui::Dialog *ui;
};
#endif // DIALOG_H

dilog.cpp

#include “dialog.h”
#include “ui_dialog.h”
#include
#include

Dialog::Dialog(QWidget *parent)
QDialog(parent)
, ui(new Ui::Dialog)
{
ui->setupUi(this);
resize(1024,1024);
eventID1=startTimer(100);
curIndex=0;
InitPixmap();
}

Dialog::~Dialog()
{
delete ui;
}
void Dialog::paintEvent(QPaintEvent event)
{
QPainter painter(this);
QRect q(0,0,80,91);
QRect q2(0,0,2
80,2*91);
painter.drawPixmap(q2,pixmap[curIndex],q);
}
void Dialog::timerEvent(QTimerEvent *event)
{
curIndex++;
if(curIndex>=64)
curIndex=0;
repaint();
}
void Dialog::InitPixmap()
{
for(int i=0;i<64;i++) //这里是一个循环 从第一张开始更换 一直到第64张
{
QString fileName=QString(":/new/prefix1/res/1_%1.png").arg(i+1,2,10,QLatin1Char(‘0’));//括号里第一位是要读的变量;第二位是变量的宽度; 用零来把空的参数补齐
// 这里是导入资源的路径(如果这里写不对可以直接去粘贴路径)``
Qt——原地奔跑的小人
Qt——原地奔跑的小人
QPixmap map(fileName);
pixmap[i]=map;
}
}

main.cpp

#include “dialog.h”

#include

int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Dialog w;
w.show();
return a.exec();
}

效果图:

Qt——原地奔跑的小人