@TOP
熟悉QT开发环境、搭建项目框架、建立图层结构、完善背景元素。
熟悉QT开发环境
1. 创建一个新项目
新建一个项目;
选择基于桌面的QT应用;
命名项目与选择项目路径;
路径选择是切记不能含有中文字符,否则不能构建(红色条);
选择构建编译系统;
选择类的基本信息;Base class 为 QWidget,不生成ui文件;
不提供翻译;
根据操作系统选择构建套件;
完成项目创建。
2. 加载文件与资源
拷贝项目资料到刚才创建的项目中;
将code中的代码文件,以及main.cpp,mainwidget.cpp,mainwidget.h文件放入新建文件夹src中;
选择 项目->Add Existing Directory 添加 src 文件夹中的所有代码文件;
添加QT资源文件,文件名写pvz;
选择pvz.qrc -> Add Existing Directory 添加audio,image两个文件夹,弹窗选择 Yes to all;
打开 项目.pro 文件,删除过期信息;
3. 项目完成,运行图示。
加入背景元素
1. mainwidget.cpp 文件
#include "mainwidget.h"
#include "ImageManager.h"
#include <QGraphicsView>
#include <QGraphicsItem>
MainWidget::MainWidget(QWidget *parent)
: QWidget(parent)
{
//创建View对象,传入this指针
QGraphicsView *gameView = new QGraphicsView(this);
//设置游戏界面尺寸
gameView->setGeometry(0,0,800,600);
//创建场景对象,设置游戏界面场景
QGraphicsScene *gameScene = new QGraphicsScene;
gameView->setScene(gameScene);
//创建图片元素对象,设置背景图片,添加背景元素到游戏场景
QGraphicsPixmapItem *backgroundItem = new \
QGraphicsPixmapItem(gImageCache->load("interface/background1.jpg"));
gameScene->addItem(backgroundItem);
}
MainWidget::~MainWidget()
{
}
2. main.cpp 文件
#include "mainwidget.h"
#include <QApplication>
#include "ImageManager.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
//初始化图片管理器
InitImageManager();
MainWidget w;
w.show();
return a.exec();
}
3. 运行图示。
类的封装
添加新的C++ class 文件;
修改类名,基类,和相关信息;
GameView 和 GameScene 两个类;
其中 gameview.h 和 gameview.cpp ,为GameView类的构造函数添加参数;
在 mainwidget.h 文件中包含类的头文件,声明类并创建对象;
在 GameView 类的构造函数中实现界面操作,在 GameScene 类的构造函数中实现场景元素操作;
#include "gameview.h"
GameView::GameView(QWidget *parent)
: QGraphicsView(parent)
{
//设置游戏界面尺寸
setGeometry(0,0,800,600);
}
#include "gamescene.h"
#include <QGraphicsItem>
#include "ImageManager.h"
GameScene::GameScene()
{
//创建图片元素对象,设置背景图片,添加背景元素到游戏场景
QGraphicsPixmapItem *backgroundItem = new \
QGraphicsPixmapItem(gImageCache->load("interface/background1.jpg"));
addItem(backgroundItem);
}
#include "mainwidget.h"
MainWidget::MainWidget(QWidget *parent)
: QWidget(parent),
gameView(new GameView(this)),
gameScene(new GameScene)
{
//设置游戏界面场景
gameView->setScene(gameScene);
}
MainWidget::~MainWidget()
{
}