qpieseries.cpp
97 lines
| 2.4 KiB
| text/x-c
|
CppLexer
/ src / qpieseries.cpp
|
r51 | #include "qpieseries.h" | ||
#include "pieslice.h" | ||||
#include <QGraphicsObject> | ||||
#include <QDebug> | ||||
QTCOMMERCIALCHART_BEGIN_NAMESPACE | ||||
|
r61 | QPieSeries::QPieSeries(QGraphicsObject *parent) : | ||
|
r51 | QChartSeries(parent), | ||
|
r60 | m_sizeFactor(1.0) | ||
|
r51 | { | ||
|
r61 | } | ||
QPieSeries::~QPieSeries() | ||||
{ | ||||
while (m_slices.count()) | ||||
delete m_slices.takeLast(); | ||||
} | ||||
bool QPieSeries::setData(QList<qreal> data) | ||||
{ | ||||
m_data = data; | ||||
|
r54 | // Create slices | ||
|
r51 | qreal fullPie = 360; | ||
qreal total = 0; | ||||
|
r61 | foreach (qreal value, m_data) | ||
|
r51 | total += value; | ||
|
r61 | QGraphicsItem *parentItem = qobject_cast<QGraphicsItem *>(parent()); | ||
|
r51 | Q_ASSERT(parentItem); | ||
|
r60 | m_chartSize = parentItem->boundingRect(); | ||
|
r51 | qreal angle = 0; | ||
|
r54 | // TODO: no need to create new slices in case size changed; we should re-use the existing ones | ||
|
r61 | foreach (qreal value, m_data) { | ||
|
r51 | qreal span = value / total * fullPie; | ||
|
r60 | PieSlice *slice = new PieSlice(randomColor(), angle, span, parentItem->boundingRect()); | ||
|
r51 | slice->setParentItem(parentItem); | ||
m_slices.append(slice); | ||||
angle += span; | ||||
} | ||||
|
r60 | |||
resizeSlices(m_chartSize); | ||||
|
r61 | return true; | ||
|
r54 | } | ||
|
r60 | void QPieSeries::chartSizeChanged(QRectF chartRect) | ||
|
r54 | { | ||
|
r60 | // TODO: allow user setting the size? | ||
// TODO: allow user defining the margins? | ||||
m_chartSize = chartRect; | ||||
resizeSlices(m_chartSize); | ||||
} | ||||
void QPieSeries::resizeSlices(QRectF rect) | ||||
{ | ||||
QRectF tempRect = rect; | ||||
if (tempRect.width() < tempRect.height()) { | ||||
tempRect.setWidth(tempRect.width() * m_sizeFactor); | ||||
tempRect.setHeight(tempRect.width()); | ||||
tempRect.moveCenter(rect.center()); | ||||
} else { | ||||
tempRect.setHeight(tempRect.height() * m_sizeFactor); | ||||
tempRect.setWidth(tempRect.height()); | ||||
tempRect.moveCenter(rect.center()); | ||||
} | ||||
foreach (PieSlice *slice, m_slices) | ||||
slice->m_rect = tempRect; | ||||
} | ||||
void QPieSeries::setSizeFactor(qreal factor) | ||||
{ | ||||
if (factor > 0.0) | ||||
m_sizeFactor = factor; | ||||
resizeSlices(m_chartSize); | ||||
// Initiate update via the parent graphics item | ||||
// TODO: potential issue: what if this function is called from the parent context? | ||||
QGraphicsItem *parentItem = qobject_cast<QGraphicsItem *>(parent()); | ||||
Q_ASSERT(parentItem); | ||||
parentItem->update(); | ||||
|
r54 | } | ||
|
r51 | QColor QPieSeries::randomColor() | ||
{ | ||||
QColor c; | ||||
c.setRed(qrand() % 255); | ||||
c.setGreen(qrand() % 255); | ||||
c.setBlue(qrand() % 255); | ||||
return c; | ||||
} | ||||
#include "moc_qpieseries.cpp" | ||||
QTCOMMERCIALCHART_END_NAMESPACE | ||||