我正在使用Delphi的GetObjectProp函数来获取表单组件的属性,我获得了几个组件的所有属性,但我无法获得像TLabel这样的组件的TextSettings.Font.Style(Bold,Italic,...)属性例如.我需要知道组件文本是粗体还是斜体.我正在尝试获取这些属性的过程如下:
procedure Tfrm1.aoClicarComponente(Sender: TObject);
var
TextSettings: TTextSettings;
Fonte: TFont;
Estilo: TFontStyle;
Componente_cc: TControl;
begin
Componente_cc := TControl(Label1);
if IsPublishedProp(Componente_cc, 'TextSettings') then
begin
TextSettings := GetObjectProp(Componente_cc, 'TextSettings') as TTextSettings;
if Assigned(TextSettings) then
Fonte := GetObjectProp(TextSettings, 'Font') as TFont;
if Assigned(Fonte) then
Estilo := GetObjectProp(Fonte, 'Style') as TFontStyle; // <-- error in this line
if Assigned(Estilo) then
Edit1.text := GetPropValue(Estilo, 'fsBold', true);
end
end;
Run Code Online (Sandbox Code Playgroud)
我在上面标记的行上显示的错误是.
[dcc64错误] uPrincipal.pas(1350):E2015运算符不适用于此操作数类型
我究竟做错了什么?
GetObjectProp(Fonte, 'Style')因为Style不是基于对象的属性,它将无法工作,它是一个Set基于属性的属性.并且GetPropValue(Estilo, 'fsBold', true)是完全错误的(并不是说你无论如何都会被调用它),因为fsBold它不是属性,它是TFontStyle枚举的成员.中检索的Style属性值,你将不得不使用GetOrdProp(Fonte, 'Style'),GetSetProp(Fonte, 'Style')或GetPropValue(Fonte, 'Style')代替(作为integer,string或variant分别).
话虽这么说,一旦你检索了TextSettings对象,你根本不需要使用RTTI来访问它的Font.Style属性,只需直接访问属性.
试试这个:
procedure Tfrm1.aoClicarComponente(Sender: TObject);
var
Componente_cc: TControl;
TextSettings: TTextSettings;
begin
Componente_cc := ...;
if IsPublishedProp(Componente_cc, 'TextSettings') then
begin
TextSettings := GetObjectProp(Componente_cc, 'TextSettings') as TTextSettings;
Edit1.Text := BoolToStr(TFontStyle.fsBold in TextSettings.Font.Style, true);
end;
end;
Run Code Online (Sandbox Code Playgroud)
更好(和首选)的解决方案是根本不使用RTTI.具有TextSettings属性的FMX类也实现了ITextSettings这种情况的接口,例如:
procedure Tfrm1.aoClicarComponente(Sender: TObject);
var
Componente_cc: TControl;
Settings: ITextSettings;
begin
Componente_cc := ...;
if Supports(Componente_cc, ITextSettings, Settings) then
begin
Edit1.Text := BoolToStr(TFontStyle.fsBold in Settings.TextSettings.Font.Style, true);
end;
end;
Run Code Online (Sandbox Code Playgroud)
阅读Embarcadero的文档了解更多详情: