【QT/qml】QT实现类Android的Toast的消息提示功能

先上结果

1、使用按键1和按键2模拟模拟触发不同的消息显示在这里插入图片描述

环境

硬件:通用PC / 手机 / Jetson Xavier NX 套件
系统:Ubuntu 20.4 / Android / Windows (均测试有效)
软件 :QT6.2.4 + Qml

解决

0、思路

使用qml 提供的PropertyAnimation 动画,改变消息框的"y"值,当消息框的内容改变时,触发显示动画,动画显示完成后,触发一个定时器,定时器用于收起消息框。

1、实现

//实现一个2秒后的收起动画
    Timer {
        id: hideToast
        interval: 2000
        repeat: false
        onTriggered:  PropertyAnimation{
                    target: toast
                    property: "y"
                    from:toast.y
                    to: height
                    duration:1000
                    easing.type: Easing.Linear
                }
    }
    //当文本改变时,触发动画
     onTextChanged:         PropertyAnimation{
         id:myPropertyAnimation
         target: toast
         property: "y"
         from:toast.y
         to: height - height * 0.12
         duration:500
         easing.type: Easing.Linear
         onRunningChanged: {
             if (!running) {
                 // 动画结束后开始计时器
                 hideToast.restart();
             }
         }
     }

2、封装 MyToast.qml

    Rectangle{ //消息提示框
        id:toast
        color: "lightgray"
        y:  350
        anchors.horizontalCenter: parent.horizontalCenter
        width:message.width + 20
        height: message.height + 10
        radius: height / 2
        Text{
            id:message
            anchors.horizontalCenter: parent.horizontalCenter
            anchors.verticalCenter: parent.verticalCenter
            font.pixelSize: 25
            text: "Hello World"
            onTextChanged:         PropertyAnimation{
                id:myPropertyAnimation
                target: toast
                property: "y"
                from:toast.y
                to: height - height * 0.12
                duration:500
                easing.type: Easing.Linear
                onRunningChanged: {
                    if (!running) {
                        // 动画结束后开始计时器
                        hideToast.restart();
                    }
                }
            }
        }
    }

3、调用

	//在需要的地方改变message.text 的值即可
     Item {
        anchors.fill: parent
        Button{
            anchors.left: parent.left
            text: "按键1"
            onClicked: {
                message.text = "点了按键1"
            }
        }
        Button{
            anchors.right: parent.right
            text: "按键2"
            onClicked: {
                message.text = "点了按键2"
            }
        }
    }

OK!
至此,问题解决。欢迎留言交流

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值