Search code examples
wxwidgets

Subclassing wxControl


My goal is to make a control with two buttons, similar to Toolbar tool with wxITEM_DROPDOWN set.

I use the following strategy:

CDropDownTool::CDropDownTool(wxWindow* parent, int id, const wxBitmap& bmptool, const wxBitmap& bmpDrop, const wxString& tooltip) :
    wxControl(parent, id, wxDefaultPosition, wxDefaultSize, wxBORDER_NONE)
{
    m_BMPTool = bmptool;
    m_BMPDrop = bmpDrop;

    m_ID = id;

    wxSize sz1 = m_BMPTool.GetSize();
    wxSize sz2 = m_BMPDrop.GetSize();

    SetClientSize(wxSize(sz1.x + sz2.x + GAP, std::max(sz1.y, sz2.y)));

    Bind(wxEVT_PAINT, &CDropDownTool::OnPaint, this);
    Bind(wxEVT_LEFT_DOWN, &CDropDownTool::OnLeftDown, this);
}

And then to paint the control:

void CDropDownTool::OnPaint(wxPaintEvent& event)
{
    wxPaintDC pdc(this);

    wxSize szBMP = m_BMPTool.GetSize();
    auto Rect = GetClientRect();

    int y = (Rect.GetHeight() - szBMP.GetHeight()) / 2;

    wxPoint TL = Rect.GetTopLeft();
    TL.y = y;

    m_Tool = wxRect(TL, szBMP);

    pdc.DrawBitmap(m_BMPTool, TL);

    wxPoint TL2 = TL;
    TL2.x += m_BMPTool.GetSize().x + GAP;

    m_DropTool = wxRect(TL2, m_BMPDrop.GetSize());

    pdc.DrawBitmap(m_BMPDrop, TL2);
}

Things work but I have the following related questions:

  1. When the mouse is over, it is not highlighted like the other controls (such as button etc...). How to add highlighting effect?
  2. I add the control to ToolBar and I realized the overriden member function DoGetBestSize is never called.

Any ideas appreciated.


Solution

  • You need to catch wxEVT_MOUSE_ENTER and _LEAVE events to be notified when the mouse cursor enters and leaves the window and be able to refresh your button -- and then take into account whether the mouse is over it or not when repainting.

    DoGetBestSize() is only used if the best size of the control needs to be determined. If you specify its size when creating it, it's not going to be called.