QT 实现Listview鼠标点击高亮移动到对应的位置

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    //高亮移动的速度
    }

效果图:可以用键盘控制,也可以用鼠标控制。代码中的model没有给出,需要自行更改
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_39139505/article/details/102974651