【问题标题】:Runtime creation of Delphi Firemonkey components from a string从字符串运行时创建 Delphi Firemonkey 组件
【发布时间】:2016-08-26 21:43:29
【问题描述】:

如何在运行时创建一个可视化组件作为最终使用 RTTI 的表单的子级? 我得到的只是一个 TValue 实例...

 t := (ctx.FindType(Edit1.Text) as TRttiInstanceType);
 inst:= t.GetMethod('Create').Invoke(t.MetaclassType,[Form1]);

谢谢!

【问题讨论】:

    标签: delphi firemonkey rtti


    【解决方案1】:

    使用 TRttiMethod.Invoke() 的纯 RTTI 方法如下所示:

    var
      ctx: TRttiContext;
      t: TRttiInstanceType;
      m: TRttiMethod;
      params: TArray<TRttiParameter>;
      v: TValue;
      inst: TControl;
    begin
      t := ctx.FindType(Edit1.Text) as TRttiInstanceType;
      if t = nil then Exit;
      if not t.MetaclassType.InheritsFrom(TControl) then Exit;
      for m in t.GetMethods('Create') do
      begin
        if not m.IsConstructor then Continue;
        params := m.GetParameters;
        if Length(params) <> 1 then Continue;
        if params[0].ParamType.Handle <> TypeInfo(TComponent) then Continue;
        v := m.Invoke(t.MetaclassType, [TComponent(Form1)]);
        inst := v.AsType<TControl>();
        // or: inst := TControl(v.AsObject);
        Break;
      end;
      inst.Parent := ...;
      ...
    end;
    

    不使用TRttiMethod.Invoke() 的更简单的方法如下所示:

    type
      // TControlClass is defined in VCL, but not in FMX
      TControlClass = class of TControl;
    
    var
      ctx: TRttiContext;
      t: TRttiInstanceType;
      inst: TControl;
    begin
      t := ctx.FindType(Edit1.Text) as TRttiInstanceType;
      if t = nil then Exit;
      if not t.MetaclassType.InheritsFrom(TControl) then Exit;
      inst := TControlClass(t.MetaclassType).Create(Form4);
      inst.Parent := ...;
      //...
    end;
    

    【讨论】:

    • 非常感谢,成功了,但是如果我需要设置控件的 Text 属性怎么办?
    • TextTTextControl 的公共属性,它派生自TControl。因此,要么将inst 类型转换为TTextControl 以直接访问Text,要么使用RTTI 为Text 获取TRttiProperty,然后调用TRttiProperty.SetValue()
    • 好的!我会选择第一个选项!谢谢!
    猜你喜欢
    • 2019-05-09
    • 2013-02-21
    • 2010-11-03
    • 1970-01-01
    • 2012-06-23
    • 2016-12-02
    • 2011-12-02
    • 2012-11-23
    • 2015-01-31
    相关资源
    最近更新 更多