How to delete an already existing layout on a widget?

Chris Wilson's answer is correct, but I've found the layout does not delete sublayouts and qwidgets beneath it. It's best to do it manually if you have complicated layouts or you might have a memory leak.

QLayout * layout = new QWhateverLayout();

// ... create complicated layout ...

// completely delete layout and sublayouts
QLayoutItem * item;
QLayout * sublayout;
QWidget * widget;
while ((item = layout->takeAt(0))) {
    if ((sublayout = item->layout()) != 0) {/* do the same for sublayout*/}
    else if ((widget = item->widget()) != 0) {widget->hide(); delete widget;}
    else {delete item;}
}

// then finally
delete layout;

You just use

delete layout;

like you would with any other pointer you created using new.

Tags:

Qt

Qt4