Search code examples
pythongtkpygobjectgtk4

How do I use CSS in PyGObject with Gtk 4?


I'm trying to create a little application with PyGObject and Gtk 4.0. All of the other answers were for Gtk 3 or below, and trying them gave me an error.

I tried this piece of code:

css = '* { background-color: #f00; }' # temporary css
css_provider = Gtk.CssProvider()
css_provider.load_from_data(css)
context = Gtk.StyleContext()
screen = Gdk.Screen.get_default()
context.add_provider_for_screen(screen, css_provider,
                                Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)

But it threw out 'gi.repository.Gdk' object has no attribute 'Screen'.

Here are my imports if that matters:

import gi

gi.require_version('Gtk', '4.0')
from gi.repository import Gtk, Gdk

Solution

  • In GTK4, the property 'Screen' is no longer available. This also means the error message.

    At its place 'Display' is used.

    In the language I preferred C, this can look like this:

      GtkCssProvider *provider;
        GdkDisplay *display;
    
        provider = gtk_css_provider_new();
        display = gdk_display_get_default();
    
        gtk_style_context_add_provider_for_display(display, GTK_STYLE_PROVIDER(provider), GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);
    
        const gchar *css_file = "style.css";
    
        gtk_css_provider_load_from_file(provider, g_file_new_for_path(css_file));
    
        g_object_unref(provider);
    
    

    see also question and answer:

    https://stackoverflow.com/a/78749667/22768315

    Greetings