实现
QTimer 定时器 、timeout()事件、singleShot事件的使用
QElapsedTimer 计数器的使用
布局
设置第一个和第二个groupBox高度为固定
timerexample.cpp
#include "timerexample.h"
#include "ui_timerexample.h"
#include "QTime"
#include "QTimer"timerExample::timerExample(QWidget *parent): QWidget(parent), ui(new Ui::timerExample)
{ui->setupUi(this);this->m_timer = new QTimer(this);this->m_timer->stop();m_timer->setTimerType(Qt::CoarseTimer);ui->radioCoarse->setChecked(true);ui->radioContinue->setChecked(true);connect(m_timer,SIGNAL(timeout()),this,SLOT(do_timer_timeout()));ui->btnStop->setEnabled(false);
}timerExample::~timerExample()
{delete ui;
}void timerExample::do_timer_timeout()
{QApplication::beep();QTime curTime = QTime::currentTime();ui->lcdHour->display(curTime.hour());ui->lcdMinute->display(curTime.minute());ui->lcdSecond->display(curTime.second());if(m_timer->isSingleShot()){int tmpElapsed= m_counter.elapsed();QString str = QString("流逝的时间:%1 毫秒").arg(tmpElapsed);ui->labElapsedTime->setText(str);ui->btnStop->setEnabled(false);ui->btnStart->setEnabled(true);ui->btnOneShot->setEnabled(true);}
}void timerExample::on_btnStart_clicked()
{//给timer设置间隔m_timer->setInterval(ui->spinInterval->value());if(ui->radioContinue->isChecked()){m_timer->setSingleShot(false);}else if(ui->radioOneShot->isChecked()){m_timer->setSingleShot(true);}if(ui->radioPrecise->isChecked()){m_timer->setTimerType(Qt::PreciseTimer);}else if(ui->radioCoarse->isChecked()){m_timer->setTimerType(Qt::CoarseTimer);}else if(ui->radioVeryCoarse->isChecked()){m_timer->setTimerType(Qt::VeryCoarseTimer);}m_timer->start();m_counter.start();ui->btnStart->setEnabled(false);ui->btnOneShot->setEnabled(false);ui->btnStop->setEnabled(true);}void timerExample::on_btnStop_clicked()
{m_timer->stop();int tmp = m_counter.elapsed();int sec= tmp/1000;QString str =QString("流逝的时间:%1秒 %2 毫秒").arg(sec).arg(tmp%1000);ui->labElapsedTime->setText(str);ui->btnStart->setEnabled(true);ui->btnOneShot->setEnabled(true);ui->btnStop->setEnabled(false);
}void timerExample::do_timer_shot()
{QApplication::beep();int tmp= m_counter.elapsed();QString str =QString("流逝的时间:%1 毫秒").arg(tmp);ui->labElapsedTime->setText(str);
}void timerExample::on_btnOneShot_clicked()
{int interval = ui->spinInterval->value();QTimer::singleShot(interval,Qt::PreciseTimer,this,&timerExample::do_timer_shot);m_counter.start();ui->btnOneShot->setEnabled(false);}
效果
步骤回顾
1、在.h文件中声明QTime *m_timer; QElaplsedTimer m_count;
2、在.h文件中声明signal do_time_out
3、在构造函数中初始化 m_timer,先停止,设置setTimeStyle 精确模式,将timer的 timeout信号绑定到槽函数
4、设置interval,启动m_timer
5、执行timeout函数