微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

delphi – 在运行时复制组件

是否有一种简单的方式来复制父组件下的所有子组件,包括其已发布的属性

例如:

> TPanel

> TLabel
> TEdit
> TListView
> TSPecialClassX

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

我听说过RTTI,但从来没有用过它.有任何想法吗?

解决方法

阅读本页

Run-Time Type Information In Delphi – Can It Do Anything For You?

注意部分Copying Properties From A Component To Another

它有一个单元,RTTIUnit与过程,似乎做了你想要的一部分,但我不认为它会复制任何子组件与额外的代码.
(我认为它可以粘贴在这里…)

procedure copyObject(ObjFrom,ObjTo: TObject);    
  var
PropInfos: PPropList;
PropInfo: PPropInfo;
Count,Loop: Integer;
OrdVal: Longint;
StrVal: String;
FloatVal: Extended;  
MethodVal: TMethod;
begin
//{ Iterate thru all published fields and properties of source }
//{ copying them to target }

//{ Find out how many properties we'll be considering }
Count := GetPropList(ObjFrom.ClassInfo,tkAny,nil);
//{ Allocate memory to hold their RTTI data }
GetMem(PropInfos,Count * SizeOf(PPropInfo));
try
//{ Get hold of the property list in our new buffer }
GetPropList(ObjFrom.ClassInfo,PropInfos);
//{ Loop through all the selected properties }
for Loop := 0 to Count - 1 do
begin
  PropInfo := GetPropInfo(ObjTo.ClassInfo,PropInfos^[Loop]^.Name);
 // { Check the general type of the property }
  //{ and read/write it in an appropriate way }
  case PropInfos^[Loop]^.PropType^.Kind of
    tkInteger,tkChar,tkEnumeration,tkSet,tkClass{$ifdef Win32},tkWChar{$endif}:
    begin
      OrdVal := GetordProp(ObjFrom,PropInfos^[Loop]);
      if Assigned(PropInfo) then
        SetordProp(ObjTo,PropInfo,OrdVal);
    end;
    tkFloat:
    begin
      FloatVal := GetFloatProp(ObjFrom,PropInfos^[Loop]);
      if Assigned(PropInfo) then
        SetFloatProp(ObjTo,FloatVal);
    end;
    {$ifndef DelphiLessthan3}
    tkWString,{$endif}
    {$ifdef Win32}
    tkLString,{$endif}
    tkString:
    begin
      { Avoid copying 'Name' - components must have unique names }
      if UpperCase(PropInfos^[Loop]^.Name) = 'NAME' then
        Continue;
      StrVal := GetStrProp(ObjFrom,PropInfos^[Loop]);
      if Assigned(PropInfo) then
        SetStrProp(ObjTo,StrVal);
    end;
    tkMethod:
    begin
      MethodVal := getmethodProp(ObjFrom,PropInfos^[Loop]);
      if Assigned(PropInfo) then
        SetMethodProp(ObjTo,MethodVal);
    end
  end
end
finally
  FreeMem(PropInfos,Count * SizeOf(PPropInfo));
end;
end;

原文地址:https://www.jb51.cc/delphi/102439.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