从Pango.FontDescription设置GtkEntry字体

Ind*_*oad 6 css gtk fonts styling gtk3

我有一个GtkEntry,我想让用户选择字体(或系统默认).我最终得到了像"Monospace 10"这样的Pango描述字符串来描述字体.

我目前正在使用override_font,不赞成使用CSS样式.

我想至少尝试"正确"地做到这一点,但现在从Pango字符串中获取CSS似乎是一个非常复杂和脆弱的工作流程.以下是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
Run Code Online (Sandbox Code Playgroud)

在CSS是一个字符串后,我可以创建一个CSSProvider并将其传递给样式上下文add_provider()(顺便说一下,这会最终累积CSS提供者吗?).

这一切似乎都需要很多工作才能将字体恢复到系统中,它可能会重新回到Pango!

这真的是正确的方法吗?

pan*_*oku 5

使用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;
}
Run Code Online (Sandbox Code Playgroud)

结果:

结果窗口