简体   繁体   English

从 C++ 读取 QML 数组属性

[英]Reading a QML array property from C++

Given QML such as:给定 QML,例如:

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

How can it be read from C++?如何从 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*".虽然value.isValid()返回 true,但如果我查询QMetaType::typeName( QMetaType::Type(int(value.type())) )它会产生“QWidget*”。

(Using Qt 5.9.4 on x86) (在 x86 上使用 Qt 5.9.4)

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:这将返回一个 QVariant 列表,因为它是最通用的类​​型,在下一个示例中,我将其解压缩并将其存储在容器中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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