2008-09-25 81 views
6

我在德尔福使用弹出菜单。我想以“收音机组”的方式使用它,如果用户选择一个项目,它会被检查,而其他项目不会被检查。我尝试使用AutoCheck属性,但是这允许检查多个项目。有没有办法设置弹出菜单,以便只能检查一个项目?德尔福弹出菜单检查

回答

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; 
+0

他也应该添加检查至少一个菜单项被选中的代码,并添加检查用户取消选中检查的条目。 这应该是简单的给你的例子。 – gabr 2008-09-25 17:21:18

12

对待弹出(或任何其他)菜单项,如广播组项目,你想有无线电组中的每个项目“RadioItem”属性设置为true。

它不会显示复选标记,而是显示所选项目的一个项目符号,但它会以您想要的方式工作,而视觉提示实际上将与Windows标准匹配。

4

在Zartog的文章中放大:Delphi中的弹出式菜单(至少D6)有一个GroupIndex属性,它允许您在菜单中有多组无线电项目。设置的GroupIndex 1为第一组,2第二等

所以: 设置自动检查=真 设置RadioItem =真 设置的GroupIndex如果你需要一组以上的无线项目