Qt qml 实现日期时间的实时刷新显示
程序员文章站
2024-01-04 08:25:04
...
三种实现方法:
1、最简化的一种(亲测可用)
import QtQuick 1.0
Item {
Text { id: time }
Timer {
id:timer
interval: 1000; running: true; repeat: true
onTriggered: time.text = Qt.formatDateTime(new Date(), "dddd\nyyyy-MM-dd\n-MMM-\nhh-mm-ss") // 星期 www.it165.net 年份 月份 号 大月份
}
Component.onCompleted: {
timer.start();
}
}
2、
import QtQuick 2.0
Item {
width: 300
height: 150
//显示
Text{
id: textDateTime
text: currentDateTime();
anchors.centerIn: parent
}
//当前日期时间
function currentDateTime(){
return Qt.formatDateTime(new Date(), "yyyy-MM-dd hh:mm:ss.zzz ddd");
}
//定时器
Timer{
id: timer
interval: 1 //间隔(单位毫秒):1000毫秒=1秒
repeat: true //重复
onTriggered:{
textDateTime.text = currentDateTime();
}
}
Component.onCompleted: {
timer.start();
}
}
/*
Text元素用来显示日期时间,
currentDateTime函数用来获取当前日期时间,
Timer元素用来定时刷新,实现动态呈现.
*/
效果如图:
3、更为繁琐一点的
import QtQuick 1.0
Item {
Timer {
interval: 500; running: true; repeat: true
onTriggered: time.text = getCurDate().toString()
}
function getCurDate()
{
var d = new Date();
var week;
switch (d.getDay()){
case 1: week="星期一"; break;
case 2: week="星期二"; break;
case 3: week="星期三"; break;
case 4: week="星期四"; break;
case 5: week="星期五"; break;
case 6: week="星期六"; break;
default: week="星期天";
}
var years = d.getFullYear();
var month = add_zero(d.getMonth()+1);
var days = add_zero(d.getDate());
var hours = add_zero(d.getHours());
var minutes = add_zero(d.getMinutes());
var seconds=add_zero(d.getSeconds());
var ndate = years+"-"+month+"-"+days+"\n"+hours+":"+minutes+":"+seconds;
return ndate;
}
function add_zero(temp)
{
if(temp<10) return "0"+temp;
else return temp;
}
Text { id: time }
}
参考博客:
https://my.oschina.net/jannn/blog/602235
https://blog.csdn.net/dcba2014/article/details/52879809