Search code examples
traitsenthoughttraitsui

Dynamically adding a trait with UI update


Is it possible in a configure_traits() window to have a button like 'Add integer' on which clicking will add a new integer field ready for edition in the same window?


Solution

  • As @jonathan-march points out, it would probably be safest if you only need a fixed number of fields to keep them hidden until you clicked the button, but if you need an indeterminate number, it's fairly trivial to make a List of Ints and then append to that list each time you click the button. The trouble will be in the book-keeping that comes with keeping track of the indices of those list elements when you want to listen to them. I whipped up a small example of how you might do this below:

    from traits.api import Button, HasStrictTraits, Int, List
    from traitsui.api import Group, Item, ListEditor, UItem, View
    
    
    class DynamicListOfInts(HasStrictTraits):
    
        integer_list = List(Int)
        add_int = Button('Add integer')
    
        def default_traits_view(self):
            view = View(
                Group(
                    UItem('add_int'),
                    Item('integer_list', editor=ListEditor()),
                ),
                width=300,
                height=500,
            )
            return view
    
        def _add_int_changed(self):
            self.integer_list.append(0)
    
    
    if __name__ == '__main__':
        list_of_ints = DynamicListOfInts()
        list_of_ints.configure_traits()