Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete all children from QVBoxLayout

Tags:

c++

qt

I have a QVBoxLayout inside a scrollArea. I dynamically add QFormLayouts.

widgetTreeStruct* tree = new widgetTreeStruct(QString::number(numberOfGraphs)); 
QFormLayout* layout = tree->getTree(); // get QFormLayout
ui->verticalLayout_2->addLayout(layout); //add to the vertical layout

At one point I need to remove all the added QFormLayouts from the QVBoxLayout.

I tried several ways to do this.

  1. Using qDeleteAll()

qDeleteAll(ui->verticalLayout_2->children());

2.delete item one by one

QLayoutItem* child;
          while((child = ui->verticalLayout_2->takeAt(0)) != 0)
          {
              if(child->widget() != 0)
              {
                  delete child->widget();
              }

              delete child;
          }

But nothing happened. Only thing is when I try to add items to QVBoxLayout again new items are added on top of the previously added items.

After added items to QVBoxLayout

I sense that I have to redraw, repaint, update, refresh or something. I tried ui->verticalLayout_2->update(); but didn't work for me.

So, What should I do?

like image 627
Rajitha Madhushan Ranasinghe Avatar asked Sep 21 '13 15:09

Rajitha Madhushan Ranasinghe


2 Answers

I recursively deleted all the children and it worked for me.

This is my code.

void Widget::remove(QLayout* layout)
{
    QLayoutItem* child;
    while(layout->count()!=0)
    {
        child = layout->takeAt(0);
        if(child->layout() != 0)
        {
            remove(child->layout());
        }
        else if(child->widget() != 0)
        {
            delete child->widget();
        }

        delete child;
    }
}

remove(ui->verticalLayout_2);
like image 185
Rajitha Madhushan Ranasinghe Avatar answered Sep 28 '22 05:09

Rajitha Madhushan Ranasinghe


Probably the widgets's parent is the containing widget, not their layout (what is passed to their constructors for the parent parameter?).

Maybe QObject::dumpObjectTree() can help you to understand the parent-child relationships.

What happens with your approach 2 (which does not rely on the widgets being children in the QObject-sense of the layout) is that it removes all items from the layout with the takeAt() method but deletes none of them: The children of your toplevel QVBoxLayout are the QFormLayouts, so calling widget() on their QLayoutItems returns 0. Just use delete child unconditionally to delete the child QLayouts. However, this still does not delete the child widgets. You could either recursively call takeAt() on the child layouts or delete all children of the parent widget (your QScrollArea) or keep a list of widgets and/or layouts yourself.

like image 21
Oberon Avatar answered Sep 28 '22 05:09

Oberon