拖放事件后如何在ListView中检索ListModel的新有序列表
Posted
技术标签:
【中文标题】拖放事件后如何在ListView中检索ListModel的新有序列表【英文标题】:How to retrieve the new ordered list of ListModel inside ListView after drag and drop event 【发布时间】:2016-12-06 10:15:58 【问题描述】:我有这个简单的 qml 代码
import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.0
import QtQml.Models 2.2
ApplicationWindow
visible: true
width: 300
height: 120
title: qsTr("Hello World")
Rectangle
anchors.fill: parent;
ListView
id: timeline
anchors.fill: parent
orientation: ListView.Horizontal
model: visualModel
delegate: timelineDelegate
moveDisplaced: Transition
NumberAnimation
properties: "x,y"
duration: 200
DelegateModel
id: visualModel
model: timelineModel
delegate: timelineDelegate
Component
id: timelineDelegate
MouseArea
id: dragArea
width: 100; height: 100
property bool held: false
drag.target: held ? content : undefined
drag.axis: Drag.XAxis
onPressAndHold: held = true
onReleased:
held = false
var listOnModel = "";
for(var i = 0; i < timelineModel.count; i++)
listOnModel += timelineModel.get(i).colore + ", "
console.log("List: " + listOnModel + "");
Rectangle
id: content
anchors horizontalCenter: parent.horizontalCenter; verticalCenter: parent.verticalCenter
width: 100
height: 100
color: colore
opacity: dragArea.held ? 0.8 : 1.0
Text
anchors.verticalCenter: parent.verticalCenter
anchors.horizontalCenter: parent.horizontalCenter
text: index
font.pixelSize: 20
Drag.active: dragArea.held
Drag.source: dragArea
Drag.hotSpot.x: width / 2
Drag.hotSpot.y: height / 2
states: State
when: dragArea.held
ParentChange target: content; parent: timeline
AnchorChanges
target: content
anchors horizontalCenter: undefined; verticalCenter: undefined
DropArea
anchors.fill: parent
onEntered:
visualModel.items.move( drag.source.DelegateModel.itemsIndex, dragArea.DelegateModel.itemsIndex);
ListModel
id: timelineModel
// @disable-check M16
ListElement colore: "blue"
// @disable-check M16
ListElement colore: "orange"
// @disable-check M16
ListElement colore: "green"
这里有一个简单的彩色可拖动矩形列表。每个矩形的中心都显示了实际的index
,该组件在模型中。
如您所见,在 drop 事件之后,每个 item 的索引都没有改变,并且模型中的 item 的顺序仍然是相同的。发生拖放事件后,有没有办法检索列表的新顺序?
【问题讨论】:
【参考方案1】:您不会重新排序ListModel
,而是您的DelegateModel
的items
。
所以你需要改用这段代码:
onReleased:
held = false
var listOnModel = "";
for(var i = 0; i < visualModel.items.count; i++)
listOnModel += visualModel.items.get(i).model.colore + ", "
console.log("List: " + listOnModel + "");
【讨论】:
以上是关于拖放事件后如何在ListView中检索ListModel的新有序列表的主要内容,如果未能解决你的问题,请参考以下文章
使用CheckBoxListCell的Javafx listview不适用于拖放
UWP - 有没有办法在退出 ListView 时更改鼠标光标而不在拖放期间触发事件?