[Interest] Create the main widget on heap in main()

Konrad Rosenbaum konrad at silmor.de
Fri Jan 10 14:33:15 CET 2014


Hi,

On Friday 10 January 2014, 程梁 wrote:
> Following is my example code:
> 
> int main(int argc, char *argv[])
> {
>     QApplication app(argc, argv);
>     QLabel *label = new QLabel;
>     label->show();
>     return app.exec();
> }
> 
> label should live longer than app so there might be unsafe because any
> QPaintDevice must have a QApplication. I'm not sure am I right? That's
> all main widgets should create on stack in main() in order to avoid such
> things? Or there is no such requirement?

In this particular case it should not present a problem because of the 
mechanism how app.exec() returns: when the last visible widget is closed the 
main event loop (i.e. app.exec()) exits and main ends (also killing the app 
object). Meaning: all widgets are already invisible. Otherwise, if it is 
killed with qApp->close(), the last action that QApplication takes is to 
unmap (close) all windows.

Of course the code would be cleaner if you told the QLabel to kill itself on 
closure:

label->setAttribute(Qt::WA_DeleteOnClose);



	Konrad
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.qt-project.org/pipermail/interest/attachments/20140110/22fb3568/attachment.html>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 588 bytes
Desc: This is a digitally signed message part.
URL: <http://lists.qt-project.org/pipermail/interest/attachments/20140110/22fb3568/attachment.sig>


More information about the Interest mailing list