delphi – 创建TToolbutton运行时

前端之家收集整理的这篇文章主要介绍了delphi – 创建TToolbutton运行时前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在运行时创建TToolbuttons以及它在TToolbar中的显示方式有问题.

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

我如何让它们出现在我的工具栏的末尾?或任何我想要他们的职位.

解决方法

这是一个通用过程,它使用工具栏,并添加一个按钮,并附带指定的标题
  1. procedure AddButtonToToolbar(var bar: TToolBar; caption: string);
  2. var
  3. newbtn: TToolButton;
  4. lastbtnidx: integer;
  5. begin
  6. newbtn := TToolButton.Create(bar);
  7. newbtn.Caption := caption;
  8. lastbtnidx := bar.ButtonCount - 1;
  9. if lastbtnidx > -1 then
  10. newbtn.Left := bar.Buttons[lastbtnidx].Left + bar.Buttons[lastbtnidx].Width
  11. else
  12. newbtn.Left := 0;
  13. newbtn.Parent := bar;
  14. end;

这里是该过程的示例用法

  1. procedure Button1Click(Sender: TObject);
  2. begin
  3. ToolBar1.ShowCaptions := True; //by default,this is False
  4. AddButtonToToolbar(ToolBar1,IntToStr(ToolBar1.ButtonCount));
  5. end;

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

  1. procedure AddButtonToToolbar(var bar: TToolBar; caption: string;
  2. addafteridx: integer = -1);
  3. var
  4. newbtn: TToolButton;
  5. prevBtnIdx: integer;
  6. begin
  7. newbtn := TToolButton.Create(bar);
  8. newbtn.Caption := caption;
  9.  
  10. //if they asked us to add it after a specific location,then do so
  11. //otherwise,just add it to the end (after the last existing button)
  12. if addafteridx = -1 then begin
  13. prevBtnIdx := bar.ButtonCount - 1;
  14. end
  15. else begin
  16. if bar.ButtonCount <= addafteridx then begin
  17. //if the index they want to be *after* does not exist,//just add to the end
  18. prevBtnIdx := bar.ButtonCount - 1;
  19. end
  20. else begin
  21. prevBtnIdx := addafteridx;
  22. end;
  23. end;
  24.  
  25. if prevBtnIdx > -1 then
  26. newbtn.Left := bar.Buttons[prevBtnIdx].Left + bar.Buttons[prevBtnIdx].Width
  27. else
  28. newbtn.Left := 0;
  29.  
  30. newbtn.Parent := bar;
  31. end;

这是修改版本的示例用法

  1. procedure Button1Click(Sender: TObject);
  2. begin
  3. //by default,"ShowCaptions" is false
  4. ToolBar1.ShowCaptions := True;
  5.  
  6. //in this example,always add our new button immediately after the 0th button
  7. AddButtonToToolbar(ToolBar1,IntToStr(ToolBar1.ButtonCount),0);
  8. end;

祝你好运!

猜你在找的Delphi相关文章