1、
头文件
#ifndef MAINWINDOW_H
#define MAINWINDOW_H#include <QMainWindow>
#include <QPaintEvent> //绘制事件类
#include <QDebug> //信息调试类
#include <QPainter> //画家类
#include <QTimerEvent> //定时器事件处理类
#include <QTime>
#include <QTimer> //定时器类
#include <QDateTime> //日期时间类QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACEclass MainWindow : public QMainWindow
{Q_OBJECTpublic:MainWindow(QWidget *parent = nullptr);~MainWindow();//重写绘制事件处理函数void paintEvent(QPaintEvent *event) override;private:Ui::MainWindow *ui;//定义一个定时器的对象指针QTimer *timer;
};
#endif // MAINWINDOW_H
源文件
#include "mainwindow.h"
#include "ui_mainwindow.h"MainWindow::MainWindow(QWidget *parent): QMainWindow(parent), ui(new Ui::MainWindow)
{ui->setupUi(this);//给定时器指针实例化对象timer = new QTimer(this);timer->start(1000); //一秒钟//将该定时器的timeout信号连接到自定义槽函数中connect(timer, SIGNAL(timeout()), this, SLOT(update()));}MainWindow::~MainWindow()
{delete ui;
}void MainWindow::paintEvent(QPaintEvent *event)
{//实例化一个画家QPainter painter(this);//实例化一个画笔QPen pen;pen.setColor(QColor("black")); //将画笔设置成黑色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), 200,200); //QPoint(0,0)为起始位置//画出表盘for(int i=1;i<=60;i++){painter.rotate(6);painter.drawLine(0,195,0,200);}//painter.rotate(0);for(int i=1;i<=12;i++){painter.rotate(30);painter.drawLine(0,190,0,200);}QTime sys_t = QTime::currentTime();//时针painter.save(); //保存pen.setColor(QColor("green")); //将画笔设置成绿色painter.setPen(pen);painter.rotate(6*sys_t.second());painter.drawLine(0,0,0,150);//分针painter.restore();painter.save();pen.setColor(QColor("blue")); //将画笔设置成蓝色painter.setPen(pen);painter.rotate(6*(sys_t.minute()+sys_t.second()/60));painter.drawLine(0,0,0,120);//秒针painter.restore();painter.save();pen.setColor(QColor("red")); //将画笔设置成红色painter.setPen(pen);painter.rotate(30*((sys_t.hour()+sys_t.minute()/60)));painter.drawLine(0,0,0,90);}
主函数
#include "mainwindow.h"#include <QApplication>int main(int argc, char *argv[])
{QApplication a(argc, argv);MainWindow w;w.show();return a.exec();
}
2、思维导图