如何正确打开从 XML 资源文件加载的 WxFrame?

How can I correctly open my WxFrame loaded from an XML resource file?

我对 C++ 和 Wx 都比较陌生,所以在过去的几个小时里我一直在努力使它工作,但我似乎遇到了比喻性的砖墙这个问题。

此代码编译没有错误,但是当 运行 时,它什么也不做。 它只是保持 运行ning 直到终止(例如使用 Ctrl-C),但是 window 永远不会打开。

这是 C++ 源代码:

#include <wx/wxprec.h>

#ifndef WX_PRECOMP
    #include <wx/wx.h>
#endif

#include <wx/xrc/xmlres.h>


class MyApp : public wxApp {
public:
    virtual bool OnInit();
};

wxIMPLEMENT_APP(MyApp);

bool MyApp::OnInit() {
    wxXmlResource::Get()->InitAllHandlers();
    wxXmlResource::Get()->Load("res.xrc");

    wxFrame MainFrame;
    wxXmlResource::Get()->LoadFrame(&MainFrame, NULL, "MainFrame");
    MainFrame.Show(true);

    return true;
}

这是随附的 XML 文件 res.xrc,它应该只生成一个包含面板内 sizer 的空框架:

<?xml version="1.0" ?>

<resource>
    <object class="wxFrame" name="MainFrame" title="Test">
        <object class="wxPanel" name="TopLevelPanel">        
        
           <object class="wxBoxSizer" name="TopLevelSizer">
                <orient>wxVERTICAL</orient>
           </object>
        </object>
    </object>
</resource> 

在 XML 中引入错误 - 例如,添加一些无效的虚假字符 XML - 会导致a window 打开, 看起来像这样(在 Linux 下):

如何修改我的代码以便 window 能够正确打开?

当您到达函数末尾时,您的 MainFrame 会被销毁,这根本不是您想要的一个应该存在很长时间的框架。最简单正确的做法是

wxFrame* MainFrame = wxXmlResource::Get()->LoadFrame(NULL, "MainFrame");
if ( !MainFrame ) {
    wxLogError("Failed to load the main frame from the resources.");
    return false;
}
MainFrame->Show();

即只需让 XRC 为您创建一个新框架(采用指针的重载在创建此框架本身时非常有用,即在其中传递 this)。