next up previous contents
Next: Observable Properties in details Up: Views Previous: Custom widgets support   Contents


An example about View Registration

A typical example of exploitation of the view registration mechanism is the setup of a gtk.TreeView chain: construction of TreeView, TreeViewColumn, CellRenderers, connection to the TreeModel, etc. As Glade does not provide a full support for these widgets, and as the TreeModel lives in the model-side of the application, their construction cannot occur within the View, but must be performed within the Controller, that knows both the view and model sides. The right time when this construction has to occur is the view registration.

The idea is to have a TreeView showing an integer and a string in two separated columns from a gtk.ListStore.

Now suppose you created a project in Glade that contains a window, some menus and other accessories, and a TreeView whose properties are set in Glade in a comfortable manner (see figure 4).

Figure: Designing a TreeView by means of Glade
Image treeview

In the example, the TreeView has been called tv_main, and after View creation the widget will be available with that name.

from gtkmvc import View

class MyView (View):
  def __init__(self, controller):
    View.__init__(self, controller, 'test.glade')
    #...
    return
  pass

The ListStore is of course not contained in the view, but it is created and stored in the Model. If the model had to be also a ListStore (i.e. derived from it) MyModel had to derive from gtkmvc.ListStoreModel instead of Model. To keep things easier, Has-A relationship is chosen.

from gtkmvc import Model
import gtk
import gobject

class MyModel (Model):
  def __init__(self):
    Model.__init__(self)

    self.list = gtk.ListStore(gobject.TYPE_INT, gobject.TYPE_STRING)
    return
  pass

The controller has the responsibility of connecting the TreeView and the ListStore, and it creates columns and renderers as well. Construction must occur after View has been created. More precisely, the ideal time is during view-registration.

from gtkmvc import Controller
import gtk

class MyCtrl (Controller):
  def __init__(self, m):
    Controller.__init__(self, m)
    return

  def register_view(self, view):
    Controller.__register_view(self, view)
    self.__setup_treeview()
    return

  def __setup_treeview(self):
    tv = self.view['tv_main']
    
    tv.set_model(self.model.list) # sets the model

    # creates the columns
    cell = gtk.CellRendererText()
    col = gtk.TreeViewColumn('Int', cell, text=0)
    tv.append_column(col)

    cell = gtk.CellRendererText()
    col = gtk.TreeViewColumn('String', cell, text=1)
    tv.append_column(col)

    # registers any treeview-related signals...

    return

  pass # end of class


next up previous contents
Next: Observable Properties in details Up: Views Previous: Custom widgets support   Contents
Roberto Cavada 2008-08-26