作业需求:完善时钟代码
实现过程:
头文件:
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include<QPainter>
#include<QPaintEvent>
#include<QTimer> //定时器类
#include<QDateTime>
#include<QDebug>
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
void paintEvent(QPaintEvent *event) ;
private:
Ui::Widget *ui;
int count=0;
int hour;
int minute;
int second;
QTimer *timer;
};
#endif // WIDGET_H
源文件
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
timer = new QTimer;
timer->start(1000);
connect(timer,&QTimer::timeout,[&](){
count++;
update();
});
QTime time=QTime::currentTime();
QString t=time.toString("HH:mm:ss");
QStringList timelist=t.split(':');
QStringList time1=t.split(':');
hour =timelist[0].toUInt();
minute =timelist[1].toUInt();
second =timelist[2].toUInt();
}
Widget::~Widget()
{
delete ui;
}
void Widget::paintEvent(QPaintEvent *event)
{
//qDebug()<<"******************";
QPainter p(this);
//给画家准备画笔
p.setPen(Qt::blue);
p.setFont(QFont("黑体",10));
//画线
//p.drawLine(10,10,200,200);
QBrush b(QColor("pink"));
p.setBrush(b);
//移动画家的起始坐标
p.translate(this->width()/2,this->height()/2);
//旋转坐标
//p.rotate(45);
//画椭圆
p.drawEllipse(QPoint(0,0),160,160);
for(int i=0;i<60;i++)
{
QPen pen;
pen.setWidth(3);
pen.setColor(QColor("green"));
p.setPen(pen);
p.drawLine(QPoint(0,160),QPoint(0,157));
p.rotate(6);
}
for(int i=1;i<13;i++)
{
QPen pen;
p.rotate(30);
pen.setWidth(5);
pen.setColor(QColor("green"));
p.setPen(pen);
p.drawLine(QPoint(0,160),QPoint(0,155));
}
for(int i=1;i<13;i++)
{
if(i==10)
{
p.rotate(-3);
}
QPen pen;
p.rotate(30);
pen.setColor(QColor("green"));
p.setPen(pen);
QFont font1("宋体",12);
p.setFont(font1);
p.drawText(0,-120,tr("%1").arg(i));
if(i==12)
{
p.rotate(3);
}
}
QPen pen1;
pen1.setWidth(10);
pen1.setColor(QColor("black"));
p.setPen(pen1);
p.rotate(30*hour+30*minute/60+30*second/60/12+30*count/60/12);
p.drawLine(QPoint(0,0),QPoint(0,-50));
p.rotate(360-(30*hour+30*minute/60+30*second/60/12+30*count/60/12));
QPen pen2;
pen2.setWidth(7);
pen2.setColor(QColor("black"));
p.setPen(pen2);
p.rotate(6*minute+6*second/60+6*count/60);
p.drawLine(QPoint(0,0),QPoint(0,-80));
p.rotate(360-(6*minute+6*second/60+6*count/60));
QPen pen3;
pen3.setWidth(7);
pen3.setColor(QColor("black"));
p.setPen(pen3);
p.rotate(6*second+6*count);
p.drawLine(QPoint(0,0),QPoint(0,-100));
p.rotate(360-(6*second+6*count));
}
实验结果:
![](https://i-blog.csdnimg.cn/blog_migrate/9c52ac43233f1941f5dd531188825909.png)