在一个循环中从 QListWidget 中删除所有项目 [英] Remove all items from QListWidget in a cycle

查看:76
本文介绍了在一个循环中从 QListWidget 中删除所有项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码,它应该从 QListWidget 中删除所有项目,但它只需单击即可删除一项(不是全部).为什么?怎么是对的?我不想使用 clear() 方法.我想逐渐删除它们.

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

推荐答案

概念与从列表中删除项目相同:如果您使用递增索引并同时删除项目,则只有一半的项目会被删除已删除.

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.

如果从0开始,去掉第0行,那么第二项就会变成第一项.由于在下一个循环中您将尝试删除第 1 行,结果是您将删除之前的第三行.

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.

因此,您可以始终删除第 0 行的项目:

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

或者使用反向范围:

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

这篇关于在一个循环中从 QListWidget 中删除所有项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