Widget.cpp
#include "widget.h"
#include "ui_widget.h"Widget::Widget(QWidget *parent): QWidget(parent), ui(new Ui::Widget)
{ui->setupUi(this);objtimer = new QTimer (this);//连接定时器的timeout信号到启动的槽函数//connect(objtimer,&QTimer::timeout,this,&Widget::timeout_slto);sp =new QTextToSpeech(this);//初始化定时器idtimerId = -1;}Widget::~Widget()
{delete ui;
}void Widget::on_pushButton_clicked()
{if(timerId==-1){timerId = startTimer(1000);
}
}/*void Widget::timeout_slto()
{QTime sysTime = QTime::currentTime();QString time = sysTime.toString("hh:mm:ss");ui->label->setText(time);}*/
//定时器处理函数的实现
void Widget::timerEvent(QTimerEvent *t)
{if(t->timerId() == timerId){QTime sytime = QTime::currentTime();QString t2 =sytime.toString("hh:mm:ss");ui->label->setText(t2);//更新标签显示时间QString time1 = ui->lineEdit->text();if(t2==time1){sp->say("还睡呢,收你们来了");}
}
}
void Widget::on_pushButton_2_clicked()
{//objtimer->stop();killTimer(timerId);
}
Widget.h
#ifndef WIDGET_H
#define WIDGET_H#include <QWidget>
#include<QTime>
#include<QTimer>
#include<QTimerEvent>
#include<QTextToSpeech>QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACEclass Widget : public QWidget
{Q_OBJECTpublic:Widget(QWidget *parent = nullptr);~Widget();//重写定时器事件处理函数void timerEvent(QTimerEvent *t) override;
private slots:void on_pushButton_clicked();//void timeout_slto();void on_pushButton_2_clicked();private:Ui::Widget *ui;//定义一个定时器指针QTimer *objtimer;//定义一个播报员指针QTextToSpeech *sp;int timerId;};
#endif // WIDGET_H