画一个时钟
#include "widget.h"
#include "ui_widget.h"
#include <QPainter>
#include <QDebug>
#include <QTime>
#include <QTimer>Widget::Widget(QWidget *parent): QWidget(parent), ui(new Ui::Widget)
{ui->setupUi(this);t1.start(1000); // 每秒钟更新一次connect(&t1, &QTimer::timeout, this, &Widget::time_slot);
}Widget::~Widget()
{delete ui;
}void Widget::paintEvent(QPaintEvent *event)
{QPainter painter(this);QPen pen;QPen pen1;QPen pen2;pen.setStyle(Qt::SolidLine);pen.setColor(Qt::black);pen.setWidth(5);pen1.setStyle(Qt::SolidLine);pen1.setColor(Qt::black);pen1.setWidth(2);pen2.setStyle(Qt::SolidLine);pen2.setColor(Qt::black);pen2.setWidth(4);painter.setPen(pen);painter.translate(this->width() / 2, this->height() / 2);painter.drawEllipse(QPoint(0, 0), 200, 200);pen.setWidth(10);painter.setPen(pen);painter.drawLine(QPoint(0, 0), QPoint(0, 0));int i = 0;while (i < 60) {if (i == 0 || i == 15 || i == 30 || i == 45) {pen.setWidth(5);painter.setPen(pen);painter.drawLine(QPoint(0, -200), QPoint(0, -180));} else if (i == 5 || i == 10 || i == 20 || i == 25 || i == 35 || i == 40 || i == 50 || i == 55) {painter.setPen(pen2);painter.drawLine(QPoint(0, -200), QPoint(0, -190));}painter.setPen(pen1);painter.rotate(6);painter.drawLine(QPoint(0, -200), QPoint(0, -195));i = i + 1;}painter.drawText(QPoint(0, -165), "12");painter.drawText(QPoint(165, 0), "3");painter.drawText(QPoint(0, 165), "6");painter.drawText(QPoint(-165, 0), "9");// 画秒针pen.setColor(Qt::red);painter.setPen(pen);painter.save();painter.rotate(secondAngle);painter.drawLine(QPoint(0, 0), QPoint(0, -80));painter.restore();// 画分针pen2.setColor(Qt::green);painter.setPen(pen2);painter.save();painter.rotate(minuteAngle);painter.drawLine(QPoint(0, 0), QPoint(0, -70));painter.restore();// 画时针pen1.setColor(Qt::blue);painter.setPen(pen1);painter.save();painter.rotate(hourAngle);painter.drawLine(QPoint(0, 0), QPoint(0, -50));painter.restore();
}void Widget::time_slot()
{QTime currentTime = QTime::currentTime();int seconds = currentTime.second();int minutes = currentTime.minute();int hours = currentTime.hour();// 计算角度secondAngle = seconds * 6; // 每秒钟6度minuteAngle = minutes * 6 + seconds * 0.1; // 每分钟6度,加上秒针的影响hourAngle = hours * 30 + minutes * 0.5; // 每小时30度,加上分钟的影响this->update(); // 刷新界面
}