Skip to content

model

model

Attributes

COLUMNS = ('Key', 'Value', 'Type') module-attribute

KIND_ROLE = QtCore.Qt.ItemDataRole.UserRole + 1 module-attribute

ModelPath = tuple[str | int, ...] module-attribute

NODE_ROLE = QtCore.Qt.ItemDataRole.UserRole + 2 module-attribute

NON_EDITABLE_KINDS = (Kind.DICT, Kind.LIST, Kind.NULL, Kind.BINARY) module-attribute

Classes

JsonTreeModel(undo_stack, parent=None)

Bases: QAbstractItemModel

Tree model over a JSON document.

Edits made through the view go through undo_stack; the *_at methods mutate the tree directly and are meant to be called by those commands.

Initialize the model.

Parameters:

Name Type Description Default
undo_stack QUndoStack

Stack that receives user edits.

required
parent QObject | None

Parent object.

None
Source code in src/json_config_qt/tree/model.py
24
25
26
27
28
29
30
31
32
33
34
35
36
37
def __init__(
    self,
    undo_stack: QtGui.QUndoStack,
    parent: QtCore.QObject | None = None,
):
    """Initialize the model.

    Args:
        undo_stack (QtGui.QUndoStack): Stack that receives user edits.
        parent (QtCore.QObject | None, optional): Parent object.
    """
    super().__init__(parent)
    self.undo_stack = undo_stack
    self._root = JsonNode(None, {})
Attributes
undo_stack = undo_stack instance-attribute
Methods:
add_child(parent, key, value)

Push an undoable edit appending a child to a container node.

Source code in src/json_config_qt/tree/model.py
148
149
150
151
152
153
154
def add_child(self, parent: JsonNode, key: str | int, value: JsonValue) -> None:
    """Push an undoable edit appending a child to a container node."""
    self.undo_stack.push(
        commands.InsertChild(
            self, self.path_of(parent), len(parent.children), key, value
        )
    )
assign_at(path, value)

Replace the value (and type) of the node at path, rebuilding children.

Source code in src/json_config_qt/tree/model.py
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
def assign_at(self, path: ModelPath, value: JsonValue) -> None:
    """Replace the value (and type) of the node at *path*, rebuilding children."""
    node = self.node_at(path)
    index = self.index_for(node)
    if node.children:
        self.beginRemoveRows(index, 0, len(node.children) - 1)
        node.children = []
        self.endRemoveRows()
    count = len(value) if isinstance(value, dict | list) else 0
    if count:
        self.beginInsertRows(index, 0, count - 1)
        node.assign(value)
        self.endInsertRows()
    else:
        node.assign(value)
    last = self.index_for(node, len(COLUMNS) - 1)
    self.dataChanged.emit(self.index_for(node), last)
columnCount(parent=QtCore.QModelIndex())

Return the number of columns (key, value, type).

Source code in src/json_config_qt/tree/model.py
193
194
195
def columnCount(self, parent=QtCore.QModelIndex()) -> int:
    """Return the number of columns (key, value, type)."""
    return len(COLUMNS)
data(index, role=QtCore.Qt.ItemDataRole.DisplayRole)

Return the data of index for role.

Besides the standard roles, KIND_ROLE returns the node's Kind and NODE_ROLE the JsonNode itself.

Parameters:

Name Type Description Default
index QModelIndex

The cell.

required
role int

The item data role.

DisplayRole

Returns:

Name Type Description
Any Any

The data, or None if there is none for this role.

Source code in src/json_config_qt/tree/model.py
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
def data(
    self, index: QtCore.QModelIndex, role=QtCore.Qt.ItemDataRole.DisplayRole
) -> typing.Any:
    """Return the data of *index* for *role*.

    Besides the standard roles, KIND_ROLE returns the node's Kind and
    NODE_ROLE the JsonNode itself.

    Args:
        index (QtCore.QModelIndex): The cell.
        role (int): The item data role.

    Returns:
        Any: The data, or None if there is none for this role.
    """
    if not index.isValid():
        return None
    node, column = self.node_for(index), index.column()
    Role = QtCore.Qt.ItemDataRole
    if role == KIND_ROLE:
        return node.kind
    if role == NODE_ROLE:
        return node
    if column == KEY_COLUMN and role == Role.DisplayRole:
        return str(node.key)
    if column == TYPE_COLUMN and role == Role.DisplayRole:
        return node.kind.value
    if column != VALUE_COLUMN:
        return None
    if role == Role.DisplayRole:
        return self._display_value(node)
    if role == Role.EditRole:
        return node.value
    if role == Role.CheckStateRole and node.kind is Kind.BOOL:
        return (
            QtCore.Qt.CheckState.Checked
            if node.value
            else (QtCore.Qt.CheckState.Unchecked)
        )
    if role == Role.DecorationRole and node.kind is Kind.COLOR:
        return QtGui.QColor(node.value)
    if role == Role.ForegroundRole and node.kind is Kind.NULL:
        return QtWidgets.QApplication.palette().placeholderText()
    return None
