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