Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add TMenuItem bitmap

I want to add a bitmap to a TMenuItem created dynamically. With this code it doesn't work, I don't have the image on my menu. What's wrong?

procedure TForm3.FormCreate(Sender: TObject);
var
   item : TmenuItem;
   icon : TIcon;
begin
   item := TMenuItem.Create(PopupMenu1);
   item.Caption := 'coucou';
   icon := TIcon.Create;
   icon.LoadFromFile('d:\SmallIcon.ico');
   icon.Height := 16;
   icon.Width := 16;
   item.Bitmap.Canvas.Draw(0,0,icon);
   PopupMenu1.Items.Add(item);
end;
like image 308
Nono Avatar asked Dec 13 '22 10:12

Nono


1 Answers

The Bitmap property on TMenuItem isn't the way to go here. You really should use image lists instead. This will allow you to share images between your UI elements in a manageable fashion.

  1. Add the icon to a TImageList.
  2. Set the Images property on the menu (i.e. PopupMenu1) to refer to the image list.
  3. Set the image index of the menu item to the index of the icon in the list, i.e. 0 if it's the first image.

Of course, you really ought to be using actions too, in which case you simply need to set the ImageIndex for the action and the framework takes care of assigning it to the menu item.

As an aside, I would note that the Delphi implementation of Vista themed menus has a large number of subtle bugs, many related to drawing of images. However, these bugs are relatively minor in visual impact.

like image 159
David Heffernan Avatar answered Jan 01 '23 10:01

David Heffernan