加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Delphi弹出菜单检查

发布时间:2020-12-15 04:21:27 所属栏目:大数据 来源:网络整理
导读:我在Delphi中使用弹出菜单.我希望以“无线电组”的方式使用它,如果用户选择了一个项目,则检查它并且不检查其他项目.我尝试使用AutoCheck属性,但这允许检查多个项目.有没有办法设置弹出菜单,以便只能检查一个项目? 解决方法 Zartog是正确的,但是如果要保留复
我在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;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读