使用继承的 QGraphicsScene 时的 SIGSEGV

SIGSEGV when using inherited QGraphicsScene

我试图从 QGraphicsScene 继承,但不知何故,当我尝试使用它时,我的程序崩溃了。我想我在某处遗漏了一件小事,但我无法弄清楚。这是我迄今为止尝试过的一个最小示例:

myscene.h

#ifndef MYSCENE_H
#define MYSCENE_H

#include <QGraphicsScene>

class MyScene : public QGraphicsScene
{
    Q_OBJECT

    QPen* pen_bg;

public:
    explicit MyScene(QObject* parent=nullptr);
    ~MyScene();
};

#endif // MYSCENE_H

myscene.cpp

#include "myscene.h"

MyScene::MyScene(QObject* parent):
    QGraphicsScene (parent)
{
    pen_bg = new QPen(Qt::blue);
}

MyScene::~MyScene()
{
    delete pen_bg;
}

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "myscene.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{    
    MyScene *m_scene = new MyScene(this);
    ui->graphicView->setScene(m_scene);
}

我一调用 setScene(m_scene) 函数,程序就崩溃并发出 SIGSEGV。

如果使用UI文件,使用前需要先调用setupUi(),否则UI元素不会被初始化。请参阅文档:http://doc.qt.io/qt-5/designer-using-a-ui-file.html

添加

 ui->setupUi(this); 

给你的 MainWindow 构造函数。