简体   繁体   中英

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?

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

是的,Qt中有一个“关闭时删除”概念,因此您可以配置消息框以遵循此类行为:

mb->setAttribute(Qt::WA_DeleteOnClose);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM