2023/09/20 day4 qt

做一个动态指针钟表

头文件

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


private slots:
    void on_startbtn_clicked();

    void timeout_slot();
private:
    Ui::Widget *ui;

    //定义一个定时器的对象指针
    QTimer *timer;
};
#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);
    connect(timer,&QTimer::timeout,this,&Widget::timeout_slot);
}

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

void Widget::paintEvent(QPaintEvent *event)
{
    //定义一个画家类
    QPainter p1(this);

    //实例化一个画笔
    QPen pen1;   //无参构造
    pen1.setColor(QColor("red"));
    pen1.setStyle(Qt::SolidLine); //设置线形,默认实线
    pen1.setWidth(5); //设置粗细
    p1.setPen(pen1);
    //直径
    int side = qMin(this->width(),this->height());
    //设置起始坐标
    p1.translate(this->width()/2,this->height()/2); //ui界面中心
    //画个圆圈当作表盘
    p1.drawEllipse(QPoint(0,0),side/2,side/2);

    //绘制刻度线
    pen1.setColor(QColor("black"));
    pen1.setWidth(3);
    p1.setPen(pen1);
    for(int i=0;i<12;i++)
    {
        p1.drawLine(0,-side/2+10,0,-side/2+20);
        p1.rotate(30);
    }

    //绘制时针、分针、秒针
    QTime curretTime = QTime::currentTime();
    //时针
    p1.setPen(Qt::NoPen);
    p1.setBrush(Qt::blue);
    p1.save();
    p1.rotate(30*(curretTime.hour()+curretTime.minute()/60));
    p1.drawConvexPolygon(QPolygon(QVector()<() << QPoint(-1, -50) << QPoint(1, -50) << QPoint(1, 100) << QPoint(-1, 100)));
    p1.restore();

    //秒针
    p1.setPen(Qt::red);
    p1.setBrush(Qt::red);
    p1.save();
    p1.rotate(6* curretTime.second());
    p1.drawConvexPolygon(QPolygon(QVector() << QPoint(-1, -70) << QPoint(1, -70) << QPoint(0, 160) << QPoint(-0, 160)));
    p1.restore();
}



//启动定时器按钮对应的槽函数
void Widget::on_startbtn_clicked()
{
    timer->start(1000);
}

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

效果图

2023/09/20 day4 qt_第1张图片

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