Qt QGraphicsScene addItem()分段错误

时间:2020-03-14 12:51:49

标签: c++ qt qgraphicsscene

在Game :: Game中,我调用Shoot()创建并添加到场景NormalBullet对象中。

#include "game.h"
#include <QDebug>
#include "dirtblock.h"
#include "normalbullet.h"
#include <QTimer>

Game::Game(QGraphicsView *parent)
    : QGraphicsView(parent)
{
    //set scene
    scene = new QGraphicsScene(this);
    scene->setSceneRect(0, 0, 500, 500);
    setFixedSize(500, 500);
    setScene(scene);
    setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);

    //set Player
    player = new PlayerTank();
    scene->addItem(player);

    //set dirtblock test
    DirtBlock * db = new DirtBlock();
    db ->setPos(100, 100);
    scene->addItem(db);

    NormalBullet *bl = new NormalBullet();
    bl->shot(QPointF(300,300), 90);

}

当我尝试将场景对象NormalBullet *:bullet添加到NormalBullet :: shoot中时,出现分段错误(信号名称:SIGSEGV)。我创建了“ test”变量,以在调试器上查看scene()返回的内容,并得出其0x0。当我尝试通过游戏->场景(test2)访问场景时,我也遇到了细分错误。为什么场景无法返回正确的指针?

#include "normalbullet.h"
#include "game.h"
#include "QTimer"
#include "dirtblock.h"
#include <QGraphicsScene>

extern Game * game;

NormalBullet::NormalBullet(QGraphicsPixmapItem *parent)
{
    setPixmap(QPixmap(":/images/NormalBullet.png"));
    damage = 10;
    speed = 10;

}

void NormalBullet::shot(QPointF coord, qreal angle)
{
    //create new bullet, setPos, add to scene and connect to timer
    NormalBullet * bullet = new NormalBullet();
    bullet->setPos(coord);
    bullet->setRotation(angle);
    //scene()->addItem(bullet);
    auto test = scene(); //return 0x0
//auto test2 = game->scene; //<= segmentation fault
    QTimer *tim = new QTimer();
    connect(tim, &QTimer::timeout, bullet, &NormalBullet::move);
    tim->start(200);

    scene()->addItem(bullet);
}
#ifndef GAME_H
#define GAME_H

#include <QWidget>
#include <QGraphicsView>
#include <QGraphicsScene>
#include "playertank.h"
#include<QObject>

class Game : public QGraphicsView
{
    Q_OBJECT
public:
    Game(QGraphicsView *parent = nullptr);
    void keyPressEvent(QKeyEvent *event) override;

    QGraphicsScene *scene;
    PlayerTank *player;
private:

};
#endif // GAME_H

由于某些原因,除了游戏类之外,我无法访问NormalBullet和otcher类中的场景指针。

0 个答案:

没有答案
相关问题