Search code examples
c++wxwidgets

Distribute and centre items over wxBoxSizer's full orientation without stretching


I am just learning about sizers and am kind of confused on how to accomplish this.

If I have a single horizontal box sizer in a frame and add two buttons to it (each with proportion "1") then they will both stretch to take up the full horizontal width of the sizer (which equals the full horizontal width of the frame) and be distributed evenly (see example 1 below).

Example 1 code:

wxFrame* frame = new wxFrame(nullptr, wxID_ANY, "Frame");
wxPanel* panel = new wxPanel(frame, wxID_ANY);

wxBoxSizer* buttonSizer = new wxBoxSizer(wxHORIZONTAL);

wxButton* buttonOk = new wxButton(panel, wxID_OK, "Ok");
wxButton* buttonCancel = new wxButton(panel, wxID_CANCEL, "Cancel");

buttonSizer->Add(buttonOk, 1, wxALL, 10);
buttonSizer->Add(buttonCancel, 1, wxALL, 10);

panel->SetSizerAndFit(buttonSizer);
frame->Show();

However, what if I want these buttons to keep their original size (not be stretched), but still be distributed evenly amongst the frame, and furthermore still be centred horizontally inside each wxSizerItem? I.e. so that both "columns" of the horizontal sizer take up half the dialog, and each button is centred in each of those columns? How would I accomplish this? Here is a drawing. The buttons should be their default size.

______________________________________
|    | Button 1 |    | Button 3 |    |
--------------------------------------

The following code does not work:

buttonSizer->Add(buttonOk, 0, wxALL, 10);
buttonSizer->Add(buttonCancel, 0, wxALL, 10);

Solution

  • One way to do it is with stretch spacers:

    buttonSizer->AddStretchSpacer();
    buttonSizer->Add(buttonOk, 0, wxALL, 10);
    buttonSizer->AddStretchSpacer();
    buttonSizer->Add(buttonCancel, 0, wxALL, 10);
    buttonSizer->AddStretchSpacer();