菜单和工具栏
接下来你应该创建一个Gtk::Builder。此时使用Gtk::Application::set_accel_for_action()告诉应用程序响应键盘快捷键也是一个好主意。
例如:
m_refBuilder = Gtk::Builder::create(); app->set_accel_for_action("example.new", "<Primary>n"); app->set_accel_for_action("example.quit", "<Primary>q"); app->set_accel_for_action("example.copy", "<Primary>c"); app->set_accel_for_action("example.paste", "<Primary>v");
如果你的主窗口是由ApplicationWindow派生而来的,并且你使用Gtk::Application::set_menubar()实例化了菜单栏,则你不需要调用set_accel_for_action()。有关示例参见:应用程序菜单和主菜单示例。
然后,你可以定义菜单和工具栏的实际可见布局,并将这个UI布局添加到Builder。这个"UI字符串"使用XML格式,你应该在其中使用你已经创建的动作的名称。例如:
Glib::ustring ui_info = "<interface>" " <menu id='menubar'>" " <submenu>" " <attribute name='label' translatable='yes'>_File</attribute>" " <section>" " <item>" " <attribute name='label' translatable='yes'>_New</attribute>" " <attribute name='action'>example.new</attribute>" " <attribute name='accel'><Primary>n</attribute>" " </item>" " </section>" " <section>" " <item>" " <attribute name='label' translatable='yes'>_Quit</attribute>" " <attribute name='action'>example.quit</attribute>" " <attribute name='accel'><Primary>q</attribute>" " </item>" " </section>" " </submenu>" " <submenu>" " <attribute name='label' translatable='yes'>_Edit</attribute>" " <item>" " <attribute name='label' translatable='yes'>_Copy</attribute>" " <attribute name='action'>example.copy</attribute>" " <attribute name='accel'><Primary>c</attribute>" " </item>" " <item>" " <attribute name='label' translatable='yes'>_Paste</attribute>" " <attribute name='action'>example.paste</attribute>" " <attribute name='accel'><Primary>v</attribute>" " </item>" " </submenu>" " </menu>" "</interface>"; m_refBuilder->add_from_string(ui_info); m_refBuilder->add_from_resource("/toolbar/toolbar.glade");
这里我们指定菜单项的名称,因为用户可以在菜单中看到它们。因此你应该添加translatable='yes'使这些的字符串可以被翻译。
要实例化Gtk::MenuBar和Gtk::Toolbar并可以实际显示他们,应该使用Builder::get_object()和Builder::get_widget()方法,然后将部件加入容器中。例如:
auto gmenu = m_refBuilder->get_object<Gio::Menu>("menubar"); auto pMenuBar = Gtk::make_managed<Gtk::MenuBar>(gmenu); m_Box.append(*pMenuBar); auto toolbar = m_refBuilder->get_widget<Gtk::Toolbar>("toolbar"); m_Box.append(*toolbar);