简体   繁体   English

PyQt4:如何迭代 QListWidget 中的所有项目

[英]PyQt4: How do you iterate all items in a QListWidget

Currently, I use the following while loop in a class that inherits QtGui.QListWidget to iterate all items:目前,我在继承 QtGui.QListWidget 的类中使用以下 while 循环来迭代所有项目:

    i = 0
    while i < self.count():
        item = self.item(i)

        i += 1

I was hoping I could use:我希望我可以使用:

for item in self.items():

but the items() method wants a QMimeData object which I don't know how to construct to return all items.但是 items() 方法需要一个 QMimeData 对象,我不知道如何构造它以返回所有项目。 Is there a cleaner approach than my while loop above?有没有比上面的 while 循环更干净的方法?

I don't know what's it with the MIME type either, and I couldn't find a convenience method either.我也不知道 MIME 类型是什么,我也找不到方便的方法。 But you could write a simple method like this and be done:但是你可以写一个像这样的简单方法并完成:

def iterAllItems(self):
    for i in range(self.count()):
        yield self.item(i)

It's even lazy (a generator).它甚至是懒惰的(生成器)。

只是为了添加我的 2 美分,因为我正在寻找这个:

itemsTextList =  [str(listWidget.item(i).text()) for i in range(listWidget.count())]

I know this is old but, I just found out a function findItems(text, Qt.MatchFlags) in QListWidget.我知道这是旧的,但是,我刚刚在 QListWidget 中发现了一个函数findItems(text, Qt.MatchFlags) So, to iterate all items:因此,要迭代所有项目:

#listWidget is a QListWidget full of items
all_items = listWidget.findItems('', QtCore.Qt.MatchRegExp)
for item in all_items:
  print item

And do whatever you need with the item =)并使用该项目做任何您需要的事情 =)

items = []
for index in xrange(self.listWidget.count()):
     items.append(self.listWidget.item(index))

Just as a note for others landing here seeking the same information about PyQt5, it's slightly different here.正如其他人在这里寻求有关 PyQt5 的相同信息的说明一样,这里略有不同。

As user Pythonic stated above for PyQt4, you can still directly index an item using:正如上面针对 PyQt4 的用户Pythonic所述,您仍然可以使用以下方法直接索引项目:

item_at_index_n = list_widget.item(n)

But to acquire a list of items for iteration, using an empty string and the MatchRegExp flag doesn't seem to work any more.但是要获取用于迭代的项目列表,使用空字符串和 MatchRegExp 标志似乎不再起作用。

One way to do this in PyQt5 is:在 PyQt5 中执行此操作的一种方法是:

all_items = list_widget.findItems('*', PyQt5.Qt.MatchWildcard)

I'm still getting to grips with PyQt, so there may well be an easier / simpler / more elegant way that I simply haven't come across yet.我仍在掌握 PyQt,所以很可能有一种我还没有遇到过的更简单/更简单/更优雅的方法。 But I hope this helps!但我希望这会有所帮助!

items = []
for index in range(self.listWidget.count()):
    items.append(self.listWidget.item(index))

If your wish to get the text of the items如果您希望获得项目的文本

for item in items:
   print(item.text())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM