尝试访问QGraphicsTextItem的成员时出现段错误

时间:2012-07-29 04:03:29

标签: c++ qt

我对c ++有点新,并且在以下代码中确定我为什么会遇到段错误时遇到了一些麻烦;

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() {


}

当我的gamecene对象的keyPressEvent方法被调用并且它试图访问与QGraphicsTextItem指针有关的任何内容时发生它,p。

我确信它显而易见,但任何帮助都会非常感激。

1 个答案:

答案 0 :(得分:1)

好的,我对您正在使用的库一无所知,但我怀疑错误在这里

GameScene::GameScene(QObject *parent) :
    QGraphicsScene(parent)
{
    QGraphicsTextItem* p = new QGraphicsTextItem(QString("HEEEEE"));
    p->setFlags(p->ItemIsMovable);
    p->moveBy(qreal(500),qreal(500));
    addItem(p);
}

应该是

GameScene::GameScene(QObject *parent) :
    QGraphicsScene(parent)
{
    p = new QGraphicsTextItem(QString("HEEEEE"));
    p->setFlags(p->ItemIsMovable);
    p->moveBy(qreal(500),qreal(500));
    addItem(p);
}

您的keyPressEvent方法尝试使用名为p的成员变量,看起来您正试图在构造函数中设置它,但事实并非如此。构造函数中的所有内容都是局部变量,也称为p。