Search code examples
c++fontswxwidgets

Scaling font as window is resized


I'm writing a C++ calculator application in wxWidgets.

My application

I want the font of all the buttons and the two wxTextCtrl's to be scaled as I resize the window. How is that done? I'm posting some code if that can help.

text_controls.cpp

#include "main.h"

void Main::AddTextControls()
{
    //creazione font
    wxFont Expression(10, wxFONTFAMILY_SWISS, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_LIGHT, false, "Lato");
    wxFont Main(30, wxFONTFAMILY_SWISS, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_LIGHT, false, "Lato");

    wxBoxSizer* sizer = new wxBoxSizer(wxVERTICAL);

    ExpText = new wxTextCtrl(this, wxID_ANY, "", wxDefaultPosition, wxDefaultSize, wxTE_READONLY | wxNO_BORDER);
    ExpText->SetFont(Expression);
    ExpText->SetForegroundColour(wxColour(125, 125, 125));
    sizer->Add(ExpText, 1, wxEXPAND);

    MainText = new wxTextCtrl(this, wxID_ANY, "", wxDefaultPosition, wxDefaultSize, wxTE_READONLY | wxNO_BORDER);
    MainText->SetFont(Main);
    MainText->SetForegroundColour(wxColour(55, 55, 55));
    MainText->Bind(wxEVT_TEXT, &Main::OnTextChange, this);
    sizer->Add(MainText, 2, wxEXPAND);

    MainSizer->Add(sizer, 4, wxEXPAND);
}

Solution

  • You could use wxFont::SetPixelSize() to set the font size to, say, one third of the text control height. E.g.:

    MainText->Bind(wxEVT_SIZE, [this](wxSizeEvent& e) {
        e.Skip();
        MainText->SetFont(wxFontInfo(wxSize(0, MainText->GetSize().y / 3)).Family(wxFONTFAMILY_SWISS).FaceName("Lato").Light());
    });
    

    (which also shows using a more readable way of creating a wxFont than the ctor taking a zillion arguments).