有些应用程序在界面上需要显示或者设置时间和日期,可以用Qt的QTime类及相关控件来实现。
首先用Designer完成控件的拖放和布局。这里用到了LCD Number和Calender Widget两个控件。注意一下,由于我们显示的时间有6个数字加2个冒号,总共需要8个数字显示位,因此要在LCD Number的属性中设置digitCount=8。
首先是获取当前时间,通过QTime::currentTime()实现。要显示时间,需要将获取到的QTime类型的时间参数转化为可显示的QString,可用toString()方法实现。然后是“:”的闪烁功能,定时每隔一秒闪烁一次,同时LCD显示也是每隔1秒刷新一次,可以用定时器QTimer实现。LCD Number 的显示时通过QLCDNumber::display()实现的,display函数的参数可以是 int或QString。我们这里需要显示QString,参数设置为QString类型。
实现方法:
定时器:
QTimer *timer = new QTimer(this);
timer->start(1000);
connect(timer,SIGNAL(timeout()),this,SLOT(showTime()));
时间显示:
void toolbox::showTime(){
QTime time = QTime::currentTime();
QString m_time = time.toString("hh:mm:ss");
if(showColon){
m_time[5] = ':';
showColon = false;
}
else{
m_time[5] = ' ';
showColon = true;
}
ui->lcdNumber->display(m_time);
}
示例下载: 点此下载
Qt版本:Qt 5.8.0(MSVC 2015,32bit)+Qt Creator 4.2.1