[pygtk] Sorting Treemodelfilter

Kalman KHIRALY khiraly123 at gmx.net
Mon Feb 9 06:26:41 WST 2009

> So can somebody help me how can I make the second (or first) column
> clickable and sortable?
> The ready-to-use demo source can be found here:
> http://www.pastebin.ca/1330860

Ok, after searching the whole day, finally I got a clue from
java-gnome documentation:

For some reason, TreeModelFilter does not implement TreeSortable. If
you plan to sort the
filtered model (ie via TreeViewColumn's setSortColumn()) make sure you
wrap your TreeModelFilter
in a TreeModelSort and add that to the TreeView instead.

So basically the packing is like this:
I add this TreeModelSort to TreeView, and it is working.

I have written a small explanation at the beginning of the code, if
somebody is interested.

I think it is a nice demo app, of this concept
(every row is a simple python object).

Here is the sourcecode:

There is one more thing MISSING: drag and drop not working.
I stopped looking at this issue, as Im not needing is (currently),
but if anybody figure it out, please post the corrected code. Thanks.

For future reference (mail archive) I paste it below:
#!/usr/bin/env python

# example of a tree implementation where each row is a simple python object.
# Features:
#   * Each row is a python object, and we simply add this object to treestore
#   * A helper method extract the required information for each column
#   * We use TreeModelFilter, which enables as filtering the treeview
#     (like togglebutton for show/hide specific rows). Not shown
#      here. Any volunteers?
#   * We use TreeModelSort which reenables column sorting

# Basic outline is: we pack our data inside a TreeStore,
# we pack that TreeStore inside a TreeModelFilter, and
# we pack this TreeModelFilter inside a TreeModelSort.
# Finally we add this TreeModelSort to Treeview which displays
# the data at the end. (treeview requires treeviewcolumn for each
# column and treeviewcolumn requires cellrenderer to display data at the end)

import pygtk
import gtk

class TreeViewColumnExample:

    # close the window and quit
    def delete_event(self, widget, event, data=None):
        return False

    def modify_func(self, model, iter, col, attrs):
        """Extract the columns of a single python object."""

        # Convert the filter iter to the corresponding child model iter.
        child_model_iter = model.convert_iter_to_child_iter(iter)
        child_model = model.get_model()
        row_obj = child_model.get_value(child_model_iter, 0)

        path = child_model.get_path(child_model_iter)
        path_str=  "-".join(str(i) for i in path)

        if col == 0: #first column
            arr = self.row[path_str][col]
        elif col == 1:
            arr = self.row[path_str][col]
        elif col == 2:
            arr = self.row[path_str][col]
            arr = "faszomat"
        return arr

    def __init__(self):
        # Create a new window
        self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        self.window.set_title("TreeViewColumn Example")
        #self.window.set_size_request(200, 200)
        self.window.connect("delete_event", self.delete_event)

        # create a liststore with one string column to use as the model
        self.treestore = gtk.TreeStore(object)

        # create the TreeView using liststore
        self.treeview = gtk.TreeView()

        # create the TreeViewColumns to display the data
        self.tvcolumn = gtk.TreeViewColumn('Pixbuf and Text')
        self.tvcolumn1 = gtk.TreeViewColumn('Text Only')

        # add a row with text and a stock item - color strings for
        # the background
        # this is a simple dict for holding the example data.
        # we add each row element as python object.
        # (list is not needed, any object will do the job)
        self.row = {}
        self.row["0"] = ['Open', gtk.STOCK_OPEN, 'Open a File', True]
        self.row["1"] = ['New', gtk.STOCK_NEW, 'New File', True]
        self.row["1-0"] = ['Save', gtk.STOCK_SAVE, 'Save File', True]
        self.row["2"]  = ['Print', gtk.STOCK_PRINT, 'Print File', False]

        # we add each row to the gtk.TreeStore.
        # Each row is a python object (list in that case)
        self.treestore.append(None, [self.row["0"]])
        parent_iter = self.treestore.append(None, [self.row["1"]])
        self.treestore.append(parent_iter, [self.row["1-0"]])
        self.treestore.append(None, [self.row["2"]])

        self.filtered = self.treestore.filter_new()
        self.filtered.set_modify_func([str, str, str, 'gboolean'],
                                 self.modify_func, ["data"])

        self.sorted = gtk.TreeModelSort(self.filtered)

        # add columns to treeview

        # create a CellRenderers to render the data
        self.cellpb = gtk.CellRendererPixbuf()
        self.cell = gtk.CellRendererText()
        self.cell1 = gtk.CellRendererText()

        # set background color property
        self.cellpb.set_property('cell-background', 'yellow')
        self.cell.set_property('cell-background', 'cyan')
        self.cell1.set_property('cell-background', 'pink')

        # add the cells to the columns - 2 in the first
        self.tvcolumn.pack_start(self.cellpb, False)
        self.tvcolumn.pack_start(self.cell, True)
        self.tvcolumn1.pack_start(self.cell1, True)

        # set the cell attributes to the appropriate liststore column
        # GTK+ 2.0 doesn't support the "stock_id" property
        self.tvcolumn.set_attributes(self.cellpb, stock_id=1)
        self.tvcolumn.set_attributes(self.cell, text=0)
        self.tvcolumn1.set_attributes(self.cell1, text=2)

        # make treeview searchable

        # Allow sorting on the column

        # Allow drag and drop reordering of rows
        #NOT WORKING! WHY?


def main():

if __name__ == "__main__":
    tvcexample = TreeViewColumnExample()

Best regards,

More information about the pygtk mailing list