[英]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.