1、
头文件
- #ifndef MAINWINDOW_H
- #define MAINWINDOW_H
-
- #include
- #include
//绘制事件类 - #include
//信息调试类 - #include
//画家类 - #include
//定时器事件处理类 - #include
- #include
//定时器类 - #include
//日期时间类 -
-
- QT_BEGIN_NAMESPACE
- namespace Ui { class MainWindow; }
- QT_END_NAMESPACE
-
- class MainWindow : public QMainWindow
- {
- Q_OBJECT
-
- public:
- 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
-
- int main(int argc, char *argv[])
- {
- QApplication a(argc, argv);
- MainWindow w;
- w.show();
- return a.exec();
- }
2、思维导图