1.widget.h
#include <QPainter> //画家
#include <QTimerEvent>
#include <QTime>
#include<QTimer> //定时器类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;//定时器处理函数void timerEvent(QTimerEvent *e) override;private:Ui::Widget *ui;int timer_id;};
#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_id = this->startTimer(1000);
}Widget::~Widget()
{delete ui;
}void Widget::paintEvent(QPaintEvent *event)
{// static int num=1;//qDebug()<<num++;QPainter painter(this);//QPen pen;pen.setColor(QColor("blue"));pen.setStyle(Qt::SolidLine);pen.setWidth(5);//painter.setPen(pen);//painter.translate(this->width()/2,this->height()/2);//设置画刷和偏移坐标系painter.rotate(0);painter.setBrush(QBrush(QColor("skyblue")));//画个圆painter.drawEllipse(QPoint(0,0),100,100);for(int i=0;i<360;i+=30){painter.rotate(30);painter.drawLine(QPoint(0,-100),QPoint(0,-90));}for(int i=0;i<360;i+=6){painter.rotate(6);painter.drawLine(QPoint(0,-100),QPoint(0,-95));}//绘制时针painter.save(); // 保存当前的绘制状态// 将绘制的坐标原点移动到表盘的中心int h=ui->label->text().toInt(); // 获取当前的小时int m=ui->label_2->text().toInt(); // 获取当前的分钟double hourAngle = (h%12 + m/60.0)*30.0; // 计算时针的角度,考虑分钟对时针的影响painter.rotate(hourAngle); // 旋转坐标系,使时针指向正确的位置painter.setPen(QPen(Qt::black,5)); //设置笔painter.drawLine(QPoint(0,0),QPoint(0,-30)); // 绘制时针,起点是坐标原点 (0, 0),终点是时针的末端位置painter.restore(); // 恢复之前保存的绘制状态,以便后续绘制//绘制分针painter.save();double minuteAngle = m*6.0;painter.rotate(minuteAngle);painter.setPen(QPen(Qt::red,3)); //设置笔painter.drawLine(QPoint(0,0),QPoint(0,-50));painter.restore();//绘制秒针painter.save();int s=ui->label_3->text().toInt();double secondAngle = s * 6.0;painter.rotate(secondAngle);painter.setPen(QPen(Qt::blue,2)); //设置笔painter.drawLine(QPoint(0,0),QPoint(0,-70));painter.restore();this->update();}void Widget::timerEvent(QTimerEvent *e)
{if(e->timerId()==timer_id){QTime sys_t=QTime::currentTime();QString h=sys_t.toString("hh");QString m=sys_t.toString("mm");QString s=sys_t.toString("ss");ui->label->setText(h);ui->label_2->setText(m);ui->label_3->setText(s);}}
main.cpp
#include "widget.h"#include <QApplication>int main(int argc, char *argv[])
{QApplication a(argc, argv);Widget w;w.show();return a.exec();
}