flags(index)

Return item flags; only the value column of editable types is editable.

Bool values are additionally user-checkable.

Source code in src/json_config_qt/tree/model.py
206
207
208
209
210
211
212
213
214
215
216
217
218
219
def flags(self, index: QtCore.QModelIndex) -> QtCore.Qt.ItemFlag:
    """Return item flags; only the value column of editable types is editable.

    Bool values are additionally user-checkable.
    """
    flags = QtCore.Qt.ItemFlag.ItemIsEnabled | QtCore.Qt.ItemFlag.ItemIsSelectable
    if index.column() != VALUE_COLUMN:
        return flags
    node = self.node_for(index)
    if node.kind is Kind.BOOL:
        flags |= QtCore.Qt.ItemFlag.ItemIsUserCheckable
    if node.kind not in NON_EDITABLE_KINDS:
        flags |= QtCore.Qt.ItemFlag.ItemIsEditable
    return flags
headerData(section, orientation, role=QtCore.Qt.ItemDataRole.DisplayRole)

Return the column titles for the horizontal header.

Source code in src/json_config_qt/tree/model.py
197
198
199
200
201
202
203
204
def headerData(self, section, orientation, role=QtCore.Qt.ItemDataRole.DisplayRole):
    """Return the column titles for the horizontal header."""
    if (
        orientation == QtCore.Qt.Orientation.Horizontal
        and role == QtCore.Qt.ItemDataRole.DisplayRole
    ):
        return COLUMNS[section]
    return None
index(row, column, parent=QtCore.QModelIndex())

Return the index of a child row/column of parent.

Parameters:

Name Type Description Default
row int

Child row.

required
column int

Child column.

required
parent QModelIndex

Parent index; invalid for top-level rows.

QModelIndex()

Returns:

Type Description
QModelIndex

QtCore.QModelIndex: The child index, or an invalid index if out of range.

Source code in src/json_config_qt/tree/model.py
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
def index(
    self,
    row: int,
    column: int,
    parent: QtCore.QModelIndex | QtCore.QPersistentModelIndex = QtCore.QModelIndex(),
) -> QtCore.QModelIndex:
    """Return the index of a child row/column of *parent*.

    Args:
        row (int): Child row.
        column (int): Child column.
        parent (QtCore.QModelIndex): Parent index; invalid for top-level rows.

    Returns:
        QtCore.QModelIndex: The child index, or an invalid index if out of range.
    """
    if not self.hasIndex(row, column, parent):
        return QtCore.QModelIndex()
    return self.createIndex(row, column, self.node_for(parent).children[row])
index_for(node, column=0)

Return the index of node in a column; the root maps to the invalid index.

Source code in src/json_config_qt/tree/model.py
75
76
77
78
79
def index_for(self, node: JsonNode, column: int = 0) -> QtCore.QModelIndex:
    """Return the index of *node* in a column; the root maps to the invalid index."""
    if node is self._root:
        return QtCore.QModelIndex()
    return self.createIndex(node.row, column, node)
insert_at(parent_path, row, key, value)

Insert a child into the container at parent_path at position row.

Source code in src/json_config_qt/tree/model.py
100
101
102
103
104
105
106
107
108
109
110
111
def insert_at(
    self, parent_path: ModelPath, row: int, key: str | int, value: JsonValue
) -> None:
    """Insert a child into the container at *parent_path* at position *row*."""
    parent = self.node_at(parent_path)
    parent_index = self.index_for(parent)
    self.beginInsertRows(parent_index, row, row)
    parent.children.insert(row, JsonNode(key, value, parent))
    parent.renumber()
    self.endInsertRows()
    self._refresh_summary(parent)
    self._refresh_keys(parent, row + 1)
load(data)

Replace the model's content.

Parameters:

Name Type Description Default
data dict[str, JsonValue]

The JSON object to show.

required
Source code in src/json_config_qt/tree/model.py
40
41
42
43
44
45
46
47
48
def load(self, data: dict[str, JsonValue]) -> None:
    """Replace the model's content.

    Args:
        data (dict[str, JsonValue]): The JSON object to show.
    """
    self.beginResetModel()
    self._root = JsonNode(None, data)
    self.endResetModel()
node_at(path)

Return the node at path (keys from the root).

