I am trying to add colors to the 2 buttons in gtk4 GUI written in c language. From the docs, I have found functions to load and set the css class name for 2 buttons. But for some reason the styles are not applied to my GUI, and I only get a window with a white background and white buttons.
#include <gtk/gtk.h>
static void on_active(GtkApplication *app){
// Create a new window and grid
GtkWidget *s_window = gtk_application_window_new (app);
gtk_window_set_default_size (GTK_WINDOW (s_window), 800, 800);
GtkWidget *s_grid = gtk_grid_new();
gtk_grid_set_column_spacing(GTK_GRID(s_grid), 15);
gtk_grid_set_row_spacing(GTK_GRID(s_grid), 15);
gtk_widget_set_halign (s_grid, GTK_ALIGN_CENTER);
gtk_widget_set_valign (s_grid, GTK_ALIGN_CENTER);
gtk_widget_set_hexpand (s_grid, TRUE);
// Create provider for styling
GtkCssProvider *cssProvider = gtk_css_provider_new();
gtk_css_provider_load_from_file(cssProvider, g_file_new_for_path ("styles.css"));
gtk_style_context_add_provider_for_display(gdk_display_get_default(), GTK_STYLE_PROVIDER(cssProvider),
GTK_STYLE_PROVIDER_PRIORITY_USER);
gtk_widget_set_visible(GTK_WIDGET(s_window), TRUE);
// Create label
GtkWidget *label = gtk_label_new("Hello World!");
// Create buttons: PvP and PvAI
GtkWidget *button1 = gtk_button_new_with_label ("1");
gtk_widget_class_set_css_name(GTK_WIDGET_GET_CLASS(button1), "btn1");
GtkWidget *button2 = gtk_button_new_with_label ("2");
gtk_widget_class_set_css_name(GTK_WIDGET_GET_CLASS(button2), "btn2");
// Set button size and position
gtk_grid_attach(GTK_GRID(s_grid), label, 50, 0, 40, 10);
gtk_grid_attach(GTK_GRID(s_grid), button1, 50, 50, 40, 10);
gtk_grid_attach(GTK_GRID(s_grid), button2, 50, 125, 40, 10);
gtk_window_set_child (GTK_WINDOW (s_window), s_grid);
gtk_window_present (GTK_WINDOW (s_window));
}
int main (int argc, char *argv[]) {
// Create a new application
GtkApplication *app = gtk_application_new ("com.example.GtkApplication", G_APPLICATION_FLAGS_NONE);
g_signal_connect (app, "activate", G_CALLBACK (on_active), NULL);
return g_application_run (G_APPLICATION (app), argc, argv);
}
here is the styles.css
btn1 {
color: green;
}
btn2 {
color: blueviolet;
}
Why isn't this code applying the css to the GUI application?
gtk_widget_class_set_css_name()
is used when you are creating a new derived widget class. You can usegtk_widget_add_css_class(widget, "some-class")
to add a new CSS class to an existing widget. And to refer the class you can use.some-class
in your CSS.The modified version of your code would look like this:
And the CSS file
styles.css
: