[英]Sending a list of javascript objects from QML to c++
我有一个从QML文件调用的可调用c ++函数。 我希望此函数接受javascript对象(或地图)列表作为参数。 Qt文档指出javascript列表已转换为QVariantList,而javascript对象已转换为QVariantMap。 ( 请参见此处 ,本节的最后一段)。
类似地,如果C ++类型将QVariantList或QVariantMap类型用作属性类型或方法参数,则可以将值创建为QML中的JavaScript数组或对象,并在将其传递给C ++时自动将其转换为QVariantList或QVariantMap。
不幸的是,当参数被键入为QVariantList
, QList<QVariant>
或什至QVariant
(然后转换为QList<QVariant>
)时,返回的长度为0。我还尝试将其键入为QList<QObject*>
和长度可以读取列表中的,但是我无法访问其中的数据,因为QObject *无法转换为QVariant。
QML代码摘录:
for(currentLabel = 0; currentLabel<acquisitionsLabels.length; currentLabel++){
label = acquisitionsLabels[currentLabel];
link = db.getLinkFromLabel(label)[0];
structureName="";
if(link){
criteria = db.getCriteriaFromId(link.fkCriteria);
structure = db.getStructureFromId(criteria.fkStructure);
structureName = structure.name;
}
labels.push({
"label":label,
"structureName":structureName,
"moreToCome":currentLabel<acquisitionsLabels.length-1
});
}
console.log(labels.length);
exportReportFile.printAcquisition(acquisition, acquisitionRenderer.renderAcquisition(acquisition), labels);
exportReportFile.cpp摘录:
void ExportReportFile::printAcquisition(QObject *a_acquisition, const QVariant& a_labels){
QList<QVariant> l_labels = a_labels.value<QList<QVariant>>();
std::cout << typeid(l_labels).name() << std::endl;
std::cout << l_labels.count() << std::endl;
if(l_labels.length()>0){
for(int i=0;i<l_labels.count();i++) {
auto item = l_labels.at(i);
std::cout << typeid(item).name() << std::endl;
}
}
}
该版本的参数是QVariant
引用,但我也尝试了所有以前引用的类型。
一个3项长的列表的预期输出为:
qml: 3
class QList<class QVariant>
3
class QVariant
class QVariant
class QVariant
它实际上是
qml: 3
class QList<class QVariant>
0
创建一个使用QJSValue
作为参数的方法。 这样,值不会转换为QVariant
而是返回实际的JS数据。 然后,您可以根据需要继续进行操作,包括在需要时转换为QVariant:
void ExportReportFile::printAcquisition(QObject *a_acquisition, const QJSValue& a_labels) {
// do stuff with it:
const int length = jsArray.property("length").toInt();
for (int i = 0; i < length; ++i) {
auto arrayElement = jsArray.property(i);
// now you have the element etc.
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.