You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现拖动元素移出MouseArea后保持cursorShape不变?

解决拖动元素时跨MouseArea保持光标状态的问题

要实现拖出MouseArea后持续保持拖动光标状态,核心问题是单个MouseArea的光标设置仅在鼠标处于其范围内时生效,当鼠标移至其他MouseArea时,会被后者的默认光标覆盖。我们可以通过将光标设置提升至窗口层级,统一跟踪拖动状态来解决:

修改后的代码

import QtQuick
import QtQuick.Controls

Window {
    width: 300
    height: 300
    visible: true
    color: "#1F1F1F"
    
    // 全局跟踪是否处于拖动状态
    property bool isDragging: false
    
    // 绑定窗口光标到拖动状态
    cursorShape: isDragging ? Qt.DragCopyCursor : Qt.ArrowCursor

    Column {
        anchors.centerIn: parent
        Repeater {
            model: 2
            delegate: Rectangle {
                z: mouseArea.drag.active ? 2 : 0
                color: "#aaaaaa"
                width: 300
                height: 50

                MouseArea {
                    id: mouseArea
                    anchors.fill: parent
                    drag.target: rec
                    
                    // 拖动开始时更新全局状态
                    onDragStarted: {
                        window.isDragging = true
                    }
                    
                    // 拖动结束时恢复全局状态
                    onDragFinished: {
                        window.isDragging = false
                    }

                    Rectangle {
                        id: rec
                        color: "white"
                        height: parent.height / 2
                        width: parent.width / 2
                        anchors.verticalCenter: parent.verticalCenter
                        anchors.horizontalCenter: parent.horizontalCenter
                        Text {
                            anchors.centerIn: parent
                            text: "test " + index
                            color: "black"
                        }
                        states: [
                            State {
                                when: mouseArea.drag.active
                                AnchorChanges {
                                    target: rec
                                    anchors.verticalCenter: undefined
                                    anchors.horizontalCenter: undefined
                                }
                            }
                        ]
                    }
                }
            }
        }
    }
}

关键改动说明

  • 新增isDragging全局属性,用于统一跟踪是否有元素正在被拖动
  • 将cursorShape绑定到窗口的cursorShape属性,确保整个窗口范围内光标状态一致
  • 通过MouseArea的onDragStarted和onDragFinished信号更新全局拖动状态,无论鼠标移到哪个区域,光标都会保持拖动样式直到拖动结束

内容的提问来源于stack exchange,提问作者Kamichanw

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 20:47:04