QTimer类实现定时器或倒计时
// widget.h
typedef struct TimeHMS{
qint32 hour;
qint32 minute;
qint32 second;
}TimeHMS;
// widget.cpp
#include "widget.h"
#include "ui_widget.h"
#include <QTime>
#include <QTimer>
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
this->hms.hour = 0;
this->hms.minute = 0;
this->hms.second = 0;
m_timer = new QTimer(this);
m_timer->stop(); // 默认定时器关闭
m_timer->setSingleShot(false);
m_timer->setTimerType(Qt::PreciseTimer);
// 间隔时间 1s
m_timer->setInterval(1000);
connect(m_timer, &QTimer::timeout, this, &Widget::do_timer_timeout);
}
Widget::~Widget()
{
delete ui;
}
// 减一秒
bool Widget::subtractOneSecond()
{
// 若全部等于0,则返回false
if(hms.second <= 0 && hms.minute == 0 && hms.hour == 0){
return false;
}
// 秒钟减1
hms.second--;
if(hms.second < 0){
hms.minute--;
hms.second = 59;
if(hms.minute < 0){
hms.hour--;
hms.minute = 59;
}
}
return true;
}
void Widget::do_timer_timeout()
{
bool retBool = this->subtractOneSecond();
if(!retBool){
// 停止timer
m_timer->stop();
return;
}
ui->lcdHour->display(hms.hour);
ui->lcdMinute->display(hms.minute);
ui->lcdSecond->display(hms.second);
}
// 开始
void Widget::on_btnStart_clicked()
{
m_timer->start();
QTime tm = ui->timeEdit->time();
this->hms.hour = tm.hour();
this->hms.minute = tm.minute();
this->hms.second = tm.second();
qDebug("Hour=%d", tm.hour());
qDebug("Minute=%d", tm.minute());
qDebug("Second=%d", tm.second());
}
// 停止
void Widget::on_btnStop_clicked()
{
m_timer->stop();
}