代码:
mainwindow.h:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QDebug> // 调试类
#include <QTime> // 时间类
#include <QTimer> // 定时器类
#include <QTimerEvent> // 定时器事件类
#include <QtTextToSpeech> // 语音播报
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
protected:
void timerEvent(QTimerEvent *event)override; // 重写定时器事件处理函数
private slots:
void on_btn_start_pressed(); // 设置启动按钮的槽函数
void on_btn_stop_pressed(); // 设置关闭按钮的槽函数
private:
Ui::MainWindow *ui;
QTimer *timer; // 定时器指针
int event_time; // 用于记录闹钟的定时器
QTime alarm; // 用于记录闹钟的时间
QTextToSpeech *speech;// 用于语音播报
};
#endif // MAINWINDOW_H
mainwindow.cpp:
#include "mainwindow.h"
#include "ui_mainwindow.h"
/// 构造
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
// 设置窗口
this->setFixedSize(this->size());
this->setWindowIcon(QIcon(""));
// 时间显示
this->ui->l_current_time->setText(QTime::currentTime().toString("H:mm:ss a"));
this->startTimer(1000);
// 闹钟输入
this->ui->le_alarm_time->setText("");
this->ui->le_alarm_time->setPlaceholderText("输入闹钟时间[如: 15:02]:");
// 启动按钮
this->ui->btn_start->setEnabled(true);
// 关闭按钮
this->ui->btn_stop->setEnabled(false);
// 多行文本
this->ui->te_alarm_text->setText("");
this->ui->te_alarm_text->setPlaceholderText("请输入闹钟响铃时语音播报文本:");
// 语音播报
speech = new QTextToSpeech(this);
qDebug() << "构造完毕";
}
/// 析构
MainWindow::~MainWindow()
{
delete ui;
// 注意完全回收成员指向空间
qDebug() << "析构完毕";
}
/// 重写定时器事件处理函数
void MainWindow::timerEvent(QTimerEvent *event)
{
// 当前时间功能
this->ui->l_current_time->setText(QTime::currentTime().toString("H:mm:ss a"));
// 测试定时标识
// qDebug() << event_time << " " << event->timerId();
// 闹钟时间功能
if(event_time == event->timerId())
{
// 测试闹钟响铃
if("" == this->ui->te_alarm_text->toPlainText())
speech->say("闹钟响铃");
else
speech->say(this->ui->te_alarm_text->toPlainText());
// 清空文本
this->ui->le_alarm_time->setText("");
this->ui->te_alarm_text->setText("");
// 关闭闹钟定时
killTimer(event_time);
// 锁定关闭按钮
this->ui->btn_stop->setEnabled(false);
// 开启启动按钮
this->ui->btn_start->setEnabled(true);
}
return ;
}
/// 设置启动按钮的槽函数
void MainWindow::on_btn_start_pressed()
{
// 提取闹钟输入
int sec = this->ui->le_alarm_time->text().toInt();
// 检查闹钟时间
// 设置闹钟时间
event_time = this->startTimer(/*提取到的闹钟秒数*/sec*1000);
// 开启关闭按钮
this->ui->btn_stop->setEnabled(true);
// 锁定启动按钮
this->ui->btn_start->setEnabled(false);
qDebug() << "启动按钮";
}
/// 设置关闭按钮的槽函数
void MainWindow::on_btn_stop_pressed()
{
// 关闭闹钟定时
killTimer(event_time);
// 锁定关闭按钮
this->ui->btn_stop->setEnabled(false);
// 开启启动按钮
this->ui->btn_start->setEnabled(false);
qDebug() << "关闭按钮";
}
截图: