首页 > 解决方案 > QML 在鼠标按下时动态转移鼠标所有权

问题描述

我有一个应用程序,右侧有一个图像列表(使用 ListView),左侧有一个查看器。用户可以将图像从列表拖到查看器中,并将图像保留在列表中(类似于列表的预览,但具有拖放功能)。

为此,当用户在列表中的图像上“pressAndHold”时,我会创建该图像的副本并将其放在列表中的图像的前面(我更改了边框,所以我知道它是副本)。

如果我然后释放并再次单击副本,我可以将副本移动到查看器,一旦我释放副本,我会销毁副本并处理拖放到查看器区域上的内容。

除非我释放并单击副本,否则我无法执行此操作,因为当鼠标处于等待状态时,我无法将“鼠标所有权”从列表图像鼠标区域转移到复制图像鼠标区域。

有任何想法吗?提前致谢!

标签: qtdrag-and-dropqmlfocusmouseevent

解决方案


对于任何寻找类似东西的人来说,我就是这样做的:在代表上,我添加了鼠标区域:

MouseArea { // This is the mouse area on the original image-list
    id: thumbnailDelegateMA
    anchors { fill: parent }

    cursorShape: containsMouse ? (drag.active ? Qt.ClosedHandCursor : Qt.PointingHandCursor) : Qt.ArrowCursor

    property var copyThumbnail: undefined
    drag.target: copyThumbnail ? copyThumbnail : null

    onPressAndHold: {
        if(!copyThumbnail){
            copyThumbnail = createThumbnailCopy(imageID, parent)

            parent = copyThumbnail
            anchors.fill = copyThumbnail
        }
    }

    onReleased:{
        if(copyThumbnail){
            parent = copyThumbnail.original
            anchors.fill = copyThumbnail.original

            copyThumbnail.destroy()
        }
    }
}

在哪里:

function createThumbnailCopy(uid, cparent){
    var main_window = cparent.parent.parent;
    var mapPos = mapFromItem(main_window, cparent.x, cparent.y);

    var thumbnailCopy = thumbnailCopyComponent.createObject(
                main_window,
                {   "original": cparent,
                    "id": uid
                    "x": mapPos .x,
                    "y": mapPos .y
                });
    return thumbnailCopy;
}

和:

Component{
    id: thumbnailCopyComponent

    Image {
        id: thumbnailCopy

        property string id;
        property var original: undefined

        Drag.hotSpot: Qt.point(width/2, 0)
        Drag.active: true

        fillMode: Image.PreserveAspectFit
        source: "image://thumbnailProvider/" + id
    }
}

推荐阅读