widget.h :
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QTimerEvent>
#include <QTime>
#include <QLineEdit>
#include <QTextToSpeech>
#include <string.h>
#include <QByteArray>
#include <QPushButton>
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
QLineEdit *edit;
void timerEvent(QTimerEvent *e) override; //定时器事件处理函数
private slots:
void on_btn1_clicked();
void on_btn2_clicked();
private:
Ui::Widget *ui;
int timer_id; //定时器的id号
QTextToSpeech *speecher;
};
#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)
{
ui->setupUi(this);
speecher = new QTextToSpeech(this);
}
Widget::~Widget()
{
delete ui;
}
//定时器事件处理函数
void Widget::timerEvent(QTimerEvent *e)
{
//static int num = 1;
//ui->label->setNum(num++);
QString t;
if(e->timerId() == timer_id) //说明定时器1到位
{
QTime sys_t = QTime::currentTime(); //获取系统时间
//将QTime类对象转换成字符串
t = sys_t.toString("hh:mm:ss");
ui->lab1->setText(t);
}
QString s = ui->lineEdit->text();
if(s == t)
{
speecher->say(ui->textEdit->toPlainText());
}
ui->lab1->setText(t);
}
void Widget::on_btn1_clicked()
{
timer_id = this->startTimer(1000);
}
void Widget::on_btn2_clicked()
{
this->killTimer(timer_id); //关闭给定的定时器
}