QML 实现图片帧渐隐渐显轮播

QML 实现图片帧渐隐渐显轮播

编码文章call10242025-06-18 11:22:292A+A-

前言

所谓图片帧渐隐渐显轮播就是,一组图片列表,当前图片逐渐改变透明度隐藏,同时下一张图片逐渐改变透明度显示,依次循环,达到渐隐渐显的效果,该效果常用于图片展示,相比左右自动切换的轮播方式来说,这种方式在视觉效果上不会显得太突兀。当然,这里的图片还可以换成其他组件,比如一个复杂的页面。

正文

实现方式并不复杂,有一种最常规的方式就是自己去实现每张图片的动画效果,然后控制切换,这种方式比较麻烦一些。其实 QML 有自带的组件可以实现这种效果,那就是StackView,可以通过设置delegate来自定义切换的动画效果,另外,为了保证图片是轮询切换,需要用到定时器,来不断的向StackView中push图片,但是又不能让StackView中的数据越来越多,要不然会很消耗内存。所以这里根据调整 push 的参数来实现StackView中永远都只保持一张图片。

先来看看效果图:

直接上源码:

Window {
    visible: true
    width: 420
    height: 320
    property int flag: 1
    property var imgList: [img1,img2,img3]

    StackView{
        id:stack
        anchors.fill: parent
        initialItem: img1
        delegate: StackViewDelegate{
            function transitionFinished(properties)
            {
                properties.exitItem.opacity = 1
            }
            pushTransition: StackViewTransition {
                PropertyAnimation {
                    target: enterItem
                    property: "opacity"
                    from: 0
                    to: 1
                    duration: 1500
                }
                PropertyAnimation {
                    target: exitItem
                    property: "opacity"
                    from: 1
                    to: 0
                    duration: 500
                }
            }
        }
    }
    Image {
        id: img1
        source: "1.jpg"
        visible: false
    }
    Image {
        id: img2
        source: "2.jpg"
        visible: false
    }
    Image {
        id: img3
        source: "3.jpg"
        visible: false
    }

    Timer{
        interval: 2000
        repeat: true
        running: true
        onTriggered: {
            stack.push({item:imgList[flag%3],immediate:false,replace:true})
            flag++
        }
    }
}

这里设置图片隐藏的时间为500ms,图片显示的时间为1500ms,通过定时器来不断的向 StackView中 push 数据,注意这里的 push 参数

stack.push({item:imgList[flag%3],immediate:false,replace:true})

item 是通过数组方式不断改变对象

immediate 这个必须为 false,否则不会有动画过程

replace 设置为 true,就会将新的图片覆盖原有的图片,这样可以保证StackView 中数据不会一直增加。

【领QT开发教程学习资料,点击下方链接免费领取↓↓,先码住不迷路~】

点击这里:Qt资料领取(视频教程+文档+代码+项目实战)

点击这里复制本文地址 以上内容由文彬编程网整理呈现,请务必在转载分享时注明本文地址!如对内容有疑问,请联系我们,谢谢!
qrcode

文彬编程网 © All Rights Reserved.  蜀ICP备2024111239号-4