基于Qt实现一个简单的定时闹钟
头文件:AlarmTest.h
#ifndef ALARMTEST_H
#define ALARMTEST_H
#include <QWidget>
#include <QDateTimeEdit>
#include <QTimerEvent>
#include <QDateTime>
#include <QFont>
#include <QTextToSpeech>
#include <QMessageBox>
#include <QDebug>
QT_BEGIN_NAMESPACE
namespace Ui { class AlarmTest; }
QT_END_NAMESPACE
class AlarmTest : public QWidget
{
Q_OBJECT
public:
AlarmTest(QWidget *parent = nullptr);
~AlarmTest();
signals:
void over();
private slots:
void on_launchBtn_clicked();
void on_cancel_clicked();
void on_speech_over();
private:
void timerEvent(QTimerEvent *event);
private:
Ui::AlarmTest *ui;
int sysTimerid;
int alarmTimerid;
QTextToSpeech *sph;
};
#endif // ALARMTEST_H
源文件:AlarmTest.cpp
#include "alarmtest.h"
#include "ui_alarmtest.h"
AlarmTest::AlarmTest(QWidget *parent)
: QWidget(parent)
, ui(new Ui::AlarmTest)
{
ui->setupUi(this);
this->sph=new QTextToSpeech(this);
ui->label->setFont(QFont("宋体",18));
ui->textEdit->setFont(QFont("宋体",18));
ui->textEdit->setText(tr("在此处写入当闹钟到点时的系统播报内容!"));
this->sysTimerid=startTimer(1000);
QDateTime curTime=QDateTime::currentDateTime();
ui->dateTimeEdit->setDisplayFormat("yyyy/MM/dd hh:mm:ss");
ui->dateTimeEdit->setDateTime(curTime);
connect(ui->launchBtn,&QPushButton::clicked,this,&AlarmTest::on_launchBtn_clicked);
connect(ui->cancelBtn,&QPushButton::clicked,this,&AlarmTest::on_cancel_clicked);
connect(this,&AlarmTest::over,this,&AlarmTest::on_speech_over);
}
AlarmTest::~AlarmTest()
{
delete ui;
}
void AlarmTest::on_launchBtn_clicked()
{
ui->dateTimeEdit->setEnabled(false);
ui->launchBtn->setEnabled(false);
ui->textEdit->setEnabled(false);
this->alarmTimerid=startTimer(1000);
ui->dateTimeEdit->text();
}
void AlarmTest::on_cancel_clicked()
{
if(!ui->launchBtn->isEnabled()){
int ret=QMessageBox::warning(this,"Warning","您是否确定要取消当前闹钟?",
QMessageBox::Yes|QMessageBox::No);
if(ret==QMessageBox::Yes){
ui->dateTimeEdit->setEnabled(true);
ui->launchBtn->setEnabled(true);
ui->textEdit->setEnabled(true);
killTimer(this->alarmTimerid);
}
}
}
void AlarmTest::timerEvent(QTimerEvent *event)
{
QDateTime curTime=QDateTime::currentDateTime();
QString textTime=curTime.toString("yyyy/MM/dd hh:mm:ss");
if(event->timerId()==sysTimerid){
ui->label->setText(textTime);
}
if(event->timerId()==alarmTimerid){
if(textTime==ui->dateTimeEdit->text()){
emit over();
ui->dateTimeEdit->setEnabled(true);
ui->launchBtn->setEnabled(true);
ui->textEdit->setEnabled(true);
killTimer(alarmTimerid);
}
}
}
void AlarmTest::on_speech_over()
{
this->sph->say(ui->textEdit->toPlainText());
}
源文件:main.cpp
#include "alarmtest.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
AlarmTest w;
w.show();
return a.exec();
}
ui界面文件:
效果图:
开始运行: 设置并启动闹钟:取消设定的闹钟: