Problem with hidden QMainWindow: application crashes after displaying QMessageBox

// main.cpp #include <QApplication> #include "mainwindow.h" int main(int argc, char* argv[]) { QApplication app(argc, argv); MainWindow* window = new MainWindow(); window->show(); return app.exec(); } // mainwindow.cpp #include <QTimer> #include <QMessageBox> #include <iostream> #include "mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { this->setCentralWidget(new QWidget()); } void MainWindow::mousePressEvent(QMouseEvent* event) { this->hide(); QTimer* timer = new QTimer(); timer->setInterval(3*1000); timer->start(); connect(timer, SIGNAL(timeout()), this, SLOT(showMessageBox())); } void MainWindow::showMessageBox() { QMessageBox::information(this, "Hello,", "world!", QMessageBox::Ok); } MainWindow::~MainWindow() { std::cerr << "Destructor called" << std::endl; } 

I click on a window - it hides and a QMessageBox appears. I click "OK" - the application terminates, and the MainWindow destructor is not called. Why is the application ending? Maybe I missed something? Qt 4.7.0, Linux.

... oops! Looks like I found what I need.

 a.setQuitOnLastWindowClosed(false); 

When I need it, I terminate the application using a.exit (0). But I still do not understand what is wrong.

Yes! Looks like I understand what’s wrong. This is the method information.

QApplication::quitOnLastWindowClosed(bool) :

This property saves whether the application closes when the last window closes. The default value is true. If this property is true, applications exit when the last visible main window (that is, a window without a parent) with the Qt :: WA_QuitOnClose attribute is closed. By default, this attribute is set for all widgets except sub-windows. See Qt :: WindowType for a detailed list of Qt :: Window objects.

After QMainWindow is hidden, there are no visible windows. When the QMessageBox is closed, the application terminates .

+8
c ++ qt qt4 qmessagebox qmainwindow
source share
2 answers

The problem is this: when the dialog closes, the application considers that there are no more open windows ( setQuitOnLastWindowClosed refers to visible top-level windows), so it quits. Your window's destructor is not called because you never delete an object!

This should print a message:

 int main(int argc, char* argv[]) { QApplication app(argc, argv); MainWindow* window = new MainWindow(); window->show(); int ret = app.exec(); delete window; return ret; } 

Alternatively, you can install the application as a window parent

+3
source share

I'm not sure, but I think that when the QMessageBox closes, it tries to return focus to its parent (Your MainWindow), the witch is hidden. This operation fails and the system throws an exception.

+2
source share

All Articles