Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to style a GtkLabel with CSS?

Tags:

c

css

gtk

gtk3

I'm trying to use CSS to style a GtkLabel. I would like to change the color and font size of the label. Here is my C code:

#include <gtk/gtk.h>

int main(int argc, char *argv[]) {
    gtk_init(&argc, &argv);

    GtkWidget *window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    GtkWidget *label = gtk_label_new("Label");

    GtkCssProvider *cssProvider = gtk_css_provider_new();
    gtk_css_provider_load_from_path(cssProvider, "theme.css", NULL);
    gtk_style_context_add_provider(gtk_widget_get_style_context(window),
                                   GTK_STYLE_PROVIDER(cssProvider),
                                   GTK_STYLE_PROVIDER_PRIORITY_USER);

    g_signal_connect(window, "destroy", G_CALLBACK(gtk_main_quit), NULL);
    gtk_container_add(GTK_CONTAINER(window), label);
    gtk_widget_show_all(window);

    gtk_main();
}

Here is my CSS in theme.css, currently this should only change the font color:

GtkLabel {
    color: green;
}

I compile with:

gcc `pkg-config gtk+-3.0 --cflags` test.c -o test `pkg-config --libs gtk+-3.0`

However, when I run the code I get black text. If I change theme.css to use a widget name or CSS class instead of GtkLabel, it still doesn't work. However, if I use * instead of GtkLabel, it works (although I don't want this to apply to everything). This means that the C code should be correct and something is wrong with the CSS.

like image 648
gsingh2011 Avatar asked Jun 11 '15 21:06

gsingh2011


1 Answers

Currently, CSS providers are not inherited to the children style contexts. So you need to add the CSS provider to the screen using gtk_style_context_add_provider_for_screen()

Try changing

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

to

gtk_style_context_add_provider_for_screen(gdk_screen_get_default(),
                                          GTK_STYLE_PROVIDER(cssProvider),
                                          GTK_STYLE_PROVIDER_PRIORITY_USER);

I don't think gtk supports multiple screens these days, but gtk_widget_get_screen() could be used to replace gdk_screen_get_default().

like image 183
Christian Hergert Avatar answered Sep 19 '22 10:09

Christian Hergert