PyQt4: How do you iterate all items in a QListWidget

China☆狼群 提交于 2019-12-03 09:46:35

I don't know what's it with the MIME type either, and I couldn't find a convenience method either. 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).

Just to add my 2 cents, as I was looking for this:

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

I know this is old but, I just found out a function findItems(text, Qt.MatchFlags) in QListWidget. 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.

As user Pythonic stated above for PyQt4, you can still directly index an item using:

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.

One way to do this in PyQt5 is:

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