How can we add custom CSS styles to a GtkWidget?

The docs says that the Gtk.StyleContext object is deprecated and that there is no replacement, using vanilla Gtk (no Adwaita), how can we solve this? For example in Adwaita, the docs says that every app loads the GResource: <resource-base-path>/styles.css file automatically, and that we should use this mechanism, but for Gtk there is nothing similar.

Hi,

What is deprecated is to apply a CssProvider to the StyleContext of a single widget.

The API to load a provider for the whole app is not deprecated: Gtk.StyleContext.add_provider_for_display

For theming a widget, don’t use its StyleContext but give it a CSS class name instead that you can style at application level.

1 Like

As gwillems said, had an example lying around.

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

class Main:
  def __init__(self, app):
    self.window = Gtk.ApplicationWindow.new(app)
    _entry = Gtk.Entry.new()

    _css = """.custom-entry {background-color: #135; color: #e95;}"""
    _provider = Gtk.CssProvider.new()
    _provider.load_from_string(_css)
    Gtk.StyleContext.add_provider_for_display(self.window.get_display(), _provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)
    _entry.add_css_class("custom-entry")

    self.window.set_child(_entry)
    self.window.present()

app = Gtk.Application()
app.connect('activate', Main)
app.run(None)
1 Like

Just noticed a few days ago that you can keep the gtkcssprovider alive and use it multiple times. Every time you run load_from_string it updates the theme globally. This is crazy efficient and works really well, I was implementing setting font-size in a gtktextview. Getting the system default font-size was not that easy though. Had to do some pretty serious digging and trial and error but in the end I managed to do it by using some pango voodoo. I would not exactly call it user friendly though. And what to do if you ever need some other default values from the currently used theme?? There should be a function like gtk_style_context_get_css_property(“textview”, “font-size”) so that you can easily inspect these default values. I wonder if that would be hard to implement?