gpt4 book ai didi

delphi - 创建TToolbutton运行时

转载 作者:行者123 更新时间:2023-12-03 14:41:16 32 4
gpt4 key购买 nike

我在运行时创建 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;

祝你好运!

关于delphi - 创建TToolbutton运行时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4093595/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com