Install GtkEntry Font from Pango.FontDescription

I have a GtkEntry that I would like to allow users to style their choice of font (or the default system). I get a Pango description string, for example, "Monospace 10", to describe the font.

I am currently using override_font , which is deprecated in favor of CSS style.

I would like to at least try to do it “right”, but now it seems like it's a rather confusing and fragile workflow to get CSS from a Pango string. Here is an example from Github :

 def _get_editor_font_css(): """Return CSS for custom editor font.""" font_desc = Pango.FontDescription("monospace") if (gaupol.conf.editor.custom_font and gaupol.conf.editor.use_custom_font): font_desc = Pango.FontDescription(gaupol.conf.editor.custom_font) # They broke theming again with GTK+ 3.22. unit = "pt" if Gtk.check_version(3, 22, 0) is None else "px" css = """ .gaupol-custom-font {{ font-family: {family},monospace; font-size: {size}{unit}; font-weight: {weight}; }}""".format( family=font_desc.get_family().split(",")[0], size=int(round(font_desc.get_size() / Pango.SCALE)), unit=unit, weight=int(font_desc.get_weight())) css = css.replace("font-size: 0{unit};".format(unit=unit), "") css = css.replace("font-weight: 0;", "") css = "\n".join(filter(lambda x: x.strip(), css.splitlines())) return css 

After the CSS is in the line, I can create a CSSProvider and pass it into the add_provider() style context ( add_provider() , does this lead to an accumulation of CSS providers?).

All of this seems like a lot of work to return the font to the system, where it is likely to return right to Pango!

Is this really the right way?

+5
source share
1 answer

Use PangoContext .

 #include <gtkmm.h> int main(int argc, char* argv[]) { auto GtkApp = Gtk::Application::create(); Gtk::Window window; Gtk::Label label; label.set_label("asdasdfdfg dfgsdfg "); auto context = label.get_pango_context(); auto fontDescription = context->get_font_description(); fontDescription.set_family("Monospace"); fontDescription.set_absolute_size(10*Pango::SCALE); context->set_font_description(fontDescription); Gtk::Label label2; label2.set_label("xcv"); Gtk::VBox box; box.pack_start(label); box.pack_start(label2); window.add(box); window.show_all(); GtkApp->run(window); return 0; } 

Result:

Resulting window

+1
source

Source: https://habr.com/ru/post/1261629/