使用QML实现轮播图

今天下午想试一下用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也不会造成什么影响就不对其深究了。

发布了6 篇原创文章 · 获赞 0 · 访问量 234

猜你喜欢

转载自blog.csdn.net/qq_35342292/article/details/104333003
今日推荐