时钟代码:
widget.h
#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_NAMESPACEclass Widget : public QWidget
{Q_OBJECTpublic: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:
#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();
}
运行截图:
思维导图