wxwidgets 连接到成员类中的函数

wxwidgets connect to function in member class

本文关键字:函数 成员类 连接 wxwidgets      更新时间:2023-10-16

Header:我有一个带有测试函数和面板的类

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

我希望该类在我的主窗口上创建一个文本控件。作为我使用的函数

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("%sn", "testfunc was called");
}

我的主窗口头文件包含指向这两个类的指针:

页眉:

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();
问题是,我

无法从主窗口函数将testsublass函数testfunc链接到这样的事件,当我尝试执行以下操作时,我会收到一些神秘的编译器消息:

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

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

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

由于我计划在面板上创建很多按钮,因此我更喜欢在成员类中定义函数,而不是为每个按钮/文本控件窗口单独编写一个函数来控制所有窗口。

这可能是一个新手问题,但我会感谢任何形式的帮助

您需要

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

,您需要调用
Connect(id, wxEVT_COMMAND_TEXT_UPDATED, wxCommandEventHandler(testsubclass::testfunc), NULL, mysubclass);

但是您仍然需要决定要/需要调用哪个对象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)

那修复了它。