Qt QGraphicsScene addItem () ошибка сегментации - PullRequest
0 голосов
/ 14 марта 2020

В 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);

}

У меня ошибка сегментации (имя сигнала: SIGSEGV), когда я пытаюсь добавить к объекту сцены NormalBullet * bullet в NormalBullet :: shoot. Я создаю переменную 'test', чтобы увидеть в отладчике, что scene () возвращает и выдает ее 0x0 Когда я пытаюсь получить доступ к сцене по game-> scene (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, кроме класса Game.

...