PDA

View Full Version : Add QLayout to QWidget which already has a layout



mikrocat
5th January 2016, 07:48
I have a QWidget in my Window "AvailableDataWidget" while runtime I add layouts with groupboxes, labels and checkboxes. I want to delete them later and add new groupboxes and checkboxes.

This is the way I create it:


void MonitorWindow::on_actionGetAvailableData_triggered (){
QVBoxLayout* verticalLayout[NumberOfAvailableTypes];
QVBoxLayout* verticalLayoutForWidget = new QVBoxLayout(ui->AvailableDataWidget);

QGroupBox *TypeGroupBox[NumberOfAvailableTypes];

for (int i = 0; i < NumberOfAvailableTypes; i++){ //1 groupbox for each type
TypeGroupBox[i] = new QGroupBox(ui->AvailableDataWidget);
TypeGroupBox[i]->setTitle(DataList.at(i).name);
verticalLayout[i] = new QVBoxLayout(TypeGroupBox[i]);

if (DataList.at(i).type != TYPEBINARY){
QCheckBox *DataCheckbox[DataList.at(i).quantity];
QLabel* tempLabel[DataList.at(i).quantity];
QHBoxLayout* horizontalLayout[DataList.at(i).quantity];

for (int j = 1; j <= DataList.at(i).quantity; j++){
DataCheckbox[j] = new QCheckBox(TypeGroupBox[i]);
DataCheckbox[j]->setChecked(false);
connect(DataCheckbox[j],SIGNAL(clicked()),SLOT(setTransducerFlags()));
horizontalLayout[j] = new QHBoxLayout();
horizontalLayout[j]->addWidget(DataCheckbox[j]);

tempLabel[j] = new QLabel(TypeGroupBox[i]);
tempLabel[j]->setText(QString("%1%2%3").arg(DataList.at(i).name).arg(" ").arg(j));
horizontalLayout[j]->addWidget(tempLabel[j]);

verticalLayout[i]->addLayout(horizontalLayout[j]);
}
}
else{
...
QCheckBox *DataCheckbox = new QCheckBox(TypeGroupBox[i]);
DataCheckbox->setChecked(false);
connect(DataCheckbox,SIGNAL(clicked()),SLOT(setTra nsducerFlags()));
QLabel* tempLabel = new QLabel(TypeGroupBox[i]);
tempLabel->setText(DataList.at(i).name);
QHBoxLayout* horizontalLayout = new QHBoxLayout;
horizontalLayout->addWidget(DataCheckbox);
horizontalLayout->addWidget(tempLabel);
myTransducermodel->addColumn(DataList.at(i).name);
verticalLayout[i]->addLayout(horizontalLayout);
}
verticalLayoutForWidget->addWidget(TypeGroupBox[i]);
}
}
}

So I need to delete the layout and widgets, right?
AvailableDataWidget should be the parent of all layouts and widgets, so i tried this:

QList<QWidget *> widgets = ui->AvailableDataWidget->findChildren<QWidget *>();
foreach(QWidget * widget, widgets){
delete widget;
}

but it makes my program crash.

anda_skoa
5th January 2016, 13:22
AvailableDataWidget should be the parent of all layouts and widgets, so i tried this:

QList<QWidget *> widgets = ui->AvailableDataWidget->findChildren<QWidget *>();
foreach(QWidget * widget, widgets){
delete widget;
}

but it makes my program crash.

QObject::findChildren() is recursive by default, so you get the immediate children and their children and so on.
When you delete a QObject object, it will delete all its children, so some of the pointers in your list will already have become invalid.

Cheers,
_