4

我有一个Gtk.TreeView像这张图片这样的子节点(出于雇主专有的原因,我已经掩盖了文本):

http://i.stack.imgur.com/kKemI.png

按“标题”列排序(单击列标题)按 3 个父节点排序,而我真的只想对每个父节点下的所有子节点进行排序。这可能吗?

请注意,按“路径”列排序会适当地对子节点进行排序;我认为是因为父节点在该列中没有文本。所以我希望在父节点的标题列中的文本周围有一种(简单的?)方法。

4

1 回答 1

2

排序有点复杂,因为您需要让代码的几个部分(模型和列)协同工作。要对您需要执行的特定列进行排序:

  1. 创建一列(无快捷方式)并为属性分配一个值SortColumnId。为简单起见,我通常分配列的序号 id,从 0 开始,即视图中的第一列是 0,第二列是 1,依此类推。
  2. 将您的模型包装在一个Gtk.TreeModelSort
  3. SetSortFunc为您要排序的列调用一次新模型,并将您在 (1) 中设置的列 ID 作为第一个参数传递。确保匹配所有列 ID。

行的排序方式取决于您用作SetSortFunc. 你得到模型和两个迭代器,你几乎可以做任何事情,甚至对多列进行排序(使用两个迭代器,你可以从模型中获取任何值,而不仅仅是排序列中显示的值。)

这是一个简单的例子:

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;
    }
}
于 2013-02-22T15:34:50.350 回答