- Qt 6.11
- Qt Widgets
- Item Views Examples
- Simple Tree Model Example
- Qt 6.11.0 Reference Documentation

# Simple Tree Model Example

The Simple Tree Model example shows how to use a hierarchical model with Qt's standard view classes.

Qt's model/view architecture provides a standard way for views to manipulate information in a data source, using an abstract model of the data to simplify and standardize the way it is accessed. Simple models represent data as a table of items, and allow views to access this data via an index-based system. More generally, models can be used to represent data in the form of a tree structure by allowing each item to act as a parent to a table of child items.

Before attempting to implement a tree model, it is worth considering whether the data is supplied by an external source, or whether it is going to be maintained within the model itself. In this example, we will implement an internal structure to hold data rather than discuss how to package data from an external source.

#### Design and Concepts

The data structure that we use to represent the structure of the data takes the form of a tree built from `TreeItem` objects. Each `TreeItem` represents an item in a tree view, and contains several columns of data.

| Simple Tree Model Structure The data is stored internally in the model using `TreeItem` objects that are linked together in a pointer-based tree structure. Generally, each `TreeItem` has a parent item, and can have a number of child items. However, the root item in the tree structure has no parent item and it is never referenced outside the model. Each `TreeItem` contains information about its place in the tree structure; it can return its parent item and its row number. Having this information readily available makes implementing the model easier. Since each item in a tree view usually contains several columns of data (a title and a summary in this example), it is natural to store this information in each item. For simplicity, we will use a list of QVariant objects to store the data for each column in the item.

The use of a pointer-based tree structure means that, when passing a model index to a view, we can record the address of the corresponding item in the index (see QAbstractItemModel::createIndex()) and retrieve it later with QModelIndex::internalPointer(). This makes writing the model easier and ensures that all model indexes that refer to the same item have the same internal data pointer.

With the appropriate data structure in place, we can create a tree model with a minimal amount of extra code to supply model indexes and data to other components.

#### TreeItem Class Definition

The `TreeItem` class is defined as follows:

     class TreeItem
     {
     public:
         explicit TreeItem(QVariantList data, TreeItem *parentItem = nullptr);

         void appendChild(std::unique_ptr<TreeItem> &&child);

         TreeItem *child(int row);
         int childCount() const;
         int columnCount() const;
         QVariant data(int column) const;
         int row() const;
         TreeItem *parentItem();

     private:
         std::vector<std::unique_ptr<TreeItem>> m_childItems;
         QVariantList m_itemData;
         TreeItem *m_parentItem;
     };

The class is a basic C++ class. It does not inherit from QObject or provide signals and slots. It is used to hold a list of QVariants, containing column data, and information about its position in the tree structure. The functions provide the following features:

- The `appendChildItem()` is used to add data when the model is first constructed and is not used during normal use.
- The `child()` and `childCount()` functions allow the model to obtain information about any child items.
- Information about the number of columns associated with the item is provided by `columnCount()`, and the data in each column can be obtained with the data() function.
- The `row()` and `parent()` functions are used to obtain the item's row number and parent item.

The parent item and column data are stored in the `parentItem` and `itemData` private member variables. The `childItems` variable contains a list of pointers to the item's own child items.

#### TreeItem Class Implementation

The constructor is only used to record the item's parent and the data associated with each column.

     TreeItem::TreeItem(QVariantList data, TreeItem *parent)
         : m_itemData(std::move(data)), m_parentItem(parent)
     {}

A pointer to each of the child items belonging to this item will be stored in the `childItems` private member variable as an std::unique_ptr. When the class's destructor is called, the child items will be automatically deleted to ensure that their memory is reused:

Since each of the child items are constructed when the model is initially populated with data, the function to add child items is straightforward:

     void TreeItem::appendChild(std::unique_ptr<TreeItem> &&child)
     {
         m_childItems.push_back(std::move(child));
     }

Each item is able to return any of its child items when given a suitable row number. For example, in the above diagram, the item marked with the letter "A" corresponds to the child of the root item with `row = 0`, the "B" item is a child of the "A" item with `row = 1`, and the "C" item is a child of the root item with `row = 1`.

The `child()` function returns the child that corresponds to the specified row number in the item's list of child items:

     TreeItem *TreeItem::child(int row)
     {
         return row >= 0 && row < childCount() ? m_childItems.at(row).get() : nullptr;
     }

The number of child items held can be found with `childCount()`:

     int TreeItem::childCount() const
     {
         return int(m_childItems.size());
     }

The `TreeModel` uses this function to determine the number of rows that exist for a given parent item.

The `row()` function reports the item's location within its parent's list of items:

     int TreeItem::row() const
     {
         if (m_parentItem == nullptr)
             return 0;
         const auto it = std::find_if(m_parentItem->m_childItems.cbegin(), m_parentItem->m_childItems.cend(),
                                      [this](const std::unique_ptr<TreeItem> &treeItem) {
                                          return treeItem.get() == this;
                                      });

         if (it != m_parentItem->m_childItems.cend())
             return std::distance(m_parentItem->m_childItems.cbegin(), it);
         Q_ASSERT(false); // should not happen
         return -1;
     }

Note that, although the root item (with no parent item) is automatically assigned a row number of 0, this information is never used by the model.

The number of columns of data in the item is trivially returned by the `columnCount()` function.

     int TreeItem::columnCount() const
     {
         return int(m_itemData.count());
     }

Column data is returned by the `data()` function. We use the QList::value() convenience function which checks the bounds and returns a default-constructed QVariant in case they are violated:

     QVariant TreeItem::data(int column) const
     {
         return m_itemData.value(column);
     }

The item's parent is found with `parent()`:

     TreeItem *TreeItem::parentItem()
     {
         return m_parentItem;
     }

Note that, since the root item in the model will not have a parent, this function will return zero in that case. We need to ensure that the model handles this case correctly when we implement the `TreeModel::parent()` function.

#### TreeModel Class Definition

The `TreeModel` class is defined as follows:

     class TreeModel : public QAbstractItemModel
     {
         Q_OBJECT

     public:
         Q_DISABLE_COPY_MOVE(TreeModel)

         explicit TreeModel(const QString &data, QObject *parent = nullptr);
         ~TreeModel() override;

         QVariant data(const QModelIndex &index, int role) const override;
         Qt::ItemFlags flags(const QModelIndex &index) const override;
         QVariant headerData(int section, Qt::Orientation orientation,
                             int role = Qt::DisplayRole) const override;
         QModelIndex index(int row, int column,
                           const QModelIndex &parent = {}) const override;
         QModelIndex parent(const QModelIndex &index) const override;
         int rowCount(const QModelIndex &parent = {}) const override;
         int columnCount(const QModelIndex &parent = {}) const override;

     private:
         static void setupModelData(const QList<QStringView> &lines, TreeItem *parent);

         std::unique_ptr<TreeItem> rootItem;
     };

This class is similar to most other subclasses of QAbstractItemModel that provide read-only models. Only the form of the constructor and the `setupModelData()` function are specific to this model. In addition, we provide a destructor to clean up when the model is destroyed.

#### TreeModel Class Implementation

For simplicity, the model does not allow its data to be edited. As a result, the constructor takes an argument containing the data that the model will share with views and delegates:

     TreeModel::TreeModel(const QString &data, QObject *parent)
         : QAbstractItemModel(parent)
         , rootItem(std::make_unique<TreeItem>(QVariantList{tr("Title"), tr("Summary")}))
     {
         setupModelData(QStringView{data}.split(u'\n'), rootItem.get());
     }

It is up to the constructor to create a root item for the model. This item only contains vertical header data for convenience. We also use it to reference the internal data structure that contains the model data, and it is used to represent an imaginary parent of top-level items in the model. The root item is managed with a std::unique_ptr to ensure the entire tree of item is deleted when the model is deleted.

The model's internal data structure is populated with items by the `setupModelData()` function. We will examine this function separately at the end of this document.

The destructor ensures that the root item and all of its descendants are deleted when the model is destroyed. This is done automatically since the root item is stored in a unique_ptr.

     TreeModel::~TreeModel() = default;

Since we cannot add data to the model after it is constructed and set up, this simplifies the way that the internal tree of items is managed.

Models must implement an `index()` function to provide indexes for views and delegates to use when accessing data. Indexes are created for other components when they are referenced by their row and column numbers, and their parent model index. If an invalid model index is specified as the parent, it is up to the model to return an index that corresponds to a top-level item in the model.

When supplied with a model index, we first check whether it is valid. If it is not, we assume that a top-level item is being referred to; otherwise, we obtain the data pointer from the model index with its internalPointer() function and use it to reference a `TreeItem` object. Note that all the model indexes that we construct will contain a pointer to an existing `TreeItem`, so we can guarantee that any valid model indexes that we receive will contain a valid data pointer.

     QModelIndex TreeModel::index(int row, int column, const QModelIndex &parent) const
     {
         if (!hasIndex(row, column, parent))
             return {};

         TreeItem *parentItem = parent.isValid()
             ? static_cast<TreeItem*>(parent.internalPointer())
             : rootItem.get();

         if (auto *childItem = parentItem->child(row))
             return createIndex(row, column, childItem);
         return {};
     }

Since the row and column arguments to this function refer to a child item of the corresponding parent item, we obtain the item using the `TreeItem::child()` function. The createIndex() function is used to create a model index to be returned. We specify the row and column numbers, and a pointer to the item itself. The model index can be used later to obtain the item's data.

The way that the `TreeItem` objects are defined makes writing the `parent()` function easy:

     QModelIndex TreeModel::parent(const QModelIndex &index) const
     {
         if (!index.isValid())
             return {};

         auto *childItem = static_cast<TreeItem*>(index.internalPointer());
         TreeItem *parentItem = childItem->parentItem();

         return parentItem != rootItem.get()
             ? createIndex(parentItem->row(), 0, parentItem) : QModelIndex{};
     }

We only need to ensure that we never return a model index corresponding to the root item. To be consistent with the way that the `index()` function is implemented, we return an invalid model index for the parent of any top-level items in the model.

When creating a model index to return, we must specify the row and column numbers of the parent item within its own parent. We can easily discover the row number with the `TreeItem::row()` function, but we follow a convention of specifying 0 as the column number of the parent. The model index is created with createIndex() in the same way as in the `index()` function.

The `rowCount()` function simply returns the number of child items for the `TreeItem` that corresponds to a given model index, or the number of top-level items if an invalid index is specified:

     int TreeModel::rowCount(const QModelIndex &parent) const
     {
         if (parent.column() > 0)
             return 0;

         const TreeItem *parentItem = parent.isValid()
             ? static_cast<const TreeItem*>(parent.internalPointer())
             : rootItem.get();

         return parentItem->childCount();
     }

Since each item manages its own column data, the `columnCount()` function has to call the item's own `columnCount()` function to determine how many columns are present for a given model index. As with the `rowCount()` function, if an invalid model index is specified, the number of columns returned is determined from the root item:

     int TreeModel::columnCount(const QModelIndex &parent) const
     {
         if (parent.isValid())
             return static_cast<TreeItem*>(parent.internalPointer())->columnCount();
         return rootItem->columnCount();
     }

Data is obtained from the model via `data()`. Since the item manages its own columns, we need to use the column number to retrieve the data with the `TreeItem::data()` function:

     QVariant TreeModel::data(const QModelIndex &index, int role) const
     {
         if (!index.isValid() || role != Qt::DisplayRole)
             return {};

         const auto *item = static_cast<const TreeItem*>(index.internalPointer());
         return item->data(index.column());
     }

Note that we only support the DisplayRole in this implementation, and we also return invalid QVariant objects for invalid model indexes.

We use the `flags()` function to ensure that views know that the model is read-only:

     Qt::ItemFlags TreeModel::flags(const QModelIndex &index) const
     {
         return index.isValid()
             ? QAbstractItemModel::flags(index) : Qt::ItemFlags(Qt::NoItemFlags);
     }

The `headerData()` function returns data that we conveniently stored in the root item:

     QVariant TreeModel::headerData(int section, Qt::Orientation orientation,
                                    int role) const
     {
         return orientation == Qt::Horizontal && role == Qt::DisplayRole
             ? rootItem->data(section) : QVariant{};
     }

This information could have been supplied in a different way: either specified in the constructor, or hard coded into the `headerData()` function.

#### Setting Up the Data in the Model

We use the `setupModelData()` function to set up the initial data in the model. This function parses a text file, extracting strings of text to use in the model, and creates item objects that record both the data and the overall model structure. Naturally, this function works in a way that is very specific to this model. We provide the following description of its behavior, and refer the reader to the example code itself for more information.

We begin with a text file in the following format:

     Getting Started                         How to familiarize yourself with Qt Widgets Designer
         Launching Designer                  Running the Qt Widgets Designer application
         The User Interface                  How to interact with Qt Widgets Designer
         ...

     Connection Editing Mode                 Connecting widgets together with signals and slots
         Connecting Objects                  Making connections in Qt Widgets Designer
         Editing Connections                 Changing existing connections

We process the text file with the following two rules:

- For each pair of strings on each line, create an item (or node) in a tree structure, and place each string in a column of data in the item.
- When the first string on a line is indented with respect to the first string on the previous line, make the item a child of the previous item created.

To ensure that the model works correctly, it is only necessary to create instances of `TreeItem` with the correct data and parent item.

#### Testing the model

Correctly implementing an item model can be challenging. The class QAbstractItemModelTester from the Qt Test module checks for model consistency, like the model index creation and parent-child relationships.

You can test your model by just passing a model instance to the class constructor, for instance as part of a Qt unit test:

     class TestSimpleTreeModel : public QObject
     {
         Q_OBJECT

     private slots:
         void testTreeModel();
     };

     void TestSimpleTreeModel::testTreeModel()
     {
         constexpr auto fileName = ":/default.txt"_L1;
         QFile file(fileName);
         QVERIFY2(file.open(QIODevice::ReadOnly | QIODevice::Text),
                  qPrintable(fileName + " cannot be opened: "_L1 + file.errorString()));
         TreeModel model(QString::fromUtf8(file.readAll()));

         QAbstractItemModelTester tester(&model);
     }

     QTEST_APPLESS_MAIN(TestSimpleTreeModel)

     #include "test.moc"

To create a test which can be run using the `ctest` executable, `add_test()` is used:

     # Unit Test

     include(CTest)

     qt_add_executable(simpletreemodel_tester
         test.cpp
         treeitem.cpp treeitem.h
         treemodel.cpp treemodel.h)

     target_link_libraries(simpletreemodel_tester PRIVATE
         Qt6::Core
         Qt6::Test
     )

     if(ANDROID)
         target_link_libraries(simpletreemodel_tester PRIVATE
             Qt6::Gui
         )
     endif()

     qt_add_resources(simpletreemodel_tester "simpletreemodel_tester"
         PREFIX
             "/"
         FILES
             ${simpletreemodel_resource_files}
     )

     add_test(NAME simpletreemodel_tester
              COMMAND simpletreemodel_tester)

Example project @ code.qt.io