Search code examples
gtk3

GTK3 GtkCssProvider not working


Configuration is Ubunutu Server 18.04 LTS / Xorg / openbox / GTK3

I have been struggling to figure out why I can't get GtkCssProvider to work on even the most basic item. If have been working with different examples but here is one similar to another post.

Here is the app code that will display the label.

#include <gtk/gtk.h>

int main(int argc, char *argv[]) 
{
gtk_init(&argc, &argv);

GtkWidget *         window          = gtk_window_new(GTK_WINDOW_TOPLEVEL);
GtkWidget *         label           = gtk_label_new("Label 0123456789");
GtkCssProvider *    cssProvider     = gtk_css_provider_new();

g_signal_connect(window, "destroy", G_CALLBACK(gtk_main_quit), NULL);

if( gtk_css_provider_load_from_path(cssProvider, "csstest.css", NULL) )
{
     gtk_style_context_add_provider(gtk_widget_get_style_context(label),
                                        GTK_STYLE_PROVIDER(cssProvider),
                                        GTK_STYLE_PROVIDER_PRIORITY_USER);

    gtk_container_add(GTK_CONTAINER(window), label);
    gtk_widget_show_all(window);

    gtk_main();
}

return 0;
}

The .CSS file is simple:

GtkLabel {
    color: green;
}

The one post indicated that the gtk_style_context_add_provider() should be replaced with the gtk_style_context_add_provider_for_screen() call. Neither seems to have any effect. The label is appearing in the default style black on gray. So what is the trick to getting the Css style to be applied to the widget.

My requirement is to have different styles I can set to different widgets. I assume I can create some type of class construct in the Css that will allow me to apply different themes to the same widget via the gtk_style_context_add_provider() call. However I have not been able to figure that out either. I see how I can set a style in the Css for a specific named widget (via ID) but this appears to be only a predefined statc definition. Any suggestions on this would be helpful.


Solution

  • The CSS selector for a label is label, not GtkLabel:

    label {
        color: green;
    }
    

    See the GtkLabel API reference which lists the valid selectors.

    You should also use the GTK Inspector to test CSS fragments.

    You may also want to read the API reference for CSS handling in GTK, as well as the GtkStyleContext documentation.