今天下午想試一下用QML實現輪播圖,用的是SwipeView和PageIndicator,在實現過程中,我發現會一次性出現2張圖片,後來發現只是因爲SwipeView這個組件並不是真正一次顯示一個組件,所以解決辦法就是在給它一個Rectangle作爲父組件,並且clip設爲true以截斷多出來的部分,代碼如下。
import QtQuick 2.0
import QtQuick.Controls 2.5
import QtQuick.Layouts 1.14
Rectangle {
id:userwindow;
//圖片地址數組↓
property var imagelist: ["https://tu1.whhost.net/uploads/20181011/23/1539271568-CDgeBNfqrn.jpg"
,"http://pic.haixia51.com/pic/?p=/qianqianhua/20180518/03/1526585503-fisYUGPeyv.jpg"
,"http://img.juimg.com/tuku/yulantu/110111/292-110111035J3100.jpg"];
property var i: 0;
//圖片組件
Component{
id:swipeImage;
Image{
asynchronous: true;
}
}
Rectangle{
id:rect;
width: parent.width/2;
height: parent.height/2;
anchors.top: parent.top;
anchors.topMargin: 20;
anchors.horizontalCenter: parent.horizontalCenter;
clip: true; //截斷多出來的部分
SwipeView{
id:swipeview;
anchors.fill: parent;
Timer{//3.5秒後切換圖片
id:imageSwitch;
interval: 3500;
repeat: true;
onTriggered: {
swipeview.currentIndex=(swipeview.currentIndex+1)%3;
indicator.currentIndex=swipeview.currentIndex;
}
}
}
//如果鼠標在輪播圖裏就停止,方便瀏覽
MouseArea{
anchors.fill: parent;
hoverEnabled: true;
onEntered: {
imageSwitch.stop();
}
onExited: {
imageSwitch.start();
}
}
PageIndicator{
id:indicator;
count:imagelist.length;
interactive: true;//可點擊
anchors.bottom: rect.bottom;
anchors.bottomMargin: 4;
anchors.horizontalCenter: rect.horizontalCenter;
onCurrentIndexChanged: {
swipeview.currentIndex=currentIndex;
}
}
}
//根據圖片數組的數量來決定生成組件的數量
Component.onCompleted: {
for(i;i<imagelist.length;i++)
{
swipeImage.createObject(swipeview,{"source":imagelist[i],"x":swipeview.x,"y":swipeview.y,
"width":swipeview.width,"height":swipeview.height});
}
swipeview.currentIndex=0;
imageSwitch.start();
}
期間還發現了個問題,就是PageIndicator的currentIndex和SwipeView的currentIndex都互相綁定了,但是運行起來卻沒有實現綁定,所以我只能通過觸發信號的方式來使他們協調。還有就是鼠標如果放在PageIndicator上,會當作鼠標離開了輪播圖,就算將組件放在rect下也沒有用,但是考慮到這種bug也不會造成什麼影響就不對其深究了。