CSS styles are not being applied on a Gtk widget

Question:

Another user here on StackOverflow has some problems styling his Gtk application with CSS. I found a solution for part of the problems, but for one I don’t know anything. The original post is with C code, but the following Python Minimal Reproducible Example has the same problem:

#!/usr/bin/python3
#-*-coding: utf-8-*-

import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk

win = Gtk.Window()
win.connect("destroy", lambda _: Gtk.main_quit())
box = Gtk.VBox()
win.add(box)
button = Gtk.Button("Button")
prov = Gtk.CssProvider.new()
prov.load_from_data("""
button {
    color: red;
    background-color: green;
    margin: 30px;
}
""".encode())
ctx = win.get_style_context()
ctx.add_provider(prov, 1000)
box.add(button)
win.show_all()
Gtk.main()

The problem is, the margins are not showing, nor the font and background color, whereas they are correctly shown in this example:

#!/usr/bin/python3
#-*-coding: utf-8-*-

import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk

win = Gtk.Window()
win.connect("destroy", lambda _: Gtk.main_quit())
box = Gtk.VBox()
win.add(box)
button = Gtk.Button("Button")
prov = Gtk.CssProvider.new()
prov.load_from_data("""
* {
    color: red;
    background-color: green;
    margin: 30px;
}
""".encode())
ctx = button.get_style_context()
ctx.add_provider(prov, 1000)
box.add(button)
win.show_all()
Gtk.main()

This led me to the conclusion that the selector button somehow does not do what I want and expect. Why is the selector wrong, and which would be the right selector to select the button ?

Asked By: TheEagle

||

Answers:

Note what the documentation for gtk_style_context_add_provider() says:

Note that a style provider added by this function only affects the style of the widget to which context belongs. If you want to affect the style of all widgets, use gtk_style_context_add_provider_for_screen().

The styles apply to that widget only, not the widget and its children. The preferred way to style GTK applications is to create one stylesheet for the whole application, then use gtk_style_context_add_class to add style classes to individual widgets.

Answered By: James Westman
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.