Making sure at least 1 item in a TPopup menu is always selected
-
12-12-2019 - |
Question
I have TPopup menu with 3 items setup with the following properties.
AutoCheck = True
RadioItem = True
and for the first menu item I set the Checked
property to True
as well so the menu has at least 1 item selected with it is initially displayed. This is all good and well, but if I click on the item that is currently selected, the check (dot) goes away and I want to make it so that at least 1 item in the popup is selected at all times. How do I go about doing that?
Solution
The items in the group should also have the same non-zero GroupIndex
. This, together with RadioItem
should make the items behave like a radio group.
However, it seems that AutoCheck
doesn't respect GroupIndex
and RadioItem
properties, since it will clear the check when you click on a currently checked item.
(Arguably, this could be considered a bug in the VCL.)
Here's a workaround:
Set AutoCheck
to False
, assign all items the same non-zero GroupIndex
and a common OnClick
handler to check the clicked item like this:
procedure TForm1.ItemClick(Sender: TObject);
begin
(Sender as TMenuItem).Checked := True;
end;
Or use Actions, with them this seems to work as expected.
OTHER TIPS
You can set following OnClick handler to all your radio group Menu Items:
procedure TForm1.MenuItemClickHandler(Sender: TObject);
begin
if Sender is TMenuItem then
begin
if not (Sender as TMenuItem).Checked then (Sender as TMenuItem).Checked:=True;
end;
end;