Search code examples
csscgtkgtk3

CSS in GTK+ doesn't work


GtkCssProvider *provider;
GdkDisplay *display;
GdkScreen *screen;

provider = gtk_css_provider_new ();
display = gdk_display_get_default ();
screen = gdk_display_get_default_screen (display);
gtk_style_context_add_provider_for_screen (screen, GTK_STYLE_PROVIDER (provider), GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);

const gchar *myCssFile = "style.css";
GError *error = 0;

gtk_css_provider_load_from_file(provider, g_file_new_for_path(myCssFile), &error);
g_object_unref (provider);

This doesn't work, but when I change "style.css" to the full path, everything works great. What am I doing wrong?


Solution

  • Please, do the bare minimum: check your error codes, and process them.

    const gchar *css_relpath = "style.css";
    GError *error = NULL;
    GFile *css_file = g_file_new_for_path(css_relpath); 
    
    gtk_css_provider_load_from_file(provider, css_file, &error);
    if (error)
    {
        // Display a warning if the stylesheet is not loaded
        g_warning ("%s", error->message);
    
        // Free the memory allocated for the error
        // and acknowledge the error has been processed
        g_clear_error (&error);
    }
    g_object_unref (css_file);