头文件:
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QTime>
#include <QTimer>
#include <QTimerEvent>
#include <QTextToSpeech> //文本转语言类
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
void timerEvent(QTimerEvent *e);
private slots:
void on_btn1_clicked();
void on_btn2_clicked();
private:
Ui::Widget *ui;
int id;
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(this);
// 设置窗口标题
this->setWindowTitle("闹钟");
id = startTimer(1000);
}
Widget::~Widget()
{
delete ui;
}
void Widget::timerEvent(QTimerEvent *e)
{
if(e->timerId() == id)
{
QTime systime = QTime::currentTime();
QString s = systime.toString("hh:mm:ss");
ui->syslab->setText(s);
ui->syslab->setAlignment(Qt::AlignCenter);
if(ui->lineEdit->text() == s)
{
for(int i=0;i<5;i++)
{
speecher->say(ui->mvlab->text());
}
}
}
}
void Widget::on_btn1_clicked()
{
id = startTimer(1000);
}
void Widget::on_btn2_clicked()
{
killTimer(id);
}
效果图: