wx位图按钮读取类参数

wxBitmapButton reading class parameters

本文关键字:参数 读取 按钮 位图 wx      更新时间:2023-10-16

我已经尝试解决这个问题几个小时了,但我的wxWidgets知识(我是初学者)和在线寻找答案都没有帮助我解决这个问题。

我创建了一个名为 Field 的类,其中包含三个参数 int xint ywxBitmapButton 按钮。现在,我要做的是,当单击该按钮时,连接到按钮的事件处理程序将从包含所用按钮同一类实例中读取 xy

本质上,我想要实现的是通过单击字段::按钮来读取给定的坐标字段::x,字段::y。有人可以帮助我完成这项任务吗?

我假设Field本身不是一个小部件(如果是这样,事情是相似的,你只需要改变它的创建方式)。一种写法是:

struct Field
{
   Field(int x_, int y_) : x(x_), y(y_) { }
   void set_button(wxBitmapButton* btn)
   {
      button = btn;
      button->Bind(wxEVT_BUTTON, [this](wxCommandEvent&)
      {
         //Do whatever you want with x and y 
         //(they're accessed through the captured this pointer).
         //For example:
         wxMessageBox(std::to_wstring(x) + ", " + std::to_wstring(y));
      });
   }
   int x;
   int y;
   wxBitmapButton* button = nullptr;
};

要测试它,您可以创建一个简单的窗口,如下所示:

struct test_frame : wxFrame
{
   test_frame() : wxFrame(nullptr, wxID_ANY, L"Test"), fld(3, 7) { }
   //fld doesn't have to be a member of the wxFrame-derived class; 
   //it just needs to live at least as long as the button it references.
   //This is just an example that satisfies that condition.
   Field fld;
};

并像这样初始化所有内容:

auto main_frame = new test_frame();
auto btn = new wxBitmapButton(main_frame, wxID_ANY, your_bitmap);
main_frame->fld.set_button(btn);
main_frame->Show();

单击按钮时,您将弹出一个消息框,显示3, 7(当然xy中的任何值)。


所有这些代码都假设你有一个相当最新的编译器 - 如您所见,它使用了相当多的 C++11 功能。当然,这一切都可以通过许多其他方式完成,但现代C++使事情变得如此美好和简单,我就是无法抗拒......