Creating and deleting a Qt widget object

I heard that widgets should be allocated on the heap (using a new one), and then there is no need to delete them (this is done automatically).

  • Can someone explain why?
  • What happens if the widget is not assigned this way, but on the stack?

I'm not sure if this matters, but all the widgets that I create have a parent.

It says:

If parent is 0, the new widget becomes a window. If the parent is another widget, this widget becomes the child window inside the parent. A new widget is deleted when its parent is removed.

+7
c ++ memory-management qt
source share
2 answers

There is no magic. Simply put, QObject automatically removes its children in its destructor. So, as long as your widget has a parent and that you are destroying that parent, you do not need to worry about children. So, if you were wondering what the QObject * parent parameter is, well, what is it for.

Also from the doc doc:

All child objects are deleted. If any of these objects is on the stack or globally, sooner or later your program will crash.

So, avoid giving parents objects that are stacked.

+20
source share

The docs on this are here . The reason they are most often allocated on the heap is to avoid problems caused by the order in which the members of the object tree are constructed. The stack is great if you follow the rules, but why bother when you have a reliable alternative?

The @Etienne link is here .

+3
source share

All Articles