Qt定时器及实现(详解)

2020-08-19 11:10:03 浏览数 (1)

QtGuiApplication5.h

代码语言:javascript复制
#pragma once

#include <QtWidgets/QMainWindow>
#include "ui_QtGuiApplication5.h"
#include <qtimer.h>
#include <QTime>

class QtGuiApplication5 : public QMainWindow
{
  Q_OBJECT

public:
  QtGuiApplication5(QWidget *parent = Q_NULLPTR);

private:
  Ui::QtGuiApplication5Class ui;
  QTimer *fTimer; //定时器
  QTime fTimeCounter;//计时器
private slots:
  void on_timer_timeout(); //定时溢出处理槽函数
  void on_btnStart_clicked();
  void on_btnStop_clicked();
};

QtGuiApplication5.cpp

代码语言:javascript复制
#include "QtGuiApplication5.h"
#include <QTime>

QtGuiApplication5::QtGuiApplication5(QWidget *parent)
  : QMainWindow(parent)
{
  ui.setupUi(this);
  fTimer = new QTimer(this);
  fTimer->stop();
  fTimer->setInterval(1000);//设置定时周期,单位:毫秒
  connect(fTimer, SIGNAL(timeout()), this, SLOT(on_timer_timeout()));
}

void QtGuiApplication5::on_timer_timeout()
{
  //定时器中断响
  QTime curTime = QTime::currentTime(); //获取当前时间
  ui.LCDHour->display(curTime.hour()); //显示小时
  ui.LCDMin->display(curTime.minute()); //显示分钟
  ui.LCDSec->display(curTime.second()); //显示秒
  int va = ui.progressBar->value();
  va  ;
  if (va > 100)
    va = 0;
  ui.progressBar->setValue(va);
}

void QtGuiApplication5::on_btnStart_clicked()
{
  fTimer->start();//定时器开始工作
  fTimeCounter.start(); //计时器开始工作
  ui.btnStart->setEnabled(false);
  ui.btnStop->setEnabled(true);
  //ui.btnSetIntv->setEnabled(false);
}
void QtGuiApplication5::on_btnStop_clicked()
{
  fTimer->stop(); //定时器停止
  int tmMsec = fTimeCounter.elapsed();//毫秒数
  int ms = tmMsec % 1000;
  int sec = tmMsec / 1000;
  QString str = QString::asprintf("流逝时间:%d 秒,%d 毫秒", sec, ms);
  //ui.LabElapsTime->setText(str);
  ui.btnStart->setEnabled(true);
  ui.btnStop->setEnabled(false);
  //ui.btnSetIntv->setEnabled(true);
}

界面显示:

0 人点赞