QMessageBox delete on close

I have a question that has an 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 to display, either you execute exec() , which stop the program until the user closes the message box, or show() , which they display only the field (possibly in a separate thread or in some way, which allows the program to continue working while the window is waiting for the user).

How to delete a field after using show ()?

This code will immediately close it, a message box for a nanosecond will appear, and then it disappeared:

 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 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 () correctly without having to handle its removal in some complicated way? Is there something like the deleteOnClose() function that just says that it will delete itself when the user closes it?

+5
source share
3 answers

You can use the flag Qt::WA_DeleteOnClose

 QMessageBox *mb = new QMessageBox(parent); mb->setAttribute(Qt::WA_DeleteOnClose, true); mb->setWindowTitle(title); mb->setText(text); mb->show(); 
+9
source

Yes, Qt has the concept of "delete in close", so you can customize the message box this way:

 mb->setAttribute(Qt::WA_DeleteOnClose); 
+2
source

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(); 

thus it will destroy when it is closed, and when the cycle of events will have nothing else.

0
source

Source: https://habr.com/ru/post/1206859/


All Articles