Correct way to set style without using StyleContext

Sorry in advance because I know this has come up before, but I can’t figure it out in the context of Vala. GtkStyleContext is deprecated. My understanding is that gtk_style_context_add_provider_for_display() was moved from gtkstylecontext.h to gtkstyleprovider.h and is now a free function rather than a method on StyleContext. Anyway, I’m using the following to set styles.

// application.vala
            Gtk.StyleContext.add_provider_for_display (Gdk.Display.get_default (), provider, Gtk.STYLE_PROVIDER_PRIORITY_USER);
// and in tab.vala
        public void set_css_font (string css) {
            var provider = new Gtk.CssProvider ();
            provider.load_from_data (css.data);
            var ctx = this.sourceview.get_style_context ();
            ctx.add_provider (provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION);
        }

Both cases are throwing warnings about the deprecation. What I’m not seeing anywhere in the Vala docs is another way to add a provider that bypasses StyleContext, so I don’t know how to update my code to deal with the deprecation.

The idea is you would only use add_provider_for_display(), not add_provider() on individual widgets’ contexts. So, rather than adding a provider to a widget - add a provider to the overall display, but selecting on a particular CSS class, and add that CSS class using widget.add_css_class(). If you had been adding different styles to different widgets, add a different class to each, then add a selector for each class to the display (once, or individually, doesn’t matter). I have used this to replace per-widget styles in two places and it’s worked fine.

I think I get it now. I replaced add_provider with add_provider_for_display in the second case above and am able to do set it once for the entire program rather than looping through each affected widget, which is a nice cleanup.

I still get a warning about StyleContext being deprecated, but I don’t think that’s my code actually being “wrong” now. I’m not getting an individual style context, just calling the function, so I think Vala might be throwing an unneeded warning in this case?

It sounds like it. The methods left ‘on’ StyleContext that are not now deprecated are not really part of StyleContext at all, and in particular are not instance methods. My guess is the Vala bindings, having put them ‘in’ StyleContext as static methods, are hitting the warning about the entire class being deprecated. I don’t know if they have a way to avoid that; hopefully someone with more introspection knowlege can comment.

See also: link

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.