'Qt calling close() closes the MainWindow instead of the dialog window

In my sample application, the MainWindow closes instead of the dialog window. Why is that and how do I change it?

I've tried setQuitOnLastWindowClosed() but it didn't have any effect.

When clicking the x in the top right corner, the dialog window closes and the MainWindow remains open as expected. But that's of course not what I want.

MainWindow.h:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QDialog>
#include <QWidget>
#include <QPushButton>
#include <QHBoxLayout>

class MainWindow : public QMainWindow
{
    Q_OBJECT
private:
    void on_mainWindowBtn();
    void on_closeBtn();

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();
};
#endif // MAINWINDOW_H

MainWindow.cpp:

#include "mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    QWidget *mainWindowWidget = new QWidget(this);
    QHBoxLayout *mainWindowHBox = new QHBoxLayout();
    QPushButton *mainWindowPushButton = new QPushButton();
    mainWindowPushButton->setText("Open Dialog Window");
    mainWindowHBox->addWidget(mainWindowPushButton);
    mainWindowWidget->setLayout(mainWindowHBox);
    this->setCentralWidget(mainWindowWidget);

    connect(mainWindowPushButton, &QPushButton::released, this, &MainWindow::on_mainWindowBtn);
}

void MainWindow::on_mainWindowBtn()
{
    QDialog *newDialog = new QDialog();
    QHBoxLayout *newHBox = new QHBoxLayout();
    QPushButton *closeBtn = new QPushButton();
    closeBtn->setText("Close Dialog Window");
    newHBox->addWidget(closeBtn);
    newDialog->setLayout(newHBox);
    newDialog->setModal(true);

    connect(closeBtn, &QPushButton::released, this, &MainWindow::on_closeBtn);

    newDialog->exec();
}

void MainWindow::on_closeBtn()
{
    close();     // closes the MainWindow but not the dialog window
}

MainWindow::~MainWindow()
{
}

main.cpp:

#include "mainwindow.h"

#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    a.setQuitOnLastWindowClosed(false);
    MainWindow w;
    w.show();
    return a.exec();
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source