隐藏窗口时退出Qt

Qt exit when hiding window

本文关键字:Qt 退出 窗口 隐藏      更新时间:2023-10-16

我有一个MainWindow,它在构造函数中调用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.
    }
}