PyQt4: How do you iterate all items in a QListWidget
Asked Answered
U

6

23

Currently, I use the following while loop in a class that inherits QtGui.QListWidget to iterate all items:

    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. Is there a cleaner approach than my while loop above?

Untangle answered 7/1, 2011 at 19:45 Comment(0)
D
27

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

Demars answered 7/1, 2011 at 20:5 Comment(2)
Thanks! What are your thoughts on using xrange here.Untangle
@majgis: My all means, yes. In Python 2, use xrange whenever possible. It's just that I'm usually using Python 3, so I get tend to write Python 3 in my examples.Demars
M
14

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

itemsTextList =  [str(listWidget.item(i).text()) for i in range(listWidget.count())]
Margartmargate answered 27/12, 2015 at 10:24 Comment(0)
M
12

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

Morass answered 8/11, 2011 at 1:45 Comment(2)
You can also find the other Qt.MatchFlag parameters here: pyqt.sourceforge.net/Docs/PyQt4/qt.html#MatchFlag-enumMalleable
I needed to use Qt.MatchWildcardQuartet
G
7
items = []
for index in xrange(self.listWidget.count()):
     items.append(self.listWidget.item(index))
Getraer answered 2/12, 2011 at 7:44 Comment(0)
J
6

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!

Jennyjeno answered 8/11, 2018 at 8:7 Comment(0)
B
3
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())
Bevatron answered 19/11, 2018 at 23:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.