.h
#ifndef WIDGET_H
#define WIDGET_H#include <QWidget>
#include <QPaintEvent>
#include <QDebug> //信息调试类
#include <QPainter>
#include <QPixmap> //图像引擎类
#include <QTime>
#include <QTimer> //定时器类
#include <QDateTime> //日期类
#include <QTimerEvent>
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACEclass Widget : public QWidget
{Q_OBJECTpublic:Widget(QWidget *parent = nullptr);~Widget();void paintEvent(QPaintEvent *event);void timerEvent(QTimerEvent *e);
private slots:private:Ui::Widget *ui;int timer_id;//给定时器实例化一个对象QTimer * timer;int hh=0,mm=0,ss=0;
};
#endif // WIDGET_H
.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);//给定时器实例化对象timer=new QTimer(this);// 设置窗口的大小和标题setFixedSize(500, 500);setWindowTitle("闹钟");}Widget::~Widget()
{delete ui;
}//绘制事件处理函数
void Widget::paintEvent(QPaintEvent *event)
{//实例化一个画家QPainter painter(this);// 设置反锯齿渲染painter.setRenderHint(QPainter::Antialiasing, true);//实例化一个画笔QPen pen;pen.setColor(QColor("blue"));pen.setStyle(Qt::DashDotLine); //设置线型//将画笔给画家安排上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);//绘制矢量文字pen.setColor(QColor("red"));painter.setPen(pen);//给画家设置字体painter.setFont(QFont("隶书",15,13));//画小时格子for(int i=1;i<=12;i++){//每转30度画一个时刻painter.rotate(30);painter.drawLine(0,-200,0,-175);painter.drawText(0,-170,QString("%1").arg(i));}//画分格子for(int i=0;i<=59;i++){//pen.setColor(QColor("green"));painter.rotate(6);painter.drawLine(0,-200,0,-190);}//绘制矢量文字painter.translate(-this->width()/2,-this->height()/2);painter.drawText(this->rect(),Qt::AlignCenter,"啊啊,我饿了");//绘制指针QPainter p1(this);QPen pen1;pen1.setWidth(5);p1.translate(this->width()/2,this->height()/2);pen1.setStyle(Qt::SolidLine); //设置线型//1、绘制秒针p1.setPen(Qt::green);p1.setBrush(Qt::green);p1.rotate(ss*360/60);p1.drawLine(0,0,160,0);//2、绘制分针p1.setPen(Qt::red);p1.setBrush(Qt::red);p1.rotate(-ss*6);p1.rotate(mm*6+ss/10);p1.drawLine(0,0,140,0);p1.restore();//3、绘制时针p1.setPen(Qt::black);p1.setBrush(Qt::black);p1.rotate(-mm*6-ss*6/60);p1.rotate(hh*30.0+mm/2.0);p1.drawLine(0,0,110,0);}//定时器事件处理函数
void Widget::timerEvent(QTimerEvent *e)
{if(e->timerId() == timer_id) //说明定时器1到位{QTime sys_t = QTime::currentTime(); //获取系统时间//将QTime类对象转换为字符串QString t = sys_t.toString("hh:mm:ss");QStringList list = t.split(":");hh = list[0].toUInt();mm = list[1].toUInt();ss = list[2].toUInt();update();}
}
main函数
#include "widget.h"#include <QApplication>int main(int argc, char *argv[])
{QApplication a(argc, argv);Widget w;w.show();return a.exec();
}