Qt-day4

1、时钟

#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    //给定时器指针实例化对象
    timer = new QTimer(this);
    //将该定时器的timeout信号连接到自定义槽函数中
    connect(timer, &QTimer::timeout, this, &Widget::timeout_slot);
}

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

//绘制事件处理函数的定义
void Widget::paintEvent(QPaintEvent *event)
{
    //实例化一个画家
    QPainter painter(this);

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

    //实例化一个画笔
    QPen pen;
    pen.setColor(QColor("hotpink"));   //表盘外框颜色
    pen.setStyle(Qt::SolidLine);       //设置线型:实线
    pen.setWidth(4);                   //线的粗细
    //将画笔给画家安排上
    painter.setPen(pen);

    //给画家偏移起始坐标点
    painter.translate(this->width()/2, this->height()/2);

    //给画家安排画刷
    painter.setBrush(QBrush(QColor("grey")));

    //画个圆形(时钟
    painter.drawEllipse(QPoint(0,0), 160, 160);

    //刻度
    for(int i=0; i<60; i++)
    {
        painter.drawLine(160,0,154,0);
        painter.rotate(6);
    }

    painter.setFont(QFont("隶书",14));
    //小时
    for(int i=1; i<=12; i++)
    {
        painter.rotate(30);
        painter.drawLine(0, -160, 0, -145);
        painter.drawText(-10, -125, QString("%1").arg(i));
    }

    painter.save();

    int hour = Time.hour();    // 获取当前的小时
    int minute = Time.minute();     // 获取当前的分钟
    double hourAngle = (hour%12 + minute/60.0)*30.0;  // 计算时针的角度
    painter.rotate(hourAngle);    // 旋转坐标系,使时针指向正确的位置

    QPen pen1;
    pen1.setColor(QColor("darkred"));      //设置时针颜色
    pen1.setStyle(Qt::SolidLine);               //实线
    pen1.setWidth(6);

    //将画笔给画家安排上
    painter.setPen(pen1);
    //画一条直线
    painter.drawLine(0, 0, 0, 80);

    painter.save();

    //绘制分针
    double minuteAngle = minute*6.0;
    painter.rotate(minuteAngle);

    QPen pen2;
    pen2.setColor(QColor("lightpink"));      //设置时针颜色
    pen2.setStyle(Qt::SolidLine);               //实线
    pen2.setWidth(4);
    //将画笔给画家安排上
    painter.setPen(pen2);
    painter.drawLine(0, 0, 0, 110);

    painter.save();

    //绘制秒针
    int second = Time.second();
    double secondAngle = second * 6.0;
    painter.rotate(secondAngle);

    QPen pen3;
    pen3.setColor(QColor("inen"));      //设置时针颜色
    pen3.setStyle(Qt::SolidLine);               //实线
    pen3.setWidth(2);
    //将画笔给画家安排上
    painter.setPen(pen3);
    painter.drawLine(0, 0, 0, 140);

    painter.restore();

}

void Widget::timeout_slot()
{
    update();
}

ui界面:

Qt-day4_第1张图片

2、思维导图

你可能感兴趣的:(作业,qt)