前言

最近学习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 属性来跟踪鼠标的进入和退出状态。
                }
            }
        }
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.

实现效果

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