Remove all items from a layout

后端 未结 2 1494
名媛妹妹
名媛妹妹 2020-11-27 08:03

I was trying to find something that would take a qt layout and delete everything from it. Just to imagine what the window looks like - I have:

QVBoxLayout
          


        
相关标签:
2条回答
  • 2020-11-27 08:21

    The safest way to clear a layout is to extract the items with its takeAt method, and then explicitly delete any widgets with deleteLater:

    def clearLayout(self, layout):
        if layout is not None:
            while layout.count():
                item = layout.takeAt(0)
                widget = item.widget()
                if widget is not None:
                    widget.deleteLater()
                else:
                    self.clearLayout(item.layout())
    
    0 讨论(0)
  • 2020-11-27 08:30

    The problem with your code is QLayout.itemAt() returns a QLayoutItem, QWidgetItem or QSpacerItem depending on the item at that position. So the condition:

    type(layout.itemAt(i)) == QtGui.QHBoxLayout
    

    will never be True and you will be trying to do .widget() for a QLayoutItem and that returns None. Thus the error you get. Another thing is, you need to loop backwards. Because removing things from the beginning will shift items and change the order of items.

    You need to write your function like this:

    def clearLayout(self, layout):
        for i in reversed(range(layout.count())):
            item = layout.itemAt(i)
    
            if isinstance(item, QtGui.QWidgetItem):
                print "widget" + str(item)
                item.widget().close()
                # or
                # item.widget().setParent(None)
            elif isinstance(item, QtGui.QSpacerItem):
                print "spacer " + str(item)
                # no need to do extra stuff
            else:
                print "layout " + str(item)
                self.clearLayout(item.layout())
    
            # remove the item from layout
            layout.removeItem(item)    
    
    0 讨论(0)
提交回复
热议问题