簡體   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