[pygtk] context menus for ListViews

Neil Dugan pygtk at butterflystitches.com.au
Wed Dec 5 22:21:47 WST 2007


Caleb Marcus wrote:
> How can I create context menus for ListView elements? The PyGTK Tutorial
> doesn't go into this, and I can't follow the GtkTreeView tutorial as
> it's not in Python.
> 


This is the code I use to put a context sensitive menu on a listview
----------
self.listview = listview = gtk.TreeView()
scrolledwindow.add_with_viewport(listview)
listview.set_headers_visible(False)
listview.connect("button_press_event", self.on_button_press_event)
----------
   def on_button_press_event(self, widget, event) :
     if event.button == 3 and event.type == gtk.gdk.BUTTON_PRESS :
       # see if there is a selected order item
       selection = self.listview.get_selection()
       (model,node) = selection.get_selected()
       active = (node != None)

       menu = gtk.Menu()
       for stock_id,callback,sensitivity in [
           (gtk.STOCK_ADD, self.on_menu_add, True),
           (gtk.STOCK_EDIT, self.on_menu_edit, active),
           (gtk.STOCK_REMOVE, self.on_menu_remove, active)]:
         item = gtk.ImageMenuItem(stock_id)
         item.connect("activate",callback)
         item.set_sensitive(sensitivity)
         item.show()
         menu.append(item)
       menu.popup(None,None,None,event.button,event.time)
       return True
     else :
       return False
----------

hope this helps.

Neil


More information about the pygtk mailing list