从Pango.FontDescription设置GtkEntry字体

问题描述 投票:6回答:1

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

我目前正在使用override_font,它被弃用以支持CSS样式。

我想至少尝试“正确”地做到这一点,但现在从Pango字符串中获取CSS似乎是一个非常复杂和脆弱的工作流程。这是一个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

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

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

这真的是正确的方法吗?

css fonts gtk gtk3 styling
1个回答
3
投票

使用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;
}

结果:

Resulting window

© www.soinside.com 2019 - 2024. All rights reserved.