Clearing a Layout in Qt

The code loop I've used before is as follows:

void clearLayout(QLayout *layout) {
    if (layout == NULL)
        return;
    QLayoutItem *item;
    while((item = layout->takeAt(0))) {
        if (item->layout()) {
            clearLayout(item->layout());
            delete item->layout();
        }
        if (item->widget()) {
           delete item->widget();
        }
        delete item;
    }
}

Hopefully that will be helpful to you!


If you transfer the layout to another widget allocated on the stack, the widgets in that layout become the children of the new widget. When the temporary object goes out of scope it destroys automatically the layout and all the widgets in it.

void moduleSelected(Module* m)
{
    if(layout())
        QWidget().setLayout(layout());

    itsLayout = new QFormLayout(this);
    itsLayout->addRow(QString(tr("Type:")),     new QLabel(m->name()));
    itsLayout->addRow(QString(tr("Instance:")), new QLabel(m->instanceID()));
    // ... Display a whole bunch of other fields that depends on the module
}

Tags:

C++

Qt

Qt4