Remove all items from QListWidget in a cycle

前端 未结 1 1670
情深已故
情深已故 2021-01-22 00:12

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

相关标签:
1条回答
  • 2021-01-22 00:46

    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))
    
    0 讨论(0)
提交回复
热议问题