Does a QWidget remove itself from the GUI on destruction?

前端 未结 2 1944
忘了有多久
忘了有多久 2021-02-20 15:31

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 behavio

相关标签:
2条回答
  • 2021-02-20 15:50

    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.

    0 讨论(0)
  • 2021-02-20 16:04

    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.

    0 讨论(0)
提交回复
热议问题