Advertisement

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 eventIDs[] = {1, 2};
int currentIndex;
void initPixmap();
private:
QArray pixmap;
QString ui;
};
#ifndef DIALOG_H
#endif

dilog.cpp

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

对话框类构造函数定义
{
定义父窗口为QWidget类型的实例
创建并返回一个与UI组件绑定的对话框实例
}
{
通过绑定方法为UI组件配置界面
设置对话框窗口尺寸为宽1024高1024像素
调用定时器开始方法设置时间间隔为一百毫秒
初始化当前索引值为零
执行图像初始化过程
}

~Dialog对象析构函数实现如下:
{
delete ui;
}
当paintEvent事件发生时:
{
QPainter painter(this);
QRect q(80, 91);
QRect q2(2_80, 182);
painter.drawPixmap(q2, pixmap[curIndex], q);
}
当timerEvent事件发生时:
{
curIndex++;
if (curIndex >= 64)
curIndex = 0;
repaint();
}
初始化图片数组函数如下:
{
for (int i = 0; i < 64; ++i) //从第一张开始更换图片直到第64张
{
QString fileName = "res/1_%1.png".arg(i + 1); //生成文件名模板
fileName = ":/new/prefix1/" + fileName; //构建完整的文件路径
pixmap[curIndex] = QImage(fileName).scaledToHeight(91);
curIndex++;
}
}

复制资源路径的方法
复制资源路径方法

QPixmap map(fileName);
pixmap[i]=map;
}
}

main.cpp

#include “dialog.h”

#include

int main() {
QApplication instance;
Window* window = nullptr;
window = new window;
window->show();
return instance->exec();
}

效果图:

最后效果

全部评论 (0)

还没有任何评论哟~