c++builder 动态创建控件及销毁

来源:互联网 发布:安卓变女声软件 编辑:程序博客网 时间:2024/05/21 18:43
创建控件: 其实创建控件相对简单。。。  直接生成需要数量的控件实例即可。 
for(int i=0;i<4;i++)           {                for(int j=0;j<MaxNum;j++)                {                     TLabel *tl = new TLabel(Application);                     tl->Left = i*100+100;                     tl->Top = j*70+50;                     tl->Caption = "测试label";                     tl->AutoSize = true;                     tl->Enabled = true;                     tl->Parent = gbox1;                     labelNum++;                }           }


销毁控件:

在我的bcb6环境下,我使用下边的代码销毁控件时报错:

 

for(int j=0;j<gbox1->ControlCount;j++)               {                    delete gbox1->Controls[j];               }

 

 如果使用这种控制方法删除,每次只能删除不超过总控件数一半的控件:

 

for(int j=0;j<gbox1->ControlCount;j++)                     {                           if(gbox1->Controls[j]->ClassType() == __classid(TLabel))                           {                                 delete  gbox1->Controls[j]; //gbox1->Controls[j]->Visible = false;                           }                     }


最终,只有通过递归,根据控件数量来计算执行上述代码断次数。  反正,这种方法是解决我的问题。

 

我的  创建/销毁 按钮的代码为:

 if(flag ==0)        {           int MaxNum = 3;           for(int i=0;i<4;i++)           {                for(int j=0;j<MaxNum;j++)                {                     TLabel *tl = new TLabel(Application);                     tl->Left = i*100+100;                     tl->Top = j*70+50;                     tl->Caption = "测试label";                     tl->AutoSize = true;                     tl->Enabled = true;                     tl->Parent = gbox1;                     labelNum++;                }           }           flag = 1;           Button1->Caption = "销毁";        }        else        {                 int t = 0;                 int k = fun(labelNum);                 for(int i=0;i<k;i++)                 {                     for(int j=0;j<gbox1->ControlCount;j++)                     {                           if(gbox1->Controls[j]->ClassType() == __classid(TLabel))                           {                                 delete  gbox1->Controls[j]; //gbox1->Controls[j]->Visible = false;                           }                     }                 }            flag = 0;            Button1->Caption = "创建";        } 

递归函数 fun(int n)代码为:

int __fastcall TForm1:: fun(int n){    if(n%2 == 1 && (n!=1))    {            t++;            n = (n-1)/2;            fun(n);    }    else if(n%2 ==0&&(n!=0))    {            t++;            n = n/2;            fun(n);    }    else if(n == 1)    {            t++;            return t;    }    else    {            return 0;    }}


 

原创粉丝点击