deinonychusaur
deinonychusaur

Reputation: 7304

Setting Selected property of Row in TreeView dynamically in Gtk3 (python)

This is the same problem as in my previous question, but I moved to python3/gtk3 to be able to use a css for setting the basic properties.

From the python file:

self.w = Gtk.Window()
self.w.set_name("App")

I can use a css:

#App GtkTreeView row:selected {
    border-color: #000000;
    border-top-width: 1px;
    border-bottom-width: 1px;
    color: #000;
}

And easily permanently change the style of the selection. To me this means that I should be able to dynamically get access to the row-object and its style where I could set the bg for the Gtk.StateFlags.SELECTED.

I've tried a bunch of weird ways, e.g (where bg_color is a Gdk.Color that works fine for e.g. changing the style of a Label outside the TreeView).

        style=self.treeview.get_style_context()
        col = style.get_background_color(Gtk.StateFlags.SELECTED)
        col.alpha =  1.0
        col.blue = bg_color.blue
        col.red = bg_color.red
        col.green = bg_color.green

Or:

        style = self.treeview.get_style().copy()
        style.bg[Gtk.StateFlags.SELECTED] = bg_color
        self.treeview.set_style(style)

(produces error: style.bg[Gtk.StateFlags.SELECTED] = bg_color IndexError: list assignment index out of range)

etcetera...

So please, how do I find the way to dynamically change the selection effect depending on the normal-color of the row? Or in other words, how do I find my way to the object that actually holds the style-setting for the selection?

Upvotes: 0

Views: 2300

Answers (1)

deinonychusaur
deinonychusaur

Reputation: 7304

I had one last idea about how it could be done after posting which actually ended up working:

Reloading the css dynamically:

In the css I added a row leaving the value for the background open to dynamic substitution:

#App GtkTreeView row:selected {
    border-color: #400;
    border-top-width: 2px;
    border-bottom-width: 2px;
    background: {0};
    color: #000;
}

Then I loaded the css in python:

    screen = Gdk.Screen.get_default()
    self._css_provider = Gtk.CssProvider()
    css = open("notify_stack.css", 'rb')
    self._css = css.read()
    css.close()
    self._css_from = bytes("{0}".encode("utf8"))
    self._css_provider.load_from_data(self._css.replace(
        self._css_from,   
        bytes("#fff".encode("utf8"))))
    context = Gtk.StyleContext()
    context.add_provider_for_screen(screen, self._css_provider,
        Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)

Later in the callback for when a row is selected I put this row (data is my ListStore):

        self._css_provider.load_from_data(
            self._css.replace(self._css_from,
                bytes(data[rows[0]][self.BG_COLOR].encode("utf8"))))

It feels really brute, there must be a nicer way, but hey it actually worked.

Upvotes: 2

Related Questions