delphi 如何创建具有Vcl.ButtonGroup.TButtonGroup类型的Published字段的VCL控件

yvfmudvl  于 2023-03-29  发布在  其他
关注(0)|答案(1)|浏览(130)

我想创建一个名为TMyDropDownButtonTSpeedButton后代,并带有一个TButtonGroup字段。当我推TSpeedButton时,TButtonGroup应该出现在正确的位置(由于这里列出了一些其他属性值)。
这个TButtonGroup属性应该是只读的(程序在调用inherited构造函数之前在Create()构造函数中创建它),并且应该被发布(将设计时的值保存到DFM中)。
但是,当我将TMyDropDownButton示例放置到表单上时,默认情况下TButtonGroup属性是未设置的。当我将写访问器添加到TButtonGroup属性时,我可以链接删除的TButtonGroup,但我不使用t want this. I want the TButtonGroup property to be linked to the TButtonGroup instance created in the constructor, and preset by the Loaded()`方法。
我该怎么做呢?
下面是我的尝试:

unit MyDropDownButton;

interface

uses
    System.Classes
  , Vcl.ButtonGroup
  , Vcl.Buttons
  ;

type
  TMyDropDownButton = class ( TSpeedButton )
    private
      // Fields
      fButtonGroup : TButtonGroup;

    protected
      procedure Loaded; override;

    public
      constructor Create( owner_ : TComponent );
      destructor Destroy; override;

    published
      property buttonGroup : TButtonGroup read fButtonGroup;

  end;

procedure Register;

implementation

procedure Register;
begin
  RegisterComponents('myDropDownButton', [TMyDropDownButton]);
end;

procedure TMyDropDownButton.Loaded;
begin
  inherited Loaded;
  // I need some settings here due to venished props inrelevant for the question
end;

constructor TMyDropDownButton.Create( owner_ : TComponent );
begin
  fButtonGroup := TButtonGroup.Create( self );
  inherited Create( owner_ );
  fButtonGroup.Parent := parent;
end;

destructor TMyDropDownButton.Destroy;
begin
//  FreeAndNIL( fButtonGroup );
  inherited Destroy;
end;

end.
t40tm48m

t40tm48m1#

TButtonGroupTComponent的后代,所以为了让你的组件将它用作Object Inspector中的嵌套属性,你必须调用它的SetSubComponent()方法,例如:

constructor TMyDropDownButton.Create( owner_ : TComponent );
begin
  inherited Create( owner_ );
  fButtonGroup := TButtonGroup.Create( Self );
  fButtonGroup.SetSubComponent( True );
  ... 
end;

否则,对象检查器将期望您将属性链接到外部组件,正如您已经发现的那样。
此外,您不能从组件的构造函数内部将TButtonGroup.Parent属性设置为组件的Parent属性,因为此时尚未分配组件的Parent
如果您需要TButtonGroup使用分配给您的组件的相同Parent,则必须覆盖组件的虚拟SetParent()方法,例如:

type
  TMyDropDownButton = class ( TSpeedButton )
    ...
    protected
      ...
      procedure SetParent(AParent: TWinControl); override;
    ...
  end;

procedure TMyDropDownButton.SetParent(AParent: TWinControl); 
begin
  inherited SetParent(AParent);
  fButtonGroup.Parent := AParent;
end;

相关问题