How does one change the model property of a TableView in qml from c++
<p>I am relatively new to QT, so any help would be greatly appreciated!</p>

<p>I am working on a Qt Quick Application, making use of the QQmlApplicationEngine for the UI. I made a subclass of QAbstractTableModel and implemented the necessary functions and successfully created and displayed a (singular) table on the Window. </p>

<p>Currently, how I linked the model in the QML file is by setting the <em>context property</em> of the <em>root property</em> of QQmlApplicationEngine. </p>

<p><strong><em>main.cpp</em></strong></p>

<pre><code>#include &lt;QGuiApplication&gt;
#include &lt;QQmlApplicationEngine&gt;
#include &lt;QSharedPointer&gt;
#include &lt;QQmlContext&gt;

#include "tablecontroller.h"

int main(int argc, char *argv[])
{
  QGuiApplication app(argc, argv);

  QSharedPointer&lt;QQmlApplicationEngine&gt; engine = 
                     QSharedPointer&lt;QQmlApplicationEngine&gt;::create();

  TableController theController(engine.toWeakRef());

  engine.data()-&gt;rootContext()-&gt;setContextProperty("TableController", &amp;theController);

  engine.data()-&gt;load(QUrl(QStringLiteral("qrc:/main.qml")));
  return app.exec();
}
</code></pre>

<p><strong><em>tabcontroller.h</em></strong></p>

<pre><code>#ifndef TABLECONTROLLER_H
#define TABLECONTROLLER_H

#include &lt;QObject&gt;
#include &lt;QQmlApplicationEngine&gt;
#include &lt;QWeakPointer&gt;
#include &lt;QHash&gt;
#include &lt;QList&gt;

#include "tablemodel.h"

class TableController : public QObject
{
  Q_OBJECT
public:
    explicit TableController(QWeakPointer&lt;QQmlApplicationEngine&gt; Engine, QObject *parent = 0);

    Q_INVOKABLE void AddEntry();

signals:

public slots:

private:
  TE::TDT::TableModel m_TableModel;
  QList&lt;QString&gt; m_Headings;
};

#endif // TABLECONTROLLER_H
</code></pre>

<p><strong><em>tabcontroller.cpp</em></strong></p>

<pre><code>#include "tablecontroller.h"
#include &lt;QQmlContext&gt;

TableController::TableController(QWeakPointer&lt;QQmlApplicationEngine&gt; Engine, QObject *parent) : QObject(parent)
{
  m_Headings &lt;&lt; "Heading1" &lt;&lt; "Heading2" &lt;&lt; "Heading3" &lt;&lt; "Heading4";
  m_TableModel.setColumnHeadings(m_Headings);

  Engine.data()-&gt;rootContext()-&gt;setContextProperty("myModel", &amp;m_TableModel);
}

void TableController::AddEntry()
{
  QHash&lt;QString, QVariant&gt; tempHash;
  int counter = 1;
  for (auto x : m_Headings)
  {
    tempHash.insert(x, QString::number(counter));
    counter++;
  }
  m_TableModel.addElement(tempHash);
}
</code></pre>

<p><strong><em>tablemodel.h</em></strong></p>

<pre><code>#ifndef TABLEMODEL_H
#define TABLEMODEL_H

#include &lt;QObject&gt;
#include &lt;QAbstractItemModel&gt;
#include &lt;QModelIndex&gt;
#include &lt;QVariant&gt;
#include &lt;QList&gt;
#include &lt;QString&gt;
#include &lt;QHash&gt;

namespace TE {

namespace TDT {

class TableModel : public QAbstractTableModel
{
  Q_OBJECT
  Q_PROPERTY(QStringList userRoleNames READ userRoleNames CONSTANT)
public:
    explicit TableModel(QObject *parent = 0);

    enum MyModelRoles {
        UserRole1 = Qt::UserRole + 1,
        UserRole2,
    };

  void setFirstColumn(const QList&lt;QString&gt; &amp;FirstColumn);

  void setColumnHeadings(const QList&lt;QString&gt; &amp;ColumnHeadings);

  void addElement(const QHash&lt;QString, QVariant&gt; Entry);

  QStringList userRoleNames();

signals:

public slots:

// QAbstractTableModel interface
public:
  int rowCount(const QModelIndex &amp;parent) const override;
  int columnCount(const QModelIndex &amp;parent) const override;
  QVariant data(const QModelIndex &amp;index, int role) const override;
  QVariant headerData(int section, Qt::Orientation orientation, int role) const override;
  QHash&lt;int, QByteArray&gt; roleNames() const override;

private:
  QList&lt;QHash&lt;QString, QVariant&gt;&gt; m_TableData;
  QList&lt;QString&gt; m_ColumnHeadings;
  QMap&lt;int, QString&gt; m_roleNames;

};

}// TDT

}// TE

#endif // TABLEMODEL_H
</code></pre>

<p><strong><em>tablemodel.cpp</em></strong></p>

<pre><code>#include "tablemodel.h"
#include &lt;QDebug&gt;
#include &lt;QAbstractListModel&gt;

TE::TDT::TableModel::TableModel(QObject *parent) : QAbstractTableModel(parent)
{

}

