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,148 @@
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
+ """StatusLabel – Statustext mit Symbol und rollenabhängiger Farbe.
24
+
25
+ Autarke Einzeldatei: benötigt nur Python ≥ 3.11 und PySide6 (Essentials). Die Datei
26
+ kann allein in ein anderes Projekt kopiert werden; weitere Dateien, Ressourcen oder
27
+ Pakete sind nicht nötig.
28
+
29
+ Beispiel::
30
+
31
+ from status_label import StatusLabel
32
+
33
+ label = StatusLabel()
34
+ label.show_message("Gespeichert", "success") # ✔ grün bzw. hellgrün im Dunkelmodus
35
+ label.show_message("Verbindung fehlt", "error")
36
+
37
+ Rollen: ``plain``, ``info``, ``success``, ``warning``, ``error``, ``busy``, ``locked``.
38
+ Die Bedeutung steht immer auch als Symbol im Text, nie nur als Farbe. Die Farbe folgt
39
+ einem Wechsel zwischen hellem und dunklem Farbschema zur Laufzeit.
40
+ """
41
+
42
+ from __future__ import annotations
43
+
44
+ from PySide6.QtCore import QEvent, Qt, QTimer
45
+ from PySide6.QtGui import QColor, QGuiApplication, QPalette
46
+ from PySide6.QtWidgets import QLabel, QWidget
47
+
48
+ __all__ = ["StatusLabel"]
49
+
50
+
51
+ # ── Statustext ─ identisch in allen Dateien mit Statusanzeige (bewusst kopiert, Test prüft Gleichheit) ──
52
+ _ROLE_COLORS = {
53
+ # Rolle: (hell, dunkel) – Kontrast ≥ 4,5:1 auf Standardhintergründen
54
+ "accent": ("#1f6feb", "#5aa2ff"),
55
+ "muted": ("#5f6773", "#a3abb8"),
56
+ "success": ("#1a7a37", "#6fd08c"),
57
+ "warning": ("#8a5a00", "#f0b44c"),
58
+ "error": ("#b3261e", "#ff8f87"),
59
+ "busy": ("#1f5fbf", "#7db4ff"),
60
+ "locked": ("#5f6773", "#a3abb8"),
61
+ }
62
+ _ROLE_SYMBOLS = {"success": "✔", "error": "✖", "warning": "⚠", "busy": "⟳", "info": "ℹ", "locked": "🔒", "plain": ""}
63
+
64
+
65
+ def _base_palette(widget: QWidget) -> QPalette:
66
+ """Ausdrücklich gesetzte Fensterpalette, sonst die der Anwendung (Stylesheets verfälschen die eigene)."""
67
+ window = widget.window()
68
+ return window.palette() if window.testAttribute(Qt.WidgetAttribute.WA_SetPalette) else QGuiApplication.palette()
69
+
70
+
71
+ def _role_color(widget: QWidget, role: str) -> QColor:
72
+ light, dark = _ROLE_COLORS.get(role, _ROLE_COLORS["muted"])
73
+ return QColor(dark if _base_palette(widget).color(QPalette.ColorRole.Window).lightness() < 128 else light)
74
+
75
+
76
+ class _StatusText(QLabel):
77
+ """Einzeiliger oder umbrechender Statustext: ``show_message(text, role)``."""
78
+
79
+ _role = "plain" # Klassenwert: Qt kann Ereignisse schon während der Konstruktion liefern
80
+
81
+ def __init__(self, parent: QWidget | None = None) -> None:
82
+ super().__init__(parent)
83
+ self._role = "plain"
84
+ self.setTextFormat(Qt.TextFormat.PlainText)
85
+ self.setWordWrap(True)
86
+ hints = QGuiApplication.styleHints()
87
+ if hasattr(hints, "colorSchemeChanged"):
88
+ hints.colorSchemeChanged.connect(self._scheme_changed)
89
+
90
+ def _scheme_changed(self, *_: object) -> None:
91
+ # Paletten werden je nach Stil verzögert aktualisiert; deshalb zweimal abgleichen.
92
+ for delay in (0, 150):
93
+ QTimer.singleShot(delay, self, self._recolor)
94
+
95
+ def show_message(self, text: str, role: str = "plain") -> None:
96
+ symbol = _ROLE_SYMBOLS.get(role, "")
97
+ self.setText(f"{symbol} {text}".strip() if text else "")
98
+ self._role = role
99
+ self._recolor()
100
+
101
+ def role(self) -> str:
102
+ return self._role
103
+
104
+ def _recolor(self) -> None:
105
+ sheet = ""
106
+ if self._role not in ("plain", ""):
107
+ sheet = f"color: {_role_color(self, 'accent' if self._role == 'info' else self._role).name()};"
108
+ if sheet != self.styleSheet():
109
+ self.setStyleSheet(sheet)
110
+
111
+ def changeEvent(self, event: QEvent) -> None:
112
+ super().changeEvent(event)
113
+ if event.type() == QEvent.Type.PaletteChange:
114
+ self._recolor()
115
+
116
+ def showEvent(self, event: QEvent) -> None:
117
+ super().showEvent(event)
118
+ self._recolor()
119
+ # ── Ende Statustext ──
120
+
121
+
122
+ class StatusLabel(_StatusText):
123
+ """Öffentliche Statusanzeige.
124
+
125
+ * ``show_message(text, role)`` – Text mit Symbol; leerer Text leert die Anzeige.
126
+ * ``role()`` – zuletzt gesetzte Rolle.
127
+ * ``SYMBOLS`` – Symbol je Rolle (nur lesen).
128
+ """
129
+
130
+ SYMBOLS = dict(_ROLE_SYMBOLS)
131
+
132
+
133
+ def _demo() -> None: # pragma: no cover – nur zum Ausprobieren: python status_label.py
134
+ from PySide6.QtWidgets import QApplication, QVBoxLayout
135
+
136
+ app = QApplication.instance() or QApplication([])
137
+ host = QWidget()
138
+ layout = QVBoxLayout(host)
139
+ for role in ("plain", "info", "success", "warning", "error", "busy", "locked"):
140
+ label = StatusLabel()
141
+ label.show_message(f"Rolle {role}", role)
142
+ layout.addWidget(label)
143
+ host.show()
144
+ app.exec()
145
+
146
+
147
+ if __name__ == "__main__":
148
+ _demo()
@@ -0,0 +1,293 @@
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
+ """SwitchEditor – Wahrheitswert als gezeichneter Umschalter mit Zustandstext.
24
+
25
+ Autarke Einzeldatei: benötigt nur Python ≥ 3.11 und PySide6 (Essentials).
26
+
27
+ Beispiel::
28
+
29
+ from switch_editor import SwitchEditor
30
+
31
+ switch = SwitchEditor(on_text="Aktiv", off_text="Inaktiv")
32
+ switch.set_value(False)
33
+ switch.value_edited.connect(print) # Klick oder Leertaste
34
+
35
+ Der Zustand steht immer auch als Text daneben (nicht nur als Farbe); ``None`` zeigt
36
+ „Nicht gesetzt“ mit mittig stehendem Knopf. Farben kommen aus der Palette.
37
+ Optionen (``configure``): ``optional``, ``on_text``, ``off_text``.
38
+ """
39
+
40
+ from __future__ import annotations
41
+
42
+ from contextlib import contextmanager
43
+ from typing import Any
44
+
45
+ from PySide6.QtCore import QRectF, QSize, Qt, Signal
46
+ from PySide6.QtGui import QColor, QPainter, QPalette, QPen
47
+ from PySide6.QtWidgets import QAbstractButton, QHBoxLayout, QLabel, QWidget
48
+
49
+ __all__ = ["SwitchEditor"]
50
+
51
+
52
+ # ── Wertbasis ─ identisch in allen Editor-Dateien (bewusst kopiert, Test prüft Gleichheit) ──
53
+ def _same(a: Any, b: Any) -> bool:
54
+ """Gleichheit ohne Pythons ``True == 1``-Vermischung."""
55
+ if a is b:
56
+ return True
57
+ if isinstance(a, bool) != isinstance(b, bool):
58
+ return False
59
+ if isinstance(a, list) and isinstance(b, list):
60
+ return len(a) == len(b) and all(_same(x, y) for x, y in zip(a, b))
61
+ if isinstance(a, dict) and isinstance(b, dict):
62
+ return a.keys() == b.keys() and all(_same(a[k], b[k]) for k in a)
63
+ try:
64
+ return bool(a == b)
65
+ except Exception: # noqa: BLE001 – fremde Typen ohne Vergleich
66
+ return False
67
+
68
+
69
+ class _ValueWidget(QWidget):
70
+ """Gemeinsamer Vertrag aller Editoren.
71
+
72
+ * ``value()`` / ``set_value(v)`` – ``None`` bedeutet „nicht gesetzt“; ein Wert falschen
73
+ Typs löst ``ValueError`` aus und wird nie still umgewandelt.
74
+ * ``value_changed(object)`` – jede Wertänderung, auch programmatisch.
75
+ * ``value_edited(object)`` – nur Änderungen durch den Benutzer.
76
+ * ``configure(**optionen)`` – Schlüssel aus ``OPTIONS``; unbekannte → ``TypeError``.
77
+ * ``set_read_only(bool)``, ``input_error()`` / ``input_error_changed(str)``, ``commit()``.
78
+ """
79
+
80
+ value_changed = Signal(object)
81
+ value_edited = Signal(object)
82
+ input_error_changed = Signal(str)
83
+
84
+ #: Schlüssel, die ``configure()`` annimmt.
85
+ OPTIONS: tuple[str, ...] = ("optional",)
86
+
87
+ def __init__(self, parent: QWidget | None = None) -> None:
88
+ super().__init__(parent)
89
+ self._optional = False
90
+ self._read_only = False
91
+ self._silent = 0
92
+ self._last_error = ""
93
+
94
+ # -- von Unterklassen bereitzustellen ------------------------------------------------
95
+ def value(self) -> Any:
96
+ raise NotImplementedError
97
+
98
+ def _apply_value(self, value: Any) -> None:
99
+ raise NotImplementedError
100
+
101
+ def _apply_options(self) -> None:
102
+ """Darstellung nach ``configure()`` nachführen."""
103
+
104
+ def _apply_read_only(self, read_only: bool) -> None:
105
+ self.setEnabled(not read_only)
106
+
107
+ def input_error(self) -> str:
108
+ """Grund, warum die aktuelle Eingabe keinen gültigen Wert ergibt (sonst leer)."""
109
+ return ""
110
+
111
+ def commit(self) -> None:
112
+ """Schließt eine angefangene Eingabe ab."""
113
+
114
+ # -- öffentliche Schnittstelle --------------------------------------------------------
115
+ def set_value(self, value: Any) -> None:
116
+ """Setzt den Wert programmatisch (ohne ``value_edited``)."""
117
+ old = self.value()
118
+ with self._programmatic():
119
+ self._apply_value(value)
120
+ new = self.value()
121
+ if not _same(old, new):
122
+ self.value_changed.emit(new)
123
+ self._check_error()
124
+
125
+ def configure(self, **options: Any) -> None:
126
+ """Setzt mehrere Optionen auf einmal, z. B. ``configure(optional=True)``."""
127
+ unknown = sorted(set(options) - set(self.OPTIONS))
128
+ if unknown:
129
+ raise TypeError(f"{type(self).__name__}: unbekannte Option(en) {', '.join(unknown)}")
130
+ for key, value in options.items():
131
+ self._set_option(key, value)
132
+ with self._programmatic():
133
+ self._apply_options()
134
+ self._check_error()
135
+
136
+ def options(self) -> dict[str, Any]:
137
+ """Aktuelle Optionen."""
138
+ return {key: getattr(self, f"_{key}") for key in self.OPTIONS}
139
+
140
+ def _set_option(self, key: str, value: Any) -> None:
141
+ if key == "optional":
142
+ value = bool(value)
143
+ setattr(self, f"_{key}", value)
144
+
145
+ def set_optional(self, optional: bool) -> None:
146
+ self.configure(optional=optional)
147
+
148
+ def is_optional(self) -> bool:
149
+ return self._optional
150
+
151
+ def set_read_only(self, read_only: bool) -> None:
152
+ self._read_only = bool(read_only)
153
+ self._apply_read_only(self._read_only)
154
+
155
+ def is_read_only(self) -> bool:
156
+ return self._read_only
157
+
158
+ # -- Hilfen für Unterklassen ----------------------------------------------------------
159
+ @contextmanager
160
+ def _programmatic(self):
161
+ self._silent += 1
162
+ try:
163
+ yield
164
+ finally:
165
+ self._silent -= 1
166
+
167
+ def _user_changed(self, *_: Any) -> None:
168
+ """Nach einer echten Benutzereingabe aufzurufen."""
169
+ if self._silent:
170
+ return
171
+ value = self.value()
172
+ self._check_error()
173
+ self.value_changed.emit(value)
174
+ self.value_edited.emit(value)
175
+
176
+ def _check_error(self) -> None:
177
+ error = self.input_error()
178
+ if error != self._last_error:
179
+ self._last_error = error
180
+ self.input_error_changed.emit(error)
181
+ # ── Ende Wertbasis ──
182
+
183
+
184
+ class _SwitchButton(QAbstractButton):
185
+ """Gezeichneter Umschalter, per Maus und Leertaste bedienbar."""
186
+
187
+ def __init__(self, parent: QWidget | None = None) -> None:
188
+ super().__init__(parent)
189
+ self.setCheckable(True)
190
+ self.setCursor(Qt.CursorShape.PointingHandCursor)
191
+ self.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
192
+ self.undefined = False
193
+
194
+ def sizeHint(self) -> QSize:
195
+ return QSize(44, 24)
196
+
197
+ minimumSizeHint = sizeHint
198
+
199
+ def paintEvent(self, event) -> None:
200
+ painter = QPainter(self)
201
+ painter.setRenderHint(QPainter.RenderHint.Antialiasing)
202
+ palette = self.palette()
203
+ track = QRectF(2, (self.height() - 20) / 2, 40, 20)
204
+ on = self.isChecked() and not self.undefined
205
+ enabled = self.isEnabled()
206
+ accent = palette.color(QPalette.ColorGroup.Active, QPalette.ColorRole.Highlight)
207
+ text = palette.color(QPalette.ColorGroup.Active if enabled else QPalette.ColorGroup.Disabled, QPalette.ColorRole.WindowText)
208
+ muted = QColor(text)
209
+ muted.setAlpha(150)
210
+ if enabled:
211
+ fill = accent if on else palette.color(QPalette.ColorRole.Base)
212
+ border = accent if on else muted
213
+ else:
214
+ border = QColor(text)
215
+ border.setAlpha(90)
216
+ fill = QColor(border) if on else palette.color(QPalette.ColorGroup.Disabled, QPalette.ColorRole.Window)
217
+ painter.setPen(QPen(border, 1.4))
218
+ painter.setBrush(fill)
219
+ painter.drawRoundedRect(track, 10, 10)
220
+ x = track.center().x() - 7 if self.undefined else (track.right() - 17 if on else track.left() + 3)
221
+ painter.setPen(Qt.PenStyle.NoPen)
222
+ knob = palette.color(QPalette.ColorRole.HighlightedText) if on and enabled else border
223
+ painter.setBrush(knob)
224
+ painter.drawEllipse(QRectF(x, track.top() + 3, 14, 14))
225
+ if self.hasFocus():
226
+ painter.setPen(QPen(accent, 1.5, Qt.PenStyle.DotLine))
227
+ painter.setBrush(Qt.BrushStyle.NoBrush)
228
+ painter.drawRoundedRect(track.adjusted(-1.5, -1.5, 1.5, 1.5), 11, 11)
229
+
230
+
231
+ class SwitchEditor(_ValueWidget):
232
+ """Wahrheitswert als Umschalter mit Zustandstext."""
233
+
234
+ OPTIONS = ("optional", "on_text", "off_text")
235
+
236
+ def __init__(self, parent: QWidget | None = None, *, on_text: str = "Ein", off_text: str = "Aus") -> None:
237
+ super().__init__(parent)
238
+ self._on_text, self._off_text = on_text, off_text
239
+ layout = QHBoxLayout(self)
240
+ layout.setContentsMargins(0, 0, 0, 0)
241
+ layout.setSpacing(8)
242
+ self._button = _SwitchButton(self)
243
+ self._button.clicked.connect(self._on_clicked)
244
+ self._label = QLabel(off_text, self)
245
+ layout.addWidget(self._button)
246
+ layout.addWidget(self._label)
247
+ layout.addStretch(1)
248
+ self.setFocusProxy(self._button)
249
+ self._update_label()
250
+
251
+ @property
252
+ def button(self) -> QAbstractButton:
253
+ return self._button
254
+
255
+ def _on_clicked(self) -> None:
256
+ self._button.undefined = False
257
+ self._update_label()
258
+ self._user_changed()
259
+
260
+ def _update_label(self) -> None:
261
+ if self._button.undefined:
262
+ self._label.setText("Nicht gesetzt")
263
+ else:
264
+ self._label.setText(self._on_text if self._button.isChecked() else self._off_text)
265
+ self._button.setAccessibleName(self._label.text())
266
+
267
+ def value(self) -> bool | None:
268
+ return None if self._button.undefined else self._button.isChecked()
269
+
270
+ def _apply_value(self, value: Any) -> None:
271
+ if value is not None and not isinstance(value, bool):
272
+ raise ValueError("Wahrheitswert erwartet")
273
+ self._button.undefined = value is None
274
+ self._button.setChecked(bool(value))
275
+ self._update_label()
276
+ self._button.update()
277
+
278
+ def _apply_options(self) -> None:
279
+ self._update_label()
280
+
281
+
282
+ def _demo() -> None: # pragma: no cover – python switch_editor.py
283
+ from PySide6.QtWidgets import QApplication
284
+
285
+ app = QApplication.instance() or QApplication([])
286
+ switch = SwitchEditor(on_text="Aktiv", off_text="Inaktiv")
287
+ switch.value_edited.connect(print)
288
+ switch.show()
289
+ app.exec()
290
+
291
+
292
+ if __name__ == "__main__":
293
+ _demo()