Sapnesh Naik
Sapnesh Naik

Reputation: 11636

How to add a sub-menu to a Gtk Menu

I have a Gtk menu in my application to which I want to add a submenu. I.e, when the main menu item is clicked, it should expand another list of menu items (A submenu).

I have tried some methods and they don't work. The documentation is sparse on this too.

Here is my code:

from gi.repository import Gtk

self.menu = Gtk.Menu()
item = Gtk.MenuItem()
item.set_label("Interfaces")
item.connect("activate", self.app.main_window.cb_show, '')
self.menu.append(item)

#Tried this way but it doesn't work.
# self.sub_menu = Gtk.Menu()
# self.menu.append(self.sub_menu)

item = Gtk.MenuItem()
item.set_label("Configuration")
item.connect("activate", self.app.config_window.cb_show, '')
self.menu.append(item)

self.menu.show_all()

How can I do this?

Update:

I tried using the gtk.MenuItem.set_submenu but it still does not work.

    self.menu = Gtk.Menu()

    item = Gtk.MenuItem()
    item.set_label("Units")
    self.menu.append(item)

    self.sub_menu = Gtk.Menu()
    submenu_item = Gtk.MenuItem()
    submenu_item.set_label("item text")
    item.set_submenu(self.sub_menu)

Upvotes: 1

Views: 1947

Answers (2)

no-one
no-one

Reputation: 174

A Menu can only be attached to a MenuItem and a MenuItem can only be added to a Menu or a Menubar.

The hierarchy you want is:

menubar
    menuitem (sort of a menu header; it's got the label, "File" for instance)
       menu (the actual file menu)
         menuitem (such as "New")
           menu (actually a submenu)
              item ("Text" for instance)

A Menu object can only be attached using set_submenu().

A MenuItem can only be attached using append().

Upvotes: 1

You need to:

  1. Create a Gtk.Menu representing submenu
  2. Create a Gtk.MenuItem in parent menu
  3. Attach submenu to menu item with gtk.MenuItem.set_submenu

Something like:

item = Gtk.MenuItem("Submenu")
self.menu.append(item)
self.sub_menu = Gtk.Menu()
item.set_submenu(self.sub_menu)

Upvotes: 2

Related Questions