- 定时器方法
- start()
启动定时器。如果定时器已经在运行,则调用此方法无效 - restart()
重启定时器,如果定时器没有运行,它将被启动,否则它将重置到初始状态并启动 - stop()
停止定时器
- 例子1
import QtQuick 2.12
import QtQuick.Window 2.12
Window {
visible: true
width: 450
height: 480
title: qsTr("timer")
Rectangle{
id: rect
anchors.fill: parent
color: "green"
Rectangle{
id:rect1
x:0
y:0
width: 50
height: 480
color:"orange"
}
}
Timer{
id: time
interval: 1000 //时间间隔,单位毫秒,默认1000
repeat: true //启动重复触发,默认false
running: true //启动定时器,默认false
triggeredOnStart: false //true,则定时器在启动后立即触发,然后再在指定的时间间隔触发;
//设置为false,则触发器触发两次,一次是启动后,一次是周期后。默认为false
onTriggered: {
if(rect1.x + rect1.width < rect.width)
{
rect1.x += 50
}else{
rect1.x = 0;
}
}
}
}
- 计时器2
在Text对象中自定义了一个属性num,用来记录当前的计数值。定义定时器,时间间隔为1s,在其信号处理函数中设置Text的值为当前的计数值,且1s递减一次。当num减到0时,代表计数结束,定时器随之停止
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")
Text {
id: text
anchors.centerIn: parent
color: "red"
text: "10"
font.pixelSize: 50
property int num: 10
}
Timer{
id: time
interval: 1000
repeat: true
triggeredOnStart: true
onTriggered: {
text.text = text.num
text.num--
if(text.num < 0)
{
time.stop()
text.text = "计时结束"
}
}
}
Button{
id:start
anchors.top: text.bottom
anchors.topMargin: 100
x:170
text: "start"
onClicked: {
time.start()
}
}
Button{
id:restart
anchors.top: text.bottom
anchors.topMargin: 100
anchors.left: start.right
anchors.leftMargin: 10
text: "restart"
onClicked: {
time.start()
text.num = 10
}
}
Button{
id:stop
anchors.top: text.bottom
anchors.topMargin: 100
anchors.left: restart.right
anchors.leftMargin: 10
text: "stop"
onClicked: {
time.stop()
}
}
}