1.动态创建按钮,并安放在ScrollBox中
获得按钮信息,然后创建, 目前案例是从数据库中取值, 然后动态创建. 源代码仅给出实现方式参考
procedure TFrm1.LoadElementPage;
var
mSetBase1 : TButton;
i,j : Integer;
tmpQuery : TDBQuery;
begin
fControl1Manager := TObjectList.Create;
tmpQuery := TDBQuery.Create(nil);
try
tmpQuery.Connection := GDBConnection;
tmpQuery.Close;
tmpQuery.SQL.Clear;
tmpQuery.SQL.Text :=
'select a.L_KEYNO, a.C_KEYVALUE, a.C_CAPTION, a.C_MODIFY, a.C_MEMO, a.C_ENGLISH, a.C_ISDISPLAY ' +
' from TDIC a ' +
' where a.L_KEYNO in (1,2) '+
' order by a.L_KEYNO ';
i:=0;
tmpQuery.Open;
tmpQuery.First;
while not tmpQuery.Eof do
begin
if not ((tmpQuery.Fieldbyname('C_ISDISPLAY').AsString<>'1') and
(tmpQuery.Fieldbyname('L_KEYNO').AsString='1')) then
begin
mSetBase1 := TButton.Create(Frm1);//注意create参数!!!!
with mSetBase1 do
begin
case StrToInt(tmpQuery.Fieldbyname('L_KEYNO').AsString) of
1:
begin
Parent := ScrollBox9;
Hint := tmpQuery.Fieldbyname('C_Memo').AsString;
end;
2:
begin
Parent := ScrollBox10;
Hint := tmpQuery.Fieldbyname('C_ENGLISH').AsString;
PopupMenu:= pmElementEdit;
end;
else
Parent := Frm1.ScrollBox10;
end;
Name := 'Ele' + IntToStr(i);
Caption := tmpQuery.Fieldbyname('C_CAPTION').AsString;
ShowHint := TRUE;
Width := bWidth;
Height := bHeight;
OnClick:= ElementClick;
end;
fControl1Manager.add(mSetBase1);
end;
inc(i);
tmpQuery.Next;
end;
finally
tmpQuery.Free;
end;
//控件安放布局省略,下面给出布局调用函数,放到ScrollBox中
end;
//控件安放布局省略,下面给出布局调用函数,放到ScrollBox中
procedure TFrm1.ButtonLayoutOn(ControlManager:TObjectList ; control:TComponent);
var
mSetBase: TButton;
iBoxW:Integer;
iPerLine :Integer;//每行个数
iBox:Integer;//每个ScrollBox中button数
i,j :Integer;
begin
iBox:=0;
iBoxW := TWinControl(control).Width - 8;
iPerLine := iBoxW div (bWidth + bWtoW);
if iPerLine < 1 then
iPerLine := 1;
for j := 0 to ControlManager.Count-1 do
begin
if TButton(ControlManager[j]).Parent = control then
begin
inc(iBox);
TButton(ControlManager[j]).Top := bHtoH + (bHeight+bHtoH)*((iBox div iPerLine)- integer((iBox mod iPerLine)=0));
TButton(ControlManager[j]).Left:= bWtoW + (bWidth+bWtoW) * ((iBox-1) mod iPerLine);
end;
TButton(ControlManager[j]).Show;
end;
end;
2.添加右键弹出菜单功能
首先窗口添加TPopupMenu, 本例命名为pmElementEdit, 弹出的时候绑定一个事件用于改变弹出菜单的选项, 设置如下
相应的ScrollBox的PopupMenu属性绑定pmElementEdit
写一个触发事件可改变弹出菜单的选项, 本例在点击ScrollBox的时候只显示新增, 点击按钮时显示新增和删除, 实现如下:
procedure TFrm1.pmElementEditPopup(Sender: TObject);
begin
if FindComponent(pmElementEdit.PopupComponent.Name) is TButton then
begin
mniElementDelete.Visible := True;
end
else
begin
mniElementDelete.Visible := False;
end;
end;
注意:按钮create中的参数为拥有者(本例为窗体本身),如果写nil 触发弹出菜单事件的时候将不能截获按钮消息,
if FindComponent(pmElementEdit.PopupComponent.Name) is TButton then
这一句在右键点击按钮会判断False,即FindComponent判断失败,正确的创建方式如下
mSetBase1 := TButton.Create(Frm1);//注意create参数!!!!
with mSetBase1 do