Setting GtkEntry font from Pango.FontDescription

爷,独闯天下 提交于 2021-02-08 13:35:14

问题


I have a GtkEntry that's I'd like to allow users to style with their choice of font (or system default). I end up with a Pango description string like "Monospace 10" to describe the font.

I'm currently using override_font, which is deprecated in favour of CSS styling.

I'd like to at least attempt to do it "right", but it seems like a pretty convoluted and fragile workflow now to get the CSS from the Pango string. Here's 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 a string, then I can create a CSSProvider and pass that to the style context's add_provider() (does this end up accumulating CSS providers, by the way?).

This all seems like a lot of work to get the font back into the system, where it presumably goes right back into Pango!

Is this really the right way to go about it?


回答1:


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:



来源:https://stackoverflow.com/questions/41257101/setting-gtkentry-font-from-pango-fontdescription

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!