QML鼠标事件处理

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

你可能感兴趣的:(QML,Qt,qt,qml)