Important: Please read the Qt Code of Conduct -

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 a QQuickWidget. Every page is different but has the same structure. There are some Text 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:


        Q_PROPERTY(QVariantMap data READ data NOTIFY dataChanged)
        QVariantMap data() const { return _mapData; }
        QVariantMap _mapData;
        void dataChanged();
    // ...
        QQmlContext *rootContext = ui->quickWidget->rootContext();
        rootContext->setContextProperty("App", this);
        _mapData.insert("123", "Hello");
        _mapData.insert("124", "Hello");
        emit dataChanged();


    Text {
        id: txt123
    Text {
        id: txt124

    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()

    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 the mapData. 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 the[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.

Log in to reply