Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if Component has a Text Property

How can I check if the component has a text property. As I read Rtti will be a good soulution but I did not worked with it before. Any help would be greatly appreciated.

function HasTextProp(aControl: TControl): Boolean;
begin
  Result := False;
  if (aComponent is ?) then
     Exit(True);
end;

var
  ObjList: TObjectList<TControl>;
  ObjIdx: Integer;
begin
   ObjList := TObjectList<TControl>.Create,
   ObjList.Add(comp1); {is TcxButton}
   ObjList.Add(comp2); {is Tedit}
   ObjList.Add(comp3); {is TDateTimeEdit}

  for ObjIdx := 0 to lObjList.Count -1 do
  begin
    if HasTextProp(lObjList.Items[ObjIdx]) then
      do something...
  end;
end;
like image 799
Steve88 Avatar asked Mar 03 '26 19:03

Steve88


2 Answers

For example for published properties:

uses
  System.TypInfo;

function HasTextProp(AControl: TControl): Boolean;
begin
  Result := IsPublishedProp(AControl, 'Text');
end;
like image 78
Victoria Avatar answered Mar 06 '26 14:03

Victoria


Victoria showed you how to accomplish your goal using old-style RTTI, which works only with published properties and nothing else. In Delphi 2010 and later, there is a new-style RTTI that works with almost everything (private/protected/public/published, properties, data members, etc), and can also accomplish your goal, eg:

uses
  ..., System.TypInfo, System.Rtti;

function HasTextProp(aControl: TControl): Boolean;
var
  Ctx: TRttiContext;
  Prop: TRttiProperty;
begin
  Prop := Ctx.GetType(aControl.ClassType).GetProperty('Text');
  Result := (Prop <> nil) and (Prop.Visibility in [mvPublic, mvPublished]);
end;    

TRttiProperty has GetValue() and SetValue() methods, eg:

var
  Ctrl: TControl
  Ctx: TRttiContext;
  Prop: TRttiProperty;
begin
  ...
  Ctrl := lObjList.Items[ObjIdx];
  Prop := Ctx.GetType(Ctrl.ClassType).GetProperty('Text');
  if (Prop <> nil) and (Prop.Visibility in [mvPublic, mvPublished]) then
  begin
    if Prop.GetValue(Ctrl).IsEmpty then
      Prop.SetValue(Ctrl, 'Not Empty Anymore!');
  end;
  ...
end;
like image 33
Remy Lebeau Avatar answered Mar 06 '26 12:03

Remy Lebeau