gpt4 book ai didi

delphi - 在运行时复制组件

转载 作者:行者123 更新时间:2023-12-03 14:38:29 24 4
gpt4 key购买 nike

有没有一种简单的方法可以复制父组件下的所有子组件,包括它们已发布的属性?

例如:

  • TPanel
    • T标签
    • T编辑
    • TListView
    • TSpecialClassX

当然,最重要的因素是,在正常情况下,它应该复制我放在 TPanel 上的任何新组件,而无需修改代码。

我听说过 RTTI,但从未实际使用过。有什么想法吗?

最佳答案

您可以正确使用CLoneProperties routine from the answer通过父控件在循环中创建重复组件后,将其设置为“Replace visual component at runtime ”。

更新:一些工作代码......

。根据您的问题,我假设您想要复制 WinControl 中包含的控件(因为父级是 TWinControl)。
。由于我不知道您是否也想使用与原始控件相同的事件处理程序来 Hook 重复的控件,因此我为此做出了一个选择。
。您可能想为重复的控件指定一个适当且有意义的名称。

uses
TypInfo;

procedure CloneProperties(const Source: TControl; const Dest: TControl);
var
ms: TMemoryStream;
OldName: string;
begin
OldName := Source.Name;
Source.Name := ''; // needed to avoid Name collision
try
ms := TMemoryStream.Create;
try
ms.WriteComponent(Source);
ms.Position := 0;
ms.ReadComponent(Dest);
finally
ms.Free;
end;
finally
Source.Name := OldName;
end;
end;

procedure CloneEvents(Source, Dest: TControl);
var
I: Integer;
PropList: TPropList;
begin
for I := 0 to GetPropList(Source.ClassInfo, [tkMethod], @PropList) - 1 do
SetMethodProp(Dest, PropList[I], GetMethodProp(Source, PropList[I]));
end;

procedure DuplicateChildren(const ParentSource: TWinControl;
const WithEvents: Boolean = True);
var
I: Integer;
CurrentControl, ClonedControl: TControl;
begin
for I := ParentSource.ControlCount - 1 downto 0 do
begin
CurrentControl := ParentSource.Controls[I];
ClonedControl := TControlClass(CurrentControl.ClassType).Create(CurrentControl.Owner);
ClonedControl.Parent := ParentSource;
CloneProperties(CurrentControl, ClonedControl);
ClonedControl.Name := CurrentControl.Name + '_';
if WithEvents then
CloneEvents(CurrentControl, ClonedControl);
end;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
DuplicateChildren(Panel1);
end;

关于delphi - 在运行时复制组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/239002/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com