我正在使用Delphi中的弹出菜单。 我想以“单选按钮组”的方式使用它,其中如果用户选择一个项目,则该项目将被选中,其他项目将不会被选中。 我尝试使用AutoCheck属性,但这允许多个项目被选中。 有没有一种方法可以设置弹出菜单,以便只能选择一个项目?
我正在使用Delphi中的弹出菜单。 我想以“单选按钮组”的方式使用它,其中如果用户选择一个项目,则该项目将被选中,其他项目将不会被选中。 我尝试使用AutoCheck属性,但这允许多个项目被选中。 有没有一种方法可以设置弹出菜单,以便只能选择一个项目?
如果您希望像处理单选按钮一样处理弹出(或其他)菜单项,可以将每个要设置为单选组的项目的“RadioItem”属性设置为true。
选定的项目将显示圆点而不是勾选标记,但它将按照您所需的方式工作,并且视觉提示实际上将与 Windows 标准匹配。
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;
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;
补充Zartog的帖子:Delphi中的弹出菜单(至少从D6开始)具有GroupIndex属性,允许您在菜单中拥有多个单选项集。将GroupIndex设置为1表示第一组,2表示第二组等。
因此: 将AutoCheck设置为True 将RadioItem设置为True 如果需要多个单选项组,则设置GroupIndex