When dynamically changing the size of the elements within a wxNotebook (e.g. hiding a button), the size of the whole notebook element is not updated. This can leave white space or prevent some elements from being shown.
Normally, a call to the parent window’s Fit() or FitInside() should do the trick, but doesn’t for the notebook. How can we resize it?
Minimal example demonstrating the problem:
#include <wx/wx.h>
#include <wx/gbsizer.h>
#include <wx/notebook.h>
const int HIDEME_ID = 512, SHOWME_ID = 513;
class MyApp: public wxApp
{
wxButton* hideme;
wxSizer* panel_sizer, *frame_sizer, *sw_sizer;
wxScrolledWindow* sw;
wxNotebook* nb;
void hide_button( wxCommandEvent& ) {
hideme->Hide();
relayout();
}
void relayout() {
/* Insert layout code here */
}
void show_button( wxCommandEvent& ) {
hideme->Show();
relayout();
}
virtual bool OnInit() {
wxFrame *frame = new wxFrame( NULL, wxID_ANY, _("Hello World"), wxPoint(50, 50), wxSize(450, 340) );
frame_sizer = new wxBoxSizer( wxVERTICAL );
frame->SetSizer( frame_sizer );
sw = new wxScrolledWindow( frame, wxID_ANY );
sw->SetScrollRate( 5, 5 );
frame_sizer->Add( sw, 1, wxEXPAND );
sw_sizer = new wxBoxSizer( wxVERTICAL );
sw->SetSizer( sw_sizer );
nb = new wxNotebook( sw, wxID_ANY );
wxPanel* panel = new wxPanel( nb, wxID_ANY );
nb->AddPage( panel, wxT("Tab1") );
sw_sizer->Add( new wxButton( sw, wxID_ANY, _("Button1"), wxDefaultPosition, wxSize(200,200) ), 0, wxEXPAND );
sw_sizer->Add( nb, 0, wxEXPAND );
sw_sizer->Add( new wxButton( sw, wxID_ANY, _("Button3") ), 1, wxEXPAND );
sw_sizer->Add( new wxButton( sw, wxID_ANY, _("Button4") ), 0, wxEXPAND );
panel_sizer = new wxBoxSizer( wxVERTICAL );
panel_sizer->Add( hideme = new wxButton(panel, HIDEME_ID, wxT("HideMe")), 0, wxEXPAND );
hideme->Hide();
panel_sizer->Add( new wxButton(panel, SHOWME_ID, wxT("ShowMe")), 0, wxEXPAND );
panel->SetSizer( panel_sizer );
frame->Show(true);
SetTopWindow(frame);
return true;
}
DECLARE_EVENT_TABLE();
};
BEGIN_EVENT_TABLE(MyApp, wxApp)
EVT_BUTTON(HIDEME_ID, MyApp::hide_button)
EVT_BUTTON(SHOWME_ID, MyApp::show_button)
END_EVENT_TABLE()
IMPLEMENT_APP( MyApp );
The somewhat surprising pitfall here is that, unlike many other windows, a wxNotebook caches its best size. We have to invalidate the cache before doing any layouting: