title: C++ model for QML TreeView
body: <p>Due to lack of any other Qt demo, I am making use of Qt widgets's <code>SimpleTreeModel</code>demo to implement C++ model for my QML TreeView. I have defined roles so QML can use it but I am having trouble connecting them with actual model data. </p>
  
  <p><del>What I also find interesting is that widgets (C++) demo works fine but <code>TreeModel</code>doesn't seem to store the data as its member variable..leaves me scratching my head.</del> I figured this out, every TreeItem store all its child items and TreeModel has only one <code>rootItem</code> which in turn stores all data as its child.</p>
  
  <p>The TreeItem class</p>
  
  <pre><code>class TreeItem
  {
  public:
      explicit TreeItem(const QList&lt;QVariant&gt; &amp;data, TreeItem *parentItem = 0);
      ~TreeItem();
  
      void appendChild(TreeItem *child);
  
      TreeItem *child(int row);
      int childCount() const;
      int columnCount() const;
      QVariant data(int column) const;
      int row() const;
      TreeItem *parentItem();
  
  private:
      QList&lt;TreeItem*&gt; m_childItems;
      QList&lt;QVariant&gt; m_itemData;
      TreeItem *m_parentItem;
  };
  </code></pre>
  
  <p>The TreeModel class</p>
  
  <pre><code>class TreeModel : public QAbstractItemModel
  {
      Q_OBJECT
  
  public:
      enum DisplayRoles {
          TitleRole = Qt::UserRole + 1,
          SummaryRole
      };
  
      explicit TreeModel(const QString &amp;data, QObject *parent = 0);
      ~TreeModel();
  
      QVariant data(const QModelIndex &amp;index, int role) const Q_DECL_OVERRIDE;
      Qt::ItemFlags flags(const QModelIndex &amp;index) const Q_DECL_OVERRIDE;
      QVariant headerData(int section, Qt::Orientation orientation,
                          int role = Qt::DisplayRole) const Q_DECL_OVERRIDE;
      QModelIndex index(int row, int column,
                        const QModelIndex &amp;parent = QModelIndex()) const Q_DECL_OVERRIDE;
      QModelIndex parent(const QModelIndex &amp;index) const Q_DECL_OVERRIDE;
      int rowCount(const QModelIndex &amp;parent = QModelIndex()) const Q_DECL_OVERRIDE;
      int columnCount(const QModelIndex &amp;parent = QModelIndex()) const Q_DECL_OVERRIDE;
  
      QHash&lt;int, QByteArray&gt; TreeModel::roleNames() const {
          QHash&lt;int, QByteArray&gt; roles;
          roles[TitleRole] = "title";
          roles[SummaryRole] = "summary";
          return roles;
      }
  
  
  private:
      void setupModelData(const QStringList &amp;lines, TreeItem *parent);
  
      TreeItem *rootItem;
  };
  </code></pre>
  
  <p>The model loads the data from a <code>default.txt</code></p>
  
  <pre><code>TreeModel::TreeModel(const QString &amp;data, QObject *parent)
      : QAbstractItemModel(parent)
  {
      QList&lt;QVariant&gt; rootData;
      rootData &lt;&lt; "Title" &lt;&lt; "Summary";
      rootItem = new TreeItem(rootData);
      setupModelData(data.split(QString("\n")), rootItem);
  }
  
  void TreeModel::setupModelData(const QStringList &amp;lines, TreeItem *parent)
  {
      QList&lt;TreeItem*&gt; parents;
      QList&lt;int&gt; indentations;
      parents &lt;&lt; parent;
      indentations &lt;&lt; 0;
  
      int number = 0;
  
      while (number &lt; lines.count()) {
          int position = 0;
          while (position &lt; lines[number].length()) {
              if (lines[number].mid(position, 1) != " ")
                  break;
              position++;
          }
  
          QString lineData = lines[number].mid(position).trimmed();
  
          if (!lineData.isEmpty()) {
              // Read the column data from the rest of the line.
              QStringList columnStrings = lineData.split("\t", QString::SkipEmptyParts);
              QList&lt;QVariant&gt; columnData;
              for (int column = 0; column &lt; columnStrings.count(); ++column)
                  columnData &lt;&lt; columnStrings[column];
  
              if (position &gt; indentations.last()) {
                  // The last child of the current parent is now the new parent
                  // unless the current parent has no children.
  
                  if (parents.last()-&gt;childCount() &gt; 0) {
                      parents &lt;&lt; parents.last()-&gt;child(parents.last()-&gt;childCount()-1);
                      indentations &lt;&lt; position;
                  }
              } else {
                  while (position &lt; indentations.last() &amp;&amp; parents.count() &gt; 0) {
                      parents.pop_back();
                      indentations.pop_back();
                  }
              }
  
              // Append a new item to the current parent's list of children.
              parents.last()-&gt;appendChild(new TreeItem(columnData, parents.last()));
          }
  
          ++number;
      }
  }
  </code></pre>
  
  <p><strong>My problem is in this function, how do I connect the roles with the data which is stored in <code>rootItem</code>?</strong>. Note <code>titleString</code> and <code>summaryString</code>are possible proposed functions (if needed) but I don't know what to write in them get access the data!</p>
  
  <pre><code>QVariant TreeModel::data(const QModelIndex &amp;index, int role) const
  {
      if (!index.isValid())
          return QVariant();
  
      if (index.isValid() &amp;&amp; role &gt;= TitleRole) {
          switch (role) {
          case TitleRole:
              return QVariant(titleString(rootItem(index))); // get title through rootItem?
          case SummaryRole:
              return QVariant(summaryString(rootItem(index))); // get summary through rootItem?
          }
      }
  
      if (role != Qt::DisplayRole)
          return QVariant();
  
      TreeItem *item = static_cast&lt;TreeItem*&gt;(index.internalPointer());
  
      return item-&gt;data(index.column());
  }
  </code></pre>
  
  <p>The <code>default.txt</code>has the following data but the same is available in the Qt Creator demo itself as well.</p>
  
  <pre><code>Getting Started             How to familiarize yourself with Qt Designer
      Launching Designer          Running the Qt Designer application
      The User Interface          How to interact with Qt Designer
  
  Designing a Component           Creating a GUI for your application
      Creating a Dialog           How to create a dialog
      Composing the Dialog        Putting widgets into the dialog example
      Creating a Layout           Arranging widgets on a form
      Signal and Slot Connections     Making widget communicate with each other
  
  Using a Component in Your Application   Generating code from forms
      The Direct Approach         Using a form without any adjustments
      The Single Inheritance Approach Subclassing a form's base class
      The Multiple Inheritance Approach   Subclassing the form itself
      Automatic Connections       Connecting widgets using a naming scheme
          A Dialog Without Auto-Connect   How to connect widgets without a naming scheme
          A Dialog With Auto-Connect  Using automatic connections
  
  Form Editing Mode           How to edit a form in Qt Designer
      Managing Forms          Loading and saving forms
      Editing a Form          Basic editing techniques
      The Property Editor         Changing widget properties
      The Object Inspector        Examining the hierarchy of objects on a form
      Layouts             Objects that arrange widgets on a form
          Applying and Breaking Layouts   Managing widgets in layouts 
          Horizontal and Vertical Layouts Standard row and column layouts
          The Grid Layout         Arranging widgets in a matrix
      Previewing Forms            Checking that the design works
  
  Using Containers            How to group widgets together
      General Features            Common container features
      Frames              QFrame
      Group Boxes             QGroupBox
      Stacked Widgets         QStackedWidget
      Tab Widgets             QTabWidget
      Toolbox Widgets         QToolBox
  
  Connection Editing Mode         Connecting widgets together with signals and slots
      Connecting Objects          Making connections in Qt Designer
      Editing Connections         Changing existing connections
  </code></pre>
  
  <p>My output shows the same number of lines as in widgets demo except that there is no text. It seems like it is just not connected to the roles properly or roles are not connected to day. I am attaching the screen shot of my output.</p>
  
  <p><a href="https://i.stack.imgur.com/DIDxl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DIDxl.png" alt="enter image description here"></a></p>