PDA

View Full Version : Killing a Window in its constructor



hardgeus
14th December 2006, 03:18
How do I kill a Window in its constructor (or some other startup event) based upon some failure?

I have tried directly calling close() in the constructor, but this isn't working. Is there some sort of signal that is emitted after the constructor, but on the initial creation of the window, from which I can successfully call the close method?

aamer4yu
14th December 2006, 04:32
You can use some sort of splash screen / window to do the startup events. If events are successful, display the main window, else dont create the main window at all.

jpn
14th December 2006, 08:39
Calling close() in a constructor doesn't have much effect because most likely you are calling show() later anyway. And the event loop isn't even running by that time. One solution would be to use QTimer::singleShot() with a 0ms delay to close the window or maybe even QObject::deleteLater() to schedule a delete when the control reaches the event loop. However, I think you'll just end up having a flickering window. The window will be closed as soon as it appears but most likely it is still possible notice.

Maybe a sufficient solution would be to move part of the code in the constructor to a separate "bool Window::initialize(..)" function or similar. Then you can simply avoid calling show() at all if the initialization fails.

wysota
14th December 2006, 10:22
Or you can set a flag in the constructor (instead of having an additional method for initialisation) whether the widget initialised properly and then when showing the window, check that condition first:

MyWidget w;
if(w.isValid()) w.show();

hardgeus
14th December 2006, 13:32
Or you can set a flag in the constructor (instead of having an additional method for initialisation) whether the widget initialised properly and then when showing the window, check that condition first:

MyWidget w;
if(w.isValid()) w.show();

Thanks! You always have the clean solution that makes me smack my forehead :)

Eldritch
15th December 2006, 17:35
You could also:

call deleteLater()
post a custom event to your application and tell it to delete the object
put window creation in a try/catch and throw an exception

wysota
15th December 2006, 18:31
You could also:

call deleteLater()
This is risky, the object may be allocated on stack. You'd have to forbid stack allocation.