作业要求:
实现一个闹钟定时器
头文件
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QTime> //时间类
#include <QTimer> //定时器类
#include <QTimerEvent> //定时器事件处理类
#include <QDateTime> //日期时间类
#include <QDebug>
#include <QMessageBox>
#include <QTextToSpeech> //文本转语音
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = nullptr);
~Widget();
void timerEvent(QTimerEvent * e)override; //重写定时器事件函数
public slots:
void timerlabel_slot(); //自定义时钟槽函数
void on_startbtn_clicked(); //自定义启动按钮槽函数
void on_closebtn_clicked(); //自定义关闭按钮槽函数
private:
Ui::Widget *ui;
QTimer *t1; //定义一个定时器指针
int tid; //定义一个定时器的标识
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);
//实例化定时器t1
t1 = new QTimer(this);
//启动时间定时器
t1->start(0);
connect(t1,&QTimer::timeout,this,&Widget::timerlabel_slot);
//实例化语音播报
speecher = new QTextToSpeech(this);
//关闭按钮禁用
ui->closebtn->setEnabled(0);
}
Widget::~Widget()
{
delete ui;
}
void Widget::timerlabel_slot()
{
//获取当前时间
QDateTime sys_time = QDateTime::currentDateTime();
//将获取到的时间打印到ui界面
ui->timelabel->setText(sys_time.toString("yyyy MM dd hh:mm:ss"));
//将时间居中显示
ui->timelabel->setAlignment(Qt::AlignCenter);
}
void Widget::on_startbtn_clicked()
{
//启动倒计时定时器
tid = this->startTimer(0);
//信息对话框
QMessageBox::information(this,"信息","定时器启动");
//开始按钮禁用
ui->startbtn->setEnabled(0);
//将文本框禁用
ui->msgEdit->setEnabled(0);
ui->regularEdit->setEnabled(0);
//关闭按钮启用
ui->closebtn->setEnabled(1);
}
void Widget::on_closebtn_clicked()
{
//将启动按钮启用
ui->startbtn->setEnabled(1);
//将文本框启用
ui->msgEdit->setEnabled(1);
ui->regularEdit->setEnabled(1);
//关闭一个定时器
this->killTimer(tid);
}
void Widget::timerEvent(QTimerEvent *e)
{
if(e->timerId() == tid)
{
QDateTime time = QDateTime::currentDateTime();
QString msg = ui->msgEdit->toPlainText();
if(ui->regularEdit->text() == time.toString("MM dd hh:mm:ss"))
{
//语音播报
speecher->say(msg);
}
}
}
主函数
#include "widget.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.show();
return a.exec();
}
效果展示