簡體   English   中英

GTK#Treeview - 如何對子節點進行排序

[英]GTK# Treeview - how to sort child nodes

我有一個像這個圖像的子節點的Gtk.TreeView (由於雇主專有原因,我已經覆蓋了文本):

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

按“標題”列排序(單擊列標題)按3個父節點排序,當我真的只想讓它對每個父節點下的所有子節目進行排序時。 這可能嗎?

請注意,按“路徑”列排序會對子節點進行適當的排序; 我認為因為父節點在該列中沒有文本。 所以我希望在父節點的Title列中有一個(簡單?)方法。

排序有點復雜,因為您需要將代碼的幾個部分(模型和列)合作。 要對特定列進行排序,這是您需要執行的操作:

  1. 創建一個列(沒有快捷方式)並為SortColumnId屬性賦值。 為了簡單起見,我通常會從0開始分配列的序號id,即視圖中的第一列為0,第二列為1,依此類推。
  2. 將模型包裝在Gtk.TreeModelSort
  3. 在新模型上調用SetSortFunc一次,對於要排序的列,並將您在(1)中設置的列ID作為第一個參數傳遞。 確保匹配所有列ID。

行的排序方式取決於您用作SetSortFunc第二個參數的SetSortFunc 你得到了模型和兩個iters,你幾乎可以做任何事情,甚至可以對多個列進行排序(使用兩個iters,你可以從模型中獲取任何值,而不僅僅是排序列中顯示的值。)

這是一個簡單的例子:

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;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM