4

Check this simplified sample (the real scenario is different), I want to set tne value of a nested property of a object, in this case set the color of the Font for a TLabel component to clRed using RTTI.

var
  p : TRttiProperty;
  p2: TRttiProperty;
  c : TRttiContext;
begin
   c := TRttiContext.Create;
   try
     p := c.GetType(Label1.ClassInfo).GetProperty('Font');
     p2 := c.GetType(p.PropertyType.Handle).GetProperty('Color');
     p2.SetValue(p.PropertyType.AsInstance,clred); //this line is not working
   finally
     c.Free;
   end;
end;

also i tried

p2.SetValue(Label1,clred);
Salvador
  • 16,132
  • 33
  • 143
  • 245

1 Answers1

4

The following code will work.

var
  p : TRttiProperty;
  p2: TRttiProperty;
  c : TRttiContext;
begin
   c := TRttiContext.Create;
   try
     p := c.GetType(Label1.ClassInfo).GetProperty('Font');
     p2 := c.GetType(p.PropertyType.Handle).GetProperty('Color');
     p2.SetValue(p.GetValue(Label1).AsObject,clred); //this line now works.
   finally
     c.Free;
   end;
end;

You need to get the Embedded Font from the Label. TRttiProperty deal with types and not instances. You need to call GetValue() or SetValue() to deal with the instance.

Your original code was referencing the type and not the instance.

Robert Love
  • 12,447
  • 2
  • 48
  • 80