简体   繁体   中英

Reading a QML array property from C++

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)

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM