一个应用菜单

就像窗口模板,在一个ui file 中我们指定了我们的应用程序菜单,然后作为资源向二进制文件中添加。

  1. <?xml version="1.0"?>
  2. <interface>
  3. <!-- interface-requires gtk+ 3.0 -->
  4. <menu id="appmenu">
  5. <section>
  6. <item>
  7. <attribute name="label" translatable="yes">_Preferences</attribute>
  8. <attribute name="action">app.preferences</attribute>
  9. </item>
  10. </section>
  11. <section>
  12. <item>
  13. <attribute name="label" translatable="yes">_Quit</attribute>
  14. <attribute name="action">app.quit</attribute>
  15. </item>
  16. </section>
  17. </menu>
  18. </interface>

为了关联应用程序和应用菜单,我们必须调用gtk_application_set_app_menu()。y因为应用菜单被活动的GActions激活,所以必须为应用程序增加一个合适的设定。

所有这些任务最好在startup()函数中做完,因为startup()函数被保证在每个应用程序实例中只被调用一次。

  1. ...
  2. static void
  3. preferences_activated (GSimpleAction *action,
  4. GVariant *parameter,
  5. gpointer app)
  6. {
  7. }
  8. static void
  9. quit_activated (GSimpleAction *action,
  10. GVariant *parameter,
  11. gpointer app)
  12. {
  13. g_application_quit (G_APPLICATION (app));
  14. }
  15. static GActionEntry app_entries[] =
  16. {
  17. { "preferences", preferences_activated, NULL, NULL, NULL },
  18. { "quit", quit_activated, NULL, NULL, NULL }
  19. };
  20. static void
  21. example_app_startup (GApplication *app)
  22. {
  23. GtkBuilder *builder;
  24. GMenuModel *app_menu;
  25. const gchar *quit_accels[2] = { "<Ctrl>Q", NULL };
  26. G_APPLICATION_CLASS (example_app_parent_class)->startup (app);
  27. g_action_map_add_action_entries (G_ACTION_MAP (app),
  28. app_entries, G_N_ELEMENTS (app_entries),
  29. app);
  30. gtk_application_set_accels_for_action (GTK_APPLICATION (app),
  31. "app.quit",
  32. quit_accels);
  33. builder = gtk_builder_new_from_resource ("/org/gtk/exampleapp/app-menu.ui");
  34. app_menu = G_MENU_MODEL (gtk_builder_get_object (builder, "appmenu"));
  35. gtk_application_set_app_menu (GTK_APPLICATION (app), app_menu);
  36. g_object_unref (builder);
  37. }
  38. static void
  39. example_app_class_init (ExampleAppClass *class)
  40. {
  41. G_APPLICATION_CLASS (class)->startup = example_app_startup;
  42. ...
  43. }
  44. ...

(full source)

菜单首选项如今并不能作任何事,但是Quit菜单选项的功能是正常的。注意它也可以被快捷键Ctrl-Q激活。这个快捷方式已经在gtk_application_set_accels_for_action()中被添加。

我们的应用菜单如下:

getting-started-app4.png