我有一个GtkEntry,我想让用户选择字体(或系统默认).我最终得到了像“Monospace 10”这样的Pango描述字符串来描述字体. 我目前正在使用override_font,不赞成使用
... . . 我有一个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 fucking 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!
这真的是正确的方法吗?
.解决方法
. 使用 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;}
结果: