我正在用gtkmm3在c++中编程。我想在程序中更改某些字体。我在gtkmm文档和gtk + documentaion中都阅读了有关CssStyleProvider,StyleContext的所有信息,但我无法使其正常运行,也找不到任何有关此的教程。我想那样

Glib::ustring data;
data="GtkMenuBar, GtkMenuItem {font-name: Sans 6}"; /*tried with semi-colon, too*/
Glib::RefPtr<Gtk::CssProvider> asd = Gtk::CssProvider::create();
Glib::RefPtr<Gtk::StyleContext> asd2 = Gtk::StyleContext::create();
asd->load_from_data(data);
asd2->add_provider(asd, 0); /*also tried different priorities*/

也这样尝试过
Glib::ustring data;
data="GtkMenuBar, GtkMenuItem {font-name: Sans 6}"; /*tried with semi-colon, too*/
Glib::RefPtr<Gtk::CssProvider> asd = Gtk::CssProvider::create();
Glib::RefPtr<Gdk::Screen> screen;
Glib::RefPtr<Gtk::StyleContext> asd2 = Gtk::StyleContext::create();
asd->load_from_data(data);
(mainWindow.get())->get_property("screen", screen);
asd2->add_provider(screen, asd, 0); /*also tried different priorities*/

我在运行主窗口之前和之后都尝试了这些,但是我没有运气。任何帮助表示赞赏。

最佳答案

您是否还尝试过使用GTK_STYLE_PROVIDER_PRIORITY_APPLICATION宏而不是0?

asd2->add_provider(screen, asd, macro GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);

适用于我,也适用于Windows。

例:
int main(int argc, char **argv) {

  Main app(argc, argv);
  Glib::ustring data = "GtkLabel {color: #ff00ea;font: Comic Sans MS 12}";
  auto css = CssProvider::create();
  if(not css->load_from_data(data)) {
      cerr << "Failed to load css\n";
      std::exit(1);
  }
  Label label("test");
  Window win;
  auto screen = Gdk::Screen::get_default();
  auto ctx = label.get_style_context();
  ctx->add_provider_for_screen(screen, css, GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);
  win.add(label);
  win.show_all();

  app.run(win);
  return 0;
}

09-05 10:10