Move layout to another layout in Qt5

I have a custom container widget in Qt5 which has a QFrame without a layout. I use setLayout on QFrame which works fine but sometimes I want to transfer an existing layout which contains widgets and other layouts to that QFrame as layout. Is that even possible in Qt5 to transfer layouts already added with addLayout?


No problem. Just make the layout the layout of the target widget with setLayout(). The widgets contained will be reparented automatically.

void MainWindow::moveLayout()
    // Move the layout from ui->g0 to ui->g1 and vice versa
    // every time you call moveLayout
    static int toggle = 0;

    QLayout* l;
    QWidget* w;
    if (toggle == 0)
        l = ui->g0->layout();
        w = ui->g1;
        l = ui->g1->layout();
        w = ui->g0;

    if (w->layout())
        // Hack to clean target widget
        QWidget z;

    toggle = 1 - toggle;