繁体   English   中英

Delphi - 创建自定义TToolBar组件

[英]Delphi - Create a custom TToolBar component

我想创建一个自定义工具栏控件(后代TToolBar),它应该有一些default-toolbarButtons。

所以我创建了一个简单的构造函数,它创建了1个默认按钮:

constructor ZMyToolbart.Create(AOwner: TComponent);
var
  ToolButton : TToolButton;
begin
  inherited;
  Parent := Owner as TWinControl;
  ToolButton := TToolButton.Create(Self);
  ToolButton.Parent := Self;
  ToolButton.Caption := 'Hallo';
end;

问题是,在窗体上拖放自定义控件后,工具栏按钮是可见的,但它不会在对象检查器中显示为工具栏的一部分。

如果尝试通过工具栏的按钮属性分配按钮,但这不起作用。 也许有人建议如何做到这一点? 谢谢!

如果使工具栏成为工具按钮的所有者,则需要具有已发布的属性才能在对象检查器中设置其属性。 这也可以在以后释放它。 代码示例中的局部变量表明情况并非如此。

type
  ZMyToolbart = class(TToolbar)
  private
    FHalloButton: TToolButton;
  public
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;
  published
    property HalloButton: TToolButton read FHalloButton write FHalloButton;
  end;

constructor ZMyToolbart.Create(AOwner: TComponent);
begin
  inherited;
  Parent := Owner as TWinControl;
  FHalloButton := TToolButton.Create(Self);
  FHalloButton.Parent := Self;
  FHalloButton.Caption := 'Hallo';
end;

destructor ZMyToolbart.Destroy;
begin
  FHalloButton.Free;
  inherited;
end;


这可能不会给你你想要的东西,你会在OI的子属性中看到按钮的属性,而不是像其他按钮一样。 如果您希望按钮显示为普通工具按钮,请将其所有者设为表单,而不是工具栏。

然后按钮可以自行选择。 这也意味着按钮可能会在设计时(以及运行时)被删除,因此您希望在删除按钮时将其通知并将其引用设置为nil。

最后,您只想在设计时创建按钮,因为在运行时,按钮将从.dfm流式创建,然后您将有两个按钮。

并且不要忘记注册按钮类:

type
  ZMyToolbart = class(TToolbar)
  private
    FHalloButton: TToolButton;
  public
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;
  protected
    procedure Notification(AComponent: TComponent; Operation: TOperation); override;
  end;

[...]
constructor ZMyToolbart.Create(AOwner: TComponent);
begin
  inherited;
  Parent := Owner as TWinControl;
  if Assigned(FHalloButton) then
    Exit;

  if csDesigning in ComponentState then begin
    FHalloButton := TToolButton.Create(Parent);
    FHalloButton.Parent := Self;
    FHalloButton.FreeNotification(Self);
    FHalloButton.Caption := 'Hallo';
  end;
end;

destructor ZMyToolbart.Destroy;
begin
  FHalloButton.Free;
  inherited;
end;

procedure ZMyToolbart.Notification(AComponent: TComponent;
  Operation: TOperation);
begin
  inherited Notification(AComponent, Operation);
  if (AComponent = FHalloButton) and (Operation = opRemove) then
    FHalloButton := nil;
end;

initialization
  RegisterClass(TToolButton);

似乎ToolButton的所有者应该是表单本身而不是工具栏。 将代码更改为以下时,ToolButton将显示在对象检查器的ToolBar下:

constructor ZMyToolbart.Create(AOwner: TComponent);
var
  ToolButton : TToolButton;
begin
  inherited;
  Parent := Owner as TWinControl;
  ToolButton := TToolButton.Create(Self.Parent);
  ToolButton.Parent := Self;
  ToolButton.Caption := 'Hallo';
end;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM