Search code examples
c++wxwidgets

How to get My object, derived from wxFrame through wxTheApp->GetTopWindow()?


I'm not so good in OOP rules in C++. I have this Application OnInit() callback:

bool Application::OnInit()
{
    MainFrame *mainFrame = new MainFrame();

    mainFrame->Show();
    SetTopWindow(mainFrame);

    return true;
}

In MainFrame, derived from wxFrame I have private member and getter for it:

wxDialog* MainFrame::GetConfigDialog()
{
    return m_ConfigDialog;
}

I want to get ConfigDialog in other class, so I call

wxTheApp->GetTopWindow()->GetConfigDialog()

But it complain about wxWindow has no member named GetConfigDialog(). Can i get my MainFrame from wxTheApp somehow?


Solution

  • There are two things here. First, you need to use wxGetApp() function. Unlike wxTheApp, it returns the application of the derived type, i.e. Application and not wxApp in your case (and it also returns it as a reference and not a pointer as it's never supposed to be null). Notice that, as explained in the documentation, you need to use wxDECLARE_APP() macro to declare this function in the header containing your application class declaration.

    Second, you still can't call your derived class GetConfigDialog() method via wxWindow pointer. You could use a dynamic cast, but this would be ugly and unsafe. Instead, add a method to retrieve the real main frame to your application class (of course, you'd need to store a pointer to it inside it too then), e.g. GetMainFrame().

    If you do both, your code would become

    wxGetApp().GetMainFrame()->GetConfigDisplay()