我想要制作一个项目儿童财产的深层副本.我尝试过这样的事情:
Item {
property variant itemsCopy
Component.onCompleted: {
var tmp = otherItem.children
itemsCopy = tmp
}
}
Run Code Online (Sandbox Code Playgroud)
但是当更改otherItem.children(由于不同的Z值排序)时,itemsCopy也会更改.是否有解决方法来打破绑定或防止孩子被分类的方法?我试过Array s,list,没什么用.更改tmp的成员将被忽略.
你可以自己复印一份:
import QtQuick 1.0
Item {
property variant itemsCopy
Component.onCompleted: {
var tmp = otherItem.children
var copy = []
for (var i = 0; i < tmp.length; ++i)
copy[i] = tmp[i]
itemsCopy = copy;
}
}
Run Code Online (Sandbox Code Playgroud)
在QtQuick 2.0中,它可以更容易使用property var:
import QtQuick 2.0
Item {
property var itemsCopy: []
Component.onCompleted: {
var tmp = otherItem.children
for (var i = 0; i < tmp.length; ++i)
itemsCopy[i] = tmp[i]
}
}
Run Code Online (Sandbox Code Playgroud)
在MartinJ提供的示例中,所有对象都将通过引用进行复制.这是"面向对象的JavaScript"一书中的经典深层复制功能:
function deepCopy(p, c) {
var c = c || {};
for (var i in p) {
if (typeof p[i] === 'object') {
c[i] = (p[i].constructor === Array) ? [] : {};
deepCopy(p[i], c[i]);
} else {
c[i] = p[i];
}
}
return c;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5929 次 |
| 最近记录: |