简体   繁体   English

如何检测 JSON 对象内的变化?

[英]How to detect change within JSON object?

import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.0

Window {
    visible: true
    width: 640
    height: 480

    property var json: {
        "name": "old"
    }

    Component.onCompleted: json.name = "new"

    onJsonChanged: console.log("Changed to : " + json.name)

    Button {
        onClicked: console.log("Button clicked: " + json.name)
    }
}
qml: Changed to : old

But I'd expect an output of:但我希望输出:

qml: Changed to : old
qml: Changed to : new

QML has no problem recognizing the onJsonChanged: signal, but the signal doesn't actually seem to activate. QML 识别onJsonChanged:信号没有问题,但该信号实际上似乎并未激活。 I know json.name is successfully changing, because I've debugged during runtime and see that it has the new value.我知道json.name正在成功更改,因为我已经在运行时调试并看到它具有新值。 So why doesn't the signal activate, and/or how can I detect the change in the json object?那么为什么信号没有激活,和/或我如何检测 json 对象的变化?

The signal associated with the X property is emitted when the object changes, in your case changing some internal attribute does not change the object (the memory space) only modifies internal properties.与 X 属性关联的信号在对象更改时发出,在您的情况下,更改某些内部属性不会更改对象(内存空间),只会修改内部属性。 To verify this you can modify your example to:要验证这一点,您可以将示例修改为:

import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.0

Window {
    visible: true
    width: 640
    height: 480

    property var json: {
        "name": "bar"
    }

    Component.onCompleted: json = {"name3": "foo"}

    onJsonChanged: console.log("Changed to : " + json)

    Button {
        onClicked: console.log("Button clicked: " + json)
    }
}

The following is obtained:得到以下内容:

qml: Changed to : [object Object]
qml: Changed to : [object Object]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM