I have a popup menu which contains several menu items and one of them can have child items. This entry has a little arrow on the right and when you hover your mouse over it, a sub-menu will open (without clicking). Now I want to populate this sub-menu at runtime, but only if the user actually opens it. If the user never opens the sub-menu, it will be empty (maybe contain a placeholder). How could I accomplish this? Is it even possible to modify a popup-menu when it is already visible?
Thanks for your help!
There is no difference between submenus in standard menus or context (popup) menus: If a menu item has a submenu attached, then its OnClick
event will fire just before the submenu is shown (note that you don't need to click for it to show up), and in that event handler you can modify the submenu (either set properties of existing items, or add new items / delete existing items).
Some demo code about dynamically adding and removing items:
procedure TForm1.FormCreate(Sender: TObject);
var
Popup: TPopupMenu;
Item, SubItem: TMenuItem;
begin
Popup := TPopupMenu.Create(Self);
PopupMenu := Popup;
Item := TMenuItem.Create(Popup);
Item.Caption := 'Test submenu';
Item.OnClick := PopupClick;
Popup.Items.Add(Item);
SubItem := TMenuItem.Create(Item);
SubItem.Caption := 'dummy';
Item.Add(SubItem);
end;
procedure TForm1.PopupClick(Sender: TObject);
var
SubmenuItem, Item: TMenuItem;
begin
SubmenuItem := Sender as TMenuItem;
// delete old items (leave at least one to keep the submenu)
while SubmenuItem.Count > 1 do
SubmenuItem.Items[SubmenuItem.Count - 1].Free;
// create new items
while SubmenuItem.Count < 3 do begin
Item := TMenuItem.Create(SubmenuItem);
Item.Caption := Format('new item created %d', [GetTickCount]);
SubmenuItem.Add(Item);
end;
end;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With