Page 1 of 1

pass treectrl item id to menu OnTreeCtrlItemMenu

Posted: Mon Nov 18, 2019 11:08 am
by paddle
Hi,
I am building a treectrl which display some items. When right click on an item I want a menu to show up with some options 'delete item' 'edit item' ...

In the treectrl sample (folder wxWidgets-3.1.2\samples\treectrl) it creates the menu, but the menu items are not linked to any functions.

My issue is that I don't know how to get the treectrl item id from the called function.

First in the OnTreeCtrl2ItemMenu we can get the item id with event.GetItem() (from sample).

Code: Select all

void MemBFrame::OnTreeCtrl2ItemMenu(wxTreeEvent& event)
{
    wxTreeItemId itemId = event.GetItem();
    static const long idMenuDeleteNode = wxNewId();
    wxMenuItem* MenuItemDeleteNode = new wxMenuItem(Menu, idMenuDeleteNode, _("Delete Node"), _("Delete all memories of this Node"), wxITEM_NORMAL);
    menu.Append(MenuItemDeleteNode);
    Connect(idMenuDeleteNode,wxEVT_COMMAND_MENU_SELECTED,(wxObjectEventFunction)&MemBFrame::OnDeleteNode);

    PopupMenu(&menu, pt);

    event.Skip();
}
But then in the MemBFrame::OnDeleteNode how to get the item id? Can I just use event.GetItem()? I think maybe it's not the same event declared in the new function scope?

Thanks

Re: pass treectrl item id to menu OnTreeCtrlItemMenu

Posted: Mon Nov 18, 2019 2:32 pm
by paddle
Found the answer in treelist sample.

Here no function is called, we just get the id of the menu item that is clicked and process it in the OnItem function.

Code: Select all

void MyFrame::OnItemContextMenu(wxTreeListEvent& event)
{
    enum
    {
        Id_Check_Item,
        Id_Uncheck_Item,
        Id_Indet_Item,
        Id_Check_Recursively,
        Id_Update_Parent
    };

    wxMenu menu;
    menu.Append(Id_Check_Item, "&Check item");
    menu.Append(Id_Uncheck_Item, "&Uncheck item");
    if ( m_treelist->HasFlag(wxTL_3STATE) )
        menu.Append(Id_Indet_Item, "Make item &indeterminate");
    menu.AppendSeparator();
    menu.Append(Id_Check_Recursively, "Check &recursively");
    menu.Append(Id_Update_Parent, "Update &parent");

    const wxTreeListItem item = event.GetItem();
    switch ( m_treelist->GetPopupMenuSelectionFromUser(menu) )
    {
        case Id_Check_Item:
            m_treelist->CheckItem(item);
            break;

        case Id_Uncheck_Item:
            m_treelist->UncheckItem(item);
            break;

        case Id_Indet_Item:
            m_treelist->CheckItem(item, wxCHK_UNDETERMINED);
            break;

        case Id_Check_Recursively:
            m_treelist->CheckItemRecursively(item);
            break;

        case Id_Update_Parent:
            m_treelist->UpdateItemParentStateRecursively(item);
            break;

        default:
            wxFAIL_MSG( "Unexpected menu selection" );
            wxFALLTHROUGH;

        case wxID_NONE:
            return;
    }
}