创建和取消分配Qt窗口小部件对象 [英] Creating and deallocating a Qt widget object

查看:122
本文介绍了创建和取消分配Qt窗口小部件对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我听说小部件应该在堆上分配(使用新的),然后没有必要删除它们(自动完成)。



  1. 如果一个窗口小部件没有按照这种方式分配, >

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



    说:


    如果parent为0,新的窗口小部件成为
    a窗口。如果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窗口小部件对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