做一个动态指针钟表
头文件
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QPainter> //绘制事件类
#include <QPaintEvent> //画家类
#include <QTime>
#include <QTimer>
#include <QTimerEvent>
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
//重写绘制事件处理函数
void paintEvent(QPaintEvent *event)override;
private slots:
void on_startbtn_clicked();
void timeout_slot();
private:
Ui::Widget *ui;
//定义一个定时器的对象指针
QTimer *timer;
};
#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);
}
Widget::~Widget()
{
delete ui;
}
void Widget::paintEvent(QPaintEvent *event)
{
//定义一个画家类
QPainter p1(this);
//实例化一个画笔
QPen pen1; //无参构造
pen1.setColor(QColor("red"));
pen1.setStyle(Qt::SolidLine); //设置线形,默认实线
pen1.setWidth(5); //设置粗细
p1.setPen(pen1);
//直径
int side = qMin(this->width(),this->height());
//设置起始坐标
p1.translate(this->width()/2,this->height()/2); //ui界面中心
//画个圆圈当作表盘
p1.drawEllipse(QPoint(0,0),side/2,side/2);
//绘制刻度线
pen1.setColor(QColor("black"));
pen1.setWidth(3);
p1.setPen(pen1);
for(int i=0;i<12;i++)
{
p1.drawLine(0,-side/2+10,0,-side/2+20);
p1.rotate(30);
}
//绘制时针、分针、秒针
QTime curretTime = QTime::currentTime();
//时针
p1.setPen(Qt::NoPen);
p1.setBrush(Qt::blue);
p1.save();
p1.rotate(30*(curretTime.hour()+curretTime.minute()/60));
p1.drawConvexPolygon(QPolygon(QVector<QPoint>()<<QPoint(-2,-40)<<QPoint(2,-40)<<QPoint(4,0)<<QPoint(-4,0)));
p1.restore();
//分针
p1.setBrush(Qt::black);
p1.save();
p1.rotate(6*(curretTime.minute() + curretTime.second() / 60));
p1.drawConvexPolygon(QPolygon(QVector<QPoint>() << QPoint(-1, -50) << QPoint(1, -50) << QPoint(1, 100) << QPoint(-1, 100)));
p1.restore();
//秒针
p1.setPen(Qt::red);
p1.setBrush(Qt::red);
p1.save();
p1.rotate(6* curretTime.second());
p1.drawConvexPolygon(QPolygon(QVector<QPoint>() << QPoint(-1, -70) << QPoint(1, -70) << QPoint(0, 160) << QPoint(-0, 160)));
p1.restore();
}
//启动定时器按钮对应的槽函数
void Widget::on_startbtn_clicked()
{
timer->start(1000);
}
void Widget::timeout_slot()
{
update();
}
效果图