Qt动态时钟

使用QPainter和QTimer制作一个简易的动态时钟。
dialog.h代码:

protected:
    //声明绘图的事件处理函数
    void paintEvent(QPaintEvent*event);

dialog.cpp代码:

#include "dialog.h"
#include "ui_dialog.h"
#include 
#include 
#include 
#include 
#include 

Dialog::Dialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::Dialog)
{
    ui->setupUi(this);
    //声明一个定时器
    QTimer*timer=new QTimer(this);
    //连接信号与槽
    connect(timer,SIGNAL(timeout()),this,SLOT(update()));
    //间隔1000毫秒调用一次
    timer->start(1000);

}

Dialog::~Dialog()
{
    delete ui;
}

void Dialog::paintEvent(QPaintEvent*event)
{
    QPen pen;
    QPainter painter(this);
    QTransform transform;

    //获取当前时间
    QTime time=QTime::currentTime();

    //绘制的范围
    int side=qMin(width(),height());

    //避免画圆时出现锯齿
    painter.setRenderHint(QPainter::Antialiasing);

    //重新定位坐标起始点
    transform.translate(width()/2,height()/2);
    //设定边界
    transform.scale(side/480.0,side/480.0);
    painter.setWorldTransform(transform);
    //设置画笔宽度为3毫米
    pen.setWidth(3);
    painter.setPen(pen);
    //画边界圆
    painter.drawEllipse(QPointF(0,0),239,239);
    //画刻度锯齿
    for(int i=0;i<=60;i++)
    {
        if(i%5==0)
        {
            painter.drawLine(210,0,239,0);
        }
        else
        {
            painter.drawLine(220,0,239,0);
        }
        transform.rotate(6);
        painter.setWorldTransform(transform);
    }

    //重置矩阵,实现时针的转动
    transform.reset();
    transform.translate(width()/2,height()/2);
    transform.scale(side/480.0,side/480.0);
    //时针旋转
    transform.rotate(30*(time.hour()+(time.minute()+time.second()/60)/60)-90);
    painter.setWorldTransform(transform);
    //时针宽度为9毫米
    pen.setWidth(9);
    painter.setPen(pen);
    //绘制时针
    painter.drawLine(-10,0,120,0);

    //重置矩阵,实现分针的转动
    transform.reset();
    transform.translate(width()/2,height()/2);
    transform.scale(side/480.0,side/480.0);
    transform.rotate(6*(time.minute()+time.second()/60)-90);
    painter.setWorldTransform(transform);
    pen.setWidth(7);
    painter.setPen(pen);
    painter.drawLine(-15,0,160,0);

    //重置矩阵,实现秒针的转动
    transform.reset();
    transform.translate(width()/2,height()/2);
    transform.scale(side/480.0,side/480.0);
    transform.rotate(6*time.second()-90);
    painter.setWorldTransform(transform);
    pen.setWidth(5);
    painter.setPen(pen);
    painter.drawLine(-20,0,200,0);


}

添加背景图后,效果图如下:Qt动态时钟_第1张图片

你可能感兴趣的:(Qt动态时钟)