画一个时钟
widget.h
#ifndef WIDGET_H
#define WIDGET_H#include <QWidget>
#include <QPaintEvent>
#include <QDebug>
#include <QPainter>
#include <QTimer>
#include <QTime>QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACEclass Widget : public QWidget
{Q_OBJECTpublic:Widget(QWidget *parent = nullptr);~Widget();void paintEvent(QPaintEvent *event) override;public slots:void update_slot();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::update_slot);timer->start(1000);
}Widget::~Widget()
{delete ui;
}
void Widget::paintEvent(QPaintEvent *event)
{QPainter painter(this);QPen pen;pen.setColor(QColor("skyblue"));pen.setStyle(Qt::SolidLine);pen.setWidth(3);painter.setPen(pen);//给画家偏移起始坐标点painter.translate(this->width()/2,this->height()/2);//给画家偏移坐标系painter.rotate(0); //旋转坐标系painter.setBrush(QBrush(QColor("pink"))); //给画家设置画刷//画个圆painter.drawEllipse(QPoint(0,0),200,200);painter.setBrush(QBrush(QColor("black")));painter.drawEllipse(QPoint(0,0),10,10);//获取系统当前时间QTime time = QTime::currentTime();pen.setColor(QColor("black"));pen.setStyle(Qt::SolidLine);painter.setPen(pen);for(int i=0;i<12;i++){painter.drawLine(QPoint(0,-190),QPoint(0,-200));painter.rotate(360/12);}painter.setFont(QFont("宋体", 20, 5));painter.setPen(pen);for(int i=12;i>=1;i--){painter.drawText(QPoint(-15,-160),QString::number(i));painter.rotate(-360/12);}pen.setWidth(1);painter.setPen(pen);for(int i=0;i<60;i++){painter.drawLine(QPoint(0,-195),QPoint(0,-200));painter.rotate(360/60);}painter.save();pen.setWidth(6);painter.setPen(pen);//时针painter.rotate(30.0*(time.hour()+(time.minute()+time.second()/60)/60));painter.drawLine(QPoint(0,0),QPoint(0,-75));painter.restore();painter.save();pen.setWidth(5);painter.setPen(pen);//分针painter.rotate(6.0*(time.minute()+time.second()/60));painter.drawLine(QPoint(0,0),QPoint(0,-100));painter.restore();painter.save();//秒针painter.rotate(6.0*time.second());painter.drawLine(QPoint(0,0),QPoint(0,-100));}void Widget::update_slot()
{update();
}
测试结果
思维导图