Overloading virtual method of widget without inheriting (PyQt)

marek.rocki at wp.pl marek.rocki at wp.pl
Tue May 27 06:08:27 EDT 2008


Since the "+=" operator won't work on methods, you have to write your
own class that will simulate dispatching multiple handlers for an
event. Maybe something like the following? I don't know, though, if it
would cooperate with PyQt nicely.

class MultiHandler(object):
	def __init__(self, owner, *initial_handlers):
		self.owner = owner
		self.handlers = list(initial_handlers)
	def __iadd__(self, handler):
		self.handlers.append(handler)
		return self
	def __call__(self, *args, **kwargs):
		for handler in self.handlers:
			handler(self.owner, *args, **kwargs)
		return None


class Calendar(object):
	def on_paint(self):
		print 'i am the default handler'

def handler1(self):
	print 'i am handler 1'

def handler2(self):
	print 'i am handler 2'


calendar = Calendar()
calendar.on_paint = MultiHandler(calendar, Calendar.on_paint)

calendar.on_paint()
calendar.on_paint += handler1
calendar.on_paint()
calendar.on_paint += handler2
calendar.on_paint()



More information about the Python-list mailing list