Source code in src/json_config_qt/tree/model.py
55
56
57
58
59
60
def node_at(self, path: ModelPath) -> JsonNode:
    """Return the node at *path* (keys from the root)."""
    node = self._root
    for key in path:
        node = next(child for child in node.children if child.key == key)
    return node
node_for(index)

Return the node of index; the invalid index maps to the root.

Source code in src/json_config_qt/tree/model.py
71
72
73
def node_for(self, index: QtCore.QModelIndex) -> JsonNode:
    """Return the node of *index*; the invalid index maps to the root."""
    return index.internalPointer() if index.isValid() else self._root
parent(child)

Return the parent index of child, invalid for top-level rows.

Source code in src/json_config_qt/tree/model.py
181
182
183
184
185
def parent(self, child: QtCore.QModelIndex) -> QtCore.QModelIndex:  # ty: ignore
    """Return the parent index of *child*, invalid for top-level rows."""
    if not child.isValid():
        return QtCore.QModelIndex()
    return self.index_for(self.node_for(child).parent)
path_of(node) staticmethod

Return the keys leading from the root to node.

Source code in src/json_config_qt/tree/model.py
62
63
64
65
66
67
68
69
@staticmethod
def path_of(node: JsonNode) -> ModelPath:
    """Return the keys leading from the root to *node*."""
    keys: list[str | int] = []
    while node.parent is not None:
        keys.append(node.key)
        node = node.parent
    return tuple(reversed(keys))
remove_at(path)

Remove the node at path from its parent.

Source code in src/json_config_qt/tree/model.py
113
114
115
116
117
118
119
120
121
122
def remove_at(self, path: ModelPath) -> None:
    """Remove the node at *path* from its parent."""
    node = self.node_at(path)
    parent, row = node.parent, node.row
    self.beginRemoveRows(self.index_for(parent), row, row)
    parent.children.pop(row)
    parent.renumber()
    self.endRemoveRows()
    self._refresh_summary(parent)
    self._refresh_keys(parent, row)
remove_node(node)

Push an undoable edit removing a node.

Source code in src/json_config_qt/tree/model.py
156
157
158
def remove_node(self, node: JsonNode) -> None:
    """Push an undoable edit removing a node."""
    self.undo_stack.push(commands.RemoveChild(self, self.path_of(node)))
rowCount(parent=QtCore.QModelIndex())

Return the number of children of parent; only column 0 has children.

Source code in src/json_config_qt/tree/model.py
187
188
189
190
191
def rowCount(self, parent=QtCore.QModelIndex()) -> int:
    """Return the number of children of *parent*; only column 0 has children."""
    if parent.column() > 0:
        return 0
    return len(self.node_for(parent).children)
setData(index, value, role=QtCore.Qt.ItemDataRole.EditRole)

Push an undoable edit for the value cell at index.

Parameters:

Name Type Description Default
index QModelIndex

The cell; only the value column is editable.

required
value Any

The new value, or a check state for bool values.

required
role int

EditRole, or CheckStateRole for bool values.

EditRole

Returns:

Name Type Description
bool bool

True if the edit was accepted.

Source code in src/json_config_qt/tree/model.py
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
def setData(self, index, value, role=QtCore.Qt.ItemDataRole.EditRole) -> bool:
    """Push an undoable edit for the value cell at *index*.

    Args:
        index (QtCore.QModelIndex): The cell; only the value column is editable.
        value (Any): The new value, or a check state for bool values.
        role (int): EditRole, or CheckStateRole for bool values.

    Returns:
        bool: True if the edit was accepted.
    """
    if not index.isValid() or index.column() != VALUE_COLUMN:
        return False
    node = self.node_for(index)
    if role == QtCore.Qt.ItemDataRole.CheckStateRole and node.kind is Kind.BOOL:
        value = QtCore.Qt.CheckState(value) == QtCore.Qt.CheckState.Checked
    elif role != QtCore.Qt.ItemDataRole.EditRole:
        return False
    self.set_value(node, typing.cast(JsonValue, value))
    return True
set_value(node, value)

Push an undoable edit replacing a node's value.

Source code in src/json_config_qt/tree/model.py
142
143
144
145
146
def set_value(self, node: JsonNode, value: JsonValue) -> None:
    """Push an undoable edit replacing a node's value."""
    if value == node.to_python() and type(value) is type(node.to_python()):
        return
    self.undo_stack.push(commands.SetValue(self, self.path_of(node), value))
to_python()

Return the current content as plain JSON data.

Source code in src/json_config_qt/tree/model.py
50
51
52
def to_python(self) -> dict[str, JsonValue]:
    """Return the current content as plain JSON data."""
    return self._root.to_python()