QML / QT无法将C ++中的QList <qvariantmap>转换为javascript中的对象数组

时间:2017-03-12 14:12:35

标签: javascript c++ qt qml

QML / QT无法将C ++中的QList转换为javascript中的对象数组。

class ParamListModel:QAbstractListModel
{
     Q_OBJECT
     QList<QVariantMap> paramMapObjList;
     // ...
 public:
     // paramMapObjList can not be converted to an array 
     // of objects in  javascript 
     // so I have to use this method:
     // the returned QVariantMap will be converted to javascript object
     // by QML automatically.
     Q_INVOKABLE QVariantMap getParamObj(int index); 
     // ...
}

有更好的方法吗?

1 个答案:

答案 0 :(得分:1)

我不确定QML是否理解QVariantMap的QList,但它确实理解QVariant。我通常像这样嵌套QVariantMap数据,以便在ListView项目中使用它:

#include <stdio.h>   
#include <stdlib.h>

FILE *IN, *OUT;

int main(int argc, char* argv[])
{
    if (argc < 2) 
    {
        printf("Error: missing command line arguments!\n");
        return 1;
    }

    printf("Enter the name of the file with the input data: ");
    scanf("%s", argv[1]);

    printf("\nEnter the name of the file for the output data: ");
    scanf("%s", argv[2]);

    IN = fopen(argv[1], "r");
    OUT = fopen(argv[2], "w");  

    fclose(IN);
    fclose(OUT);

    return 0;
}

然后你就可以得到这样的Q_PROPERTY:

QVariant MyClass::myListModel()
{
    QVariantList vList;

    for(Group *grp : groups())
    {
        QVariantMap vMap;
        vMap.insert("mIcon", "qrc:/icon.svg");
        vMap.insert("mLabel", grp->name());
        vMap.insert("mValue", grp->id());
        vList.append(vMap);
    }

    return QVariant::fromValue(vList);
}