听说widgets应该分配在堆上(用new),然后就不用删除了(自动完成)。
- 谁能解释为什么?
- 如果小部件不是以这种方式分配,而是分配在堆栈上,会发生什么情况?
我不确定这是否重要,但我创建的所有小部件都有父级。
This说:
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.
最佳答案
没有魔法。简而言之,QObject 在其析构函数中自动删除其子对象。因此,只要您的小部件有父级并且您销毁了该父级,您就不必担心子级。因此,如果您想知道 QObject * parent
参数是什么,那么,这就是它的作用。
此外,来自文档:
All child objects are deleted. If any of these objects are on the stack or global, sooner or later your program will crash.
因此,避免为堆栈分配的对象提供父对象。
关于c++ - 创建和释放 Qt 小部件对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4267854/