How to change a font for label in gtkmm

Hi all,
I’ve just started to try GTKmm 4 with a simple example.
I need to change the font of a label using an external ttf file.
Googling around I found this lines of c++ code:

    // Load custom font
    auto css_provider = Gtk::CssProvider::create();
    css_provider->load_from_data(
        "@font-face {"
        "   font-family: 'DSEG7';"
        "   src: url('m06-quadra.ttf');"
        "}"
        "window { background-color: #000000; }"
        "label { color: #FFFFFF; }"
        "button { background: blue; color: white; }"
    );

The problem is that this code generates a warning:

(gtkSpeed:28095): Gtk-WARNING **: 17:53:29.571: Theme parser error: <data>:1:1-11: Unknown @ rule

and, of course, it doesn’t work.
Please, how can I solve it?
Thanks!

Hi,

@font-face is not supported by Gtk (see CSS reference here and here).

The available fonts are reported by Pango, and their detection is not generic, it depends on each platform’s backend (Linux, Windows, …) so giving a font file name directly from CSS is anyway impossible (see this issue for details).

If you don’t care about portability, you may try to load the TTF manually with native APIs (probably fontconfig on Linux), then from the CSS just give the family name:

label {
    font-family: DSEG7;
}

pango recently added pango_font_map_add_file() (still not implemented for macOS, but works on Linux and Windows).

If you just want to set a font on a specific label, it is easier to use gtk_label_set_attributes().

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.