Delphi 弹出式菜单勾选

6

我正在使用Delphi中的弹出菜单。 我想以“单选按钮组”的方式使用它,其中如果用户选择一个项目,则该项目将被选中,其他项目将不会被选中。 我尝试使用AutoCheck属性,但这允许多个项目被选中。 有没有一种方法可以设置弹出菜单,以便只能选择一个项目?

3个回答

12

如果您希望像处理单选按钮一样处理弹出(或其他)菜单项,可以将每个要设置为单选组的项目的“RadioItem”属性设置为true。

选定的项目将显示圆点而不是勾选标记,但它将按照您所需的方式工作,并且视觉提示实际上将与 Windows 标准匹配。


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;

他还应该添加代码来检查至少有一个菜单项被选中,并在用户取消选中已选项时重新添加选中状态。根据你的示例,这应该很简单。 - gabr
我不确定那是他的目标,但我在答案中添加了一个块来处理它。这实际上使事情变得更简单了一些。 - JosephStyons
1
这绝对不是正确的方法:这个功能已经内置了。请参考Zartog和Gerry的帖子,并将两者结合起来。 - onnodb

4

补充Zartog的帖子:Delphi中的弹出菜单(至少从D6开始)具有GroupIndex属性,允许您在菜单中拥有多个单选项集。将GroupIndex设置为1表示第一组,2表示第二组等。

因此: 将AutoCheck设置为True 将RadioItem设置为True 如果需要多个单选项组,则设置GroupIndex


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接