この Javascript の小さなスニペットは、Qml アイテムのすべてのプロパティと関数をログに記録します。これは、モデルを持つ動的コントロールに深く入り込んでいて、コードが機能しない理由を知りたい場合に役立ちます。おそらく、正しいプロパティ名を使用していないためです。または、少なくとも、それは私がよく持っているものです。すべてのプロパティまたは関数をログに記録すると、その問題を把握するのに役立ちます。
すべてのプロパティをログに記録するコードは、実際には非常に単純です:
function listProperties(item) {
var properties = ""
for (var p in item)
if (typeof item[p] != "function")
properties += (p + ": " + item[p] + "\n")
return properties
}
すべての関数をログに記録する場合も同様です:
function listFunctions(item) {
var functions = ""
for (var f in item)
if (typeof item[f] == "function")
functions += (f + ": " + item[f] + "\n")
return functions
}
if(typeof...
を削除すると 次に、出力で両方を取得します。
使い方は簡単で、 id:
を渡すだけです 記録したいアイテムの:
Button {
id: logButton
[...]
text: "Log Properties"
onClicked: {
console.log(listProperties(logButton))
}
}
JSON.stringify()
を使用することもできます しかし、それを使用すると再帰ループがクラッシュするのを見たので、これは私の小さな goto スニペットです。
デモ Qml プログラム
これは、関数またはプロパティのいずれかをコマンド ラインと TextArea
に記録する小さな Qml デモ プログラムです。 .
main.qml
import QtQuick 2.15
import QtQuick.Controls 2.12
import QtQuick.Window 2.15
Window {
width: 640
height: 480
visible: true
title: qsTr("Log Properties Example")
function listProperties(item) {
var properties = ""
for (var p in item)
if (typeof item[p] != "function")
properties += (p + ": " + item[p] + "\n")
return properties
}
function listFunctions(item) {
var functions = ""
for (var f in item)
if (typeof item[f] == "function")
functions += (f + ": " + item[f] + "\n")
return functions
}
Button {
id: logButton
anchors.top: parent.top
anchors.left: parent.left
anchors.margins: 50
objectName: "Raymii.org Example"
text: "Log Properties"
onClicked: {
console.log(listProperties(logButton))
logTextarea.text = listProperties(logButton)
}
}
Button {
id: logFunctionsButton
anchors.top: parent.top
anchors.left: logButton.right
anchors.margins: 50
text: "Log Functions"
onClicked: {
console.log(listFunctions(logFunctionsButton))
logTextarea.text = listFunctions(logFunctionsButton)
}
}
ScrollView {
id: propertyview
anchors.top: logButton.bottom
anchors.left: parent.left
anchors.margins: 50
width: 500
height: 300
TextArea {
id: logTextarea
anchors.fill: parent
placeholderText: "click the buttons"
}
}
}
main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
int main(int argc, char *argv[])
{
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endif
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
const QUrl url(QStringLiteral("qrc:/main.qml"));
QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
&app, [url](QObject *obj, const QUrl &objUrl) {
if (!obj && url == objUrl)
QCoreApplication::exit(-1);
}, Qt::QueuedConnection);
engine.load(url);
return app.exec();
}