头文件
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QPainter>
#include <QTime>
#include <QTimerEvent>
#include <QDebug>
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
void paintEvent(QPaintEvent *event) override;
private:
Ui::Widget *ui;
//声明 事件处理函数 重载
void timerEvent(QTimerEvent *event) override;
};
#endif // WIDGET_H
原文件
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
this->startTimer(1000);
}
Widget::~Widget()
{
delete ui;
}
//时钟底座
void Widget::paintEvent(QPaintEvent *event)
{
QPainter painter(this);//实例化画家
QPen pen;//实例化笔
QFont font;//实例化字体
//画笔属性
pen.setWidth(5);
//字体属性
font.setFamily("楷体");
font.setPointSize(10);
//画家属性
painter.setPen(pen);
painter.setFont(font);
painter.translate(this->width()/2,this->height()/2);//画家坐标
//绘制圆
painter.drawEllipse(QPoint(0,0),300,300);
//绘制粗刻度
painter.rotate(-60);
for(int i = 0; i < 12; i++)
{
painter.drawLine(300,0,290,0);
painter.rotate(30);
}
//绘制细刻度
pen.setWidth(2);
painter.setPen(pen);
painter.rotate(-24);
for(int i = 0; i < 60 ; i++)
{
painter.drawLine(300,0,295,0);
painter.rotate(6);
}
//获取系统时间
QTime time = QTime::currentTime();
//绘制秒针
painter.setPen(pen);
painter.rotate(-6);
painter.rotate(6*time.second());
painter.drawLine(290,0,0,0);
painter.rotate(-6*time.second());
//绘制分针
pen.setWidth(10);
painter.setPen(pen);
painter.rotate(6*time.minute());
painter.drawLine(200,0,0,0);
painter.rotate(-6*time.minute());
//绘制时针
pen.setWidth(15);
painter.setPen(pen);
painter.rotate(30*time.hour());
painter.drawLine(100,0,0,0);
qDebug()<<time.hour()<<" "<<time.minute()<<" "<<time.second();
}
void Widget::timerEvent(QTimerEvent *event)
{
this->update();
}