gavr
gavr

Reputation: 945

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

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;")

Upvotes: 4

Views: 956

Answers (3)

scrutari
scrutari

Reputation: 1618

The answer for Gtk-4 (based on the Jens's answer above):

private void apply_css(Gtk.ApplicationWindow window) {
    var provider = new Gtk.CssProvider();
    provider.load_from_resource("/org/example/app/style.css");
    Gtk.StyleContext.add_provider_for_display(
        window.display,  // use display instead of screen
        provider,
        Gtk.STYLE_PROVIDER_PRIORITY_USER);
}

Upvotes: 1

gavr
gavr

Reputation: 945

For anyone who is reading this I have posted both examples with and without file to Git https://gitlab.com/gavr123456789/vala-css-examples/tree/master

Upvotes: 1

Jens Mühlenhoff
Jens Mühlenhoff

Reputation: 14873

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.

Upvotes: 2

Related Questions