[pygtk] Tutorial Question...

John Finlay finlay at moeraki.com
Mon Aug 9 04:55:01 WST 2004


David M. Cook wrote:

>On Sun, Aug 08, 2004 at 05:45:38AM -0400, dave wrote:
>
>  
>
>>Are we supposed to be talking about TreeStore's here instead of liststores?
>>
>>I'm currently doing a search on a TreeStore:
>>for row in treestore:
>> if row[0]==searchedthing:
>>    return row
>>    
>>
>
>Here's what I came up with when someone asked about this back on 7/7:
>
>#untested back-of-the-envelope coding!
>#Uses the gtk standard of returning False on match.
>def search_func(model, col, key, iter, user_data):
>    value = model.get_value(iter, col)
>    return value!=key
>
>def search(model, col, key, iter, search_func, user_data):
>    if search_func(model, col, key, iter, user_data):
>        for i in range(model.iter_n_children()):
>             child = model.iter_nth_child(i)
>             search(model, col, key, child, search_func, user_data)
>    else:
>        yield iter
>
>it = model.get_iter_first()
>mysearch = search(model, 0, 'foobar', it, search_func)
>matches = list(mysearch)
>
>  
>
Unfortunately that doesn't work. Here's a fixed up version:

        def search_func(model, col, key, iter):
            value = model.get_value(iter, col)
            return value==key
        def search(model, col, key, iter, search_func):
            while iter:
                if search_func(model, col, key, iter):
                        yield iter
                for it in search(model, col, key, 
model.iter_children(iter), search_func):
                    yield it
                iter = model.iter_next(iter)
        it = self.treestore.get_iter_first()
        mysearch = search(self.treestore, 0, 'foobar', it, search_func)
        matches = list(mysearch)


Or alternatively:

        def compare_func(row, col, key):
            return row[col]==key
        def search1(rows, col, key, func):
            if not rows: return
            for row in rows:
                if func(row, col, key):
                    yield row
                for r in search1(row.iterchildren(), col, key, func):
                    yield r
        mrows = search1(self.treestore, 0, 'foobar', compare_func)

John



More information about the pygtk mailing list