访问自定义wxPanel中的子项

Access child in customized wxPanel

本文关键字:自定义 wxPanel 访问      更新时间:2023-10-16

所以我有一个从wxPanel继承的类MyPanel:

 class MyPanel : public wxPanel
 {
       public:
          MyPanel(wxWindow* parent) : wxPanel(parent){}
          void OnMouseMove(wxMouseEvent& event);
       private:
          DECLAER_EVENT_TABLE()
  };

以及下面定义的另一个主要wxframe:

 class mainFrame : public wxFrame
 {
       ...
       private:
          ...
          MyPanel* myPanel;
          ...
          wxStaticText* StaticText1;
          ...
 };

StaticText1最终将被分配为myPanel的子级。所以我想在方法OnMouseMove()中更新鼠标光标的坐标

我想知道如何访问StaticText1并更新内容。

使用友元声明,如下所示:

class mainFrame : public wxFrame
{
  friend class MyPanel;
  ...
};

您可以在MyPanel中定义一个成员,并在需要时将StaticText1分配给它。在OnMouseMove检查中,如果StaticText1是否为NULL。

 class MyPanel : public wxPanel
  {
        public:
           MyPanel(wxWindow* parent) : wxPanel(parent){}
           void OnMouseMove(wxMouseEvent& event) { if (StaticText1) { /* do something */ } ;
           void SetStaticText1(wxStaticText* txt) { StaticText1 = txt;}
        private:
           DECLAER_EVENT_TABLE()
           wxStaticText* StaticText1;
   };

从编程的角度来看,您可以使用朋友解决方案。然而,从逻辑上讲,如果wxStaticText*StaticText1将由MyPanel作为父级,并且主要从MyPanel的一个成员函数中引用/更新。那么wxStaticText最好在MyPanel中声明和定义,而不是在mainFrame中。