Search code examples
csspython-3.xcss-selectorsgtkmargins

CSS margins not being applied to a Gtk textview


I have the following minimal reproducible example code:

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

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

win = Gtk.Window()
win.connect("destroy", lambda _: Gtk.main_quit())
box = Gtk.VBox()
win.add(box)
view = Gtk.TextView()
buf = view.get_buffer()
buf.set_text("Hello, this is some text !")
prov = Gtk.CssProvider.new()
prov.load_from_data("""
text {
    color: red;
    background-color: yellow;
    margin: 30px;
}
""".encode())
ctx = win.get_style_context()
ctx.add_provider_for_screen(Gdk.Screen.get_default(), prov, 800)
box.add(view)
win.show_all()
Gtk.main()

The font and background gets colored, but the margins are not applied. Why, and what would fix it ?

Note : When I apply the margins to the box with following CSS

text {
    color: red;
    background-color: yellow;
}
box {
    margin: 30px;
}

or add `python view.set("margin-left", 10) view.set("margin_right, 10) ...

the margins are applied. So the cause must be a wrong selector ...

Solution

  • There are not css nodes to margins in textview. You need to use functions like set_left_margin(left_margin) set_right_margin(right_margin) or set_justification(justification).

    usage

    Gtk.TextView().set_left_margin(10) /*value is in pixels*/
    

    CSS nodes

    textview.view
    ├── border.top
    ├── border.left
    ├── text
    │   ╰── [selection]
    ├── border.right
    ├── border.bottom
    ╰── [window.popup]
    

    css nodes only appears in c docs c documentation

    this is the py documentation py documentation