且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从网格布局中删除最后一个小部件

更新时间:2023-11-14 16:46:16

您的函数会删除所有小部件,因为您正在循环浏览所有小部件,从第一个到最后一个最后.

Your function removes all widgets because you are cycling through all the widgets, from the first to the last.

此外,实际上没有必要遍历整个布局,因为您已经保留了一个小部件列表,这些小部件列表总是将最后一个附加到最后.

Also, there is really no need to go through the whole layout, since you already keep a list of widgets that always appends the last one at the end.

只需从列表中弹出最后一项.不需要从布局中删除它,因为 deleteLater() 会处理它,但这只是为了演示目的.

Just pop out the last item from the list. Removing it from the layout shouldn't be necessary, as deleteLater() would take care of it, but that's just for demonstration purposes.

def deleate_widgets(self):
    # remove the last item from the list
    lastWidget = self.mylist.pop(-1)
    self.main_layout.removeWidget(lastWidget)
    lastWidget.deleteLater()

为了完整起见,您的函数应该完成以下操作:

For the sake of completeness, your function should have done the following:

  1. 在布局中循环小部件向后;
  2. 打破第一个(如最后一个)项目的循环;
  1. cycle the widgets through the layout backwards;
  2. break the cycle as soon as the first (as in last) item is found;

def deleate_widgets(self):
    widgets = [self.main_layout.itemAt(i).widget() for i in range(self.main_layout.count())]
    # use reversed() to cycle the list backwards
    for widget in reversed(widgets):
        if isinstance(widget, qtw.QLineEdit):
            print("linedit: %s  - %s" %(widget.objectName(), widget.text()))
            widget.deleteLater()
            # the line edit has been found, exit the cycle with break to avoid
            # deleting further widgets
            break

此外,为不需要持久引用的对象创建实例属性 (self.someobject = ...) 真的没有用,特别是如果您重复创建这些对象(这将导致该属性不断覆盖,使其无用)并且您已经将它们保存在一个持久数据模型对象(通常是一个列表、一个元组、一个字典)中,例如 self.mylist 在您的情况下(that 必须是一个实例属性):

Also, there's really no use in creating instance attributes (self.someobject = ...) for objects that don't need a persistent reference, especially if you are creating those objects repeatedly (which will result in a constant overwrite of that attribute, making it useless) and you already are keeping them in an persistent data model object (usually a list, a tuple, a dictionary) like self.mylist in your case (and that has to be an instance attribute):

def add_widget(self):
        # no need to create a "self.my_lineedit"
        my_lineedit = qtw.QLineEdit()
        self.mylist.append(my_lineedit)
        self.main_layout.addWidget(my_lineedit)

看过你之前的问题和评论,我强烈建议你更好地学习和试验 Python 数据模型控制流,因为它们是的基本概念(Python 和一般编程)在尝试做任何事情之前,必须被理解和内化.

Having seen your previous questions and comments, I strongly suggest you to better study and experiment with the Python data models, control flows and classes, as they are basic concepts (of Python and programming in general) that must be understood and internalized before attempting to do anything else.