import QtQuick 2.5
import QtQuick.Window 2.2
Window {
visible: true
width: 600
height: 600
Rectangle {
id: root
width: 400
height: 400
ListView {
id: listView
width: parent.width / 2
height: parent.height
property int dragItemIndex: -1
model: ListModel{
id: list_model
Component.onCompleted: {
for(var i=0;i<5;i++)
list_model.append({"name": i});
}
}
delegate: Item {
id: delegateItem
width: listView.width
height: 50
Rectangle {
id: dragRect
width: listView.width
height: 50
anchors.horizontalCenter: parent.horizontalCenter
anchors.verticalCenter: parent.verticalCenter
color: mouseArea.drag.active ? "transparent" : "white"
border.color: Qt.darker(color)
Text {
anchors.centerIn: parent
text: name
}
MouseArea {
id: mouseArea
anchors.fill: parent
drag.target: dragRect
drag.axis: Drag.YAxis
drag.onActiveChanged: {
if (mouseArea.drag.active) {
listView.dragItemIndex = index;
}
dragRect.Drag.drop();
}
}//end mousearea
states: [
State {
when: dragRect.Drag.active
ParentChange {
target: dragRect
parent: root
}
AnchorChanges {
target: dragRect
anchors.horizontalCenter: undefined
anchors.verticalCenter: undefined
}
}
]
Drag.active: mouseArea.drag.active
Drag.hotSpot.x: dragRect.width / 2
Drag.hotSpot.y: dragRect.height / 2
}//end rectangle
DropArea {
id: dropArea
anchors.fill: parent
onDropped:{
console.log("onDropped")
var other_index = listView.indexAt(mouseArea.mouseX + delegateItem.x, mouseArea.mouseY + delegateItem.y);
console.log("index:",index,"other_index:",other_index,"listView.dragItemIndex:",listView.dragItemIndex);
list_model.move(listView.dragItemIndex,other_index, 1);
}
Rectangle {
id: dropRectangle
anchors.fill: parent
color: "transparent"
states: [
State {
when: dropArea.containsDrag
PropertyChanges {
target: dropRectangle
color: "lightsteelblue"
}
}
]
}//end Rectangle
}//end drop
}//end item
}//end lisview
}//end rectangle
}
QML实现listview用Drag的方式实现拖拽交换item位置
于 2023-09-12 16:02:56 首次发布