[PyKDE] iterating over a QListView
Jim Bublitz
jbublitz at nwinternet.com
Tue Feb 22 21:01:50 GMT 2005
On Tuesday 22 February 2005 11:35, Christopher J. Bottaro wrote:
> The C++ documentation shows this example:
>
> QPtrList<QListViewItem> lst;
> QListViewItemIterator it( myListView );
> while ( it.current() ) {
> if ( it.current()->isSelected() )
> lst.append( it.current() );
> ++it;
>
> I'm wondering if there is a Pythonic way of doing this. Maybe something
> like:
>
> lst = []
> for listviewitem in listview:
> if listviewitem.isSelected():
> lst.append(listviewitem)
>
> or maybe:
>
> lst = []
> for listviewitem in QListViewItemIterator(listview):
> if listviewitem.isSelected():
> lst.append(listviewitem)
>
> Or is there no Pythonic way and I just have to translate the C++ directly?
> This question goes for all Qt iterator classes (i.e. are they turned into
> Python iterables by PyQt?).
>
> Thanks for the help.
I think this is what you're asking for (it's just cut and pasted from a
comp.lang.python post I did a while ago). 'listView' would be a QListView,
'selectedLVIList' is a Python list of QListViewItems.
--------------------------------------
def getSelectedItems (listView):
selectedLVIList = []
listViewItem = listView.firstChild()
scan(listViewItem, selectedLVIList)
return selectedLVIList
def scan(listViewItem, selectedLVIList):
while listViewItem:
if listViewItem.isSelected():
selectedLVIList.append(listViewItem)
scan(listViewItem.firstChild())
listViewItem = listViewItem.nextSibling()
The docs say that you might not traverse the list view items in sort order
using firstChild/nextSibling. This also doesn't keep track explicitly of
which level an item is on, although you can trace back each item's
parent(s) (or else modify the code to track that).
-------------------------------------
I don't know if that's sufficiently "Pythonic" - you could probably create
some kind of iterator in a fashion similar to 'scan'.
Jim
More information about the PyQt
mailing list