I would like to subclass TToolBar with another class called MyTToolBar so that I can override a method. I’m new to Delphi, but after two hours of trying various methods, I can’t get MyTToolBar to be used instead of TToolBar. I can’t be the first person who’s wanted to override a method on a visual component class.
I come more from an Xcode background where subclassing a visual component is easy. You create a subclass (e.g., MySubclass) of a parent class (e.g., MySuperClass) and then just simply assign the subclass in the Interface Builder view of Xcode. The subclass is automatically recognized and used.
Why can’t I seem to do this in Delphi RAD Studio XE3?
After adding a TToolBar to a TForm, it doesn’t seem possible to change the class. I tried through the Object Inspector as well as through the .PAS source code file. If I change the class in the .PAS file, I get an error message saying the toolbar “should be of type Vcl.ComCtrls.TToolBar but is declared as MyTToolbar. Correct the declaration?” This just seems silly…
Oh, and I’ve also used the new component wizard from selecting: File -> New -> Other -> Delphi Projects -> Delphi Files -> Component. I select the ancestor for MyTToolBar as TToolBar and tell it to register in the ‘Samples’ palette page. However, it doesn’t appear in the ‘Samples’ page.
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
TToolBarusage. You instead declare a new class that derives from the standardTToolBarcomponent but is also namedTToolBarand you make it visible to the compiler after the standardTToolBarhas been declared. WhicheverTToolBarclass is last seen by the compiler will be the actual class type that gets instantiated whenever theTFormDFM is streamed.You can make your custom
TToolBarclass be seen by the compiler after the standardTToolBarclass by one of two different ways:declare the custom
TToolBarclass in the same unit as yourTFormclass:you can declare the custom
TToolBarclass in its own unit that is then added to theTFormunit’susesclause after theComCtrlsunit has been added:.
This approach works on a per-project basis only. If you want to use your custom
TToolBarclass in multiple projects, then you are better off installing it into the IDE, like @KenWhite describes, and use it instead of the standardTToolBar. Go back to naming itTMyToolBar(or whatever), do not name itTToolBaranymore 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).TMyToolBarwill be available at design-time for you to drop on yourTFormlike any other component. If it is not, then you did not set it up correctly.