已发布的嵌套组件的属性未保存,事件在对象检查器中不可见

Properties of published nested components are not saved, events are not visible in object inspector

我创建了一个包含以下内容的组件:

TEditLine = class(TCustomControl)
strict private
  FCaptionLabel: TLabel;
  FUnitLabel: TLabel;
  FEdit: TMyEdit;
end;

然后我开始通过创建相应的 getter/setter 对来传播嵌套组件的必要属性。

我突然想到,将这些嵌套组件本身发布为只读属性可能更容易,这样当一些新的 属性 或方法被引入这些组件之一时,容器组件接口不会发生变化需要:

TEditLine = class(TCustomControl)
strict private
  FCaptionLabel: TLabel;
  FUnitLabel: TLabel;
  FEdit: TMyEdit;
published
  property CaptionLabel: TLabel read FCaptionLabel;
  property UnitLabel: TLabel read FUnitLabel;
  property Edit: TMyEdit read FEdit;
end;

当我将组件放在窗体上时,我在 Object Inspector 中看到了 CaptionLabel、UnitLabel 和 Edit,但我只能做到这些。

这样做通常是个好主意吗?我如何解决上面列出的两个问题?

默认情况下,基于

TComponent 的属性被视为对外部组件的引用,除非您在支持它们的对象上调用 SetSubComponent(True),例如:

TEditLine = class(TCustomControl)
strict private
  FCaptionLabel: TLabel;
  FUnitLabel: TLabel;
  FEdit: TMyEdit;
public
  constructor Create(AOwner: TComponent); override;
published
  property CaptionLabel: TLabel read FCaptionLabel;
  property UnitLabel: TLabel read FUnitLabel;
  property Edit: TMyEdit read FEdit;
end;

... 

constructor TEditLine.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);
  ...
  FCaptionLabel := TLabel.Create(Self);
  FCaptionLabel.Parent := Self;
  FCaptionLabel.SetSubComponent(True); // <-- ADD THIS
  ...
  FUnitLabel := TLabel.Create(Self);
  FUnitLabel.Parent := Self;
  FUnitLabel.SetSubComponent(True); // <-- ADD THIS
  ...
  FEdit := TMyEdit.Create(Self);
  FEdit.Parent := Self;
  FEdit.SetSubComponent(True); // <-- ADD THIS
  ...
end;