我有一个 ListModel 和一个中继器。中继器从 ListModel 中绘制项目,一个在另一个之上。到目前为止效果很好。
除了在每个应用程序启动时,我都希望有不同的绘制顺序。
所以我想最好在应用Repeater之前“洗牌”ListModel中的ListElements。我怎样才能做到这一点?
使用以下答案:
并适应ListModel
你得到以下功能:
实用程序.js
//https://stackoverflow.com/a/2450976/6622587
function shuffle(model){
var currentIndex = model.count, temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex)
currentIndex -= 1
// And swap it with the current element.
// the dictionaries maintain their reference so a copy should be made
// https://stackoverflow.com/a/36645492/6622587
temporaryValue = JSON.parse(JSON.stringify(model.get(currentIndex)))
model.set(currentIndex, model.get(randomIndex))
model.set(randomIndex, temporaryValue);
}
return model;
}
main.qml
import QtQuick 2.9
import QtQuick.Window 2.2
import "utils.js" as Util
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
ListModel {
id: fruitModel
ListElement {
name: "Apple"
cost: 2.45
}
ListElement {
name: "Banana"
cost: 1.95
}
ListElement {
name: "Orange"
cost: 3.25
}
}
Column {
Repeater {
model: Util.shuffle(fruitModel)
Row {
spacing: 10
Text { text: name }
Text { text: '$' + cost }
}
}
}
}
在此链接中,您可以找到一个示例。