Dynamic submenu creation in Delphi

I have a popup menu and I want one of the elements to open a submenu with a dynamically created list (this is a list of user-defined flags). Here, as I create the menu items ( FlagAs- this is the menu item to which I want to add a submenu):

lNewMenuItems: array[0..flagCount] of tMenuItem;

for I := 0 to flagCount do
begin
  { Create a new menu item }
  lNewMenuItems[I] := tMenuItem.Create(FlagAs);
  lNewMenuItems[I].Caption := FlagNames[I];
  lNewMenuItems[I].Tag := I; { Tag with the flag number }
  lNewMenuItems[I].OnClick := miFlagClick;
end;

FlagAs.Add(lNewMenuItems);

The handler miFlagClicksimply switches the checked state of its sender:

procedure TMyForm.miFlagClick(Sender: TObject);
begin
  (Sender as tMenuItem).Checked := not (Sender as tMenuItem).Checked;
end;

Elements are added perfectly, but they are not checked when I click on them. The event handler is called EDIT: and Sender is the correct menu item, but the checkmark does not appear the next time I open the menu.

What am I doing wrong? Or am I going to create a menu incorrectly? (Note flagCountmay change in the future, but is defined as a constant in the code)

: - .

+3
4

Delphi 2009 : :

procedure TForm5.FormCreate(Sender: TObject);
var
  i : Integer;
  mis : array[0..3] of TMenuItem;
begin
  for i := 0 to 3 do begin
    mis[i] := tMenuItem.Create(SubMenu);
    NewMenu(mis[i]);
  end;
  SubMenu.Add(mis);
end;

procedure TForm5.NewMenu(var mi: TMenuItem);
begin
  mi.Caption := 'Test';
  mi.OnClick := TestClick;
end;

procedure TForm5.TestClick(Sender: TObject);
begin
 (Sender as tMenuItem).Checked := not (Sender as tMenuItem).Checked;
end;
+4

( , )

lNewMenuItems: array [0..flagCount] tMenuItem; ?

, AutoCheck?

 var
    NewMenuItem: TMenuItem;
    I : Integer;
  begin
    for I := 0 to flagCount do
    begin
      { Create a new menu item }
      NewMenuItem := TMenuItem.Create(FlagAs);
      NewMenuItem.Caption := FlagNames[I];
      NewMenuItem.Tag := I; { Tag with the flag number }
      // NewMenuItem.OnClick := miFlagClick;
      NewMenuItem.AutoCheck := True;
      FlagAs.Add(NewMenuItem);
    end;
  end;
+2

. Checked, . . ...

0

, , ?

0

Source: https://habr.com/ru/post/1703280/


All Articles