作业
QT简易时钟
头文件
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include<QTimer>
#include<QTime>
#include<QTimerEvent>
#include<QPushButton>
#include<QLabel>
#include<QLineEdit>
#include<QDebug>
#include<QTextEdit>
#include<QtTextToSpeech/QTextToSpeech>
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
public slots:
void startTiming(); // 开始计时槽函数
void stopTiming(); // 停止计时槽函数
void checkTime(); // 检查时间槽函数
void updateDateTime(); // 更新日期时间槽函数
private:
Ui::Widget *ui;
QLabel *timeLab; //时间显示
QLineEdit *clockLin; //闹钟显示
QPushButton *startBtn; //启动按钮
QPushButton *quitBtn; //取消按钮
QTextEdit *textEdit; //闹钟文本
QTimer *t1; //定时器
QTimer *dateTimeTimer; //更新日期
QTextToSpeech *speecher; //定义播报员指针
};
#endif // WIDGET_H
源文件
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
//给播报员实例化空间
//this->speecher = new QTextToSpeech(this);
timeLab = new QLabel("",this);
timeLab->setFont(QFont("Arial",20));
timeLab->move(40,40);
updateDateTime();
clockLin = new QLineEdit("00:00",this);
clockLin->resize(300,50);
clockLin->move(400,20);
clockLin->clear();
clockLin->setPlaceholderText("请输入时间");
startBtn =new QPushButton("启动",this);
startBtn->resize(80,40);
startBtn->move(400,100);
quitBtn =new QPushButton("取消",this);
quitBtn->resize(80,40);
quitBtn->move(600,100);
textEdit = new QTextEdit("沃氏逆蝶",this);
textEdit->resize(700,300);
textEdit->move(40,200);
t1 = new QTimer(this);
dateTimeTimer = new QTimer(this);
connect(startBtn, &QPushButton::clicked, this, &Widget::startTiming);
connect(quitBtn, &QPushButton::clicked, this, &Widget::stopTiming);
connect(t1, &QTimer::timeout, this, &Widget::checkTime);
connect(dateTimeTimer, &QTimer::timeout, this, &Widget::updateDateTime);
t1->setInterval(1000); // 每秒检查一次
dateTimeTimer->start(1000); // 每秒更新时间
}
Widget::~Widget()
{
delete ui;
}
void Widget::startTiming()
{
startBtn->setEnabled(false);
quitBtn->setEnabled(true);
clockLin->setEnabled(false);
textEdit->setEnabled(false);
t1->start(1000); // 每秒检查一次
}
void Widget::stopTiming()
{
startBtn->setEnabled(true);
quitBtn->setEnabled(false);
clockLin->setEnabled(true);
textEdit->setEnabled(true);
t1->stop();
}
void Widget::checkTime()
{
QString labelTime = timeLab->text().split(" ")[1].split(".")[0];
if (labelTime == clockLin->text())
{
QString dt = textEdit->toPlainText();
qDebug()<<dt;
//speecher->say(dt);
stopTiming();
}
}
void Widget::updateDateTime()
{
timeLab->setText(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));
}