QT计时器

widget.h

cpp 复制代码
#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QTimerEvent> //计时器类
#include <QTime> //时间类
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE

class Widget : public QWidget
{
    Q_OBJECT

public:
    Widget(QWidget *parent = nullptr);
    ~Widget();
    void timerEvent(QTimerEvent *e);//计时器函数

private slots:
    void on_pushButton_clicked();

    void on_pushButton_2_clicked();

private:
    Ui::Widget *ui;
    int tid; 
    int naozhong;
    QTime time;
};
#endif // WIDGET_H

widget.cpp

cpp 复制代码
#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    tid = startTimer(1000);//启动计时器
    ui->naozhongEdit->setPlaceholderText("请输入闹钟时间");
    ui->naozhongEdit->setFont(QFont("Agency FB",20,50,false));
   

}

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

void Widget::timerEvent(QTimerEvent *e)
{
    if(e->timerId() == tid)//系统时间的计时器事件
    {
        time = QTime::currentTime();//获取当前时间
        QString s = time.toString("hh:mm:ss");//将时间内容转换为qstring类型
        ui->sys_time_Lab->setText(s);//设置标签中内容
        ui->sys_time_Lab->setFont(QFont("Agency FB",80,50,false));//设置标签字体
        ui->sys_time_Lab->setAlignment(Qt::AlignCenter);//设置字体居中
    }
    if(e->timerId() == naozhong)//设置闹钟的计时器事件
    {
        time = QTime::currentTime();
        QString s = time.toString("hh:mm:ss");
        ui->sys_time_Lab->setText(s);
        if(s == ui->naozhongEdit->text())//如果系统时间与设置时间一致
        {
            ui->naozhongLab->setText("起床辣!!!!!");//显示内容
            ui->naozhongLab->setFont(QFont("Agency FB",60,50,false));//内容字体
        }
    }
}

void Widget::on_pushButton_clicked()
{
    naozhong = startTimer(1000);//点击开始设置naozhong计时器
}

void Widget::on_pushButton_2_clicked()
{
    killTimer(naozhong);//点击停止关闭naozhong计时器
}
相关推荐
希望20171 小时前
Golang Panic & Throw & Map/Channel 并发笔记
开发语言·golang
朗迹 - 张伟1 小时前
Golang安装笔记
开发语言·笔记·golang
yzx9910131 小时前
生活在数字世界:一份人人都能看懂的网络安全生存指南
运维·开发语言·网络·人工智能·自动化
小周同学@1 小时前
谈谈对this的理解
开发语言·前端·javascript
橙*^O^*安2 小时前
Go 语言基础:变量与常量
运维·开发语言·后端·golang·kubernetes
NiKo_W2 小时前
Linux 文件系统与基础指令
linux·开发语言·指令
工程师小星星3 小时前
Golang语言的文件组织方式
开发语言·后端·golang
乂爻yiyao3 小时前
java 代理模式实现
java·开发语言·代理模式
张子夜 iiii3 小时前
实战项目-----Python+OpenCV 实现对视频的椒盐噪声注入与实时平滑还原”
开发语言·python·opencv·计算机视觉
2301_770373733 小时前
Java集合
java·开发语言