Search code examples
pythonpython-3.xpyqtpyqt5qlistwidget

Remove all items from QListWidget in a cycle


I have the following code, which should remove all items from QListWidget, but it removes only one item on one click (not all). Why? How is it right? I don't want to use clear() method. I want to remove them gradually.

def onRemoveItems(self): # button click event
   for i in range(self.myListWidget2.count()):
       itemI = self.myListWidget2.item(i)
       self.myListWidget2.takeItem(self.myListWidget2.row(itemI))

Solution

  • The concept is the same as removing items from a list: if you use increasing indexes and remove the items at the same time, only half of the items will be removed.

    If you start from 0 and remove the row 0, then the second item will become the first one. Since at the next cycle you'll try to remove row 1, the result is that you'll be removing what was the third row before.

    So, you can either always remove the item at row 0:

        def onRemoveItems(self):
            for i in range(self.myListWidget2.count()):
                itemI = self.myListWidget2.item(0)
                self.myListWidget2.takeItem(self.myListWidget2.row(itemI))
    

    Or use a reverse range:

        def onRemoveItems(self): # button click event
            for i in range(self.myListWidget2.count() - 1, -1, -1):
                itemI = self.myListWidget2.item(i)
                self.myListWidget2.takeItem(self.myListWidget2.row(itemI))