Re: how to disable OK button when invalid input in UI
I managed this (see subject) the other day. I wanted to have a Perform
button (actually an Action) that would be greyed out like the OK button
when some parameters of my experiment were marked as invalid in the UI,
to ensure the user wouldn't start the experiment with old values in its
traits. This is how I did it using a handler.
return False if self.info.ui.errors > 0 else True
def perform(self, info):
view = View(
buttons = [
tooltip='Perform the experiment with the current
Controller automatically assigns self.info, so if you are just using
Handler you might need to do 'self.info = info' yourself in __init__()
Using an intermediate property like has_valid_parameters means that
subclasses of my ExperimentHandler can implement their own, more
sophisticated, _get_has_valid_parameters() method with the option to
call this method with super().
I found the necessary mention of ui.errors in:
'errors', dispatch='ui'), so it is not surprised that you couldn't find
it looking for the OK button code (which was my first instinct too).
Michael Sorich wrote:
> Any advice would be appreciated on how to disable the OK button
> conditional on any of the the traits in the UI being invalid.
> The default OK button becomes disabled under most circumstances but
> not when an instance trait is included in the view with style='custom'
> (see example below - if favourite_number is invalid (e.g. a string)
> the input field is highlighted and the OK button disabled, but if the
> address.street_number is invalid the field is highlighted but the OK
> button is still enabled).
> from enthought.traits.api import HasTraits, Str, Instance, Int
> from enthought.traits.ui.api import Item, View
> class Address ( HasTraits ):
> street_number = Int
> street_name = Str
> class Person( HasTraits ):
> name = Str
> favourite_number = Int
> address = Instance( Address, () )
> traits_view = View(['name', 'favourite_number', Item('address',
> buttons = ['OK','Cancel']
> I cannot seem to find the code for how the default OK button is
> defined when creating the view - presumably the 'enabled_when' trait
> is set to monitor a value on some object (perhaps the UI object) which
> flags when one or more of the traits are invalid. OKButton is defined
> in traits\ui\menu.py, but there is no indication here of how it is
> enabled/disabled and I presume the enabled_when trait is set at some
> later time. If anyone can point me to the correct file it would be
> Thanks in advance