I want to create a magicgui widget that contains two ComboBox
widgets. The choices of the second ComboBox
should depend on the current value of the first ComboBox
. How can I accomplish that?
I know that the choices
keyword of the @magicgui
decorator can use functions as input.
I want to create a magicgui widget that contains two ComboBox
widgets. The choices of the second ComboBox
should depend on the current value of the first ComboBox
. How can I accomplish that?
I know that the choices
keyword of the @magicgui
decorator can use functions as input.
1 Answer
Reset to default 0The following code should illustrate how to achieve two ComboBox
widgets where the choices of the second depend on the current value of the first. This makes use of the changed
signal of the first ComboBox
to call the reset_choices
of the second ComboBox
to update its choices
whenever the value of the first ComboBox
got changed. The possible choices are saved as a dict
.
# Dictionary to save choice dependencies.
choices = {
"Choice 1": ["First A", "First B", "First C"],
"Choice 2": ["Second A", "Second B", "Second C", "Second D"],
"Choice 3": ["Only one choice"],
}
# The choices function receives the `ComboBox`
# widget as argument.
def get_second_choice(gui):
# before final initialization the parent
# of our `ComboBox` widget is None.
if gui.parent is not None:
return choices[gui.parent.box1.value]
else:
return []
@magicgui(
box1={"widget_type": "ComboBox", "choices": list(choices.keys())},
box2={"widget_type": "ComboBox", "choices": get_second_choice},
)
def widget(box1, box2, viewer: napari.Viewer) -> None:
return f"{box1} - {box2}"
# Changes to box1 should result in resetting
# choices in box2.
widget.box1.changed.connect(widget.box2.reset_choices)