How to style GTK+ with custom CSS?

user1502482 picture user1502482 · Jan 19, 2013 · Viewed 14k times · Source

can someone type up a simple example for styling a GTK+ widget with css? I could not figure out how to do it looking at the docs:

#include <gtk/gtk.h>
int main(int argc,char *argv[])
{
    gtk_init(&argc,&argv);
    GtkWidget *window;
    GtkWidget *button;
    GtkCssProvider *cssProvider;

    gtk_css_provider_load_from_path(cssProvider,"./gtkExample2.css",NULL);

    window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    button = gtk_button_new_with_label("GTK Button");

    gtk_style_context_add_provider(gtk_widget_get_style_context(window),cssProvider,GTK_STYLE_PROVIDER_PRIORITY_USER);

    g_signal_connect_swapped(window,"delete-event",G_CALLBACK(gtk_widget_destroy),window);

    gtk_container_set_border_width(GTK_CONTAINER(window),20);
    gtk_container_add(GTK_CONTAINER(window),button);

    gtk_widget_show(window);
    gtk_widget_show(button);

    gtk_main();
    return 1;
}

Answer

liberforce picture liberforce · Jan 21, 2013

Don't know a single thing about CSS styling in GTK3 (except that it often breaks as the developers prefer to fix things - to respect the CSS standards - than keep compatibility through versions).

However, I can tell you that this is wrong:

g_signal_connect_swapped(window,"delete-event",G_CALLBACK(gtk_widget_destroy),window);

What you really want it to stop GTK when the main window is closed. This is done like this:

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

Another remark is that you're calling

gtk_widget_show(window);
gtk_widget_show(button);

When the widgets tree has been completed (ie., you stopped adding widgets in the containers and the containers in the toplevel window), this can be simplified into:

gtk_widget_show_all(window);

Please also note that a program which worked should return 0 on success, and use non-zero values tor report errors.