使用星空图作为窗口背景,点击键盘的WASD控制小飞机在上面移动。
选做内容:
如果小飞机触碰到窗口边缘,弹出QMessageBox,显示坠机信息。
dialog.h
#ifndef DIALOG_H
#define DIALOG_H
#include <QDialog>
#include <QPixmap> //图片类
#include <QPainter> //画家类
#include <QKeyEvent> //键盘事件
#include <QMessageBox>
namespace Ui {
class Dialog;
}
class Dialog : public QDialog
{
Q_OBJECT
public:
explicit Dialog(QWidget *parent = 0);
~Dialog();
protected:
void paintEvent(QPaintEvent * event);
void keyPressEvent(QKeyEvent * event);
//void moveEvent(QMoveEvent * event);
private:
Ui::Dialog *ui;
};
#endif // DIALOG_H
dialog.cpp
#include "dialog.h"
#include "ui_dialog.h"
Dialog::Dialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::Dialog)
{
ui->setupUi(this);
QSize size(ui->label->width(),ui->label->height());
QPixmap pic(":/new/prefix1/feiji.png");
pic = pic.scaled(size,Qt::KeepAspectRatioByExpanding);
ui->label->setPixmap(pic);
}
void Dialog::paintEvent(QPaintEvent * ){
QPainter painter(this);
QPixmap pic(":/new/prefix1/xingkong2.png");
painter.drawPixmap(0,0,width(),height(),pic);
}
void Dialog::keyPressEvent(QKeyEvent * event){
int y = ui->label->y();
int x = ui->label->x();
if(event->key() == Qt::Key_W){
ui->label->move(x,y-2);
}else if(event->key() == Qt::Key_S){
ui->label->move(x,y+2);
}else if(event->key() == Qt::Key_A){
int y = ui->label->y();
int x = ui->label->x();
ui->label->move(x-2,y);
}else if(event->key() == Qt::Key_D){
int y = ui->label->y();
int x = ui->label->x();
ui->label->move(x+2,y);
}
if((x<=0||x>=width()-30)||(y<=0||y>=height()-30))//坠毁边距
{
QMessageBox::critical(this,"失败","飞机已坠毁");
ui->label->move(160,120); //重生
}
}
Dialog::~Dialog()
{
delete ui;
}
ui界面