Search code examples
pythongtkpygtkgtktreeviewcellrenderer

How to set the color of a single cell in a pygtk treeview?


I have a PyGtk treeview with a couple of columns. During runtime i add constantly new rows. Each cell contains a string. Normaly, i would use a gtk.CellRenderer for each row, but I want to set the background color of each cell, according to the value inside the cell.

I tried a couple of solutions, but it seems that I have to create a CellRenderer for each cell, set the text attribute and the background color. This seems a little oversized, so i asked myself if there is a nicer solution for the problem. Any suggestions?


Solution

  • You can define background and foreground for your treeview cells in extra fields of the treeview data source. Then setup foreground and background attributes for the treeview columns to get their values from the corresponding data source fields.

    Below is a small example:

    import gtk
    
    test_data = [
        { 'column0' : 'test00', 'column1' : 'test01', 'f': '#000000', 'b': '#FF00FF' },
        { 'column0' : 'test10', 'column1' : 'test11', 'f': '#FF0000', 'b': '#C9C9C9' },
        { 'column0' : 'test20', 'column1' : 'test21', 'f': '#00FF00', 'b': '#FF0000' }]
    
    class TestWindow(gtk.Window):
        def __init__(self):
            gtk.Window.__init__(self)
    
            # create list storage        
            store = gtk.ListStore(str, str, str, str)
            for i in test_data:
                store.append([i['column0'], i['column1'], i['f'], i['b']])
            treeview = gtk.TreeView(store)
    
            # define columns
            column0 = gtk.TreeViewColumn("Column 0", gtk.CellRendererText(), text=1, foreground=2, background=3)        
            treeview.append_column(column0)            
            column1 = gtk.TreeViewColumn("Column 1", gtk.CellRendererText(), text=1, foreground=2, background=3)        
            treeview.append_column(column1)
    
            self.connect("destroy", lambda w: gtk.main_quit())
            self.connect("delete_event", lambda w, e: gtk.main_quit())
    
            self.add(treeview)
            self.show_all()
    
    if __name__ == "__main__":
        TestWindow()
        gtk.main() 
    

    hope this helps, regards