How to expose QMap to QML using QDeclarative
Asked Answered
I

1

7

How can I expose QMap from C++ to QML? Using QList I can use QDeclarativeListProperty.

Illuminator answered 23/2, 2012 at 15:17 Comment(0)
L
6

You could convert or change it into a QVariantMap. In QML you can use the QVariantMap instance as a normal Javascript object.

class MyClass : public QObject {
Q_OBJECT
public:
    Q_INVOKABLE QVariantMap getIntMap() {
        QVariantMap rval;
        foreach (QString key, m_intMap.keys()) {
            // int has an implicit conversion to QVariant
            rval[key] = m_intMap[key]; 
        }
        return rval;
    }

    Q_INVOKABLE QVariantMap getObjMap() {
        QVariantMap rval;
        foreach (QString key, m_objMap.keys()) {
            // TODO: make sure all QObject subclasses are exported to QML
            rval[key] = QVariant::fromValue<QObject*>(m_objMap[key]); 
        }
        return rval;
    }

private:
    QMap<QString, int> m_intMap;
    QMap<QString, QObject*> m_objMap;
}
Loireatlantique answered 23/2, 2012 at 21:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.