qt 主窗口关闭时关闭子窗口

1、this指定主窗口为父类

void MainWindow::on_pushButton_clicked()
{
    Dialog *aa = new Dialog(this);
    aa->show();
}

2、重写主窗口closeEvent事件
mainwindow.h

QVector<Dialog*> m_test;

mainwindow.cpp

QVector<Dialog*> m_test;

void MainWindow::closeEvent(QCloseEvent *event)
{
    qDebug() << "close";
    foreach(Dialog *cc, m_test)
    {
        if(cc != nullptr)
        {
            delete cc;
            cc = nullptr;
        }
    }
}

void MainWindow::on_pushButton_clicked()
{
    Dialog *aa = new Dialog();
    m_test.append(aa);
    aa->show();
}

当子窗口关闭,同时delete子窗口对象,释放资源可用Qt::WA_DeleteOnClose 属性

void MainWindow::on_pushButton_clicked()
{
    Dialog *aa = new Dialog();
    aa->setAttribute(Qt::WA_DeleteOnClose, true);
    aa->show();
}

你可能感兴趣的:(QT)