There is a standard way of representing data for use in QAbstractItemModels
, in which there is a separate data item class that stores data about an item, and its position in the model.
The simpletreemodel example (in Python) illustrates a pretty standard way of doing this, where the data is stored in a TreeItem
that is initialized with:
class TreeItem(object):
def __init__(self, data, parent=None):
self.parentItem = parent
self.itemData = data
self.childItems = []
Note that each TreeItem
instance contains its relevant item-specific data (self.itemData), but also has a list of its child items (which are TreeItems
themselves), as well as its parent item (also a TreeItem
) as attributes.
Why is this not a really inefficient use of memory? Let's focus on item B in the following tree diagram:
A
|
|--B
| |--C
| |
| |--D
|
|-E
Naively, it seems B's data will be stored four times once the full data tree is constructed. It will be returned by A.childItems[0]
, C.parentItem
, D.parentItem
, and of course B.itemData
.
Is there some Python magic under the hood that makes this not be an inefficient use of memory?
Note: even though these types of data containers are used a lot when QAbstract*Model
is subclassed, these containers themselves actually contain no Qt (no Qt classes are being subclassed in the code for TreeItem
). So this is really an elementary Python question, not a Qt question.
Possibly Relevant Post