Search code examples
c++event-handlingwxwidgets

wxWidget which button (wxButton) was pressed?


I am trying to create an array of buttons by using this code

for(int i = 0; i < 10; i++)
{
    wxButton *btn_random = new wxButton(this, wxID_ANY, _T("Button " + std::to_string(i)), wxPoint(250, 10*i + 10*i), wxSize(60, 25), 0);

    btn_random->Bind(wxEVT_COMMAND_BUTTON_CLICKED, &MyFrame::OnPressed, this);
}

In the function OnPressed(wxCommandEvent& event) I can get the unique Id of the button, but I want to change and modify the button inside the OnPressed function. How do I do that?

Also, I have read that it is possible to cast a wxWindow when using wxWindow::GetWindowById(id) but I cannot get this method to work.


Solution

  • You can use event.GetEventObject() to retrieve the object which generated the event. You will need to (dynamic_-) cast it to the correct type, however. If you'd rather avoid this, you need to use fixed IDs, e.g. MY_BUTTON_OFFSET + i and store the button pointers yourself somewhere and then use event.GetId() - MY_BUTTON_OFFSET as index for retrieving them.

    P.S. Nothing to do with your question, but wxEVT_COMMAND_BUTTON_CLICKED is long and unwieldy and exists for compatibility only nowadays, just use wxEVT_BUTTON instead.