Qt - remove all widgets from layout?

前端 未结 12 649
野性不改
野性不改 2020-12-01 01:33

This doesn\'t seem easy. Basically, I add QPushButtons through a function to a layout, and when the function executes, I want to clear the layout first (removi

12条回答
  •  隐瞒了意图╮
    2020-12-01 02:18

    Untried: Why not create a new layout, swap it with the old layout and delete the old layout? This should delete all items that were owned by the layout and leave the others.

    Edit: After studying the comments to my answer, the documentation and the Qt sources I found a better solution:

    If you still have Qt3 support enabled, you can use QLayout::deleteAllItems() which is basically the same as hint in the documentation for QLayout::takeAt:

    The following code fragment shows a safe way to remove all items from a layout:

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

    Edit: After further research it looks like both version above are equivalent: only sublayouts and widget without parents are deleted. Widgets with parent are treated in a special way. It looks like TeL's solution should work, you only should be careful not to delete any top-level widgets. Another way would be to use the widget hierarchy to delete widgets: Create a special widget without parent and create all your removeable widgets as child of this special widget. After cleaning the layout delete this special widget.

提交回复
热议问题