代码之家  ›  专栏  ›  技术社区  ›  pmf

QML:对属性类型的反射访问

  •  0
  • pmf  · 技术社区  · 6 年前

    在QML中,如何通过反射查询项的属性类型?

    我有一件东西 C x 类型 real 还有一处房产 y 类型 string ; 在另一个调用站点,我有一个 并希望查询其属性的类型 . 使用普通Qt,我可以使用 QMetaObject ,但如何对QML执行相同的操作?

    1 回复  |  直到 6 年前
        1
  •  3
  •   GrecKo    6 年前

    在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)
    }
    

    这将打印 qml: number string number .

    请注意,这两者之间没有区别 x z 尽管它们的类型不同,但这是因为JavaScript只知道一种数字类型,每个数字都是64位浮点*。

    为此,可以将c++类型公开为 qml singleton ,并在其中公开一个可调用的方法,该方法返回对象属性的类型名:

    #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
    

    在QML中执行此操作:

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

    然后打印 qml: double QString int

    here