1.头文件
cpp
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QPainter>
#include <QTimer>
#include <QTime>
#include <QPaintEvent>
#include <QDebug>
#include <QBrush>
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 slots:
void updateTime();
private:
Ui::Widget *ui;
QTimer *timer;
QPixmap dial;
};
#endif // WIDGET_H
2.源文件
cpp
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
this->setFixedSize(600,600);
QTimer *timer = new QTimer(this);
connect(timer,&QTimer::timeout,this,&Widget::updateTime);
timer->start(1000);
this->setStyleSheet("background-color:white;");
}
Widget::~Widget()
{
delete ui;
}
void Widget::paintEvent(QPaintEvent *event)
{
Q_UNUSED(event);
//实例化一个画家
QPainter painter(this);
//设置绘图器(QPainter)的渲染提示,开启抗锯齿效果
painter.setRenderHint(QPainter::Antialiasing);
//获取当前时间
QTime currentTime = QTime::currentTime();
int X=this->width()/2;
int Y=this->height()/2;
int radius=200;
//绘制表盘
painter.setPen(QPen(Qt::black,7)); //设置笔
if(dial.isNull())
{
dial.load("E:\\clock.png");
}
if(!dial.isNull())
{
painter.drawPixmap(X-radius,Y-radius,radius*2,radius*2,dial);
}
//绘制时针
painter.save(); // 保存当前的绘制状态
painter.translate(X,Y); // 将绘制的坐标原点移动到表盘的中心
int hour = currentTime.hour(); // 获取当前的小时
int minute = currentTime.minute(); // 获取当前的分钟
double hourAngle = (hour%12 + minute/60.0)*30.0; // 计算时针的角度,考虑分钟对时针的影响
painter.rotate(-90); // 将坐标系旋转,使12点位置对应0度
painter.rotate(hourAngle); // 旋转坐标系,使时针指向正确的位置
painter.setPen(QPen(Qt::black,5)); //设置笔
painter.drawLine(0,0,0,-radius*0.5); // 绘制时针,起点是坐标原点 (0, 0),终点是时针的末端位置
painter.restore(); // 恢复之前保存的绘制状态,以便后续绘制
//绘制分针
painter.save();
painter.translate(X,Y);
double minuteAngle = minute*6.0;
painter.rotate(-90);
painter.rotate(minuteAngle);
painter.setPen(QPen(Qt::red,3)); //设置笔
painter.drawLine(0,0,0,-radius*0.7);
painter.restore();
//绘制秒针
painter.save();
painter.translate(X,Y);
int second = currentTime.second();
double secondAngle = second * 6.0;
painter.rotate(-90);
painter.rotate(secondAngle);
painter.setPen(QPen(Qt::blue,2)); //设置笔
painter.drawLine(0,0,0,-radius*0.9);
painter.restore();
}
void Widget::updateTime()
{
update();
}