Win32项目中如何以Dialog为父窗口显示wxFormBuilder生成的Panel?
问题描述
我有一个Win32项目(Windows子系统),通过wxFormBuilder创建了一个MyPanel面板类。实例化该面板时必须传入父窗口句柄,但目前我没有可用的窗口句柄。测试时我创建过Frame类型窗口,它可以无参数实例化并正常显示,但我更倾向于使用Dialog类型窗口来承载这个Panel,请问该如何让Panel正常显示?
当前报错的代码如下:
#include <wx/wx.h> #include "gui.h" class MyApp : public wxApp { public: bool OnInit() override; }; wxIMPLEMENT_APP(MyApp); bool MyApp::OnInit() { MyPanel* mp = new MyPanel(NULL); //<---运行时错误: "can't create wxWindow without parent" mp->Show(true); return true; }
wxFormBuilder生成的MyPanel类定义:
class MyPanel : public wxPanel { private: protected: wxButton* m_bnInit; public: MyPanel(wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize(500, 300), long style = wxTAB_TRAVERSAL, const wxString& name = wxEmptyString); ~MyPanel(); };
解决方案
wxPanel作为容器控件,必须依赖父窗口才能创建,不能单独作为顶层窗口显示。要使用Dialog承载Panel,只需先创建一个wxDialog实例作为父容器,再将Panel挂载到这个Dialog上即可。
修改后的OnInit()代码示例:
bool MyApp::OnInit() { // 创建Dialog作为顶层父窗口,传NULL表示它是独立顶层窗口 wxDialog* dialog = new wxDialog(NULL, wxID_ANY, _("Dialog承载Panel"), wxDefaultPosition, wxSize(500, 300)); // 将Dialog作为父窗口实例化Panel MyPanel* mp = new MyPanel(dialog); // 用布局管理器让Panel铺满整个Dialog wxBoxSizer* sizer = new wxBoxSizer(wxVERTICAL); sizer->Add(mp, 1, wxEXPAND | wxALL, 0); dialog->SetSizer(sizer); // 显示Dialog,Panel会随父窗口一同显示 dialog->Show(true); return true; }
关键说明:
- 顶层窗口(wxFrame、wxDialog这类)可以传
NULL作为父参数,它们本身是独立窗口;但wxPanel作为子控件,必须绑定到顶层窗口或其他容器控件上。 - 使用布局管理器能让Panel自动适配Dialog的大小,避免布局错乱或控件显示不全。
- 无需单独调用
mp->Show(),父窗口Dialog显示后,Panel会自动被渲染。
内容的提问来源于stack exchange,提问作者Ben Nguyen
相关产品推荐
相关产品推荐

