dynamic-settings-widget 2.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. dynamic_settings_widget/__init__.py +56 -0
  2. dynamic_settings_widget/adapters/__init__.py +42 -0
  3. dynamic_settings_widget/adapters/base.py +179 -0
  4. dynamic_settings_widget/adapters/memory.py +201 -0
  5. dynamic_settings_widget/adapters/runner.py +63 -0
  6. dynamic_settings_widget/core/__init__.py +1 -0
  7. dynamic_settings_widget/core/catalog.py +201 -0
  8. dynamic_settings_widget/core/common.py +214 -0
  9. dynamic_settings_widget/core/conditions.py +146 -0
  10. dynamic_settings_widget/core/datatypes.py +414 -0
  11. dynamic_settings_widget/core/diagnostics.py +69 -0
  12. dynamic_settings_widget/core/loader.py +101 -0
  13. dynamic_settings_widget/core/model.py +245 -0
  14. dynamic_settings_widget/core/overrides.py +353 -0
  15. dynamic_settings_widget/core/parser.py +552 -0
  16. dynamic_settings_widget/core/presentation.py +68 -0
  17. dynamic_settings_widget/core/registry.py +258 -0
  18. dynamic_settings_widget/core/state.py +314 -0
  19. dynamic_settings_widget/data/example_catalog.json +23 -0
  20. dynamic_settings_widget/data/example_layout.json +23 -0
  21. dynamic_settings_widget/data/settings_catalog.schema.json +388 -0
  22. dynamic_settings_widget/data/settings_definition.schema.json +1041 -0
  23. dynamic_settings_widget/data/settings_layout.schema.json +701 -0
  24. dynamic_settings_widget/data/settings_override.schema.json +406 -0
  25. dynamic_settings_widget/py.typed +0 -0
  26. dynamic_settings_widget/session.py +1537 -0
  27. dynamic_settings_widget/standalone/__init__.py +67 -0
  28. dynamic_settings_widget/standalone/action_button.py +200 -0
  29. dynamic_settings_widget/standalone/auth_widget.py +377 -0
  30. dynamic_settings_widget/standalone/check_box_editor.py +233 -0
  31. dynamic_settings_widget/standalone/choice_buttons_editor.py +394 -0
  32. dynamic_settings_widget/standalone/color_editor.py +316 -0
  33. dynamic_settings_widget/standalone/dropdown_editor.py +356 -0
  34. dynamic_settings_widget/standalone/editable_label.py +428 -0
  35. dynamic_settings_widget/standalone/float_spin_box.py +621 -0
  36. dynamic_settings_widget/standalone/font_editor.py +348 -0
  37. dynamic_settings_widget/standalone/hotkey_editor.py +681 -0
  38. dynamic_settings_widget/standalone/info_label.py +190 -0
  39. dynamic_settings_widget/standalone/int_spin_box.py +627 -0
  40. dynamic_settings_widget/standalone/multi_choice_editor.py +428 -0
  41. dynamic_settings_widget/standalone/password_editor.py +348 -0
  42. dynamic_settings_widget/standalone/path_editor.py +615 -0
  43. dynamic_settings_widget/standalone/protected_group_box.py +287 -0
  44. dynamic_settings_widget/standalone/server_connection_editor.py +642 -0
  45. dynamic_settings_widget/standalone/slider_spin_box.py +840 -0
  46. dynamic_settings_widget/standalone/sound_selection_widget.py +710 -0
  47. dynamic_settings_widget/standalone/status_label.py +148 -0
  48. dynamic_settings_widget/standalone/switch_editor.py +293 -0
  49. dynamic_settings_widget/standalone/text_editor.py +265 -0
  50. dynamic_settings_widget/testlab/__init__.py +1 -0
  51. dynamic_settings_widget/testlab/__main__.py +5 -0
  52. dynamic_settings_widget/testlab/app.py +699 -0
  53. dynamic_settings_widget/testlab/assets/extra_sounds/Signal.wav +0 -0
  54. dynamic_settings_widget/testlab/assets/sounds/Benachrichtigung.wav +0 -0
  55. dynamic_settings_widget/testlab/assets/sounds/feedback/Signal.wav +0 -0
  56. dynamic_settings_widget/testlab/definitions/broken_base.json +25 -0
  57. dynamic_settings_widget/testlab/definitions/demo.json +634 -0
  58. dynamic_settings_widget/testlab/definitions/gallery.json +255 -0
  59. dynamic_settings_widget/testlab/definitions/override_example.json +41 -0
  60. dynamic_settings_widget/testlab/definitions/override_invalid.json +11 -0
  61. dynamic_settings_widget/testlab/definitions/override_syntax_error.json +5 -0
  62. dynamic_settings_widget/testlab/definitions/override_weaken.json +10 -0
  63. dynamic_settings_widget/testlab/definitions/voice_v2/01_left_top.json +1190 -0
  64. dynamic_settings_widget/testlab/definitions/voice_v2/catalog.json +1930 -0
  65. dynamic_settings_widget/testlab/definitions/voice_v2/models.json +141 -0
  66. dynamic_settings_widget/testlab/definitions/voice_v2/wakewords.json +161 -0
  67. dynamic_settings_widget/testlab/dummy.py +353 -0
  68. dynamic_settings_widget/testlab/extensions.py +149 -0
  69. dynamic_settings_widget/testlab/gallery.py +223 -0
  70. dynamic_settings_widget/testlab/http_adapter.py +430 -0
  71. dynamic_settings_widget/testlab/http_server.py +493 -0
  72. dynamic_settings_widget/testlab/voice_v2.py +251 -0
  73. dynamic_settings_widget/ui/__init__.py +23 -0
  74. dynamic_settings_widget/ui/base.py +63 -0
  75. dynamic_settings_widget/ui/builders.py +226 -0
  76. dynamic_settings_widget/ui/containers.py +441 -0
  77. dynamic_settings_widget/ui/dialog.py +231 -0
  78. dynamic_settings_widget/ui/editing.py +51 -0
  79. dynamic_settings_widget/ui/row.py +810 -0
  80. dynamic_settings_widget/ui/view.py +248 -0
  81. dynamic_settings_widget/widgets/__init__.py +74 -0
  82. dynamic_settings_widget/widgets/base.py +145 -0
  83. dynamic_settings_widget/widgets/bridge.py +222 -0
  84. dynamic_settings_widget/widgets/theme.py +107 -0
  85. dynamic_settings_widget-2.0.0.dist-info/METADATA +237 -0
  86. dynamic_settings_widget-2.0.0.dist-info/RECORD +90 -0
  87. dynamic_settings_widget-2.0.0.dist-info/WHEEL +5 -0
  88. dynamic_settings_widget-2.0.0.dist-info/entry_points.txt +5 -0
  89. dynamic_settings_widget-2.0.0.dist-info/licenses/LICENSE +21 -0
  90. dynamic_settings_widget-2.0.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,233 @@
