Why does the application exit when closing a QMessageBox with an invisible parent window?

32 views Asked by At

This is a boiled down simple example:

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H
 
#include <QMainWindow>
#include <QTimer>
 
class MainWindow : public QMainWindow
{
    Q_OBJECT
public:
    explicit MainWindow();
private slots:
    void OnTimer();
private:
    MainWindow(const MainWindow&);
    QTimer timer;
};
 
#endif // MAINWINDOW_H

mainwindow.cpp

#include "mainwindow.h"
#include <QMessageBox>
 
MainWindow::MainWindow() : QMainWindow(nullptr)
{
    connect(&timer, &QTimer::timeout, this, &MainWindow::OnTimer);
    timer.start(2000);
}

void MainWindow::OnTimer()
{
    QMessageBox::information(this, "", "2 seconds over");
}

main.cpp

#include <QString>
#include <QApplication>
#include "mainwindow.h"

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    MainWindow win;

    if (argc >= 2 && !QString(argv[1]).compare("show"))
    {
        win.show();
    }

    return app.exec();
}

mainwindow.pro

SOURCES += main.cpp mainwindow.cpp
HEADERS += mainwindow.h
QT += widgets
TARGET = mainwindow

When executing this example with command line parameter show the MainWindow is visible, and every 2 seconds, a message box pops up. That's what I would expect.

But when executing without a command line parameter, the MainWindow (intentionally) is not visible. In this case the message box only pops up once, followed by finishing the message loop and exiting.

What has to be changed to keep the application running, popping up message boxes every 2 seconds even if the MainWindow is not visible?

0

There are 0 answers