Search code examples
pythonmodel-view-controllertraitstraitsui

TraitsUI - Joining views


Reading the documentation about applying the MVC pattern with TraitsUI, I read the example MVC_demo.py. Now, I'm wondering how to manage multiple "MVC". I want to write some "includeallMVCs.py" and to have something like:

import MyViewController1, MyViewController2, MyViewController2

class IncludeallMVCs(HasTraits):
    view = Include(MyViewController1, MyViewController2, MyViewController3)

Where MyViewController, MyViewController, MyViewController are classes like the MVC_demo sample.

So, the idea is to separate differents views with their controllers, and then "join" all of them in only one "generic" view.


Solution

  • Searching in the examples I found this one: Dynamic Forms Using Instances Then I modified it to separate an AdultHandler. In this example I use the salary variable to be controlled by AdultHandler.

    File: adult.py

    from traitsui.api import Handler
    class AdultHandler(Handler):
        def object_salary_changed (self, info):
            if (info.object.salary >= 20000):
                print "Good Salary!"
    
            else:
                print "Bad Salary"
    

    File: adult_model.py

    from adult import AdultHandler
    
    class AdultSpec ( HasTraits ):
        """ Trait list for adults (assigned to 'misc' for a Person when age >= 18).
        """
    
        marital_status   = Enum( 'single', 'married', 'divorced', 'widowed' )
        registered_voter = Bool
        military_service = Bool
        salary = Int
    
        traits_view = View(
            'marital_status',
            'registered_voter',
            'military_service',
            'salary',
            handler = AdultHandler()
        )
    
    if __name__ == '__main__':
        a = AdultSpec()
        a.configure_traits()
    

    File: main.py

    from adult_model import AdultSpec
    
    class Person ( HasTraits ):
        """ Demo class for demonstrating dynamic interface restructuring.
        """
        datainput       = Instance( AdultSpec )
    
        # Interface for attributes that depend on the value of 'age':
        spec_group = Group(
            Group(
                Item( name = 'datainput', style = 'custom' ),
                show_labels = False
            ),
            label       = 'Additional Info',
            show_border = True
        )
    
        # A simple View is enough as long as the right handler is specified:
        view = View(
            Group(
                spec_group
                ),
            title     = 'Using MVC',
            buttons   = [ 'OK' ],
            resizable = True,
            width = 300
        )
    
    # Create the demo:
    demo = Person( datainput = AdultSpec() )
    
    # Run the demo (if invoked from the command line):
    if __name__ == '__main__':
        demo.configure_traits()