qml - 如何在 qml 中给睡眠
问题描述
当我现在按下按钮时,它会立即转到下一页。是否可以让这个 loading.gif 休眠 5 秒?
我试图给它一个duration: 5000
但是它给出了一个错误
---- 完整代码更新 ----
登录.qml
import QtQuick 2.12
import QtQuick.Controls 2.12
import QtQuick.Layouts 1.15
Component
{
Rectangle
{
Rectangle
{
anchors.fill: parent
// Timer for Creating delay
Timer
{
id: timer
}
function delay(delayTime,cb)
{
timer.interval = delayTime;
timer.repeat = false;
timer.triggered.connect(cb);
timer.start();
}
ColumnLayout
{
// Some other items.
Button
{
onClicked:
{
backend.inloggen(email.text, wachtwoord.text, dropdown.currentText)
delay(5000, function()
{
loading_container.visible = true
})
stack.push(btnHomepage)
}
}
Rectangle
{
id: loading_container
visible: false
AnimatedImage
{
source: "./images/loading.gif"
}
}
}
}
}
}
错误:Login.qml:170: ReferenceError: delay is not defined
可悲的是更新 QtQuick nad QtQuick.controls 更新不是解决方案
解决方案
您可以使用Timer创建延迟,这是您的代码,我添加了一个创建延迟的函数,它的持续时间为 5000 表示 5 秒,以及一个将连接到 Timer 的函数。此功能的作用类似于单发。
import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.12
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
// Timer for Creating delay
Timer {
id: timer
}
function delay(delayTime,cb) {
timer.interval = delayTime;
timer.repeat = false;
timer.triggered.connect(cb);
timer.start();
}
Rectangle
{
id: loading_container
anchors.fill: parent
color: "#d71616"
anchors.rightMargin: 0
anchors.bottomMargin: 0
anchors.leftMargin: 0
anchors.topMargin: 60
visible: false
}
Button {
id: button
x: 0
y: 0
width: 151
height: 62
text: qsTr("Click me ")
onClicked:
{
delay(5000, function() {
loading_container.visible = true
})
}
}
}