1
/****************************************************************************
2
** Copyright (C) 2001-2010 Klaralvdalens Datakonsult AB. All rights reserved.
4
** This file is part of the KD Chart library.
6
** Licensees holding valid commercial KD Chart licenses may use this file in
7
** accordance with the KD Chart Commercial License Agreement provided with
11
** This file may be distributed and/or modified under the terms of the
12
** GNU General Public License version 2 and version 3 as published by the
13
** Free Software Foundation and appearing in the file LICENSE.GPL included.
15
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
16
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
18
** Contact info@kdab.com if any conditions of this licensing are not
21
**********************************************************************/
23
#include "KDChartCartesianAxis.h"
24
#include "KDChartCartesianAxis_p.h"
32
#include <QApplication>
34
#include "KDChartPaintContext.h"
35
#include "KDChartChart.h"
36
#include "KDChartAbstractCartesianDiagram.h"
37
#include "KDChartAbstractGrid.h"
38
#include "KDChartPainterSaver_p.h"
39
#include "KDChartLayoutItems.h"
40
#include "KDChartBarDiagram.h"
41
#include "KDChartStockDiagram.h"
42
#include "KDChartLineDiagram.h"
43
#include "KDChartPrintingParameters.h"
45
#include <KDABLibFakes>
49
using namespace KDChart;
53
CartesianAxis::CartesianAxis ( AbstractCartesianDiagram* diagram )
54
: AbstractAxis ( new Private( diagram, this ), diagram )
59
CartesianAxis::~CartesianAxis ()
61
// when we remove the first axis it will unregister itself and
62
// propagate the next one to the primary, thus the while loop
63
while ( d->mDiagram ) {
64
AbstractCartesianDiagram *cd = qobject_cast<AbstractCartesianDiagram*>( d->mDiagram );
67
Q_FOREACH( AbstractDiagram *diagram, d->secondaryDiagrams ) {
68
AbstractCartesianDiagram *cd = qobject_cast<AbstractCartesianDiagram*>( diagram );
73
void CartesianAxis::init ()
80
bool CartesianAxis::compare( const CartesianAxis* other )const
82
if( other == this ) return true;
84
//qDebug() << "CartesianAxis::compare() cannot compare to Null pointer";
88
qDebug() << (position() == other->position());
89
qDebug() << (titleText() == other->titleText());
90
qDebug() << (titleTextAttributes() == other->titleTextAttributes());
92
return ( static_cast<const AbstractAxis*>(this)->compare( other ) ) &&
93
( position() == other->position() ) &&
94
( titleText() == other->titleText() ) &&
95
( titleTextAttributes() == other->titleTextAttributes() );
99
void CartesianAxis::setTitleText( const QString& text )
105
QString CartesianAxis::titleText() const
110
void CartesianAxis::setTitleTextAttributes( const TextAttributes &a )
112
d->titleTextAttributes = a;
113
d->useDefaultTextAttributes = false;
117
TextAttributes CartesianAxis::titleTextAttributes() const
119
if( hasDefaultTitleTextAttributes() ){
120
TextAttributes ta( textAttributes() );
121
Measure me( ta.fontSize() );
122
me.setValue( me.value() * 1.5 );
123
ta.setFontSize( me );
126
return d->titleTextAttributes;
129
void CartesianAxis::resetTitleTextAttributes()
131
d->useDefaultTextAttributes = true;
135
bool CartesianAxis::hasDefaultTitleTextAttributes() const
137
return d->useDefaultTextAttributes;
141
void CartesianAxis::setPosition ( Position p )
147
#if QT_VERSION < 0x040400 || defined(Q_COMPILER_MANGLES_RETURN_TYPE)
150
CartesianAxis::Position CartesianAxis::position() const
155
void CartesianAxis::layoutPlanes()
157
//qDebug() << "CartesianAxis::layoutPlanes()";
158
if( ! d->diagram() || ! d->diagram()->coordinatePlane() ) {
159
//qDebug() << "CartesianAxis::layoutPlanes(): Sorry, found no plane.";
162
AbstractCoordinatePlane* plane = d->diagram()->coordinatePlane();
164
plane->layoutPlanes();
165
//qDebug() << "CartesianAxis::layoutPlanes() OK";
170
void CartesianAxis::paintEvent( QPaintEvent* event )
174
if( ! d->diagram() || ! d->diagram()->coordinatePlane() ) return;
176
PaintContext context;
177
QPainter painter( this );
178
context.setPainter( &painter );
179
AbstractCoordinatePlane* plane = d->diagram()->coordinatePlane();
180
context.setCoordinatePlane( plane );
181
QRectF rect = QRectF ( 1, 1, plane->width() - 3, plane->height() - 3 );
182
context.setRectangle( rect );
183
d->geometry.setSize( size() );
184
paintCtx( &context );
189
static bool referenceDiagramIsBarDiagram( const AbstractDiagram * diagram )
191
const AbstractCartesianDiagram * dia =
192
qobject_cast< const AbstractCartesianDiagram * >( diagram );
193
if( dia && dia->referenceDiagram() )
194
dia = dia->referenceDiagram();
195
return qobject_cast< const BarDiagram* >( dia ) != 0;
198
static bool referenceDiagramNeedsCenteredAbscissaTicks( const AbstractDiagram *diagram )
200
const AbstractCartesianDiagram * dia =
201
qobject_cast< const AbstractCartesianDiagram * >( diagram );
202
if( dia && dia->referenceDiagram() )
203
dia = dia->referenceDiagram();
204
if ( qobject_cast< const BarDiagram* >( dia ) )
206
if ( qobject_cast< const StockDiagram* >( dia ) )
209
const LineDiagram * lineDiagram = qobject_cast< const LineDiagram* >( dia );
210
return lineDiagram && lineDiagram->centerDataPoints();
213
bool CartesianAxis::isAbscissa() const
215
const Qt::Orientation diagramOrientation = referenceDiagramIsBarDiagram( d->diagram() ) ? ((BarDiagram*)(d->diagram()))->orientation()
217
return diagramOrientation == Qt::Vertical ? position() == Bottom || position() == Top
218
: position() == Left || position() == Right;
221
bool CartesianAxis::isOrdinate() const
223
const Qt::Orientation diagramOrientation = referenceDiagramIsBarDiagram( d->diagram() ) ? ((BarDiagram*)(d->diagram()))->orientation()
225
return diagramOrientation == Qt::Vertical ? position() == Left || position() == Right
226
: position() == Bottom || position() == Top;
229
void CartesianAxis::paint( QPainter* painter )
231
if( ! d->diagram() || ! d->diagram()->coordinatePlane() ) return;
233
ctx.setPainter ( painter );
234
ctx.setCoordinatePlane( d->diagram()->coordinatePlane() );
235
const QRect rect( areaGeometry() );
237
//qDebug() << "CartesianAxis::paint( QPainter* painter ) " << " areaGeometry()():" << rect << " sizeHint():" << sizeHint();
242
QPointF(rect.left(), rect.top()),
243
QSizeF(rect.width(), rect.height() ) ) );
244
// enabling clipping so that we're not drawing outside
245
QRegion clipRegion( rect.adjusted( -1, -1, 1, 1 ) );
247
painter->setClipRegion( clipRegion );
250
//qDebug() << "KDChart::CartesianAxis::paint() done.";
253
void CartesianAxis::Private::drawSubUnitRulers( QPainter* painter, CartesianCoordinatePlane* plane, const DataDimension& dim,
254
const QPointF& rulerRef, const QVector<int>& drawnTicks, const bool diagramIsVertical,
255
const RulerAttributes& rulerAttr ) const
257
const QRect geoRect( axis()->geometry() );
258
int nextMayBeTick = 0;
262
qreal fLogSubstep = f;
263
const bool isAbscissa = axis()->isAbscissa();
264
const bool isLogarithmic = (dim.calcMode == AbstractCoordinatePlane::Logarithmic );
265
const int subUnitTickLength = axis()->tickLength( true );
267
// Use negative limit to ensure that also the last tick is painted,
268
// which is needed if major tick marks are disabled
269
while ( dim.end - f > -std::numeric_limits< float >::epsilon() ) {
270
const qreal quotient = f / dim.stepWidth;
271
const bool isMinorTickMark = qAbs(qRound(quotient) - quotient) > std::numeric_limits< float >::epsilon();
272
// 'Drawn' ticks isn't quite the right naming here, it also counts major tick marks, which are not drawn.
273
if( drawnTicks.count() > nextMayBeTick )
274
mayBeTick = drawnTicks[ nextMayBeTick ];
275
// Paint minor tick mark only if there is no major tick mark drawn at this point
276
if ( isMinorTickMark || !rulerAttr.showMajorTickMarks() ) {
279
QPointF topPoint = diagramIsVertical ? QPointF( f, 0 ) : QPointF( 0, f );
280
QPointF bottomPoint( topPoint );
281
// we don't draw the sub ticks, if we are at the same position as a normal tick
282
topPoint = plane->translate( topPoint );
283
bottomPoint = plane->translate( bottomPoint );
284
if ( diagramIsVertical ) {
285
topPoint.setY( rulerRef.y() + subUnitTickLength );
286
bottomPoint.setY( rulerRef.y() );
288
topPoint.setX( rulerRef.x() + subUnitTickLength );
289
bottomPoint.setX( rulerRef.x() );
291
if( qAbs( mayBeTick - topPoint.x() ) > 1 )
293
if ( rulerAttr.hasTickMarkPenAt( topPoint.x() ) )
294
painter->setPen( rulerAttr.tickMarkPen( topPoint.x() ) );
296
painter->setPen( rulerAttr.minorTickMarkPen() );
297
painter->drawLine( topPoint, bottomPoint );
305
QPointF leftPoint = plane->translate( diagramIsVertical ? QPointF( 0, f ) : QPointF( f, 0 ) );
306
//qDebug() << "geoRect:" << geoRect << " geoRect.top()" << geoRect.top() << "geoRect.bottom()" << geoRect.bottom() << " translatedValue:" << translatedValue;
307
// we don't draw the sub ticks, if we are at the same position as a normal tick
308
if( qAbs( mayBeTick - diagramIsVertical ? leftPoint.y() : leftPoint.x() ) > 1 ){
309
const qreal translatedValue = leftPoint.y();
310
bool translatedValueIsWithinBoundaries;
311
if ( diagramIsVertical ) {
312
translatedValueIsWithinBoundaries = translatedValue > geoRect.top() && translatedValue <= geoRect.bottom();
314
translatedValueIsWithinBoundaries = translatedValue > geoRect.left() && translatedValue <= geoRect.right();
316
if( translatedValueIsWithinBoundaries ){
317
QPointF rightPoint = diagramIsVertical ? QPointF( 0, f ) : QPointF( f, 0 );
318
rightPoint = plane->translate( rightPoint );
319
if ( diagramIsVertical ) {
320
leftPoint.setX( rulerRef.x() + subUnitTickLength );
321
rightPoint.setX( rulerRef.x() );
323
leftPoint.setY( rulerRef.y() + (position == Bottom ? subUnitTickLength : -subUnitTickLength) );
324
rightPoint.setY( rulerRef.y() );
326
if ( rulerAttr.hasTickMarkPenAt( f ) )
327
painter->setPen( rulerAttr.tickMarkPen( f ) );
329
painter->setPen( rulerAttr.minorTickMarkPen() );
330
painter->drawLine( leftPoint, rightPoint );
337
if ( isLogarithmic ){
338
if( logSubstep == 9 ){
339
fLogSubstep *= ( fLogSubstep > 0.0 ) ? 10.0 : 0.1;
340
if( fLogSubstep == 0 )
351
f += dim.subStepWidth;
357
const TextAttributes CartesianAxis::Private::titleTextAttributesWithAdjustedRotation() const
359
TextAttributes titleTA( titleTextAttributes );
360
if( (position == Left || position == Right) ){
361
int rotation = titleTA.rotation() + 270;
362
if( rotation >= 360 )
365
// limit the allowed values to 0, 90, 180, 270:
368
else if( rotation < 180 )
370
else if( rotation < 270 )
372
else if( rotation < 360 )
377
titleTA.setRotation( rotation );
382
void CartesianAxis::setTitleSpace( qreal axisTitleSpace )
384
d->axisTitleSpace = axisTitleSpace;
387
qreal CartesianAxis::titleSpace() const
389
return d->axisTitleSpace;
392
void CartesianAxis::Private::drawTitleText( QPainter* painter, CartesianCoordinatePlane* plane, const QRect& areaGeoRect ) const
394
const TextAttributes titleTA( titleTextAttributesWithAdjustedRotation() );
395
if( titleTA.isVisible() ) {
396
TextLayoutItem titleItem( titleText,
399
KDChartEnums::MeasureOrientationMinimum,
400
Qt::AlignHCenter|Qt::AlignVCenter );
402
QSize size( titleItem.sizeHint() );
403
//FIXME(khz): We definitely need to provide a way that users can decide
404
// the position of an axis title.
408
point.setX( areaGeoRect.left() + areaGeoRect.width() / 2.0);
409
point.setY( areaGeoRect.top() + (size.height() / 2)*1/axisTitleSpace );
410
size.setWidth( qMin( size.width(), axis()->geometry().width() ) );
413
point.setX( areaGeoRect.left() + areaGeoRect.width() / 2.0);
414
point.setY( areaGeoRect.bottom() - (size.height()/2)*1/axisTitleSpace);
415
size.setWidth( qMin( size.width(), axis()->geometry().width() ) );
418
point.setX( areaGeoRect.left() + (size.width() / 2)*1/axisTitleSpace);
419
point.setY( areaGeoRect.top() + areaGeoRect.height() / 2.0);
420
size.setHeight( qMin( size.height(), axis()->geometry().height() ) );
423
point.setX( areaGeoRect.right() - (size.width() / 2)*1/axisTitleSpace);
424
point.setY( areaGeoRect.top() + areaGeoRect.height() / 2.0);
425
size.setHeight( qMin( size.height(), axis()->geometry().height() ) );
428
const PainterSaver painterSaver( painter );
429
painter->translate( point );
430
//if( axis()->isOrdinate() )
431
// painter->rotate( 270.0 );
432
titleItem.setGeometry( QRect( QPoint(-size.width() / 2, -size.height() / 2), size ) );
433
//painter->drawRect(titleItem.geometry().adjusted(0,0,-1,-1));
434
titleItem.paint( painter );
439
static void calculateNextLabel( qreal& labelValue, qreal step, bool isLogarithmic, qreal min )
441
if ( isLogarithmic ){
446
if( labelValue == 0.0 )
447
labelValue = pow( 10.0, floor( log10( min ) ) );
449
//qDebug() << "new axis label:" << labelValue << "+" << step << "=" << labelValue+step;
451
if( qAbs(labelValue) < 1.0e-15 )
457
void CartesianAxis::paintCtx( PaintContext* context )
460
Q_ASSERT_X ( d->diagram(), "CartesianAxis::paint",
461
"Function call not allowed: The axis is not assigned to any diagram." );
463
CartesianCoordinatePlane* plane = dynamic_cast<CartesianCoordinatePlane*>(context->coordinatePlane());
464
Q_ASSERT_X ( plane, "CartesianAxis::paint",
465
"Bad function call: PaintContext::coodinatePlane() NOT a cartesian plane." );
467
// note: Not having any data model assigned is no bug
468
// but we can not draw an axis then either.
469
if( ! d->diagram()->model() )
472
// Determine the diagram that specifies the orientation of the diagram we're painting here
473
// That diagram is the reference diagram, if it exists, or otherwise the diagram itself.
474
// Note: In KDChart 2.3 or earlier, only a bar diagram can be vertical instead of horizontal.
475
const AbstractCartesianDiagram * refDiagram = qobject_cast< const AbstractCartesianDiagram * >( d->diagram() );
476
if( refDiagram && refDiagram->referenceDiagram() )
477
refDiagram = refDiagram->referenceDiagram();
478
const BarDiagram *barDiagram = qobject_cast< const BarDiagram* >( refDiagram );
479
const Qt::Orientation diagramOrientation = barDiagram ? barDiagram->orientation() : Qt::Vertical;
480
const bool diagramIsVertical = diagramOrientation == Qt::Vertical;
483
* let us paint the labels at a
485
* Same mini pixel value as for
488
//const qreal MinimumPixelsBetweenRulers = 1.0;
489
DataDimensionsList dimensions( plane->gridDimensionsList() );
490
//qDebug("CartesianAxis::paintCtx() gets DataDimensionsList.first(): start: %f end: %f stepWidth: %f", dimensions.first().start, dimensions.first().end, dimensions.first().stepWidth);
492
// test for programming errors: critical
493
Q_ASSERT_X ( dimensions.count() == 2, "CartesianAxis::paint",
494
"Error: plane->gridDimensionsList() did not return exactly two dimensions." );
495
DataDimension dimX, dimY;
497
// If the diagram is horizontal, we need to inverse the x/y ranges
498
if ( diagramIsVertical ) {
499
/*double yStart = dimY.start;
500
double yEnd = dimY.end;
501
dimY.start = dimX.start;
505
dimX = AbstractGrid::adjustedLowerUpperRange( dimensions.first(), true, true );
506
dimY = AbstractGrid::adjustedLowerUpperRange( dimensions.last(), true, true );
509
// Ugly workaround for dimensions being bound to both, the x coordinate direction and the abscissa
510
//if ( referenceDiagramIsPercentLyingBarDiagram ) {
511
// dimY.stepWidth = 10.0;
512
// dimY.subStepWidth = 2.0;
515
dimX = AbstractGrid::adjustedLowerUpperRange( dimensions.last(), true, true );
516
dimY = AbstractGrid::adjustedLowerUpperRange( dimensions.first(), true, true );
518
dim = (isAbscissa() ? dimX : dimY);
522
qDebug() << " " << "Abscissa:" << dimX.start <<".."<<dimX.end <<" step"<<dimX.stepWidth<<" sub step"<<dimX.subStepWidth;
524
qDebug() << " " << "Ordinate:" << dimY.start <<".."<<dimY.end <<" step"<<dimY.stepWidth<<" sub step"<<dimY.subStepWidth;
528
* let us paint the labels at a
530
* Same mini pixel value as for
533
const qreal MinimumPixelsBetweenRulers = qMin( dimX.stepWidth, dimY.stepWidth );//1.0;
535
// preparation: calculate the range that will be displayed:
536
const qreal absRange = qAbs( dim.distance() );
538
qreal numberOfUnitRulers;
539
if ( isAbscissa() ) {
540
if( dimX.isCalculated )
541
numberOfUnitRulers = absRange / qAbs( dimX.stepWidth ) + 1.0;
543
numberOfUnitRulers = d->diagram()->model()->rowCount(d->diagram()->rootIndex()) - 1.0;
545
numberOfUnitRulers = absRange / qAbs( dimY.stepWidth ) + 1.0;
548
// qDebug() << "absRange" << absRange << "dimY.stepWidth:" << dimY.stepWidth << "numberOfUnitRulers:" << numberOfUnitRulers;
550
qreal numberOfSubUnitRulers;
552
if( dimX.isCalculated )
553
numberOfSubUnitRulers = absRange / qAbs( dimX.subStepWidth ) + 1.0;
555
numberOfSubUnitRulers = dimX.subStepWidth>0 ? absRange / qAbs( dimX.subStepWidth ) + 1.0 : 0.0;
557
numberOfSubUnitRulers = absRange / qAbs( dimY.subStepWidth ) + 1.0;
560
// - calculate the absolute range in screen pixels:
561
const QPointF p1 = plane->translate( diagramIsVertical ? QPointF(dimX.start, dimY.start) : QPointF(dimY.start, dimX.start) );
562
const QPointF p2 = plane->translate( diagramIsVertical ? QPointF(dimX.end, dimY.end) : QPointF(dimY.end, dimX.end ) );
566
screenRange = qAbs ( p1.x() - p2.x() );
568
screenRange = qAbs ( p1.y() - p2.y() );
570
const bool useItemCountLabels = isAbscissa() && ! dimX.isCalculated;
572
// attributes used to customize ruler appearance
573
const RulerAttributes rulerAttr = rulerAttributes();
575
const bool drawUnitRulers = rulerAttr.showMajorTickMarks() && (screenRange / ( numberOfUnitRulers / dimX.stepWidth ) > MinimumPixelsBetweenRulers);
576
const bool drawSubUnitRulers = rulerAttr.showMinorTickMarks() &&
577
(numberOfSubUnitRulers != 0.0) &&
578
(screenRange / numberOfSubUnitRulers > MinimumPixelsBetweenRulers);
580
const TextAttributes labelTA = textAttributes();
581
const bool drawLabels = labelTA.isVisible();
583
// - find the reference point at which to start drawing and the increment (line distance);
585
// Point at the other end of the axis
587
const QRect areaGeoRect( areaGeometry() );
588
const QRect geoRect( geometry() );
591
QPainter* const ptr = context->painter();
593
//for debugging: if( isAbscissa() )ptr->drawRect(areaGeoRect.adjusted(0,0,-1,-1));
594
//qDebug() << " " << (isAbscissa() ? "Abscissa":"Ordinate") << "axis painting with geometry" << areaGeoRect;
596
// The "major" ruler line perpendicular to all tick mark lines
598
// FIXME references are of course different for all locations:
602
rulerRef.setX( areaGeoRect.x() );
603
rulerRef.setY( areaGeoRect.y() + areaGeoRect.height() );
604
rulerRef2 = rulerRef;
605
rulerRef2.rx() += areaGeoRect.width();
608
rulerRef.setX( areaGeoRect.x() );
609
rulerRef.setY( areaGeoRect.y() );
610
rulerRef2 = rulerRef;
611
rulerRef2.rx() += areaGeoRect.width();
614
rulerRef.setX( areaGeoRect.x() );
615
rulerRef.setY( areaGeoRect.y() + areaGeoRect.height() );
616
rulerRef2 = rulerRef;
617
rulerRef2.ry() -= areaGeoRect.height();
620
rulerRef.setX( areaGeoRect.x() + areaGeoRect.width() );
621
rulerRef.setY( areaGeoRect.y() + areaGeoRect.height() );
622
rulerRef2 = rulerRef;
623
rulerRef2.ry() -= areaGeoRect.height();
627
if ( rulerAttr.showRulerLine() ) {
628
ptr->setPen( rulerAttr.pen() );
629
ptr->drawLine( QLineF( rulerRef, rulerRef2 ) );
632
// set up the lines to paint:
634
// set up a map of integer positions,
636
// - starting with the fourth
639
// this will override all halfs and fourth that hit a higher-order ruler
640
// MAKE SURE TO START AT (0, 0)!
642
// set up a reference point, a step vector and a unit vector for the drawing:
644
const qreal minValueY = dimY.start;
645
const qreal maxValueY = dimY.end;
646
const qreal minValueX = dimX.start;
647
const qreal maxValueX = dimX.end;
648
const bool isLogarithmicX = (dimX.calcMode == AbstractCoordinatePlane::Logarithmic );
649
const bool isLogarithmicY = (dimY.calcMode == AbstractCoordinatePlane::Logarithmic );
650
//#define AXES_PAINTING_DEBUG 1
651
#ifdef AXES_PAINTING_DEBUG
652
qDebug() << "CartesianAxis::paint: reference values:" << endl
653
<< "-- range x/y: " << dimX.distance() << "/" << dimY.distance() << endl
654
<< "-- absRange: " << absRange << endl
655
<< "-- numberOfUnitRulers: " << numberOfUnitRulers << endl
656
<< "-- screenRange: " << screenRange << endl
657
<< "-- drawUnitRulers: " << drawUnitRulers << endl
658
<< "-- drawLabels: " << drawLabels << endl
659
<< "-- ruler reference point:: " << rulerRef << endl
660
<< "-- minValueX: " << minValueX << " maxValueX: " << maxValueX << endl
661
<< "-- minValueY: " << minValueY << " maxValueY: " << maxValueY << endl
665
// solving issue #4075 in a quick way:
666
ptr->setPen ( PrintingParameters::scalePen( labelTA.pen() ) ); // perhaps we want to add a setter method later?
668
//ptr->setPen ( Qt::black );
670
const QObject* referenceArea = plane->parent();
672
// that QVector contains all drawn x-ticks (so no subticks are drawn there also)
673
QVector< int > drawnAbscissaTicks;
674
// and that does the same for the y-ticks
675
QVector< int > drawnYTicks;
678
* Find out if it is a bar diagram
679
* bar diagrams display their data per column
680
* we need to handle the last label another way
681
* 1 - Last label == QString null ( Header Labels )
682
* 2 - Display labels and ticks in the middle of the column
685
const bool centerAbscissaTicks = referenceDiagramNeedsCenteredAbscissaTicks( d->diagram() );
687
// this draws the unit rulers
688
if ( drawUnitRulers ) {
689
const QStringList labelsList( labels() );
690
const QStringList shortLabelsList( shortLabels() );
691
const int hardLabelsCount = labelsList.count();
692
const int shortLabelsCount = shortLabelsList.count();
693
bool useShortLabels = false;
695
bool useConfiguredStepsLabels = false;
696
QStringList headerLabels;
697
if( useItemCountLabels ){
698
//qDebug() << (isOrdinate() ? "is Ordinate" : "is Abscissa");
701
? d->diagram()->datasetLabels()
702
: d->diagram()->itemRowLabels();
703
//qDebug() << numberOfUnitRulers;
704
// check if configured stepWidth
705
useConfiguredStepsLabels = isAbscissa() &&
707
(( (headerLabels.count() - 1)/ dimX.stepWidth ) != numberOfUnitRulers);
708
if( useConfiguredStepsLabels ) {
709
numberOfUnitRulers = ( headerLabels.count() - 1 )/ dimX.stepWidth;
710
// we need to register data values for the steps
711
// in case it is configured by the user
712
QStringList configuredStepsLabels;
713
double value = dimX.start;// headerLabels.isEmpty() ? 0.0 : headerLabels.first().toDouble();
714
configuredStepsLabels << QString::number( value );
716
for( int i = 0; i < numberOfUnitRulers; i++ )
719
value += dimX.stepWidth;
720
configuredStepsLabels.append( d->diagram()->unitPrefix( i, diagramIsVertical ? Qt::Horizontal : Qt::Vertical, true ) +
721
QString::number( value ) +
722
d->diagram()->unitSuffix( i, diagramIsVertical ? Qt::Horizontal : Qt::Vertical, true ) );
724
headerLabels = configuredStepsLabels;
727
if ( centerAbscissaTicks )
728
headerLabels.append( QString() );
731
const int headerLabelsCount = headerLabels.count();
732
//qDebug() << "headerLabelsCount" << headerLabelsCount;
734
TextLayoutItem* labelItem =
736
? new TextLayoutItem( QString::number( minValueY ),
739
KDChartEnums::MeasureOrientationMinimum,
742
TextLayoutItem* labelItem2 =
744
? new TextLayoutItem( QString::number( minValueY ),
747
KDChartEnums::MeasureOrientationMinimum,
750
const QFontMetricsF met(
752
? labelItem->realFont()
753
: QFontMetricsF( QApplication::font(), GlobalMeasureScaling::paintDevice() ) );
754
const qreal halfFontHeight = rulerAttr.labelMargin() >= 0 ? rulerAttr.labelMargin() : met.height() * 0.5;
755
const qreal halfFontWidth = rulerAttr.labelMargin() >= 0 ? rulerAttr.labelMargin() : met.averageCharWidth() * 0.5;
757
if ( isAbscissa() ) {
758
//Draw ticks at custom postions on x-axis
759
if( !d->customTicksPositions.isEmpty() )
761
const QList< double > values = d->customTicksPositions;
762
KDAB_FOREACH( const double v, values )
764
QPointF topPoint = diagramIsVertical ? QPointF( v, 0.0 ) : QPointF( 0.0, v );
765
QPointF bottomPoint = topPoint;
766
topPoint = plane->translate( topPoint );
767
bottomPoint = plane->translate( bottomPoint );
768
if ( diagramIsVertical ) {
769
topPoint.setY( rulerRef.y() + tickLength() );
770
bottomPoint.setY( rulerRef.y() );
772
topPoint.setX( rulerRef.x() + tickLength() );
773
bottomPoint.setX( rulerRef.x() );
776
context->painter()->drawLine(topPoint, bottomPoint);
780
if( !d->annotations.isEmpty() )
782
const QList< double > values = d->annotations.keys();
783
KDAB_FOREACH( const double v, values )
785
QPointF topPoint = diagramIsVertical ? QPointF( v, 0.0 ) : QPointF( 0.0, v );
786
QPointF bottomPoint = topPoint;
787
topPoint = plane->translate( topPoint );
788
bottomPoint = plane->translate( bottomPoint );
789
if ( diagramIsVertical ) {
790
topPoint.setY( rulerRef.y() + tickLength() );
791
bottomPoint.setY( rulerRef.y() );
793
topPoint.setX( rulerRef.x() + tickLength() );
794
bottomPoint.setX( rulerRef.x() );
797
labelItem->setText( d->annotations[ v ] );
798
const QSize size( labelItem->sizeHint() );
799
if ( diagramIsVertical ) {
800
labelItem->setGeometry(
803
static_cast<int>( topPoint.x() - size.width() / 2.0 ),
804
static_cast<int>( topPoint.y() +
805
( position() == Bottom
807
: ((halfFontHeight + size.height()) * -1.0) ) ) ),
810
labelItem->setGeometry(
813
static_cast<int>( bottomPoint.x() +
814
( position() == Right
816
: (-halfFontWidth - size.width()) ) ),
818
static_cast<int>( topPoint.y() - ( size.height() ) * 0.5 ) ),
822
QRect labelGeo = labelItem->geometry();
823
// if our item would only half fit, we disable clipping for that one
824
if( labelGeo.left() < geoRect.left() && labelGeo.right() > geoRect.left() )
825
ptr->setClipping( false );
826
else if( labelGeo.left() < geoRect.right() && labelGeo.right() > geoRect.right() )
827
ptr->setClipping( false );
829
labelItem->paint( ptr );
833
qreal labelDiff = dimX.stepWidth;
834
const int precision = ( QString::number( labelDiff ).section( QLatin1Char('.'), 1, 2 ) ).length();
836
// If we have a labels list AND a short labels list, we first find out,
837
// if there is enough space for showing ALL of the long labels:
838
// If not, use the short labels.
839
if( drawLabels && hardLabelsCount > 0 && shortLabelsCount > 0 && d->annotations.isEmpty() ){
840
bool labelsAreOverlapping = false;
843
while ( i < maxValueX-1 && !labelsAreOverlapping )
845
const int idx = (iLabel < hardLabelsCount ) ? iLabel : 0;
846
const int idx2= (iLabel < hardLabelsCount - 1) ? iLabel + 1 : 0;
847
if ( dimX.stepWidth != 1.0 && ! dim.isCalculated )
849
// Check intersects for the header label - we need to pass the full string
850
// here and not only the i value.
851
if( useConfiguredStepsLabels ){
852
labelItem->setText( customizedLabel(headerLabels[ idx ]) );
853
labelItem2->setText( customizedLabel(headerLabels[ idx2 ]) );
855
//qDebug() << "i + labelDiff " << i + labelDiff;
856
labelItem->setText( customizedLabel(headerLabelsCount > i && i >= 0 ?
857
headerLabels[static_cast<int>(i)] :
858
QString::number( i, 'f', precision )) );
859
// qDebug() << "1 - labelItem->text() " << labelItem->text();
860
//qDebug() << "labelDiff" << labelDiff
861
// << " index" << i+labelDiff << " count" << headerLabelsCount;
862
labelItem2->setText( customizedLabel(headerLabelsCount > i + labelDiff && i + labelDiff >= 0 ?
863
headerLabels[static_cast<int>(i+labelDiff)] :
864
QString::number( i + labelDiff, 'f', precision )) );
865
//qDebug() << "2 - labelItem->text() " << labelItem->text();
868
//qDebug() << iLabel << i << "("<<hardLabelsCount<<") :";
869
const int shortIdx = (iLabel < shortLabelsCount ) ? iLabel : 0;
870
const int shortIdx2 = (iLabel < shortLabelsCount - 1) ? iLabel + 1 : 0;
871
labelItem->setText( customizedLabel(
872
useShortLabels ? shortLabelsList[ shortIdx ] : labelsList[ idx ] ) );
873
labelItem2->setText( customizedLabel(
874
useShortLabels ? shortLabelsList[ shortIdx2 ] : labelsList[ idx2 ] ) );
877
QPointF firstPos = diagramIsVertical ? QPointF( i, 0.0 ) : QPointF( 0.0, i );
878
firstPos = plane->translate( firstPos );
880
QPointF secondPos = diagramIsVertical ? QPointF( i + labelDiff, 0.0 ) : QPointF( 0.0, i + labelDiff );
881
secondPos = plane->translate( secondPos );
883
labelsAreOverlapping = labelItem->intersects( *labelItem2, firstPos, secondPos );
885
if ( ++iLabel > hardLabelsCount - 1 )
887
if ( isLogarithmicX )
891
//qDebug() << labelsAreOverlapping << iLabel << i << labelsAreOverlapping << firstPos << secondPos.x()-firstPos .x() << labelItem->text() << labelItem2->text();
894
useShortLabels = labelsAreOverlapping;
897
// qDebug() << "initial labelDiff " << labelDiff;
898
if ( drawLabels && d->annotations.isEmpty() )
903
while ( i + labelDiff < maxValueX )
905
const int idx = (iLabel < hardLabelsCount ) ? iLabel : 0;
906
const int idx2= (iLabel < hardLabelsCount - 1) ? iLabel + 1 : 0;
907
//qDebug() << "drawLabels" << drawLabels << " hardLabelsCount" << hardLabelsCount
908
// << " dimX.stepWidth" << dimX.stepWidth << " dim.isCalculated" << dim.isCalculated;
909
if ( !drawLabels || hardLabelsCount < 1 || ( dimX.stepWidth != 1.0 && ! dim.isCalculated ) )
911
// Check intersects for the header label - we need to pass the full string
912
// here and not only the i value.
913
if( useConfiguredStepsLabels ){
914
labelItem->setText( customizedLabel(headerLabels[ idx ]) );
915
labelItem2->setText( customizedLabel(headerLabels[ idx2 ]) );
917
//qDebug() << "i + labelDiff " << i + labelDiff;
918
labelItem->setText( customizedLabel(headerLabelsCount > i && i >= 0 ?
919
headerLabels[static_cast<int>(i)] :
920
QString::number( i, 'f', precision )) );
921
// qDebug() << "1 - labelItem->text() " << labelItem->text();
922
//qDebug() << "labelDiff" << labelDiff
923
// << " index" << i+labelDiff << " count" << headerLabelsCount;
924
labelItem2->setText( customizedLabel(headerLabelsCount > i + labelDiff && i + labelDiff >= 0 ?
925
headerLabels[static_cast<int>(i+labelDiff)] :
926
QString::number( i + labelDiff, 'f', precision )) );
927
//qDebug() << "2 - labelItem->text() " << labelItem->text();
930
const int shortIdx = (iLabel < shortLabelsCount ) ? iLabel : 0;
931
const int shortIdx2 = (iLabel < shortLabelsCount - 1) ? iLabel + 1 : 0;
932
labelItem->setText( customizedLabel(
933
useShortLabels ? shortLabelsList[ shortIdx ] : labelsList[ idx ] ) );
934
labelItem2->setText( customizedLabel(
935
useShortLabels ? shortLabelsList[ shortIdx2 ] : labelsList[ idx2 ] ) );
938
QPointF firstPos = diagramIsVertical ? QPointF( i, 0.0 ) : QPointF( 0.0, i );
939
firstPos = plane->translate( firstPos );
941
QPointF secondPos = diagramIsVertical ? QPointF( i + labelDiff, 0.0 ) : QPointF( 0.0, i + labelDiff );
942
secondPos = plane->translate( secondPos );
944
if ( labelItem->intersects( *labelItem2, firstPos, secondPos ) )
948
// fix for issue #4179:
950
// old code: labelDiff += labelDiff;
953
//qDebug() << firstPos << secondPos.x()-firstPos .x() << labelItem->text() << labelItem2->text() << labelDiff;
958
//qDebug() << firstPos << secondPos.x()-firstPos .x() << labelItem->text() << labelItem2->text();
961
if ( (++iLabel > hardLabelsCount - 1) && !useConfiguredStepsLabels )
966
// fixing bugz issue #5018 without breaking issue #4179:
967
if( minValueX + labelDiff > maxValueX )
968
labelDiff = maxValueX - minValueX;
969
// This makes sure the first and the last X label are drawn
970
// if there is not enouth place to draw some more of them
971
// according to labelDiff calculation performed above.
975
qreal iLabelF = minValueX;
976
//qDebug() << iLabelF;
978
qreal labelStep = 0.0;
979
// qDebug() << "dimX.stepWidth:" << dimX.stepWidth << "labelDiff:" << labelDiff;
980
//dimX.stepWidth = 0.5;
981
while( i <= maxValueX && d->annotations.isEmpty() )
983
// Line charts: we want the first tick to begin at 0.0 not at 0.5 otherwise labels and
984
// values does not fit each others
985
QPointF topPoint = diagramIsVertical ? QPointF( i + ( centerAbscissaTicks ? 0.5 : 0.0 ), 0.0 ) : QPointF( 0.0, i + ( centerAbscissaTicks ? 0.5 : 0.0 ) );
986
QPointF bottomPoint ( topPoint );
987
topPoint = plane->translate( topPoint );
988
bottomPoint = plane->translate( bottomPoint );
989
if ( diagramIsVertical ) {
990
topPoint.setY( rulerRef.y() + tickLength() );
991
bottomPoint.setY( rulerRef.y() );
993
bottomPoint.setX( rulerRef.x() - (position() == Left ? tickLength() : -tickLength()) );
994
topPoint.setX( rulerRef.x() );
997
const qreal translatedValue = diagramIsVertical ? topPoint.x() : topPoint.y();
998
bool bIsVisibleLabel;
999
if ( diagramIsVertical )
1000
bIsVisibleLabel = ( (translatedValue >= geoRect.left() && translatedValue <= geoRect.right() && !isLogarithmicX) || i != 0.0 );
1002
bIsVisibleLabel = ( (translatedValue >= geoRect.top() && translatedValue <= geoRect.bottom() && !isLogarithmicX) || i != 0.0 );
1004
// fix for issue #4179:
1005
bool painttick = bIsVisibleLabel && labelStep <= 0;
1006
// old code: bool painttick = true;
1008
//Dont paint more ticks than we need
1009
//when diagram type is Bar
1010
if ( centerAbscissaTicks && i == maxValueX )
1013
if ( bIsVisibleLabel && painttick ) {
1015
if ( rulerAttr.hasTickMarkPenAt( i ) )
1016
ptr->setPen( rulerAttr.tickMarkPen( i ) );
1018
ptr->setPen( rulerAttr.majorTickMarkPen() );
1019
ptr->drawLine( topPoint, bottomPoint );
1023
drawnAbscissaTicks.append( static_cast<int>( diagramIsVertical ? topPoint.x() : topPoint.y() ) );
1025
if( bIsVisibleLabel ){
1026
if ( isLogarithmicX )
1027
labelItem->setText( customizedLabel(QString::number( i ) ) );
1028
/* We don't need that
1029
* it causes header labels to be skipped even if there is enough
1030
* space for them to displayed.
1031
* Commenting for now - I need to test more in details - Let me know if I am wrong here.
1034
else if( (dimX.stepWidth != 1.0) && ! dimX.isCalculated ) {
1035
labelItem->setText( customizedLabel(QString::number( i, 'f', 0 )) );
1039
int idx = idxLabel + static_cast<int>(minValueX);
1040
if( hardLabelsCount ){
1041
if( useShortLabels ){
1042
if( idx >= shortLabelsList.count() )
1045
if( idx >= labelsList.count() )
1052
? ( useShortLabels ? shortLabelsList[ idx ] : labelsList[ idx ] )
1053
: ( headerLabelsCount ? headerLabels[ idx ] : QString::number( iLabelF ))));
1054
//qDebug() << "x - labelItem->text() " << labelItem->text() << headerLabelsCount;
1056
// No need to call labelItem->setParentWidget(), since we are using
1057
// the layout item temporarily only.
1058
if( labelStep <= 0 ) {
1059
const PainterSaver p( ptr );
1060
//const QSize size( labelItem->sizeHint() );
1061
QPoint topLeft, topRight, bottomRight, bottomLeft;
1063
labelItem->sizeHintAndRotatedCorners(
1064
topLeft, topRight, bottomRight, bottomLeft) );
1065
const QSize sizeUnrotated( labelItem->sizeHintUnrotated() );
1066
const int rotation = labelTA.rotation();
1067
const bool rotPositive = (rotation > 0 && rotation < 180);
1068
QPoint midOfSide(0,0);
1073
midOfSide = (topLeft + bottomLeft) / 2;
1074
dX = topLeft.x() - midOfSide.x();
1075
dY = bottomLeft.y() - midOfSide.y();
1077
midOfSide = (topRight + bottomRight) / 2;
1078
dX = midOfSide.x() - topLeft.x();
1079
dY = midOfSide.y() - topRight.y();
1084
qDebug()<<"------"<<size<<topPoint<<topLeft<<topRight<<bottomRight<<bottomLeft<<" m:"<<midOfSide<<" dx"<<dX<<" dy"<<dY;
1085
ptr->setPen( Qt::black );
1086
QRectF rect(topPoint, QSizeF(sizeUnrotated));
1087
ptr->drawRect( rect );
1088
ptr->drawRect( QRectF(topPoint, QSizeF(2,2)) );
1089
ptr->drawRect( QRectF(topPoint+topLeft, QSizeF(2,2)) );
1090
ptr->drawRect( QRectF(topPoint+bottomLeft, QSizeF(2,2)) );
1091
ptr->drawRect( QRectF(topPoint+bottomRight, QSizeF(2,2)) );
1092
ptr->drawRect( QRectF(topPoint+topRight, QSizeF(2,2)) );
1093
ptr->drawRect( QRectF(topPoint+midOfSide, QSizeF(2,2)) );
1094
ptr->setPen( Qt::green );
1095
rect = QRectF(topPoint, QSizeF(size));
1096
ptr->drawRect( rect );
1097
ptr->drawRect( QRectF(QPointF((rect.topLeft() + rect.bottomLeft()) / 2.0 - QPointF(2.0,2.0)), QSizeF(3.0,3.0)) );
1098
//ptr->drawRect( QRectF(QPointF((rect.topRight() + rect.bottomRight()) / 2.0 - QPointF(2.0,2.0)), QSizeF(3.0,3.0)) );
1102
if( diagramIsVertical ){
1105
static_cast<int>( topPoint.x() ) - dX,
1106
static_cast<int>( topPoint.y() - dY +
1107
( position() == Bottom
1109
: ((halfFontHeight + size.height()) * -1.0) ) ) );
1112
static_cast<int>( topPoint.x() - size.width() / 2.0 ),
1113
static_cast<int>( topPoint.y() +
1114
( position() == Bottom
1116
: ((halfFontHeight + size.height()) * -1.0) ) ) );
1121
static_cast<int>( topPoint.x() ) + dX,
1122
static_cast<int>( topPoint.y() - dY +
1123
( position() == Bottom
1125
: ((halfFontHeight + size.height()) * -1.0) ) ) );
1128
static_cast<int>( bottomPoint.x() +
1129
( position() == Right
1131
: (-halfFontWidth - size.width()) ) ),
1132
static_cast<int>( topPoint.y() - ( size.height() ) * 0.5 ) );
1135
labelItem->setGeometry( QRect(topLeftPt, size) );
1137
QRect labelGeo = labelItem->geometry();
1138
//ptr->drawRect(labelGeo);
1139
// if our item would only half fit, we disable clipping for that one
1140
if( labelGeo.left() < geoRect.left() && labelGeo.right() > geoRect.left() )
1141
ptr->setClipping( false );
1142
else if( labelGeo.left() < geoRect.right() && labelGeo.right() > geoRect.right() )
1143
ptr->setClipping( false );
1145
if( !isLogarithmicX )
1146
labelStep = labelDiff - dimX.stepWidth;
1148
// if our item would only half fit, we disable clipping for that one
1149
if( labelGeo.left() < geoRect.left() && labelGeo.right() > geoRect.left() )
1150
ptr->setClipping( false );
1151
else if( labelGeo.left() < geoRect.right() && labelGeo.right() > geoRect.right() )
1152
ptr->setClipping( false );
1154
labelItem->paint( ptr );
1156
// do not call customizedLabel() again:
1157
labelItem2->setText( labelItem->text() );
1160
labelStep -= dimX.stepWidth;
1164
if( hardLabelsCount ) {
1165
if( useShortLabels && idxLabel >= shortLabelsCount - 1 )
1167
else if( !useShortLabels && idxLabel >= hardLabelsCount - 1 )
1170
idxLabel += static_cast<int>(dimX.stepWidth);
1171
//qDebug() << "dimX.stepWidth:" << dimX.stepWidth << " idxLabel:" << idxLabel;
1173
} else if( headerLabelsCount ) {
1174
if( ++idxLabel > headerLabelsCount - 1 ) {
1178
iLabelF += dimX.stepWidth;
1181
if ( isLogarithmicX )
1186
const qreal j = dimensions.first().start;
1187
i = j == 0.0 ? 1.0 : pow( 10.0, floor( log10( j ) ) );
1192
i += dimX.stepWidth;
1196
const PainterSaver p( ptr );
1197
const double maxLimit = maxValueY;
1198
const double steg = dimY.stepWidth;
1199
int maxLabelsWidth = 0;
1201
if( drawLabels && position() == Right ){
1202
// Find the widest label, so we to know how much we need to right-shift
1203
// our labels, to get them drawn right aligned:
1204
labelValue = minValueY;
1205
while ( labelValue <= maxLimit ) {
1206
const QString labelText = diagram()->unitPrefix( static_cast< int >( labelValue ), diagramOrientation, true ) +
1207
QString::number( labelValue ) +
1208
diagram()->unitSuffix( static_cast< int >( labelValue ), diagramOrientation, true );
1209
labelItem->setText( customizedLabel( labelText ) );
1210
maxLabelsWidth = qMax( maxLabelsWidth, diagramIsVertical ? labelItem->sizeHint().width() : labelItem->sizeHint().height() );
1212
calculateNextLabel( labelValue, steg, isLogarithmicY, dimensions.last().start );
1216
labelValue = minValueY;
1218
bool nextLabel = false;
1219
//qDebug("minValueY: %f maxLimit: %f steg: %f", minValueY, maxLimit, steg);
1221
//Draws custom tick marks in the y-axis
1222
if( !d->customTicksPositions.isEmpty() )
1224
const QList< double > values = d->customTicksPositions;
1225
KDAB_FOREACH( const double value, values )
1227
QPointF annoPoint = (diagramIsVertical ? QPointF( 0.0, value ) : QPointF( value, 0.0 ));
1228
QPointF leftPoint = plane->translate( annoPoint );
1229
QPointF rightPoint = plane->translate( annoPoint );
1231
if ( diagramIsVertical ) {
1232
leftPoint.setX( rulerRef.x() + tickLength() );
1233
rightPoint.setX( rulerRef.x() );
1235
leftPoint.setY( rulerRef.y() + ((position() == Bottom) ? tickLength() : -tickLength()) );
1236
rightPoint.setY( rulerRef.y() );
1239
context->painter()->drawLine(leftPoint, rightPoint);
1245
// first calculate the steps depending on labels colision
1246
while( labelValue <= maxLimit ) {
1247
QPointF leftPoint = plane->translate( diagramIsVertical ? QPointF( 0, labelValue ) : QPointF( labelValue, 0 ) );
1248
const qreal translatedValue = diagramIsVertical ? leftPoint.y() : leftPoint.x();
1249
//qDebug() << "geoRect:" << geoRect << " geoRect.top()" << geoRect.top() << "geoRect.bottom()" << geoRect.bottom() << " translatedValue:" << translatedValue;
1250
const bool bTranslatedValueIsWithinRange = diagramIsVertical ? translatedValue > geoRect.top() && translatedValue <= geoRect.bottom()
1251
: translatedValue > geoRect.left() && translatedValue <= geoRect.right();
1252
if( bTranslatedValueIsWithinRange ){
1253
const QString labelText = diagram()->unitPrefix( static_cast< int >( labelValue ), diagramOrientation, true ) +
1254
QString::number( labelValue ) +
1255
diagram()->unitSuffix( static_cast< int >( labelValue ), diagramOrientation, true );
1256
const QString label2Text = diagram()->unitPrefix( static_cast< int >( labelValue + step ), diagramOrientation, true ) +
1257
QString::number( labelValue + step ) +
1258
diagram()->unitSuffix( static_cast< int >( labelValue + step ), diagramOrientation, true );
1259
labelItem->setText( customizedLabel( labelText ) );
1260
labelItem2->setText( customizedLabel( QString::number( labelValue + step ) ) );
1261
QPointF nextPoint = plane->translate( diagramIsVertical ? QPointF( 0, labelValue + step ) : QPointF( labelValue + step, 0 ) );
1262
if ( labelItem->intersects( *labelItem2, leftPoint, nextPoint ) )
1273
if ( nextLabel || isLogarithmicY )
1274
calculateNextLabel( labelValue, step, isLogarithmicY, dimensions.last().start );
1276
labelValue = minValueY;
1279
// Second - Paint the labels
1280
labelValue = minValueY;
1281
//qDebug() << "axis labels starting at" << labelValue << "step width" << step;
1282
if( !d->annotations.isEmpty() )
1284
const QList< double > annotations = d->annotations.keys();
1285
KDAB_FOREACH( const double annotation, annotations )
1287
QPointF annoPoint = (diagramIsVertical ? QPointF( 0.0, annotation ) : QPointF( annotation, 0.0 ));
1288
QPointF leftPoint = plane->translate( annoPoint );
1289
QPointF rightPoint = plane->translate( annoPoint );
1291
if ( diagramIsVertical ) {
1292
leftPoint.setX( rulerRef.x() + tickLength() );
1293
rightPoint.setX( rulerRef.x() );
1295
leftPoint.setY( rulerRef.y() + ((position() == Bottom) ? tickLength() : -tickLength()) );
1296
rightPoint.setY( rulerRef.y() );
1299
const qreal translatedValue = diagramIsVertical ? rightPoint.y() : rightPoint.x();
1300
const bool bIsVisibleLabel = diagramIsVertical ?
1301
( (translatedValue >= geoRect.top() && translatedValue <= geoRect.bottom() && !isLogarithmicY) || labelValue != 0.0 )
1302
: ( (translatedValue >= geoRect.left() && translatedValue <= geoRect.right() && !isLogarithmicY) || labelValue != 0.0 );
1304
if( bIsVisibleLabel )
1307
if ( rulerAttr.hasTickMarkPenAt( annotation ) )
1308
ptr->setPen( rulerAttr.tickMarkPen( annotation ) );
1310
ptr->setPen( rulerAttr.majorTickMarkPen() );
1311
ptr->drawLine( leftPoint, rightPoint );
1314
labelItem->setText( d->annotations[ annotation ] );
1315
const QSize labelSize( labelItem->sizeHint() );
1317
if ( diagramIsVertical ) {
1318
x = static_cast<int>( leftPoint.x() + met.height() * ( position() == Left ? -0.5 : 0.5)
1319
- ( position() == Left ? labelSize.width() : 0.0 ) );
1320
y = static_cast<int>( leftPoint.y() - ( met.ascent() + met.descent() ) * 0.6 );
1322
const qreal halfFontHeight = met.height() * 0.5;
1323
x = static_cast<int>( leftPoint.x() - labelSize.width() * 0.5 );
1324
y = static_cast<int>( (position() == Bottom ? leftPoint.y() : rightPoint.y()) +
1325
+ ( position() == Bottom ? halfFontHeight : -(halfFontHeight + labelSize.height()) ) );
1327
labelItem->setGeometry( QRect( QPoint( x, y ), labelSize ) );
1329
QRect labelGeo = labelItem->geometry();
1330
// if our item would only half fit, we disable clipping for that one
1331
if( labelGeo.left() < geoRect.left() && labelGeo.right() > geoRect.left() )
1332
ptr->setClipping( false );
1333
else if( labelGeo.left() < geoRect.right() && labelGeo.right() > geoRect.right() )
1334
ptr->setClipping( false );
1336
labelItem->paint( ptr );
1342
while( labelValue <= maxLimit ) {
1343
//qDebug() << "value now" << labelValue;
1344
const QString labelText = diagram()->unitPrefix( static_cast< int >( labelValue ), diagramOrientation, true ) +
1345
QString::number( labelValue ) +
1346
diagram()->unitSuffix( static_cast< int >( labelValue ), diagramOrientation, true );
1347
labelItem->setText( customizedLabel( labelText ) );
1348
QPointF leftPoint = plane->translate( diagramIsVertical ? QPointF( 0, labelValue ) : QPointF( labelValue, 0 ) );
1349
QPointF rightPoint = leftPoint;
1351
if ( diagramIsVertical ) {
1352
leftPoint.setX( rulerRef.x() + tickLength() );
1353
rightPoint.setX( rulerRef.x() );
1355
leftPoint.setY( rulerRef.y() + ((position() == Bottom) ? tickLength() : -tickLength()) );
1356
rightPoint.setY( rulerRef.y() );
1359
bool bIsVisibleLabel;
1360
const qreal translatedValue = diagramIsVertical ? rightPoint.y() : rightPoint.x();
1361
if ( diagramIsVertical)
1362
bIsVisibleLabel = ( (translatedValue >= geoRect.left() && translatedValue <= geoRect.right() && !isLogarithmicX) || labelValue != 0.0 );
1364
bIsVisibleLabel = ( (translatedValue >= geoRect.top() && translatedValue <= geoRect.bottom() && !isLogarithmicX) || labelValue != 0.0 );
1366
if( bIsVisibleLabel ){
1368
if ( rulerAttr.hasTickMarkPenAt( labelValue ) )
1369
ptr->setPen( rulerAttr.tickMarkPen( labelValue ) );
1371
ptr->setPen( rulerAttr.majorTickMarkPen() );
1372
ptr->drawLine( leftPoint, rightPoint );
1375
drawnYTicks.append( static_cast<int>( diagramIsVertical ? leftPoint.y() : leftPoint.x() ) );
1376
const QSize labelSize( labelItem->sizeHint() );
1379
if ( diagramIsVertical ) {
1380
x = static_cast<int>( leftPoint.x() + met.height() * ( position() == Left ? -0.5 : 0.5) )
1381
- ( position() == Left ? labelSize.width() : (labelSize.width() - maxLabelsWidth) );
1382
y = static_cast<int>( leftPoint.y() - ( met.ascent() + met.descent() ) * 0.6 );
1384
const qreal halfFontHeight = met.height() * 0.5;
1385
x = static_cast<int>( leftPoint.x() - labelSize.width() * 0.5 );
1386
y = static_cast<int>( (position() == Bottom ? leftPoint.y() : rightPoint.y()) +
1387
+ ( position() == Bottom ? halfFontHeight : -(halfFontHeight + labelSize.height()) ) );
1390
labelItem->setGeometry( QRect( QPoint( x, y ), labelSize ) );
1391
const QRect labelGeo = labelItem->geometry();
1392
const bool hadClipping = ptr->hasClipping();
1393
if( labelGeo.top() < geoRect.top() && labelGeo.bottom() > geoRect.top() )
1394
ptr->setClipping( false );
1395
else if( labelGeo.top() < geoRect.bottom() && labelGeo.bottom() > geoRect.bottom() )
1396
ptr->setClipping( false );
1398
// if our item would only half fit, we disable clipping for that one
1399
if( labelGeo.left() < geoRect.left() && labelGeo.right() > geoRect.left() )
1400
ptr->setClipping( false );
1401
else if( labelGeo.left() < geoRect.right() && labelGeo.right() > geoRect.right() )
1402
ptr->setClipping( false );
1404
labelItem->paint( ptr );
1405
ptr->setClipping( hadClipping );
1409
calculateNextLabel( labelValue, step, isLogarithmicY, dimensions.last().start );
1418
// this draws the subunit rulers
1419
if ( drawSubUnitRulers && d->annotations.isEmpty() ) {
1422
d->drawSubUnitRulers( ptr, plane, dim, rulerRef, isAbscissa() ? drawnAbscissaTicks : drawnYTicks, diagramIsVertical, rulerAttr );
1427
if( ! titleText().isEmpty() ) {
1428
d->drawTitleText( ptr, plane, areaGeoRect );
1431
//qDebug() << "KDChart::CartesianAxis::paintCtx() done.";
1435
/* pure virtual in QLayoutItem */
1436
bool CartesianAxis::isEmpty() const
1438
return false; // if the axis exists, it has some (perhaps default) content
1440
/* pure virtual in QLayoutItem */
1441
Qt::Orientations CartesianAxis::expandingDirections() const
1443
Qt::Orientations ret;
1444
switch ( position() )
1448
ret = Qt::Horizontal;
1455
Q_ASSERT( false ); // all positions need to be handeld
1462
static void calculateOverlap( int i, int first, int last,
1464
bool centerAbscissaTicks,
1465
int& firstOverlap, int& lastOverlap )
1468
if( centerAbscissaTicks ){
1469
//TODO(khz): Calculate the amount of left overlap
1470
// for bar diagrams.
1472
firstOverlap = measure / 2;
1475
// we test both bounds in on go: first and last might be equal
1477
if( centerAbscissaTicks ){
1478
//TODO(khz): Calculate the amount of right overlap
1479
// for bar diagrams.
1481
lastOverlap = measure / 2;
1487
void CartesianAxis::setCachedSizeDirty() const
1489
d->cachedMaximumSize = QSize();
1492
/* pure virtual in QLayoutItem */
1493
QSize CartesianAxis::maximumSize() const
1495
if( ! d->cachedMaximumSize.isValid() )
1496
d->cachedMaximumSize = d->calculateMaximumSize();
1497
return d->cachedMaximumSize;
1500
QSize CartesianAxis::Private::calculateMaximumSize() const
1506
const AbstractCartesianDiagram * dia = qobject_cast< const AbstractCartesianDiagram * >( diagram() );
1507
if( dia && dia->referenceDiagram() )
1508
dia = dia->referenceDiagram();
1509
const BarDiagram *barDiagram = qobject_cast< const BarDiagram* >( dia );
1510
const Qt::Orientation diagramOrientation = barDiagram != 0 ? barDiagram->orientation() : Qt::Vertical;
1511
const bool diagramIsVertical = diagramOrientation == Qt::Vertical;
1513
const TextAttributes labelTA = mAxis->textAttributes();
1514
const bool drawLabels = labelTA.isVisible();
1516
const TextAttributes titleTA( titleTextAttributesWithAdjustedRotation() );
1517
const bool drawTitle = titleTA.isVisible() && ! axis()->titleText().isEmpty();
1519
AbstractCoordinatePlane* plane = diagram()->coordinatePlane();
1520
//qDebug() << this<<"::maximumSize() uses plane geometry" << plane->geometry();
1521
QObject* refArea = plane->parent();
1522
TextLayoutItem labelItem( QString(), labelTA, refArea,
1523
KDChartEnums::MeasureOrientationMinimum, Qt::AlignLeft );
1524
TextLayoutItem titleItem( axis()->titleText(), titleTA, refArea,
1525
KDChartEnums::MeasureOrientationMinimum, Qt::AlignHCenter | Qt::AlignVCenter );
1527
const QFontMetrics fm( labelItem.realFont(), GlobalMeasureScaling::paintDevice() );
1529
const qreal labelGap =
1531
? ( (diagramIsVertical ? fm.height() : fm.averageCharWidth()) / 3.0)
1533
const QFontMetricsF titleFM = QFontMetricsF( titleItem.realFont(), GlobalMeasureScaling::paintDevice() );
1534
const qreal titleGap =
1536
? ( (diagramIsVertical ? titleFM.height() : titleFM.averageCharWidth()) / 3.0)
1539
if ( axis()->isAbscissa() ) {
1540
const bool centerAbscissaTicks = referenceDiagramNeedsCenteredAbscissaTicks(diagram());
1541
int leftOverlap = 0;
1542
int rightOverlap = 0;
1544
qreal w = diagramIsVertical ? 10.0 : 0.0;
1545
qreal h = diagramIsVertical ? 0.0 : 10.0;
1547
// if there're no label strings, we take the biggest needed number as height
1548
if( !annotations.isEmpty() )
1550
const QStringList strings = annotations.values();
1551
KDAB_FOREACH( const QString& string, strings )
1553
labelItem.setText( string );
1554
const QSize siz = labelItem.sizeHint();
1555
if ( diagramIsVertical )
1556
h = qMax( h, static_cast< qreal >( siz.height() ) );
1558
w = qMax( w, static_cast< qreal >( siz.width() ) );
1561
else if ( !axis()->labels().isEmpty() )
1563
// find the longest label text:
1565
const int last=axis()->labels().count()-1;
1566
const QStringList labelsList( axis()->labels() );
1567
for ( int i = first; i <= last; ++i )
1569
labelItem.setText( axis()->customizedLabel(labelsList[ i ]) );
1570
const QSize siz = labelItem.sizeHint();
1572
if ( diagramIsVertical )
1573
h = qMax( h, static_cast<qreal>(siz.height()) );
1575
w = qMax( w, static_cast<qreal>(siz.width()) );
1576
calculateOverlap( i, first, last, diagramIsVertical ? siz.width() : siz.height(), centerAbscissaTicks,
1577
leftOverlap, rightOverlap );
1583
QStringList headerLabels = diagram()->itemRowLabels();
1584
const int headerLabelsCount = headerLabels.count();
1585
if( headerLabelsCount ){
1586
if( cachedHeaderLabels == headerLabels && ( diagramIsVertical ? cachedFontHeight == fm.height() : cachedFontWidth == fm.averageCharWidth() )) {
1587
if ( diagramIsVertical )
1588
h = cachedLabelHeight;
1590
w = cachedLabelWidth;
1592
cachedHeaderLabels = headerLabels;
1593
if ( diagramIsVertical )
1594
cachedFontWidth = fm.averageCharWidth();
1596
cachedFontHeight = fm.height();
1597
const bool useFastCalcAlgorithm
1598
= (strcmp( axis()->metaObject()->className(), "KDChart::CartesianAxis" ) == 0);
1600
const int last=headerLabelsCount-1;
1601
for ( int i = first;
1603
i = (useFastCalcAlgorithm && i < last) ? last : (i+1) )
1605
labelItem.setText( axis()->customizedLabel(headerLabels[ i ]) );
1606
const QSize siz = labelItem.sizeHint();
1607
if ( diagramIsVertical ) {
1608
h = qMax( h, static_cast<qreal>(siz.height()) );
1609
cachedLabelHeight = h;
1611
cachedLabelWidth = w;
1612
w = qMax( w, static_cast<qreal>(siz.width()) );
1614
calculateOverlap( i, first, last, diagramIsVertical ? siz.width() : siz.height(), centerAbscissaTicks,
1615
leftOverlap, rightOverlap );
1620
axis()->customizedLabel(
1621
QString::number( diagramIsVertical ? plane->gridDimensionsList().first().end
1622
: plane->gridDimensionsList().last().end, 'f', 0 )));
1623
const QSize siz = labelItem.sizeHint();
1624
if ( diagramIsVertical )
1628
calculateOverlap( 0, 0, 0, siz.width(), centerAbscissaTicks,
1629
leftOverlap, rightOverlap );
1632
// we leave a little gap between axis labels and bottom (or top, resp.) side of axis
1635
// space for a possible title:
1637
// we add the title height and leave a little gap between axis labels and axis title
1638
if ( diagramIsVertical ) {
1639
h += titleItem.sizeHint().height() + titleGap;
1640
w = titleItem.sizeHint().width() + 2.0;
1642
h = titleItem.sizeHint().height() + 2.0;
1643
w += titleItem.sizeHint().width() + titleGap;
1646
// space for the ticks
1647
if ( diagramIsVertical )
1648
h += qAbs( axis()->tickLength() ) * 3.0;
1650
w += qAbs( axis()->tickLength() ) * 3.0;
1651
result = QSize ( static_cast<int>( w ), static_cast<int>( h ) );
1653
//qDebug()<<"calculated size of x axis:"<<result;
1655
// If necessary adjust the widths
1656
// of the left (or right, resp.) side neighboring columns:
1657
amountOfLeftOverlap = leftOverlap;
1658
amountOfRightOverlap = rightOverlap;
1659
/* Unused code for a push-model:
1660
if( leftOverlap || rightOverlap ){
1661
QTimer::singleShot(200, const_cast<CartesianAxis*>(this),
1662
SLOT(adjustLeftRightGridColumnWidths()));
1667
int bottomOverlap = 0;
1669
qreal w = diagramIsVertical ? 0.0 : 10.0;
1670
qreal h = diagramIsVertical ? 10.0 : 0.0;
1672
// if there're no label strings, we loop through the values
1673
// taking the longest (not largest) number - e.g. 0.00001 is longer than 100
1674
if( !annotations.isEmpty() )
1676
const QStringList strings = annotations.values();
1677
KDAB_FOREACH( const QString& string, strings )
1679
labelItem.setText( string );
1680
const QSize siz = labelItem.sizeHint();
1681
if ( diagramIsVertical )
1682
w = qMax( w, static_cast< qreal >( siz.width() ) );
1684
h = qMax( h, static_cast< qreal >( siz.height() ) );
1687
else if( axis()->labels().isEmpty() )
1689
const DataDimension dimY = AbstractGrid::adjustedLowerUpperRange(
1690
diagramIsVertical ? plane->gridDimensionsList().last()
1691
: plane->gridDimensionsList().first(), true, true );
1692
const double step = dimY.stepWidth;
1693
const qreal minValue = dimY.start;
1694
const qreal maxValue = dimY.end;
1695
const bool isLogarithmicY = (dimY.calcMode == AbstractCoordinatePlane::Logarithmic );
1696
qreal labelValue = minValue;
1698
while( labelValue <= maxValue ) {
1699
const QString labelText = diagram()->unitPrefix( static_cast< int >( labelValue ), diagramOrientation, true ) +
1700
QString::number( labelValue ) +
1701
diagram()->unitSuffix( static_cast< int >( labelValue ), diagramOrientation, true );
1702
labelItem.setText( axis()->customizedLabel( labelText ) );
1704
const QSize siz = labelItem.sizeHint();
1705
if ( diagramIsVertical )
1706
w = qMax( w, (qreal)siz.width() );
1708
h = qMax( h, (qreal)siz.height() );
1709
calculateOverlap( 0, 0, 0, diagramIsVertical ? siz.height() : siz.width(), false,// bar diagram flag is ignored for Ordinates
1710
topOverlap, bottomOverlap );
1711
calculateNextLabel( labelValue, step, isLogarithmicY, plane->gridDimensionsList().last().start );
1714
// find the longest label text:
1716
const int last=axis()->labels().count()-1;
1717
const QStringList labelsList( axis()->labels() );
1718
for ( int i = first; i <= last; ++i )
1720
labelItem.setText( axis()->customizedLabel(labelsList[ i ]) );
1721
const QSize siz = labelItem.sizeHint();
1722
if ( diagramIsVertical )
1723
w = qMax( w, (qreal)siz.width() );
1725
h = qMax( h, (qreal)siz.height() );
1726
calculateOverlap( 0, 0, 0, diagramIsVertical ? siz.height() : siz.width(), false,// bar diagram flag is ignored for Ordinates
1727
topOverlap, bottomOverlap );
1730
// we leave a little gap between axis labels and left (or right, resp.) side of axis
1733
// space for a possible title:
1735
// we add the title height and leave a little gap between axis labels and axis title
1736
if ( diagramIsVertical ) {
1737
w += titleItem.sizeHint().width() + titleGap;
1738
h = titleItem.sizeHint().height() + 2.0;
1740
w = titleItem.sizeHint().width() + 2.0;
1741
h += titleItem.sizeHint().height() + titleGap;
1743
//qDebug() << "left/right axis title item size-hint:" << titleItem.sizeHint();
1745
// space for the ticks
1746
if ( diagramIsVertical )
1747
w += qAbs( axis()->tickLength() ) * 3.0;
1749
h += qAbs( axis()->tickLength() ) * 3.0;
1751
result = QSize ( static_cast<int>( w ), static_cast<int>( h ) );
1752
//qDebug() << "left/right axis width:" << result << " w:" << w;
1755
// If necessary adjust the heights
1756
// of the top (or bottom, resp.) side neighboring rows:
1757
amountOfTopOverlap = topOverlap;
1758
amountOfBottomOverlap = bottomOverlap;
1759
/* Unused code for a push-model:
1760
if( topOverlap || bottomOverlap ){
1761
QTimer::singleShot(200, const_cast<CartesianAxis*>(this),
1762
SLOT(adjustTopBottomGridRowHeights()));
1766
//qDebug() << "*******************" << result;
1767
//result=QSize(0,0);
1770
/* pure virtual in QLayoutItem */
1771
QSize CartesianAxis::minimumSize() const
1773
return maximumSize();
1775
/* pure virtual in QLayoutItem */
1776
QSize CartesianAxis::sizeHint() const
1778
return maximumSize();
1780
/* pure virtual in QLayoutItem */
1781
void CartesianAxis::setGeometry( const QRect& r )
1783
// qDebug() << "KDChart::CartesianAxis::setGeometry(" << r << ") called"
1784
// << (isAbscissa() ? "for Abscissa":"for Ordinate") << "axis";
1786
setCachedSizeDirty();
1788
/* pure virtual in QLayoutItem */
1789
QRect CartesianAxis::geometry() const
1794
int CartesianAxis::tickLength( bool subUnitTicks ) const
1798
if ( isAbscissa() ) {
1799
result = position() == Top ? -4 : 3;
1801
result = position() == Left ? -4 : 3;
1805
result = result < 0 ? result + 1 : result - 1;
1810
QMap< double, QString > CartesianAxis::annotations() const
1812
return d->annotations;
1815
void CartesianAxis::setAnnotations( const QMap< double, QString >& annotations )
1817
if( d->annotations == annotations )
1820
d->annotations = annotations;
1824
QList< double > CartesianAxis::customTicks() const
1826
return d->customTicksPositions;
1829
void CartesianAxis::setCustomTicks( const QList< double >& customTicksPositions )
1831
if( d->customTicksPositions == customTicksPositions )
1834
d->customTicksPositions = customTicksPositions;
1839
/* unused code from KDChartCartesianAxis.h for using a push-model:
1841
void needAdjustLeftRightColumnsForOverlappingLabels(
1842
CartesianAxis* axis, int left, int right );
1843
void needAdjustTopBottomRowsForOverlappingLabels(
1844
CartesianAxis* axis, int top, int bottom );
1846
void adjustLeftRightGridColumnWidths();
1847
void adjustTopBottomGridRowHeights();
1851
// Unused code trying to use a push-model: This did not work
1852
// since we can not re-layout the planes each time when
1853
// Qt layouting is calling sizeHint()
1854
void CartesianAxis::adjustLeftRightGridColumnWidths()
1856
if( ! d->amountOfLeftOverlap && ! d->amountOfRightOverlap )
1858
const int leftOverlap = d->amountOfLeftOverlap;
1859
const int rightOverlap= d->amountOfRightOverlap;
1860
d->amountOfLeftOverlap = 0;
1861
d->amountOfRightOverlap = 0;
1862
emit needAdjustLeftRightColumnsForOverlappingLabels(
1863
this, leftOverlap, rightOverlap );
1866
void CartesianAxis::adjustTopBottomGridRowHeights()
1868
if( ! d->amountOfTopOverlap && ! d->amountOfBottomOverlap )
1870
const int topOverlap = d->amountOfTopOverlap;
1871
const int bottomOverlap= d->amountOfBottomOverlap;
1872
d->amountOfTopOverlap = 0;
1873
d->amountOfBottomOverlap = 0;
1874
emit needAdjustTopBottomRowsForOverlappingLabels(
1875
this, topOverlap, bottomOverlap );