实现闹钟
头文件:
#define ALARM_CLOCK_H
#include <QWidget>
#include <QTime>
#include <QTimerEvent>
#include <QTimer>
#include <QtTextToSpeech> //文本转语音类
#include <QDebug>
QT_BEGIN_NAMESPACE
namespace Ui { class Alarm_clock; }
QT_END_NAMESPACE
class Alarm_clock : public QWidget
{
Q_OBJECT
public:
Alarm_clock(QWidget *parent = nullptr);
~Alarm_clock();
//声明重写定时器事件函数
void timerEvent(QTimerEvent *e);
private slots:
void on_start_button1_clicked(); //开始获取系统时间按钮槽函数声明
void on_start_button2_clicked(); //启动闹钟槽按钮函数声明
private:
Ui::Alarm_clock *ui;
int id1; //系统时间定时器id
int id2;//闹钟定时器id
//实例化一个语言播报者
QTextToSpeech *speecher;
};
#endif // ALARM_CLOCK_H
源文件:
#include "alarm_clock.h"
#include "ui_alarm_clock.h"
Alarm_clock::Alarm_clock(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Alarm_clock)
,speecher(new QTextToSpeech(this)) //给语言播报者实例化空间
{
ui->setupUi(this);
}
Alarm_clock::~Alarm_clock()
{
delete ui;
}
//定时器超时事件发送处理函数
void Alarm_clock::timerEvent(QTimerEvent *e)
{
if(e->timerId() == id1) //获取系统时间处理
{
//获取系统时间
QTime sys_time = QTime::currentTime();
//将系统时间转换成字符串设置到窗口上的show_systime航编辑器上
ui->show_systime->setText(sys_time.toString("hh:mm:ss"));
//居中显示
ui->show_systime->setAlignment(Qt::AlignCenter);
}
else if(e->timerId() == id2)//闹钟超时处理
{
ui->text_lable->setText("起床了,上学要迟到了");
int count = 0;
while(count<5) //循环播报5次后结束,并关闭定时器
{
speecher->say(ui->text_lable->text());
count++;
}
killTimer(id2);
ui->start_button2->setText("启动");
}
}
//开始获取系统时间按钮对应的槽函数实现
void Alarm_clock::on_start_button1_clicked()
{
if(ui->start_button1->text() == "开始")
{
//设置定时器
id1 = startTimer(1000);//每隔一秒更新系统时间在ui界面上的显示
//改变按钮文本
ui->start_button1->setText("结束");
}
else
{
killTimer(id1);
ui->start_button1->setText("开始");
}
}
//启动闹钟槽按钮函数实现
void Alarm_clock::on_start_button2_clicked()
{
if(ui->start_button2->text() == "启动")
{
QTime sys_time = QTime::currentTime();//获取系统时间
QTime alarm_clock = QTime::fromString(ui->time_Edit->text(),"hh:mm:ss");//将设置的闹钟事件从字符串转换为QTime类
int number = -alarm_clock.msecsTo(sys_time);//计算时差
//设置定时器
id2 = startTimer(number);
//改变按钮文本
ui->start_button2->setText("关闭");
}
else
{
killTimer(id2);
ui->start_button2->setText("启动");
}
}
Qt_day5作业1
思维导图: