Popup Menus

Menus are normally just added to a window, but they can also be displayed temporarily as the result of a mouse button click. For instance, a context menu might be displayed when the user clicks their right mouse button.

For instance:

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);

Glib::RefPtr<Glib::Object> object = m_refBuilder->get_object("menu-examplepopup");
Glib::RefPtr<Gio::Menu> gmenu = Glib::RefPtr<Gio::Menu>::cast_dynamic(object);
m_pMenuPopup = new Gtk::Menu(gmenu);

To show the popup menu, use Gtk::Menu's popup() method, providing the button identifier and the time of activation, as provided by the button_press_event signal, which you will need to handle anyway. For instance:

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;
}