[fpc-devel] Bug in trunk?

Graeme Geldenhuys graemeg.lists at gmail.com
Fri Mar 28 12:40:27 CET 2008


On 28/03/2008, Martin Schreiber <fpmse at bluewin.ch> wrote:
>  > Unrelated (because I think such declarations are
>  > broken for fpu types/values): what code do you have to write so that
>  > this default value is actually used?
>  >
>
> fcolor is initialized to the default value in constructor. TWriter does


Well, you can set the default values automatically without having to
do it manually in the constructor.  :-)  I have been toying with this
idea in fpGUI. All that the developer needs to do is set the default
value in the class declaration.

I created a descendant TComponent class and in the AfterConstructor
method I call the SetDefaults();

procedure TfpgWindowBase.AfterConstruction;
begin
  inherited AfterConstruction;
  { Here is a neater way by using RTTI to set default property
    values all automatically. No need to duplicate the efforts
    and manually set the property default values in the
    constructor. This code is now the same for each
    TfpgWindowBase descendant (which includes GUI widgets) }
  SetDefaults(self);
end;


// This function uses RTTI to automatically set the default values
// of properties. That means we don't have to do it in the
// constructor anymore! :-)
procedure SetDefaults(Obj: TObject);
var
  PropInfos: PPropList;
  Count, Loop: Integer;
begin
  PropInfos := nil;
  { Find out how many properties we'll be considering }
  Count := GetPropList(Obj.ClassInfo, tkPropsWithDefault, nil);
  { Allocate memory to hold their RTTI data }
  GetMem(PropInfos, Count * SizeOf(PPropInfo));
  try
    { Get hold of the property list in our new buffer }
    GetPropList(Obj.ClassInfo, tkPropsWithDefault, PropInfos);
    { Loop through all the selected properties }
    for Loop := 0 to Count - 1 do
      with PropInfos^[Loop]^ do
        { If there is supposed to be a default value... }
        if Default <> NoDefault then
          { ...then jolly well set it }
          SetOrdProp(Obj, PropInfos^[Loop], Default)
  finally
    FreeMem(PropInfos, Count * SizeOf(PPropInfo));
  end;
end;


RTTI can be very handy sometimes!  ;-)


Regards,
  - Graeme -


_______________________________________________
fpGUI - a cross-platform Free Pascal GUI toolkit
http://opensoft.homeip.net/fpgui/



More information about the fpc-devel mailing list