Hi i am using wxWidgets to create a simple app. But the example app(shown below) crashes when you click on black button on the screen. The app crashes only when you add the statement mySimplebook->GetPageCount()
from inside the onClick() event handler. If i remove the use of the above statement from inside onClick() then the app does not crash. Also the use of the above statement in the MySimplebook constructor also does not crashes the app. The program only crashes when i use mySimplebook->GetPageCount();
inside the onClick() handler. Otherwise, if you omit this statement from inside the onClick() handler the program works fine. The complete reproducible code that i have is as follows:
mysimplebook.cpp
MySimplebook::MySimplebook(wxFrame *m_parentWindow, int id): wxPanel(m_parentWindow, id)
{
wxBoxSizer *mainBoxsizer = new wxBoxSizer(wxVERTICAL);
CustomButton *button = new CustomButton(this, wxID_ANY);
mainBoxsizer->Add(button, 1, wxEXPAND, 0);
mySimplebook = new wxSimplebook(this, wxID_ANY);
First_Page *firstPage = new First_Page(mySimplebook);
mySimplebook->AddPage(firstPage, "Input", false);
mainBoxsizer->Add(mySimplebook, wxSizerFlags(1).Expand());
/*program doesn't crashes here*/
std::cout<<"Pages inside constructor: "<<(mySimplebook->GetPageCount())<<std::endl;
this->SetSizer(mainBoxsizer);
}
void MySimplebook::onClick(wxMouseEvent &event)
{
std::cout<<"event received from button"<<std::endl;
//program creashes here
std::cout<<"pagecount inside onclick:"<<(mySimplebook->GetPageCount())<<std::endl;
}
custombutton.cpp
CustomButton::CustomButton(wxWindow *parent, int id):wxPanel(parent, id)
{
SetBackgroundColour(wxColour(0,0,0));
Connect(wxEVT_LEFT_UP, wxMouseEventHandler(MySimplebook::onClick));
}
The program crashes when i click on the button. My questions are:
bind
. Or which part of my code should be changed and how?The program crashes with the following on the console:
Pages inside constructor: 1
event received from button
Segmentation fault (core dumped)
PS: I know the problem is most probably with the Connect()
call. But don't know how to resolve/correct it.
The solution is to use bind
instead of connect
. Instead of using the Connect() call from inside custombutton.cpp we can just use bind
right after that button is created inside the mysimplebook.cpp. So after changing the statement:
Connect(wxEVT_LEFT_UP, wxMouseEventHandler(MySimplebook::onClick));
to
button->Bind(wxEVT_LEFT_UP, &MySimplebook::onClick, this);
the program works. Note that the bind statement is just after the definition of the CustomButton inside mysimplebook.cpp and there is no need to use it inside the custombutton constructor.