1
+ # MIT License
2
+ #
3
+ # Copyright (c) 2026 marcosudau-vps
4
+ #
5
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ # of this software and associated documentation files (the "Software"), to deal
7
+ # in the Software without restriction, including without limitation the rights
8
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ # copies of the Software, and to permit persons to whom the Software is
10
+ # furnished to do so, subject to the following conditions:
11
+ #
12
+ # The above copyright notice and this permission notice shall be included in all
13
+ # copies or substantial portions of the Software.
14
+ #
15
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ # SOFTWARE.
22
+
23
+ """CheckBoxEditor – Wahrheitswert als Checkbox; „nicht gesetzt“ erscheint teilweise markiert.
24
+
25
+ Autarke Einzeldatei: benötigt nur Python ≥ 3.11 und PySide6 (Essentials).
26
+
27
+ Beispiel::
28
+
29
+ from check_box_editor import CheckBoxEditor
30
+
31
+ box = CheckBoxEditor(text="Beim Start öffnen")
32
+ box.set_value(True)
33
+ box.value_edited.connect(print) # True/False nach Klick oder Leertaste
34
+
35
+ Optionen (``configure``): ``optional``, ``text``.
36
+ """
37
+
38
+ from __future__ import annotations
39
+
40
+ from contextlib import contextmanager
41
+ from typing import Any
42
+
43
+ from PySide6.QtCore import Qt, Signal
44
+ from PySide6.QtWidgets import QCheckBox, QHBoxLayout, QWidget
45
+
46
+ __all__ = ["CheckBoxEditor"]
47
+
48
+
49
+ # ── Wertbasis ─ identisch in allen Editor-Dateien (bewusst kopiert, Test prüft Gleichheit) ──
50
+ def _same(a: Any, b: Any) -> bool:
51
+ """Gleichheit ohne Pythons ``True == 1``-Vermischung."""
52
+ if a is b:
53
+ return True
54
+ if isinstance(a, bool) != isinstance(b, bool):
55
+ return False
56
+ if isinstance(a, list) and isinstance(b, list):
57
+ return len(a) == len(b) and all(_same(x, y) for x, y in zip(a, b))
58
+ if isinstance(a, dict) and isinstance(b, dict):
59
+ return a.keys() == b.keys() and all(_same(a[k], b[k]) for k in a)
60
+ try:
61
+ return bool(a == b)
62
+ except Exception: # noqa: BLE001 – fremde Typen ohne Vergleich
63
+ return False
64
+
65
+
66
+ class _ValueWidget(QWidget):
67
+ """Gemeinsamer Vertrag aller Editoren.
68
+
69
+ * ``value()`` / ``set_value(v)`` – ``None`` bedeutet „nicht gesetzt“; ein Wert falschen
70
+ Typs löst ``ValueError`` aus und wird nie still umgewandelt.
71
+ * ``value_changed(object)`` – jede Wertänderung, auch programmatisch.
72
+ * ``value_edited(object)`` – nur Änderungen durch den Benutzer.
73
+ * ``configure(**optionen)`` – Schlüssel aus ``OPTIONS``; unbekannte → ``TypeError``.
74
+ * ``set_read_only(bool)``, ``input_error()`` / ``input_error_changed(str)``, ``commit()``.
75
+ """
76
+
77
+ value_changed = Signal(object)
78
+ value_edited = Signal(object)
79
+ input_error_changed = Signal(str)
80
+
81
+ #: Schlüssel, die ``configure()`` annimmt.
82
+ OPTIONS: tuple[str, ...] = ("optional",)
83
+
84
+ def __init__(self, parent: QWidget | None = None) -> None:
85
+ super().__init__(parent)
86
+ self._optional = False
87
+ self._read_only = False
88
+ self._silent = 0
89
+ self._last_error = ""
90
+
91
+ # -- von Unterklassen bereitzustellen ------------------------------------------------
92
+ def value(self) -> Any:
93
+ raise NotImplementedError
94
+
95
+ def _apply_value(self, value: Any) -> None:
96
+ raise NotImplementedError
97
+
98
+ def _apply_options(self) -> None:
99
+ """Darstellung nach ``configure()`` nachführen."""
100
+
101
+ def _apply_read_only(self, read_only: bool) -> None:
102
+ self.setEnabled(not read_only)
103
+
104
+ def input_error(self) -> str:
105
+ """Grund, warum die aktuelle Eingabe keinen gültigen Wert ergibt (sonst leer)."""
106
+ return ""
107
+
108
+ def commit(self) -> None:
109
+ """Schließt eine angefangene Eingabe ab."""
110
+
111
+ # -- öffentliche Schnittstelle --------------------------------------------------------
112
+ def set_value(self, value: Any) -> None:
113
+ """Setzt den Wert programmatisch (ohne ``value_edited``)."""
114
+ old = self.value()
115
+ with self._programmatic():
116
+ self._apply_value(value)
117
+ new = self.value()
118
+ if not _same(old, new):
119
+ self.value_changed.emit(new)
120
+ self._check_error()
121
+
122
+ def configure(self, **options: Any) -> None:
123
+ """Setzt mehrere Optionen auf einmal, z. B. ``configure(optional=True)``."""
124
+ unknown = sorted(set(options) - set(self.OPTIONS))
125
+ if unknown:
126
+ raise TypeError(f"{type(self).__name__}: unbekannte Option(en) {', '.join(unknown)}")
127
+ for key, value in options.items():
128
+ self._set_option(key, value)
129
+ with self._programmatic():
130
+ self._apply_options()
131
+ self._check_error()
132
+
133
+ def options(self) -> dict[str, Any]:
134
+ """Aktuelle Optionen."""
135
+ return {key: getattr(self, f"_{key}") for key in self.OPTIONS}
136
+
137
+ def _set_option(self, key: str, value: Any) -> None:
138
+ if key == "optional":
139
+ value = bool(value)
140
+ setattr(self, f"_{key}", value)
141
+
142
+ def set_optional(self, optional: bool) -> None:
143
+ self.configure(optional=optional)
144
+
145
+ def is_optional(self) -> bool:
146
+ return self._optional
147
+
148
+ def set_read_only(self, read_only: bool) -> None:
149
+ self._read_only = bool(read_only)
150
+ self._apply_read_only(self._read_only)
151
+
152
+ def is_read_only(self) -> bool:
153
+ return self._read_only
154
+
155
+ # -- Hilfen für Unterklassen ----------------------------------------------------------
156
+ @contextmanager
157
+ def _programmatic(self):
158
+ self._silent += 1
159
+ try:
160
+ yield
161
+ finally:
162
+ self._silent -= 1
163
+
164
+ def _user_changed(self, *_: Any) -> None:
165
+ """Nach einer echten Benutzereingabe aufzurufen."""
166
+ if self._silent:
167
+ return
168
+ value = self.value()
169
+ self._check_error()
170
+ self.value_changed.emit(value)
171
+ self.value_edited.emit(value)
172
+
173
+ def _check_error(self) -> None:
174
+ error = self.input_error()
175
+ if error != self._last_error:
176
+ self._last_error = error
177
+ self.input_error_changed.emit(error)
178
+ # ── Ende Wertbasis ──
179
+
180
+
181
+ class CheckBoxEditor(_ValueWidget):
182
+ """Wahrheitswert als Checkbox."""
183
+
184
+ OPTIONS = ("optional", "text")
185
+
186
+ def __init__(self, parent: QWidget | None = None, *, text: str = "") -> None:
187
+ super().__init__(parent)
188
+ self._null = False
189
+ self._text = text
190
+ layout = QHBoxLayout(self)
191
+ layout.setContentsMargins(0, 0, 0, 0)
192
+ self._box = QCheckBox(text, self)
193
+ self._box.clicked.connect(self._on_clicked)
194
+ layout.addWidget(self._box)
195
+ layout.addStretch(1)
196
+ self.setFocusProxy(self._box)
197
+
198
+ @property
199
+ def check_box(self) -> QCheckBox:
200
+ return self._box
201
+
202
+ def _on_clicked(self) -> None:
203
+ self._null = False
204
+ self._box.setTristate(False)
205
+ self._user_changed()
206
+
207
+ def value(self) -> bool | None:
208
+ return None if self._null else self._box.isChecked()
209
+
210
+ def _apply_value(self, value: Any) -> None:
211
+ if value is not None and not isinstance(value, bool):
212
+ raise ValueError("Wahrheitswert erwartet")
213
+ self._null = value is None
214
+ self._box.setTristate(self._null)
215
+ state = Qt.CheckState.PartiallyChecked if self._null else Qt.CheckState.Checked if value else Qt.CheckState.Unchecked
216
+ self._box.setCheckState(state)
217
+
218
+ def _apply_options(self) -> None:
219
+ self._box.setText(self._text)
220
+
221
+
222
+ def _demo() -> None: # pragma: no cover – python check_box_editor.py
223
+ from PySide6.QtWidgets import QApplication
224
+
225
+ app = QApplication.instance() or QApplication([])
226
+ box = CheckBoxEditor(text="Beim Start öffnen")
227
+ box.value_edited.connect(print)
228
+ box.show()
229
+ app.exec()
230
+
231
+
232
+ if __name__ == "__main__":
233
+ _demo()
@@ -0,0 +1,394 @@
1
+ # MIT License
2
+ #
3
+ # Copyright (c) 2026 marcosudau-vps
4
+ #
5
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ # of this software and associated documentation files (the "Software"), to deal
7
+ # in the Software without restriction, including without limitation the rights
8
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ # copies of the Software, and to permit persons to whom the Software is
10
+ # furnished to do so, subject to the following conditions:
11
+ #
12
+ # The above copyright notice and this permission notice shall be included in all
13
+ # copies or substantial portions of the Software.
14
+ #
15
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ # SOFTWARE.
22
+
23
+ """ChoiceButtonsEditor – exklusive Auswahl über nebeneinanderliegende Schaltflächen.
24
+
25
+ Autarke Einzeldatei: benötigt nur Python ≥ 3.11 und PySide6 (Essentials). Enthält
26
+ außerdem ``FlowLayout``, ein umbrechendes Layout, das auch einzeln nutzbar ist.
27
+
28
+ Beispiel::
29
+
30
+ from choice_buttons_editor import ChoiceButtonsEditor
31
+
32
+ buttons = ChoiceButtonsEditor()
33
+ buttons.set_choices([("off", "Aus"), ("standard", "Standard"), ("high", "Stark")])
34
+ buttons.set_value("standard")
35
+ buttons.value_edited.connect(print)
36
+
37
+ Bei Platzmangel brechen die Schaltflächen um. Die Auswahl ist zusätzlich zur Farbe
38
+ durch Fettschrift gekennzeichnet. Ein Wert, der nicht (mehr) angeboten wird, erscheint
39
+ als „⚠ … (nicht verfügbar)“. Optionen (``configure``): ``optional``.
40
+ """
41
+
42
+ from __future__ import annotations
43
+
44
+ import math
45
+ from collections.abc import Iterable
46
+ from contextlib import contextmanager
47
+ from typing import Any
48
+
49
+ from PySide6.QtCore import QMargins, QPoint, QRect, QSize, Qt, Signal
50
+ from PySide6.QtWidgets import QButtonGroup, QLayout, QLayoutItem, QPushButton, QWidget
51
+
52
+ __all__ = ["ChoiceButtonsEditor", "FlowLayout"]
53
+
54
+
55
+ # ── Wertbasis ─ identisch in allen Editor-Dateien (bewusst kopiert, Test prüft Gleichheit) ──
56
+ def _same(a: Any, b: Any) -> bool:
57
+ """Gleichheit ohne Pythons ``True == 1``-Vermischung."""
58
+ if a is b:
59
+ return True
60
+ if isinstance(a, bool) != isinstance(b, bool):
61
+ return False
62
+ if isinstance(a, list) and isinstance(b, list):
63
+ return len(a) == len(b) and all(_same(x, y) for x, y in zip(a, b))
64
+ if isinstance(a, dict) and isinstance(b, dict):
65
+ return a.keys() == b.keys() and all(_same(a[k], b[k]) for k in a)
66
+ try:
67
+ return bool(a == b)
68
+ except Exception: # noqa: BLE001 – fremde Typen ohne Vergleich
69
+ return False
70
+
71
+
72
+ class _ValueWidget(QWidget):
73
+ """Gemeinsamer Vertrag aller Editoren.
74
+
75
+ * ``value()`` / ``set_value(v)`` – ``None`` bedeutet „nicht gesetzt“; ein Wert falschen
76
+ Typs löst ``ValueError`` aus und wird nie still umgewandelt.
77
+ * ``value_changed(object)`` – jede Wertänderung, auch programmatisch.
78
+ * ``value_edited(object)`` – nur Änderungen durch den Benutzer.
79
+ * ``configure(**optionen)`` – Schlüssel aus ``OPTIONS``; unbekannte → ``TypeError``.
80
+ * ``set_read_only(bool)``, ``input_error()`` / ``input_error_changed(str)``, ``commit()``.
81
+ """
82
+
83
+ value_changed = Signal(object)
84
+ value_edited = Signal(object)
85
+ input_error_changed = Signal(str)
86
+
87
+ #: Schlüssel, die ``configure()`` annimmt.
88
+ OPTIONS: tuple[str, ...] = ("optional",)
89
+
90
+ def __init__(self, parent: QWidget | None = None) -> None:
91
+ super().__init__(parent)
92
+ self._optional = False
93
+ self._read_only = False
94
+ self._silent = 0
95
+ self._last_error = ""
96
+
97
+ # -- von Unterklassen bereitzustellen ------------------------------------------------
98
+ def value(self) -> Any:
99
+ raise NotImplementedError
100
+
101
+ def _apply_value(self, value: Any) -> None:
102
+ raise NotImplementedError
103
+
104
+ def _apply_options(self) -> None:
105
+ """Darstellung nach ``configure()`` nachführen."""
106
+
107
+ def _apply_read_only(self, read_only: bool) -> None:
108
+ self.setEnabled(not read_only)
109
+
110
+ def input_error(self) -> str:
111
+ """Grund, warum die aktuelle Eingabe keinen gültigen Wert ergibt (sonst leer)."""
112
+ return ""
113
+
114
+ def commit(self) -> None:
115
+ """Schließt eine angefangene Eingabe ab."""
116
+
117
+ # -- öffentliche Schnittstelle --------------------------------------------------------
118
+ def set_value(self, value: Any) -> None:
119
+ """Setzt den Wert programmatisch (ohne ``value_edited``)."""
120
+ old = self.value()
121
+ with self._programmatic():
122
+ self._apply_value(value)
123
+ new = self.value()
124
+ if not _same(old, new):
125
+ self.value_changed.emit(new)
126
+ self._check_error()
127
+
128
+ def configure(self, **options: Any) -> None:
129
+ """Setzt mehrere Optionen auf einmal, z. B. ``configure(optional=True)``."""
130
+ unknown = sorted(set(options) - set(self.OPTIONS))
131
+ if unknown:
132
+ raise TypeError(f"{type(self).__name__}: unbekannte Option(en) {', '.join(unknown)}")
133
+ for key, value in options.items():
134
+ self._set_option(key, value)
135
+ with self._programmatic():
136
+ self._apply_options()
137
+ self._check_error()
138
+
139
+ def options(self) -> dict[str, Any]:
140
+ """Aktuelle Optionen."""
141
+ return {key: getattr(self, f"_{key}") for key in self.OPTIONS}
142
+
143
+ def _set_option(self, key: str, value: Any) -> None:
144
+ if key == "optional":
145
+ value = bool(value)
146
+ setattr(self, f"_{key}", value)
147
+
148
+ def set_optional(self, optional: bool) -> None:
149
+ self.configure(optional=optional)
150
+
151
+ def is_optional(self) -> bool:
152
+ return self._optional
153
+
154
+ def set_read_only(self, read_only: bool) -> None:
155
+ self._read_only = bool(read_only)
156
+ self._apply_read_only(self._read_only)
157
+
158
+ def is_read_only(self) -> bool:
159
+ return self._read_only
160
+
161
+ # -- Hilfen für Unterklassen ----------------------------------------------------------
162
+ @contextmanager
163
+ def _programmatic(self):
164
+ self._silent += 1
165
+ try:
166
+ yield
167
+ finally:
168
+ self._silent -= 1
169
+
170
+ def _user_changed(self, *_: Any) -> None:
171
+ """Nach einer echten Benutzereingabe aufzurufen."""
172
+ if self._silent:
173
+ return
174
+ value = self.value()
175
+ self._check_error()
176
+ self.value_changed.emit(value)
177
+ self.value_edited.emit(value)
178
+
179
+ def _check_error(self) -> None:
180
+ error = self.input_error()
181
+ if error != self._last_error:
182
+ self._last_error = error
183
+ self.input_error_changed.emit(error)
184
+ # ── Ende Wertbasis ──
185
+
186
+
187
+ # ── Auswahloptionen ─ identisch in allen Dateien mit Auswahllisten (bewusst kopiert) ──
188
+ def _is_scalar(value: Any) -> bool:
189
+ return isinstance(value, (str, int, float, bool)) and not (isinstance(value, float) and not math.isfinite(value))
190
+
191
+
192
+ class _Choice:
193
+ """Ein auswählbarer Wert mit Beschriftung (intern; nimmt Qt-Umwandlungen wie bool↔int aus dem Spiel)."""
194
+
195
+ __slots__ = ("value", "label", "description", "available", "unavailable_reason")
196
+
197
+ def __init__(self, value: Any, label: str, description: str = "",
198
+ available: bool = True, unavailable_reason: str = "") -> None:
199
+ self.value, self.label, self.description = value, label, description
200
+ self.available, self.unavailable_reason = available, unavailable_reason
201
+
202
+ @classmethod
203
+ def parse(cls, raw: Any) -> "_Choice":
204
+ """Akzeptiert Skalar, ``(value, label[, description])``, ``{"value", "label", "description"}``
205
+ oder ein Objekt mit den Attributen ``value``/``label``/``description``."""
206
+ available, reason = True, ""
207
+ if isinstance(raw, dict):
208
+ if "value" not in raw or set(raw) - {"value", "label", "description", "available", "unavailable_reason"}:
209
+ raise ValueError(f"Auswahloption {raw!r}: erwartet value, label, description")
210
+ value, label, description = raw["value"], raw.get("label", str(raw["value"])), raw.get("description", "")
211
+ available, reason = raw.get("available", True), raw.get("unavailable_reason", "")
212
+ elif isinstance(raw, (tuple, list)):
213
+ if not 1 <= len(raw) <= 3:
214
+ raise ValueError(f"Auswahloption {raw!r}: erwartet (value, label[, description])")
215
+ value, label, description = raw[0], (raw[1] if len(raw) > 1 else str(raw[0])), (raw[2] if len(raw) > 2 else "")
216
+ elif _is_scalar(raw):
217
+ value, label, description = raw, str(raw), ""
218
+ elif hasattr(raw, "value") and hasattr(raw, "label"):
219
+ value, label, description = raw.value, raw.label, getattr(raw, "description", "") or ""
220
+ available, reason = getattr(raw, "available", True), getattr(raw, "unavailable_reason", "")
221
+ else:
222
+ raise ValueError(f"Auswahloption {raw!r} nicht lesbar")
223
+ if not _is_scalar(value):
224
+ raise ValueError(f"Auswahlwert {value!r} muss Text, Zahl oder Wahrheitswert sein")
225
+ if not isinstance(label, str) or not isinstance(description, str):
226
+ raise ValueError(f"Auswahloption {value!r}: label/description müssen Text sein")
227
+ if type(available) is not bool or not isinstance(reason, str):
228
+ raise ValueError("available muss boolesch und unavailable_reason Text sein")
229
+ return cls(value, label, description, available, reason)
230
+ # ── Ende Auswahloptionen ──
231
+
232
+
233
+ class FlowLayout(QLayout):
234
+ """Ordnet Elemente nebeneinander an und bricht bei Platzmangel um."""
235
+
236
+ def __init__(self, parent: QWidget | None = None, spacing: int = 6) -> None:
237
+ super().__init__(parent)
238
+ self._items: list[QLayoutItem] = []
239
+ self.setContentsMargins(QMargins(0, 0, 0, 0))
240
+ self.setSpacing(spacing)
241
+
242
+ def addItem(self, item: QLayoutItem) -> None:
243
+ self._items.append(item)
244
+
245
+ def count(self) -> int:
246
+ return len(self._items)
247
+
248
+ def itemAt(self, index: int) -> QLayoutItem | None:
249
+ return self._items[index] if 0 <= index < len(self._items) else None
250
+
251
+ def takeAt(self, index: int) -> QLayoutItem | None:
252
+ return self._items.pop(index) if 0 <= index < len(self._items) else None
253
+
254
+ def expandingDirections(self) -> Qt.Orientation:
255
+ return Qt.Orientation(0)
256
+
257
+ def hasHeightForWidth(self) -> bool:
258
+ return True
259
+
260
+ def heightForWidth(self, width: int) -> int:
261
+ return self._arrange(QRect(0, 0, width, 0), apply=False)
262
+
263
+ def setGeometry(self, rect: QRect) -> None:
264
+ super().setGeometry(rect)
265
+ self._arrange(rect, apply=True)
266
+
267
+ def sizeHint(self) -> QSize:
268
+ width = sum(i.sizeHint().width() for i in self._items) + self.spacing() * max(0, len(self._items) - 1)
269
+ height = max((i.sizeHint().height() for i in self._items), default=0)
270
+ return QSize(width, height)
271
+
272
+ def minimumSize(self) -> QSize:
273
+ size = QSize()
274
+ for item in self._items:
275
+ size = size.expandedTo(item.minimumSize())
276
+ return size
277
+
278
+ def _arrange(self, rect: QRect, *, apply: bool) -> int:
279
+ x, y, line = rect.x(), rect.y(), 0
280
+ for item in self._items:
281
+ if item.widget() is not None and item.widget().isHidden():
282
+ continue
283
+ hint = item.sizeHint().boundedTo(QSize(max(rect.width(), item.minimumSize().width()), 10_000))
284
+ if x + hint.width() > rect.right() + 1 and line > 0:
285
+ x, y, line = rect.x(), y + line + self.spacing(), 0
286
+ if apply:
287
+ item.setGeometry(QRect(QPoint(x, y), hint))
288
+ x += hint.width() + self.spacing()
289
+ line = max(line, hint.height())
290
+ return y + line - rect.y()
291
+
292
+
293
+ class ChoiceButtonsEditor(_ValueWidget):
294
+ """Exklusive Auswahl über Schaltflächen."""
295
+
296
+ OPTIONS = ("optional",)
297
+
298
+ def __init__(self, parent: QWidget | None = None) -> None:
299
+ super().__init__(parent)
300
+ self._current: Any = None
301
+ self._options: list[_Choice] = []
302
+ self._flow = FlowLayout(self)
303
+ self._group = QButtonGroup(self)
304
+ self._group.setExclusive(True)
305
+ self._group.idClicked.connect(self._on_clicked)
306
+
307
+ def buttons(self) -> list[QPushButton]:
308
+ return [b for b in self._group.buttons() if isinstance(b, QPushButton)]
309
+
310
+ def set_choices(self, choices: Iterable[Any]) -> None:
311
+ self._options = [_Choice.parse(c) for c in choices]
312
+ with self._programmatic():
313
+ self._rebuild()
314
+
315
+ def choices(self) -> list[dict[str, Any]]:
316
+ return [
317
+ {"value": o.value, "label": o.label, "description": o.description,
318
+ **({"available": False} if not o.available else {}),
319
+ **({"unavailable_reason": o.unavailable_reason} if o.unavailable_reason else {})}
320
+ for o in self._options
321
+ ]
322
+
323
+ def _on_clicked(self, index: int) -> None:
324
+ option = self._shown()[index]
325
+ value = option.value
326
+ if self._read_only or not option.available or _same(value, self._current):
327
+ return
328
+ self._current = value
329
+ with self._programmatic():
330
+ self._mark()
331
+ self._user_changed()
332
+
333
+ def _shown(self) -> list[_Choice]:
334
+ options = list(self._options)
335
+ if self._current is not None and not any(_same(self._current, o.value) for o in options):
336
+ options.append(_Choice(self._current, str(self._current), available=False))
337
+ return options
338
+
339
+ def value(self) -> Any:
340
+ return self._current
341
+
342
+ def _apply_value(self, value: Any) -> None:
343
+ if value is not None and not _is_scalar(value):
344
+ raise ValueError("Skalarer Auswahlwert erwartet")
345
+ self._current = value
346
+ self._rebuild()
347
+
348
+ def _rebuild(self) -> None:
349
+ shown = self._shown()
350
+ labels = [o.label if o.available else f"⚠ {o.label} (nicht verfügbar)" for o in shown]
351
+ if [b.text().replace("&&", "&") for b in self.buttons()] != labels:
352
+ for button in self.buttons():
353
+ self._group.removeButton(button)
354
+ self._flow.removeWidget(button)
355
+ button.deleteLater()
356
+ for index, label in enumerate(labels):
357
+ button = QPushButton(label.replace("&", "&&"), self)
358
+ button.setCheckable(True)
359
+ button.setAutoDefault(False)
360
+ self._group.addButton(button, index)
361
+ self._flow.addWidget(button)
362
+ button.show()
363
+ self.updateGeometry()
364
+ if self.buttons():
365
+ self.setFocusProxy(self.buttons()[0])
366
+ self._mark()
367
+
368
+ def _mark(self) -> None:
369
+ self._group.setExclusive(False)
370
+ for option, button in zip(self._shown(), self.buttons()):
371
+ button.setEnabled(option.available)
372
+ button.setToolTip("\n".join(filter(None, (option.description, option.unavailable_reason))))
373
+ selected = _same(option.value, self._current)
374
+ button.setChecked(selected)
375
+ font = button.font()
376
+ font.setBold(selected)
377
+ button.setFont(font)
378
+ self._group.setExclusive(True)
379
+
380
+
381
+ def _demo() -> None: # pragma: no cover – python choice_buttons_editor.py
382
+ from PySide6.QtWidgets import QApplication
383
+
384
+ app = QApplication.instance() or QApplication([])
385
+ buttons = ChoiceButtonsEditor()
386
+ buttons.set_choices([("off", "Aus"), ("standard", "Standard"), ("high", "Stark")])
387
+ buttons.set_value("standard")
388
+ buttons.value_edited.connect(print)
389
+ buttons.show()
390
+ app.exec()
391
+
392
+
393
+ if __name__ == "__main__":
394
+ _demo()