Search code examples
c++wxwidgets

How to show another frame after the event?


how to show another frame after button click event? like this

My code here show window OnInit. but what to do next? I did not find how to do this. little experience with this. I comment the window that should be.

enum
{
    wxID_First_Load = 5000,
    wxID_First_Frame,
    wxID_First_Panel
};

class MyFrame : public wxFrame
{
public:
    MyFrame(const wxString& title, const wxPoint& pos, const wxSize& size);
    void fileLoad(wxCommandEvent& event);
private:
    int file_count = 0;
    wxDECLARE_EVENT_TABLE();
};

wxBEGIN_EVENT_TABLE(MyFrame, wxFrame)
    EVT_BUTTON(wxID_First_Load, MyFrame::fileLoad)
wxEND_EVENT_TABLE()

wxIMPLEMENT_APP(MyApp);

bool MyApp::OnInit()
{
    MyFrame *frame = new MyFrame("Hello World", wxDefaultPosition, wxSize(450, 250));
    frame->SetWindowStyle(wxCAPTION | wxSYSTEM_MENU );
    frame->Show(true);
    return true;
}

MyFrame::MyFrame(const wxString& title, const wxPoint& pos, const wxSize& size)
    : wxFrame(NULL, wxID_First_Frame, title, pos, size)
{
        wxBoxSizer *first_sizer = new wxBoxSizer(wxVERTICAL);
        wxPanel *firstPanel = new wxPanel(this, wxID_First_Panel);
        wxButton *firstButton_Load = new wxButton(firstPanel, wxID_First_Load, "Choose file");

        firstPanel->SetSizer(first_sizer); 
        first_sizer->Add(firstButton_Load, 1, wxEXPAND | wxALL, 10);
        firstPanel->SetSizer(first_sizer);
}

void MyFrame::fileLoad(wxCommandEvent& WXUNUSED(event))
{
    file_count = 2;
}

Second Frame or window:

wxPanel *firstPanel = new wxPanel(this, wxID_First_Panel);
wxBoxSizer *second_sizer = new wxBoxSizer(wxVERTICAL);
for (int i = 0; i < file_count; i++)
{
second_sizer->Add(new wxTextCtrl(firstPanel, wxWindowID(i), "Hello", wxDefaultPosition, wxSize(235, 60)), wxSizerFlags(0).Border(wxALL, 5));
}
firstPanel->SetSizer(second_sizer);

Solution

  • To create a new frame you need to create a new object of wxFrame class or a class deriving from it. Typically, you want to put some data and logic into your new frame, so you would create some class, e.g. MySecondaryFrame (but hopefully with a better name) , inheriting from wxFrame in a similar way to your existing MyFrame class.

    Then to show it you would do the same thing that you do in MyApp::OnInit(), i.e. create a new object of this class and call Show() to actually show it.

    P.S. Note that your SetWindowStyle(wxCAPTION | wxSYSTEM_MENU ) call is unnecessary, these styles are already on by default. Also, hard coding the frame size in pixels is a bad idea, consider using sizers to determine the best size suitable for the frame contents or just leave it unspecified if it really doesn't matter.