时钟代码:
widget.h
cpp
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QPainter>
#include <QPaintEvent>
#include <QTime>
#include <QTimer>
#include <QDebug>
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
public slots:
void paintEvent(QPaintEvent *event) override;
void myupdate();
private:
Ui::Widget *ui;
//定义一个计时器
QTimer *timer;
};
#endif // WIDGET_H
widget.cpp:
cpp
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
timer = new QTimer(this);
connect(timer, &QTimer::timeout, this, &Widget::myupdate);
timer->start(1000);
}
Widget::~Widget()
{
delete ui;
}
void Widget::paintEvent(QPaintEvent *event)
{
qDebug()<<"paintEvent执行";
QTime nowtime = QTime::currentTime();
int hour = nowtime.hour();
int minute = nowtime.minute();
int second = nowtime.second();
//定义一个画家类
QPainter painter(this);
//实例化一个画笔
QPen pen; //使用无参构造
pen.setColor(QColor("blue"));
pen.setWidth(10);
//将画笔给画家安排上
painter.setPen(pen);
//给画家偏移起始坐标点
painter.translate(this->width()/2, this->height()/2);
//画个圆
painter.drawEllipse(QPoint(0,0), 200,200);
pen.setWidth(2);
painter.setPen(pen);
//12刻度实现
for(int i=1; i<=12; i++){
painter.drawLine(180, 0, 200, 0);
painter.rotate(360/12);
}
//60刻度实现
painter.save();
for(int i=1; i<=60; i++){
painter.drawLine(190, 0, 200, 0);
painter.rotate(360/60);
}
//数字实现
for(int i=12; i>=1; i--){
painter.drawText(QPoint(0, -160), QString::number(i));
painter.rotate(-360/12);
}
painter.restore();
//给画家 偏移坐标系
painter.save();
painter.rotate((hour-12)%12*360/12+180); //旋转坐标系
qDebug()<<(hour-12)%12/12*360+180;
pen.setColor(QColor("red"));
pen.setWidth(10);
painter.setPen(pen);
//画个直线 时针
painter.drawLine(0, 0, 0, 100);
//给画家 偏移坐标系
painter.restore();
painter.save();
painter.rotate(minute*360/60+second/60+180); //旋转坐标系
pen.setColor(QColor("yellow"));
pen.setWidth(5);
painter.setPen(pen);
painter.translate(0, 0);
//画个直线 分针
painter.drawLine(0, 0, 0, 125);
//给画家 偏移坐标系
painter.restore();
painter.save();
painter.rotate(second*360/60+180); //旋转坐标系
pen.setColor(QColor("pick"));
pen.setWidth(2);
painter.setPen(pen);
//画个直线 秒针
painter.drawLine(0, 0, 0, 150);
}
void Widget::myupdate()
{
update();
}
运行截图:
思维导图