wxwidgets 连接到成员 class 中的函数

wxwidgets connect to function in member class

Header: 我有 class 带有测试功能和面板

class testsubclass{
      public:
         testsubclass();
         void testfunc(wxCommandEvent &event);
};

class panelonwindow : public wxPanel{
      public:
         panelonwindow(wxWindow *windowid, int ID);
         wxWindow *mywindow, *mypanel;
         wxTextCtrl *mytextcontrol;

         void maketextctrl(std::string label, int &id);
}

我希望 class 在我的主 window 上创建一个文本控件。作为我使用的函数

testsubclass::testsubclass(){
}

panelonwindow::panelonwindow(wxWindow *windowid, int ID)
    :wxPanel(windowid, ID, wxDefaultPosition, wxSize(150, 150)){
        mywindow = windowid;
        mypanel = this;
};

void panelonwindow::maketextctrl(std::string label, int &id){
    wxString newlabel(label.c_str(), wxConvUTF8);
    mytextcontrol = new wxTextCtrl(mypanel, id, newlabel, wxDefaultPosition, wxSize(130, 30));
}


void testsubclass::testfunc(wxCommandEvent &event){
    printf("%s\n", "testfunc was called");
}

我的主 window header 文件包含指向这两个 class 的指针:

Header:

wxWindow *mainwindow;
testsubclass *mysubclass;
panelonwindow *testpanel;
int ID1 = 100;
int ID2 = 101;

现在主要功能如下所示:

mainwindow = this;
std::string textcontrolstring = "this is a test";
testpanel = new panelonwindow(mainwindow, ID);
testpanel->maketextctrl(textcontrolstring, ID2);

mysubclass = new testsubclass();

问题是,我不能 link testsublass 函数 testfunc 从主 window 函数到这样的事件,当我尝试做这样的事情时,我得到一些神秘的编译器消息:

Connect(ID2, wxEVT_COMMAND_TEXT_UPDATED,
    wxCommandEventHandler(mysubclass->testfunc));

我可以 link 从 void panelonwindow::maketextctrl 到 panelonwindow 函数的另一个成员的事件(前提是我以类似 void panelonwindow::testfunc 的方式声明它们(wxCommandEvent &事件)

void panelonwindow::maketextctrl(std::string label, int &id){
    wxString newlabel(label.c_str(), wxConvUTF8);
    mytextcontrol = new wxTextCtrl(mypanel, id, newlabel, wxDefaultPosition, wxSize(130, 30));

Connect(id, wxEVT_COMMAND_TEXT_UPDATED,
    CommandEventHandler(panelonwindow::testfunc))
}

因为我计划在一个面板上创建很多按钮,所以我更喜欢在成员 class 中定义函数,而不是为每个 button/textcontrolwindow 单独编写一个函数来控制所有 windows.

这可能是一个新手问题,但我将不胜感激任何帮助

您需要在生成事件的对象上调用 Connect() 并将处理它的对象传递给它(否则 wxWidgets 将如何确定将事件发送到哪个对象?它无法读取您的代码来找出)。因此,要在 testsubclass::testfunc() 中处理 evnet,您需要调用

Connect(id, wxEVT_COMMAND_TEXT_UPDATED, wxCommandEventHandler(testsubclass::testfunc), NULL, mysubclass);

但您仍然需要决定 want/need 调用哪个对象 Connect()

如果你使用 wxWidgets 3(你应该),考虑使用更短的事件类型名称和更现代的 Bind() 因为它更清晰和更短:

Bind(wxEVT_TEXT, &testsubclass::testfunc, mysubclass, id);

这在很大程度上解决了问题。然而,部分

Connect(id, wxEVT_COMMAND_TEXT_UPDATED,  CommandEventHandler(testsubclass::testfunc), NULL, mysubclass);

还是不行。我用

代替了它
Connect(id, wxEVT_COMMAND_TEXT_UPDATED,
(wxObjectEventFunction) (wxEventFunction) (wxCommandEventFunction) &testsubclass::testfunc,
NULL, mysubclass)

修复了它。