.h文件
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QPushButton> //按钮
#include <QTextEdit> //文本
#include <QLabel> //标签
#include <QLineEdit> //行编辑器
#include <QTimerEvent> //定时器事件类头文件
#include <QDateTime> //日期时间类
#include <QtTextToSpeech/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 *event) override;
signals:
void my_signal();
public slots:
void btn1_slots(); //启动按钮槽函数
void btn2_slots(); //关闭按钮槽函数
private:
Ui::Widget *ui;
QPushButton *btn1;
QPushButton *btn2;
QLabel *lab;
QTextEdit *text;
QLineEdit *line;
//实例化一个定时器指针
//QTimer *timer;
//定义一个定时器的id
int timer_id;
//设置一个播报员
QTextToSpeech *speecher;
};
#endif // WIDGET_H
.cpp文件
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
//设置窗口的大小
this->setFixedSize(540,410);
//设置启动按钮
btn1 = new QPushButton("启动",this);
btn1->resize(70,50);
btn1->move(340,100);
connect(btn1,&QPushButton::clicked,this,&Widget::btn1_slots);
//设置关闭按钮
btn2 = new QPushButton("关闭",this);
btn2->resize(btn1->size());
btn2->move(btn1->x()+90,btn1->y());
btn2->setEnabled(false);
connect(btn2,&QPushButton::clicked,this,&Widget::btn2_slots);
//设置定时闹钟
lab = new QLabel("闹钟",this);
lab->resize(310,150);
lab->setStyleSheet("background-color:skyblue");
//设置定的时间
line = new QLineEdit(this);
line->resize(160,50);
line->move(btn1->x(),btn1->y()-70);
//设置文本
text = new QTextEdit(this);
text->resize(540,270);
text->move(lab->x(),lab->y()+180);
text->setText("时间到了!");
//设置播报员
speecher = new QTextToSpeech;
connect(this,&Widget::my_signal,[&](){
speecher->say(this->text->toPlainText());
});
//定时器
//timer = new QTimer(this);
//将该定时的time信号连接到自定义的槽函数中
//connect(timer,&QTime::timeout,this,&Widget::timeout_slots);
}
Widget::~Widget()
{
delete ui;
}
void Widget::timerEvent(QTimerEvent *event)
{
if(event->timerId()==timer_id)
{
QDateTime sys_dt = QDateTime::currentDateTime();//获取当前系统日期时间
this->lab->setText(sys_dt.toString("yyyy-MM-dd hh:mm:ss"));
if(sys_dt.toString("yyyy-MM-dd hh:mm:ss") == this->line->text())
{
emit my_signal();
}
}
}
void Widget::btn1_slots()
{
//启动定时器
timer_id=this->startTimer(1000);
btn2->setEnabled(true);
btn1->setEnabled(false);
line->setEnabled(false);
lab->setEnabled(false);
}
void Widget::btn2_slots()
{
this->killTimer(timer_id);
btn2->setEnabled(false);
btn1->setEnabled(true);
line->setEnabled(true);
lab->setEnabled(true);
speecher->stop();
}