Tuesday, March 1, 2011

TV with bindings in PyObjC


This post is a "note to myself" reminding me of how to do a very simple NSTableView with bindings in PyObjC.

There is a window in the xib file holding a Table View and two buttons, and an Array Controller as well. The buttons are hooked up to actions in the AppDelegate. The window of the app looks like the screenshot above. Here's the IB window with the objects on it:



The bindings are set up like this. The first one is for the left-hand Table Column. The second is for the App Controller.





One thing I always forget is whether you need self in the Model Key Path for the App Controller (you don't).

The code is below. The second thing I have trouble with is remembering to do the objc.ivar thing, and to have a method like setL_. Without those, the App Controller can read the values, but it can't write them to the model, and it won't know if the model is updated programmatically.


from Foundation import *
from AppKit import *
import objc

class TV_bindingsAppDelegate(NSObject):
L = objc.ivar("L")

def init(self):
self.L = [ {'x':'x1', 'y':'y1'},
{'x':'x2', 'y':'y2'} ]
return self

def setL_(self, value):
if value != self.L:
self.L = value

@objc.IBAction
def report_(self, sender):
print 'report'
for D in self.L:
for k in sorted(D.keys()):
print k, D[k],
print

@objc.IBAction
def reprogram_(self, sender):
L = self.L[:]
s = str(len(L)+1)
L.append({'x':'x'+s,'y':'y'+s})
self.setL_(L)

No comments: