Search code examples
stylespygtkgtktreeview

How to add different color to odd and even rows in a pygtk TreeView


I have created a pygtk TreeView and wanted to add different colors between each line. I went here and it says that there exists a TreeView Style property that does exactly the same.The property is called 'odd-row-color' and 'even-row-color'. So went to my code and tried to apply this by using the set_property(). But i get an error message for doing that

    self.customer_view.set_property('even-row-color', gtk.gdk.Color(211, 211, 211))
TypeError: object of type `GtkTreeView' does not have property `even-row-color' 

How can achieve that. And where is that property handled?


Solution

  • You can use css (GTK3) to change the colors, something like:

    style_provider = Gtk.CssProvider()
    css = '''
    GtkTreeView row:nth-child(even) { background-color: shade(@base_color, 0.9); }
    GtkTreeView row:nth-child(odd) { background-color: shade(@base_color, 1.0); }
    '''
    style_provider.load_from_data(css.encode('utf8'))
    
    Gtk.StyleContext.add_provider_for_screen(Gdk.Screen.get_default(),
                                style_provider,
                                Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)
    

    Make sure to tell GTK that you want to paint alternate colors:

    treeview.set_rules_hint(True)