How to delete an existing layout on a widget?

You must first remove the existing layout manager (layout () is returned) before you can call setLayout () with the new layout.

from http://doc.qt.io/qt-5.9/qwidget.html#setLayout

What function is used to delete the previous layout?

+12
qt qt4
source share
4 answers

You just use

delete layout; 

like any other pointer created with new .

+15
source share

Chris Wilson's answer is correct, but I found that the layout does not remove the sublanguages ​​and qwidgets under it. This is best done manually if you have a complicated layout 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; 
+15
source share

I want to delete the current layout, replace it with a new layout, but keep all the widgets controlled by the layout. I found that in this case, Chris Wilson's solution does not work. The layout does not always change.

This worked for me:

 void RemoveLayout (QWidget* widget) { QLayout* layout = widget->layout (); if (layout != 0) { QLayoutItem *item; while ((item = layout->takeAt(0)) != 0) layout->removeItem (item); delete layout; } } 
+3
source share

I know this question is old and answered, but: since QtAlgorithms offers qDeleteAll , you can delete the layout, including deleting all its children with a single line.

This is a repetition of the text that I posted here: https://stackoverflow.com/a/316677/

This code deletes the layout, all its children and everything inside the layout disappears.

 qDeleteAll(yourWidget->children()); 

Here is a description of the overloaded function:

void qDeleteAll (ForwardIterator begin, ForwardIterator end)

Deletes all elements in the range [start, end] using the C ++ operator delete>. The type of the element must be a pointer (for example, QWidget *).

Note that qDeleteAll must be passed with the container from this widget (and not this layout). And note that qDeleteAll does NOT delete yourWidget - only its children.

Now a new layout can be installed.

+2
source share

All Articles