弹出菜单
Menus通常将直接被加入到窗口中,但也可以通过鼠标单击来临时显示他们。例如当用户单击鼠标右键的时候,可能需要显示上下文菜单。
例如:
Glib::ustring ui_info = "<interface>" " <menu id='menu-examplepopup'>" " <section>" " <item>" " <attribute name='label' translatable='yes'>Edit</attribute>" " <attribute name='action'>examplepopup.edit</attribute>" " </item>" " <item>" " <attribute name='label' translatable='yes'>Process</attribute>" " <attribute name='action'>examplepopup.process</attribute>" " </item>" " <item>" " <attribute name='label' translatable='yes'>Remove</attribute>" " <attribute name='action'>examplepopup.remove</attribute>" " </item>" " </section>" " </menu>" "</interface>"; m_refBuilder->add_from_string(ui_info); auto gmenu = m_refBuilder->get_object<Gio::Menu>("menu-examplepopup"); m_pMenuPopup = std::make_unique<Gtk::Menu>(gmenu);
要显示弹出菜单,请使用Gtk::Menu的popup()方法,无论如何你都需要处理由button_press_event信号提供的激活时机(鼠标单双三击、按下还是释放)和按钮标识(哪个鼠标按键)。例如:
bool ExampleWindow::on_button_press_event(GdkEventButton* event) { if( (event->type == GDK_BUTTON_PRESS) && (event->button == 3) ) { if(!m_pMenuPopup->get_attach_widget()) m_pMenuPopup->attach_to_widget(*this); m_pMenuPopup->popup(event->button, event->time); return true; //It has been handled. } else return false; }