如何修复Delphi组件与TFont属性,在设计时"无法将NIL分配给TFont"?

Rob*_*ler 6 delphi components vcl design-time properties

我已经开始在Delphi 6 Pro中构建一个新组件.目前它只有一个TFont发布的财产.但是,当我在设计时将组件放在Form上,并单击"textAttr_1"属性(省略号)的编辑按钮时,我得到一个异常,说"不能将NIL分配给TFont".我做错了什么导致了这个错误?以下是组件的代码:

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.
Run Code Online (Sandbox Code Playgroud)

Dav*_*nan 16

您的主要问题是您忘记添加override组件的构造函数.这意味着它没有被调用,因为VCL框架利用了虚拟构造函数TComponent.这就解释了为什么你的字体实例是零.

您还需要一个set方法来调用Assign复制字体的属性,而不是替换不可避免地导致内存损坏错误的实例.

VCL源有无数的这种模式的例子.它看起来像这样:

property Font: TFont read FFont write SetFont;
...
procedure TMyComponent.SetFont(Value: TFont);
begin
  FFont.Assign(Value);
end;
Run Code Online (Sandbox Code Playgroud)

  • 不要忘记添加一个`OnChange`事件处理程序,以便您的组件也可以对Font的子属性中的更改做出反应. (6认同)