Drawing icons for PopupMenu items


#1

I am struggling to add a Drawable icon to my PopupMenu’s items. I can successfully draw an icon on the first item, but passing the same Drawable to subsequent menu items causes an exception.

Here’s what I’ve got:

// In header
DrawableComposite* folderIcon;

// In .cpp's constructor
ScopedPointer<XmlElement> svgFolderIcon (XmlDocument::parse (BinaryData::foldericon_svg));
if (svgFolderIcon != nullptr) {
  folderIcon = dynamic_cast<DrawableComposite*>(Drawable::createFromSVG(*svgFolderIcon));
}

// later (menu is a PopupMenu)
menu.addItem(1, "label1", true, false, folderIcon); // this works
menu.addItem(2, "label2", true, false, folderIcon); // this breaks

The exception in Juce_PopupMenu.cpp is triggered on line 1332:

image (other.image != nullptr ? other.image->createCopy() : nullptr)

“Exception has occurred. EXC_BAD_ACCESS (code=1, address=0x170)”

Can anyone suggest why I can’t pass my Drawable to two PopupMenu items? Or is there is a better way to show icons on multiple items?

Thanks in advance.


#2

Drawable::createFromSVG()

The object returned must be deleted by the caller. 
If something goes wrong while parsing, it may return nullptr.

and

void PopupMenu::addItem	(	int 	itemResultID,
const String & 	itemText,
bool 	isEnabled,
bool 	isTicked,
Drawable * 	iconToUse 
)		
Appends a new item with an icon.

Parameters
itemResultID	the number that will be returned from the show() method if the user picks this item. The value should never be zero, because that's used to indicate that the user didn't select anything.
itemText	the text to show.
isEnabled	if false, the item will be shown 'greyed-out' and can't be picked
isTicked	if true, the item will be shown with a tick next to it
iconToUse	a Drawable object to use as the icon to the left of the item. 
>>> The menu will take ownership of this drawable object and will delete it later when no longer needed

you should do:

menu.addItem(id, name, true, false, Drawable::createFromSVG(*svgFolderIcon)); 

for each item


#3

Perfect, thank you so much!


#4

hopefully the docs are accurate and that solution works for ya


#5

It does indeed work :slight_smile:

I had seen the PopupMenu doc referencing the fact that the Drawable would be be deleted when no longer needed, and suspected that’s what was happening.

Thanks for the speedy suggestion!