How to fix a Delphi component with a TFont property that gets "cannot assign NIL to TFont" during development?

I started creating a new component in Delphi 6 Pro. Currently, it has only one published TFont property. However, when I drop the component on the form at design time and click on the edit button for the textAttr_1 (ellipsis) property, I get an exception saying "cannot assign NIL to TFont." What am I doing wrong that causes this error? Below is the code for the component:

unit JvExtendedTextAttributes; interface uses Windows, Messages, SysUtils, Classes, JvRichEdit, Graphics; type TJvExtendedTextAttributes = class(TComponent) private { Private declarations } protected { Protected declarations } FTextAttr_1: TFont; public { Public declarations } constructor Create(AOwner: TComponent); published { Published declarations } property textAttr_1: TFont read FTextAttr_1 write FTextAttr_1; end; procedure Register; implementation procedure Register; begin RegisterComponents('FAVORITES', [TJvExtendedTextAttributes]); end; // --------------------------------------------------------------- constructor TJvExtendedTextAttributes.Create(AOwner: TComponent); begin inherited Create(AOwner); FTextAttr_1 := TFont.Create; end; // --------------------------------------------------------------- end. 
+6
source share
1 answer

The main problem is that you forgot to add override to your component constructor. This means that it is not called because the VCL infrastructure uses the TComponent virtual constructor. This explains why your font instance is zero.

You also need the set method, which calls Assign , to copy the font properties, and not replace the instance, which inevitably leads to memory corruption errors.

There are countless examples of this template in the VCL source. It looks like this:

 property Font: TFont read FFont write SetFont; ... procedure TMyComponent.SetFont(Value: TFont); begin FFont.Assign(Value); end; 
+16
source

Source: https://habr.com/ru/post/896831/


All Articles