QQmlListProperty已转换为不透明的QVariant

QQmlListProperty converted to opaque QVariant

本文关键字:QVariant 不透明 转换 QQmlListProperty      更新时间:2023-10-16

我的QQmlListProperty有问题。

我的类返回一个QQmlListProperty列表。我调用一个c++类的qml中的函数,该函数返回相应的列表。但当我尝试访问列表时,比如list.lenght,我会得到一个未定义的javascript对象。

C++侧面

class IControllerInterface {
...
public:
QQmlListProperty<IObject> objectsQml() {
return QQmlListProperty<IObject>(this,
this,
&IController::qmlListAppend,
&IController::qmlListCount,
&IController::qmlListAt,
&IController::qmlListClear);
}
private:
static void qmlListAppend(QQmlListProperty<IObject> *list, IObject *object);
static IObject *qmlListAt(QQmlListProperty<IObject> *list, int index);
static int qmlListCount(QQmlListProperty<IObject> *list);
static void qmlListClear(QQmlListProperty<IObject> *list);
...
}
void IController::qmlListAppend(QQmlListProperty<IObject> *list, IObject *object)
{
}
IObject *IController::qmlListAt(QQmlListProperty<IObject> *list, int index)
{
return reinterpret_cast< IController* >(list->data)->objects()[index];
}
int IController::qmlListCount(QQmlListProperty<IObject> *list)
{
return reinterpret_cast< IController* >(list->data)->objects().size();
}
void IController::qmlListClear(QQmlListProperty<IObject> *list)
{
}

class RestAPI {
...
Q_INVOKABLE QQmlListProperty<IObject> lookupObjectsQml(const IObject::ObjectType type) {
Q_D(RestAPI);
return d->getController(type)->objectsQml();
}
...
}

*注意:RestAPI是一个单例类

QML侧面

RestControl {
id: ctrl
Component.onCompleted: {
var lst = RestAPI.lookupObjectsQml(IObject.FARM)
console.log(lst)
console.log('found ' + lst.length + ' objects..')
for(var obj in lst) {
console.log(obj.id)
}
}
}

当我调用RestAPI.lookupObjectsQml(IObject.FARM)并将结果分配给变量lst时。。我收到一个不透明的qvariant对象:

QVariant(QQmlListProperty)

这样我就无法访问我的对象。

例如,此调用将返回未定义的:lst.length

我做错了什么?

调试05-01-19 10:42:49:889[GUI][root]QVariant(QQmlListProperty)

调试05-01-19 10:42:49:890[GUI][root]发现未定义的对象。。

类型QQmlListProperty应该作为属性本身公开给QML:

Q_PROPERTY(QQmlListProperty<IObject> objects READ objects)

为了正确使用这种类型,QML代码中JavaScript的语义应该是:

RestAPI.lookupObjectsQml(IObject.FARM);
for(var obj in RestAPI.objects) {
console.log(obj.id)
}

您的代码的其余部分表明,您将能够用C++完成这样的更改。但当然,您可以找到许多其他方法[例如]来根据需要提供函数调用中的对象列表,但当QQmlListProperty完全用作QML属性时,就不能这样了。