Skip to content

editor_widget

editor_widget

Attributes

NO_PARENT = '(none — root layer)' module-attribute

Classes

ConfigEditorWidget(config, parent=None)

Bases: QWidget

Tree editor for the layers of a LayeredConfig.

The widget has no menus; hosts can place its public actions (save_action, save_all_action, new_layer_action, undo_action, redo_action, expand_all_action, collapse_all_action) wherever they like. Shortcuts only apply while the editor has focus.

Attributes:

Name Type Description
saved Signal

Emitted with the layer name after a layer is saved.

Initialize the editor.

Parameters:

Name Type Description Default
config LayeredConfig

The config whose layers are edited.

required
parent QWidget | None

Parent widget.

None
Source code in src/json_config_qt/editor_widget.py
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
def __init__(self, config: LayeredConfig, parent: QtWidgets.QWidget | None = None):
    """Initialize the editor.

    Args:
        config (LayeredConfig): The config whose layers are edited.
        parent (QtWidgets.QWidget | None, optional): Parent widget.
    """
    super().__init__(parent)
    self.document = LayerDocument(config, self)
    self.proxy = FilterProxy(self)
    self._create_actions()
    self._create_widgets()
    self._create_layouts()
    self._create_connections()
    self._refresh_combo()
    self._on_layer_changed(self.document.current_layer)
Attributes
document = LayerDocument(config, self) instance-attribute
proxy = FilterProxy(self) instance-attribute
saved = QtCore.Signal(str) class-attribute instance-attribute
Methods:
add_key(parent)

Ask for a key name and type, then add it to a dict node.

Parameters:

Name Type Description Default
parent JsonNode

The dict node to add the key to.

required
Source code in src/json_config_qt/editor_widget.py
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
def add_key(self, parent: JsonNode) -> None:
    """Ask for a key name and type, then add it to a dict node.

    Args:
        parent (JsonNode): The dict node to add the key to.
    """
    existing = {child.key for child in parent.children}
    key, ok = QtWidgets.QInputDialog.getText(self, "Add key", "Key name:")
    if not ok or not key:
        return
    if key in existing:
        QtWidgets.QMessageBox.warning(
            self, "Add key", f"Key '{key}' already exists."
        )
        return
    kind = self._ask_kind()
    if kind is not None:
        self.document.model.add_child(parent, key, nodes.default_value(kind))
        self._expand(parent)
append_item(parent)

Ask for a type, then append a default item to a list node.

Parameters:

Name Type Description Default
parent JsonNode

The list node to append to.

required
Source code in src/json_config_qt/editor_widget.py
390
391
392
393
394
395
396
397
398
399
400
401
def append_item(self, parent: JsonNode) -> None:
    """Ask for a type, then append a default item to a list node.

    Args:
        parent (JsonNode): The list node to append to.
    """
    kind = self._ask_kind()
    if kind is not None:
        self.document.model.add_child(
            parent, len(parent.children), nodes.default_value(kind)
        )
        self._expand(parent)
change_type(node, kind)

Replace a node's value with the default value of another type.

Parameters:

Name Type Description Default
node JsonNode

The node to convert.

required
kind Kind

The new type.

required
Source code in src/json_config_qt/editor_widget.py
403
404
405
406
407
408
409
410
411
412
def change_type(self, node: JsonNode, kind: Kind) -> None:
    """Replace a node's value with the default value of another type.

    Args:
        node (JsonNode): The node to convert.
        kind (Kind): The new type.
    """
    if kind != node.kind:
        self.document.model.set_value(node, nodes.default_value(kind))
        self._expand(node)
confirm_discard()

Ask what to do with unsaved layers; return False if the user cancels.

Source code in src/json_config_qt/editor_widget.py
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
def confirm_discard(self) -> bool:
    """Ask what to do with unsaved layers; return False if the user cancels."""
    if not self.document.is_dirty:
        return True
    Button = QtWidgets.QMessageBox.StandardButton
    names = ", ".join(self.document.dirty_layers)
    answer = QtWidgets.QMessageBox.question(
        self,
        "Unsaved changes",
        f"Save changes to: {names}?",
        Button.Save | Button.Discard | Button.Cancel,
    )
    if answer == Button.Save:
        return self.save_all()
    return answer == Button.Discard
prompt_new_layer()

Ask for a new layer's details and register it on the config.

Source code in src/json_config_qt/editor_widget.py
254
255
256
257
258
259
260
261
262
def prompt_new_layer(self) -> None:
    """Ask for a new layer's details and register it on the config."""
    dialog = NewLayerDialog(self.document.layers, self.document.current_layer, self)
    if dialog.exec() != QtWidgets.QDialog.DialogCode.Accepted:
        return
    try:
        self.document.new_layer(*dialog.values())
    except ValueError as error:
        QtWidgets.QMessageBox.warning(self, "New layer", str(error))
save_all()

Save all layers with unsaved edits, showing an error dialog on failure.

Returns:

Name Type Description
bool bool

True if everything was saved.

Source code in src/json_config_qt/editor_widget.py
284
285
286
287
288
289
290
def save_all(self) -> bool:
    """Save all layers with unsaved edits, showing an error dialog on failure.

    Returns:
        bool: True if everything was saved.
    """
    return self._guarded(self.document.save_all)
save_current()

Save the current layer, showing an error dialog on failure.

Returns:

Name Type Description
bool bool

True if the layer was saved.

Source code in src/json_config_qt/editor_widget.py
275
276
277
278
279
280
281
282
def save_current(self) -> bool:
    """Save the current layer, showing an error dialog on failure.

    Returns:
        bool: True if the layer was saved.
    """
    name = self.document.current_layer
    return name is not None and self._guarded(lambda: self.document.save_layer(name))

NewLayerDialog(layers, current, parent=None)

Bases: QDialog

Ask for the name, parent layer and file of a new layer.

Initialize the dialog.

Parameters:

Name Type Description Default
layers list[str]

Existing layer names offered as parent.

required
current str | None

Layer preselected as parent.

required
parent QWidget | None

Parent widget.

None
Source code in src/json_config_qt/editor_widget.py
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
def __init__(self, layers: list[str], current: str | None, parent=None):
    """Initialize the dialog.

    Args:
        layers (list[str]): Existing layer names offered as parent.
        current (str | None): Layer preselected as parent.
        parent (QtWidgets.QWidget | None, optional): Parent widget.
    """
    super().__init__(parent)
    self._layers = layers
    self._current = current
    self.setWindowTitle("New layer")
    self._create_widgets()
    self._create_layouts()
    self._create_connections()
Methods:
values()

Return the entered values.

Returns:

Type Description
tuple[str, str | None, Path | None]

tuple[str, str | None, pathlib.Path | None]: Layer name, parent layer name (None for a root layer) and file path (None if left empty).

Source code in src/json_config_qt/editor_widget.py
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
def values(self) -> tuple[str, str | None, pathlib.Path | None]:
    """Return the entered values.

    Returns:
        tuple[str, str | None, pathlib.Path | None]: Layer name, parent layer
            name (None for a root layer) and file path (None if left empty).
    """
    parent = self.parent_combo.currentText()
    path = self.path_edit.text().strip()
    return (
        self.name_edit.text().strip(),
        None if parent == NO_PARENT else parent,
        pathlib.Path(path) if path else None,
    )