Delphi弹出菜单检查

前端之家收集整理的这篇文章主要介绍了Delphi弹出菜单检查前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在Delphi中使用弹出菜单.我希望以“无线电组”的方式使用它,如果用户选择了一个项目,则检查它并且不检查其他项目.我尝试使用Autocheck属性,但这允许检查多个项目.有没有办法设置弹出菜单,以便只能检查一个项目?

解决方法

Zartog是正确的,但是如果要保留复选框,请将此事件分配给弹出菜单中的每个项目.

请注意,此代码有点毛茸茸,因为它不依赖于知道弹出菜单名称(因此,使用“GetParentComponent”查找).

  1. procedure TForm2.OnPopupItemClick(Sender: TObject);
  2. var
  3. i : integer;
  4. begin
  5. with (Sender as TMenuItem) do begin
  6. //if they just checked something...
  7. if Checked then begin
  8. //go through the list and *un* check everything *else*
  9. for i := 0 to (GetParentComponent as TPopupMenu).Items.Count - 1 do begin
  10. if i <> MenuIndex then begin //don't uncheck the one they just clicked!
  11. (GetParentComponent as TPopupMenu).Items[i].Checked := False;
  12. end; //if not the one they just clicked
  13. end; //for each item in the popup
  14. end; //if we checked something
  15. end; //with
  16. end;

您可以在运行时将事件分配给表单上的每个弹出框(如果您想这样做):

  1. procedure TForm2.FormCreate(Sender: TObject);
  2. var
  3. i,j: integer;
  4. begin
  5. inherited;
  6.  
  7. //look for any popup menus,and assign our custom checkBox handler to them
  8. if Sender is TForm then begin
  9. with (Sender as TForm) do begin
  10. for i := 0 to ComponentCount - 1 do begin
  11. if (Components[i] is TPopupMenu) then begin
  12. for j := 0 to (Components[i] as TPopupMenu).Items.Count - 1 do begin
  13. (Components[i] as TPopupMenu).Items[j].OnClick := OnPopupItemClick;
  14. end; //for every item in the popup list we found
  15. end; //if we found a popup list
  16. end; //for every component on the form
  17. end; //with the form
  18. end; //if we are looking at a form
  19. end;

回答此答案下方的评论:如果您要求至少检查一个项目,请使用此项目代替第一个代码块.您可能希望在oncreate事件中设置默认选中的项目.

  1. procedure TForm2.OnPopupItemClick(Sender: TObject);
  2. var
  3. i : integer;
  4. begin
  5. with (Sender as TMenuItem) do begin
  6. //go through the list and make sure *only* the clicked item is checked
  7. for i := 0 to (GetParentComponent as TPopupMenu).Items.Count - 1 do begin
  8. (GetParentComponent as TPopupMenu).Items[i].Checked := (i = MenuIndex);
  9. end; //for each item in the popup
  10. end; //with
  11. end;

猜你在找的Delphi相关文章