Friday, August 8, 2008

NSToolbar


Toolbars add a nice professional look to an application. Shown above is a screenshot from a simple demo of toolbars using PyObjC. The toolbar's delegate (MyToolbarDelegate) implements the three required methods. In this example, we add a custom toolbar item called "Analyze":

    def toolbar_itemForItemIdentifier_willBeInsertedIntoToolbar_(
self, toolbar, identifier, flag):
if identifier == "Analyze":
item = NSToolbarItem.alloc().initWithItemIdentifier_(
"Analyze")
item.setLabel_("Analyze")
item.setPaletteLabel_("Analyze")
item.setToolTip_("Analyze Your Gene")
item.setImage_(NSImage.imageNamed_("GeneFinderIcon"))
item.setTarget_(self.AD)
sel = 'analyze:'
item.setAction_(sel)
return item
return None

def toolbarDefaultItemIdentifiers_(self, toolbar):
return [NSToolbarCustomizeToolbarItemIdentifier,
NSToolbarShowColorsItemIdentifier,
"Analyze"]

def toolbarAllowedItemIdentifiers_(self, toolbar):
return [NSToolbarCustomizeToolbarItemIdentifier,
NSToolbarShowColorsItemIdentifier,
"Analyze",
NSToolbarPrintItemIdentifier,
NSToolbarShowFontsItemIdentifier,
NSToolbarSpaceItemIdentifier,
NSToolbarSeparatorItemIdentifier ]

There is an icon added to the project in Resources.

We also need to initialize the toolbar and attach it to the window. I do this in a separate class called MyToolbarController. (All the outlets are set up as you'd expect, in the xib file). This one is relayed through the AppDelegate (AD).

    def awakeFromNib(self):
self.toolbar = NSToolbar.alloc().initWithIdentifier_("toolbar")
self.toolbar.setDelegate_(self.AD.myToolbarDelegate)
print "delegate", self.toolbar.delegate()

self.toolbar.insertItemWithItemIdentifier_atIndex_("Analyze", 0)
for item in self.toolbar.items(): print item.itemIdentifier()

self.toolbar.setDisplayMode_(NSToolbarDisplayModeIconOnly)
# this allows customization as you'd expect

self.toolbar.setAllowsUserCustomization_(True)
self.toolbar.setAutosavesConfiguration_(True)
self.myWindow.setToolbar_(self.toolbar)
print "visible?", self.toolbar.isVisible()