最近在做一个小的音乐播放器,歌词滚动效果在qml中居然可以很容易的实现。
在QML的源码中找到思路的,现在就把这种效果单独做了个demo出来。
利用的是listView的preferredHighlightBegin和preferredHighlightEnd
源文件:
main.qml
import QtQuick 2.9
import QtQuick.Window 2.2
Window {
visible: true
width: 240
height: 400
title: qsTr("Hello World")
HightRange {
width: 200
height: 400
anchors.top: parent.top
anchors.topMargin: 20
anchors.left: parent.left
anchors.leftMargin: 60
}
}
PetsModel.qml文件:
import QtQuick 2.0
ListModel {
ListElement {
name: "Polly"
type: "Parrot"
age: 12
size: "Small"
}
ListElement {
name: "Penny"
type: "Turtle"
age: 4
size: "Small"
}
ListElement {
name: "Warren"
type: "Rabbit"
age: 2
size: "Small"
}
ListElement {
name: "Spot"
type: "Dog"
age: 9
size: "Medium"
}
ListElement {
name: "Schrödinger"
type: "Cat"
age: 2
size: "Medium"
}
ListElement {
name: "Joey"
type: "Kangaroo"
age: 1
size: "Medium"
}
ListElement {
name: "Kimba"
type: "Bunny"
age: 65
size: "Large"
}
ListElement {
name: "Rover"
type: "Dog"
age: 5
size: "Large"
}
ListElement {
name: "Tiny"
type: "Elephant"
age: 15
size: "Large"
}
}
HightRange.qml文件:
import QtQuick 2.0
Rectangle {
id: root
property int current: 0
property bool increasing: true
SequentialAnimation {
id: anim
loops: -1
running: true
ScriptAction {
script: if (increasing) {
current++;
if (current >= aModel.count -1) {
current = aModel.count - 1;
increasing = !increasing;
}
} else {
current--;
if (current <= 0) {
current = 0;
increasing = !increasing;
}
}
}
PauseAnimation { duration: 500 }
}
// MouseArea{
// id: ma
// z: 1
// anchors.fill: parent
// onClicked: { z = 1 - z; if (anim.running) anim.stop(); else anim.restart();}
// }
ListView {
id: list
anchors.fill: parent
model: PetsModel {id: aModel}
delegate: petDelegate
highlight: Rectangle { color: "yellow" }
currentIndex: root.current
preferredHighlightBegin: 60
preferredHighlightEnd: 120
highlightRangeMode: ListView.StrictlyEnforceRange
}
Component {
id: petDelegate
Item {
width: 160
height: 60
Column {
id: column
Text { text: 'Name: ' + name }
Text { text: 'Type: ' + type }
Text { text: 'Age: ' + age }
}
MouseArea {
anchors.fill: parent
onClicked: root.current = index
}
}
}
}
在Qt Creator中查找highlightRangeMode
在第二项就可以找到,然后去Qt安装目录中去找qml的源码既可看到官方的demo。