Search code examples
c++apiuser-interfacewxwidgets

Why does the second wxSizer fail to center the button?


I created a global panel and called a method that creates a sizer and a button. The button clears the sizer (i.e., also the panel), and then deletes is. Then, another method is called, using the same logic, it creates another sizer and another button. This time they don't work.

my code(windows, vs studio):

#include "MainFrame.h"
#include <wx/wx.h>s
MainFrame::MainFrame(const wxString& title) : wxFrame(nullptr, wxID_ANY, title)
{
    panel = new wxPanel(this);
    StartParty(panel);

}
void MainFrame::ClearButtonClicked(wxCommandEvent& evt)
{
    panel->GetSizer()->Clear(true);
    panel->SetSizerAndFit(nullptr);
    ChooseMode(panel);
}

void MainFrame::StartParty(wxPanel* parent)
{
    wxButton* start_button = new wxButton(parent, wxID_ANY, "Start the Party!", wxDefaultPosition, wxSize(200, 70));
    wxBoxSizer* sizer = new wxBoxSizer(wxHORIZONTAL);
    sizer->AddStretchSpacer(1);
    sizer->Add(
        start_button,
        0,
        wxALL | wxALIGN_CENTER,
        0);
    sizer->AddStretchSpacer(1);
    parent->SetSizerAndFit(sizer);
    start_button->Bind(wxEVT_BUTTON, &MainFrame::ClearButtonClicked, this);
}

void MainFrame::ChooseMode(wxPanel* parent)
{
    wxButton* select_button = new wxButton(parent, wxID_ANY, "Choose", wxDefaultPosition, wxSize(200, 70));
    wxBoxSizer* sizer = new wxBoxSizer(wxHORIZONTAL);
    sizer->AddStretchSpacer(1);
    sizer->Add(
        select_button,
        0,
        wxALL | wxALIGN_CENTER,
        0);
    sizer->AddStretchSpacer(1);
    parent->SetSizer(sizer);
}

First button, which is working

Second button, not centerd (why?)


Solution

  • You do need Layout(), as mentioned in the comments, as this is what actually repositions the windows -- SetSizer() just specifies the sizer to use for doing it, but doesn't do anything on its own immediately (it will when the window is resized the next time, as this results in a call to Layout()).

    However, even if it's somewhat unrelated to the question itself, I think you shouldn't be doing this at all and use wxSimplebook instead. This simple (sic) class allows you to add a few pages to it and then easily switch between them.