1

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)
2
  • You don't add submenu_item to self.sub_menu. Commented Oct 17, 2018 at 9:41
  • @el.pescado thanks! works now :) Commented Oct 17, 2018 at 10:18

2 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

1 Comment

@SapneshNaik I am using Gtk#, but this basic idea of setting a Menu to SubMenu worked. If it does not work, why have you marked it as the answer. If it worked, you need to remove the comment above.
1

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().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.