delphi – 在运行时复制组件

前端之家收集整理的这篇文章主要介绍了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.f2er.com/delphi/102439.html

猜你在找的Delphi相关文章