5

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?

4

2 回答 2

8

我递归地删除了所有孩子,它对我有用。

这是我的代码。

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);
于 2013-10-06T17:42:34.320 回答
2

可能小部件的父级是包含小部件,而不是它们的布局(传递给它们的构造函数的parent参数是什么?)。

也许QObject::dumpObjectTree()可以帮助您了解亲子关系。

您的方法 2 会发生什么(它不依赖于QObject布局意义上的子小部件)是它使用该takeAt()方法从布局中删除所有项目但不删除它们:顶层的孩子QVBoxLayoutQFormLayouts ,所以呼唤widget()他们的QLayoutItems回报0。只需delete child无条件地使用删除 child QLayout。但是,这仍然不会删除子小部件。您可以递归调用takeAt()子布局或删除父小部件(您的QScrollArea)的所有子级,或者自己保留小部件和/或布局的列表。

于 2013-09-21T15:42:17.483 回答