widget.cpp
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
///给定时器类指针实例化对象
time = new QTimer(this);
time->start(1000);
//将定时器类对象的timeout信号用Lambda表达式进行连接
connect(time,&QTimer::timeout,this,[&](){update();});
}
Widget::~Widget()
{
delete ui;
}
//绘制事件定义
void Widget::paintEvent(QPaintEvent *event)
{
//qDebug()<<"**********";
QPainter p(this);
//给画家准备画笔
p.setPen(Qt::blue);
p.setFont(QFont("黑体",30));
QBrush b(QColor("pink"));
p.setBrush(b);
//画线
//p.drawLine(10,10, 200,200);
//移动画家的起始坐标
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(2);
pen.setColor(QColor("red"));
//p.setPen(QColor("red"));
p.setPen(pen);
p.drawLine(QPoint(0,160),QPoint(0,155)); //画线(刻度
p.rotate(6);
}
for(int i =0;i<60;i++)
{
QPen pen;
pen.setWidth(5);
pen.setColor(QColor("red"));
//p.setPen(QColor("red"));
p.setPen(pen);
p.drawLine(QPoint(0,160),QPoint(0,155)); //画线(刻度
p.rotate(30);
}
//获取时间
QTime time = QTime::currentTime();
//将时间转换成字符串
QString t = time.toString("HH:mm:ss");
QStringList timelist = t.split(':'); //将字符串分割成三个字符串
hour = timelist[0].toUInt(); //将字符串转变成无符号整数
minute = timelist[1].toUInt();
secend = timelist[2].toUInt();
//时针
QPen pen;
QPainter p1(this);
p1.translate(this->width()/2,this->height()/2);
pen.setWidth(5);
pen.setColor(QColor("black"));
p1.setPen(pen);
p1.rotate(hour*30+(minute/60)*30+secend/3600*30);
p1.drawLine(QPoint(0,0),QPoint(0,-35)); //画线(刻度
//分
QPainter p2(this);
p2.translate(this->width()/2,this->height()/2);
pen.setWidth(3);
pen.setColor(QColor("blue"));
p2.setPen(pen);
p2.rotate(minute*6+secend/60*6);
p2.drawLine(QPoint(0,0),QPoint(0,-45)); //画线(刻度
//秒
QPainter p3(this);
p3.translate(this->width()/2,this->height()/2);
pen.setWidth(2);
pen.setColor(QColor("blue"));
p3.setPen(pen);
p3.rotate(secend*6);
p3.drawLine(QPoint(0,0),QPoint(0,-55)); //画线(刻度
}
main.cpp
#include "widget.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.show();
return a.exec();
}
header.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QPainter> //画家类
#include <QPaintEvent> //绘制事件类
#include <QDebug>
#include <QTimeEdit>
#include <QTimer>
#include <QDateTime>
#include <QTimerEvent>
#include <QTime>
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)override;
private:
Ui::Widget *ui;
//定义定时器类的指针
QTimer * time;
int hour;
int secend;
int minute;
};
#endif // WIDGET_H
结果如图所示
![](https://i-blog.csdnimg.cn/blog_migrate/47861ef4357bd2134986fcf7a6d062d2.png)