skip to Main Content

I’m using glade to design an application for a gtk4 program. I convert the xml code that’s gtk3 into gtk4 code because glade isn’t ported into gtk4. I tried connecting the window that I want to have the background color black to a class in a CSS file. It threw no errors at me but the background did not turn black. If there’s another way to alter window background colors in gtk4 that would be appreciated. I’ll list some code and some of glade.

styles.css
.window { background-color: #000000; }

main.c
`GtkCssProvider *provider;
GdkDisplay *display;

// Create a new CSS Provider
provider = gtk_css_provider_new();

// Load the CSS file named "style.css" from the current directory
gtk_css_provider_load_from_path(provider, "styles.css");

// Get the default display
display = gdk_display_get_default();

// Add provider for display in priority FALLBACK
gtk_style_context_add_provider_for_display(display, GTK_STYLE_PROVIDER(provider), GTK_STYLE_PROVIDER_PRIORITY_FALLBACK);

g_object_unref(provider);`

I tried using glade to change the color but did not find a property and I tried using CSS but for some reason it wouldn’t work but threw no errors.

2

Answers


  1. A GtkWindow is the element you want to style, it’s not a valid css class (IE: .window is invalid).

    Per GTK4 documentation on GtkWindow‘s CSS implementation. A class of .background is applied to instances of GtkWindow.

    https://docs.gtk.org/gtk4/class.Window.html#css-nodes

    You should be able to target the .background class/selector on GtkWindow itself or .background class globally

    // target .background class on all window instances
    window.background {
        background-color: red;
    }
    // OR .background class globally
    .background {
        background-color: green;
    }
    

    For CSS debugging GTK4’s interactive debugger is more than capable
    https://docs.gtk.org/gtk4/running.html

    If GTK4 has not be built with debugging enabled, you can query the GtkWidget for any CSS classes that are attached to it.

    GtkWindow *win = gtk_window_new();
    char **classes = gtk_widget_get_css_classes(GTK_WIDGET(win));
    
    for (int i=0; classes[i] != NULL; i++) {
        g_printerr("Class: %s n", classes[i]);
    }
    
    Login or Signup to reply.
  2. When testing this example, I came across the following:

    "Since GTK 4.12, GtkWindow uses the GTK_ACCESSIBLE_ROLE_APPLICATION role."

    GtkWidget *win = gtk_window_new();
    ...
    ...
    g_strfreev(classes);
    
    

    styles.css

    /* target .background class on all window instances */
    
    window.background {
         background-color: red;
    }
    
    /* OR .background class globally */
    
    .background {
        background-color: green;
    }
    
    

    The ones in question and in the 1. Answer specified scripts lead to errors or do not work. ( GTK 4.15.4 )

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search