import QtQuick 2.6
import QtQuick.Window 2.2
Window {
visible: true
width: 1024
height: 480
title: qsTr("Drag Icon")
property ListModel dataModel: ListModel {
ListElement { title: qsTr("电话") }
ListElement { title: qsTr("相册") }
ListElement { title: qsTr("短信") }
ListElement { title: qsTr("网络") }
ListElement { title: qsTr("微信") }
ListElement { title: qsTr("设置") }
ListElement { title: qsTr("日历") }
ListElement { title: qsTr("天气") }
ListElement { title: qsTr("百度") }
ListElement { title: qsTr("时间") }
ListElement { title: qsTr("生活") }
}
QtObject {
id: d
readonly property int cellWidth: 128
readonly property int cellHeight: 128
readonly property int iconWidth: 96
readonly property int iconHeight: 96
property int dragIndex: -1
property bool dragBehavior: false
}
GridView {
id: gridView
anchors.fill: parent
cellWidth: d.cellWidth
cellHeight: d.cellHeight
move: Transition {
NumberAnimation { properties: "x"; duration: 100; easing.type: Easing.OutCubic }
NumberAnimation { properties: "y"; duration: 100; easing.type: Easing.OutCubic }
}
moveDisplaced: Transition {
NumberAnimation { properties: "x"; duration: 300; easing.type: Easing.OutCubic}
NumberAnimation { properties: "y"; duration: 100; easing.type: Easing.OutCubic }
}
model: dataModel
delegate: Item {
width: d.cellWidth
height: d.cellHeight
z: mouseArea.pressed ? 1000 : 1
Rectangle {
id: btnIconArea
anchors.centerIn: parent
width: d.iconWidth
height: d.iconWidth
radius: 8
color: "transparent"
border.color: "gray"
Rectangle {
id: btnIcon
width: d.iconWidth
height: d.iconWidth
radius: 8
color: "blue"
border.color: "black"
Behavior on x { enabled: d.dragBehavior; NumberAnimation { duration: 200 } }
Behavior on y { enabled: d.dragBehavior; NumberAnimation { duration: 200 } }
Text {
anchors.centerIn: parent
color: "white"
text: model.title
}
MouseArea {
id: mouseArea
anchors.fill: parent
drag.target: parent
onPressed: {
d.dragBehavior = false;
var pos = gridView.mapFromItem(btnIcon, 0, 0);
d.dragIndex = model.index;
btnIcon.parent = gridView;
btnIcon.x = pos.x
btnIcon.y = pos.y
}
onReleased: {
d.dragIndex = -1;
var pos = gridView.mapToItem(btnIconArea, btnIcon.x, btnIcon.y);
btnIcon.parent = btnIconArea;
btnIcon.x = pos.x;
btnIcon.y = pos.y;
d.dragBehavior = true;
btnIcon.x = 0;
btnIcon.y = 0;
}
onPositionChanged: {
var pos = gridView.mapFromItem(btnIcon, 0, 0);
var idx = gridView.indexAt(pos.x, pos.y);
if (idx > -1 && idx < gridView.count) {
dataModel.move(d.dragIndex, idx, 1)
d.dragIndex = idx;
}
}
}
}
}
}
}
}