【QML学习】触发动画

文章展示了如何在QtQuick环境中创建一个可点击的图片组件(ClickableImage.qml),该组件在点击后能执行动画效果。第1张图片自动上移,第2张和第3张图片在点击后移动,其中第3张图片点击后会返回起点并重新开始动画。主要涉及NumberAnimation和Behavior来实现动画行为。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

功能:

共有3张图片,第1张自动往上移动,第2张在窗体点击后才移动,第3张同样是窗体点击后移动,但再次点击后会回到起点处继续运行。

  • 效果演示
    在这里插入图片描述
  • 代码实现
    新建ClickableImage.qml文件封装功能
import QtQuick

Item {
    id:root
    width: container.childrenRect.width
    height:container.childrenRect.height

    property alias text:label.text
    property alias source:image.source
    signal clicked

    Column{
        id:container

        Image{
            id:image
        }

        Text{
            id:label
            width: image.width
            horizontalAlignment: Text.AlignHCenter
            wrapMode: Text.WordWrap
            color:"green"
        }
    }

    MouseArea{
        anchors.fill: parent
        onClicked: root.clicked()
    }
}

在主窗体中调用ClickableImage

import QtQuick

Window {
    id:root
    width: 640
    height: 480
    visible: true
    title: qsTr("Hello World")

    ClickableImage{
        id:cf1
        x:40
        y:root.height-height
        source:"../Image/cf.png"
        text: "This is a Cf girl"

        NumberAnimation on y{
            to:40
            duration: 3000
        }
    }

    ClickableImage{
        id:cf2
        x:40+cf1.width+30
        y:root.height-height
        source:"../Image/cf.png"
        text: "This is a Cf girl"

        Behavior on y{
            NumberAnimation{duration: 3000}
        }

        onClicked: y=40
    }

    ClickableImage{
        id:cf3
        x:cf2.x+cf1.width+30
        y:root.height-height
        source:"../Image/cf.png"
        text: "This is a Cf girl"
        onClicked: anim.restart()

        NumberAnimation{
            id:anim
            target: cf3
            to:40
            from: root.height-cf3.height
            duration: 3000
            property: "y"
        }

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值