I have a Gtk4 Gtk.Label.
I want to change it's color & size attribute programatically.
The markup way <span foreground='red' size='large'>
is easy to use.
But after some time, I want to remove these styles and make label colorless again.
I used my_lbl.label = my_lbl.get_text();
to unstylize it.
What is the PangoAttribute way to stylize a label?
How can I do this without markup labels?
Thanks!
Like NoDakker already replied, GTK re-uses CSS as a styling language instead of inventing its own.
What applications in your situation usually do is the following: they create a CSS file, e.g. "myapp.css", and load it using GtkCssProvider
's API, like gtk_css_provider_load_from_resource()
. Then they add it for the whole application
GdkDisplay *display = gdk_display_get_default ();
GtkCssProvider *provider = gtk_css_provider_new ();
gtk_css_provider_load_from_resource (provider, "/org/myapp/my-app.css");
gtk_style_context_add_provider_for_display (display,
GTK_STYLE_PROVIDER (provider),
GTK_STYLE_PROVIDER_PRIORITY_FALLBACK);
g_object_unref (provider);
or in Vala
var provider = new Gtk.CssProvider ();
provider.load_from_resource ("/org/myapp/my-app.css");
Gtk.StyleContext.add_provider_for_display (Gdk.Display.get_default (),
provider,
Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION);
Next, in the CSS file, they usually create CSS classes. For example, a common use case similar to yours is to mark something as "bad" or "error", so you would get something like
.error {
color: red;
}
Finally, in your code, you can then easily add or remove the class from a widget when needed, with gtk_widget_add_css_class
static void
validate_input (GtkWidget *input)
{
if (input_is_valid (input))
gtk_widget_remove_css_class (input, "error");
else
gtk_widget_add_css_class (input, "error");
}
or in Vala
private void validate_input (Gtk.Widget input) {
if (input_is_valid (input))
input.remove_css_class ("error");
else
input.add_css_class ("error");
}