CSS from code? How to use CSS decoration directly from Vala?

Viewed 518

How to use CSS customization directly from Vala? Not like in this example with file. Let's say I want the button to turn red by clicking on it, without using an external css file, as this action is too simple to create a css file with a single field.

I mean smth like this:

label.set_styleSheet("font-size: 17px;")
2 Answers

You still have to create a CssProvider, like in the code you linked to:

var screen = this.get_screen ();
var css_provider = new Gtk.CssProvider();

You can call load_from_data () instead of load_from_path () to load it from a string in memory instead of a file:

https://valadoc.org/gtk+-3.0/Gtk.CssProvider.load_from_data.html

css_provider.load_from_data(".my_class { font-size: 17px; }");
Gtk.StyleContext.add_provider_for_screen(screen, css_provider, Gtk.STYLE_PROVIDER_PRIORITY_USER);

When the CSS provider has loaded the custom styles to be used, you can manipulate every Gtk+ widget with get_style_context ().

The style context has methods to add, remove and query a class, etc.

https://valadoc.org/gtk+-3.0/Gtk.StyleContext.html

label.get_style_context().add_class("my_class");

Since you only have to setup the style provider once, I don't think it is too much overhead.

Related