79520112

Date: 2025-03-19 11:59:08
Score: 0.5
Natty:
Report link

The 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)
Reasons:
  • Blacklisted phrase (1): how to achieve
  • Long answer (-1):
  • Has code block (-0.5):
  • Self-answer (0.5):
  • Low reputation (0.5):
Posted by: Niklas Netter