一、思维导图
二、闹钟
头文件代码
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QTime> //时间类
#include <QTimer> //时间事件类
#include <QTimerEvent> //定时器事件类
#include <QMouseEvent> //鼠标事件类
#include <QPoint> //向量类
#include <QMessageBox> //对话框类
#include <QDebug>
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
//重写timerEvent()函数的声明
void timerEvent(QTimerEvent *e);
/*鼠标事件函数声明*/
void mousePressEvent(QMouseEvent *event) override; //按下
void mouseMoveEvent(QMouseEvent *event) override; //移动
private slots:
void on_startBtn_clicked();
private:
Ui::Widget *ui;
int id; //定时器id
QPoint p; //记录当前鼠标位置
QTime alarmTime; //闹钟时间
};
#endif // WIDGET_H
源文件代码
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
this->setWindowFlag(Qt::FramelessWindowHint); //纯净窗口
this->setAttribute(Qt::WA_TranslucentBackground); //去黑框
QDate sys_date = QDate::currentDate();
QString date = sys_date.toString("yyyy年MM月dd日");
ui->dataLabel->setText(date);
//启动一个定时器
id = startTimer(1000); //每秒自动执行timerEvent()
}
Widget::~Widget()
{
delete ui;
}
//定时器超时自动执行功能函数
void Widget::timerEvent(QTimerEvent *e)
{
int count = 0;
if(e->timerId() == id)
{
//获取系统时间
QTime sys_time = QTime::currentTime();
//时间转换字符串
QString time = sys_time.toString("hh:mm:ss");
//将系统时间放入lab
ui->timeLabel->setText(time);
//文本居中显示
ui->timeLabel->setAlignment(Qt::AlignCenter);
if(sys_time >= alarmTime && !alarmTime.isNull())
{
ui->textEdit->setText("时间到了!");
// qDebug() << "时间到了";
count++;
if(count == 10) //闹钟响一分钟
{
alarmTime = QTime();
ui->textEdit->setText("~~~~~~~");
count = 0;
}
}
}
}
//重写鼠标按下事件函数实现
void Widget::mousePressEvent(QMouseEvent *event)
{
//当前窗口坐标
p = event->pos();
}
//重写鼠标移动事件函数实现
void Widget::mouseMoveEvent(QMouseEvent *event)
{
//判断是否是左键按下
if(event->buttons() == Qt::LeftButton)
{
//窗口移动
this->move(event->globalPos() - p);
//全局坐标 当前窗口坐标
}
}
void Widget::on_startBtn_clicked()
{
alarmTime = QTime::fromString(ui->clockEdit->text(), "hh:mm:ss");
if(alarmTime.isValid())
{
QMessageBox msg(QMessageBox::Information,
"提示",
"闹钟设置成功",
QMessageBox::Ok,
this);
msg.exec();
}
else
{
QMessageBox msg(QMessageBox::Warning,
"警告",
"格式设置有误",
QMessageBox::Ok,
this);
msg.exec();
}
}