计时器可以用于触发一个动作,一次或在给定的时间间隔内重复触发,在嵌入式单片机中也是非常常见。简单说设定一个周期定时值,值溢出后将触发事件,如设定起床闹钟值,时间到,闹钟响,恩,该起床干活啦~ 关闭后,如果设定了重复,那么每天都得早起哦~
1. 实例
直接推实例:
import QtQuick 2.0
import QtQuick.Window 2.12
import QtQuick.Controls 1.4
Window {
id: root;
visible: true;
width: 400;
height: 200;
Text {
id: cnt;
anchors.centerIn: parent;
color: "red";
font.pixelSize: 24; //像素大小
property int seconds : 4;
}
Timer {
id: tim;
interval: 1000;
// running: true;
repeat: true
triggeredOnStart: true;
onTriggered: {
cnt.text = cnt.seconds;
cnt.seconds --;
if(cnt.seconds <0)
{
tim.stop();
cnt.text = "Time out!!!"
}
}
}
//开始
Button {
id: startBtn;
anchors.bottom: cnt.top;
anchors.bottomMargin: 30;
anchors.right: stopBtn.left;
anchors.rightMargin: 10;
text: "Start";
onClicked: {
tim.start();
cnt.seconds = 4;
}
}
//停止
Button {
id: stopBtn;
anchors.bottom: cnt.top;
anchors.bottomMargin: 30;
anchors.horizontalCenter: cnt.horizontalCenter;
text: "Stop";
onClicked: {
tim.stop();
}
}
//重新开始
Button {
id: restartBtn;
anchors.bottom: cnt.top;
anchors.bottomMargin: 30;
anchors.left: stopBtn.right;
anchors.leftMargin: 10;
text: "Restart";
onClicked: {
tim.restart();
}
}
}
2. 运行结果
开始界面和停止界面:
重新开始界面和时间到界面:
3. 定时器详细介绍
导入声明
import QtQml 2.12
属性
● interval : int
设置触发器之间的间隔,以毫秒为单位。
默认间隔:1000毫秒。
● repeat : bool
如为真,则会重复触发计时器; 否则只触发一次,然后停止(即运行将设置为假)。
repeat,默认值为false。
● running : bool
如为真,则启动计时器; 否则停止计时器。对于不是重复的计时器,在触发计时器后将running设置为false。
running,默认为false。
● triggeredOnStart: bool
当计时器启动时,本来定时器启动后要等待设定的间隔才触发。如果triggeredOnStart为真,则在启动时立即触发计时器,然后在指定的时间间隔触发。
注意,如果repeat设置为false,则触发计时器两次;一次开始,一次周期后。
triggeredOnStart,默认为false。
信号
● triggered()
计时器超时后触发。 对应的处理程序“onTriggered”
方法
● restart()
重启定时器。如果计时器没有运行,它将被启动,否则它将重置到初始状态并启动。
● start ()
启动定时器。如果计时器已经在运行,则调用此方法无效。
● stop ()
停止计时器。如果计时器不运行,则调用此方法无效。
【参考链接】:Qt Quick事件处理之鼠标、键盘、定时器
QT QUICK QML 菜鸡教程:
● QT Quick QML入门笔记(一)应用程序结构分析和QML基础