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?
QObject::findChildren
to get the buttons only. – thuga