1
votes

I am trying to implement a custom wxWidgets widget in which a minus-button and a plus-button are placed next to each other.

To implement this, I let my custom widget class inherit from wxPanel, and place out two buttons using a horizontal wxBoxSizer:

#include <wx/wx.h>

class CustomWidget : public wxPanel{
private:
    wxButton* m_minusButton;
    wxButton* m_plusButton;
public:

    CustomWidget(wxWindow *parent, const wxPoint& pos):  wxPanel(parent, wxID_ANY, pos, wxSize(-1, -1), wxBORDER_NONE){

    wxBoxSizer *hbox = new wxBoxSizer(wxHORIZONTAL);

    m_minusButton = new wxButton(this, wxID_ANY, wxT("-"), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT );
    m_plusButton = new wxButton(this, wxID_ANY, wxT("+"), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT );

    hbox->Add(m_minusButton, 1, wxALL, 5);
    hbox->Add(m_plusButton, 1, wxALL, 5);
    hbox->SetSizeHints(this);

    this->SetSizer(hbox);
    }
};

My application is divided into a left and a right pane. I place out the custom widget in the right pane. Here is a greatly simplified version of my application:

class TestFrame: public wxFrame{
    wxPanel *m_lp;
    wxPanel *m_rp;
public:
    TestFrame(): wxFrame(NULL, wxID_ANY, "Title", wxDefaultPosition, wxSize(400,400)){
    wxBoxSizer *hbox = new wxBoxSizer(wxHORIZONTAL);

    m_lp = new wxPanel(this,-1, wxPoint(-1, -1), wxSize(-1, -1), wxBORDER_SUNKEN);
    m_rp = new wxPanel(this,-1, wxPoint(-1, -1), wxSize(-1, -1), wxBORDER_SUNKEN);

    hbox->Add(m_lp, 1, wxEXPAND | wxALL, 5);
    hbox->Add(m_rp, 1, wxEXPAND | wxALL, 5);

    this->SetSizer(hbox);

    new CustomWidget(m_rp, wxPoint(50,100));
    }
};

class TestApp: public wxApp{
public:
    virtual bool OnInit() {
    TestFrame *frame = new TestFrame();
    frame->Show( true );
    return true;
    }
};

wxIMPLEMENT_APP(TestApp);

If you compile and run this program, the result can be seen in the following image:

http://i.imgur.com/JcRJJKi.png

The desired result is that a minus-button and a plus-button are drawn next to each other. However, it appears that the plus-button is drawn on top of the minus-button.

How can I fix so that the buttons are drawn next to each other?

1

1 Answers

1
votes

I think this is simply due to the fact that your CustomWidget never gets a resize event and so is never laid out, so just calling Layout() on it explicitly (either at the end of its ctor or after creating it) should fix the problem.

FWIW usually this problem doesn't arise because widgets are positioned by sizers and get a resize event when they're put in place, but as you create this one at a fixed position and it's not managed by a sizer, it never gets any size events.

Finally, I'm not sure why do you need plus/minus buttons but if you're going to use them in conjunction with any listbox-like control, you could be interested in wxAddRemoveCtrl available in the latest git master and which tries to implement the native look for all of the major platforms.