C++ 隐藏窗口时退出

C++ 隐藏窗口时退出,c++,qt,C++,Qt,我有一个main窗口,它调用构造函数中的LoginWindow。LoginDialog有一个创建帐户的按钮,该帐户将创建QDialog 我想在新帐户的对话框显示时隐藏LoginDialog,但不知怎的它崩溃了 当我删除函数的第一行和最后一行时,它隐藏并显示了LoginDialog,这是绝对正确的。为什么它会在调用hide()和show()时崩溃 void LoginDialog::createAccount() { // (-> will cause crash later) hi

我有一个
main窗口
,它调用构造函数中的LoginWindow。
LoginDialog
有一个创建帐户的按钮,该帐户将创建
QDialog

我想在新帐户的对话框显示时隐藏
LoginDialog
,但不知怎的它崩溃了

当我删除函数的第一行和最后一行时,它隐藏并显示了
LoginDialog
,这是绝对正确的。为什么它会在调用
hide()
show()
时崩溃

void LoginDialog::createAccount()
{
    // (-> will cause crash later) hide(); //Hides LoginDialog
    QDialog dlg;
    dlg.setGeometry( this->x(), this->y(), this->width(), this->height() );

    QWidget* centralWidget = new QWidget( &dlg );
    QVBoxLayout* l = new QVBoxLayout( centralWidget );
    dlg.setLayout( l );

    QLineEdit *dlgUser = new QLineEdit( centralWidget );
    QLineEdit *dlgPass = new QLineEdit( centralWidget );
    dlgPass->setEchoMode( QLineEdit::Password );

    l->addWidget( new QLabel( tr("Username :"), centralWidget ) );
    l->addWidget( dlgUser );
    l->addWidget( new QLabel( tr("Password :"), centralWidget ) );
    l->addWidget( dlgPass );
    l->addWidget( new QDialogButtonBox( QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal, centralWidget ) );

    if( dlg.exec() != QDialog::Rejected )
    {
        ;
    }
    delete centralWidget;
    // (-> will cause crash later) show(); //Show LoginDialog again
}
没有错误,它只是意外地崩溃,有时会以代码(0)退出


当使用调试器进行分析并真正完成每个步骤时,它不会崩溃。将显示
LoginDialog
,它不会崩溃。

我不明白对话框中的
centralWidget
的目的是什么?我认为根本不需要它,您可以在对话框中直接组装小部件。我将以以下方式重写您的代码:

void LoginDialog::createAccount()
{
    QDialog dlg;
    dlg.setGeometry( this->x(), this->y(), this->width(), this->height() );

    QLineEdit *dlgUser = new QLineEdit( &dlg );
    QLineEdit *dlgPass = new QLineEdit( &dlg );
    dlgPass->setEchoMode( QLineEdit::Password );

    QVBoxLayout* l = new QVBoxLayout;
    l->addWidget( new QLabel( tr("Username :"), &dlg ) );
    l->addWidget( dlgUser );
    l->addWidget( new QLabel( tr("Password :"), &dlg ) );
    l->addWidget( dlgPass );
    l->addWidget( new QDialogButtonBox( QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal, &dlg ) );

    dlg.setLayout( l );

    if( dlg.exec() != QDialog::Rejected )
    {
        // Do something.
    }
}

@Davlog,啊,你在打开另一个创建帐户的模式子对话框时隐藏了父对话框?那么,如果您只调用
dlg.show()
,而不是调用
dlg.exec()
?嗯。。。我用dlg.show()替换了if语句,但它仍然崩溃。@Davlog,崩溃的回溯跟踪可用吗?QLabel和QDialogButtonBox不需要父级,因为它们被放置在一个布局中,将被重新分配them@vahancho我试图用调试器检查它崩溃的地方,但每次我用调试器检查它时,它都能工作。。。没有崩溃,没有错误:/