Reputation: 109
I'm a bit new to c++ and am having a bit of trouble establishing why I am getting a segfault in the following code;
gamescene.h
#ifndef GAMESCENE_H
#define GAMESCENE_H
#include <QGraphicsScene>
class GameScene : public QGraphicsScene
{
Q_OBJECT
public:
explicit GameScene(QObject *parent = 0);
virtual void keyPressEvent(QKeyEvent* );
QGraphicsTextItem* p;
~GameScene();
signals:
public slots:
};
#endif // GAMESCENE_H
gamescene.cpp
#include "gamescene.h"
#include "QKeyEvent"
#include "QGraphicsTextItem"
#include "QGraphicsRectItem"
#include "QDebug"
#include "QGraphicsScene"
#include "QScopedPointer"
GameScene::GameScene(QObject *parent) :
QGraphicsScene(parent)
{
QGraphicsTextItem* p = new QGraphicsTextItem(QString("HEEEEE"));
p->setFlags(p->ItemIsMovable);
p->moveBy(qreal(500),qreal(500));
addItem(p);
}
void GameScene::keyPressEvent(QKeyEvent *event)
{
qDebug() << (p != NULL);
switch(event->key())
case ( Qt::Key_W ):
{
qreal x, y;
x = qreal(5);
y = qreal(5);
p->moveBy(x,y);
qDebug() << "move up";
}
}
GameScene::~GameScene() {
}
Its happening when my gamescene object's keyPressEvent method is called and it attempts to access anything to do with the QGraphicsTextItem pointer, p.
I'm sure its obvious, but any help would be greatly appreciated.
Upvotes: 0
Views: 441
Reputation: 3119
OK, I know nothing about the library you are using but I suspect the error is here
GameScene::GameScene(QObject *parent) :
QGraphicsScene(parent)
{
QGraphicsTextItem* p = new QGraphicsTextItem(QString("HEEEEE"));
p->setFlags(p->ItemIsMovable);
p->moveBy(qreal(500),qreal(500));
addItem(p);
}
should be
GameScene::GameScene(QObject *parent) :
QGraphicsScene(parent)
{
p = new QGraphicsTextItem(QString("HEEEEE"));
p->setFlags(p->ItemIsMovable);
p->moveBy(qreal(500),qreal(500));
addItem(p);
}
Your keyPressEvent
method tries to use a member variable called p, and it looks like you are trying to set that up in the constructor, but you aren't. All you have in your constructor is local variable also called p.
Upvotes: 1