PyQt如何从布局中删除布局

2024-09-27 04:21:43 发布

您现在位置:Python中文网/ 问答频道 /正文

datainputHbox = QHBoxLayout()
layout = QVBoxLayout(self)
layout.addLayout(datainputHbox)


pagedatainputdeletboxbutton1.clicked.connect(lambda:self.boxdelete(datainputHbox))

def boxdelete(self, box):

这是PyQt程序 如何编写boxdelete函数以删除datainputbox表单布局。我试了很多。不过,我只能删除所有的小部件,但不能删除布局。


Tags: lambdaselfboxdefconnect布局pyqtlayout
2条回答

作为一般答案:taken from here有轻微但重要的更改:不应该调用widget.deleteLater()。至少在我的例子中,这导致了python崩溃

全局函数

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())

Brendan Abel's应答中的boxdelete函数一起

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

您可以通过获取它们对应的QLayoutItem并移除它来移除QLayouts。您还应该存储对布局的引用,否则以后将无法访问它们,除非您知道它们所属的小部件。

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

相关问题 更多 >

    热门问题