Killing a Window in its constructor
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?
Re: Killing a Window in its constructor
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.
Re: Killing a Window in its constructor
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.
Re: Killing a Window in its constructor
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:
Code:
MyWidget w;
if(w.isValid()) w.show();
Re: Killing a Window in its constructor
Quote:
Originally Posted by
wysota
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:
Code:
MyWidget w;
if(w.isValid()) w.show();
Thanks! You always have the clean solution that makes me smack my forehead :)
Re: Killing a Window in its constructor
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
Re: Killing a Window in its constructor
Quote:
Originally Posted by
Eldritch
You could also:
- call deleteLater()
This is risky, the object may be allocated on stack. You'd have to forbid stack allocation.