鼠标事件

处理来自所有指向设备(包括鼠标和触摸屏)的事件的更现代方法是通过输入处理程序。本页介绍了最初的Qt Quick MouseArea 类型,该类型最初设计用于处理鼠标输入,后来开始在简单的面向触摸的用户界面中处理单点触摸事件(以合成鼠标事件的形式)。

鼠标类型

鼠标事件处理

QML 使用信号和处理程序来传递鼠标交互。具体来说,Qt Quick 提供了MouseAreaMouseEvent 类型,允许开发人员定义 JavaScript 回调(也称为信号处理程序),在定义的区域内接受鼠标事件。

定义鼠标区域

MouseArea 类型可接收定义区域内的事件。定义该区域的一种快速方法是使用anchors.fill 属性将MouseArea 锚定到其父区域。如果父级是Rectangle (或任何Item 组件),那么MouseArea 将填充父级尺寸所定义的区域。另外,也可以定义一个比父对象小或大的区域。

Rectangle {
    id: button
    width: 100; height: 100

    MouseArea {
        anchors.fill: parent
        onClicked: console.log("button clicked")
    }
    MouseArea {
        width:150; height: 75
        onClicked: console.log("irregular area clicked")
    }
}

接收事件

MouseArea 类型会根据不同的鼠标事件发出信号MouseArea 类型文档更详细地描述了这些手势:

  • 取消
  • 单击
  • 双击
  • 进入
  • 退出
  • 位置已更改
  • 按下并保持
  • 按下
  • 释放

这些信号可以有回调,在信号发出时被调用。

    MouseArea {
        anchors.fill: parent
        onClicked: console.log("area clicked")
        onDoubleClicked: console.log("area double clicked")
        onEntered: console.log("mouse entered the area")
        onExited: console.log("mouse left the area")
    }

启用手势

某些鼠标手势和按钮点击需要在发送或接收事件前启用。某些MouseAreaMouseEvent 属性会启用这些手势。

要监听(或明确忽略)某个鼠标按钮,可将相应的鼠标按钮设置为acceptedButtons 属性。

当然,鼠标事件(如按键和鼠标位置)会在鼠标点击时发送。例如,containsMouse 属性只有在鼠标按下时才会获取其正确值。即使没有按下鼠标按钮,hoverEnabled 也会启用鼠标事件和定位。将hoverEnabled 属性设置为true 后,将启用enteredexitedpositionChanged 信号及其各自的信号处理器。

    MouseArea {
        hoverEnabled: true
        acceptedButtons: Qt.LeftButton | Qt.RightButton
        onEntered: console.log("mouse entered the area")
        onExited: console.log("mouse left the area")
    }

此外,要禁用整个鼠标区域,可将MouseArea enabled 属性设置为false

鼠标事件对象

信号及其回调接收MouseEvent 对象作为参数。mouse 对象包含鼠标事件的相关信息。例如,可通过mouse.button 属性查询启动事件的鼠标按钮。

MouseEvent 对象还可以使用其accepted 属性忽略鼠标事件。

接受更多信号

许多信号会被多次发送,以反映双击等各种鼠标事件。为了便于对鼠标点击进行分类,MouseEvent 对象有一个accepted 属性,用于禁用事件传播。

要了解 QML 事件系统的更多信息,请阅读信号和处理程序以及事件系统文档。

© 2025 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.