It should work, but without seeing your model, it's hard to say what's going wrong. This works for me:
#include <QAbstractItemModel>
#include <QStandardItemModel>
#include <QApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
class ModelManager : public QObject
{
Q_OBJECT
public:
ModelManager() {
QStandardItemModel *model1 = new QStandardItemModel(4, 1, this);
for (int row = 0; row < 4; ++row) {
QStandardItem *item = new QStandardItem(QString("model1 row %0, column 0").arg(row));
model1->setItem(row, 0, item);
}
mModels.insert("model1", model1);
QStandardItemModel *model2 = new QStandardItemModel(4, 1, this);
for (int row = 0; row < 4; ++row) {
QStandardItem *item = new QStandardItem(QString("model2 row %0, column 0").arg(row));
model2->setItem(row, 0, item);
}
mModels.insert("model2", model2);
}
Q_INVOKABLE QObject *getModel(const QString &modelName) {
return mModels.value(modelName);
}
Q_INVOKABLE void changeStuff() {
QStandardItemModel *model = static_cast<QStandardItemModel*>(mModels.value("model1"));
QStandardItem *item = model->item(0, 0);
item->setText("model1 row 0 column 0 - changed");
}
private:
QHash<QString, QAbstractItemModel*> mModels;
};
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
ModelManager modelManager;
qRegisterMetaType<QAbstractItemModel*>();
QQmlApplicationEngine engine;
engine.rootContext()->setContextProperty("modelManager", &modelManager);
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
return app.exec();
}
#include "main.moc"
QML:
import QtQuick 2.4
import QtQuick.Controls 1.3
import QtQuick.Window 2.2
import QtQuick.Dialogs 1.2
ApplicationWindow {
title: qsTr("Hello World")
width: 640
height: 480
visible: true
ComboBox {
id: comboBox
model: ["model1", "model2"]
}
ListView {
id: listView
width: 200
height: 200
anchors.centerIn: parent
model: modelManager.getModel(comboBox.currentText)
delegate: Rectangle {
width: listView.width
height: text.implicitHeight
Text {
id: text
anchors.centerIn: parent
text: display
}
}
}
Button {
text: "Change stuff"
anchors.horizontalCenter: listView.horizontalCenter
onClicked: modelManager.changeStuff()
}
}