Search code examples
delphidelphi-7

How to respond to changes in fields of object properties in Delphi


In Delphi 7, descend a new component from TGraphicControl, and add a TFont property, implement the paint method to write some string using the TFont property. Install the component.

At design time when you change the TFont property using the property dialog, it will be reflected in your component instantaneously. But when you change individual properties of TFont like Color or Size, your component will not be repainted until you hover over it.

How do I correctly handle changes in fields of object properties?


Solution

  • Assign an event handler to the TFont.OnChange event. In the handler, Invalidate() your control to trigger a repaint. For example:

    type
      TMyControl = class(TGraphicControl)
      private
        FMyFont: TFont;
        procedure MyFontChanged(Sender: TObject);
        procedure SetMyFont(Value: TFont);
      protected
        procedure Paint; override;
      public
        constructor Create(AOwner: TComponent); override;
        destructor Destroy; override;
      published
        property MyFont: TFont read FMyFont write SetMyFont;
      end;
    

    constructor TMyControl.Create(AOwner: TComponent);
    begin
      inherited;
      FMyFont := TFont.Create;
      FMyFont.OnChange := MyFontChanged;
    end;
    
    destructor TMyControl.Destroy;
    begin
      FMyFont.Free;
      inherited;
    end;
    
    procedure TMyControl.MyFontChanged(Sender: TObject);
    begin
      Invalidate;
    end;
    
    procedure TMyControl.SetMyFont(Value: TFont);
    begin
      FMyFont.Assign(Value);
    end;
    
    procedure TMyControl.Paint;
    begin
      // use MyFont as needed...
    end;