加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

delphi – 按标题搜索标签

发布时间:2020-12-15 10:12:26 所属栏目:大数据 来源:网络整理
导读:我试图找出如何通过其标题搜索标签: for I := ComponentCount - 1 downto 0 dobegin if Components[i] is TLabel then if Components[i].Caption = mnNumber then begin Components[i].Left := Left; Components[i].Top := Top + 8; end;end; 我收到一个错
我试图找出如何通过其标题搜索标签:
for I := ComponentCount - 1 downto 0 do
begin
  if Components[i] is TLabel then
    if Components[i].Caption = mnNumber then
    begin
      Components[i].Left := Left;
      Components[i].Top := Top + 8;
    end;
end;

我收到一个错误:未声明的标识符:’标题’.
我该如何解决这个问题?

解决方法

最后一条信息在您对Golez答案的评论中落实到位:您的标签是在运行时创建的,因此他们有可能没有表格作为所有者.您需要使用Controls []数组来查看表单父级的所有控件,并以递归方式查看所有TWinControl后代,因为它们也可能包含TLabel.

如果你要做这个分配和不同类型的控件,你可能想要实现某种帮助,所以你不要经常重复自己.看看大卫的答案,为现成的解决方案设法包括一些“花里胡哨”,除了解决手头的问题;就像使用匿名函数来操作找到的控件的能力一样,它能够使用匿名函数根据任何条件过滤控件.

在开始使用这样一个复杂的解决方案之前,您应该了解最简单的解决方案.一个非常简单的递归函数,它只是从表单开始查看所有容器上的所有TControl.像这样的东西:

procedure TForm1.Button1Click(Sender: TObject);

  procedure RecursiveSearchForLabels(const P: TWinControl);
  var i:Integer;
  begin
    for i:=0 to P.ControlCount-1 do
      if P.Controls[i] is TWinControl then
        RecursiveSearchForLabels(TWinControl(P.Controls[i]))
      else if P.Controls[i] is TLabel then
        TLabel(P.Controls[i]).Caption := 'Test';
  end;

begin
  RecursiveSearchForLables(Self);
end;

使用David的通用代码,上面的内容可以重写为:

procedure TForm1.Button1Click(Sender: TObject);
begin
  TControls.WalkControls<TLabel>(Self,nil,procedure(lbl: TLabel)
    begin
      lbl.Caption := 'Test';
    end
  );
end;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读