QT实现闹钟
widget.h
#ifndef WIDGET_H
#define WIDGET_H#include <QWidget>
#include<QTimerEvent>
#include<QDateTime>
#include<QLineEdit>
#include<QLabel>
#include<QPushButton>
#include <QTextToSpeech>
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACEclass Widget : public QWidget
{Q_OBJECT
signals:void my_signal();
public:Widget(QWidget *parent = nullptr);~Widget();void timerEvent(QTimerEvent *event) override;private slots:void on_btn1_clicked();void on_btn2_clicked();private:Ui::Widget *ui;int timer_id;QTextToSpeech*speecher;};
#endif // WIDGET_H
widget.cpp
#include "widget.h"
#include "ui_widget.h"Widget::Widget(QWidget *parent): QWidget(parent), ui(new Ui::Widget)
{ui->setupUi(this);ui->btn2->setEnabled(false);ui->edit->setPlaceholderText("输入要响铃的时间");speecher=new QTextToSpeech(this);connect(this,&Widget::my_signal,[&](){speecher->say(ui->textedit->toPlainText());});
}Widget::~Widget()
{delete ui;
}void Widget::on_btn1_clicked()
{//启动一个定时器timer_id=this->startTimer(1000);ui->btn1->setEnabled(false);ui->edit->setEnabled(false);ui->textedit->setEnabled(false);ui->btn2->setEnabled(true);
}
void Widget::on_btn2_clicked()
{this->killTimer(timer_id);ui->btn1->setEnabled(true);ui->edit->setEnabled(true);ui->textedit->setEnabled(true);ui->btn2->setEnabled(false);speecher->stop();
}
void Widget::timerEvent(QTimerEvent *event)
{if(event->timerId()==timer_id){QDateTime sys_dt=QDateTime::currentDateTime();//获取当前系统日期时间ui->label->setText(sys_dt.toString("yyyy-MM-dd hh:mm:ss"));if(sys_dt.toString("yyyy-MM-dd hh:mm:ss")==ui->edit->text()){emit my_signal();}}
}