简体   繁体   English

Qt中的close事件导致程序崩溃

[英]Program crashes on close Event in Qt

I was trying to set the close event to my code but when I set this code my program crashes. 我试图将close事件设置为我的代码,但是当我设置此代码时,我的程序崩溃了。

mainwindow.cpp 主窗口

 void MainWindow::closeEvent(QCloseEvent *event)
    {
        event->ignore();

        if (QMessageBox::Yes == QMessageBox::question(this, "Close Confirmation?",
                                                      "Are you sure you want to exit?",
                                                      QMessageBox::Yes|QMessageBox::No))
        {
            if(QMessageBox::Yes)
            {
                if(aboutDialog)
                {
                    aboutDialog->close();
                    event->accept();
                }
                event->accept();
            }
        }
    }

void MainWindow::showAboutDialog()
{
    aboutDialog = new QDialog;
    Ui::About aboutUi;
    aboutUi.setupUi(aboutDialog);
    connect(aboutUi.Close, SIGNAL(pressed()), aboutDialog, SLOT(close()));
    aboutDialog->show();
}

mainwindow.h 主窗口

private:
QDialog *aboutDialog;

I am confused why this happens. 我很困惑为什么会这样。 Help me out to solve this! 帮我解决这个问题!

Don't ignore the event if you're planning to close, try this: 如果您打算关闭活动,请不要忽略该事件,请尝试以下操作:

void MainWindow::closeEvent(QCloseEvent *event)
{
    if (QMessageBox::Yes != QMessageBox::question(this, "Close Confirmation?",
        "Are you sure you want to exit?", QMessageBox::Yes | QMessageBox::No))
    {
        event->ignore();
    }
}

And when creating the aboutDialog -box, you should pass the mainWindow as parent as Nejat's comment suggests: aboutDialog = new QDialog(mainWindow); 并且在创建aboutDialog -box时,应按照Nejat的注释建议将mainWindow作为父级传递: aboutDialog = new QDialog(mainWindow); . This will make sure that the aboutDialog will get closed if the main window closes. 这将确保如果关闭主窗口,则aboutDialog将被关闭。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM