实现闹钟功能
widget.h
ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QDateTime>
#include <QDateTimeEdit>
#include <QDialog>
#include <QHBoxLayout>
#include <QtTextToSpeech>
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
signals:
void mysig_alarmClock();
public:
explicit Widget(QWidget *parent = nullptr);
~Widget();
void timerEvent(QTimerEvent *event);
private slots:
void myslo_alarmClock();
void on_pushButton_2_clicked();
void on_pushButton_3_clicked();
private:
Ui::Widget *ui;
QTextToSpeech *speech;
int tid;
};
#endif // WIDGET_H
widget.cpp
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
tid = this->startTimer(1000);
connect(this,&Widget::mysig_alarmClock,this,&Widget::myslo_alarmClock);
speech = new QTextToSpeech(this);
}
Widget::~Widget()
{
delete ui;
}
void Widget::timerEvent(QTimerEvent *event)
{
if(event->timerId()==tid)
{
QDateTime sys_time = QDateTime::currentDateTime();
ui->label->setAlignment(Qt::AlignHCenter|Qt::AlignVCenter);
ui->label_2->setAlignment(Qt::AlignHCenter|Qt::AlignVCenter);
QFont font;
font.setPointSize(15);
ui->label->setFont(font);
ui->label->setText(sys_time.toString("yyyy年 M月 dd日 hh:mm:ss"));
if(ui->label->text()==ui->label_2->text())
{
emit mysig_alarmClock();
}
}
}
void Widget::myslo_alarmClock()
{
this->speech->say(ui->textEdit->toPlainText());
}
void Widget::on_pushButton_2_clicked()
{
QDialog *dialog = new QDialog(this);
QHBoxLayout *layout = new QHBoxLayout(dialog);
QDateTimeEdit *datetimeEdit = new QDateTimeEdit(QDateTime::currentDateTime(), dialog);
layout->addWidget(datetimeEdit);
datetimeEdit->setDisplayFormat("yyyy-MM-dd HH:mm:ss");
QPushButton *button = new QPushButton("OK", dialog);
layout->addWidget(button);
connect(button, &QPushButton::clicked, [=]() {
QDateTime selectedDateTime = datetimeEdit->dateTime();
ui->label_2->setText(selectedDateTime.toString("yyyy年 M月 dd日 hh:mm:ss"));
dialog->accept();
});
dialog->exec();
}
void Widget::on_pushButton_3_clicked()
{
ui->label_2->setText("闹钟关闭");
}
效果图