Search code examples
delphifiremonkeydelphi-xe6

Custom button inherited from TButton does not show


I am converting a large project to Firemonkey and we have some custom buttons, which does not show on the form. I have isolated the problem to a very simple project:

With the code below, on both mobile and desktop (using default new applications in Delphi XE6), creating tTestButton1 works fine, but tTestButton2 does not show on the form. How is that possible?

type
tTestButton1 = class(TButton);
tTestButton2 = class(tTestButton1);

tMainForm = class(TForm)
private
  fTestButton: TButton;
public
  constructor Create(aOwner: TComponent); override;
end;

constructor tMainForm .Create(aOwner: TComponent);
begin
  inherited;

//  fTestButton := tTestButton1.Create(Self); // this works fine (used instead of next line)
  fTestButton := tTestButton2.Create(Self);  //this button does not show up
  fTestButton.Text := 'Test';
  fTestButton.Parent := Self;
  fTestButton.Visible := True;
  fTestButton.Position.X := 20;
  fTestButton.Position.Y := 20;
end;

Solution

  • The problem is that the control does not have a style registered for it. So the natural solution is for you to do that.

    But that's a reasonable amount of work, and I expect that all you really want to do is arrange that the control uses the same style as TButton. Achieve that like so:

    type
      TButtonBase = class(TButton)
      protected
        function GetDefaultStyleLookupName: string; override;
      end;
    
    function TButtonBase.GetDefaultStyleLookupName: string;
    begin
      Result := 'Buttonstyle';
    end;
    

    Now derive your classes from TButtonBase.

    type
      tTestButton1 = class(TButtonBase);
      tTestButton2 = class(tTestButton1);
    

    Instead of looking for styles based on the control's class name, classes derived from TButtonBase will use the style named Buttonstyle.