Delphi弹出菜单检查

时间:2020-03-06 14:43:57  来源:igfitidea点击:

我在Delphi中使用弹出菜单。我想以"无线电组"的方式使用它,如果用户选择一个项目,则选中该项目,而其他项目则不选中。我尝试使用AutoCheck属性,但这可以检查多个项目。有没有一种方法可以设置弹出菜单,以便仅可以检查一项?

解决方案

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;

要将弹出菜单(或者其他任何菜单)项与单选组项一样对待,请将要包含在单选组中的每个项的" RadioItem"属性设置为true。

它不会显示选中标记,而是显示所选项目的项目符号,但是会按照我们想要的方式工作,并且视觉提示实际上会与Windows标准匹配。

放大Zartog的文章:Delphi中的弹出菜单(至少从D6起)具有GroupIndex属性,该属性使我们可以在菜单中具有多组单选项目。将第一个组的GroupIndex设置为1,将第二个组的GroupIndex设置为2,依此类推。

所以:
设置自动检查=真
设置RadioItem = True
如果我们需要一组以上的单选项目,请设置GroupIndex