画个钟
头文件:
#ifndef WIDGET_H
#define WIDGET_H#include <QWidget>
#include <QPaintEvent>
#include <QDebug>
#include <QPainter>
#include <QTimerEvent>
#include <QTime>
#include <QDateTime>
#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;int hour;int min;int sec;private:Ui::Widget *ui;QTimer *timer;int timer_id;private slots:void timeout_slot();
};
#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 = new QTimer(this);connect(timer,&QTimer::timeout,this,&Widget::timeout_slot);timer->start(1000);
}Widget::~Widget()
{delete ui;
}//绘制事件处理函数的定义
void Widget::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.drawEllipse(QPoint(0,0),200,200);pen.setColor(QColor("black"));painter.setPen(pen);//画出时针间隔for(int i=1;i<13;i++){painter.rotate(30);painter.drawLine(0,-200,0,-180);painter.drawText(-5,-160,QString("%0").arg(i));}//画出分钟间隔for(int i=0;i<60;i++){painter.rotate(6);painter.drawLine(0,-200,0,-195);}//画出秒针painter.rotate(-90);painter.rotate(6*sec);painter.drawLine(0,0,120,0);//画出分针painter.rotate(-6*sec);painter.rotate(6*min+6*sec/60);painter.drawLine(0,0,90,0);//画出时针pen.setColor(QColor("red"));painter.setPen(pen);painter.rotate(-6*min-6*sec/60);painter.rotate(30*hour+6*min/12+6*sec/60/12);painter.drawLine(0,0,70,0);
}void Widget::timeout_slot()
{//获取当前时间QTime sys_t = QTime::currentTime();//转为字符串QString t = sys_t.toString("hh:mm:ss");//获取时分秒hour = sys_t.hour();min = sys_t.minute();sec = sys_t.second();//触发重绘update();//显示ui->label->setText(t);
}