Qt计时器

Qt 时钟主要使用QTimer和QTime类

QTimer类

初始化QTimer对象
QTimer *timer = new QTimer;
开始计时
// void start(std::chrono::milliseconds msec)
timer->start(1000);
// 每隔 1000 毫秒发射一个timeout信号
关联timeout信号
connect(timer, &QTimer::timeout, this, &timerDemo::timeout_slot);

timeout_slot中实现增加时间,更新label显示时间

暂停计时
timer->stop();

QTime 类

初始化QTime对象
QTime *time = new QTime;
time->setHMS(0,0,0,0);
增加时间
// 增加毫秒数
*time = time->addMSecs();
格式化输出
time->toString("hh:mm:ss zzz");

完整代码

timerdemo.h
#ifndef TIMERDEMO_H
#define TIMERDEMO_H

#include 
#include 
#include 


QT_BEGIN_NAMESPACE
namespace Ui { class timerDemo; }
QT_END_NAMESPACE

class timerDemo : public QWidget
{
    Q_OBJECT

public:
    QTimer *timer;
    QTime * time;

    int count;

public:
    timerDemo(QWidget *parent = nullptr);
    ~timerDemo();

    void timeout_slot();


private slots:
    void on_startBtn_clicked();

    void on_paushBtn_clicked();

    void on_resetBtn_clicked();

    void on_bitBtn_clicked();

private:
    Ui::timerDemo *ui;
};
#endif // TIMERDEMO_H

timerdemo.cpp
#include "timerdemo.h"
#include "ui_timerdemo.h"

timerDemo::timerDemo(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::timerDemo)
    , timer(new QTimer)
    , time(new QTime)
    , count(0)
{
    ui->setupUi(this);

    connect(timer, &QTimer::timeout, this, &timerDemo::timeout_slot);
    time->setHMS(0,0,0);
    ui->timerLabel->setText(time->toString("hh:mm:ss zzz"));
}

timerDemo::~timerDemo()
{
    delete ui;
}

void timerDemo::timeout_slot()
{
    *time = time->addMSecs(30);
    ui->timerLabel->setText(time->toString("hh:mm:ss zzz"));
}


void timerDemo::on_startBtn_clicked()
{
    if (!timer->isActive())
    {
        timer->start(30);

    }
}

void timerDemo::on_paushBtn_clicked()
{
    if (timer->isActive())
    {
        timer->stop();
    }
}

void timerDemo::on_resetBtn_clicked()
{
    if (timer->isActive())
    {
        timer->stop();
    }
    time->setHMS(0,0,0);
    ui->timerLabel->setText(time->toString("hh:mm:ss zzz"));
}

void timerDemo::on_bitBtn_clicked()
{
    count += 1;
    ui->bitEdit->appendPlainText(QString("count %1 time %2").arg(count).arg(time->toString("hh:mm:ss zzz")));
}

main.cpp
#include "timerdemo.h"

#include 

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    timerDemo w;
    w.show();
    return a.exec();
}

你可能感兴趣的:(qt,qt,ui,开发语言)