目录
时钟
头文件:Widget.h:
源文件:Widget.c:
效果图:
思维导图
时钟
头文件:Widget.h:
#ifndef WIDGET_H
#define WIDGET_H#include <QWidget>
#include <QPaintEvent>
#include <QPainter>
#include <QTime>
#include <QTimerEvent>
#include <QTimer>
#include <QDebug>QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACEclass Widget : public QWidget
{Q_OBJECTpublic:Widget(QWidget *parent = nullptr);~Widget();void timerEvent(QTimerEvent *e) override;void paintEvent(QPaintEvent *event) override;private:Ui::Widget *ui;//定义一个定时器int timerId;};
#endif // WIDGET_H
源文件:Widget.c:
#include "widget.h"
#include "ui_widget.h"Widget::Widget(QWidget *parent): QWidget(parent), ui(new Ui::Widget)
{ui->setupUi(this);timerId = startTimer(1000);}Widget::~Widget()
{delete ui;
}void Widget::timerEvent(QTimerEvent *e)
{this->update();
}void Widget::paintEvent(QPaintEvent *event){//实例化一个画家QPainter Panter(this);//实例化一支画笔QPen pen;//设置画笔线形为实线pen.setStyle(Qt::SolidLine);//设置画笔宽度为5pen.setWidth(5);//设置画笔颜色为红色pen.setColor(QColor("red"));//把画笔给画家安排上Panter.setPen(pen);//将基准坐标系设为界面正中心Panter.translate(QPoint(this->width()/2,this->height()/2));//给画家设置画刷,给钟添加底色Panter.setBrush(QBrush(QColor(188, 75, 126), Qt::Dense1Pattern));//画出一个半径为200的圆,作为时钟的框架Panter.drawEllipse(QPoint(0, 0), 200, 200);for(int i=0; i<60; i++){//每6度画一个小竖杠Panter.rotate(6);pen.setColor(QColor("black"));pen.setWidth(3);Panter.setPen(pen);Panter.drawLine(QPoint(0, 192),QPoint(0,200));}for(int i=1; i<=12; i++){//每30度画一个大竖杠Panter.rotate(30);pen.setColor(QColor("black"));pen.setWidth(3);Panter.setPen(pen);Panter.drawLine(QPoint(0, 186),QPoint(0,200));}Panter.rotate(212);for(int i=1; i<=12; i++){//每30度写上文字Panter.translate(0,184);pen.setColor(QColor("black"));pen.setWidth(20);Panter.setPen(pen);//设置文本QString text = QString::number(i);Panter.drawText(QPointF(0,0),text);Panter.translate(0,-184);Panter.rotate(30);}Panter.rotate(-32+180);QTime time = QTime::currentTime();int h = time.hour();int m = time.minute();int s = time.second();QPainter painterH(this);//设置画笔线形为实线pen.setStyle(Qt::SolidLine);//设置画笔宽度为5pen.setWidth(5);//设置画笔颜色为黑色pen.setColor(QColor("black"));painterH.setPen(pen);QPainter painterM(this);painterM.setPen(pen);QPainter painterS(this);painterS.setPen(pen);//将基准坐标系设为界面正中心painterH.translate(QPoint(this->width()/2,this->height()/2));painterH.rotate((h*3600+m*60+s)/120+180);painterM.translate(QPoint(this->width()/2,this->height()/2));painterM.rotate((m*60+s)/10+180);painterS.translate(QPoint(this->width()/2,this->height()/2));painterS.rotate(s*6+180);painterH.drawLine(0,0, 0,150);painterH.save();painterM.drawLine(0,0, 0,120);painterM.save();painterS.drawLine(0,0, 0,90);painterH.save();qDebug()<<h<<":"<<m<<":"<<s;
}