PDA

View Full Version : Simple RAII question with Qt



maverick_pol
12th November 2008, 14:14
Hi,

In the main.cpp I create the main class object. In one of the main class member methods I create a pointer to a data widget, like:


void MainClass::showHelpWidget()
{
HelpWidtet* widget = new HelpWidget(this);
widget->show();
}

The widget will be deleted when returning from the method and will it be removed from parent's child list?


The helpWidget contains 3 pointer members which are create in the constructor and deleted in the destructor. Will he destructor be called every time I close the app, or should I set the flag "delete on close" for the help widget?

Trivial questions, but still looking for a short explanations.


Thank you.

spirit
12th November 2008, 14:22
if you set parent (as I see you set it :) ) then this widget will be deleted when parent will be deleted.

maverick_pol
12th November 2008, 14:30
That is clear. Ok, I misunderstood one thing:

Qt::WA_DeleteOnClose

Makes Qt delete this widget when the widget has accepted the close event (see QWidget::closeEvent()).

Closing a widget is not equal to destroying it, but you can force Qt to destroy a widget on close.

Let's say I set the flag on my widget. So when is it will be closed it will be deleted and the parent will not to try to delete it again ???

spirit
12th November 2008, 14:33
when you use this flag then signal QObject::destroyed will be sent immediately before an object will be deleted. so, when you use this flag then by calling close() method, the widget will be deleted after closing and you must to allocate this widget again if you want to display it, but if you don't use this flag then the widget will be deleted when the parent widget will be deleted (of course if you set parent for this widget) :)

pastor
12th November 2008, 14:39
Yes, if you will have code like this:


void MainClass::showHelpWidget()
{
HelpWidtet* widget = new HelpWidget(this);
widget->setAttribute(Qt::WA_DeleteOnClose);
widget->show();
}

after closing HelpWidtet it will be destroyed and parent widget (MainClass) will not try to delete it again.