有没有办法在QML和Qt 5.1中列出所有对象成员/属性?
如:
var obj=myQObject; console.log(obj) // expected output: // obj { x:123..... }
这对调试非常有帮助.
使用元对象,您可以调试任何QML的所有属性obj
(即QQuickItem).
您需要一些C++来获取QML组件的元对象,并在QML中将属性名称和值作为文本返回.
首先QMLDebugger
,使用properties
方法在C++中创建一个类:
QString QMLDebugger::properties(QQuickItem *item, bool linebreak) { const QMetaObject *meta = item->metaObject(); QHash<QString, QVariant> list; for (int i = 0; i < meta->propertyCount(); i++) { QMetaProperty property = meta->property(i); const char* name = property.name(); QVariant value = item->property(name); list[name] = value; } QString out; QHashIterator<QString, QVariant> i(list); while (i.hasNext()) { i.next(); if (!out.isEmpty()) { out += ", "; if (linebreak) out += "\n"; } out.append(i.key()); out.append(": "); out.append(i.value().toString()); } return out; }
此功能可以是静态的或可实现的,无关紧要.QML不支持将静态方法从C++导出到QML.我使用标题:
public: Q_INVOKABLE static QString properties(QQuickItem *item, bool linebreak = true);
现在将类导出为QML.在你main.cpp
添加
#include "qmldebugger.h"
和
qmlRegisterType<QMLDebugger>("MyDemoLibrary", 1, 0, "QMLDebugger");
在您的QML文件中导入新库,创建QMLDebugger实例并开始快乐调试:
import QtQuick 2.0 import MyDemoLibrary 1.0 Rectangle { id: mainRectangle width: 360 height: 360 color: "silver" Text { id: textElement color: "#d71f1f" text: qsTr("Hello World") font.bold: true font.italic: true font.underline: true style: Text.Raised horizontalAlignment: Text.AlignHCenter font.pointSize: 16 anchors.top: parent.top anchors.left: parent.left anchors.right: parent.right } QMLDebugger { id: qmlDebugger } Component.onCompleted: { console.log("Debug mainRectangle:"); console.log(qmlDebugger.properties(mainRectangle)); console.log("Debug textElement:"); console.log(qmlDebugger.properties(textElement, false)); } }
完整的源代码可作为最小的Qt Creator项目使用:https://github.com/webmaster128/QMLDebugger
直接的javascript提供您所需要的:
JSON.stringify(anything)
它适用于QML项目,如Rectangle,它也适用于大多数任意对象!
将对象转换为字符串
只需将QML/C++组件/对象转换为JavaScript var对象,并使用for-each语法列出所有属性:
function listProperty(item) { for (var p in item) console.log(p + ": " + item[p]); }
在你的QML文件中,只需调用即可
onClicked: { listProperty(ItemID) //or with this to list self properties listProperty(this) }