diff --git a/harmonyqml/backend/model/list_model.py b/harmonyqml/backend/model/list_model.py index 9dbeca12..2d7f1e44 100644 --- a/harmonyqml/backend/model/list_model.py +++ b/harmonyqml/backend/model/list_model.py @@ -5,15 +5,17 @@ from typing import ( from namedlist import namedlist from PyQt5.QtCore import ( - QAbstractListModel, QModelIndex, Qt, pyqtProperty, pyqtSlot + QAbstractListModel, QModelIndex, QObject, Qt, pyqtProperty, pyqtSlot ) NewValue = Union[Mapping[str, Any], Sequence] class ListModel(QAbstractListModel): - def __init__(self, initial_data: Optional[List[NewValue]] = None) -> None: - super().__init__() + def __init__(self, + initial_data: Optional[List[NewValue]] = None, + parent: Optional[QObject] = None) -> None: + super().__init__(parent) self._ref_namedlist = None self._roles: Tuple[str, ...] = () self._list: list = [] diff --git a/harmonyqml/backend/model/list_model_map.py b/harmonyqml/backend/model/list_model_map.py index 4528e3e4..51322bc9 100644 --- a/harmonyqml/backend/model/list_model_map.py +++ b/harmonyqml/backend/model/list_model_map.py @@ -8,7 +8,10 @@ from .list_model import ListModel class ListModelMap(QObject): def __init__(self) -> None: super().__init__() - self.dict: DefaultDict[Any, ListModel] = DefaultDict(ListModel) + + # Set the parent to prevent item garbage-collection on the C++ side + self.dict: DefaultDict[Any, ListModel] = \ + DefaultDict(lambda: ListModel(parent=self)) @pyqtSlot(str, result="QVariant") @@ -21,6 +24,7 @@ class ListModelMap(QObject): def __setitem__(self, key, value: ListModel) -> None: + value.setParent(self) self.dict[key] = value