Sorting is a bit complicated because you need to have several parts of your code (model and columns) for collaboration. To sort by a specific column, what you need to do:
- Create a column (without labels) and assign a value to the
SortColumnId
attribute. To keep it simple, I usually assign the ordinal identifier of the column starting at 0, i.e. The first column in the view is 0, the second 1, etc. - Wrap your model in
Gtk.TreeModelSort
- Call
SetSortFunc
in the new model once for the very column that you want to sort and pass the column identifier specified in (1) as the first argument. Verify that all column identifiers match.
How the rows are sorted depends on which delegate you use as the second argument to SetSortFunc
. You get a model and two iterators, and you can do almost everything, even sort by multiple columns (with two iterators, you can get any value from the model, not just the values ββshown in the sorted column.)
Here is a simple example:
class MainClass { public static void Main (string[] args) { Application.Init (); var win = CreateTreeWindow(); win.ShowAll (); Application.Run (); } public static Gtk.Window CreateTreeWindow() { Gtk.Window window = new Gtk.Window("Sortable TreeView"); Gtk.TreeIter iter; Gtk.TreeViewColumn col; Gtk.CellRendererText cell; Gtk.TreeView tree = new Gtk.TreeView(); cell = new Gtk.CellRendererText(); col = new Gtk.TreeViewColumn(); col.Title = "Column 1"; col.PackStart(cell, true); col.AddAttribute(cell, "text", 0); col.SortColumnId = 0; tree.AppendColumn(col); cell = new Gtk.CellRendererText(); col = new Gtk.TreeViewColumn(); col.Title = "Column 2"; col.PackStart(cell, true); col.AddAttribute(cell, "text", 1); tree.AppendColumn(col); Gtk.TreeStore store = new Gtk.TreeStore(typeof (string), typeof (string)); iter = store.AppendValues("BBB"); store.AppendValues(iter, "AAA", "Zzz"); store.AppendValues(iter, "DDD", "Ttt"); store.AppendValues(iter, "CCC", "Ggg"); iter = store.AppendValues("AAA"); store.AppendValues(iter, "ZZZ", "Zzz"); store.AppendValues(iter, "GGG", "Ggg"); store.AppendValues(iter, "TTT", "Ttt"); Gtk.TreeModelSort sortable = new Gtk.TreeModelSort(store); sortable.SetSortFunc(0, delegate(TreeModel model, TreeIter a, TreeIter b) { string s1 = (string)model.GetValue(a, 0); string s2 = (string)model.GetValue(b, 0); return String.Compare(s1, s2); }); tree.Model = sortable; window.Add(tree); return window; } }
source share