自定义 wxWidgets 小部件中彼此相邻的两个按钮

Two buttons next to each other in a custom wxWidgets widget

我正在尝试实现一个自定义 wxWidgets 小部件,其中一个减号按钮和一个加号按钮彼此相邻放置。

为了实现这个,我让我的自定义小部件 class 继承自 wxPanel,并使用水平 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);
    }
};

我的应用程序分为左窗格和右窗格。我将自定义小部件放在右窗格中。这是我的应用程序的一个大大简化的版本:

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);

如果编译运行这个程序,结果如下图所示:

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

期望的结果是一个减号按钮和一个加号按钮彼此相邻绘制。但是,加号按钮似乎绘制在减号按钮之上。

我该如何解决才能使按钮彼此相邻绘制?

我认为这仅仅是因为您的 CustomWidget 从未获得调整大小事件,因此从未布局,因此只需显式调用 Layout() 即可(无论是在它的 ctor 或创建它之后)应该可以解决问题。

FWIW 通常不会出现此问题,因为小部件由 sizer 定位并在放置到位时获得调整大小事件,但是当您在固定位置创建它并且它不受 sizer 管理时,它永远不会发生任何规模的事件。

最后,我不确定您为什么需要 plus/minus 按钮,但如果您要将它们与任何类似列表框的控件结合使用,您可能会对 wxAddRemoveCtrl 感兴趣在最新的 git master 中可用,它试图为所有主要平台实现原生外观。