Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

gtk

vala

gtk3

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;")
like image 715
5 revs Avatar asked Oct 25 '25 08:10

5 revs


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.

like image 111
Jens Mühlenhoff Avatar answered Oct 28 '25 04:10

Jens Mühlenhoff


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

like image 41
5 revs Avatar answered Oct 28 '25 03:10

5 revs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!