datainputHbox = QHBoxLayout()
layout = QVBoxLayout(self)
layout.addLayout(datainputHbox)
pagedatainputdeletboxbutton1.clicked.connect(lambda:self.boxdelete(datainputHbox))
def boxdelete(self, box):
这是 PyQt proragm如何编写框删除功能以删除数据输入Hbox表单布局。我尝试了很多。但是我只能删除所有小部件,但不能删除布局。
作为一个通用答案:从这里开始,略有但重要的更改:你不应该调用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())
连同布伦丹·亚伯答案中的 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
实现 TheTrowser 答案的单个函数,可以说更干净:
def clear_item(self, item):
if hasattr(item, "layout"):
if callable(item.layout):
layout = item.layout()
else:
layout = None
if hasattr(item, "widget"):
if callable(item.widget):
widget = item.widget()
else:
widget = None
if widget:
widget.setParent(None)
elif layout:
for i in reversed(range(layout.count())):
self.clear_item(layout.itemAt(i))
使用上面的东西,我做了一个删除所有布局及其小部件的函数。不幸的是,它还会破坏上述布局和小部件的其他实例,因此请谨慎使用。
def clearLayout(self, layout: QLayout):
"""
Args:
layout (QLayout): The layout to clear
"""
if layout is not None:
while layout.count():
item = layout.takeAt(0)
if item is not None:
while item.count():
subitem = item.takeAt(0)
widget = subitem.widget()
if widget is not None:
widget.setParent(None)
layout.removeItem(item)