如果你看一下这一页 http://doc.qt.io/qt-5/qml-var.html它指出,当对象更改时,与 var 属性的绑定不会自动更新:
Item {
property var car: new Object({wheels: 4})
Text {
text: "The car has " + car.wheels + " wheels";
}
Component.onCompleted: {
car.wheels = 6;
}
}
这会说“汽车有 4 个轮子”,因为car.wheels = 6;
不会自动触发更新。
该页面没有说明如何解决这个问题?如何手动触发更新(无需替换整个car
目的)。
Edit:明确地说,我不想更换整个car
对象,而我do想要使用一个property var
(我的实际属性是一个 javascript 对象,无法存储在任何本机 QML 属性类型中)。
Edit 2:这是一个使用的示例QtObject
that doesn't工作(它说“汽车有 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");
}
}
}
其实页面does说说如何解决这个问题:
如果 onCompleted 处理程序改为“car = new Object({wheels: 6})”
那么文本将更新为“汽车有 6 个轮子”,因为
汽车属性本身会发生变化,从而导致变化
发出通知。
虽然我认为这违背了你不更换整个的要求car
object.
话虽这么说,(至少)还有另一种选择——使用QtObject http://doc.qt.io/qt-5/qml-qtqml-qtobject.html:
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
}
}
Edit
对于新示例,如果您需要使用包含基本类型的 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;
}
}
}
这对于您的需求来说可能过于严厉。创建一个的黑客方法property bool update
并在更改数组时更改它可能是更好的选择。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)