繁体   English   中英

在Delphi中删除TLabel

[英]Delete TLabel in Delphi

当前,我动态创建了两个TLabel和一个TEdit,将它们分别命名为LblDesc + i,EdtAmount + i和LblUnit + i-其中i是一个整数,每次添加这3个元素时,我都会将其迭代一次。 元素中的数据仅用于仿真目的。 我现在的问题是删除三个对象。 Ive尝试了free和FreeAndNil,一点都没有运气。 任何帮助是极大的赞赏。

procedure TForm1.BtnAddClick(Sender: TObject);
begin
  LblDesc := TLabel.Create(Self);
  LblDesc.Caption := 'Item '+IntToStr(i);
  LblDesc.Name := 'LblDesc'+IntToStr(i);
  LblDesc.Left := 16;
  LblDesc.Top := 30 + i*30;
  LblDesc.Width := 100;
  LblDesc.Height := 25;
  LblDesc.Parent := Self;

  EdtAmount := TEdit.Create(Self);
  EdtAmount.Text := IntToStr(i);
  EdtAmount.Name := 'EdtAmount'+IntToStr(i);
  EdtAmount.Left := 105;
  EdtAmount.Top := 27 + i*30;
  EdtAmount.Width := 60;
  EdtAmount.Height := 25;
  EdtAmount.Parent := Self;

  LblUnit := TLabel.Create(Self);
  LblUnit.Caption := 'Kg';
  LblUnit.Name := 'LblUnit'+IntToStr(i);
  LblUnit.Left := 170;
  LblUnit.Top := 30 + i*30;
  LblUnit.Width := 50;
  LblUnit.Height := 25;
  LblUnit.Parent := Self;

  i := i+1;
end;

procedure TForm1.BtnRemoveClick(Sender: TObject);
begin
  //Delete

end;

过去,我遇到过与删除某些组件有关的问题,我已经解决了将父组件的组件设置为nil但是现在不再如此,因为TControl的析构函数(如果调用了)已经完成了这项工作。

只需释放组件即可将其删除。

LblUnit.Free;

如果需要按组件名称查找组件,请使用System.Classes.TComponent.FindComponent或在“ Components列表上进行迭代。

for i := ComponentCount-1 downto 0 do begin
  if Components[i].Name = 'LblUnit'+IntToStr(i) then begin
    //TControl(Components[i]).Parent := nil; {uncomment if you have the same issue I've had}
    Components[i].Free;
  end;
  . . .  
end;

编辑

如果索引i用于该组件的名称施工'LblUnit'+IntToStr(i)不位于范围[0..ComponentCount-1]索引必须被相应地修改。

要删除动态创建的组件,您必须具有有效的引用。

您可以组织自己的数组或列表来保留对象,也可以使用现有列表,例如Form.Components[] ,其中包含所有者为Form对象。

在第二种情况下,您必须按名称查找具有FindComponent的所需对象,或遍历Components[]并搜索具有某些功能(名称,类类型,标记等)的组件

最终起作用的答案是:

procedure TForm1.BtnRemoveClick(Sender: TObject);
var
  j: Integer;

begin
  for j := ComponentCount-1 downto 0 do begin
    if Components[j].Name = 'LblDesc'+IntToStr(i-1) then begin
      TControl(Components[j]).Parent := nil;
      Components[j].Free;
    end;
  end;
end;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM