Search code examples
python-3.xgtkpygobject

Modify background of all TreeView items in PyGObject


I want to have a (from default) different color my items in a Gtk.TreeView. The example code below has no effect. The background keeps white.

#!/usr/bin/env python3

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
from gi.repository import Gdk

class MyTree(Gtk.TreeView):
    def __init__(self):
        Gtk.TreeView.__init__(self)

        # color
        color = Gdk.RGBA(221, 29, 157, 1)

        # model
        model = Gtk.TreeStore(int)
        for i in range(4):
            model.append(None, [i])
        self.set_model(model)

        # column
        ren = Gtk.CellRendererText(background_set=True,
                                   background_rgba=color)
        col = Gtk.TreeViewColumn('int', ren)
        col.add_attribute(ren, 'text', 0)
        self.append_column(col)


class MyWindow(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self)
        tree = MyTree()
        self.add(tree)
        self.connect('destroy', Gtk.main_quit)


if __name__ == '__main__':
    win = MyWindow()
    win.show_all()
    Gtk.main()

Solution

  • It was just a "bug". I used the Gdk.RGBA() the wrong way. It's parameter are valid only between 0.0 and 1.0.

    color = Gdk.RGBA(.2, .9, .15, 1)