widget.h
#ifndef WIDGET_H
#define WIDGET_H#include <QWidget>
#include<QTime>//时间类
#include<QtTextToSpeech>//文本转语音类
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACEclass Widget : public QWidget
{Q_OBJECTpublic:Widget(QWidget *parent = nullptr);~Widget();void timerEvent(QTimerEvent *e);private slots:void on_startbtn_clicked();private:Ui::Widget *ui;int id1;//实例化一个语音播报者QTextToSpeech *speecher;int temp;
};
#endif // WIDGET_H
main.cpp
#include "widget.h"#include <QApplication>int main(int argc, char *argv[])
{QApplication a(argc, argv);Widget w;w.show();return a.exec();
}
widget.cpp
#include "widget.h"
#include "ui_widget.h"Widget::Widget(QWidget *parent): QWidget(parent), ui(new Ui::Widget),speecher(new QTextToSpeech(this))
{ui->setupUi(this);id1=startTimer(1000);}Widget::~Widget()
{delete ui;
}void Widget::timerEvent(QTimerEvent *e)
{if(e->timerId()==id1){//获取系统时间QTime sys_time=QTime::currentTime();//将系统时间转换成字符串QString s=sys_time.toString("hh::mm::ss");//将系统时间设置到ui界面上ui->timelab->setText(s);//居中ui->timelab->setAlignment(Qt::AlignCenter);if(ui->lineEdit->text()==ui->timelab->text()&&temp==1){for(int i=0;i<5;i++){//闹钟时间到,就开始speech,读取内容speecher->say(ui->label_3->text());}}}}//启动按钮对应的槽函数处理
void Widget::on_startbtn_clicked()
{if(ui->startbtn->text()=="启动"){ui->startbtn->setText("关闭");temp=1;}else{ui->startbtn->setText("启动");temp=0;}}
运行结果: