#include "carwidget.h"
#include <QPainter>
#include <math.h>
#include <QDebug>
CarWidget::CarWidget(QWidget *parent) : QWidget(parent)
{
m_iCar = 76;
m_iCarWidth = 0;
m_index = 0;
m_type = Left;
m_bgColor = QColor(68,68,68);
m_carColor = QColor(20,190,150);
m_textColor = QColor(255,255,255);
m_iSize = 10;
}
CarWidget::~CarWidget()
{
}
void CarWidget::paintEvent(QPaintEvent *p)
{
QPainter painter(this);
//绘制背景色
painter.setBrush(m_bgColor);
painter.setPen(m_bgColor);
painter.drawRect(rect());
paintCar(painter);
return QWidget::paintEvent(p);
}
void CarWidget::resizeEvent(QResizeEvent *)
{
calc();
update();
}
void CarWidget::calc()
{
QRect rect = this->geometry();
//圆的直径
int iDiameter = rect.width() < rect.height() ? rect.width() : rect.height();
//上下留5个像素
m_iDiameter = iDiameter - 10;
m_iLeft = m_iDiameter * 3 / 100 > 0 ? m_iDiameter * 3 / 100 : 3;
m_iRight = width() - m_iDiameter + m_iLeft;
int iLength = 3.14 * m_iDiameter + 2 * ( width() - m_iDiameter );
//平均的距离
m_iCarWidth = iLength / ( m_iCar * 1.5 );
}
void CarWidget::paintCar(QPainter &painter)
{
//Y的高度
int iHeight = (height() - m_iDiameter) / 2 + m_iCarWidth;
painter.setRenderHint(QPainter::Antialiasing, true);
painter.setPen(m_carColor);
QPainterPath path;
path.addEllipse(m_iCarWidth , iHeight , m_iDiameter - m_iCarWidth * 2, m_iDiameter - m_iCarWidth * 2);
QPainterPath pathRect;
pathRect.addRect(m_iDiameter / 2 + m_iCarWidth,
iHeight ,
width() - m_iDiameter - m_iCarWidth * 2,
m_iDiameter - m_iCarWidth * 2);
path = path.united(pathRect);
pathRect.addEllipse(width() - m_iDiameter + m_iCarWidth ,
iHeight ,
m_iDiameter - m_iCarWidth * 2,
m_iDiameter - m_iCarWidth * 2);
path = path.united(pathRect);
//painter.drawPath(path);
QFont font;
font.setPointSize(m_iSize);
painter.setFont(font);
if(m_type == Right)
{
if(m_index >= m_iCar)
{
m_index = 0;
}
}
else if(m_type == Left)
{
if(m_index <= -m_iCar)
{
m_index = 0;
}
}
for(int i = 0 ; i < m_iCar ; i++ )
{
QPointF point = path.pointAtPercent(i / (m_iCar * 1.0));
int index = m_type == Right ? (i + m_index) % m_iCar + 1 : (i + m_iCar + m_index) % m_iCar + 1;
painter.setPen(m_textColor);
painter.drawText(point , QString("%1").arg(index));
mapColorCar::iterator iter = m_mapCar.find(index);
if( iter != m_mapCar.end())
{
painter.setPen(iter.value());
painter.setBrush(iter.value());
}
else
{
painter.setPen(m_carColor);
painter.setBrush(m_carColor);
}
painter.drawRect(point.x() , point.y() , m_iCarWidth , m_iCarWidth);
}
m_type == Right ? m_index++ : m_index--;
}
void CarWidget::setDireciton(CarWidget::directionType type)
{
m_type = type;
}
void CarWidget::setBgColor(QColor color)
{
m_bgColor = color;
}
void CarWidget::setTextColor(QColor color)
{
m_textColor = color;
}
void CarWidget::setTextSize(int iSize)
{
m_iSize = iSize;
}
void CarWidget::setCarColor(CarWidget::mapColorCar mapCar)
{
m_mapCar = mapCar;
}
void CarWidget::setCarSize(int iSize)
{
m_iCar = iSize;
}