Delphi subclass visual component and use it

The closest equivilent to your XCode approach is to use an “interposer” class in Delphi. Basically, you do not change the code that the IDE creates for the standard TToolBar usage. You instead declare a new class that derives from the standard TToolBar component but is also named TToolBar and you make it visible to the compiler after the standard TToolBar has been declared. Whichever TToolBar class is last seen by the compiler will be the actual class type that gets instantiated whenever the TForm DFM is streamed.

You can make your custom TToolBar class be seen by the compiler after the standard TToolBar class by one of two different ways:

  1. declare the custom TToolBar class in the same unit as your TForm class:

    unit MyForm;
    
    interface
    
    uses
      ..., Vcl.ComCtrls, ...;
    
    type
      TToolBar = class(Vcl.ComCtrls.TToolBar)
        // override what you need...
      end;
    
      TMyForm = class(TForm)
        ToolBar1: TToolBar; // <-- do not change this!
        ...
      end;
    
    implementation
    
    // implement custom TToolBar as needed...
    
    // normal TForm implementation code as needed ...
    
    end.
    
  2. you can declare the custom TToolBar class in its own unit that is then added to the TForm unit’s uses clause after the ComCtrls unit has been added:

    unit MyToolBar;
    
    interface
    
    uses
      ..., Vcl.ComCtrls;
    
    type
      TToolBar = class(Vcl.ComCtrls.TToolBar)
        // override what you need...
      end;
    
    implementation
    
    // implement custom TToolBar as needed...
    
    end.
    

    .

    unit MyForm;
    
    interface
    
    uses
      ..., Vcl.ComCtrls, ..., MyToolBar;
    
    type
      TMyForm = class(TForm)
        ToolBar1: TToolBar; // <- do not change this!
        ...
      end;
    
    implementation
    
    // normal TForm implementation code as needed ...
    
    end.
    

This approach works on a per-project basis only. If you want to use your custom TToolBar class in multiple projects, then you are better off installing it into the IDE, like @KenWhite describes, and use it instead of the standard TToolBar. Go back to naming it TMyToolBar (or whatever), do not name it TToolBar anymore since it is not going to be used as an interposer. Make sure the Package is marked as “Runtime and Designtime” in its Project Options (creating separate runtime-only and designtime-ony Packages is outside the scope of this discussion). TMyToolBar will be available at design-time for you to drop on your TForm like any other component. If it is not, then you did not set it up correctly.

Leave a Comment