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.
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.
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?
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);
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 QFormLayout
s, so calling widget()
on their QLayoutItems
returns 0
. Just use delete child
unconditionally to delete the child QLayout
s. 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With