| 1 |
# (C) Copyright 2004-2023 Enthought, Inc., Austin, TX |
| 2 |
# All rights reserved. |
| 3 |
# |
| 4 |
# This software is provided without warranty under the terms of the BSD |
| 5 |
# license included in LICENSE.txt and may be redistributed only under |
| 6 |
# the conditions described in the aforementioned license. The license |
| 7 |
# is also available online at http://www.enthought.com/licenses/BSD.txt |
| 8 |
# |
| 9 |
# Thanks for using Enthought open source! |
| 10 |
|
| 11 |
from traits.api import HasTraits, Str, List |
| 12 |
from traitsui.api import Group, Item, TableEditor, View |
| 13 |
from traitsui.table_column import ObjectColumn |
| 14 |
|
| 15 |
|
| 16 |
class Word(HasTraits): |
| 17 |
word = Str() |
| 18 |
|
| 19 |
|
| 20 |
class Foo(HasTraits): |
| 21 |
|
| 22 |
# arbitrary string containing spaces |
| 23 |
input = Str() |
| 24 |
|
| 25 |
# input split on space |
| 26 |
parsed = List() |
| 27 |
|
| 28 |
def _input_changed(self): |
| 29 |
words = self.input.split() |
| 30 |
|
| 31 |
for word in self.parsed[:]: |
| 32 |
if word.word in words: |
| 33 |
words.remove(word.word) |
| 34 |
else: |
| 35 |
self.parsed.remove(word) |
| 36 |
|
| 37 |
for word in words: |
| 38 |
self.parsed.append(Word(word=word)) |
| 39 |
|
| 40 |
return |
| 41 |
|
| 42 |
table_editor = TableEditor( |
| 43 |
columns=[ObjectColumn(name='word')], editable=True |
| 44 |
) |
| 45 |
|
| 46 |
help = Str( |
| 47 |
"""Type in the 'input' box before clicking the Parsed tab. |
| 48 |
The first non-whitespace character will cause changes to the parsed trait |
| 49 |
and therefore changes to the table rows. That is expected. |
| 50 |
|
| 51 |
BUG: the table grabs the focus from 'input' and thus subsequent typing goes |
| 52 |
into one of the table cells. |
| 53 |
|
| 54 |
If you click the 'Parsed' tab, to view the table, and then the 'Inputs' tab |
| 55 |
the focus will stay with the 'input' box. |
| 56 |
""" |
| 57 |
) |
| 58 |
|
| 59 |
traits_view = View( |
| 60 |
Group(Item('help', style='readonly'), Item('input'), label='Input'), |
| 61 |
Group(Item('parsed', editor=table_editor), label='Parsed'), |
| 62 |
dock='tab', |
| 63 |
resizable=True, |
| 64 |
width=320, |
| 65 |
height=240, |
| 66 |
) |
| 67 |
|
| 68 |
|
| 69 |
if __name__ == '__main__': |
| 70 |
|
| 71 |
# simple test of the model |
| 72 |
foo = Foo() |
| 73 |
foo.input = 'these words in the list' |
| 74 |
assert [word.word for word in foo.parsed] == [ |
| 75 |
'these', |
| 76 |
'words', |
| 77 |
'in', |
| 78 |
'the', |
| 79 |
'list', |
| 80 |
] |
| 81 |
foo.input = 'these dudes in the bar' |
| 82 |
assert [word.word for word in foo.parsed] == [ |
| 83 |
'these', |
| 84 |
'in', |
| 85 |
'the', |
| 86 |
'dudes', |
| 87 |
'bar', |
| 88 |
] |
| 89 |
|
| 90 |
foo.configure_traits(kind='modal') |
| 91 |
print(foo.input, [word.word for word in foo.parsed]) |