头文件代码:
#ifndef WIDGET_H
#define WIDGET_H#include <QWidget>
#include <QTimerEvent> //定时器事件处理时间头文件
#include <QTime> //时间类
#include <QtTextToSpeech>
#include <QPushButton>
#include <QLabel>
#include <QLineEdit>
#include <QMessageBox>
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();void on_cancelbtn_clicked();private:Ui::Widget *ui;//基于事件处理的定时器idint tid;QTextToSpeech *speecher;
};
#endif // WIDGET_H
源文件代码:
#include "widget.h"
#include "ui_widget.h"Widget::Widget(QWidget *parent): QWidget(parent), ui(new Ui::Widget)
{ui->setupUi(this);speecher=new QTextToSpeech;
}Widget::~Widget()
{delete ui;
}//事件处理按钮对应的槽函数
void Widget::on_startbtn_clicked()
{if(ui->startbtn->text()=="启动"){//启动一个定时器tid=startTimer(1000);ui->sysLab->setEnabled(false);ui->lineEdit->setEnabled(false);ui->textEdit->setEnabled(false);ui->startbtn->setEnabled(false);}}
void Widget::timerEvent(QTimerEvent *e)
{//判断是哪个定时器到位if(e->timerId()==tid){//获取系统时间QTime sys_time=QTime::currentTime(); //QTime类对象//将时间转换成字符串QString t=sys_time.toString("hh-mm-ss"); //时分秒,都是两位数//将字符串展示到ui界面ui->sysLab->setText(t);ui->sysLab->setAlignment(Qt::AlignCenter); //将时间放在中间if(ui->sysLab->text()==ui->lineEdit->text()){speecher->say(ui->textEdit->toPlainText());}}
}void Widget::on_cancelbtn_clicked()
{int ret=QMessageBox::information(this,"停止提示","是否确认暂停",QMessageBox::Yes|QMessageBox::No,QMessageBox::Yes);if(ret==QMessageBox::Yes){this->killTimer(tid);ui->sysLab->setEnabled(true);ui->lineEdit->setEnabled(true);ui->textEdit->setEnabled(true);ui->startbtn->setEnabled(true);ui->lineEdit->clear();ui->textEdit->clear();}
}