QT 绘图与重绘事件

发布时间:2024年01月16日

代码实现仪表盘

.cpp

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

#include <QPainter>
#include <QPen>
#include <QBrush>

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

    ui->Slidersudu->setMaximum(300);
    ui->Slidersudu->setMinimum(0);
    connect(ui->Slidersudu,SIGNAL(valueChanged(int)),this,SLOT(hSliderValueChangedSlot(int)));
}

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

void Widget::paintEvent(QPaintEvent *event)
{
    QPainter p (this);
    p.translate( this->width()/2, this->height()/2);
    QBrush brush; brush.setColor(QColor(0,42,79));  brush.setStyle(Qt::SolidPattern);
    p.setBrush(brush);
    p.drawEllipse(-200,-200,400,400); //drawEllipse(x,y,w,h) 圆
    QBrush brush2; brush.setColor(QColor(0,0,0));  brush.setStyle(Qt::SolidPattern);
    p.setBrush(brush);
    p.drawEllipse(-175,-175,350,350);

    QBrush brush3; brush.setColor(QColor(0,180,150));  brush.setStyle(Qt::SolidPattern);
    p.setBrush(brush);
    p.drawEllipse(-75,-75,150,150);

    QBrush brush4; brush.setColor(QColor(0,0,0));  brush.setStyle(Qt::SolidPattern);
    p.setBrush(brush);
    p.drawEllipse(-40,-40,80,80);
    //划线
    p.rotate(120);
    QPen pen; pen.setColor( QColor(0,255,50));  pen.setWidth(3); pen.setStyle(Qt::SolidLine);
    p.setPen(pen);
    int log = 0;
    for(int i = 6;;)
    {
       p.rotate(i);
       log++;
       if(log == 50)
        {
           break;
       }
       if(log%2 == 0)
       {
       p.drawLine(120,0,140,0);
       }
       else if(log%2 != 0)
       {
        p.drawLine(110,0,140,0);
       }
    }
    p.rotate(60);
    p.rotate( ui->Slidersudu->value() );
    QPen pen2;pen2.setColor(QColor(255,0,0));pen2.setWidth(3);pen2.setStyle(Qt::SolidLine);
    p.setPen(pen2);
    p.drawLine(0,0,this->width()/3,0);
    this->update();
}

void Widget::hSliderValueChangedSlot(int)
{
    qDebug()<<__func__;
   this->update();
}

.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>

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 hSliderValueChangedSlot(int);


private:
    Ui::Widget *ui;
};
#endif // WIDGET_H

现象

?

文章来源:https://blog.csdn.net/weixin_64965464/article/details/135633318
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。