移动矩形,在第一个例子基础上,建立一个矩形类,实现keyPressEvent方法。空格键的地方写了一个子弹(bullet), 里面有一个定时器,不停地向上移动, 利用到了qt 的一个很重要的特性,signal and slot.
#-------------------------------------------------
#
# Project created by QtCreator 2017-01-17T19:56:59
#
#-------------------------------------------------
QT += core gui
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = Totorial2
TEMPLATE = app
SOURCES += main.cpp \
myrect.cpp \
bullet.cpp
HEADERS += \
myrect.h \
bullet.h
#ifndef BULLET_H
#define BULLET_H
#include <QGraphicsRectItem>
#include <QObject>
class Bullet : public QObject, public QGraphicsRectItem {
Q_OBJECT
public:
Bullet();
public slots:
void move();
};
#endif // BULLET_H
#include <QTimer>
#include "bullet.h"
Bullet::Bullet()
{
setRect(0, 0, 10, 50);
QTimer *timer = new QTimer();
connect(timer, SIGNAL(timeout()), this, SLOT(move()));
timer->start(50);
}
void Bullet::move() {
setPos(x(), y()-10);
}
#ifndef MYRECT_H
#define MYRECT_H
#include <QGraphicsRectItem>
class MyRect : public QGraphicsRectItem {
public:
void keyPressEvent(QKeyEvent *event);
};
#endif // MYRECT_H
#include "myrect.h"
#include "QGraphicsRectItem"
#include <QKeyEvent>
#include "bullet.h"
#include <QGraphicsScene>
#include <QDebug>
void MyRect::keyPressEvent(QKeyEvent *event)
{
if (event->key() == Qt::Key_Left) {
setPos(x()-10, y());
} else if (event->key() == Qt::Key_Right) {
setPos(x()+10, y());
} else if (event->key() == Qt::Key_Up) {
setPos(x(), y()-10);
} else if (event->key() == Qt::Key_Down) {
setPos(x(), y()+10);
} else if (event->key() == Qt::Key_Space) {
qDebug() << "Bullet shooted";
}
}
#include <QApplication>
#include <QGraphicsScene>
#include "myrect.h"
#include <QGraphicsView>
/*
* Tutorial Topics:
* -event (keyPressEvent() and QkeyEvent)
* -event propogation system
* -QDebug
*/
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
// create a scene
QGraphicsScene *scene = new QGraphicsScene();
// create an item to put into the scene
MyRect *rect = new MyRect();
rect->setRect(0, 0, 100, 100);
// make rect focusable
rect->setFlag(QGraphicsItem::ItemIsFocusable);
rect->setFocus();
// add the item to the scene
scene->addItem(rect);
// add a view to visualize the scene
QGraphicsView *view = new QGraphicsView(scene);
view->show();
return a.exec();
}