widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QObject>
#include <QPushButton>
#include <QLineEdit>
#include <QLabel>
#include <QTimer>
#include <QString>
#include <QTime>
#include <QTextEdit>
#include <QMessageBox>
#include <QDebug>
#include <QtTextToSpeech>
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
static QTime sysTime;
QPushButton *StartUp;
QPushButton *Cancel;
QLineEdit *TimeEdit;
QTextEdit *PoetryEdit;
QLabel *SysTime;
QTextToSpeech *speech;
void timerEvent(QTimerEvent *event) override;
int timerId;
public slots:
// 显示系统时间
void SysTimeShow();
// 启动定时器
void StartTimer();
// 关闭定时器
private:
Ui::Widget *ui;
};
#endif // WIDGET_H
widget.cpp
#include "widget.h"
#include "ui_widget.h"
#include <QTextToSpeech>
QTime Widget::sysTime;
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
this->setFixedSize(500, 500);
// 启动按钮
StartUp = new QPushButton(this);
StartUp->setText("启动");
StartUp->setFixedSize(70, 40);
StartUp->move(270, 150);
connect(StartUp, &QPushButton::clicked, this, &Widget::StartTimer);
// 取消按钮
Cancel = new QPushButton(this);
Cancel->setText("取消");
Cancel->setFixedSize(70, 40);
Cancel->move(370, 150);
// 时间行编辑器
TimeEdit = new QLineEdit(this);
TimeEdit->setFixedSize(180, 40);
TimeEdit->move(270, 100);
// 诗句行编辑器
PoetryEdit = new QTextEdit(this);
PoetryEdit->setFixedSize(400, 250);
PoetryEdit->move(50, 200);
// 系统时间标签
SysTime = new QLabel(this);
SysTime->setFixedSize(190, 85);
SysTime->move(50, 100);
SysTime->setStyleSheet("background-color:rgb(248,227,228)");
SysTime->setAlignment(Qt::AlignCenter);
// 播报
speech = new QTextToSpeech(this);
timerId = startTimer(1000);
}
// 显示系统时间
void Widget::SysTimeShow()
{
Widget::sysTime = QTime::currentTime();
QString tm = Widget::sysTime.toString("hh::mm::ss");
SysTime->setText(tm);
qDebug() << tm;
}
// 启动按钮
void Widget::StartTimer()
{
// 获取输入的时间
QString TimeStr = TimeEdit->text();
QString Sys = sysTime.toString("hh::mm::ss");
qDebug() << TimeStr;
qDebug() << Sys;
}
void Widget::timerEvent(QTimerEvent *event)
{
if (event->timerId() == timerId)
{
SysTimeShow();
QString TimeStr = TimeEdit->text();
QString Sys = sysTime.toString("hh::mm::ss");
if (TimeStr == Sys)
{
// 播报诗句行编辑器中的内容
speech->say(PoetryEdit->toPlainText());
}
}
}
Widget::~Widget()
{
delete ui;
delete speech;
}
标签:Widget,定时器,QT,sysTime,StartUp,事件驱动,SysTime,new,include
From: https://blog.csdn.net/weixin_64005144/article/details/142109092