【发布时间】:2021-08-06 10:18:22
【问题描述】:
我正在编写一个小型扫雷游戏,只是为了熟悉 wxWidgets(Windows,wxWidgets 3.1.4)。该应用程序可以很好地处理一个游戏,现在我想添加“新游戏”功能。对于布局,我使用的是wxGridSizer。
我的第一种方法是创建一个新的wxGridSizer,其中包含新字段,然后用新的sizer 替换当前的sizer。尽管我想出了如何重用旧的sizer(总的来说这可能也是一个更好的解决方案),但我还是很好奇如何正确更换sizer。
我能够将我的问题简化为:
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
class MyApp : public wxApp {
public:
virtual bool OnInit();
};
class MyFrame : public wxFrame {
public:
MyFrame(const wxString &title, const wxPoint &pos, const wxSize &size);
private:
void OnExit(wxCommandEvent &event);
void OnRefill(wxCommandEvent &event);
wxDECLARE_EVENT_TABLE();
};
enum { ID_Refill = 1 };
wxBEGIN_EVENT_TABLE(MyFrame, wxFrame)
EVT_MENU(ID_Refill, MyFrame::OnRefill)
EVT_MENU(wxID_EXIT, MyFrame::OnExit)
wxEND_EVENT_TABLE() wxIMPLEMENT_APP(MyApp);
bool MyApp::OnInit() {
MyFrame *frame = new MyFrame("Hello World", wxPoint(50, 50), wxSize(300, 200));
frame->Show(true);
return true;
}
MyFrame::MyFrame(const wxString &title, const wxPoint &pos, const wxSize &size)
: wxFrame(NULL, wxID_ANY, title, pos, size) {
wxMenu *menu = new wxMenu;
menu->Append(ID_Refill, "&Refill...\tCtrl-R", "Creates new layout");
wxMenuBar *menuBar = new wxMenuBar;
menuBar->Append(menu, "&Menu");
SetMenuBar(menuBar);
wxGridSizer *sizer = new wxGridSizer(2, 2, 1, 1);
SetSizer(sizer);
for (auto i = 0; i < 4; i++) {
wxButton *button = new wxButton(this, wxID_ANY, std::to_string(i), wxDefaultPosition, wxDefaultSize, 0);
sizer->Add(button, wxALL, 0);
}
}
void MyFrame::OnExit(wxCommandEvent &) {
Close(true);
}
void MyFrame::OnRefill(wxCommandEvent &) {
Freeze();
GetSizer()->Clear(true);
wxGridSizer *sizer = new wxGridSizer(3, 3, 1, 1);
SetSizer(sizer);
for (auto i = 0; i < 9; i++) {
wxButton *button = new wxButton(this, wxID_ANY, std::string("Refilled") + std::to_string(i), wxDefaultPosition,
wxDefaultSize, 0);
sizer->Add(button, wxALL, 0);
}
sizer->Layout();
Thaw();
Refresh();
}
问题是在 OnRefill 函数之后,应用只显示第一个按钮 (Refilled0),而不显示其余按钮。
OnRefill之前:
OnRefill之后:
我的问题是如何正确替换MyFrame 的sizer?根据我从示例和文档中了解到的情况,这应该可行,但我想我遗漏了一些东西。
【问题讨论】:
-
为什么要更换任何东西?布局是一样的,对吧?您在同一位置有相同的按钮网格。您需要更改的只是您显示的图标。对吗?
-
字段的大小也可以更改。我能够通过重用 sizer 来解决我原来的问题,但我想知道如何正确更换 sizer。我对此感兴趣,因为我看不出我粘贴的代码不应该工作的任何原因,因此找出问题会教给我一些东西(我认为这是在学习过程中所需要的)。