widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QDateTime>
#include <QTimer>
#include <QTime>
#include <QTimerEvent>
#include <QDebug>
#include <QObject>
#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)override;
private slots:
void on_startbtn_clicked();
void on_closebtn_clicked();
private:
Ui::Widget *ui;
int tid_1;//闹钟号
QTextToSpeech *speech;//实例化播音员
int showFlag = true;
};
#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);
//设置标签文本居中
ui->label->setAlignment(Qt::AlignCenter);
//设置行编辑文本占位符
ui->lineEdit->setPlaceholderText("请输入时间");
//设置行编辑文本占位符
ui->textEdit->setPlaceholderText("请输入语音播报内容");
//实例化播音员
speech = new QTextToSpeech(this);
}
void Widget::timerEvent(QTimerEvent *e)
{
//如果是第一个闹钟触发
if(e->timerId() == tid_1)
{
QDateTime t1 = QDateTime::currentDateTime();//获得当前时间
QString time = t1.toString("hh:mm:ss");//当前时间转为QString类型
if(showFlag)
{
time[2]=':';
time[5]=':';
showFlag=false;
}else
{
time[2]=' ';
time[5]=' ';
showFlag =true;
}
//展示到ui界面
ui->label->setText(time);
}
//如果行编辑内容和文本编辑内容相同
if(ui->lineEdit->text() == ui->label->text())
{
//将文本编辑内容转为QString类型
QString s1 = ui->textEdit->toPlainText();
//将QString类型文本读出来
speech->say(s1);
}
}
void Widget::on_startbtn_clicked()
{
//如果启动按钮文本为 "启动"
if(ui->startbtn->text() == "启动")
{
//设置定时器1s;
tid_1 = this->startTimer(1000);
//将启动按钮变为不可启用状态
ui->startbtn->setDisabled(true);
//将关闭按钮变为可启用状态
ui->closebtn->setDisabled(false);
}
}
void Widget::on_closebtn_clicked()
{
//如果关闭按钮文本为 "关闭"
if(ui->closebtn->text() == "关闭")
{
//将启动按钮变为可启用状态
ui->startbtn->setDisabled(false);
//将关闭按钮变为不可启用状态
ui->closebtn->setDisabled(true);
//清空行编辑和文本编辑框
ui->lineEdit->clear();
ui->textEdit->clear();
//关掉定时器
killTimer(tid_1);
}
}
Widget::~Widget()
{
delete ui;
}