How to delete an already existing layout on a widget?

前端 未结 4 422
南笙
南笙 2021-01-04 06:53

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

4条回答
  •  死守一世寂寞
    2021-01-04 07:13

    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;
    

提交回复
热议问题