QML garbage collection deletes objects still in use

后端 未结 3 1182
感动是毒
感动是毒 2020-11-29 11:23

I\'ve encountered this problem on several occasions, with objects created dynamically, regardless of whether they were created in QML or C++. The objects are deleted while s

3条回答
  •  借酒劲吻你
    2020-11-29 12:00

    Create an array inside of a .js file and then create an instance of that array with var myArray = []; on the top-level of that .js. file.

    Now you can reference any object that you append to myArray including ones that are created dynamically.

    Javascript vars are not deleted by garbage collection as long as they remain defined, so if you define one as a global object then include that Javascript file in your qml document, it will remain as long as the main QML is in scope.


    In a file called: backend.js

    var tiles = [];
    
    function create_square(new_square) {
        var component = Qt.createComponent("qrc:///src_qml/src_game/Square.qml");
        var sq = component.createObject(background, { "backend" : new_square });
        sq.x = new_square.tile.x
        sq.y = new_square.tile.y
        sq.width = new_square.tile.width;
        sq.height = new_square.tile.height;
        tiles[game.board.getIndex(new_square.tile.row, new_square.tile.col)] = sq;
        sq.visible = true;
    }
    

    EDIT :

    Let me explain a little more clearly how this could apply to your particular tree example.

    By using the line property Item object you are inadvertently forcing it to be a property of Item, which is treated differently in QML. Specifically, properties fall under a unique set of rules in terms of garbage collections, since the QML engine can simply start removing properties of any object to decrease the memory required to run.

    Instead, at the top of your QML document, include this line:

    import "./object_file.js" as object_file
    

    Then in the file object_file.js , include this line:

     var object_hash = []; 
    

    Now you can use object_hash any time to save your dynamically created components and prevent them from getting wiped out by referencing the

    object_file.object_hash

    object.

    No need to go crazy changing ownership etc

提交回复
热议问题