I have a question with some of the code for a tutorial I'm following for Qt Creator. My first question is how is MyRect()
(in file "main.cpp" on line MyRect * rect = new MyRect();
) was created? I thought it was only a class and not a function. Could someone explain that?
I'm also having trouble understanding how (under "myrect.cpp") the keyPressEvent
function is called whenever I press an arrow key. How does the function know to respond without me calling it? If it has been called and I've just missed it, could someone specify where, thanks.
main.cpp:
#include <QApplication>
#include <QGraphicsScene>
#include "myrect.h"
#include <QGraphicsView>
using namespace std;
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);
// add the item to the scene
scene->addItem(rect);
//Make item focusable
rect->setFlag(QGraphicsItem::ItemIsFocusable);
rect->setFocus();
// add a view to visualize the scene
QGraphicsView * view = new QGraphicsView(scene);
view->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
view->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
view->show();
return a.exec();
}
myrect.cpp:
#include "MyRect.h"
#include <QGraphicsScene>
#include <QKeyEvent>
#include "bullet.h"
#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){
//creates a bullet
Bullet* bullet = new Bullet();
bullet->setPos(x(),y());
scene()->addItem(bullet);
}
}
myrect.h:
#ifndef MYRECT_H
#define MYRECT_H
#include <QGraphicsRectItem>
class MyRect: public QGraphicsRectItem{
public:
void keyPressEvent(QKeyEvent* event);
};
#endif // MYRECT_H
bullet.cpp:
#include "Bullet.h"
#include <QTimer>
Bullet::Bullet(){
//draw rect
setRect(0,0,10,50);
//connect
QTimer * timer = new QTimer();
connect(timer,SIGNAL(timeout()),this,SLOT(move()));
timer->start(50);
}
void Bullet::move(){
//move bullet up
setPos(x(),y()-10);
}
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