how to copy all the TLabels parented with a TPanel on delphi to another TPanel?

后端 未结 2 758
无人共我
无人共我 2021-01-25 21:01

I have a TPanel on a delphi form, I want to copy all the TLabels parented with this TPanel when i press a button and put them in other panel. Is there a way to do that? Thanks.

2条回答
  •  时光说笑
    2021-01-25 21:17

    TPanel is a container of Components. It has a list of its child components in its Controls property. You may iterate over this list to get access to its children.

    At the press of the button your code has to

    1. iterate on the Controls list of Panel1

    2. check if the control is a TLabel

    3. change the Parent property of the TLabel to be Panel2

    something like this

    for i := 0 to Panel1.ControlCount - 1 do
      if Panel1.Controls[i] is TLabel then
        (Panel1.Controls[i] as TLabel).Parent:=Panel2;
    

    But, wait!, this will not work. Why? Because doing this change 'on the fly' you will be changing the very same list you are iterating over.

    So, you have to save the labels to be moved in a temporary list. Something like this...

     var 
      i:integer;
      l:TObjectList;
    
     begin
      l:=TObjectList.Create;
      l.ownsObjects:=False;
      for i := 0 to Panel1.ControlCount - 1 do
       if Panel1.Controls[i] is TLabel then
         l.add(Panel1.Controls[i]);
    
      for i:= 0 to l.Count-1 do
        (l[i] as TLabel).Parent:=Panel2;
    
      l.Free;
     end;
    

提交回复
热议问题