Remove all items from QListWidget in a cycle

▼魔方 西西 提交于 2020-07-03 09:09:26

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/60567277/remove-all-items-from-qlistwidget-in-a-cycle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!