0
votes

I'm testing the following point of Qt Documentation.

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.

I created five QPushButtons and one QGroupbox using QDesigner. Then I add those buttons to QGridLayout and set that as layout of groupbox.

Then I tried to check the children of groupbox. But it shows 6 children instead of 5. One is empty and others are pushbuttons.

Here is my code.

QGridLayout *grd = new QGridLayout();
grd->addWidget(ui->pushButton,0,0);
grd->addWidget(ui->pushButton_2,0,1);
grd->addWidget(ui->pushButton_3,1,0,1,3);
grd->addWidget(ui->pushButton_4,2,0);
grd->addWidget(ui->pushButton_5,2,1);

ui->groupBox->setLayout(grd);

qDebug() << ui->groupBox->children().count();

foreach (QObject *button, ui->groupBox->children())
{
    qDebug() << "obj name" << button->objectName();
    QPushButton *push_button = qobject_cast<QPushButton *>(button) ;
    if(push_button)
    {
        qDebug() << push_button->text();
    }
}

Results I got.

6 
obj name "" 
obj name "pushButton" 
"button 1" 
obj name "pushButton_2" 
"button 2" 
obj name "pushButton_3" 
"button 3" 
obj name "pushButton_4" 
"button 4" 
obj name "pushButton_5" 
"button 5" 

Anyone can tell me why children().count() equal to 6 rather than 5?

1
Use QObject::findChildren to get the buttons only.thuga
This is not about getting the buttons. I was tried to find why I'm getting 6 children rather than 5.Hareen Laks
Could it be because you are getting 1 layout child + 5 button children's?~ Set QGridLayout.objectName = "xxx" and run it again then you should get xxx on 1st position ?Dariusz

1 Answers

1
votes

Do the following:

qDebug() << "Class name:" << button->metaObject()->className();

and you will see one child is the QGridLayout

Or alternatively:

grd->setObjectName("GridLayout");

And the name should be displayed in the place of the empty string

What does this mean: the layout of the widget becomes a child of the widget.