PyQt How to remove a layout from a layout

后端 未结 2 1406
南方客
南方客 2020-12-20 09:06
datainputHbox = QHBoxLayout()
layout = QVBoxLayout(self)
layout.addLayout(datainputHbox)


pagedatainputdeletboxbutton1.clicked.connect(lambda:self.boxdelete(datainp         


        
相关标签:
2条回答
  • 2020-12-20 09:52

    You can remove QLayouts by getting their corresponding QLayoutItem and removing it. You should also be storing references to your Layouts, otherwise there is no other way to access them later on unless you know the widget they belong to.

    datainputHbox = QHBoxLayout()
    self.vlayout = QVBoxLayout(self)
    layout.addLayout(datainputHbox)
    pagedatainputdeletboxbutton1.clicked.connect(lambda: self.boxdelete(datainputHbox))
    
    def boxdelete(self, box):
        for i in range(self.vlayout.count()):
            layout_item = self.vlayout.itemAt(i)
            if layout_item.layout() == box:
                self.vlayout.removeItem(layout_item)
                return
    
    0 讨论(0)
  • 2020-12-20 09:54

    As a generic answer: taken from here with slight, but important changes: you should not call widget.deleteLater(). At least in my case this caused python to crash

    Global Function

    def deleteItemsOfLayout(layout):
         if layout is not None:
             while layout.count():
                 item = layout.takeAt(0)
                 widget = item.widget()
                 if widget is not None:
                     widget.setParent(None)
                 else:
                     deleteItemsOfLayout(item.layout())
    

    together with the boxdelete function from Brendan Abel's answer

    def boxdelete(self, box):
        for i in range(self.vlayout.count()):
            layout_item = self.vlayout.itemAt(i)
            if layout_item.layout() == box:
                deleteItemsOfLayout(layout_item.layout())
                self.vlayout.removeItem(layout_item)
                break
    
    0 讨论(0)
提交回复
热议问题