Parent of new QLabel(...)?
-
Hello,
If I create a VBOXLayout and groupboxes, something like this:
QGroupBox *box1 = new QGroupBox("Options", this); QVBoxLayout *box1layout = new QVBoxLayout(box1); box1layout->addWidget(new QLabel("", box1)); box1->setLayout(box1layout); layout->addWidget(box1);
In my mind I imagine it the way that if I create a groupbox, then it would become the parent of everything that I place into it. If I add a new widget then the widget would become the parent of everything inside it. Therefore my parent-child relationship looks something like this:
mainwindow <-- box1 <-- QLabel
Is this logic correct? Or should I just use always
this
as parent? Or should I just usenull
for parent? What is the preferred way of doing this? Thanks in advance. -
@need4openid
To give a simple answer, in fact you don't need to pass anything (nullptr
is the default) if you will be adding the new widget onto an existing widget/layout (e.g. viaaddWidget()
orsetLayout()
), which is the normal case. For example, if you add thatQGroupBox
onto a widget after creating it, which I imagine you will, you could have omitted thethis
parent there. Up to you, I usually don't bother.As an example, see https://doc.qt.io/qt-5/layout.html#tips-for-using-layouts and the code they give there. Note e.g.
When you use a layout, you do not need to pass a parent when constructing the child widgets. The layout will automatically reparent the widgets (using QWidget::setParent()) so that they are children of the widget on which the layout is installed.