Nominate our 2022 Qt Champions!

Clarification on deleting layouts and widgets within them

  • Hello Qt Universe,

    I would like some clarification and some help on something I'm working on. Let's say that I have the following:
    note: this wasn't copied from my code so please forgive syntax errors

    QPushButton *btn1, *btn2, *btn3, *btn4, *delBtn;
    QHBoxLayout *hbox1, *hbox2;
    QVBoxLayout *vbox1;
    btn1 = new QPushButton(Tr("1");
    btn2 = new QPushButton(Tr("2");
    btn3 = new QPushButton(Tr("3");
    btn4 = new QPushButton(Tr("4");
    delBtn = new QPushButton(Tr("del");
    connect(delBtn, &QPushButton::clicked, this, &MyClass::delBtnClicked);
    hbox1 = new QHBoxLayout;
    hbox2 = new QHBoxLayout;
    vbox1 = new QVBoxLayout;
    void MyClass::delBtnClicked()
         //remove and delete entire vbox1 layout

    I've seen the following:

    QLayoutItem *child;
    while ((child = layout->takeAt(0)) != 0) {
    delete child;

    Would each hbox be "child" and "layout" would be vbox? And if I delete "child" will that then delete the QPushButton widgets within hbox1 and hbox2?


  • Lifetime Qt Champion


    Most likely yes.

  • Well I got my example to work by using the following:

    while(!vbox1->isEmpty()) {
        QLayout *hb = vbox1->takeAt(0)->layout();
        while(!hb->isEmpty()) {
            QWidget *w = hb->takeAt(0)->widget();
            delete w;
        delete hb;
    delete vbox1;

    This removes the widgets and the layout they're on, as well as deletes them from memory. Thanks!

  • Lifetime Qt Champion

    Yes Deleting QLayoutItem seems not to free any Widget it manages.

  • Lifetime Qt Champion

    No, it doesn't. The QLayoutItem is not the parent of the widget, it is not a QObject. That's not its job.