简体   繁体   English

QMessageBox在关闭时删除

[英]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). QMessageBox http://qt-project.org/doc/qt-5/qmessagebox.html有两种显示方式,你可以exec()来停止程序执行,直到用户关闭消息框,或show()只显示该框(可能在单独的线程中或以某种方式允许程序在框等待用户时继续)。

How do I delete the box after I use show()? 使用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? 那么如何正确使用show(),而不必以某种复杂的方式处理它的删除? Is there something like deleteOnClose() function that would just tell it to delete itself once user close it? 是否有类似deleteOnClose()函数的东西只会告诉它一旦用户关闭它就会自行删除?

You can use Qt::WA_DeleteOnClose flag 您可以使用Qt::WA_DeleteOnClose标志

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. 这样它会在它关闭时以及当事件循环没有别的事情时会被破坏。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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