我在运行时创建TToolbuttons
时出现问题,以及它们在我的TToolbar
中的显示方式。创建TToolbutton运行时
基本上我已经有了一个带有一些按钮的工具栏。我可以在运行时创建按钮 并将父项设置为工具栏。但它们始终显示为我工具栏中的第一个按钮。
如何让它们出现在我的工具栏的末尾?或者我希望他们成为的任何职位。
我在运行时创建TToolbuttons
时出现问题,以及它们在我的TToolbar
中的显示方式。创建TToolbutton运行时
基本上我已经有了一个带有一些按钮的工具栏。我可以在运行时创建按钮 并将父项设置为工具栏。但它们始终显示为我工具栏中的第一个按钮。
如何让它们出现在我的工具栏的末尾?或者我希望他们成为的任何职位。
这里是需要一个工具条,并增加了一个按钮,它具有指定标题的通用程序left
属性:
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;
祝你好运!
如果它的工作方式与滚动面板相同,那么您可以将.left属性设置为比将按钮置于该按钮左侧的按钮多1。或者将.left属性设置为比按钮小1,以将其放置在该按钮的右侧。
可以使用TToolButton
组件
检查该样本
//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]'? – nurettin 2017-04-05 08:18:54
Aargh ....我们正在做同样的事情,只是在Left值之前指定Parent。这是搞砸了布局。你的是相反的,现在我很高兴。谢谢 ! – Rick 2010-11-04 03:55:53
@罗德里克:很高兴帮助!我修改了答案以包含一种添加到TToolbar上的任意点的方法。 – JosephStyons 2010-11-04 04:09:57
@JosephStyons:谢谢你。我正在寻找添加TToolButtons在运行时,我的第一次尝试不能正常工作。我没有浪费时间,而是决定在这里做一个快速搜索,找到你的帖子。为我节省了一些时间。 :) +1 – 2011-10-01 00:49:20