qt使用widget崩溃

时间:2014-04-29 19:24:07

标签: c++ qt append qtextedit

我有一个班级:

class gameClientInteraction : public QMainWindow

,在.h:

private :
QTextEdit* console; 

我的构造函数是这样的:

gameClientInteraction::gameClientInteraction()
{ 
// Menus
QMenu *menuFichier = menuBar()->addMenu("&Jeu");
QAction *actionQuitter = new QAction("&Quitter", this);
menuFichier->addAction(actionQuitter);
connect(actionQuitter, SIGNAL(triggered()), qApp, SLOT(quit()));


// View
QGraphicsView *theGraphicsView = new QGraphicsView(this);
theGraphicsView->setFixedSize(605,605);

QTextEdit* console = new QTextEdit(this);
console->setGeometry(0,625,600,100);
console->setReadOnly(true);
console->append("Bienvenue !");

setCentralWidget(theGraphicsView);

//Scene
theGraphicsView->setScene(m.afficheMap());//afficheMap give me a QGraphicsScene*
}

我有这个功能,当我启动它时会崩溃我的程序(当我评论指令时没关系。)

   void gameClientInteraction::msgConsole(QString msg){
   console->append(msg);
}

那么为什么它会因此指令而崩溃?

1 个答案:

答案 0 :(得分:1)

通过声明具有相同名称的本地指针,您已在构造函数中隐藏了类成员变量console。换句话说,这个:

QTextEdit* console = new QTextEdit(this);

应该是这样的:

console = new QTextEdit(this);

作为替代方案,请考虑使用初始化列表:

gameClientInteraction::gameClientInteraction() : console(new QTextEdit(this))
{
    // constructor code goes here

    console->setGeometry(0,625,600,100);
    console->setReadOnly(true);
    console->append("Bienvenue !");
}