头文件:
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QPaintEvent> //绘制事件类
#include <QPainter> //画家类
#include <QTimer>
#include <QTime>
#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
源文件:
#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.drawEllipse(QPoint(this->width()/2,this->height()/2),200,200);
painter.setBrush(QBrush(QColor("skyblue"))); //给画家设置画刷
//绘制表盘
painter.setPen(QPen(Qt::black,7)); //设置笔
if(dial.isNull())
{
dial.load("C:\\Users\\m\\Desktop\\123.jpg");
}
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(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(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(secondAngle);
painter.setPen(QPen(Qt::blue,2)); //设置笔
painter.drawLine(0,0,0,-radius*0.9);
painter.restore();
}
void Widget::updateTime()
{
update();
}