Qt中的父代是做什么用的? [英] What is parent for in Qt?
问题描述
几乎每个QtWidgets类都可以具有父级.通常,在对象初始化时设置父级是可选的.例如,如果我创建一个继承QWidget
类的类,则将在构造函数上执行以下操作:
Almost every QtWidgets class can have parent. And usually it's optional to set parent at object initialization. For example,If I create a class that inherits QWidget
class, I will do the following on the constructor:
Widget::Widget(QWidget* parent): QWidget(parent) {
hbox = new QHBoxLayout(this);
yes_button = new QPushButton("&Yes");
no_button = new QPushButton("&No", this);
cancel_button = new QPushButton("&Cancel", hbox);
}
我可以设置父级,也可以不设置父级.我可以将cancel_button
设置为hbox
的子级.我也可以将cancel_button
设置为yes_button
的子代,但是我认为这是一件坏事.
I can set or not set parent. I can set cancel_button
to be a child of hbox
. I can too set cancel_button
to be a child of yes_button
, but I think it's a bad thing to do.
这有什么意义?而且,是否真的有必要为我创建的每个基于QWidget
的类设置父级?
What's the point of this? And, is it really necessary to set parent for every QWidget
based class that I create?
推荐答案
除了帮助GUI对象绘制顺序外,它还有助于内存管理,因此当销毁QObject时,它的所有子级也会被销毁.参见 http://doc.qt.io/qt-4.8/objecttrees.html有关更多详细信息.当父项发生变化(例如,调整大小)时,它可以通知子项也进行更新.
Besides helping with draw order in GUI objects, it also helps with memory management, so that when you destroy a QObject, all of it's children are destroyed too. See http://doc.qt.io/qt-4.8/objecttrees.html for more details. When something changes in the parent (e.g. when it is resized), it can notify its children to update themselves too.
要回答您的问题,您不需要为所有内容设置父级(毕竟这就是为什么它是可选参数的原因),但是在大多数情况下,最好对其进行正确设置.
To answer your question, you're not required to set the parent for everything (that's why it's an optional parameter, after all), but most of the time it's better to set it correctly.
这篇关于Qt中的父代是做什么用的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!