int TE::TDT::TableModel::rowCount(const QModelIndex &amp;parent) const
{
  Q_UNUSED(parent);
  return m_TableData.count();
}

int TE::TDT::TableModel::columnCount(const QModelIndex &amp;parent) const
{
  Q_UNUSED(parent);
  return m_ColumnHeadings.count();
}

QVariant TE::TDT::TableModel::data(const QModelIndex &amp;index, int role) const
{
  QVariant retVal;
  try {
     if(!index.isValid())
     {
         throw QString("Invalid index for inherited data function");
     }
     // Check row index
     if(index.row() &gt;= m_TableData.count() || index.row() &lt; 0)
     {
         throw QString("Index (row) out of bounds for data function");
     }
     //Check column index
     if(index.column() &gt;= m_ColumnHeadings.count() || index.column() &lt; 0)
     {
         throw QString("Index (column) out of bounds for data function");
     }

     QList&lt;int&gt; keys = m_roleNames.keys();

     if(role == Qt::DisplayRole || role == Qt::EditRole)
     {
         QString colKey = m_ColumnHeadings.at(index.column());
         if (m_TableData.at(index.row()).value(colKey).isNull())
         {
             retVal = QVariant();
         } else {
             retVal = m_TableData.at(index.row()).value(colKey);
         }
     } else if (m_roleNames.keys().contains(role)) {
         QHash&lt;QString, QVariant&gt; temp1 = m_TableData.at(index.row());
         retVal = m_TableData.at(index.row()).value(m_roleNames.value(role));
     }
     return retVal;

  } catch (QString &amp;e) {
     qDebug() &lt;&lt; e;
     return QVariant();
  }
}

QVariant TE::TDT::TableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
  Q_UNUSED(orientation);
  QVariant retVal;
  if (role == Qt::DisplayRole)
  {
     retVal = m_ColumnHeadings.at(section);
  }
  return retVal;
}

QHash&lt;int, QByteArray&gt; TE::TDT::TableModel::roleNames() const {
  // Populate the roles - basically the column headings
  QHash&lt;int, QByteArray&gt; roles = QAbstractTableModel::roleNames();

  // Should not overwrite existing roles
  int LastIndexOfUserRole = Qt::UserRole;
  for (int x = 1; x &lt;= m_ColumnHeadings.count(); x++)
  {
     roles[LastIndexOfUserRole + x] = m_ColumnHeadings.at(x-1).toUtf8();
  }
  return roles;
}

QStringList TE::TDT::TableModel::userRoleNames() // Return ordered List of user-defined roles
{
  QHashIterator&lt;int, QByteArray&gt; i(roleNames());
  while (i.hasNext())
  {
     i.next();
     if(i.key() &gt; Qt::UserRole)
     {
         m_roleNames[i.key()] = i.value();
     }
  }
  return m_roleNames.values();
}

void TE::TDT::TableModel::setColumnHeadings(const QList&lt;QString&gt; &amp;ColumnHeadings)
{
  m_ColumnHeadings = ColumnHeadings;
}

void TE::TDT::TableModel::addElement(const QHash&lt;QString, QVariant&gt; Entry)
{
   beginInsertRows(QModelIndex(), this-&gt;rowCount(QModelIndex()), this-&gt;rowCount(QModelIndex()));
   m_TableData.append(Entry);
   endInsertRows();
}
</code></pre>

<p><strong><em>main.qml</em></strong>
    import QtQuick 2.5
    import QtQuick.Window 2.2
    import QtQuick.Controls 1.2</p>

<pre><code>Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")
    id: mainwindow

    // template component for the column headings
    Component
    {
        id: columnComponent
        TableViewColumn{width: 100 }
    }

    TableView {
        id: tableview
        height: mainwindow.height - 50
        width: mainwindow.width
        y: 5
        x: 0
        visible: true
        resources:
        {
            var roleList = myModel.userRoleNames
            var temp = []
            for(var i = 0; i &lt; roleList.length; i++)
            {
                var role  = roleList[i]
                temp.push(columnComponent.createObject(tableview, { "role": role, "title": role}))
            }
            return temp
        }
        model: myModel
    }

    Rectangle {
        id: abutton
        anchors.top: tableview.bottom
        height: 40
        width: mainwindow.width

        Text {
            text: "Click to Add"
            anchors.fill: parent
        }

        MouseArea {
            anchors.fill: parent
            onClicked: {
                TableController.AddEntry()
            }
        }
    }
}
</code></pre>

<p>Code adapted from:
<a href="https://stackoverflow.com/questions/27230818/qml-tableview-with-dynamic-number-of-columns">QML TableView with dynamic number of columns</a></p>

<p>Now, my question is, if I wanted to re-use the TableView as that defined in the <strong><em>main.qml</em></strong> I want to use another <em>model</em> for it. The problem is (from my limited understanding) that the "variable" that the model in the QML links to is static (defined at start-up), in this case, "myModel". </p>

<p>How can I change the model once I create another <em>instance</em> of this TableView? Will I have to link another "variable" every time?</p>

<p>I have tried to cast the TableView (in QML) to a QQuickItem (in c++) and trying to set the property there, to no avail (gives a null, but also QQuickItem doesn't have a "setModel" function) </p>

<p>Sorry for the long post, wanted to give as much information as possible.</p>