Tuesday, June 12, 2012

GTK3: How to create menu button?

In Gtk3, we are provided with GtkMenuToolButton GtkMenuToolButton to show a dropdown menu from a button, but this toolbutton consists of two parts: a button and an additional button that popups a menu when toggled. The first button is useless when we plan to use GtkMenuToolButton as a menu button, thus requires us to find new solution.

There are several methods to create menu button:
  1. Connect the "clicked" or "toggled" signal of a button or toggle button to a callback that pops up a menu. For this method, we need to create a custom positioning function, which is to me a tedious work.
  2. Customize the GtkMenuToolButton by getting it's child and remove the button part as well as replacing the GtkArrow with another widget.
  3. Using GtkMenuBar.
This article only covers the 3rd solution.

Convert GtkMenuBar into Menu Button

This is the simplest way to create a menu button. Before this, I used the second method to come up with a menu button until I updated my Gnome installation to version 3.4 and found out Epiphany 3.4['s] way of implementing this. I don't know why am I so stupid to come up with that method? :(

What the developer did, is just changing the style class of the GtkMenuBar into button style. That's all. As easy as that! >.<

Code (in python)
menub = Gtk.MenuBar()
onlyitem = Gtk.MenuItem()
onlyitem_child = Gtk.Button(label = "Menu")
onlyitem.add(onlyitem_child)
 
menu = Gtk.Menu()
mitem1 = Gtk.MenuItem(label = "Item 1")
mitem2 = Gtk.MenuItem(label = "Item 2")

menu.insert(mitem1, 0)
menu.insert(mitem2, 1)
onlyitem.set_submenu(menu)
menub.insert(onlyitem, 0)

menub.get_style_context().add_class("button") #this is the key line.

**UPDATE**
Since Gtk+ 3.6, a native menu button widget, GtkMenuButton has been added.

2 comments:

  1. onlyitem points to a button - but this doesnt have a set_submenu method - any thoughts on this?

    ReplyDelete
    Replies
    1. Thanks for the comment. My previous code was wrong, sorry for that. I've updated the code. Anyhow, as of Gtk+ 3.6, you don't need this anymore since GtkMenuButton has been introduced. :)

      Delete