如何删除已创建的标签,我google了很长时间但没有显示!我尝试了FindComponent
但是faild,我必须做什么?我应该将父母设置为其他组件,如TPanel或什么?我感到很困惑!
procedure TForm1.Button1Click(Sender: TObject);
var
lblLink : TLabel;
begin
for i := 0 to stringtList.Count-1 do
begin
lblLink := TLabel.create(self);
with lblLink do
begin
name:='lblLink'+inttostr(i);
caption:inttostr(i);
Parent := self;
font.style := [fsUnderline];
cursor := crHandPoint;
color := clBlue;
font.Color := clBlue;
end;
end;
end;
答案 0 :(得分:10)
您可以迭代Components属性,然后检查组件的名称,最后释放组件。
Var
LIndex : Integer;
LComponent : TComponent;
begin
for LIndex := ComponentCount-1 downto 0 do
if StartsText('lblLink',Components[LIndex].Name) then
begin
LComponent:=Components[LIndex];
FreeAndNil(LComponent);
end;
end;
答案 1 :(得分:3)
你不必释放它。您有责任将其释放到lblLink := TLabel.create(self);
的表单中。表单将在表单释放时释放标签。
然而,话虽如此,您可以通过循环遍历表单的Components
数组来释放它:
procedure TForm1.DeleteLabel(const LabelName: string);
var
i: Integer;
begin
for i := ComponentCount - 1 downto 0 do
begin
if Components[i] is TLabel then
if Components[i].Name = LabelName then
begin
Components[i].Free;
Break;
end;
end;
end;
答案 2 :(得分:3)
您为每个Owner
分配了Parent
和TLabel
,因此从技术上讲,您根本不需要释放它们。所有者和家长都将为您处理。但是,如果您想提前释放它们,则可以遍历所有者的Components
列表或父级Controls
列表,手动搜索标签。更好的选择是保留您自己创建的标签列表,然后您可以在需要时循环遍历该列表,例如:
type
TForm1 = class(TForm)
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
...
private
Labels: TList;
procedure FreeLabels;
...
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
Labels := TList.Create;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
Labels.Free;
end;
procedure TForm1.FreeLabels;
var
I: Integer;
begin
for I := 0 to Labels.Count-1 do
TLabel(Labels[I]).Free;
Labels.Clear;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
lblLink : TLabel;
...
begin
...
for I := 0 to StringList.Count-1 do
begin
lblLink := TLabel.Create(Self);
try
with lblLink do
begin
Name := 'lblLink' + IntToStr(i);
Parent := Self;
Caption := IntToStr(i);
Font.Style := [fsUnderline];
Cursor := crHandPoint;
Color := clBlue;
Font.Color := clBlue;
end;
Labels.Add(lblLink);
except
lblLink.Free;
raise;
end;
end;
end;