Home > Software engineering >  How to assign Owner to cloned TMenuItem?
How to assign Owner to cloned TMenuItem?

Time:06-08

When I create a TmenuItem programmatically the usual way, the Owner of the created menu item is passed as a parameter in the Create function, e.g.:

var NewMenuItem := TMenuItem.Create(MainMen1);

However, when creating a menu item by CLONING it, assigning its Owner property causes an error:

function CloneMenuItem(SourceItem: TMenuItem): TMenuItem;
begin
  with SourceItem do  
    Result := Vcl.Menus.NewItem(Caption, Shortcut, Checked, Enabled, OnClick, HelpContext, Name   'Cloned'); 
  //Result.Owner := pmMyPopupMenu; // ERROR
end;

So how can I specify the Owner of a cloned TMenuItem?

CodePudding user response:

You can set the owner using TComponent.InsertComponent method like:.

function CloneMenuItem(SourceItem: TMenuItem): TMenuItem;
begin
  with SourceItem do  
    Result := Vcl.Menus.NewItem(Caption, Shortcut, Checked, Enabled, OnClick, HelpContext, Name   'Cloned'); 
  pmMyPopupMenu.InsertComponent(Result);
  pmMyPopupMenu.Items.Add(Result);
end;

If you look at NewItem function implementation in Vcl.Menus, it simply creates an item with nil as owner and sets the passed properties. Nothing smart there. I'd preffer inline code in your case or a local function that explicitly sets the owner on item creation.

  • Related