创建QML QtObject:
QtObject {
property int p: 42
property int q: 44
}
将其存储在局部变量QObject *obj
中后,如何打印所有自定义属性名称和可能的值(即,对于上面的示例,仅打印p
和q
)?我希望这适用于任何类(不仅仅是QtObject
),而不打印已经用Q_PROPERTY
声明的属性。
澄清:我所说的"自定义"并不是指通过QObject::setProperty
添加的、未使用Q_PROPERTY
声明的属性。我指的是通过property <type> <name>: <value>
表示法在QML中声明的属性,而不是使用QML对象的QObject
子类中的Q_PROPERTY
声明的属性。快速测试表明,QObject::dynamicPropertyNames
中没有出现这些属性。
C++和QML方法
要只打印动态属性名称,可以在可调用的C++函数中使用QObject
的dynamicPropertyNames()函数:
#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"
main.qml:
import QtQuick 2.3
import QtQuick.Controls 1.2
ApplicationWindow {
width: 400
height: 400
visible: true
Component.objectName: object.printDynamicPropertyNames()
}
输出:
("dynamicProperty")
仅QML方法
如果您想纯粹使用QML打印对象的所有属性,动态或非,请使用JavaScript。。。语法:
用于。。in语句以任意顺序迭代对象的可枚举属性。对于每个不同的属性,都可以执行语句。
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: 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
...
所有关于属性、可调用方法(插槽)和信号的信息都由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();
}
要获得"您的";QML 中对象的属性
Component.onCompleted: {
for(var property in rect)
if (property in rect.parent === false) {
console.log("local property:", property, typeof(rect[property]))
}
}