Does a QWidget remove itself from the GUI on destruction?

前端 未结 2 1990
忘了有多久
忘了有多久 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 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.

提交回复
热议问题