看網(wǎng)上都是通過PathView來寫,但是寫出來的都是首位相連的效果,并不是想要的效果汽摹,而且又改不動(接觸QML不長成榜,無奈自己寫),而我想要的效果是從左往右,一頁顯示三個(gè),最中間的的圖片放大 。
先看效果
先分析效果圖 ,用ListView來實(shí)現(xiàn) ,首先第一個(gè)view是顯示在中間 聊疲,所以要添加一個(gè)header,然后尾部也是要顯示在中間 所以 沪悲,尾部也添加一個(gè)view
ListView{
...
header: Item {
width: listView.width / 3
height: listView.height
}
footer: Item {
width: listView.width / 3
height: listView.height
}
...
}
為什么width是listView.width/3? 因?yàn)楫?dāng)前可視界面需要顯示3個(gè)view获洲,所以 寬度都設(shè)置成listView的 1/3 就好,如果需要顯示
2個(gè) 除2就好了 依此類推殿如。
ListView{
delegate: Item {
width: listView.width / 3
height: listView.height
...
}
...
}
delegate 也是跟 頭尾一樣寬度贡珊。
計(jì)算currentIndex最爬,當(dāng)選中的view 縮放,用到onMovementEnded
方法
onMovementEnded: {
var itemWidth = listView.width / 3;
var start = contentX + itemWidth;
var newIndex = Math.floor(start / itemWidth); // 向下取整 計(jì)算出 currentIndex
listView.currentIndex = newIndex;
}
說明
比較重要的屬性
-
header
: 添加頭部 -
footer
: 添加底部 -
snapMode
:滾動時(shí)的對齊方式 例如 ListView.SnapToItem 表示滾動時(shí)會自動對齊到最近的項(xiàng)。 -
boundsBehavior
: 邊界行為门岔,例如 Flickable.StopAtBounds 表示滾動到邊界時(shí)停止爱致。
重要方法
-
onMovementEnded
:表示移動結(jié)束
全部代碼
import QtQuick 2.9
import QtQuick.Window 2.2
Window {
visible: true
width: 1080
height: 700
title: qsTr("Hello World")
id: root
property int count: 6
property int current: 4
ListView {
id: listView
anchors.fill: parent
model: root.count
currentIndex: root.current
orientation: ListView.Horizontal
snapMode: ListView.SnapToItem
boundsBehavior: Flickable.StopAtBounds
property int lastContentX: 0
header: Item {
width: listView.width / 3
height: listView.height
}
footer: Item {
width: listView.width / 3
height: listView.height
}
delegate: Item {
width: listView.width / 3
height: listView.height
Image {
anchors.fill: parent
scale: listView.currentIndex === index ? 0.9 : 0.7 //縮放大小
fillMode: Image.PreserveAspectFit
// source: root.current=== index ? "qrc:/image/test.png" : "qrc:/image/test.png" // 可以判斷顯示不同圖片
source: "qrc:/image/test.png"
// 看起來柔和點(diǎn) 添加動畫
Behavior on scale {
NumberAnimation {
duration: 100
easing.type: Easing.InOutQuad
}
}
Text {
text: index+""
font.pixelSize: 32
}
}
}
onMovementEnded: {
var itemWidth = listView.width / 3;
var start = contentX + itemWidth;
var newIndex = Math.floor(start / itemWidth);
listView.currentIndex = newIndex;
}
// 看起來柔和點(diǎn) 添加動畫
transitions: Transition {
NumberAnimation {
properties: "contentX"
duration: 100
easing.type: Easing.InOutQuad
}
}
}
Component.onCompleted: {
// 滾動到currentIndex
var itemWidth = listView.width / 3;
listView.contentX = (listView.currentIndex-1) * itemWidth
}
}