PyQt4: How do you iterate all items in a QListWidget

majgis picture majgis · Jan 7, 2011 · Viewed 36.6k times · Source

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?

Answer

user395760 picture user395760 · Jan 7, 2011

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