简体   繁体   English

QML:以反射方式访问属性类型

[英]QML: reflective access to type of property

In QML, how can I query for the type of a property of an item via reflection? 在QML中,如何通过反射查询项的属性类型?

Ie I have an Item C with a property x of type real and a property y of type string ; 即我有一个Item C ,它的属性xreal类型,属性ystring ; at some other callsite I have an instance of C and want to query the type of its property x . 在其他某个呼叫站点,我有C的实例,并想查询其属性x的类型。 With plain Qt, I can use QMetaObject , but how to do the same with QML? 使用普通Qt,我可以使用QMetaObject ,但是如何使用QML呢?

As in JavaScript, you can use typeof : 与JavaScript中一样,您可以使用typeof

QtObject {
    id: c
    property real x
    property string y
    property int z
    Component.onCompleted: print(typeof c.x, typeof c.y, typeof c.z)
}

This will print qml: number string number . 这将打印qml: number string number

Note that there is no difference here between x and z even though they are not of the same type, that's because JavaScript knows of only 1 number type, every number is 64-bit floating point*. 请注意,即使xz的类型不同,这里也没有区别,这是因为JavaScript只能识别1个数字类型,每个数字都是64位浮点数*。

If you want to know how types are actually stored by the Qt engine, you would have to do as you mentionned in your question, use QMetaObject. 如果您想知道Qt引擎实际上是如何存储类型的,则必须按照问题中的说明进行操作,请使用QMetaObject。 For that you can expose a c++ type as a qml singleton , and expose an invokable method in it returning the typename of an object's property : 为此,您可以将c ++类型公开为qml单例 ,并在其中公开一个可调用的方法,以返回对象属性的类型名:

#ifndef METAOBJECTHELPER_H
#define METAOBJECTHELPER_H

#include <QMetaObject>
#include <QObject>
#include <QQmlProperty>

class MetaObjectHelper : public QObject {
    Q_OBJECT
public:
    using QObject::QObject;
    Q_INVOKABLE QString typeName(QObject* object, const QString& property) const
    {
        QQmlProperty qmlProperty(object, property);
        QMetaProperty metaProperty = qmlProperty.property();
        return metaProperty.typeName();
    }
};

#endif // METAOBJECTHELPER_H

Doing this in QML : 在QML中执行此操作:

print(MetaObjectHelper.typeName(c, "x"), MetaObjectHelper.typeName(c, "y"), MetaObjectHelper.typeName(c, "z"));

Will then print qml: double QString int 然后将打印qml: double QString int

* : more nuanced details here *:更多细节在这里

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

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