[Gtk-sharp-list] Some useful TreeModel extension methods

Chris Howie cdhowie at gmail.com
Tue Jun 16 11:55:48 EDT 2009


I'm working on an increasingly complex mono-addins based program, and
I do quite a bit of TreeView stuff.  If you're like me, you get
annoyed iterating over TreeIters and extracting objects from the
model.  I've written a couple of extension methods that make this a
ton easier.

See <http://gitorious.org/gazebo-chess-interface/mainline/blobs/59662ee0a91b8ac56ee53a581b06bfa080b350df/Gazebo.Core/Extensions.cs>
lines 172-206.

If you are using models that have only one column used to contain a
data object, and use your own data functions for rendering different
columns, these methods should prove incredibly useful.  Rather than
doing something ugly like this ...

    // store is a ListStore
    TreeIter iter;
    if (!store.GetIterFirst(out iter)) {
    do {
        DataClass data = (DataClass) store.GetValue(iter, 0);
        // Do stuff with data
    } while (store.IterNext(ref iter));

... you can do something much simpler and a lot more obvious ...

    foreach (DataClass data in store.TraverseColumn<DataClass>(0)) {
        // Do stuff with data

Note that using this on a non-flat TreeModel (like a TreeStore or
something) these methods will in fact navigate the whole tree, from
the first element to the last, as though they were all on the same
level.  You can use model.Traverse() to enumerate the iters if you
need to filter.  This makes for some fun LINQ:

var dataObjects = from iter in store.Traverse()
    where store.GetPath(iter).Depth > 1
    select (DataObject) store.GetValue(iter, 0);

The particular lines mentioned above of this specific version of this
source file are hereby released under the terms of the MIT/X11

Chris Howie

More information about the Gtk-sharp-list mailing list