本页内容

Qt Quick 示例 - MouseArea

这是 QML 中 `MouseArea ` 类型的示例。

红色“点击”方块和蓝色“拖动”方块,下方显示鼠标事件状态文本

MouseArea示例演示了如何使用MouseArea 处理点击和拖动操作。如需了解更多信息,请参阅《Qt Quick 中的重要概念——用户输入》。

运行示例

您可以通过以下方式运行该示例:

MouseArea 行为

当您点击红色方块内部时,Text 类型将列出该点击的若干属性,这些属性可供QML使用。只要鼠标按键被按下且光标仍位于MouseArea 内,红色方块的透明度就会降低。

当在MouseArea 内部发生点击或其他离散操作时,该行为会发出信号。

onPressAndHold: btn.text = qsTr('Press and hold')
onClicked: (mouse) => { btn.text = qsTr('Clicked (wasHeld=') + mouse.wasHeld + ')' }
onDoubleClicked: btn.text = qsTr('Double clicked')

MouseArea 该控件还可用于拖动项目。通过设置 drag 属性的参数,当用户在鼠标区域边界内开始拖动时,目标项目将被拖动。

drag.target: blueSquare
drag.axis: Drag.XAndYAxis
drag.minimumX: 0
drag.maximumX: box.width - parent.width
drag.minimumY: 0
drag.maximumY: box.height - parent.width

示例项目 @ code.qt.io

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