@@ -48,7 +48,7 @@ def set_value(self, value: str | None) -> None:
48
48
if index != - 1 :
49
49
self .setCurrentIndex (index )
50
50
else :
51
- self .setCurrentIndex (0 ) # Set NULL if not found
51
+ self .setCurrentIndex (0 ) # Set selection to NULL if item with `value` was not found
52
52
53
53
54
54
class HierarchicalCodeComboBox (QComboBox ):
@@ -102,29 +102,39 @@ def value(self) -> str:
102
102
item = self .tree_widget .selectedItems ()[0 ]
103
103
return item .data (0 , Qt .UserRole )
104
104
105
- def set_value (self , value : str | None ) -> None :
106
- # NOTE: Does not work fully currently
105
+ def _find_item_recursive (self , item : QTreeWidgetItem , value : str ) -> QTreeWidgetItem :
106
+ """Recursively try to find item with given value and return the item if found."""
107
+ # Found item, return it
108
+ if item .data (0 , Qt .UserRole ) == value :
109
+ return item
110
+
111
+ # Loop children
112
+ for i in range (item .childCount ()):
113
+ found_item = self ._find_item_recursive (item .child (i ), value )
114
+ if found_item :
115
+ return found_item
107
116
108
- def find_item_recursive (item : QTreeWidgetItem , value : str ) -> QTreeWidgetItem :
109
- if item .data (0 , Qt .UserRole ) == value :
110
- return item
111
- for i in range (item .childCount ()):
112
- found_item = find_item_recursive (item .child (i ), value )
113
- if found_item :
114
- return found_item
115
- return None
117
+ return None
116
118
119
+ def set_value (self , value : str | None ) -> None :
120
+ # Set selection to NULL if `value` is None
117
121
if value is None :
118
- self .setCurrentIndex (0 )
122
+ self .setCurrentIndex (self . null_index )
119
123
return
120
124
125
+ # Loop top level tree items
121
126
for i in range (self .count ()):
122
- found_item = find_item_recursive (self .tree_widget .topLevelItem (i ), value )
127
+ # Handle child items recursively
128
+ found_item = self ._find_item_recursive (self .tree_widget .topLevelItem (i ), value )
129
+
130
+ # If matching item was found, set it as selected. Because of the hybrid TreeWidget + ComboBox
131
+ # nature of the widget, value setting is unintuitive and tricky
123
132
if found_item :
133
+ self .tree_widget .setCurrentItem (found_item )
124
134
idx = self .tree_widget .indexFromItem (found_item )
125
135
self .setRootModelIndex (idx .parent ())
126
136
self .setCurrentIndex (idx .row ())
127
137
self .setRootModelIndex (self .null_index .parent ())
128
138
return
129
139
130
- self .setCurrentIndex (0 ) # Set combobox index to NULL
140
+ self .setCurrentIndex (self . null_index ) # Set selection to NULL if item with `value` was not found
0 commit comments