第一步,在头文件中定义一个QLabel,用来呈现当前时间
QLabel * ShowTimeLabel = NULL;
第二步,定义一个槽函数,用来和定时器配合,不间断刷新时间
private slots:
void TimeUpdate();
第三步,在cpp文件中, 实现TimeUpdate函数,头文件有QTime,QTimer
void MainWindow::TimeUpdate()
{
QDateTime CurrentTime=QDateTime::currentDateTime();
QString strTime=CurrentTime.toString(" yyyy年MM月dd日 hh:mm:ss "); //设置显示的格式
ShowTimeLabel->setText(strTime);
}
第四步,实例化第一步定义的Label,然后绑定定时器
QTimer *timer=new QTimer(this);
timer->start(1000); // 每次触发timeout信号时间间隔为1秒
connect(timer,SIGNAL(timeout()),this,SLOT(TimeUpdate()));
ShowTimeLabel = new QLabel(this);
ShowTimeLabel->setFixedSize(2000,30);
ShowTimeLabel->setStyleSheet("font:30px;");
ShowTimeLabel->show();
这一步中可以自己定义大小,字体等。最终效果如下: