2017-07-26 105 views
1

我有一个TreeView与ListStore模型和3个文本列(使用CellRenderText)。Vala:TreeVIew + ListStore行背景颜色

我的问题是如果有什么办法可以改变背景色一行。当你选择一行时,它的颜色发生了变化,我可以在不点击它的情况下得到与某个随机行相同的效果。

回答

1

简单的方法是让模型中的一列设置背景颜色。

下面是一个例子,您可以切换的第三排背景色:

public class Application : Gtk.Window { 
    public Application() { 
     // Prepare Gtk.Window: 
     this.title = "My Gtk.TreeView"; 
     this.window_position = Gtk.WindowPosition.CENTER; 
     this.destroy.connect (Gtk.main_quit); 
     this.set_default_size (350, 70); 

     Gtk.Box box = new Gtk.Box (Gtk.Orientation.VERTICAL, 6); 

     // The Model: 
     Gtk.ListStore list_store = new Gtk.ListStore (2, typeof (string), typeof (Gdk.RGBA)); 
     Gtk.TreeIter iter; 

     list_store.append (out iter); 
     list_store.set (iter, 0, "Stack", 1, "#FFFFFF"); 
     list_store.append (out iter); 
     list_store.set (iter, 0, "Overflow", 1, "#FFFFFF"); 
     list_store.append (out iter); 
     list_store.set (iter, 0, "Vala", 1, "#FFFFFF"); 
     list_store.append (out iter); 
     list_store.set (iter, 0, "Gtk", 1, "#FFFFFF"); 

     // The View: 
     Gtk.TreeView view = new Gtk.TreeView.with_model (list_store); 
     box.add (view); 

     Gtk.ToggleButton button = new Gtk.ToggleButton.with_label ("Change bg color row 3"); 
     box.add (button); 

     this.add (box); 

     Gtk.CellRendererText cell = new Gtk.CellRendererText(); 
     view.insert_column_with_attributes (-1, "State", cell, "text", 0, "background-rgba", 1); 


     // Setup callback to change bg color of row 3 
     button.toggled.connect (() => { 
      // Reuse the previous TreeIter 
      list_store.get_iter_from_string (out iter, "2"); 

      if (!button.get_active()) { 
       list_store.set (iter, 1, "#c9c9c9"); 
      } else { 
       list_store.set (iter, 1, "#ffffff"); 
      } 
     }); 
    } 

    public static int main (string[] args) { 
     Gtk.init (ref args); 

     Application app = new Application(); 
     app.show_all(); 
     Gtk.main(); 
     return 0; 
    } 
} 

的结果应该是这样的:

enter image description here

这里触发手册,但你可以有业务逻辑决定哪一行更改...

+0

它是完美的!谢谢! (这是你第二次解决我的问题,至少对我来说是无法解决的问题) – bcedu

+0

@bcedu乐于帮助:) –