qt day4

设置一个时钟

qt day4_第1张图片

 widget.cpp

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

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

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

//绘制时间处理函数的定义
void Widget::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    // 绘制背景
    painter.fillRect(rect(), Qt::white);
    // 获取当前时间
    QDateTime currentTime = QDateTime::currentDateTime();
    int hour = currentTime.time().hour();
    int minute = currentTime.time().minute();
    int second = currentTime.time().second();

    // 绘制刻度
    painter.save();
    painter.translate(width() / 2, height() / 2); // 将坐标系原点移到中心点
    painter.scale(width() / 200.0, height() / 200.0); // 缩放坐标系

    // 绘制小时刻度
    painter.setPen(QPen(Qt::black, 4));
    for (int i = 0; i < 12; ++i) {
        painter.drawLine(80, 0, 96, 0);
        painter.rotate(30);
    }

    // 绘制分钟刻度
    painter.setPen(QPen(Qt::black, 2));
    for (int i = 0; i < 60; ++i) {
        if (i % 5 != 0) {
            painter.drawLine(88, 0, 96, 0);
        }
        painter.rotate(6);
    }
    painter.restore();

    // 绘制时钟指针
    painter.save();
    painter.translate(width() / 2, height() / 2);
    painter.scale(width() / 200.0, height() / 200.0);
    painter.setPen(QPen(Qt::black, 6));

    // 绘制小时指针
    painter.save();
    painter.rotate(hour * 30.0 + minute * 0.5); // 每小时30度,每分钟0.5度
    painter.drawLine(-10, 0, 40, 0);
    painter.restore();

    // 绘制分钟指针
    painter.save();
    painter.rotate(minute * 6.0 + second * 0.1); // 每分钟6度,每秒0.1度
    painter.drawLine(-10, 0, 60, 0);
    painter.restore();

    // 绘制秒钟指针
    painter.save();
    painter.rotate(second * 6.0); // 每秒6度
    painter.setPen(QPen(Qt::red, 1));
    painter.setBrush(Qt::red);
    painter.drawLine(-10, 0, 80, 0);
    painter.drawEllipse(-5, -5, 10, 10); // 绘制一个小圆点表示秒钟指针的末端
    painter.restore();

    painter.restore();

}
void Widget::timerEvent(QTimerEvent *event)
{
    update();
}

widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include 
#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;
    void timerEvent(QTimerEvent *event) override;

private slots:
    //void timeout_slot();
private:
    Ui::Widget *ui;
    QTimer *timer;

};
#endif // WIDGET_H

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