QMessageBox delete on close

4.5k views Asked by At

I have a question that has obvious answer for some of you, but I just can't figure it out.

QMessageBox http://qt-project.org/doc/qt-5/qmessagebox.html has 2 ways of being displayed, either you do exec() which stop the program execution until user close the message box, or show() which just display the box (probably in separate thread or in some way that allows program to continue while box is waiting for user).

How do I delete the box after I use show()?

This code immediately close it, message box appears for nanosecond and then it's gone:

QMessageBox *mb = new QMessageBox(parent);
mb->setWindowTitle(title);
mb->setText(text);
mb->show();
delete mb; // obvious, we delete the mb while it was still waiting for user, no wonder it's gone

this code does the same

QMessageBox mb(parent);
mb.setWindowTitle(title);
mb.setText(text);
mb.show();
// obvious, as we exit the function mb which was allocated on stack gets deleted

also this code does the same

QMessageBox *mb = new QMessageBox(parent);
mb->setWindowTitle(title);
mb->setText(text);
mb->show();
mb->deleteLater(); // surprisingly this doesn't help either

So how can I use show() properly, without having to handle its deletion in some complex way? Is there something like deleteOnClose() function that would just tell it to delete itself once user close it?

3

There are 3 answers

0
Meefte On BEST ANSWER

You can use Qt::WA_DeleteOnClose flag

QMessageBox *mb = new QMessageBox(parent);
mb->setAttribute(Qt::WA_DeleteOnClose, true);
mb->setWindowTitle(title);
mb->setText(text);
mb->show();
0
Zaiborg On

you can use the following:

QMessageBox* msg = new QMessageBox;
msg->setWindowTitle(title);
msg->setText(text);
connect(msg, SIGNAL(done(int)), msg, SLOT(deleteLater()));
msg->show();

that way it will destroy when it gets closed and when the event loop has nothing else to do.

0
vahancho On

Yes, there is a 'delete on close' concept in Qt, so you can configure your message box to follow such behavior:

mb->setAttribute(Qt::WA_DeleteOnClose);