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

Qt Qml报错:ReferenceError: mouse未定义,自定义信号无法调用mouse

问题原因与解决方案

问题根源

mouse 对象是Qt Quick中MouseArea内置鼠标信号(如onMouseXChanged、onPressed)的上下文变量,只有在这些与鼠标事件直接绑定的信号处理函数中,mouse 才会被自动注入并可用。

而自定义信号(比如你的onRemoveAction)触发时,并没有关联的鼠标事件上下文,因此mouse变量未定义,直接访问mouse.x就会抛出ReferenceError。


解决方案

方案1:触发自定义信号时传递鼠标坐标

在触发removeAction信号的地方(比如MouseArea的鼠标事件处理中),直接把当前鼠标的x、y坐标作为参数传递给信号,后续在Connections中接收参数使用。

修改MouseArea中的触发逻辑

假设你是在右键菜单或鼠标点击时触发removeAction,修改为:

MouseArea {
    id: mapMouseArea
    anchors.fill: parent
    acceptedButtons: Qt.LeftButton | Qt.RightButton

    onMouseXChanged: {
        // ... 原有代码
        if (mouse.button === Qt.RightButton) {
            // 触发removeAction时传递鼠标坐标
            mainwindow.removeAction(mouse.x, mouse.y)
        }
    }
}

修改Connections中的信号处理

Connections {
    target: mainwindow
    onSelectItem: {
        var coordinate = QtPositioning.coordinate(x, y)
        mapview.center = coordinate
        mapview.update()
    }

    // 接收传递过来的鼠标坐标参数
    onRemoveAction: function(mouseX, mouseY) {
        var coordinate = mapview.toCoordinate(Qt.point(mouseX, mouseY))
        mainwindow.deleteAction(coordinate.latitude, coordinate.longitude)
    }
}

方案2:全局维护当前鼠标位置

如果需要在任意时刻获取鼠标位置,可以让MouseArea实时更新一个全局可访问的鼠标位置属性,后续直接读取该属性即可。

给MouseArea添加跟踪属性

MouseArea {
    id: mapMouseArea
    anchors.fill: parent
    acceptedButtons: Qt.LeftButton | Qt.RightButton

    // 实时维护当前鼠标位置
    property point currentMousePos: Qt.point(0, 0)
    onMouseXChanged: currentMousePos = Qt.point(mouse.x, mouse.y)
    onMouseYChanged: currentMousePos = Qt.point(mouse.x, mouse.y)

    // ... 原有代码
}

在自定义信号中使用该属性

Connections {
    target: mainwindow
    onSelectItem: {
        var coordinate = QtPositioning.coordinate(x, y)
        mapview.center = coordinate
        mapview.update()
    }

    onRemoveAction: {
        // 直接读取MouseArea维护的当前鼠标位置
        var coordinate = mapview.toCoordinate(mapMouseArea.currentMousePos)
        mainwindow.deleteAction(coordinate.latitude, coordinate.longitude)
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 07:55:28