today's neat PyGTK hack: fixing paste in gtk.SpinButton
07:00 pm
GtkSpinButtons have an annoying behaviour in numeric mode that makes it hard to paste values into them. If the value you're pasting has more decimal places that your spinbutton is configured for, it simply doesn't work. More annoyingly still, the existing contents of the box is not removed when you paste in the new value.

This fix makes both the standard GTK+ paste actions, plus middle-click behave in a way more like the user will expect:
def spinbutton_fix_paste (spinbutton):
	def _paste (button, clipboard):
		button.delete_text (0, -1)

		text = clipboard.wait_for_text ()
		ndigits = button.get_digits ()
		try:
			idx = text.index ('.')
		except ValueError:
			button.set_text (text)
			return

		if ndigits == 0:
			button.set_text (text[:idx])
		else:
			button.set_text (text[:idx + ndigits + 1])

	def _spinbutton_press_event (button, event):
		if event.button == 2: # paste
			clipboard = button.get_clipboard ("PRIMARY")
			_paste (button, clipboard)
			button.grab_focus ()

			return True

		return False
	
	def _spinbutton_paste_clipboard (button):
		clipboard = button.get_clipboard ("CLIPBOARD")
		_paste (button, clipboard)
	
	spinbutton.connect ('paste-clipboard', _spinbutton_paste_clipboard)
	spinbutton.connect ('button-press-event', _spinbutton_press_event)
Call it with each of your spinbutton widgets when you set up. You could probably write a function to descend the GTK+ packing tree, checking isinstance (widget, gtk.SpinButton) if you felt like it; or you could implement the whole thing as a subclass, if you're not using Glade.
(posted on Tuesday January 15th, 2008 at 07:00 pm — 4 comments)

Livejournal

Navigation

Related Links

Syndication

RSS 2.0 Atom FOAF

Planetarium

Web Presence

Hacking Life   UCC   GNOME

Contact Me

License

Creative Commons License