Search code examples
treeviewgtkbackground-colorvala

Vala: TreeVIew + ListStore row background color


I have a TreeView with a ListStore model and 3 text columns (made with CellRenderText).

My question is if is there any way to change the background color of one row. When you select a row its color is changed, can I get the same efect with some random row without clicking it?.


Solution

  • The simple approach would be to have a column in the model set the background color.

    Here is an example where you can toggle the third row background color:

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

    the result should be something like this:

    enter image description here

    Here the trigger is manual but you can have business logic decide which row to change...