QT 使用定时器完成闹钟
#include "widget.h"
#include "ui_widget.h"
void Widget::timestart()
{
timer.start(1000);
}
void Widget::timeend()
{
timer.stop();
}
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
this->resize(800,550);
this->setFixedSize(800,550);
this->setWindowTitle("Alarm");
lab1 = new QLabel(this);
lab1->resize(360,120);
lab1->move(80,80);
lab1->setStyleSheet("background-color:rgb(225, 255, 248);font: 36pt;border-radius:10px");
txtedt = new QTextEdit(this);
txtedt->resize(650,250);
txtedt->move(80,250);
txtedt->setStyleSheet("background-color:rgb(225, 255, 248);font: 36pt;border-radius:10px");
linedt1 = new QLineEdit(this);
linedt1->resize(250,50);
linedt1->move(480,80);
linedt1->setPlaceholderText("预定时间");
linedt1->setStyleSheet("background-color:rgb(225, 255, 248);font: 36pt;border-radius:10px");
btn1 = new QPushButton("启动",this);
btn1->resize(125,50);
btn1->move(480,150);
btn1->setStyleSheet("background-color:rgb(225, 255, 248);font: 36pt;border-radius:10px");
QPushButton *btn2 = new QPushButton("停止",this);
btn2->resize(125,50);
btn2->move(610,150);
btn2->setStyleSheet("background-color:rgb(225, 255, 248);font: 36pt;border-radius:10px");
speecher = new QTextToSpeech;
connect(btn1, &QPushButton::clicked, this, &Widget::timestart);
connect(btn2, &QPushButton::clicked, this, &Widget::timeend);
connect(&timer,&QTimer::timeout,this,&Widget::timer_slots);
connect(&timer,&QTimer::timeout,this,&Widget::timealarm);
}
Widget::~Widget()
{
delete ui;
}
void Widget::timer_slots()
{
QTime sysTime = QTime::currentTime();
QString time = sysTime.toString("hh : mm : ss");
lab1->setText(time);
}
void Widget::timealarm()
{
QTime sysTime = QTime::currentTime();
//将Qtime转换为Qstring
QString time = sysTime.toString("hh:mm:ss");
if(linedt1->text()==time)
{
QString msg = txtedt->toPlainText();
speecher->say(msg);
}
}
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QLabel>
#include <QTextEdit>
#include <QLineEdit>
#include <QPushButton>
#include <QTimer> //定时器类
#include <QTime>
#include <QTimerEvent>
#include <QDateTime>
#include <QtTextToSpeech> //文本转语音类
#include <QDebug>
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
public slots:
void timestart();
void timeend();
void timer_slots();
void timealarm();
public:
Widget(QWidget *parent = nullptr);
~Widget();
private:
Ui::Widget *ui;
int tid = 0;
QTimer timer;
QPushButton *btn1;
QLabel *lab1;
QTextToSpeech *speecher;
QLineEdit *linedt1;
QTextEdit *txtedt;
};
#endif // WIDGET_H