【发布时间】:2010-11-04 03:13:38
【问题描述】:
我在运行时创建 TToolbuttons 以及它们如何出现在我的 TToolbar 中时遇到问题。
基本上我已经有了一个带有一些按钮的工具栏。我可以在运行时创建按钮 并将父级设置为工具栏。但它们总是显示为我工具栏中的第一个按钮。
如何使它们出现在工具栏的末尾?或者我希望他们担任的任何职位。
【问题讨论】:
我在运行时创建 TToolbuttons 以及它们如何出现在我的 TToolbar 中时遇到问题。
基本上我已经有了一个带有一些按钮的工具栏。我可以在运行时创建按钮 并将父级设置为工具栏。但它们总是显示为我工具栏中的第一个按钮。
如何使它们出现在工具栏的末尾?或者我希望他们担任的任何职位。
【问题讨论】:
下面是一个通用过程,它接受一个工具栏,并为其添加一个按钮,并带有指定的标题:
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;
这是该过程的示例用法:
procedure Button1Click(Sender: TObject);
begin
ToolBar1.ShowCaptions := True; //by default, this is False
AddButtonToToolbar(ToolBar1,IntToStr(ToolBar1.ButtonCount));
end;
您的问题还询问如何将按钮添加到 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;
以下是此修订版的示例用法:
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;
祝你好运!
【讨论】:
您可以使用TToolButton 组件的left 属性
检查此示例
//adding buttons to the end of the ToolBar.
procedure TForm1.Button1Click(Sender: TObject);
var
Toolbutton : TToolButton;
begin
Toolbutton :=TToolButton.Create(ToolBar1);
Toolbutton.Parent := ToolBar1;
Toolbutton.Caption := IntToStr(ToolBar1.ButtonCount);
Toolbutton.Left := ToolBar1.Buttons[ToolBar1.ButtonCount-1].Left + ToolBar1.ButtonWidth;
end;
【讨论】:
ToolBar1.Buttons[-1] 是什么?
如果它像滚动面板一样工作,那么您可以将 .left 属性设置为比按钮多 1 以将其放置在该按钮的左侧。或者将 .left 属性设置为比按钮小 1 以将其放置在该按钮的右侧。
【讨论】: