闹钟实现
head.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QTime>
#include <QTimer>
#include <QTimerEvent>
#include <QDateTime>
#include <QDebug>
#include <QTextToSpeech>
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
signals:
void clock();
public:
Widget(QWidget *parent = nullptr);
~Widget();
void timerEvent(QTimerEvent *e)override;
private slots:
void on_open_clicked();
void on_pushButton_2_clicked();
void on_timeout();
void my_speech();
private:
Ui::Widget *ui;
QTextToSpeech *speech;
QTimer *t1;
int tid1;
};
#endif // WIDGET_H
main.cpp
#include "widget.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.show();
return a.exec();
}
weight.cpp
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
speech = new QTextToSpeech(this);
t1 = new QTimer(this);
ui->pushButton_2->setEnabled(false);
ui->settime->setPlaceholderText("输入要定的闹钟时间");
ui->textEdit->setPlaceholderText("输入要语音播报的内容");
connect(this,SIGNAL(clock()),this,SLOT(my_speech()));
connect(t1,&QTimer::timeout,this,&Widget::on_timeout);
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_open_clicked()
{
if(ui->open->text() == "启动")
{
t1->start(1000);
ui->open->setText("关闭");
}else
{
t1->stop();
ui->open->setText("启动");
}
ui->pushButton_2->setEnabled(true);
}
void Widget::on_pushButton_2_clicked()
{
ui->settime->clear();
ui->textEdit->clear();
qDebug() << "rwerwe";
speech->say("你好");
qDebug() << "rwerwe";
}
void Widget::on_timeout()
{
QTime sys_t = QTime::currentTime();
QString time = sys_t.toString("hh:mm:ss");
ui->nowtime->setAlignment(Qt::AlignCenter);
// ui->nowtime->setTextFormat("宋体");
ui->nowtime->setText(time);
}
void Widget::timerEvent(QTimerEvent *e)
{
//通过函数调出系统日期时间
QDateTime sys_dt = QDateTime::currentDateTime();
QString da = sys_dt.toString("yyyy MM dd - hh:mm:ss");
ui->settime->setAlignment(Qt::AlignCenter);
ui->settime->setText(da);
QTime currentTime = QTime::currentTime();
QString timeString = ui->settime->text();
QTime alarmTime = QTime::fromString(timeString, "hh:mm:ss");
if(currentTime.hour() == alarmTime.hour() && currentTime.minute() == alarmTime.minute() && currentTime.second() == alarmTime.second()){
emit clock();
}
}
void Widget::my_speech()
{
speech->say(ui->textEdit->toPlainText());
}