Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a custom component handle events of its children?

I'm designing a panel descendant component that has a button control on it:

THidePanel = class(TPanel)
private
  TActivateButton: TButton;
public
  constructor Create(aOwner: TComponent); override;
  procedure WMSize(var Msg: TWMSize); message WM_SIZE;
  procedure HideComponents;
end;

How can this component handle the OnClick event of its TActivateButton control?

like image 606
Franz Avatar asked Feb 16 '23 21:02

Franz


1 Answers

As the button is private to the component you can just attach an eventhandler to it, ie

THidePanel = class(TPanel)
  ...
  private
    procedure H_ActivateButtonClick(Sender: TObject);
  ...
end;

constructor THidePanel.Create(aOwner: TComponent);
begin
  inherited;
  ...
  FActivateButton := TButton.Create(Self);
  FActivateButton.Parent := Self;
  FActivateButton.OnClick:= H_ActivateButtonClick;
end

procedure THidePanel.H_ActivateButtonClick(Sender: TObject)
begin
  // button is clicked!
end

If you also need to provide an event to the end user of the compnent then you need to add an TNotifyEvent property and call it from your internal handler, ie

THidePanel = class(TPanel)
  private
    FOnActivateBtnClick: TNotifyEvent;
  ...
  published
    property OnActivateButtonClick: TNotifyEvent read FOnActivateBtnClick write FOnActivateBtnClick;
end;

procedure THidePanel.H_ActivateButtonClick(Sender: TObject)
begin
  // button is clicked!
  ...
  // fire the end user event
  if(Assigned(FOnActivateBtnClick))then FOnActivateBtnClick(Self);
end
like image 66
ain Avatar answered Feb 22 '23 12:02

ain