widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
void CalcPosition();
protected:
void timerEvent(QTimerEvent *event) override;
void paintEvent(QPaintEvent *event) override;
private:
float radius; // 半径
int xSecond,ySecond,xMinute,yMinute,xHour,yHour;
int xCenter,yCenter; // 时钟中心坐标数字
int second,minute,hour; // 时分秒实际数字
};
#endif // WIDGET_H
widget.cpp
#include "widget.h"
#include <qmath.h>
#include <QPainter>
#include <QTime>
#define PI 3.14159265
Widget::Widget(QWidget *parent)
: QWidget(parent)
{
QTime time;
radius = 100;
xCenter = 120,yCenter = 120;
// hour = 3,minute = 56,second = 55; //初始时间
QString s = time.currentTime().toString("hh:mm:ss");
hour = time.currentTime().hour(); // 当前小时
minute = time.currentTime().minute(); // 当前分
second = time.currentTime().second(); // 当前秒
CalcPosition(); //计算初始位置用于第一次显示
startTimer(1000);
}
Widget::~Widget()
{
}
void Widget::CalcPosition()
{
float secondHandLen,minuteHandLen,hourHandLen;
secondHandLen = radius * 0.8; //计算秒针长度
minuteHandLen = radius * 0.65; //计算分针长度
hourHandLen = radius * 0.5; // 计算时真长度
xSecond = xCenter+secondHandLen*cos(second * PI/30-PI/2); //计算秒针针尖位置
ySecond = yCenter+secondHandLen*sin(second * PI/30-PI/2);
xMinute = xCenter+minuteHandLen*cos(minute * PI/30-PI/2); //计算分针针尖位置
yMinute = yCenter+minuteHandLen*sin(minute * PI/30-PI/2);
xHour = xCenter+hourHandLen*cos((hour+1.0*minute/60)*PI/6-PI/2); //计算时针针尖位置
yHour = yCenter+hourHandLen*sin((hour+1.0*minute/60)*PI/6-PI/2);
}
void Widget::timerEvent(QTimerEvent *event)
{
CalcPosition();
second++;
if(second == 60){
second = 0;
minute++;
}
if(minute == 60){
minute = 0;
hour++;
}
update();
}
void Widget::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
QPen pen;
painter.drawEllipse(QPointF(120.0,120.0),radius,radius); //画圆
painter.drawLine(xCenter,yCenter,xSecond,ySecond); //画秒针 后面的两个参都是随着cos sin来算的每次触发更新圆
pen.setWidth(2); // 设置分针的宽度
painter.setPen(pen);
painter.drawLine(xCenter,yCenter,xMinute,yMinute); //画分针
pen.setWidth(4); // 设置时针的宽度
painter.setPen(pen);
painter.drawLine(xCenter,yCenter,xHour,yHour); //画时针
}
main.cpp
#include "widget.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.show();
return a.exec();
}