[PyKDE] Re: iterating over a QListView

David Boddie david at boddie.org.uk
Tue Feb 22 23:27:39 GMT 2005

On Tue, 22 Feb 2005, Christopher J. Bottaro wrote:

> Right, but what I meant was does PyQt turn those iterator classes into
> "Python iterables".  By that I mean, can they be used in a for loop such
> as:
> # lv is a QListView
> for lvi in QListViewItemIterator(lv):
>   # do something with the list view item
> The answer is no, btw.  The above code yields a "TypeError: iteration over
> non-sequence" exception.

Try the following:

class Iterator:
  def __init__(self, obj):
    self.data = obj.firstChild()
  def __iter__(self):
    return self
  def next(self):
    item = self.data
    if item is None:
      raise StopIteration
      self.data = self.data.nextSibling()
    return item

for lvi in Iterator(lv):
 # Do something with the list view item.

That should work for any item class that implements firstChild() and
nextSibling() methods.

> That kinda stinks, it would be nice if it was more Pythonic (while still
> adhering to the C++ API of course).

It seems that some far-sighted person has thoughtfully provided some recipes
to solve just this sort of problem:


Maybe I should add the above class to that page.

Hope this helps,


More information about the PyQt mailing list