How can I set the value of a nested property using RTTI

Check this simplified sample (the real scenario is different), I want to set the value of the attached property of the object, in this case set the font color for the 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); 
+3
source share
1 answer

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 deals with types, not instances. You need to call GetValue() or SetValue() to work with the instance.

Your source code referred to a type, not an instance.

+3
source

All Articles