2

Given QML such as:

Item {
  objectName: "myitem"
  property var myarr: [1,2,3]
}

How can it be read from C++?

The following doesn't work:

QObject* item = root->findChild<QObject*>("myitem");
QVariant value = item->property("myarr");

While value.isValid() returns true, if I query QMetaType::typeName( QMetaType::Type(int(value.type())) ) it yields "QWidget*".

(Using Qt 5.9.4 on x86)

1 Answer 1

1

This returns a list of QVariant since it is the most generic type, in the next example I unpack it and store it in a container:

if(QObject *item = root->findChild<QObject *>("myitem")){
    std::vector<int> vector; // another option std::vector<float>;
    for(const QVariant & v: item->property("myarr").toList()){
       vector.push_back(v.toInt()); // another option toFloat();
    }
    qDebug() << vector;
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. On a related note - any clue how to detect if the property is a list or something else (e.g. a map)? If I call value.canConvert(QMetaType::Type::QVariantList) it returns true, but so does canConvert(QMetaType::Type::QVariantMap))
@DavidJ I do not prefer to obtain data from QML to C ++, that method always brings compatibility problems, instead I create a QObject that has qproperties that manage the business logic and export it using setContextProperty. The problem you have had now is not dangerous but for example QML creates and removes elements dynamically and say you get the item but QML deletes it so the pointer will point to non-reserved memory. I recommend you read: doc.qt.io/qt-5/…
That isn't possible in this instance as the properties belong to dynamically created & loaded QML generated from cross-translation from another declarative markup language.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.