I'm trying to inherit from a QGraphicsScene but somehow that crashes my program when I try to use it. I guess somewhere I'm missing a small thing, but I couldn't figure it out. Here is a minimal example of what I tried so far:
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);
}
As soon as I call the setScene(m_scene)
function, the program crashes with a SIGSEGV.
If you use the UI file, you need to first call setupUi()
before using it, otherwise the UI elements are not initialized. See docs: http://doc.qt.io/qt-5/designer-using-a-ui-file.html
Add
ui->setupUi(this);
to your MainWindow
constructor.