[Pythonmac-SIG] [PyObjC] setting button name in NSOpenPanel

Nicholas Riley njriley at uiuc.edu
Thu Apr 2 14:23:03 CEST 2009


On Thu, Apr 02, 2009 at 01:36:46PM +0200, Steph-info wrote:
> Thanks Nicholas, it works for the "Open" button.
> 
> I found the following cocoa reference for the "Cancel" button :
> 
> """
>     NSSavePanel *panel = [NSSavePanel savePanel];
>     NSButton* cancelButton =
>         [[panel contentView]  
> buttonWithTag:NSFileHandlingPanelCancelButton];
> """
> 
> Do you know how I can translate this to PyObjC ?

This is a hack - NSFileHandlingPanelCancelButton is 0, so trying to
match the tag like this will match all buttons with no tag assigned
(as is the default in Interface Builder).  In addition, it assumes
that the button is a direct descendant of the window's content view -
since 2002 when the code above was written, it is no longer the case,
so that code is already broken on OS X 10.5.

That said, if you really must, a better way would be to check the
control's action rather than its tag, searching through the entire
hierarchy - something like this.

  def buttons_with_action(view, action):
      for subview in view.subviews():
          if isinstance(subview, NSButton) and subview.action() == action:
              yield subview
          for i in buttons_with_action(subview, action):
              yield i
  cancelButtons = list(buttons_with_action(openPanel.contentView(), 'cancel:'))
  if len(cancelButtons) != 1:
      pass # handle error
  cancelButtons[0].setTitle_('Go Away')
  openPanel.runModalForTypes_(None)

and assuming you're going to be distributing your app, make sure you
handle the case when the button isn't there, or there are two of them,
or the button doesn't have a title, or something else weird happens in
a future OS version.

-- 
Nicholas Riley <njriley at uiuc.edu>


More information about the Pythonmac-SIG mailing list