2008-09-25 57 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如果你需要一組以上的無線項目