Tree views - Best design practices

Diez B. Roggisch deets at
Thu Jan 8 17:41:20 CET 2009

Filip Gruszczyński wrote:

> Hi!
> I have certain design problem, which I cannot solve elegantly. Maybe
> you know some good design patterns for this kind of tasks.
> Task:
> We have a model which has two kinds of objects: groups and elements.
> Groups can hold other groups (subgroups) and elements. It's a simple
> directory tree, for example. We would like to display it in a tree
> view (which sound good for this kind of model). What is more required,
> for groups and elements there are different sets of operations, which
> should be available under right click. For example for group, there
> should be operations: 'add element' and 'add group', and for element
> there should be 'change properties'.
> Do you know any smart way to achieve this? The simplest way is to ask
> for the class and display operations accordingly. But from the first
> day with OO programming I have heard, that asking for class is wrong.
> But I can hardly see any easy and more maintainable solution for this
> problem. Could you help me with this?

You don't ask *for* the class. You ask the class itself (or better, the
object you currently deal with) what operations it supports. Your
treeview-code then gets a list of strings for example (or better, a list of
tuples (action, menuentry) ) that it uses to build the context-menu. When a
given entry is selected, you then ask the object again to perform the
action on itself, by passing the action-name. Or invoking a method called
that way, or some such.

Thus your treeview-code is completely generic and easily extendable with new

There are variations of this scheme, if you don't want to "pollute" your
model-classes with view/controller-logic. Then you need some sort of
ActionFactory or something like that, which eventually somewhere might
resort to a hard-coded list of class-to-action-mappings.


More information about the Python-list mailing list