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?

Michael Allan Jackson
  • 4,217
  • 3
  • 35
  • 45

6 Answers6

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

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())]
Pythonic
  • 2,091
  • 3
  • 21
  • 34
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 =)

Anchmerama
  • 117
  • 1
  • 6
Diego Ponciano
  • 1,453
  • 1
  • 19
  • 23
7
items = []
for index in xrange(self.listWidget.count()):
     items.append(self.listWidget.item(index))
sam
  • 18,509
  • 24
  • 83
  • 116
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!

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())
salafi
  • 387
  • 6
  • 9