更新 QML 中 var 属性的绑定

Tim*_*mmm 3 qt qml

如果您查看此页面,您会注意到当对象更改时,与 var 属性的绑定不会自动更新:

Item {
    property var car: new Object({wheels: 4})

    Text {
        text: "The car has " + car.wheels + " wheels";
    }

    Component.onCompleted: {
        car.wheels = 6;
    }
}
Run Code Online (Sandbox Code Playgroud)

这会说“汽车有 4 个轮子”,因为car.wheels = 6;不会自动触发更新。

该页面没有说明如何解决这个问题?如何手动触发更新(无需替换整个car对象)。

编辑:要明确的是,我不想替换整个car对象,并且我确实想使用 a property var(我的实际属性是一个 javascript 对象,无法存储在任何本机 QML 属性类型中)。

编辑 2:QtObject这是一个不起作用示例(它说“汽车有 0 个轮子。”:

import QtQuick 2.4
import QtQuick.Controls 1.3
import QtQuick.Window 2.2
import QtQuick.Dialogs 1.2

ApplicationWindow {
    width: 640
    height: 480
    visible: true

    property var car: QtObject { property var wheels: [] }

    Item {

        Text {
            text: "The car has " + car.wheels.length + " wheels";
        }

        Component.onCompleted: {
            car.wheels.push("Rear-left");
            car.wheels.push("Rear-right");
            car.wheels.push("Front-left");
            car.wheels.push("Front-right");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

RA.*_*RA. 5

实际上,该页面确实说明了如何解决此问题:

如果 onCompleted 处理程序改为“car = new Object({wheels: 6})”,则文本将更新为“汽车有 6 个轮子”,因为汽车属性本身将被更改,这会导致更改通知被发射。

尽管我认为这违背了您不替换整个car对象的要求。

话虽如此,(至少)还有另一种选择——使用QtObject

Item
{
    property var car: QtObject { property int wheels: 4 }

    Text {
        text: "The car has " + car.wheels + " wheels";
    }

    Component.onCompleted: {
        car.wheels = 6;  // This will update the text
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑

在新示例中,如果您需要使用包含基本类型的 Javascript 数组,则列出的代码不会触发更新。但是,如果您能够使用list包含 QML 类型,则可以使用以下解决方法:

import QtQuick 2.4
import QtQuick.Controls 1.3
import QtQuick.Window 2.2
import QtQuick.Dialogs 1.2

ApplicationWindow {
    id: window
    width: 640
    height: 480
    visible: true

    property var car: QtObject { property list<Item> wheels }

    Component
    {
        id: wheelComponent
        QtObject
        {
            property var wheelName;
        }
    }

    Text
    {
        anchors.fill: parent
        text: "The car has " + car.wheels.length + " wheels";

        Component.onCompleted:
        {
            var wheel = wheelComponent.createObject(window, {"wheelName": "Rear-left"} );
            car.wheels += wheel;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这对于您的需求来说可能过于严厉。创建property bool update并在更改数组时更改它的黑客方法可能更可取。