最近在项目中用到了ListView中单元的上下拖动功能,由于在网上找这方面的资料不是太多,所以这里将实现方法记录下来。实现方法:使用onMouseXChanged、onMouseYChanged两个函数来得到该区域内x,y变化后的坐标值,并在里面通过listview.indexAt()函数计算得到索引值index,最后使用move函数来移动listview显示单元。这里提供了一个简单的listview实例,并搭配上了移动时的动画效果,感觉还行。参考程序如下。
参考程序:
import QtQuick 2.4
import QtQuick.Controls 1.3
import QtQuick.Window 2.2
import QtQuick.Dialogs 1.2
Rectangle {
width: 800
height: 600
ListModel{
id: objmodel
ListElement{
name: "苹果"
cost: "5000"
manufacturer: "Apple公司"
}
ListElement{
name: "小米2"
cost: "2000"
manufacturer: "小米公司"
}
ListElement{
name: "三星"
cost: "3000"
manufacturer: "三星公司"
}
}
Component {
id: phone_delegate
Item {
id: wrapper
width: parent.width
height: 30
Row{
anchors.left: parent.left
anchors.verticalCenter: parent.verticalCenter
spacing: 8
Text {
id: coll
text: name
color: wrapper.ListView.isCurrentItem? "red":"black"
font.pixelSize: 20
}
Text {
text: cost
color: wrapper.ListView.isCurrentItem? "red":"black"
font.pixelSize: 20
}
Text {
text: manufacturer
color: wrapper.ListView.isCurrentItem? "red":"black"
font.pixelSize: 20
}
}
MouseArea {
id: mousearea
anchors.fill: parent
onClicked: {
}
onPressed: {
}
onReleased: {
}
onMouseXChanged: {
var pore = listview.indexAt( mousearea.mouseX + wrapper.x, mousearea.mouseY + wrapper.y );
if( index != pore ) {
objmodel.move( index, pore , 1)
}
}
onMouseYChanged: {
var pore = listview.indexAt( mousearea.mouseX + wrapper.x, mousearea.mouseY + wrapper.y );
if( index != pore ) {
objmodel.move( index, pore , 1)
}
}
}
}
}
property int n_flag: 0
ListView {
id: listview
anchors.fill: parent
delegate: phone_delegate
model:objmodel
interactive: false
focus: true
function move_down() {
if( ( n_flag == 0 ) && ( currentIndex+1 ) < second_model.count ) {
model.move( currentIndex, currentIndex+1, 1)
}
if( n_flag == 1 && ( currentIndex-1 ) >= 0) {
model.move( currentIndex, currentIndex-1, 1)
}
if( currentIndex -1 == 0 ) {
n_flag = 0;
}
if( currentIndex + 1 == second_model.count ) {
n_flag = 1
}
}
move: Transition {
NumberAnimation { properties: "x,y"; duration: 100 }
}
}
Rectangle {
anchors.bottom: parent.bottom
width: 100
height: 100
border.width: 0.6
MouseArea {
anchors.fill: parent
onClicked: {
console.log( listview.currentIndex )
listview.move_down()
}
}
}
}