Lazarus TActionList

Wednesday, December 31. 2008

Lazarus TActionList

In Delphi I used TActionList with lots of TAction items to implement the various actions in an application. These actions can then be linked to menu items and buttons. An action can have an OnUpdate event handler which is responsible for activating and deactivating the action depending on the current state of the application. This is a very useful feature which is also available in Lazarus but unfortunately it is somewhat broken in current Lazarus version (At least up to daily snapshot 20081231) because the OnUpdate event handlers are not called correctly for actions which are only linked to menu items. This bug is already reported and hopefully it will be fixed soon. But for now I have created a little workaround for it.

The workaround consists of a single line in the FormCreate method and two additional small methods in the form:

procedure TForm1.FormCreate(Sender: TObject);
begin
  InstallActionUpdateFix(MainMenu1.Items);
end;

procedure TForm1.InstallActionUpdateFix(MenuItem: TMenuItem);
var
  i: Integer;
begin
  if (MenuItem.Count > 0) and (not Assigned(MenuItem.OnClick)) then
  begin
    MenuItem.OnClick := @FixActionUpdate;
    for i := 0 to MenuItem.Count - 1 do
      InstallActionUpdateFix(MenuItem.Items[i]);
  end;
end;

procedure TForm1.FixActionUpdate(Sender: TObject);
var
  i: Integer;
  MenuItem: TMenuItem;
begin
  for i := 0 to TMenuItem(Sender).Count - 1 do
  begin
    MenuItem := TMenuItem(Sender).Items[i];
    if Assigned(MenuItem.Action) and Assigned(MenuItem.Action.OnUpdate) then
    begin
      MenuItem.Action.OnUpdate(MenuItem.Action);
    end;
  end;
end;

This code does the following: When the form is created then a special OnClick handler is installed into all main menu items which have sub menu items. This special OnClick handler calls the OnUpdate method of all actions connected to sub menu items of the clicked menu item.

Update (2009-01-11)

This bug is fixed in current SVN trunk so the above workaround is no longer needed when 0.9.27 is released or when a current snapshot is used.

Posted in Delphi | Comments (2)
Marco van de Voort at 2009-01-09 15:02
According http://bugs.freepascal.org/view.php?id=12776

fixed one day later on jan 1st.
Khalid at 2012-11-01 09:00
Hi Marco,

it's 3 years later... :)

Do you know if this bug is fixed in Lazarus now? I really just want to get the TAction component working. I can't even find the component. What unit file should I include/use to have TAction?

Thanks!

Enclosing asterisks marks text as bold (*word*), underscore are made via _word_.