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

I have a PyGtk tree with multiple columns. At runtime, I add constantly new lines. Each cell contains a row. Normal, I would use gtk.CellRenderer for each row, but I want to set the background color of each cell to match the value inside the cell.

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

+4
source share
1 answer

You can define the background and foreground for your tree cells in the additional fields of the treeview data source. Then configure the foreground and background attributes for the columns of the tree to get their values ​​from the corresponding fields in the data source.

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, believes

+9
source

Source: https://habr.com/ru/post/1342032/


All Articles