Aquí es un procedimiento genérico que tiene una barra de herramientas, y añade un botón para que, con un título especificado:
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;
Y aquí es ejemplo de uso de este procedimiento:
procedure Button1Click(Sender: TObject);
begin
ToolBar1.ShowCaptions := True; //by default, this is False
AddButtonToToolbar(ToolBar1,IntToStr(ToolBar1.ButtonCount));
end;
Su pregunta también le pregunta cómo agregar un botón a un lugar arbitrario en el TToolbar. Este código es similar al anterior, pero también le permite especificar en qué índice desea que aparezca el nuevo botón después de.
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;
Y aquí es ejemplo de uso de esta versión revisada:
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;
Buena suerte!
Aargh .... estamos haciendo lo mismo, excepto que asigno el valor Parent antes del Left. Y estaba arruinando el diseño. Tu es inverso y ahora estoy feliz. Gracias ! – Rick
@Roderick: ¡me alegro de que haya ayudado! Revisé la respuesta para incluir una forma de agregar a un punto arbitrario en TToolbar, también. – JosephStyons
@JosephStyons: Gracias por esto. Estaba buscando agregar TToolButtons en tiempo de ejecución, y mi primer intento no funcionó correctamente. En lugar de perder el tiempo, decidí hacer una búsqueda rápida aquí y encontrar su publicación. Me salvó un poco de tiempo :) +1 –