使用C++编写一个语音播报时钟(Qt)

要求:当系统时间达到输入的时间时,语音播报对话框中的内容。定时可以取消。qt界面如上图所示。组件如下:

countdownEdit作为书写目标时间的line_edit

start_btn作为开始和停止的按钮

stop_btn作为取消的按钮

systimelab显示系统时间的lab

textEdit显示播报内容

代码:头文件:

cpp 复制代码
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include<QTimer>            //定时器类
#include<QTime>            //时间类
#include<QTimerEvent>       //定时器事件类
#include<QDateTime>         //日期时间类
#include <QtTextToSpeech>

QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE

class Widget : public QWidget
{
    Q_OBJECT

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

private slots:

    void on_stop_btn_clicked();
    void on_start_btn_clicked();
    void sys_time_slot();

private:
    Ui::Widget *ui;
    //定义一个定时器变量
    QTimer t1;
    int tid = 0;        //定时器id号
    //void timerEvent(QTimerEvent *event) override;
    //定时器事件处理函数的声明
    QTextToSpeech *textToSpeech;

};
#endif // WIDGET_H

程序文件:

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

Widget::Widget(QWidget *parent)
    : QWidget(parent), ui(new Ui::Widget), textToSpeech(new QTextToSpeech(this))
{
    ui->setupUi(this);
    // 由于定时器事件的信号与槽的绑定只需要一次,所以直接写在构造函数中即可
    connect(&t1, &QTimer::timeout, this, &Widget::sys_time_slot);
}

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

void Widget::on_start_btn_clicked()
{
    if (ui->start_btn->text() == "启动")
    {
        t1.start(1000); // 每隔指定的时间,发送一个systime的信号
        ui->start_btn->setText("停止");
    }
    else
    {
        t1.stop();
        ui->start_btn->setText("启动");
    }
}

void Widget::sys_time_slot()
{
    // 获取系统的时间
    QTime sysTime = QTime::currentTime();
    // 将QTime类对象转变成字符串
    QString tm = sysTime.toString("hh:mm:ss");
    // 将时间展示到ui界面上
    ui->systimelab->setText(tm);
    // 设置标签居中显示
    ui->systimelab->setAlignment(Qt::AlignCenter);
    // 比较系统时间和用户输入的时间
    if (tm == ui->countdownEdit->text())
    {
        ui->textEdit->append("三更灯火五更鸡,\n正是男儿读书时,\n黑发不知勤学早,\n白首方悔读书迟。");
        // 语音播报
        textToSpeech->say(ui->textEdit->toPlainText());
    }
}

void Widget::on_stop_btn_clicked()
{
    ui->start_btn->setText("启动");
    ui->countdownEdit->setText("00:00:00"); // 清除显示
}
相关推荐
会员源码网1 小时前
构造函数抛出异常:C++对象部分初始化的陷阱与应对策略
c++
xlp666hub3 小时前
Leetcode第二题:用 C++ 解决字母异位词分组
c++·leetcode
不想写代码的星星4 小时前
static 关键字:从 C 到 C++,一篇文章彻底搞懂它的“七十二变”
c++
xlp666hub20 小时前
Leetcode第一题:用C++解决两数之和问题
c++·leetcode
不想写代码的星星1 天前
C++继承、组合、聚合:选错了是屎山,选对了是神器
c++
不想写代码的星星2 天前
std::function 详解:用法、原理与现代 C++ 最佳实践
c++
齐生13 天前
iOS 知识点 - 渲染机制、动画、卡顿小集合
笔记
Felix_One3 天前
Qt 串口通信避坑指南:QSerialPort 的 5 个常见问题
qt
用户962377954483 天前
VulnHub DC-1 靶机渗透测试笔记
笔记·测试
樱木Plus4 天前
深拷贝(Deep Copy)和浅拷贝(Shallow Copy)
c++