Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QML item's children list deep copy

Tags:

qt

qml

I'd like to make a deep copy of an items children property. I've tried things along the lines:

Item {
  property variant itemsCopy

  Component.onCompleted: {
    var tmp = otherItem.children
    itemsCopy = tmp
  }
}

But when otherItem.children is changed (sorted due to different Z values), itemsCopy is also changed. Is there a workaround to break the binding or a way to prevent children from being sorted? I've tried Array s, list, nothing works. Changing members of tmp is ignored.

like image 296
user1095108 Avatar asked Dec 21 '22 19:12

user1095108


1 Answers

In the example provided by MartinJ all objects will be copied by reference. Here is a classic deep copy function from "Object-Oriented JavaScript" book:

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;
}
like image 120
Pavel Osipov Avatar answered Dec 30 '22 00:12

Pavel Osipov