创建和释放 Qt 小部件对象

时间:2023-01-22
本文介绍了创建和释放 Qt 小部件对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

听说widget应该在堆上分配(使用new),然后就不需要删除了(自动完成).

  1. 有人能解释一下原因吗?
  2. 如果小部件不是以这种方式分配而是在堆栈中,会发生什么情况?

我不确定这是否重要,但我创建的所有小部件都有一个父级.

这个说:

<块引用>

如果 parent 为 0,则新小部件变为一个窗口.如果 parent 是另一个小部件,这个小部件成为一个子窗口内父.新的小部件是删除其父项时删除.

解决方案

没有魔法.简单地说,一个 QObject 会在它的析构函数中自动删除它的孩子.所以,只要你的小部件有一个父级并且你销毁了那个父级,你就不必担心子级.因此,如果您想知道 QObject * parent 参数是什么,那么,这就是它的用途.

此外,来自文档:

<块引用><块引用>

删除所有子对象.如果这些对象中的任何一个在堆栈上或全局上,您的程序迟早会崩溃.

因此,避免将父级分配给堆栈分配的对象.

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.

解决方案

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.

这篇关于创建和释放 Qt 小部件对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:使用 pkg-config 输出将库链接到 QT 项目 下一篇:Qt 5.2 Model-View-Pattern:如何通知模型对象底层数据结

相关文章

最新文章