I am learning GTK4 from scratch, using GTKBuilder XML to construct objects and CSS to add style information from a file using:
const char cssPath[] = "/a/path/that/is/confirmed/to_be/working.css";
GtkCssProvider * cssProvider = gtk_css_provider_new();
gtk_css_provider_load_from_path(cssProvider, cssPath);
gtk_style_context_add_provider_for_display(gdk_display_get_default(), GTK_STYLE_PROVIDER(cssProvider), GTK_STYLE_PROVIDER_PRIORITY_USER);
When I use a generic CSS selector my style changes take affect, like so:
box { background-color: white; }
/* box goes white as expected */
but when I try and target a specific object using it's id="myBox" XML attribute, it doesn't work:
box#myBox { background-color: white; }
/* no colour change happens */
or
#myBox { background-color: white; }
/* no colour change happens here either */
The relevant section from my XML .ui file is:
<object class="GtkBox" id="myBox">
<property name="halign">GTK_ALIGN_CENTER</property>
<child>
<object class="GtkLabel" id="centreLabel">
<property name="single-line-mode">true</property>
<property name="xalign">0</property>
<property name="yalign">0.5</property>
</object>
</child>
</object>
Maybe I'm misunderstanding the way CSS selectors work, relative to the objects instantiated using GtkBuilder? I've read the docs, so I would appreciate any help anyone can offer here!
Cheers.
CodePudding user response:
Using the name
property in the UI file, you can set the specific Css name that you want your <object>
to have. In order for this custom name to be used, you also need to put #
in front of the myBox
name in the Css, which you have already done.
To define the name
property, simply add this line under your Box object in your UI file:
<property name="name">myBox</property>
Here is what your UI file should look like:
<object class="GtkBox" id="myBox">
<property name="halign">GTK_ALIGN_CENTER</property>
<property name="name">myBox</property>
<child>
<object class="GtkLabel" id="centreLabel">
<property name="single-line-mode">true</property>
<property name="xalign">0</property>
<property name="yalign">0.5</property>
</object>
</child>
</object>
And here is what the Css should look like (you already had it this way):
#myBox { background-color: white; }