在使用qml编程的过程中,有时候执行一个任务结束后需要有一个结果提示,而且这个提示等待几秒后自动消失,这个就是一个Toast提示,本文介绍的就是使用qml显示Toast效果,具体的示例代码如下:
//Toast.qml
import QtQuick 2.12
Rectangle{
id: toast
property real time: defaultTime
readonly property real defaultTime: 3000
readonly property real fadeTime: 300
property real margin: 10
property bool selfDestroying: false
width: 98
height: 98
radius: 4
opacity: 0
color: "#000000"
anchors.horizontalCenter: parent.horizontalCenter
function show(text, duration){
theText.text = text;
if(typeof duration !== "undefined"){
if(duration >= 2*fadeTime)
time = duration;
else
time = 2*fadeTime;
}
else
time = defaultTime;
anim.start();
}
Image {
id: imgHeader
anchors.top: parent.top
anchors.topMargin: 13
anchors.horizontalCenter: parent.horizontalCenter
sourceSize.width: 50
sourceSize.height: 50
source: "qrc:/image/notice_50.svg"
}
Text{
id: theText
text: ""
horizontalAlignment: Text.AlignHCenter
x: 28
y: 68
font.pixelSize: 14
color: "#ffffff"
}
SequentialAnimation on opacity {
id: anim
running: false
NumberAnimation{
to: 0.9
duration: fadeTime
}
PauseAnimation{
duration: time - 2*fadeTime
}
NumberAnimation{
to: 0
duration: fadeTime
}
onRunningChanged:{
if(!running && selfDestroying)
toast.destroy();
}
}
}
//ToastManager.qml
import QtQuick 2.12
Column{
function show(text, duration) {
var toast = toastComponent.createObject(toastManager);
toast.selfDestroying = true;
toast.show(text, duration);
}
id: toastManager
z: Infinity
spacing: 5
anchors.centerIn: parent
property var toastComponent
Component.onCompleted: toastComponent = Qt.createComponent("Toast.qml")
}
//main.qml
import QtQuick 2.12
import QtQuick.Window 2.12
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
ToastManager{ id: toast }
Rectangle {
id: rect1
width: 100;
height: 50
color: "red"
anchors.top: parent.top
anchors.left: parent.left
MouseArea {
anchors.fill: parent
onClicked: {
toast.show("已开启")
}
}
}
Rectangle {
id: rect2
width: 100;
height: 50
color: "blue"
anchors.top: parent.top
anchors.right: parent.right
MouseArea {
anchors.fill: parent
onClicked: {
toast.show("显示蓝色", 5000)
}
}
}
}
运行结果: