Search code examples
user-interfacetextresizewxwidgets

How to resize text dynamically along with window resizing in wxWidgets?


I want to make something simple, inside a panel, have a text that resizes when you resize the window. I tried with a wxBoxSizer, doesn't work the way I naively hoped.

    wxBoxSizer* sizer = new wxBoxSizer(wxVERTICAL);

    wxStaticText* scalable_text = new wxStaticText(this, wxID_ANY, "This text resizes nicely");
    sizer->Add(scalable_text);

    this->SetSizerAndFit(sizer);

Do I have to make a custom text class and catch a "resize" event? If so, how would I go about doing that?


Solution

  • The wxStaticText doesn't get resized because you didn't specify neither a non-zero proportion to resize it in the sizer direction (vertically here) nor wxEXPAND flag to resize it in the other direction (horizontally), but even if it were resized, the problem is that resizing it doesn't change its font size and I think it would be very weird if it did this by default.

    So if you want to change the font size, you do need to do it yourself. Of course, you don't need to define a custom class to do it, you can just do something like

    scalable_text->Bind(wxEVT_SIZE, [=](wxSizeEvent& e) {
      auto f = scalable_text->GetFont();
      f.SetPixelSize(wxSize(0, e.GetSize().y / 2)); // or whatever...
      scalable_text->SetFont(f));
      scalable_text->Refresh();
    });
    

    And you should also tell the sizer to resize this element

       sizer->Add(scalable_text, wxSizerFlags(1).Expand());