创建TToolbutton运行时

Ric*_*ick 10 delphi toolbar

TToolbuttons在运行时创建以及它们在我的运行中出现的问题TToolbar.

基本上我已经有了一个带有一些按钮的工具栏.我可以在运行时创建按钮并将父项设置为工具栏.但它们始终显示为工具栏中的第一个按钮.

如何让它们显示在工具栏的末尾?或者我希望他们成为的任何职位.

Jos*_*ons 15

这是一个通用的过程,它带有一个工具栏,并为其添加一个按钮,具有指定的标题:

procedure AddButtonToToolbar(var bar: TToolBar; caption: string);
var
  newbtn: TToolButton;
  lastbtnidx: integer;
begin
  newbtn := TToolButton.Create(bar);
  newbtn.Caption := caption;
  lastbtnidx := bar.ButtonCount - 1;
  if lastbtnidx > -1 then
    newbtn.Left := bar.Buttons[lastbtnidx].Left + bar.Buttons[lastbtnidx].Width
  else
    newbtn.Left := 0;
  newbtn.Parent := bar;
end;
Run Code Online (Sandbox Code Playgroud)

以下是该过程的示例用法:

procedure Button1Click(Sender: TObject);
begin
  ToolBar1.ShowCaptions := True;  //by default, this is False
  AddButtonToToolbar(ToolBar1,IntToStr(ToolBar1.ButtonCount));
end;
Run Code Online (Sandbox Code Playgroud)

您的问题还会询问如何将按钮添加到TToolbar上的任意位置.此代码与之前类似,但它还允许您指定希望新按钮显示哪个索引之后.

procedure AddButtonToToolbar(var bar: TToolBar; caption: string;
  addafteridx: integer = -1);
var
  newbtn: TToolButton;
  prevBtnIdx: integer;
begin
  newbtn := TToolButton.Create(bar);
  newbtn.Caption := caption;

  //if they asked us to add it after a specific location, then do so
  //otherwise, just add it to the end (after the last existing button)
  if addafteridx = -1 then begin
    prevBtnIdx := bar.ButtonCount - 1;
  end
  else begin
    if bar.ButtonCount <= addafteridx then begin
      //if the index they want to be *after* does not exist,
      //just add to the end
      prevBtnIdx := bar.ButtonCount - 1;
    end
    else begin
      prevBtnIdx := addafteridx;
    end;
  end;

  if prevBtnIdx > -1 then
    newbtn.Left := bar.Buttons[prevBtnIdx].Left + bar.Buttons[prevBtnIdx].Width
  else
    newbtn.Left := 0;

  newbtn.Parent := bar;
end;
Run Code Online (Sandbox Code Playgroud)

以下是此修订版的示例用法:

procedure Button1Click(Sender: TObject);
begin
  //by default, "ShowCaptions" is false
  ToolBar1.ShowCaptions := True;

  //in this example, always add our new button immediately after the 0th button
  AddButtonToToolbar(ToolBar1,IntToStr(ToolBar1.ButtonCount),0);
end;
Run Code Online (Sandbox Code Playgroud)

祝好运!

  • Aargh ....除了我在Left值之前分配Parent之外,我们做了同样的事情.它搞砸了布局.你的情况正好相反,现在我很高兴.谢谢 ! (5认同)
  • @JosephStyons:谢谢你.我想在运行时添加TToolButtons,我的第一次尝试无法正常工作.而不是浪费时间,我决定在这里快速搜索,找到你的帖子.救了我一些时间.:) +1 (2认同)