右键单击时,MenuBar中的PopupMenu

时间:2017-05-02 10:09:48

标签: c++ wxwidgets wxformbuilder

以下是给我一个问题的代码:

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);
}

我在这里尝试的是在右键单击时显示弹出菜单,我希望它与我项目的菜单栏中的第二个菜单相同。

当我使用wxWidgets v2.8

编译时,它有效

现在我尝试使用v3.0,这是错误:

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

我该怎么做才能解决这个问题?

2 个答案:

答案 0 :(得分:1)

我认为比分离和附加菜单的现有答案更强大的解决方案是改为创建一个新菜单,例如像这样的东西:

std::unique_ptr<wxMenu> CreateActionsMenu() { ... }

// In your frame ctor or wherever you initialize your menu bar.
MyFrame::MyFrame() {
    wxMenuBar* const mb = new wxMenuBar;
    mb->Append(CreateActionsMenu().release(), "&Actions");
    SetMenuBar(mb);
}

// In your event handler function showing the popup menu.
void MyFrame::OnShowPopup(wxCommandEvent&) {
    auto menu = CreateActionsMenu();
    PopupMenu(menu.get());
}

创建一个菜单相对较快,在显示它之前应该没有问题(当然,如果构建它真的很大或者代价很高,你也可以将它缓存一下)。 / p>

答案 1 :(得分:0)

最后,我发现使用&gt; 3.0 wxWidgets 版本,您无法从连接到框架的wxMenuBar中获取元素。所以你必须暂时取消并重新连接它。

您将如何:

1 - 使用MenuBar初始化新的wxMenu。就我而言:

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 - 检查是否已附上:

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

3 - 完成后,将wxMenu重新连接到wxMenuBar

pMenuActions->Attach(pMenuBar);