c++wxwidgetswxformbuilder

PopupMenu from MenuBar when right click


Here is the piece of code that gives me a problem :

void CMainFrame::DisplayActionsPopupMenu()
{
    // get "Actions" menu
    wxMenuBar* pMenuBar = GetMenuBar();
    ASSERT(pMenuBar != NULL);
    int nIndex = pMenuBar->FindMenu("Actions");
    ASSERT(nIndex != wxNOT_FOUND);
    wxMenu *pMenuActions = pMenuBar->GetMenu(nIndex);
    ASSERT(pMenuActions != NULL);
    // display a popup menu for actions
    PopupMenu(pMenuActions);
}

What I try to do here is to display a popupmenu when right clicking and I want it to be the same as the second menu in the menubar of my project.

It worked when I compiled with wxWidgets v2.8

Now I tried with v3.0 and here is the error:

../src/common/menucmn.cpp(715): assert "!IsAttached()" failed in SetInvokingWindow(): menus attached to menu bar can't have invoking window

What should I do to fix this?


Solution

  • Finally I found that with the >3.0 wxWidgets version, you can't get elements from the wxMenuBar which is attached to your frame. So you have to temporarly unattach and reattach it.

    Here is how you would so:

    1 - Initialize the new wxMenu with the MenuBar. In my case:

    wxMenuBar* pMenuBar = GetMenuBar();
    ASSERT(pMenuBar != NULL);
    cout<<pMenuBar->IsAttached()<<endl;
    int nIndex = pMenuBar->FindMenu("Actions");
    ASSERT(nIndex != wxNOT_FOUND);
    wxMenu *pMenuActions = pMenuBar->GetMenu(nIndex);
    

    2 - Check if it's attached:

    if(pMenuActions->IsAttached()){
        pMenuActions->Detach();
    }
    

    3 - When your done, reAttach the wxMenu to the wxMenuBar

    pMenuActions->Attach(pMenuBar);