【问题标题】:Get TextSettings.Font.Style property with GetObjectProp using Delphi Tokyo 10.2使用 Delphi Tokyo 10.2 使用 GetObjectProp 获取 TextSettings.Font.Style 属性
【发布时间】:2017-08-31 02:30:22
【问题描述】:

我在使用Delphi的GetObjectProp函数获取表单组件的属性,我获取了几个组件的所有属性,但是获取不到TextSettings.Font.Style(Bold, Italic, ...)的属性例如像 TLabel 这样的组件。我需要知道组件文本是粗体还是斜体。我正在尝试获取这些属性的过程如下:

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; 

我上面标记的那一行显示的错误是。

[dcc64 Error] uPrincipal.pas(1350): E2015 运算符不适用于此操作数类型

我做错了什么?

【问题讨论】:

  • 在示例中我简化了代码以便更好地理解,但在实际应用程序中它更复杂,组件在运行时创建并且可以是任何类,所以我使用 rtti。我将其更改为 TFontStyles segestao,但错误仍然存​​在。
  • Style 属于TFontStyles 类型,它不是对象类型,而是类型属性的集合。而fsBold 不是属性,而是该集合的可能成员。
  • 但是如果不是对象类型,如何获取属性呢?
  • 使用GetOrdProp。 Set 只是一个序数值,您可以通过 in 运算符查询成员。或者如果要将集合成员打印为字符串,可以使用GetSetProp

标签: delphi firemonkey


【解决方案1】:

GetObjectProp(Fonte, 'Style') 将不起作用,因为Style 不是一个基于对象的属性,它是一个基于Set 的属性。而GetPropValue(Estilo, 'fsBold', true) 完全是错误的(并不是说你无论如何都会调用它),因为fsBold 不是属性,它是TFontStyle 枚举的成员。要检索Style 属性值,您必须使用GetOrdProp(Fonte, 'Style')GetSetProp(Fonte, 'Style')GetPropValue(Fonte, 'Style')(分别作为integerstringvariant)。

话虽如此,一旦您检索到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; 

更好(和首选)的解决方案是根本不使用 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; 

阅读 Embarcadero 的文档了解更多详情:

Setting Text Parameters in FireMonkey

【讨论】:

  • 谢谢,我要去码头看医生。您提供的示例代码显示错误 [dcc64 Error] uPrincipal.pas (1343): E2003 Undeclared identifier: 'fsBold'
  • @Juliano:那是因为 FMX 使用scoped enums。请改用TFontStyle.fsBold
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-14
  • 1970-01-01
相关资源
最近更新 更多