如何打印QML对象的自定义属性列表?

时间:2014-10-24 05:10:54

标签: qt qml qt5

创建了QML QtObject:

QtObject {
    property int p: 42
    property int q: 44
}

将其存储在本地变量QObject *obj后,如何打印所有自定义属性名称和可能的值(例如,上面的示例只有pq)?我希望这适用于任何课程(不仅仅是QtObject),而且不会打印已使用Q_PROPERTY声明的属性。

澄清:通过&#34; custom&#34;我并不是指通过QObject::setProperty添加的未使用Q_PROPERTY声明的属性。我的意思是在QML中通过property <type> <name>: <value>表示法声明的属性未在Q_PROPERTY子类中使用QObject为该QML对象声明。快速测试表明QObject::dynamicPropertyNames中没有出现这些属性。

3 个答案:

答案 0 :(得分:6)

C ++和QML方法

要仅打印动态属性名称,可以在可调用的C ++函数中使用QObject非常恰当的#include <QGuiApplication> #include <QtQml> class Object : public QObject { Q_OBJECT Q_PROPERTY(int staticProperty READ staticProperty) public: Object() { setProperty("dynamicProperty", 1); } int staticProperty() const { return 0; } Q_INVOKABLE void printDynamicPropertyNames() const { qDebug() << dynamicPropertyNames(); } }; int main(int argc, char** argv) { QGuiApplication app(argc, argv); Object object; QQmlApplicationEngine engine; engine.rootContext()->setContextProperty("object", &object); engine.load("main.qml"); return app.exec(); } #include "main.moc" 函数:

import QtQuick 2.3
import QtQuick.Controls 1.2

ApplicationWindow {
    width: 400
    height: 400
    visible: true

    Component.objectName: object.printDynamicPropertyNames()
}

main.qml:

("dynamicProperty")

输出:

import QtQuick 2.2

Rectangle {
    id: rect
    width: 360
    height: 360

    Component.onCompleted: {
        for (var prop in rect) {
            print(prop += " (" + typeof(rect[prop]) + ") = " + rect[prop]);
        }
    }
}

仅QML方法

如果要打印对象的所有属性,动态或不,纯粹使用QML,请使用JavaScript的dynamicPropertyNames()语法:

  

for..in语句以任意顺序迭代对象的可枚举属性。对于每个不同的属性,可以执行语句。

qml: objectName (string) = 
qml: parent (object) = null
qml: data (object) = [object Object]
qml: resources (object) = [object Object]
qml: children (object) = [object Object]
qml: x (number) = 0
qml: y (number) = 0
qml: z (number) = 0
qml: width (number) = 360
qml: height (number) = 360
qml: opacity (number) = 1
qml: enabled (boolean) = true
...

输出:

{{1}}

答案 1 :(得分:2)

有关属性,可调用方法(插槽)和信号的所有信息都由 QMetaObject 存储在每个QObject中。如果要列出对象中的所有属性:

QObject *obj = findObjectMethod();
QMetaObject *meta = obj->metaObject();
int n = meta->propertyCount();
for(int i = 0; i < n; ++i)
{
  qDebug() << "Property: " << meta->property(i)->name();
}

答案 2 :(得分:0)

在QML中获取对象的“您的”属性

Component.onCompleted: {
    for(var property in rect)
        if (property in rect.parent === false) {
            console.log("local property:", property, typeof(rect[property]))
        }
}