Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a QWidget remove itself from the GUI on destruction?

Tags:

qt

If I delete a QWidget using delete, does it unregister itself from the GUI or do I have to do this manually? Is there a logical reason for this behavior?

like image 203
Pieter Avatar asked May 17 '11 17:05

Pieter


2 Answers

When you call addWidget on a layout or stacked widget the ownership of the widget is transferred to the layout/stacked widget. All this means is that if the layout/stacked widget gets deleted then all the widgets that were added to it get deleted too.

It's perfectly okay to delete a widget once you are finished with it regardless of who owns it. The ownership is simply a convenient way of clearing up the memory of a hierarchy of objects. It in no way says that the object that owns it must delete it. If that were the case then once you added all your widgets you would only be able to get rid of them all or none at all!

If you didn't want your widget to be deleted when the layout/stacked widget gets deleted then you would call removeWidget. Note that it's not clear where the ownership of the widget really goes. A simple test app. I just wrote suggests that removeWidget did not even transfer ownership away from a QStackedWidget at all!

So, to answer your question, Qt will correctly remove the widget from the layout/stacked widget if you delete it. Furthermore this is the correct way to remove the widget if it no longer belongs in the layout/stacked widget.

like image 72
Troubadour Avatar answered Sep 18 '22 12:09

Troubadour


As already pointed out by @CatPlusPlus , Qt uses an ownership system. So whenver you add widgets to layouts or layouts to widgets and so forth the ownership of the addee is given to the adder/parent. This is usually documented in the method documentation. For example if you look at documentation for QWidget::addLayout(QLayout*), it says the Qwidget takes ownership of the QLayout. When you delete the parent it deletes all its children as well. Read this article for more info .

Object Trees and Ownership in Qt

This method is very useful, because in traditional C++ the developer has to keep track of every bit of memory allocated on the heap. This ownership system however requires that the developer onl keep track of the parents.

like image 44
Abhijith Avatar answered Sep 18 '22 12:09

Abhijith