tags:

views:

177

answers:

1

Hi everyone,

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!

+5  A: 

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;
mghie
But I don't click... I hover and it opens. Without clicking. (I edited the question to better reflect this)
Heinrich Ulbricht
I didn't say you need to click. Would you maybe just try it?
mghie
Wow, this works! Sorry for not trying first, I thought this was a misunderstanding about clicking the item or not. But hovering actually fires OnClick! Thank you!
Heinrich Ulbricht