QT implements Listview mouse click to highlight and move to the corresponding position

Component{
        id:higlight
        Rectangle{
            color:"lightsteelblue";
            radius:5
            y:menu_listview.currentItem.y
            Behavior on y{
                SpringAnimation{
                    spring: 1;
                    damping:0.2 
                }
            }
        }
    }
    
ListView{
        id:menu_listview
        width: parent.width
        height: parent.height
        model: menu_model
        delegate:Item {
            id: menu_item
            width: 100
            height: 20
            Column{
                x:5
                y:5
                Text {
                    text: model.text
                }
            }
			//添加鼠标事件
            MouseArea{
                anchors.fill: parent
                onClicked: {
                    menu_listview.currentIndex=index     //重点是这句,currentIndex变化,高亮位置随之变化
                    console.log(menu_listview.currentIndex)
                }
            }
        }
        onCurrentIndexChanged: {
            console.log(currentIndex)
        }

        highlight: higlight
        focus: true                    //可以用鼠标控制高亮位置
        keyNavigationWraps: true        //高亮到最后一个元素是否返回第一个元素
        highlightMoveVelocity: 1000    //高亮移动的速度
    }

Effect picture: It can be controlled by keyboard or mouse. The model in the code is not given, you need to change it yourself
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_39139505/article/details/102974651