Skip to content

Commit 4483e55

Browse files
SylvainCorlayjasongrout
authored andcommitted
Setup default selected index behavior
1 parent e643166 commit 4483e55

File tree

2 files changed

+18
-3
lines changed

2 files changed

+18
-3
lines changed

ipywidgets/widgets/widget_selectioncontainer.py

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,15 +10,16 @@
1010
from .widget_box import Box
1111
from .widget import register
1212
from .widget_core import CoreWidget
13-
from traitlets import Unicode, Dict, CInt, TraitError, validate
13+
from traitlets import Unicode, Dict, CInt, TraitError, validate, observe
1414

1515

1616
class _SelectionContainer(Box, CoreWidget):
1717
"""Base class used to display multiple child widgets."""
1818
_titles = Dict(help="Titles of the pages").tag(sync=True)
1919
selected_index = CInt(
2020
help="""The index of the selected page. This is either an integer selecting a particular sub-widget, or None to have no widgets selected.""",
21-
allow_none=True
21+
allow_none=True,
22+
default_value=None
2223
).tag(sync=True)
2324

2425
@validate('selected_index')
@@ -28,6 +29,11 @@ def _validated_index(self, proposal):
2829
else:
2930
raise TraitError('Invalid selection: index out of bounds')
3031

32+
@observe('children')
33+
def _observe_children(self, change):
34+
if self.selected_index is not None and len(change.new) < self.selected_index:
35+
self.selected_index = None
36+
3137
# Public methods
3238
def set_title(self, index, title):
3339
"""Sets the title of a container page.
@@ -79,6 +85,15 @@ class Tab(_SelectionContainer):
7985
_view_name = Unicode('TabView').tag(sync=True)
8086
_model_name = Unicode('TabModel').tag(sync=True)
8187

88+
def __init__(self, **kwargs):
89+
if 'children' in kwargs and 'selected_index' not in kwargs and len(kwargs['children']) > 0:
90+
kwargs['selected_index'] = 0
91+
super(Tab, self).__init__(**kwargs)
92+
93+
@observe('children')
94+
def _observe_children(self, change):
95+
if len(change.new) > 0:
96+
self.selected_index = 0
8297

8398
@register
8499
class Stacked(_SelectionContainer):

packages/controls/src/widget_selectioncontainer.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ export class SelectionContainerModel extends BoxModel {
3131
return {
3232
...super.defaults(),
3333
_model_name: 'SelectionContainerModel',
34-
selected_index: 0,
34+
selected_index: null,
3535
_titles: {}
3636
};
3737
}

0 commit comments

Comments
 (0)