This class solved a problem that has been bothering me for a long time: how
to do interactive searches when your store contains only objects.  The
TreeView wants to access a column of strings to do this.  Also, the new
ComboBoxEntry can use a TreeModel, but again it wants to access a column
directly to get its text.

This is where TMF comes in.  Not only can you filter a model, but it also
lets you synthesize completely new columns.  Jon Finlay's amazing tutorial
does a good job covering TMF:

http://tinyurl.com/2qjn9

The other solutions I came up with were writing a custom TreeModel (requires
keeping track of a lot), and keeping a redundant string column that is kept
synchronized with the object column using the Observer pattern.

And here's some code showing how TMF can be used in this case:

import gtk

class Node(object):

    def __init__(self, name):
        self.name = name

    def __str__(self):
        return self.name


def modify_func(model, iter, col):
    child_iter = model.convert_iter_to_child_iter(iter)
    child_model = model.get_model()
    return child_model.get_value(child_iter, 0)

def print_nodes(model):
    it = model.get_iter_first()
    while it:
        print model.get_value(it, 0), repr(model.get_value(it, 1))
        it = model.iter_next(it)

store = gtk.ListStore(object)

# ModelFilter synthesizes a string column using the modify func.
# This string column can be used for interactive searches and ComboBoxes.
filtered = store.filter_new()
filtered.set_modify_func((str, object), modify_func)

# put objects in the store
nodes = map(Node, ['larry', 'bill', 'scott'])
for node in nodes:
    it = store.append()
    store.set_value(it, 0, node)
print_nodes(filtered)

# modify the objects
for node, name in zip(nodes, ['guido', 'linus', 'james']):
    node.name = name
# does the ModelFilter track our changes?    
print_nodes(filtered)
_______________________________________________
pygtk mailing list   [EMAIL PROTECTED]
http://www.daa.com.au/mailman/listinfo/pygtk
Read the PyGTK FAQ: http://www.async.com.br/faq/pygtk/

Reply via email to