已发布的属性默认值在设计时重置

问题描述

我正在开发一些组件 - 自定义按钮。我安装了它,但在设计时自定义发布的属性重置为零。首先,我在谈论颜色 - 它重置为 clBlack(或对于 clBtnFace 属性重置为 Color)。 Caption 重置为空字符串。我的意思是当我在设计时放置组件以形成表单时,对象检查器中的所有自定义属性都重置为零(颜色为 clBlack 等等)。我可以手动更改它,但为什么我在代码中设置的默认值不起作用?问题仅在设计时。当我在运行时创建组件时,它工作正常。这是代码(以 Color 属性为例)。

基类

TpfCustomButton = class(TCustomControl)
...
published
...
  property Color;
...
end;

主要代码

TpfCustomColoredButton = class(TpfCustomButton)
...
public
  constructor Create(AOwner: TComponent);
...
end;

constructor TpfCustomColoredButton.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);

  Color := $00E1E1E1;//Look at this: setting Color
  ...
end;

组件代码

TpfColoredButton = class(TpfCustomColoredButton)
published
  ...
  property Action;
  property Align;
  //And some other standard properties
end;

procedure Register;

implementation

procedure Register;
begin
  RegisterComponents('PF Components',[TpfColoredButton]);
end;
...

此外,只是为了测试我正在尝试这样的代码:

TpfColoredButton = class(TpfCustomColoredButton)
  public
    constructor Create(AOwner: TComponent);
  ...  
  
constructor TpfColoredButton.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);
  Caption := 'abc';
end;

在设计时 Caption 是空的,但同样,如果我在运行时创建它,我们会看到我们预期的 Caption=abc。在运行时,我像这样创建新对象(并且工作正常):

TForm2 = class(TForm)  
  procedure FormCreate(Sender: TObject);
private
  pf: TpfColoredButton;
end;

procedure TForm2.FormCreate(Sender: TObject);
begin
  pf := TpfColoredButton.Create(Self);
  pf.Parent := Self;
end;

解决方法

您在派生类构造函数中更改了属性的默认值,但您没有在属性声明中指定相同的默认值来更新其 RTTI,它由对象检查器和 DFM 流使用。

此外,您的派生构造函数中缺少 override。这就是在设计时创建组件时您的属性没有正确初始化的原因。您的派生构造函数甚至没有被调用。而在运行时,您是直接调用派生构造函数。

改变这个:

TpfCustomColoredButton = class(TpfCustomButton)
  ...
public
  constructor Create(AOwner: TComponent);
  ...
end;

为此:

TpfCustomColoredButton = class(TpfCustomButton)
  ...
published
  ...
  property Color default $00E1E1E1;
  ...
public
  constructor Create(AOwner: TComponent); override;
  ...
end;

对默认值与其基类不同的派生类的所有其他已发布属性执行相同的操作。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...