Creating and deallocating a Qt widget object

前端 未结 2 884
[愿得一人]
[愿得一人] 2020-12-03 09:07

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 explai
相关标签:
2条回答
  • 2020-12-03 09:17

    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.

    0 讨论(0)
  • 2020-12-03 09:25

    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.

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