Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating and deallocating a Qt widget object

I heard that the widgets should be allocated on the heap (using new), and then there are no needs to delete them (it is done automatically).

  1. Can someone explain why?
  2. What happens if a widget is not allocated that way, but on a stack?

I am not sure if it matters, but all widgets I am creating have a parent.

This says :

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

like image 502
BЈовић Avatar asked Nov 24 '10 14:11

BЈовић


2 Answers

There's no magic involved. Simply put, a QObject automatically deletes its children in its destructor. So, as long as your widget has a parent and that you destroy that parent, you don't have to worry about the children. So if you wondered what was that QObject * parent parameter, well, that's what it's there for.

Also, from the doc:

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

So, avoid giving parents to objects that are stack-allocated.

like image 81
Etienne de Martel Avatar answered Nov 13 '22 19:11

Etienne de Martel


The docs on this are here. The reason they are most often allocated on the heap is to avoid problems caused by construction order of the members of the object tree. The stack is fine so long as you follow the rules, but why bother when you have a reliable alternative?

The reference @Etienne cited is here.

like image 25
Steve Townsend Avatar answered Nov 13 '22 19:11

Steve Townsend