Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QMessageBox delete on close

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?

like image 392
Petr Avatar asked Nov 14 '14 08:11

Petr


Video Answer


1 Answers

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();
like image 191
Meefte Avatar answered Sep 18 '22 05:09

Meefte