Search code examples
pythontreeviewgtk3

Sort a column in a treeview by default or programmatically


I know my question has already been asked here:

How to Programmatically Sort TreeView

But the link given doesn't link nothing and I'm still not able to have my treeview sorted when my window is showed.

Here is my code:

    treeview = Gtk.TreeView(model=liststore)
    col = renderer_text('Nom', 1, store=liststore, sortable=True)
    col.set_sort_order(Gtk.SortType.ASCENDING) #??????????????????????????
    treeview.append_column(col)

def renderer_text(title, col, editable=False, store=None, sortable=None):
    render = Gtk.CellRendererText()
    if editable:
        render.set_property('editable', True)
        render.connect('edited', text_edited, store, col)
    column = Gtk.TreeViewColumn(title, render, text=col)
    if sortable:
        column.set_sort_column_id(col)
    return column

The set_sort_order(Gtk.SortType.ASCENDING) would have been fantastic but It doesn't sort nothing in my case !


Solution

  • It's hard to see what's going wrong without seeing more of your code, but I'll wager exactly the same thing is happening as in the other question: you need to wrap your tree model in a Gtk.TreeModelSort.

    sorted_model = Gtk.TreeModelSort(model=liststore)
    sorted_model.set_sort_column_id(1, Gtk.SortType.ASCENDING)
    treeview = Gtk.TreeView(model=sorted_model)
    

    Note that 1 is the index into your model's columns in this case, not the visible treeview columns.