c++&qt day11

通过代码实现电子钟表

头文件

#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;

private:
    Ui::Widget *ui;
    int m_sec = 0;
    int m_min = 0;
    int m_hour = 0;
    QTimer *timer;
    void timeout_slot();
};
#endif // WIDGET_H

源文件

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

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

    timer = new QTimer(this);
    timer->start(1000);//一秒钟
    connect(timer, &QTimer::timeout, this, &Widget::timeout_slot);
}

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

void Widget::paintEvent(QPaintEvent *event)
{
    //实例化画家1
    QPainter painter(this);

    //实例化一个画笔
    QPen pen;       //使用无参构造
    pen.setColor(QColor("black"));      //设置画笔颜色
    //pen.setStyle(Qt::DashDotDotLine);   //设置线型
    pen.setWidth(5);                    //设置画笔宽度

    //将画笔给画家
    painter.setPen(pen);
    //给画家安排画刷
    painter.setBrush(QBrush(QColor("skyblue")));
    //给画家偏移起始坐标点
    painter.translate(this->width()/2, this->height()/2);
    //给画家偏移坐标系
    //painter.rotate(0);          //旋转坐标系
    //画个椭圆
    painter.drawEllipse(QPoint(0,0), 200, 200);

    //画刻度线
    for(int i = 1; i <=60; ++i)
    {
        painter.save();
        painter.rotate(6*i);//坐标轴旋转6度
        if (i % 5 == 0)
        {
            painter.drawLine(0, -188, 0, -200);
            painter.drawText(QPoint(-6,-160), QString::number(i/5));
        }
        else
        {
            painter.drawLine(0, -192, 0, -200);
        }
        painter.restore();//绘制图形后复位坐标系
    }

    painter.save();
    painter.rotate(6*m_sec);
    painter.drawLine(0,0,0,-170);
    painter.restore();

    painter.save();
    double m = (m_min*6.0 + m_sec*0.1);
    painter.rotate(m);
    painter.drawLine(0,0,0,-140);
    painter.restore();

    painter.save();
    double h = (m_hour%12 + m_min/60.0)*30.0;
    painter.rotate(h);
    painter.drawLine(0,0,0,-110);
    painter.restore();

}

void Widget::timeout_slot()
{
    QDateTime datetime = QDateTime::currentDateTime();

    m_sec = datetime.time().second();
    m_min = datetime.time().minute();
    m_hour = datetime.time().hour();

    update();
}

主函数

#include "widget.h"

#include 

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    w.show();
    return a.exec();
}

效果展示

c++&qt day11_第1张图片

你可能感兴趣的:(c++,qt,java)