目录
前言
对象树是 Qt 的核心特色之一。在编写界面代码时,我们无需关心各个控件的释放,当然前提是你指定了控件的父对象。学习 Qt 时第一次接触了父对象这个词,刚开始还以为和父类和子类有关,其实并没有关系,父对象不一定就是父类的对象,父对象可以是任何一个 QObject 对象。
一 QObject 对象树
下面内容参考自官方文档
QObjects organize themselves in object trees. When you create a QObject with another object as parent, it’s added to the parent’s children() list, and is deleted when the parent is. It turns out that this approach fits the needs of GUI objects very well. For example, a QShortcut (keyboard shortcut) is a child of the relevant window, so when the user closes that window, the shortcut is deleted too.
QObject 以对象树的形式组织自己。当你创建一个以另一个对象为父对象的 QObject 对象时,它会被添加到父对象的 children() 列表中,并在父对象析构时析构。事实证明,这种方法非常适合图形用户界面对象。例如,QShortcut(键盘快捷方式)是相关窗口的子对象,因此当用户关闭该窗口时,QShortcut 子对象也会被删除。
QWidget, the fundamental class of the Qt Widgets module, extends the parent-child relationship. A child normally also becomes a child widget, i.e. it is displayed in its parent’s coordinate system and is graphically clipped by its parent’s boundaries. For example, when the application deletes a message box after it has been closed, the message box’s buttons and label are also deleted, just as we’d want, because the buttons and label are children of the message box.
QT Widget 模块的基类 QWidget 扩展了这种机制。在界面里,子对象通常会成为子控件,即会在父控件的坐标系中显示,并在显示上被父控件的边界所裁剪。当应用程序在关闭消息框并将其销毁时,消息框里的按钮和标签也会被销毁,这正是我们所希望的,因为按钮和标签都是消息框的子控件。
You can also delete child objects yourself, and they will remove themselves from their parents. For example, when the user removes a toolbar it m