How to Clone Menu Items for TPopupMenu?
Asked Answered
U

1

5

I want to clone an entire TMenuItem with it's children to another TPopupMenu. Here is a nice code:

function CloneMenuItem(SourceItem: TMenuItem): TMenuItem;
var
  I: Integer;
Begin
  with SourceItem do
  Begin
    Result := NewItem(Caption, Shortcut, Checked, Enabled, OnClick, HelpContext, Name + 'Copy');
    for I := 0 To Count - 1 do
      Result.Add(CloneMenuItem(Items[I]));
  end;
end;

The following works just fine (b1 is a PopupMenu1.TMenuItem with sub menus):

PopupMenu2.Items.Add(CloneMenuItem(b1));

The problem is that I can't clone an entire TPopupMenu if the SourceItem is the root item. e.g :

PopupMenu2.Items.Add(CloneMenuItem(PopupMenu1.Items));

Wont work. All I can see is 1 Item, as if it was a separator.

Ubana answered 15/5, 2012 at 16:4 Comment(0)
C
8

You cannot clone the TPopupMenu.Items like that. Even though TPopupMenu.Items is a TMenuItem object, it is not an actual menu item, it is just a container for hosting the other TMenuItem objects. You would have to loop through those children and clone them individually instead, eg:

for I := 0 to PopupMenu1.Items.Count-1 do
  PopupMenu2.Items.Add(CloneMenuItem(PopupMenu1.Items[I])); 
Codger answered 15/5, 2012 at 17:2 Comment(1)
Is there a way to detect that a TMenuItem is the root item? (TMenuItem.Parent == nil will do?)Ubana

© 2022 - 2024 — McMap. All rights reserved.