.h
#ifndef WIDGET_H
#define WIDGET_H#include <QWidget>
#include <QPaintEvent>
#include <QDebug> //信息调试类
#include <QPainter>
#include <QPixmap> //图像引擎类
#include <QTime>
#include <QTimer> //定时器类
#include <QDateTime> //日期类
#include <QTimerEvent>
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACEclass Widget : public QWidget
{Q_OBJECTpublic:Widget(QWidget *parent = nullptr);~Widget();void paintEvent(QPaintEvent *event);void timerEvent(QTimerEvent *e);
private slots:private:Ui::Widget *ui;int timer_id;//给定时器实例化一个对象QTimer * timer;int hh=0,mm=0,ss=0;
};
#endif // WIDGET_H
.cpp
#include "widget.h"
#include "ui_widget.h"Widget::Widget(QWidget *parent): QWidget(parent), ui(new Ui::Widget)
{ui->setupUi(this);timer_id=this->startTimer(1000);//给定时器实例化对象timer=new QTimer(this);// 设置窗口的大小和标题setFixedSize(500, 500);setWindowTitle("闹钟");}Widget::~Widget()
{delete ui;
}//绘制事件处理函数
void Widget::paintEvent(QPaintEvent *event)
{//实例化一个画家QPainter painter(this);// 设置反锯齿渲染painter.setRenderHint(QPainter::Antialiasing, true);//实例化一个画笔QPen pen;pen.setColor(QColor("blue"));//设置线型pen.setStyle(Qt::DashDotLine);//将画笔给画家安排上painter.setPen(pen);//设置基准坐标系painter.translate(this->width()/2,this->height()/2);//画个钟盘painter.setBrush(QBrush(QColor("skyblue")));painter.drawEllipse(QPoint(0,0),200,200);//绘制矢量文字pen.setColor(QColor("black"));painter.setPen(pen);//给画家设置字体painter.setFont(QFont("隶书",15,13));//画小时格子for(int i=1;i<=12;i++){//每转30度画一个时刻painter.rotate(30);pen.setWidth(4);painter.setPen(pen);painter.drawLine(0,-200,0,-175);painter.drawText(0,-170,QString("%1").arg(i));}//画分格子for(int i=0;i<=59;i++){painter.rotate(6);pen.setWidth(2);painter.setPen(pen);painter.drawLine(0,-200,0,-190);}//绘制矢量文字painter.translate(-this->width()/2,-this->height()/2);painter.drawText(this->rect(),Qt::AlignCenter,"啊啊,我饿了");//绘制指针pen.setWidth(5);painter.translate(this->width()/2,this->height()/2);pen.setStyle(Qt::SolidLine); //设置线型//1、绘制秒针painter.save();painter.setPen(Qt::green);painter.setBrush(Qt::green);painter.rotate(ss*6-90);painter.drawLine(0,0,160,0);painter.restore();//2、绘制分针painter.save();painter.setPen(pen);painter.setPen(Qt::red);painter.rotate(6*(mm+ss/60.0)-90);painter.drawLine(0,0,140,0);painter.restore();//3、绘制时针painter.save();//painter.translate(this->width()/2,this->height()/2);pen.setWidth(4);painter.setPen(pen);painter.setPen(Qt::black);painter.setBrush(Qt::black);painter.rotate(30*(hh+mm/60.0+ss/3600.0)-90);painter.drawLine(0,0,90,0);painter.restore();
}//定时器事件处理函数
void Widget::timerEvent(QTimerEvent *e)
{if(e->timerId() == timer_id) //说明定时器1到位{QDateTime current = QDateTime::currentDateTime(); // 获取当前系统时间QTime sys_t = current.time(); // 获取系统时间的时、分、秒hh = sys_t.hour();mm = sys_t.minute();ss = sys_t.second();update();qDebug()<<"hh:mm:ss"<<hh<<mm<<ss;}
}
main函数
#include "widget.h"#include <QApplication>int main(int argc, char *argv[])
{QApplication a(argc, argv);Widget w;w.show();return a.exec();
}