qml ListView点击元素元素高亮实现(ListView移入到元素高亮实现)

前言

最近学习qml,在使用listview时想实现点击高亮效果,记录一波。

实现代码

import QtQuick 2.0
import QtQuick.Controls 2.15

ListView {
    width: 200
    height: 400
    model: ["Item 1", "Item 2", "Item 3", "Item 4", "Item 5"]
    
    delegate: Item {
        property bool hovered: false // 添加用于跟踪鼠标进入和退出状态的属性
        width: listView.width
        height: 40
        
        Rectangle {
            width: parent.width
            height: parent.height
            color: (listView.currentIndex === index || hovered) ? "lightblue" : "transparent"
            
            Text {
                anchors.centerIn: parent
                text: modelData
            }
            
            MouseArea {
                id: mouseArea
                anchors.fill: parent
                
                onClicked: {
                    listView.currentIndex = index
                }
                
                onEntered: {
                    hovered = true // 更新 hovered 属性来跟踪鼠标的进入和退出状态。
                }
                
                onExited: {
                    hovered = false // 更新 hovered 属性来跟踪鼠标的进入和退出状态。
                }
            }
        }
    }
}

实现效果

qml ListView点击元素元素高亮实现(ListView移入到元素高亮实现)_第1张图片

你可能感兴趣的:(QML学习,前端,linux,javascript,qml)