Search code examples
c++eventswxwidgets

Assign click event to a wxPanel instance


I have a wxPanel class. I need every instance of that class handle a click event. Is that possible in wxWidgets? So far, I always had to use window IDs to assign events to objects (eg. buttons).
However this wxPanel is about to occur multiplicatively on the screen, so I need to avoid using window ID.

The class:

panel.h

class UVStatusPanel : public wxPanel
{

public:
    UVStatusPanel(wxFrame* parent, int pos);

    void paintEvent(wxPaintEvent& evt);
    void paintNow();

    //THIS is expected to be the event function
    void onClick(wxCommandEvent& WXUNUSED(event));

    bool State(bool state);
    bool State();

    DECLARE_EVENT_TABLE()
private:
    bool painting;
    bool state;
    void render(wxDC &dc);
};

panel.cpp

/**The constructor*/
UVStatusPanel::UVStatusPanel(wxFrame* parent, int pos) :
wxPanel(parent)
{
 /** some align and draw rect code was there**/
 //My two attepmts to assign the click event to the panel
 Connect(this->m_windowId, wxEVT_COMMAND_LEFT_CLICK, 
          wxCommandEventHandler(UVStatusPanel::onClick));
 //EVT_COMMAND_LEFT_CLICK(this->m_windowId,UVStatusPanel::onFocus);
}

Currently noc clicks are registered. Can anyone explain how click events work in wxWidgets?


Solution

  • wxEVT_COMMAND_LEFT_CLICK is not generated by wxPanel (nor by almost anything else, to be honest), the event you are looking for is called wxEVT_LEFT_UP and it's a wxMouseEvent, not a wxCommandEvent.

    Also, the use of both event table and Connect() in your example is not recommended. It does work but risks being confusing, just pick one and stick with it (preferably Connect() or, if you use 2.9+, Bind()).