qml 为 ListView 添加鼠标经过时颜色变化

  • 显而易见,想要实现该效果需要捕获鼠标进入和离开行事件:
property bool isHover: false
MouseArea{
	anchors.fill: parent
	hoverEnabled: true
	onEntered: isHover = true
	onExited: isHover = false
	onClicked: {
		listview.currentIndex = index
		console.log(listview.currentIndex)
	}
}
  • 使用qml怎么能少得了动画, 现在增加一点颜色动画
states: [
	State { name: "true"; PropertyChanges { target: item; color : "red" } },
	State { name: "false"; PropertyChanges { target: item; color : "white" }}
]
transitions: [
	Transition { ColorAnimation { to: "red"; duration: 200 } },
	Transition { ColorAnimation { to: "white"; duration: 200  } }
]
  • 全部代码
    FxModel{
        id: fxModel
    }

    ListView{
        id: listview
        anchors.top: parent.top
        anchors.left: parent.left
        anchors.right: parent.right
        anchors.bottom: parent.bottom
        model: fxModel

        delegate: Rectangle{

            property bool isHover: false
            id:item
            width: listview.width
            height: 30
            color: isHover == true ? "red" : "white"
            state: isHover
            clip: true
            Text {
                text: qsTr(name)
            }
            MouseArea{
                anchors.fill: parent
                hoverEnabled: true
                onEntered: isHover = true
                onExited: isHover = false
            }

            states: [
                State { name: "true"; PropertyChanges { target: item; color : "red" } },
                State { name: "false"; PropertyChanges { target: item; color : "white" }}
            ]
            transitions: [
                Transition { ColorAnimation { to: "red"; duration: 200 } },
                Transition { ColorAnimation { to: "white"; duration: 200  } }
            ]
        }

    }

posted @ 2022-06-07 07:59  清楚xc  阅读(120)  评论(0)    收藏  举报