制作简易小闹钟
Timer.pro
QT += core gui texttospeechgreaterThan(QT_MAJOR_VERSION, 4): QT += widgetsCONFIG += c++11# The following define makes your compiler emit warnings if you use
# any Qt feature that has been marked deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS# You can also make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0SOURCES += \main.cpp \widget.cppHEADERS += \widget.hFORMS += \widget.ui# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target
widget.h
#ifndef WIDGET_H
#define WIDGET_H#include <QWidget>
#include <QTimerEvent> //定时器事件头文件
#include <QTimer>
#include <QtTextToSpeech>
#include <QTime>
#include <QLabel>
#include <QLineEdit>
#include <QTextEdit>
#include <QPushButton>QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACEclass Widget : public QWidget
{Q_OBJECTpublic:Widget(QWidget *parent = nullptr);~Widget();void timerEvent(QTimerEvent *e); //要重写定时器事件处理时间private slots:void on_OnBtn_clicked();void on_OffBtn_clicked();private:Ui::Widget *ui;QTimer *t1;//基于事件处理的定时器idint tId;QTextToSpeech *speech;};
#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();
}
widget.cpp
#include "widget.h"
#include "ui_widget.h"Widget::Widget(QWidget *parent): QWidget(parent), ui(new Ui::Widget)
{ui->setupUi(this);this->setWindowTitle("---迷你闹钟---");speech=new QTextToSpeech;}Widget::~Widget()
{delete ui;
}//启动按钮处理事件
void Widget::on_OnBtn_clicked()
{if(ui->OnBtn->text()=="ON"){//启动一个定时器tId=startTimer(1000); //启动一个定时器,每隔1000毫秒会自动执行timeEvent函数ui->OnBtn->setEnabled(false);ui->timeEdit->setEnabled(false);ui->textEdit->setEnabled(false);ui->currentLab->setEnabled(false);}}//停止按钮处理事件
void Widget::on_OffBtn_clicked()
{if(ui->OffBtn->text()=="OFF"){//关闭一个定时器this->killTimer(tId);ui->OnBtn->setEnabled(true);ui->OffBtn->setEnabled(false);ui->timeEdit->setEnabled(true);ui->textEdit->setEnabled(true);ui->timeEdit->clear();}
}//定时器事件处理函数定义
void Widget::timerEvent(QTimerEvent *e)
{//判断是哪个定时器到位if(e->timerId()==tId){//获取系统时间QTime sys_time=QTime::currentTime(); //QTime类对象//将时间转换成字符串QString t=sys_time.toString("hh-mm-ss"); //时分秒,都是两位数//将字符串展示到ui界面ui->currentLab->setText(t);ui->currentLab->setAlignment(Qt::AlignCenter); //将时间放在中间if(ui->timeEdit->text()==ui->currentLab->text()){QString text=ui->textEdit->toPlainText();speech->say(text);}}}
思维导图