Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

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 use null 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. via addWidget() or setLayout()), which is the normal case. For example, if you add that QGroupBox onto a widget after creating it, which I imagine you will, you could have omitted the this 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.



  • @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. via addWidget() or setLayout()), which is the normal case. For example, if you add that QGroupBox onto a widget after creating it, which I imagine you will, you could have omitted the this 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.


Log in to reply