我在Delphi中使用弹出菜单。我希望以“无线电组”的方式使用它,如果用户选择了一个项目,则检查它并且不检查其他项目。我尝试使用AutoCheck属性,但这允许检查多个项目。有没有办法设置弹出菜单,以便只能检查一个项目?
答案 0 :(得分:12)
要处理弹出广告(或任何其他)菜单项(如广播组项目),请将“RadioItem”属性设置为您要在广播组中拥有的每个项目的真实属性。
它不会显示复选标记,而是会显示所选项目的项目符号,但它会按照您想要的方式工作,而视觉提示实际上会与Windows标准相匹配。
答案 1 :(得分:5)
Zartog是对的,但是如果你想保留复选框,请将此事件分配给弹出菜单中的每个项目。
请注意,此代码有点毛茸茸,因为它不依赖于知道弹出菜单的名称(因此,使用“GetParentComponent”查找)。
procedure TForm2.OnPopupItemClick(Sender: TObject);
var
i : integer;
begin
with (Sender as TMenuItem) do begin
//if they just checked something...
if Checked then begin
//go through the list and *un* check everything *else*
for i := 0 to (GetParentComponent as TPopupMenu).Items.Count - 1 do begin
if i <> MenuIndex then begin //don't uncheck the one they just clicked!
(GetParentComponent as TPopupMenu).Items[i].Checked := False;
end; //if not the one they just clicked
end; //for each item in the popup
end; //if we checked something
end; //with
end;
您可以在运行时将事件分配给表单上的每个弹出框(如果您想这样做):
procedure TForm2.FormCreate(Sender: TObject);
var
i,j: integer;
begin
inherited;
//look for any popup menus, and assign our custom checkbox handler to them
if Sender is TForm then begin
with (Sender as TForm) do begin
for i := 0 to ComponentCount - 1 do begin
if (Components[i] is TPopupMenu) then begin
for j := 0 to (Components[i] as TPopupMenu).Items.Count - 1 do begin
(Components[i] as TPopupMenu).Items[j].OnClick := OnPopupItemClick;
end; //for every item in the popup list we found
end; //if we found a popup list
end; //for every component on the form
end; //with the form
end; //if we are looking at a form
end;
在回答此答案下面的评论时:如果您要求至少检查一个项目,请使用此项目代替第一个代码块。您可能希望在oncreate事件中设置默认选中的项目。
procedure TForm2.OnPopupItemClick(Sender: TObject);
var
i : integer;
begin
with (Sender as TMenuItem) do begin
//go through the list and make sure *only* the clicked item is checked
for i := 0 to (GetParentComponent as TPopupMenu).Items.Count - 1 do begin
(GetParentComponent as TPopupMenu).Items[i].Checked := (i = MenuIndex);
end; //for each item in the popup
end; //with
end;
答案 2 :(得分:4)
放大Zartog的帖子:Delphi中的弹出菜单(至少来自D6)具有GroupIndex属性,允许您在菜单中拥有多组无线电项目。将GroupIndex设置为1表示第一组,2表示一秒钟等。
所以: 设置AutoCheck = True 设置RadioItem = True 如果您需要多组无线电项目,请设置GroupIndex