Search code examples
gtk3vala

How to display a context menu on Gtk.TreeView right click?


I am trying to show a custom context menu when I right click on a row in a TreeView.

treeView.button_press_event.connect ((event) => {
    if (event.type == EventType.BUTTON_PRESS && event.button == 3) {
        Gtk.Menu menu = new Gtk.Menu ();
        Gtk.MenuItem menu_item = new Gtk.MenuItem.with_label ("Add file");
        menu.add (menu_item);
        menu.show ();
    }
});

It doesn't show anything. If I debug a message there I can see the block is being executed when right clicking on a row in the TreeView. I tried show_all () with no success either. popup_at_pointer () is available only on Gtk+ 3.22 and later versions. I am using Gtk+ 3.18.

Is there any way to show a custom menu when right clicking a row on a Gtk.TreeView?


Solution

  • Found out one has to attach the Gtk.Menu to a widget using attach_to_widget () and then use show_all () before calling the only method to show the menu available in Gtk+ 3.18 which is popup (...). popup (...) is deprecated since Gtk+ 3.22, but it is the only method available in Gtk+ 3.18.

    Here is the code

    treeView.button_press_event.connect ((event) => {
        if (event.type == EventType.BUTTON_PRESS && event.button == 3) {
            Gtk.Menu menu = new Gtk.Menu ();
            Gtk.MenuItem menu_item = new Gtk.MenuItem.with_label ("Add file");
            menu.attach_to_widget (treeView, null);
            menu.add (menu_item);
            menu.show_all ();
            menu.popup (null, null, null, event.button, event.time);
        }
    });
    

    Relevant source: https://developer.gnome.org/gtkmm-tutorial/stable/sec-treeview-examples.html.en#treeview-popup-menu-example