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计时器
}
相关推荐
代码雕刻家6 分钟前
课设实验-数据结构-单链表-文教文化用品品牌
c语言·开发语言·数据结构
一个闪现必杀技9 分钟前
Python入门--函数
开发语言·python·青少年编程·pycharm
Fan_web12 分钟前
jQuery——事件委托
开发语言·前端·javascript·css·jquery
龙图:会赢的16 分钟前
[C语言]--编译和链接
c语言·开发语言
威桑39 分钟前
记一次控件提升后,运行却不显示的Bug
qt
FL16238631292 小时前
[深度学习][python]yolov11+bytetrack+pyqt5实现目标追踪
深度学习·qt·yolo
XKSYA(小巢校长)2 小时前
NatGo我的世界联机篇
开发语言·php
Cons.W2 小时前
Codeforces Round 975 (Div. 1) C. Tree Pruning
c语言·开发语言·剪枝
憧憬成为原神糕手2 小时前
c++_ 多态
开发语言·c++
VBA63372 小时前
VBA信息获取与处理第三个专题第三节:工作薄在空闲后自动关闭
开发语言