Menús emergentes

Normalmente, simplemente se añaden los Menus a la ventana, pero también pueden mostrarse temporalmente como resultado de una pulsación del botón del ratón. Por ejemplo, se puede mostrar un menú contextual cuando el usuario pulsa el botón derecho de su ratón.

Por ejemplo:

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

Para mostrar el menú contextual, use el método popup() del Gtk::Menu, proporcionándole el identificador del botón y el tiempo de activación, como los proporciona la señal button_press_event que, de todos modos, deberá manejar. Por ejemplo:

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