Safely replaces all items in a QComboBox and sets the current index, ensuring that the `currentTextChanged` signal is emitted exactly once (and only if items are present). This method suppresses intermediate signal emissions that can be triggered by `clear()` and `addItems()` — both
(combo_box: QtWidgets.QComboBox, items: list[str], index: int = 0)
| 71 | |
| 72 | |
| 73 | def set_combo_items(combo_box: QtWidgets.QComboBox, items: list[str], index: int = 0): |
| 74 | """Safely replaces all items in a QComboBox and sets the current index, ensuring |
| 75 | that the `currentTextChanged` signal is emitted exactly once (and only if items are |
| 76 | present). |
| 77 | |
| 78 | This method suppresses intermediate signal emissions that can be triggered |
| 79 | by `clear()` and `addItems()` — both of which may emit multiple signals |
| 80 | depending on the underlying Qt model and signal connections. |
| 81 | |
| 82 | It also handles the edge case where the item at the target index is already |
| 83 | selected: by default, Qt will not emit a signal if the index doesn't change. |
| 84 | To ensure consistent behavior, this method temporarily sets the index to -1 |
| 85 | (i.e., no selection), which is done with signals blocked, then restores the |
| 86 | intended index — causing the signal to emit once and only once. |
| 87 | |
| 88 | Parameters: |
| 89 | combo_box (QComboBox): The combo box to update. |
| 90 | items (list of str): New items to populate the combo box. |
| 91 | index (int): The index to select after updating items. Defaults to 0. |
| 92 | |
| 93 | Note: |
| 94 | - If the items list is empty, no item will be selected and no signal will be emitted. |
| 95 | - This method is designed to be safe for use with PySide, where signals |
| 96 | cannot be manually emitted, and future-proof if multiple slots are connected. |
| 97 | """ |
| 98 | combo_box.blockSignals(True) |
| 99 | combo_box.clear() |
| 100 | combo_box.addItems(items) |
| 101 | combo_box.blockSignals(False) |
| 102 | |
| 103 | if not items: |
| 104 | combo_box.setCurrentIndex(-1) |
| 105 | return |
| 106 | |
| 107 | current = combo_box.currentIndex() |
| 108 | if current == index: |
| 109 | # Temporarily change index to suppress duplicate signal |
| 110 | combo_box.blockSignals(True) |
| 111 | combo_box.setCurrentIndex(-1) |
| 112 | combo_box.blockSignals(False) |
| 113 | |
| 114 | combo_box.setCurrentIndex(index) |
| 115 | |
| 116 | |
| 117 | class BodypartListWidget(QtWidgets.QListWidget): |
no test coverage detected