实现一个闹钟,当输入时间后,点击启动到达时间后循环播报三遍,便签内容
头文件:
#ifndef WIDGET_H
#define WIDGET_H#include <QWidget>
#include <QTextToSpeech> //文本转语言类
#include <QTimerEvent> //定时器事件类
#include <QTime> //时间类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;//定义一个语音播报者QTextToSpeech *speecher;//定时器1的idint id1;//定时器2的idint id2;
};
#endif // WIDGET_H
源文件:
#include "widget.h"
#include "ui_widget.h"Widget::Widget(QWidget *parent): QWidget(parent), ui(new Ui::Widget)
{ui->setupUi(this);//设置一个1s定时器id1 = startTimer(1000);//居中显示label_3内容ui->label_3->setAlignment(Qt::AlignCenter);
}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");//居中显示label内容ui->label->setAlignment(Qt::AlignCenter);//让label显示当前时间ui->label->setText(s);}if(e->timerId() == id2){//获取系统当前时间QTime sys_time = QTime::currentTime();//将系统时间转换QString s = sys_time.toString("hh::mm::ss");if(ui->lineEdit->text() == s){//给语言播报者实例化空间speecher = new QTextToSpeech(this);//播报3次label_3里的内容for(int i = 0;i < 3; i++){speecher->say(ui->label_3->text());}}}
}void Widget::on_pushButton_clicked()
{//设置一个1s定时器id2 = startTimer(1000);
}
主函数文件:
#include "widget.h"#include <QApplication>int main(int argc, char *argv[])
{QApplication a(argc, argv);Widget w;w.show();return a.exec();
}
运行结果:
思维导图: