I am trying to add a custom coloring to the buttons and elements in a gtk4 GUI written in c language, from the docs I found the functions to load and set the css class name for the different widget that i am using but for some reason the styles are not applied and I get a window with a white background containing only a button with a white color
static void activate(GtkApplication * app, gpointer user_data)
{
GtkWidget * window;
GtkWidget * box;
GtkWidget * btn;
GtkWidget * txt;
GtkEntryBuffer * text;
GtkCssProvider * provider;
// create window
window = gtk_application_window_new(app);
gtk_window_set_title(GTK_WINDOW(window), "CSS example");
gtk_window_set_default_size(GTK_WINDOW(window), 800, 800);
// load css file
provider = gtk_css_provider_new ();
gtk_css_provider_load_from_file (provider, g_file_new_for_path ("styles.css"));
gtk_style_context_add_provider_for_display (gtk_widget_get_display (window),
GTK_STYLE_PROVIDER (provider),
GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);
// create the box and set the height and width
box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0);
gtk_widget_set_halign(box, GTK_ALIGN_CENTER);
gtk_widget_set_valign(box, GTK_ALIGN_CENTER);
// add box to main window
gtk_window_set_child(GTK_WINDOW(window),box);
// create text
text = gtk_entry_buffer_new("hello world", strlen("hello world"));
// create text widget
txt = gtk_text_new();
gtk_text_set_buffer(GTK_TEXT(txt), text);
gtk_window_set_child(GTK_WINDOW(window), txt);
// use css from file
gtk_widget_class_set_css_name(GTK_WIDGET_GET_CLASS (txt), "txt");
// adding button
btn = gtk_button_new_with_label("clickme");
g_signal_connect(btn, "clicked", G_CALLBACK(print_hello), NULL);
gtk_widget_class_set_css_name(GTK_WIDGET_GET_CLASS (btn), ".btn");
gtk_window_set_child(GTK_WINDOW(window), btn);
gtk_window_present(GTK_WINDOW(window));
}
here is styles.css
.txt
{
background-color: blue;
color: black;
}
.btn
{
color: blueviolet;
}
Why isn’t this code applying the css to the GUI application
2
Answers
Possibly you’ll have to follow a hint from GTK4 CssProvider doc: ‘To track errors while loading CSS, connect to the
GtkCssProvider::parsing-error
signal.’Do not use the period in setting the name or referring to it, as that interferes with css functionality.
So
gtk_widget_class_set_css_name(GTK_WIDGET_GET_CLASS (btn), ".btn");
should becomeand in your CSS file .btn should be just
Keep in mind
gtk_widget_set_name()
may be what you are looking for, as it does not compmletely remove the native css styling of the GtkWidget. The name you set here can be referred to in the CSS file with a hashtag.