QML : How to read a QList from C++



  • I'm trying to pass QList of integer from QML to C++ code, but somehow my approach is not working.

    Any inputs to solve the problem is highly appreciated.

    Below is my code snippet

    @Header file

    Q_PROPERTY(QDeclarativeListProperty<int> enableKey READ enableKey) 
    
    QDeclarativeListProperty<int> enableKey(); //function declaration
    QList<int> m_enableKeys;
    

    cpp file

    QDeclarativeListProperty<int> KeyboardContainer::enableKey()
    {
    return QDeclarativeListProperty<int>(this, 0, &KeyboardContainer::append_list);
    }

    void KeyboardContainer::append_list(QDeclarativeListProperty<int> *list, int *key)
    {
    int *ptrKey = qobject_cast<int *>(list->object);
    if (ptrKey) {
    key->setParentItem(ptrKey);
    ptrKey->m_enableKeys.append(key);
    }
    }@



  • QDeclarativeListProperty is not what you think it is. Don't use it.

    If you were using QtQuick2, you could simply use QList<int> but in QtQuick1 you're basically out of luck. One terrible hack is to use a QVariantMap and insert(index, value). But it will be exposed in JS as an object, not an array.

    Cheers,
    Chris.



  • Thanks for the reply :)



  • For your specific case a better work around could be to just expose an append(int) function to QML directly and iterate over the JS array contents in QML.

    [quote author="chrisadams" date="1355987161"]QDeclarativeListProperty is not what you think it is. Don't use it.
    [/quote]

    To be a little more helpful, QDeclarativeListProperty is only for lists of QObject* or pointers to QObject derived types. Not for primitive types.

    Also QList<int> works fine for exporting lists from C++ to QML, better than QVariantMap. But it won't work as you'd expect for assigning to it in QML.



  • The discussion really gave me better insight to the concepts :)


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.