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计时器
}
相关推荐
软件开发技术局1 小时前
撕碎QT面具(8):对控件采用自动增加函数(转到槽)的方式,发现函数不能被调用的解决方案
开发语言·qt
OopspoO2 小时前
QT事件循环
qt·事件循环
周杰伦fans2 小时前
C#中修饰符
开发语言·c#
yngsqq2 小时前
c# —— StringBuilder 类
java·开发语言
赔罪3 小时前
Python 高级特性-切片
开发语言·python
MessiGo3 小时前
OpenGL(2)基于Qt做OpenGL开发
qt
子豪-中国机器人4 小时前
2月17日c语言框架
c语言·开发语言
夏天的阳光吖4 小时前
C++蓝桥杯基础篇(四)
开发语言·c++·蓝桥杯
oioihoii4 小时前
C++17 中的 std::to_chars 和 std::from_chars:高效且安全的字符串转换工具
开发语言·c++
秋窗75 小时前
Mac下Python版本管理,适用于pyenv不起作用的情况
开发语言·python·macos