简体   繁体   中英

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.

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); . This will make sure that the aboutDialog will get closed if the main window closes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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