本页内容

鼠标事件

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

鼠标类型

鼠标事件处理

QML 使用信号和处理程序来传递鼠标交互。具体来说,Qt Quick 提供了MouseArea 和MouseEvent 类型,允许开发者定义 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 类型的文档对这些手势进行了更详细的描述:

  • canceled
  • clicked
  • doubleClicked
  • entered
  • exited
  • 位置已更改
  • 长按
  • 按下
  • 已释放

这些信号可以关联回调函数,当信号被发出时,这些回调函数会被调用。

    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")
    }

启用手势

某些鼠标手势和按钮点击在发送或接收事件之前需要先被启用。某些MouseArea 和MouseEvent 属性可启用这些手势。

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

当然,鼠标事件(如按钮按下和鼠标位置)是在鼠标点击期间发送的。例如,containsMouse 属性仅在鼠标按下期间才能获取其正确值。hoverEnabled 即使在没有鼠标按钮按下的情况下,也会启用鼠标事件和定位功能。将hoverEnabled 属性设置为true ,将相应地启用entered 、exited 和positionChanged 信号及其各自的信号处理程序。

    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 对象

信号及其回调函数会接收一个MouseEvent 对象作为参数。该mouse 对象包含有关鼠标事件的信息。例如,可以通过mouse.button 属性查询触发该事件的鼠标按钮。

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

接收更多信号

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

要进一步了解 QML 的事件系统,请阅读《信号与处理程序》和《事件系统》文档。

© 2026 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.