QT-day4

画一个时钟

widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include 
#include 
#include 
#include 
#include 
#include 


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;



public slots:
   void update_slot();

private:
    Ui::Widget *ui;

    QTimer *timer;
};
#endif // WIDGET_H

widget.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::update_slot);
    timer->start(1000);
}

Widget::~Widget()
{
    delete ui;
}
void Widget::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);

    QPen pen;
    pen.setColor(QColor("skyblue"));
    pen.setStyle(Qt::SolidLine);
    pen.setWidth(3);

    painter.setPen(pen);
    //给画家偏移起始坐标点
    painter.translate(this->width()/2,this->height()/2);
    //给画家偏移坐标系
    painter.rotate(0); //旋转坐标系
    painter.setBrush(QBrush(QColor("pink"))); //给画家设置画刷

    //画个圆
    painter.drawEllipse(QPoint(0,0),200,200);

    painter.setBrush(QBrush(QColor("black")));
    painter.drawEllipse(QPoint(0,0),10,10);


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

    pen.setColor(QColor("black"));
    pen.setStyle(Qt::SolidLine);
    painter.setPen(pen);

    for(int i=0;i<12;i++){
        painter.drawLine(QPoint(0,-190),QPoint(0,-200));
        painter.rotate(360/12);
    }

    painter.setFont(QFont("宋体", 20, 5));
    painter.setPen(pen);
    for(int i=12;i>=1;i--){
        painter.drawText(QPoint(-15,-160),QString::number(i));
        painter.rotate(-360/12);
    }
    pen.setWidth(1);
    painter.setPen(pen);
    for(int i=0;i<60;i++){
        painter.drawLine(QPoint(0,-195),QPoint(0,-200));
        painter.rotate(360/60);
    }
    painter.save();

    pen.setWidth(6);
    painter.setPen(pen);
    //时针
    painter.rotate(30.0*(time.hour()+(time.minute()+time.second()/60)/60));
    painter.drawLine(QPoint(0,0),QPoint(30,-75));
    painter.restore();
    painter.save();

    pen.setWidth(5);
    painter.setPen(pen);
    //分针
    painter.rotate(6.0*(time.minute()+time.second()/60));

    painter.drawLine(QPoint(0,0),QPoint(75,-100));
    painter.restore();
    painter.save();

    //秒针
    painter.rotate(6.0*time.second());
    painter.drawLine(QPoint(0,0),QPoint(150,-100));


}

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

测试结果

QT-day4_第1张图片

思维导图

QT-day4_第2张图片

你可能感兴趣的:(qt,开发语言)