QT第五天

使用QT绘图和绘图事件,完成仪表盘绘图,如下图:

QT第五天_第1张图片

 程序运行结果:

QT第五天_第2张图片 

代码:

widget.h

#ifndef WIDGET_H
#define WIDGET_H

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

private:
    Ui::Widget *ui;
};
#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);

    ui->horizontalSlider->setValue(0);
    ui->horizontalSlider->setMinimum(0);
    ui->horizontalSlider->setMaximum(280);
    connect(ui->horizontalSlider,SIGNAL(valueChanged(int)), this, SLOT(horizontalSliderValueChanged(int)));
}

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

void Widget::paintEvent(QPaintEvent *event)
{
    //
    QPainter p (this);
    QPen pen;
    QBrush brush;

    p.translate(this->width()/2,this->height()/2);

    //
    p.setPen(Qt::NoPen);

    //画外部圆
    brush.setColor(QColor(100,100,100));
    brush.setStyle(Qt::SolidPattern);
    p.setBrush(brush);
    p.drawEllipse(-150,-150,300,300);

    //画内部圆
    brush.setColor(QColor(60,60,60));
    p.setBrush(brush);
    p.drawEllipse(-140,-140,280,280);

    //画蓝色圈
    brush.setColor(QColor(0,105,210));
    p.setBrush(brush);
    p.drawEllipse(-40,-40, 80, 80);

    //画中心圆
    brush.setColor(QColor(60,60,60));
    p.setBrush(brush);
    p.drawEllipse(-20,-20,40,40);

    brush.setColor(QColor(0,255,255));
    p.setBrush(brush);
    p.drawEllipse(-5,-5,10,10);

    //画刻度

    pen.setWidth(3);
    pen.setStyle(Qt::SolidLine);
    p.rotate(130);
    for (int i = 0; i <= 40; i++ ) {
        pen.setColor(QColor(255,240-i*6,0));
        p.setPen(pen);
        if(i%2 == 0)
        {
            p.drawLine(130,0,115,0);
        }
        else
        {
            p.drawLine(130,0,120,0);
        }
        p.rotate(7);
    }

    //画指针
    p.rotate(73);
    p.rotate(ui->horizontalSlider->value());
    pen.setColor(QColor(0,255,255));
    p.setPen(pen);
    p.drawLine(106,0,0,0);

}

void Widget::horizontalSliderValueChanged(int)
{
    //通知,整个窗口重绘
    this->update();
}

widget.ui



 Widget
 
  
   
    0
    0
    400
    400
   
  
  
   
    400
    400
   
  
  
   仪表盘
  
  
   
    
     100
     370
     200
     20
    
   
   
    Qt::Horizontal
   
  
 
 
 

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