添加QGraphicsProxyWidget时崩溃

问题描述:

我想在我的场景中有QPushButton,但是当我试图将QGraphicsProxyWidget添加到场景时,它崩溃了。添加QGraphicsProxyWidget时崩溃

所以这里的.cpp

#include "upgradecromagnon.h" 
#include "game.h" 
#include <QGraphicsProxyWidget> 
#include <qDebug> 

extern Game *game; 
UpgradeCromagnon::UpgradeCromagnon() 
{ 

    this->setRect(-50,0,150,50); 
    buttonAmelio = new QPushButton("salut"); 
    teste(); 
} 

void UpgradeCromagnon::teste() 
{ 
    QGraphicsProxyWidget *proxy = new QGraphicsProxyWidget(); 
    proxy->setWidget(buttonAmelio); 
    scene()->addItem(proxy); 
} 

及其.h

#ifndef UPGRADECROMAGNON_H 
#define UPGRADECROMAGNON_H 
#include <QPainter> 
#include <QGraphicsRectItem> 
#include <QPushButton> 
class UpgradeCromagnon: public QGraphicsRectItem 
{ 
public: 
    UpgradeCromagnon(); 
    void teste(); 
private: 
    QPushButton *buttonAmelio; 
}; 

#endif // UPGRADECROMAGNON_H 
+0

在'UpgradeCromagnon :: teste'中调用'scene()'是否肯定返回非null? –

+0

那么我可以有其他类之前,所以现场已设置在这一点:) – noonana

UpgradeCromagnon构造函数调用UpgradeCromagnon::teste,反过来,调用QGraphicsItem::scene。此时QGraphicsItem::scene必须返回一个空指针,因为在它的构造函数完成之前(不是根据您提供的代码),UpgradeCromagnon实例可能已经被添加到QGraphicsScene中。