使用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"); // 清除显示
}
相关推荐
clint4561 天前
C++进阶(1)——前景提要
c++
夜悊1 天前
C++代码示例:进制数简单生成工具
c++
郝学胜_神的一滴1 天前
CMake 021: IF 条件判据详诠
c++·cmake
_wyt0012 天前
洛谷 B3930 [GESP202312 五级] 烹饪问题 题解
c++·gesp
玖玥拾2 天前
C/C++ 数据结构(七)栈、容器适配器
c语言·数据结构·c++··容器适配器
闪闪发亮的小星星2 天前
高斯光以及高斯光公式解释
笔记
桥田智能2 天前
桥田智能 QT-650S:面向白车身焊装的 800kg 重载快换解决方案
开发语言·qt·系统架构
один but you2 天前
constexpr函数
c++
cqbzcsq2 天前
CellFlow虚拟细胞论文阅读
论文阅读·人工智能·笔记·学习·生物信息
凡人叶枫2 天前
Effective C++ 条款41:了解隐式接口和编译期多态
java·开发语言·c++·effective c++