QT_day5:使用定时器实现闹钟

1、

程序代码:

widget.h:

cpp 复制代码
#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QTime>//时间类
#include <QTimer>//时间事件类
#include <QTextToSpeech>//文本转语音类
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_startBtn_clicked();

private:
    Ui::Widget *ui;

    int id;//定时器id
    int id2;
    //实例化一个语音播报员
    QTextToSpeech *speech;
};
#endif // WIDGET_H

widget.cpp:

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

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
    , speech(new QTextToSpeech(this))//实例化申请空间
{
    ui->setupUi(this);
    //纯净窗口
    this->setWindowFlag(Qt::FramelessWindowHint);
    //删除空白
    this->setAttribute(Qt::WA_TranslucentBackground);

    //启动定时器
    id = startTimer(1000);//系统每隔1秒  执行timerEvent()函数
}

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

void Widget::timerEvent(QTimerEvent *e)
{
    //1、显示系统时间
    //获取系统时间QTime
    QTime sys_time = QTime::currentTime();//获取当前系统时间
    //将系统时间转换成字符串
    QString s = sys_time.toString("hh:mm:ss");

    if(e->timerId() == id)
    {
        //将系统时间设置到ui界面上的sysTime
        ui->sysTime->setText(s);
        //居中显示
        ui->sysTime->setAlignment(Qt::AlignCenter);
    }
    
    if(s == ui->Edit->text())
    {
        killTimer(id2);
        for(int i=0;i<5;i++)
        {
            speech->say(ui->tipLab->text());
        }
    }

}
//启动按钮对应的槽函数处理
void Widget::on_startBtn_clicked()
{
    //2、计时器开始计时
    //启动一个定时器
    id2 = startTimer(1000);//系统每隔1秒  执行timerEvent()函数
}

运行结果:

相关推荐
渣渣盟12 分钟前
JavaScript核心概念全解析
开发语言·javascript·es6
java叶新东老师1 小时前
goland编写go语言导入自定义包出现: package xxx is not in GOROOT (/xxx/xxx) 的解决方案
开发语言·后端·golang
檀越剑指大厂1 小时前
【Python系列】Flask 应用中的主动垃圾回收
开发语言·python·flask
檀越剑指大厂2 小时前
【Python系列】使用 memory_profiler 诊断 Flask 应用内存问题
开发语言·python·flask
笠码2 小时前
JVM Java虚拟机
java·开发语言·jvm·垃圾回收
橙小花2 小时前
C语言:指针、变量指针与指针变量、数组指针与指针数组
c语言·开发语言
Cyanto2 小时前
MyBatis-Plus高效开发实战
java·开发语言·数据库
艾莉丝努力练剑2 小时前
【LeetCode&数据结构】二叉树的应用(二)——二叉树的前序遍历问题、二叉树的中序遍历问题、二叉树的后序遍历问题详解
c语言·开发语言·数据结构·学习·算法·leetcode·链表
wjs20243 小时前
XML 语法详解
开发语言
双叶8363 小时前
(Python)文件储存的认识,文件路径(文件储存基础教程)(Windows系统文件路径)(基础教程)
开发语言·windows·python