作业:实现闹钟
代码:
头文件:
#ifndef WIDGET_H
#define WIDGET_H#include <QWidget>
#include <QTimerEvent> //定时器事件
#include <QTime> //时间类
#include <QtTextToSpeech> //文本转语音类
#include <QMouseEvent> //鼠标事件类
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACEclass Widget : public QWidget
{Q_OBJECTpublic:Widget(QWidget *parent = nullptr);~Widget();//声明重写定时器事件函数void timerEvent(QTimerEvent *e);private slots:void on_startbtn_clicked();private:Ui::Widget *ui;int id;//定时器idint id2;//实例化一个语言播报员QTextToSpeech *speecher;
};
#endif // WIDGET_H
源文件:
#include "widget.h"
#include "ui_widget.h"Widget::Widget(QWidget *parent): QWidget(parent), ui(new Ui::Widget), speecher(new QTextToSpeech(this)) //给播报员申请空间
{ui->setupUi(this);//启动定时器id = startTimer(0);}Widget::~Widget()
{delete ui;
}void Widget::timerEvent(QTimerEvent *e)
{if(e->timerId() == id){//获取系统时间QTime sys_time = QTime::currentTime();//将系统时间转换为字符串QString s = sys_time.toString("hh:mm:ss");//将系统时间在ui界面显示ui->timelab->setText(s);//居中显示ui->timelab->setAlignment(Qt::AlignCenter);}else if(e->timerId() == id2){//当设置的时间到达后,开始播报if(ui->timeredit->text() == ui->timelab->text()){int num = 5;while(num--){speecher->say(ui->testlab->text());}//关闭定时器killTimer(id2);}}
}//按下启动按钮
void Widget::on_startbtn_clicked()
{//按下启动按钮后,开启定时器2id2 = startTimer(0);}
效果:
1711457275783729381