📝 QML鼠标事件

示例代码 #

import QtQuick 2.15
import QtQuick.Controls 2.15

ApplicationWindow {
    visible: true
    width: 640
    height: 480

    Rectangle {
        id: container
        width: 200
        height: 200
        color: "lightblue"

        MouseArea {
            anchors.fill: parent
            onEntered: {
                console.log("Mouse entered")
                container.color = "lightgreen"
            }
            onExited: {
                console.log("Mouse exited")
                container.color = "lightblue"
            }
        }
    }
}

问题描述 #

鼠标进入矩形区域时,不会改变矩形的颜色。

解决方法 #

需要在MouseArea中设置hoverEnabled: true属性,这样鼠标进入矩形区域时,会触发onEntered事件,改变矩形的颜色。