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

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

我进行了广泛的搜索,并考虑了很长一段时间的不同选择,但现在完全被难住了。我创建了一个简单的 class,它包含 16 个按钮并在构造函数中为它们分配 ID。我希望每个按钮在单击时都触发一个事件。

Class 在 header:

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 中的按钮的唯一方法是在 Main wxFrame 的初始化部分使用 Connect() 方法,但是在程序的那部分连接它们不会带来预期的结果.主要是因为我需要一组新的 16 个按钮,在 step16 class 的每个实例中都有唯一的 ID 和事件。我将如何为每个按钮添加独特的点击事件?

您可以使用 Bind 绑定派生自 wxEventHandler 的任何 class 中的处理程序(即几乎任何标准 wxWidgets class,包括 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 class 中创建了事件处理程序,一个指向其实例的指针被传递给 step16.[=20= 的 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;
    }
}