• QML事件处理之鼠标事件(MouseEvent)和滚轮事件(WheelEvent)


    QtQuick的可视项目结合MouseArea获取鼠标相关事件,并通过信号和处理器与鼠标进行交互。大多数MouseArea的信号都包含了一个mouse参数,它是MouseEvent类型的,例如前面使用的mouse.accepted。在MouseEvent对象中,可以设置accepted属性为true来防止鼠标事件传播到下层的项目;通过x和y属性获取鼠标的位置;通过button或buttons属性可以获取按下的按键;通过modifiers属性可以获取按下的键盘修饰符等。这里的button可取的值有Qt.LeftButton左键、Qt.RightButton右键和Qt.MiddleButton中键;而modifiers的值由多个按键进行位组合而成,在使用时需要将modifiers与这些特殊的按键进行按位与来判断按键,常用的按键有:

    • Qt.NoModifier:没有修饰键被按下;
    • Qt.ShiftModifier:Shift键被按下;
    • Qt.ControlModifier:Ctrl键被按下;
    • Qt.AltModifier:Alt键被按下;
    • Qt.MetaModifier:Meta 键被按下;
    • Qt.KeypadModifier:一个小键盘按钮被按下。
        Rectangle {
            width: 100; height: 100
            color: "green"
            MouseArea {
                anchors.fill: parent
                acceptedButtons: Qt.LeftButton | Qt.RightButton
                onClicked: {
                    if(mouse.button == Qt.RightButton)
                        parent.color = 'blue';
                    else
                        parent.color ='red';
                }
                onDoubleClicked: {
                    if((mouse.button == Qt.LeftButton) && (mouse.modifiers & Qt.ShiftModifier))
                        parent.color = "green"
                }
            }
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    除了使用MouseEvent获取鼠标按键事件,还可以使用WheelEvent获取鼠标滚轮
    事件。MouseArea的onWheel处理器有一个wheel参数,就是WheelEvent类型的。
    WheelEvent 最重要的一个属性就是 angleDelta,可以用来获取滚轮滚动的距离,它的
    x和y坐标分别保存了水平和垂直方向的增量。滚轮向上或向右滚动返回正直,向下或
    向左滚动返回负值。对于大多数鼠标,每当滚轮旋转一下,默认是15°,此时angleDelta的
    值就是15x8即整数1201。在下面的例子中,当按下Ctrl键的同时,滚轮向上滚动便放大
    字号,向下滚动便缩小字号。

        Rectangle {
            width:360; height: 360
            Text {id:myText; anchors.centerIn: parent;text: "QT"}
            MouseArea {
                anchors.fill: parent
                onWheel: {
                    if(wheel.modifiers& Qt.ControlModifier){
                        if(wheel.angleDelta.y > 0)
                            myText.font.pointSize += 1
                        else
                            myText.font.pointSize -= 1
                    }
                }
            }
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
  • 相关阅读:
    [动态规划] (十二) 简单多状态 LeetCode 213.打家劫舍II
    前端入门学习笔记三十三
    HTTP协议和Tomcat服务器
    码云Gitee单仓库最高只支持3G,中国的开源技术真的只能这么Low吗?
    Linux Vim撤销和恢复撤销快捷键
    基于Echarts实现可视化数据大屏科技业务数据统计
    Linux系统conda虚拟环境离线迁移移植
    软交换呼叫中心系统的支撑系统
    Butterworth型IIR滤波器
    RK3399驱动开发 | 09 - 基于RK808 PMIC的电源管理驱动
  • 原文地址:https://blog.csdn.net/kingzhou_/article/details/128193953