头:
#ifndef WIDGET_H
#define WIDGET_H#include <QWidget>
#include <QTimerEvent> //定时器事件
#include <QTime> //时间类
#include <QtTextToSpeech> //文本转语音类
#include <QMouseEvent> //鼠标事件类
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_pushButton_clicked();private:Ui::Widget *ui;int id;//定时器idint flag;//实例化一个语言播报员QTextToSpeech *speecher;
};
#endif // WIDGET_H
源:
#include "widget.h"
#include "ui_widget.h"Widget::Widget(QWidget *parent): QWidget(parent), ui(new Ui::Widget), speecher(new QTextToSpeech(this)) //给播报员申请空间
{ui->setupUi(this);//启动定时器id = startTimer(1000);flag = 0;//按下启动按钮后,当到达设置的时间后开始播报}Widget::~Widget()
{delete ui;
}void Widget::timerEvent(QTimerEvent *e)
{if(e->timerId() == id){//获取系统时间QTime sys_time = QTime::currentTime();//将系统时间转换为字符串QString s = sys_time.toString("hh:mm:ss");//将系统时间在ui界面显示ui->systemLabel->setText(s);//居中显示ui->systemLabel->setAlignment(Qt::AlignCenter);}
}void Widget::on_pushButton_clicked()
{if(ui->pushButton->text() == "开始"){//开始定时flag = 1;ui->pushButton->setText("结束");}else{//中断flag = 0;ui->pushButton->setText("开始");}if(flag){if(ui->lineEdit->text() == ui->systemLabel->text()){int num = 5;while(num--){speecher->say(ui->contentLabel->text());}}}
}