![](https://i-blog.csdnimg.cn/direct/4c1daba502e8469aa92ba883e5f7dc94.png)
widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QTextEdit>
#include <QVBoxLayout>
#include <QTimer>
#include <QDateTime>
#include<stdio.h>
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
private slots:
void on_btn1_clicked();
void on_btn2_clicked();
void updateTime();
private:
Ui::Widget *ui;
QTimer *timer;
int num;
};
#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);
timer = new QTimer(this);
connect(timer, &QTimer::timeout, this, &Widget::updateTime);
timer->start(1000);
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_btn1_clicked()
{
num=1;
ui->label2->setText("闹钟已开启");
}
void Widget::on_btn2_clicked()
{
num=0;
ui->label2->setText("闹钟已关闭");
ui->textEdit->clear();
}
void Widget::updateTime()
{
QDateTime currentDateTime = QDateTime::currentDateTime();
QString currentTimeStr = currentDateTime.toString("hh:mm:ss");
ui->label1->setText(currentTimeStr);
if (num==1){
QString alarmTimeStr = ui->lineEdit->text();
QTime alarmTime = QTime::fromString(alarmTimeStr, "hh:mm");
if (currentDateTime.time().hour() == alarmTime.hour() && currentDateTime.time().minute() == alarmTime.minute()) {
ui->textEdit->setText("起床了!");
} else {
ui->textEdit->clear();
}
}
}