Skip to content Skip to sidebar Skip to footer

Delete Last Widget From Gridlayout

I have a Grid layout in which I add Qlineedits at runtime. while pushing the button I want to delete the last qline edit from the gridlaout Why does this function delete all ql

Solution 1:

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.

defdeleate_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. cycle the widgets through the layout backwards;
  2. break the cycle as soon as the first (as in last) item is found;
defdeleate_widgets(self):
    widgets = [self.main_layout.itemAt(i).widget() for i inrange(self.main_layout.count())]
    # use reversed() to cycle the list backwardsfor widget inreversed(widgets):
        ifisinstance(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 widgetsbreak

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

defadd_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.

Post a Comment for "Delete Last Widget From Gridlayout"