Qt4应用程序崩溃,单击连接按钮时出现分段错误

Qt4 application crash, segmentaton fault when click connected button

我用 QGraphicsView 创建了一个简单的应用程序,但我遇到了连接按钮的问题。 有一个简单的 window 与 QGraphicsScene 和一个 QPushButton 以及一个应该向我的场景添加一个矩形的函数。编译没问题,它可以工作,在我单击此按钮后应用程序崩溃。

.h 文件:

class Canvas : public QWidget{
    Q_OBJECT
public:
    Canvas(QWidget *parent = 0);

private slots:
    void addPoint();

private:
    QGraphicsScene *scene;
    QPushButton *btn;

};

.cpp 文件:

Canvas::Canvas(QWidget *parent)
    : QWidget(parent)
{
    QVBoxLayout *vbox = new QVBoxLayout(this);
    vbox->setSpacing(1);
    QPushButton *btn = new QPushButton("test", this);
    QGraphicsView *view = new QGraphicsView(this);
    QGraphicsScene *scene = new QGraphicsScene(this);
    view->setScene(scene);
    vbox->addWidget(view);
    vbox->addWidget(btn);
    setLayout(vbox);
    connect(btn, SIGNAL(clicked()), this, SLOT(addPoint()));
}

void Canvas::addPoint()
{
    scene->addRect(100,0,80,100);
}

调试者还说:

The inferior stopped because it received a signal from the Operating System.

Signal name : SIGSEGV
Signal meaning : Segmentation fault

并指向这一行:

{ return addRect(QRectF(x, y, w, h), pen, brush); }

我做错了什么?提前致谢。

构造函数中的以下语句是局部变量定义和初始化:

QGraphicsScene *scene = new QGraphicsScene(this);  

实际的 scene 成员变量从未被初始化,任何尝试使用 this->scene 的东西都会使应用程序崩溃。

因为要初始化已有的scene变量,需要省略变量前面的类型:

scene = new QGraphicsScene(this);