如何在Listview中拖拽其中的子Item移动其位置

最近开发遇到一个需求,需要显示的对象支持拖拽,一般的对象直接使用dargarea即可。但我用的是Listview来显示,而且是自己定义的listmodel,可以说是相当的烦。

1、一种情况,如果是使用qml中的listmodel则直接调用model的move方法进行移动:核心代码为

                      MouseArea

            {
                id:mos;
                anchors.fill: parent;
                onMouseXChanged:
                {
                    var pore = list.indexAt( mos.mouseX + dlt.x, mos.mouseY + dlt.y );
                    console.debug("pore = ",pore);
                    if(index !== pore && pore >= 0)
                    {
                        root.model.move(index, index, pore);
                    }
                }
            }
2、是当自己定义listmodel时,他的移动也必须自己实现,直接上代码
void myModel::move(int srcFirst, int srcLast,int desIndex)
{
    //两种情况----为了能看懂逻辑写的简单点
    int tmp_desIndex = 0;
    //1、从前往后拖拽
    if(srcFirst < desIndex)
    {
        //desIndex不可以在范围(srcFirst,srcFirst+1),如果是则此时desIndex必须+1
        tmp_desIndex = srcFirst + 1 >= desIndex? desIndex + 1 : desIndex;
    }
    else//2、从后往前
    {
        tmp_desIndex = desIndex;
    }
    //注意,结合上面的拖拽信号处理,一次只能移动一个位置,所以srcFirst == srcLast
    emit beginMoveRows(QModelIndex(),srcFirst,srcLast,QModelIndex(), tmp_desIndex);
    m_datas.move(srcFirst,desIndex);//在此处自己实现c++数据的移动。信号只能帮你在qml中实现移动
    emit endMoveRows();
}

以上,两种情况的处理。然后就可以尽情的拖拽吧

猜你喜欢

转载自blog.csdn.net/wei375653972/article/details/77899731