Working with delegate model and delegate model group dynamically QML?

Tags: , , ,



I have been using a DelegateModel and DelegateModelGroup to only show certain items of a List Model in my delegate. The process is essentially the same as the process described in the first answer to this question. The code for the DelegateModel is below.

DelegateModel {
        id: displayDelegateModel
        delegate:  mMissionDelegate
        model: mMissionModel                     
        groups: [
            DelegateModelGroup   {                 
                includeByDefault: false         
                name: "todaysMissions"
            }
        ]
        filterOnGroup: "todaysMissions"     
        Component.onCompleted: {
            updateMissions()
        }
    }

I am using this so that only 3 random elements from a ListModel are shown in a delegate at once. I then use a function to update these once a timer from c++ times out and emits a signal so a new 3 elements are used. Here is the code for the updating function and he connection with c++.

Connections{
    target: FlashingTimer
    function onCallUpdateMissions(){
        updateMissions();
    }
}
function updateMissions(){
    var rowCount = mMissionModel.count;
    mArray = [];
    displayDelegateModel.items.remove(0,displayDelegateModel.items.count);
    for(let i =0;i < rowCount;i++ ) {
        let entry = mMissionModel.get(i);
        mArray.push(entry)
    }
    let arr = mArray.sort(() => Math.random() - Math.random()).slice(0, 3)
    displayDelegateModel.items.insert(arr[0], "todaysMissions");
    displayDelegateModel.items.insert(arr[1], "todaysMissions");
    displayDelegateModel.items.insert(arr[2], "todaysMissions");
}

At the start, it automatically calls the function with Component.onCompleted as well. My problem is that I cannot figure out how to remove everything from the group before I switch them out. I thought that the items.remove line would do it, but even though the items.count becomes zero, the items still appear in the delegate and the items.insert just adds to to the bottom (so 6 delegates are visible).

Does anyone know a way I could do this, if I have a simple syntax or I should be using an entirely different approach?

Answer

I’m not too familiar with DelegateModels, and even in that SO link you shared, it’s mentioned that DelegateModels are not the shortest path for this. I would recommend a QSortFilterProxyModel instead. The source model contains all of the list elements, and then the proxy model would filter out everything except a random 3 items.

One nice thing about doing it this way is that the timer code and the randomization would all be isolated in the C++ model. The QML code would be completely unaware of any of that. It would just display whatever the model tells it to.



Source: stackoverflow