Reputation: 1
I want to send QVariantMap
to QML from cpp using QPROPERTY. I am able to send it. But I am not able to access the QVariantMap
key or Value in QML. I am not getting the way to access using object of cpp class.
Also I am trying to set model for listview using this QVariantMap
.
I am able to do with QVariantList
and I can access data through "modelData".
When I try to access the QVariantMap
data through "modelData", I am not getting anything.
Upvotes: 0
Views: 4959
Reputation: 2969
As @ManuelH commented, the relevant documentation is located here
Here is how you expose your QVariantMap
instance to your QML:
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QVariantMap>
#include <QQmlContext>
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
QVariantList bazList = { "hello", "world!" };
QVariantMap variantMap;
variantMap["foo"] = "bar";
variantMap["num"] = 42;
variantMap["baz"] = bazList;
QQmlApplicationEngine engine;
// Exposing the QVariantMap in the QML engine root context
engine.rootContext()->setContextProperty("variantMap", variantMap);
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
if (engine.rootObjects().isEmpty())
return -1;
return app.exec();
}
Here is how you access your QVariantMap
properties in your QML. As the documentation states, your map is converted as a Javascript Object. You can therefore the keys in your map as you would to access your Object properties:
import QtQuick 2.9
import QtQuick.Window 2.2
Window {
visible: true
width: 640
height: 480
Column {
width: 640
anchors.centerIn: parent
Text { text: "varianMap is of type: " + typeof(variantMap) }
Text { text: variantMap["foo"] }
Text { text: variantMap.foo }
Text { text: "Foo is of type: " + typeof(variantMap.foo) }
Text { text: variantMap["num"] }
Text { text: variantMap.num }
Text { text: "Num is of type: " + typeof(variantMap.num) }
// Accessing nested QVarianList by index
Text { text: variantMap.baz[0] }
Text { text: variantMap.baz[1] }
Repeater {
model: variantMap.baz // Using list as model
Text {
text: modelData // Using list value directly
}
Text {
text: variantMap.baz[index] // Using list value by index
}
}
}
}
Upvotes: 0