Base code to make context menu work with wxPython CustomTreeCtrl

After it took me an hour or two to figure that out, here is some base Python code snippet showing how to make context menues work with wxPython’s CustomTreeCtrl:

class CustomTreeCtrl(CT.CustomTreeCtrl):

    def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition,
                 size=wx.DefaultSize,
                 style=wx.SUNKEN_BORDER|wx.WANTS_CHARS,
                 agwStyle=CT.TR_HAS_BUTTONS|CT.TR_HAS_VARIABLE_ROW_HEIGHT,
                 log=None):

        CT.CustomTreeCtrl.__init__(self, parent, id, pos, size, style, agwStyle)
        
        # ...        
        self.item = None
        self.Bind(wx.EVT_CONTEXT_MENU, self.OnContextMenu)
        self.Bind(wx.EVT_RIGHT_DOWN, self.OnRightDown)
        
    def OnRightDown(self, event):

        pt = event.GetPosition()
        item, flags = self.HitTest(pt)

        if item:
            self.item = item    
        
    def OnContextMenu(self, event):
        # Setup right-click menu for tree items
        menu = wx.Menu()
        treeMenuItem1 = menu.Append(wx.ID_ANY, "Menu Entry 1")
        treeMenuItem2 = menu.Append(wx.ID_ANY, "Menu Entry 2")
        self.Bind(wx.EVT_MENU, self.OnMenuEntry1, treeMenuItem1)
        self.Bind(wx.EVT_MENU, self.OnMenuEntry2, treeMenuItem2)
        
        self.PopupMenu(menu)
        menu.Destroy()
        
    def OnMenuEntry1(self, event):
        print "Method OnMenuEntry1 not implemented yet."
        
    def OnMenuEntry2(self, event):
        print "Method OnMenuEntry2 not implemented yet."

In essence:

  • we need a method to capture what item has been selected in a tree. This is done by OnRightDown() and the HitTest() method. We store the selected item in an attribute of our CustomTreeCtrl object: self.item
  • we need a method to display the context menu: OnContextMenu()
  • we need one method per context menu entry, yet to be implemented: OnMenuEntry1(), onMenuEntry2(), …
  • we need to ensure the proper bindings so that all these methods working, thus:
    • binding wx.EVT_CONTEXT_MENU to OnContextMenu() in the constructor of our CustomTreeCtrl object
    • binding wx.EVT_RIGHT_DOWN to OnRightDown() in the constructor of our CustomTreeCtrl object
    • binding wx.EVT_MENU to every method used to handle clicking a menu entry, like OnMenuEntry1(), onMenuEntry2(), in OnContextMenu()
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: