本节,我们要实现ListView的悬浮和选中效果。
首先我们知道悬浮效果是通过在

代码如下:
import QtQuick 2.15
import QtQuick.Controls 2.15
import com.SystemSetting 1.0
ListView {
id:myview
spacing:5
width:155
height:260
property int lastIndex: -1
header:Label{
text:"发现音乐"
leftPadding: 30
font.pixelSize: 20
color: "grey"
bottomPadding: 15
}
model:ListModel{
ListElement{
name:"为你推荐"
icon:""
}
ListElement{
name:"乐库"
icon:""
}
ListElement{
name:"歌单"
icon:""
}
ListElement{
name:"频道"
icon:""
}
ListElement{
name:"视频"
icon:""
}
ListElement{
name:"直播"
icon:""
}
}
delegate: Rectangle{
id:myRectItem
width:155
height:30
radius: 5
color:"white"
Row{
Image {
width:30
height:30
source: " "//图片资源暂时没加
}
Label{
height:30
font.pixelSize:currentIndex==index?20:15
font.bold: currentIndex==index
text: name
verticalAlignment: Text.AlignVCenter
}
}
MouseArea{
id:myarea
anchors.fill: parent
hoverEnabled: true
onExited:
if(currentIndex!=index)
myRectItem.color=Qt.rgba(1,1,1,0)
onHoveredChanged:
myRectItem.color=Qt.rgba(227/255,227/255,227/255,1)
onClicked: {
currentIndex=index
if(lastIndex!=-1)
setLastIndexItemStyle(lastIndex)
lastIndex=currentIndex
}
}
}
//由于鼠标点击事件的优先级大于鼠标离开事件,会导致我们点击下一项时,导致上一项鼠标离开事件消失,从而导致图二所示。
//为了解决这个错误,我们定义下面这个函数,并在鼠标点击时,主动调用该方法。
function setLastIndexItemStyle(flag,myindex){
if(flag===false)
myview.itemAtIndex(lastIndex).color= "white"
}
}
图2:(错误示意)
