Qt 带计时器的Qml功能工作错误
我有一个QML项目,在那里我有一个定时器类。当我运行代码时,只有一个没有任何内容的白色窗口。我想当我按下“向上”按钮时,会有一个黄色的矩形显示5秒钟,在这个矩形上会写上数字“5”1秒,然后写上数字“4”1秒,以此类推,5秒钟后这个矩形就会消失 但我的代码工作方式不同,我真的很困惑Qt 带计时器的Qml功能工作错误,qt,qml,Qt,Qml,我有一个QML项目,在那里我有一个定时器类。当我运行代码时,只有一个没有任何内容的白色窗口。我想当我按下“向上”按钮时,会有一个黄色的矩形显示5秒钟,在这个矩形上会写上数字“5”1秒,然后写上数字“4”1秒,以此类推,5秒钟后这个矩形就会消失 但我的代码工作方式不同,我真的很困惑 import QtQuick 2.9 import QtQuick.Window 2.2 Window { visible: true width: 640 height: 480 Time
import QtQuick 2.9
import QtQuick.Window 2.2
Window {
visible: true
width: 640
height: 480
Timer {
id: timer
function setTimeout(cb, delayTime) {
timer.interval = delayTime;
timer.repeat = true;
timer.triggered.connect(cb);
timer.start();
}
}
Rectangle{ // This is invisible rectangle
width: 100
height: 100
focus: true
Keys.onPressed: { //
if (event.key == Qt.Key_Up){ // this is function where I change values of number
console.log(tf.counter); //this is for debugging
tf.counter = 5; // tf is id of Text
test.visible = true; // test is id of yellow rectangle
timer.setTimeout(function(){ //setTimeout is function defined in Timer
tf.counter--;
if (tf.counter > 0){
tf.text = tf.counter;
}
else {
tf.counter = 5;
tf.text = tf.counter;
test.visible = false;
timer.stop();
}
}, 1000);
}
}
}
Rectangle{
id: test
visible: false // now this is invisible
color: "yellow"
width: 100
height: 100
x: 200
y: 200
Text {
x: 5
y: 5
property int counter: 5 // this is custom property wich I assign to tf.text
id: tf
text: "5"
}
}
}
当我第一次按“向上”按钮时,它工作得很好,但第二次按“向上”之后,它工作得很奇怪,我不明白为什么。第二次,它给了我“5”,然后是“3”,然后是“1”。第三次,它给了我“4”,“1”。然后我的矩形只显示一秒钟,上面总是有随机数。请帮帮我。我非常努力地试图解决为什么这段代码不能正常工作。您的逻辑很复杂,如果建立了以下规则,那么逻辑很简单:
Window {
visible: true
width: 640
height: 480
Timer {
id: timer
onTriggered: tf.counter--; // 2
interval: 1000
repeat: true
}
Rectangle{ // This is invisible rectangle
width: 100
height: 100
focus: true
Keys.onPressed: if (event.key === Qt.Key_Up){rect.visible = true; timer.start()} // 1
}
Rectangle{
id: rect
visible: false
color: "yellow"
width: 100
height: 100
x: 200
y: 200
Text {
id: tf
x: 5
y: 5
property int counter: 5
onCounterChanged: if(counter == 0){rect.visible = false; timer.stop(); counter=5} // 3
text: counter
}
}
}
另一个解决方案:
Window {
visible: true
width: 640
height: 480
Timer {
id: timer
onTriggered: tf.counter--;
interval: 1000
repeat: true
running: tf.counter > 0
}
Rectangle{ // This is invisible rectangle
width: 100
height: 100
focus: true
Keys.onPressed: if (event.key === Qt.Key_Up && !timer.running){tf.counter = 5}
}
Rectangle{
id: rect
visible: timer.running
color: "yellow"
width: 100
height: 100
x: 200
y: 200
Text {
x: 5
y: 5
property int counter: 0
id: tf
text: counter
}
}
}