Qt5.8汽车仪表盘制作

制作一个可以由SpinBox控制转动的仪表盘,具体源代码如下:
/**********************************************common.h******************************/
#ifndef COMMON_H
#define COMMON_H

#define Meter_Centre_X 242 //仪表盘中心坐标
#define Meter_Centre_Y 242

#define P_Centre_X -65//指针旋转中心坐标
#define P_Centre_Y -136

#define P_W 130//指针图片长和宽
#define P_H 159

#define MaxAngle 130//最大旋转角度和最小旋转角度
#define MinAngle -130

#define Step 1//摆动步长

#endif // COMMON_H


/**************************************widget.h**********************************/
#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QPainter>
#include <QPaintDevice>
#include <QPaintEvent>
#include <QPixmap>
#include <QDebug>
#include <QLabel>
#include <QSpinBox>
#include "common.h"

class Widget : public QWidget
{
    Q_OBJECT

public:
    Widget(QWidget *parent = 0);
    ~Widget();
    void paintEvent(QPaintEvent * );
    void SetAngle();
public slots:
    void Spinbox_Slot();

private:
    QSpinBox *Spin;
    QPixmap pixmap;
    int around = 0;
};

#endif // WIDGET_H

/**********************************************widget.cpp***********************************/
#include "widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
{
    this->setWindowTitle("汽车仪表盘制作");
    QPixmap pixmap(":/Photo/表盘.jpg");
    QPalette palette;
    palette.setBrush(this->backgroundRole(),QBrush(pixmap));
    this->setPalette(palette);
    this->setFixedSize(500,452);
    around = MinAngle;
    Spin = new QSpinBox(this);
    Spin->setMinimum(-130);
    Spin->setMaximum(130);
    connect(this->Spin,SIGNAL(valueChanged(int)),this,SLOT(Spinbox_Slot()));
}

void Widget::paintEvent(QPaintEvent *)
{
    pixmap.load(":/Photo/指针.png");
//    this->SetAngle();//调用函数实现自动摆动
    QPainter *P = new QPainter(this);
    P->setRenderHint(QPainter::Antialiasing,true);
    P->setRenderHint(QPainter::SmoothPixmapTransform,true);
    P->save();
    P->translate(Meter_Centre_X,Meter_Centre_Y);//指针中心放置坐标
    P->rotate(around);//旋转一定的角度
    qDebug()<<"around:"<<around;
    P->drawPixmap(P_Centre_X,P_Centre_Y,P_W,P_H,pixmap);//指针的旋转中心坐标和图片长宽
    P->restore();//使原点复原
    this->update();//刷新界面
}

void Widget::SetAngle()
{
    static int Direction = 1;
    if(around >= MaxAngle)
    {
        Direction = -1;
    }
    else if(around <= MinAngle)
    {
        Direction = 1;
    }
    around = around + Direction * Step;
}

void Widget::Spinbox_Slot()
{
    around = Spin->value();
}

Widget::~Widget()
{

}

实现的效果如下:





原文地址:https://www.cnblogs.com/jiayezi/p/14053154.html