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.
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:
- cycle the widgets through the layout backwards;
- 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
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)
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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…