Setting CSS attributes on individual widget instances

After the removal of the API for setting GtkStyleContexts on indivual widgets,

(See What good is GtkCssProvider without GtkStyleContext?
and Retiring Gtk.StyleContext)

How would one go about setting CSS attributes on individual GtkWidgets?

After all, in HTML one can set a style for an individual element, without involving CSS selectors (the style attribute for div tags).

My main problem concerns the use-cases, such as letting the user of my application specify the font of one specfic label, or color of a specific widget.

As I understand it, currently this would require me to globally add many selectors,
for each widget I want to modify the properties for, then set only that selector using gtk_style_context_add_provider_for_display.
As I understand it this would also include automatically having to generate CSS IDs or classes, that I then have to assign to the widget.

You add a CSS class and load a CSSProvider for the default GdkDisplay.

Adding a CSSProvider instance for a single widget is not recommended in GTK3, because unlike HTML, the CSSProvider on a widget does not cascade into the children of the widget.

Yes, that requires either generating CSS at run time and loading it up on the main style—after all, you can add multiple CSSProvider instances with different priorities—or it requires creating custom widgets that draw themselves without necessarily using the CSS state—e.g. a “button” that draws a rectangle with a color that is specified in a property, or a label that uses a specific PangoFontDescription.

1 Like

Thanks! I wanted to ensure I’m not missing anything.

For documentation purposes:
Currently, I’m generating names for the widgets based on their pointer.
(So to say in their “init” function).
I then use this name to generate a GtkCssProvider (by using the “#” in front of the name) with the new properties and store a reference to it inside my custom widget, for when the widget is destroyed.

Then I call gtk_style_context_add_provider_for_display, to apply this style.
In case the widget is being destroyed, gtk_style_context_remove_provider_for_display will be called.

So far that seems to work fine.

Would there be any major reason to prefer CSS classes over this approach (using names)?

Mainly that a widget name has no constraint imposed, or guarantee provided, by the toolkit, and it’s primarily meant to be used as a debugging tool.

1 Like

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