如何向wxwidgets中的类中创建的按钮添加命令

How to add commands to buttons created from within a class in wxwidgets?

本文关键字:按钮 添加 命令 创建 wxwidgets      更新时间:2023-10-16

我搜索了很长一段时间,考虑了不同的选择,现在我完全被难住了。我创建了一个简单的类,它创建了16个按钮,并在构造函数中为它们分配了id。我想每个按钮都有一个事件触发时点击。

头文件中的类:

class step16
{
    ///signals and buttons
private:
    wxButton*       sequencer              [16];
    long*           ids          = new long[16];
public:
    step16(wxFrame* frame);
    ~step16();
};

源文件中函数的声明:

///constructor for 16 step sample sequencer class
step16::step16(wxFrame* frame)
{
    ///clear all signals on initialization and create buttons
    for(int i = 0; i < 16; i++){
        ids      [i] = wxNewId();
        sequencer[i] = new wxButton(frame,ids[i],wxString::Format(_("")),
                                    wxPoint(i*30 ,     0,wxSize(30,20) );
    }
}
///destructor for the 16 step sequencer class
step16::~step16(){delete[]signals;}

我知道如何在wxWidgets中添加单击事件到按钮的唯一方法是在主wxFrame的初始化部分使用Connect()方法,但是在程序的该部分连接它们不会带来期望的结果。主要是因为我需要在step16类的每个实例中使用一组新的16个具有唯一id和事件的按钮。如何为每个按钮添加唯一点击事件?

您可以使用Bind来绑定从wxEventHandler派生的任何类中的处理程序(即几乎任何标准wxWidgets类,包括wxFrame)。

将按钮的ID传递给Bind()调用,以便您的事件处理程序知道哪个按钮已被按下。

例如,您的step16构造函数可能如下所示:

///constructor for 16 step sample sequencer class
step16::step16(wxFrame* frame)
{
    ///clear all signals on initialization and create buttons
    for(int i = 0; i < 16; i++)
    {
        ids      [i] = wxNewId();
        sequencer[i] = new wxButton(frame,ids[i],wxString::Format(_("")),
                                        wxPoint(i*30,0), wxSize(30,20));
        /// Add it to something so I can test this works!
        frame->GetSizer()->Add(sequencer[i]);
        /// Bind the clicked event for this button to a handler 
        /// in the Main Frame.
        sequencer[i]->Bind(wxEVT_COMMAND_BUTTON_CLICKED, 
                            &MainFrame::OnPress, 
                            (MainFrame*)frame);
    }
}

在这个例子中,我在MainFrame类中创建了事件处理程序,一个指向step16的实例的指针传递给了ctor。

您可以使用event.GetId()来区分按钮按下,这将是由行设置的值:

ids [i] = wxNewId();

MainFrame::OnPress方法可以像这样:

void MainFrame::OnPress(wxCommandEvent& event)
{
    long firstID = *theStep16->GetIDs();
    switch(event.GetId() - firstID)
    {
        case 0:
            std::cout << "First button" << std::endl;
            break;
        case 1:
            std::cout << "Second button" << std::endl;
            break;
        default:
            std::cout << "One of the other buttons with ID " 
                      << event.GetId() << std::endl;
    }
}