The controller - so to speak - is the most complicated part of this example. It is the only part of the MVC pattern which knows the model and the view instances which it is linked to. These are accessible via members self.model and self.view respectively.
# This is file ctrl_glade.py
from gtkmvc.controller import Controller
import gtk
class MyController (Controller):
def __init__(self, model):
Controller.__init__(self, model)
# The controller is an observer for properties contained in
# the model:
self.model.registerObserver(self)
return
def registerView(self, view):
"""This method is called by the view, that calls it when it is
ready to register itself. Here we connect the 'pressed' signal
of the button with a controller's method. Signal 'destroy'
for the main window is handled as well."""
Controller.registerView(self, view)
# connects the signals:
self.view['main_window'].connect('destroy', gtk.mainquit)
# initializes the text of label:
self.view['label'].set_text("%d" % self.model.counter)
return
# signals:
def on_button_clicked(self, button):
self.model.counter += 1 # changes the model
return
# observable properties:
def property_counter_change_notification(self, model, old, new):
self.view['label'].set_text("%d" % new)
print "Property 'counter' changed from %d to %d" % (old, new)
return
pass # end of class
In the class constructor, at first base class constructor is called, passing the Model instance this Controller instance belongs to. From that moment on, class member self.model will be accessible.
Then method Model.registerObserver is called, in order to make the controller an observer for the observable property counter in the model. After this, every change applied to MyModel class' member counter will make method property_counter_change_notification of class MyController be called automatically.
Method registerView is called when a class View instance requires to be registered to the controller it belongs to. This method is mainly used to connect signals and initialize the GUI side that depends on the application logic. In the example, signal destroy of the main window is connected to gtk.mainquit to close the application when the user closes the window. Notice here the use of member self.view and how a class View can be used as a map to retrieve widgets from their names.
Also, the text label is initialized to the initial value of the counter.
Method on_button_clicked is called as a callback every time the user clicks the button. The corresponding signal is automatically connected to this method when class MyView registers itself within the controller.
Finally, method property_counter_change_notification is called when the property counter in class MyModel changes. The model containing the property, the old value and the new value are passed to this method. Notice that the model is passed since the controller might be an observer for more than one models, even different from the model it is directly connected to in the MVC chain.