Add map items at run-time
-
I'm trying to automate a bit of logic, instead of hard-write values each time.
My application may load QML pages into aQQuickWidget
. Every page is different but has the same structure. There are someText
controls that have a unique name. They must show a value retrieved by the C++ backend class.First thoughts. I defined a
QVariantMap
where the keys are the items' names. Once the map is filled by my C++ class the QML page can show the actual values. Something like this:C++
public: Q_PROPERTY(QVariantMap data READ data NOTIFY dataChanged) QVariantMap data() const { return _mapData; } private: QVariantMap _mapData; signals: void dataChanged(); // ... QQmlContext *rootContext = ui->quickWidget->rootContext(); rootContext->setContextProperty("App", this); ui->quickWidget->setSource(QUrl(filename)); _mapData.insert("123", "Hello"); _mapData.insert("124", "Hello"); emit dataChanged();
QML
Text { id: txt123 text: App.data["123"] } Text { id: txt124 text: App.data["123"] }
Now the problem is I have different keys for each QML page. I might define a C++ slot so the QML page can tell what keys it has:
signal qmlSignal(string msg) function foo() { qmlSignal("123,124,125") }
and in C++ I can split the string and insert them as map keys.
It's ok but still I need to manually compile the list.I'm looking for an automagic way, like what the
QMap::operator[]
does. I mean, the first time the QML object try to read a value with a given key, if this is not present it should add to themapData
. Hence, every time I refresh the values I can find new keys.In C++ I know how to do this (using the
[]
operator as said) but how to do the same in QML using only theApp.data[key]
call?
Unfortunately the getter function doesn't allow me to retrieve the current key, otherwise it would be easy enough to check whether it exists.