I have a QML TreeView
that gets data through a QStandardItemModel
. When the application is running, I press a button which adds a new entry. I know the data is changing, but the QML TreeView
is not updating. I've also tried beginResetModel()
and endResetModel()
. The data is correctly displayed in the TreeView
upon loading the application, but the TreeView
does not change when modifying the data in the model.
treeviewmodel.cpp
#include <QDebug>
#include <QStandardItemModel>
#include "treeviewmodel.h"
TreeViewModel::TreeViewModel(QObject *parent) :
QStandardItemModel(parent)
{
m_roleNameMapping[TreeViewModel_Role_Name] = "name_role";
QStandardItem* entry;
entry = new QStandardItem(QString("my_entry"));
entry->setData("abc", TreeViewModel_Role_Name);
auto childEntry = new QStandardItem( "my_child_entry" );
childEntry->setData( "def",TreeViewModel_Role_Name);
entry->appendRow(childEntry);
appendRow( entry );
}
TreeViewModel& TreeViewModel::Instance()
{
static TreeViewModel instance; //Guaranteed to be destroyed
return instance;
}
void TreeViewModel::addEntry()
{
qDebug () << "Adding entry...";
QStandardItem* entry;
entry = new QStandardItem(QString("my_entry"));
entry->setData("Second Entry", TreeViewModel_Role_Name);
auto childEntry = new QStandardItem( "my_child_entry" );
childEntry->setData( "Second Entry Child",TreeViewModel_Role_Name);
entry->appendRow(childEntry);
appendRow( entry );
qDebug () << rowCount(); //Increases everytime I call the function
//Data is being added
}
QHash<int, QByteArray> TreeViewModel::roleNames() const
{
return m_roleNameMapping;
}
main.qml
import treeModel 1.0
...
MyTreeModel {
id: theModel
}
//Left Tree View
Rectangle {
id: leftView
Layout.minimumWidth: 50
width: 200
//Layout.fillWidth: true
color: "white"
TreeView {
id: treeView
anchors.fill: parent
model: theModel
TableViewColumn {
role: "name_role"
title: "Name"
}
TableViewColumn {
role: "description_role"
title: "Description"
}
}
}
ToolButton {
iconSource: "lock.png"
onClicked: {
treeviewmodel.addEntry()
}
}
main.cpp
QQmlContext* treeViewModelCtx = engine.rootContext();
treeViewModelCtx->setContextProperty("treeviewmodel", &TreeViewModel::Instance());
//Register types
qmlRegisterType<TreeViewModel>("treeModel", 1, 0, "MyTreeModel" );