Here is my code:
Code:
def __init__(self):
menuBar = self.addMenus() # returns MenuBar object
self.window.add(self.mainHBox)
# add to mainHBox
self.mainHBox.pack_start(menuBar)
def addMenus(self):
# This will hold the menu items
fileMenuList = gtk.Menu()
helpMenuList = gtk.Menu()
fileMenu = [gtk.MenuItem("File"), gtk.MenuItem("Quit")]
helpMenu = [gtk.MenuItem("Help"), gtk.MenuItem("About")]
fileMenu[0].set_submenu(fileMenuList)
fileMenuList.append(fileMenu[1])
helpMenu[0].set_submenu(helpMenuList)
helpMenuList.append(helpMenu[1])
menuBar = gtk.MenuBar()
menuBar.append(fileMenu[0])
menuBar.append(helpMenu[0])
return menuBar # return MenuBar object
So, let's give context to the addMenus() method. And the above code is indeed in Python but the GTK+ API remains the same for whatever language you use with GTK+, whether C, PHP(GTK), etc.
Code:
fileMenuList = gtk.Menu()
helpMenuList = gtk.Menu()
This is for the menu list (i.e. what appears in the File and Help menu options.
Code:
fileMenu = [gtk.MenuItem("File"), gtk.MenuItem("Quit")]
helpMenu = [gtk.MenuItem("Help"), gtk.MenuItem("About")]
We create the menu items for each individual menu item. Specifying what is a menu option and a specific menu item within a menu option (i.e. File is the menu option and Quit is the menu item) will be done later.
Code:
fileMenu[0].set_submenu(fileMenuList)
fileMenuList.append(fileMenu[1])
helpMenu[0].set_submenu(helpMenuList)
helpMenuList.append(helpMenu[1])
If you didn't notice above, we are using lists (which are like arrays), so we are specifying the sub menu for the "File" file menu item as the fileMenuList (the GtkMenu class), and likewise with the Help menu option.
Then each Menu class is being appended the relevant MenuItem.
Code:
menuBar = gtk.MenuBar()
menuBar.append(fileMenu[0])
menuBar.append(helpMenu[0])
return menuBar # return MenuBar object
Then the MenuBar is created, and the main menu options are appended to the MenuBar. Why do we not append the other 2 items? It is because the menu items for the menu options (menu options being File and Help) have been appended to the Menus, and the Menus have been set as the sub menu for the Menu Options, so the only thing to do is append the menu options to the MenuBar, and everything will then be displayed.
Then, we pack the MenuBar to the mainHBox, which is then added to the main GtkWindow in some other code not shown:
Code:
def __init__(self):
menuBar = self.addMenus() # returns MenuBar object
self.window.add(self.mainHBox)
# add to mainHBox
self.mainHBox.pack_start(menuBar)
Hope this helps.