头文件
#ifndef WIDGET_H
#define WIDGET_H#include <QWidget>
#include <QTimerEvent>
#include <QTimer>
#include <QTime>
#include <QTextToSpeech>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_Btn_clicked();private:Ui::Widget *ui;int id,id1;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);ui->clock_timeLab->setAlignment(Qt::AlignCenter);//居中显示//启动一个定时器id = startTimer(1000);speecher = new QTextToSpeech(this);//给语音播报者实例化空间
}Widget::~Widget()
{delete ui;
}void Widget::timerEvent(QTimerEvent *e)
{if(e->timerId()==id){QTime system_time = QTime::currentTime();//获取系统当前时间QString s = system_time.toString("hh:mm:ss");//将系统时间转换ui->sys_timeLab->setText(s);//将系统时间放入到label中ui->sys_timeLab->setAlignment(Qt::AlignCenter);//居中显示}else if(e->timerId()==id1){if(ui->lineEdit->text()==ui->sys_timeLab->text())//判断条件{ui->label->setText("吃饱啦");ui->label->setAlignment(Qt::AlignCenter);for(int i=0;i<5;i++){speecher->say(ui->label->text());//语音播报者播报文本内容}ui->Btn->setText("启动");}}
}
//按钮点击的槽函数
void Widget::on_Btn_clicked()
{id1 = startTimer(1000);//启动一个定时器ui->Btn->setText("已启动");//更改文本直观看到是否启动
}
效果图
思维导图