Jeremy S wrote:
I would like to use a spinbutton but instead of just displaying a
float or integer, I want the display to be formatted.  In my case I
want it to be formatted as currency ($ in front and commas separating
thousands, millions, etc.), but I can't even find any information on
how to tackle this problem generally.

I know for treeviews this type of thing can be accomplished with
set_cell_data_func.  Is there anything similar for spinbuttons?

The "input" and "output" signals on the spinbutton solve this problem. Using the "input" signal is rather complex however because the second argument is a C pointer to a double and not a python type. To make it worse, it's passed as an opaque "gpointer" type. I found (by looking at the pygtk source code) that I could access the real address from it using the "hash" function, and once I had that I could use ctypes to set the double it points to.

Attached an ugly hack that solves your problem. Thanks for posting btw, this was fun ;)

--
Tim Evans
Applied Research Associates NZ
http://www.aranz.com/
import gtk, ctypes

def _currency_input(spinbutton, gpointer):
    text = spinbutton.get_text()
    if text.startswith('$'):
        text = text[1:]
    double = ctypes.c_double.from_address(hash(gpointer))
    double.value = float(text)
    return True

def _currency_output(spinbutton):
    text = '$%.*f' % (int(spinbutton.props.digits), 
spinbutton.props.adjustment.value)
    spinbutton.set_text(text)
    return True

def format_spinbutton_currency(spinbutton):
    spinbutton.connect('input', _currency_input)
    spinbutton.connect('output', _currency_output)

def _test():
    s = gtk.SpinButton(gtk.Adjustment(value=1, lower=0, upper=1000, 
step_incr=1))
    s.props.digits = 2
    format_spinbutton_currency(s)
    w = gtk.Window()
    w.props.border_width = 12
    w.add(s)
    w.show_all()
    w.connect('destroy', gtk.main_quit)
    gtk.main()

if __name__ == '__main__':
    _test()
_______________________________________________
pygtk mailing list   pygtk@daa.com.au
http://www.daa.com.au/mailman/listinfo/pygtk
Read the PyGTK FAQ: http://www.async.com.br/faq/pygtk/

Reply via email to