QML鼠标事件处理

8 篇文章 0 订阅

QML鼠标事件处理

鼠标事件分为click,doubleClick,drag,hover等

笔记内容在QmlBook In Chinese.pdf文件的55页左右

click事件:

Image {
        id: root
        source: "images/background.PNG"

        Image {
            id: pole
            anchors.horizontalCenter: parent.horizontalCenter
            anchors.bottom: parent.bottom
            anchors.bottomMargin: 50
            source: "images/pole.PNG"
        }

        Image {
            id: wheel
            anchors.horizontalCenter: parent.horizontalCenter
            source: "images/pinwheel.PNG"
            Behavior on rotation {
                NumberAnimation {
                    duration: 500
                }
            }
        }

        MouseArea {
            anchors.fill: pole
            onClicked: wheel.rotation += 180
        }
    }

使用MouseArea指定点击区域,其中,
anchors.fill设置点击的范围(对象),
onclicked设置点击后的进行的操作

pressed和released事件

Rectangle {
    width: 400
    height: 200
    color: "lightblue"

    Text {
        anchors.horizontalCenter: parent.horizontalCenter
        anchors.verticalCenter: parent.verticalCenter
        text: "Press it"
        font.pixelSize: 50
        MouseArea {
            anchors.fill: parent
            onPressed: parent.color = "blue"
            onReleased: parent.color = "red"
        }
    }
}

使用onPressed设置点击时将text的文本颜色设为蓝色,
onReleased设置释放点击时text的文本颜色为红色

指定点击的鼠标键,双击处理

Text {
    anchors.horizontalCenter: parent.horizontalCenter
    anchors.verticalCenter: parent.verticalCenter
    text: "Press it"
    font.pixelSize: 50

    MouseArea {
        anchors.fill: parent
        acceptedButtons: Qt.LeftButton | Qt.RightButton
        onClicked: {
            if(mouse.button === Qt.RightButton)
                parent.color = 'pink'
            else
                parent.color = 'red'
        }

        onDoubleClicked: {
            parent.color = 'blue'
        }
    }
}

上面使用acceptedButtons: Qt.LeftButton | Qt.RightButton设置鼠标响应左键和右键,
并在onClicked中根据点击的鼠标键不同设置不同的颜色,添加doubleClicked事件

鼠标的悬停和属性

Rectangle {
    id: rect2
    anchors.top: rect1.bottom
    anchors.topMargin: 5
    width: 400
    height: 200
    color: "lightblue"
    Rectangle {
        x: 150
        y: 50
        width: 100
        height: 100
        color: mouse_area.containsMouse ? "red" : "blue"
        MouseArea {
            id: mouse_area
            anchors.fill: parent
            hoverEnabled: true
        }
    }
}
···

使用id.containMouse判断id为mouse_area的方块是否存在鼠标。   
开启hover:hoverEnabled: true
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值