Best way to remove dynamic qml object from a listmodel
-
I have self destroying qml objects in a list model.
When they are destroyd I want to remove then from the listmodel, but I dont know their index. So to find the index I'm setting a flag to false when they are about to be destroyed, then I iterate the list to find the object index. It works, but it looks ugly and hacky, is there a better way to find the object list index from inside the object ?This is what I did:
ListModel { id: activeEnemiesList } Component.onCompleted: { var enemy2count = 55 for (i = 0; i < enemy2count;i++) { var enemy2 = lib.createItem("Enemy02.qml", parent) //dynamic creation } }
Enemy02.qml :
Item { id: enemy02 property bool timerRunning: y > spaceLimitYmin && y < spaceLimitYmax property bool alive: true onTimerRunningChanged: { if (timerRunning) { // add object to the list activeEnemiesList.append({"obj": enemy02}) console.log("added enemy to the list, size is "+activeEnemiesList.count) } else { //remove object from the list and destroy it alive = false for(var i = 0; i < activeEnemiesList.count; i++) { if (activeEnemiesList.get(i).obj.alive === false) { activeEnemiesList.remove(i,1) enemy02.destroy() break; } } } }
-
How are you displaying the individual objects. It must be through delegate. You can use 'index' property inside the delegate which gives you the information required.
-
Thats the problem, I'm not using any delegates so no index available. They are just dynamic qml rectangles that self display randomly on screen, when created. I'm only using a Listmodel to keep track of them to do stuff like collision detection (I could have also used a javascript array instead of listmodel).