1 /***************************************************************************
2 **                                                                        **
3 **  QCustomPlot, an easy to use, modern plotting widget for Qt            **
4 **  Copyright (C) 2011-2016 Emanuel Eichhammer                            **
5 **                                                                        **
6 **  This program is free software: you can redistribute it and/or modify  **
7 **  it under the terms of the GNU General Public License as published by  **
8 **  the Free Software Foundation, either version 3 of the License, or     **
9 **  (at your option) any later version.                                   **
10 **                                                                        **
11 **  This program is distributed in the hope that it will be useful,       **
12 **  but WITHOUT ANY WARRANTY; without even the implied warranty of        **
13 **  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         **
14 **  GNU General Public License for more details.                          **
15 **                                                                        **
16 **  You should have received a copy of the GNU General Public License     **
17 **  along with this program.  If not, see http://www.gnu.org/licenses/.   **
18 **                                                                        **
19 ****************************************************************************
20 **           Author: Emanuel Eichhammer                                   **
21 **  Website/Contact: http://www.qcustomplot.com/                          **
22 **             Date: 13.09.16                                             **
23 **          Version: 2.0.0-beta                                           **
24 ****************************************************************************/
25 
26 #include "qcustomplot.h"
27 
28 
29 /* including file 'src/vector2d.cpp', size 7340                              */
30 /* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
31 
32 ////////////////////////////////////////////////////////////////////////////////////////////////////
33 //////////////////// QCPVector2D
34 ////////////////////////////////////////////////////////////////////////////////////////////////////
35 
36 /*! \class QCPVector2D
37   \brief Represents two doubles as a mathematical 2D vector
38 
39   This class acts as a replacement for QVector2D with the advantage of double precision instead of
40   single, and some convenience methods tailored for the QCustomPlot library.
41 */
42 
43 /* start documentation of inline functions */
44 
45 /*! \fn void QCPVector2D::setX(double x)
46 
47   Sets the x coordinate of this vector to \a x.
48 
49   \see setY
50 */
51 
52 /*! \fn void QCPVector2D::setY(double y)
53 
54   Sets the y coordinate of this vector to \a y.
55 
56   \see setX
57 */
58 
59 /*! \fn double QCPVector2D::length() const
60 
61   Returns the length of this vector.
62 
63   \see lengthSquared
64 */
65 
66 /*! \fn double QCPVector2D::lengthSquared() const
67 
68   Returns the squared length of this vector. In some situations, e.g. when just trying to find the
69   shortest vector of a group, this is faster than calculating \ref length, because it avoids
70   calculation of a square root.
71 
72   \see length
73 */
74 
75 /*! \fn QPoint QCPVector2D::toPoint() const
76 
77   Returns a QPoint which has the x and y coordinates of this vector, truncating any floating point
78   information.
79 
80   \see toPointF
81 */
82 
83 /*! \fn QPointF QCPVector2D::toPointF() const
84 
85   Returns a QPointF which has the x and y coordinates of this vector.
86 
87   \see toPoint
88 */
89 
90 /*! \fn bool QCPVector2D::isNull() const
91 
92   Returns whether this vector is null. A vector is null if \c qIsNull returns true for both x and y
93   coordinates, i.e. if both are binary equal to 0.
94 */
95 
96 /*! \fn QCPVector2D QCPVector2D::perpendicular() const
97 
98   Returns a vector perpendicular to this vector, with the same length.
99 */
100 
101 /*! \fn double QCPVector2D::dot() const
102 
103   Returns the dot/scalar product of this vector with the specified vector \a vec.
104 */
105 
106 /* end documentation of inline functions */
107 
108 /*!
109   Creates a QCPVector2D object and initializes the x and y coordinates to 0.
110 */
QCPVector2D()111 QCPVector2D::QCPVector2D() :
112   mX(0),
113   mY(0)
114 {
115 }
116 
117 /*!
118   Creates a QCPVector2D object and initializes the \a x and \a y coordinates with the specified
119   values.
120 */
QCPVector2D(double x,double y)121 QCPVector2D::QCPVector2D(double x, double y) :
122   mX(x),
123   mY(y)
124 {
125 }
126 
127 /*!
128   Creates a QCPVector2D object and initializes the x and y coordinates respective coordinates of
129   the specified \a point.
130 */
QCPVector2D(const QPoint & point)131 QCPVector2D::QCPVector2D(const QPoint &point) :
132   mX(point.x()),
133   mY(point.y())
134 {
135 }
136 
137 /*!
138   Creates a QCPVector2D object and initializes the x and y coordinates respective coordinates of
139   the specified \a point.
140 */
QCPVector2D(const QPointF & point)141 QCPVector2D::QCPVector2D(const QPointF &point) :
142   mX(point.x()),
143   mY(point.y())
144 {
145 }
146 
147 /*!
148   Normalizes this vector. After this operation, the length of the vector is equal to 1.
149 
150   \see normalized, length, lengthSquared
151 */
normalize()152 void QCPVector2D::normalize()
153 {
154   double len = length();
155   mX /= len;
156   mY /= len;
157 }
158 
159 /*!
160   Returns a normalized version of this vector. The length of the returned vector is equal to 1.
161 
162   \see normalize, length, lengthSquared
163 */
normalized() const164 QCPVector2D QCPVector2D::normalized() const
165 {
166   QCPVector2D result(mX, mY);
167   result.normalize();
168   return result;
169 }
170 
171 /*! \overload
172 
173   Returns the squared shortest distance of this vector (interpreted as a point) to the finite line
174   segment given by \a start and \a end.
175 
176   \see distanceToStraightLine
177 */
distanceSquaredToLine(const QCPVector2D & start,const QCPVector2D & end) const178 double QCPVector2D::distanceSquaredToLine(const QCPVector2D &start, const QCPVector2D &end) const
179 {
180   QCPVector2D v(end-start);
181   double vLengthSqr = v.lengthSquared();
182   if (!qFuzzyIsNull(vLengthSqr))
183   {
184     double mu = v.dot(*this-start)/vLengthSqr;
185     if (mu < 0)
186       return (*this-start).lengthSquared();
187     else if (mu > 1)
188       return (*this-end).lengthSquared();
189     else
190       return ((start + mu*v)-*this).lengthSquared();
191   } else
192     return (*this-start).lengthSquared();
193 }
194 
195 /*! \overload
196 
197   Returns the squared shortest distance of this vector (interpreted as a point) to the finite line
198   segment given by \a line.
199 
200   \see distanceToStraightLine
201 */
distanceSquaredToLine(const QLineF & line) const202 double QCPVector2D::distanceSquaredToLine(const QLineF &line) const
203 {
204   return distanceSquaredToLine(QCPVector2D(line.p1()), QCPVector2D(line.p2()));
205 }
206 
207 /*!
208   Returns the shortest distance of this vector (interpreted as a point) to the infinite straight
209   line given by a \a base point and a \a direction vector.
210 
211   \see distanceSquaredToLine
212 */
distanceToStraightLine(const QCPVector2D & base,const QCPVector2D & direction) const213 double QCPVector2D::distanceToStraightLine(const QCPVector2D &base, const QCPVector2D &direction) const
214 {
215   return qAbs((*this-base).dot(direction.perpendicular()))/direction.length();
216 }
217 
218 /*!
219   Scales this vector by the given \a factor, i.e. the x and y components are multiplied by \a
220   factor.
221 */
operator *=(double factor)222 QCPVector2D &QCPVector2D::operator*=(double factor)
223 {
224   mX *= factor;
225   mY *= factor;
226   return *this;
227 }
228 
229 /*!
230   Scales this vector by the given \a divisor, i.e. the x and y components are divided by \a
231   divisor.
232 */
operator /=(double divisor)233 QCPVector2D &QCPVector2D::operator/=(double divisor)
234 {
235   mX /= divisor;
236   mY /= divisor;
237   return *this;
238 }
239 
240 /*!
241   Adds the given \a vector to this vector component-wise.
242 */
operator +=(const QCPVector2D & vector)243 QCPVector2D &QCPVector2D::operator+=(const QCPVector2D &vector)
244 {
245   mX += vector.mX;
246   mY += vector.mY;
247   return *this;
248 }
249 
250 /*!
251   subtracts the given \a vector from this vector component-wise.
252 */
operator -=(const QCPVector2D & vector)253 QCPVector2D &QCPVector2D::operator-=(const QCPVector2D &vector)
254 {
255   mX -= vector.mX;
256   mY -= vector.mY;
257   return *this;
258 }
259 /* end of 'src/vector2d.cpp' */
260 
261 
262 /* including file 'src/painter.cpp', size 8670                               */
263 /* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
264 
265 ////////////////////////////////////////////////////////////////////////////////////////////////////
266 //////////////////// QCPPainter
267 ////////////////////////////////////////////////////////////////////////////////////////////////////
268 
269 /*! \class QCPPainter
270   \brief QPainter subclass used internally
271 
272   This QPainter subclass is used to provide some extended functionality e.g. for tweaking position
273   consistency between antialiased and non-antialiased painting. Further it provides workarounds
274   for QPainter quirks.
275 
276   \warning This class intentionally hides non-virtual functions of QPainter, e.g. setPen, save and
277   restore. So while it is possible to pass a QCPPainter instance to a function that expects a
278   QPainter pointer, some of the workarounds and tweaks will be unavailable to the function (because
279   it will call the base class implementations of the functions actually hidden by QCPPainter).
280 */
281 
282 /*!
283   Creates a new QCPPainter instance and sets default values
284 */
QCPPainter()285 QCPPainter::QCPPainter() :
286   QPainter(),
287   mModes(pmDefault),
288   mIsAntialiasing(false)
289 {
290   // don't setRenderHint(QPainter::NonCosmeticDefautPen) here, because painter isn't active yet and
291   // a call to begin() will follow
292 }
293 
294 /*!
295   Creates a new QCPPainter instance on the specified paint \a device and sets default values. Just
296   like the analogous QPainter constructor, begins painting on \a device immediately.
297 
298   Like \ref begin, this method sets QPainter::NonCosmeticDefaultPen in Qt versions before Qt5.
299 */
QCPPainter(QPaintDevice * device)300 QCPPainter::QCPPainter(QPaintDevice *device) :
301   QPainter(device),
302   mModes(pmDefault),
303   mIsAntialiasing(false)
304 {
305 #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) // before Qt5, default pens used to be cosmetic if NonCosmeticDefaultPen flag isn't set. So we set it to get consistency across Qt versions.
306   if (isActive())
307     setRenderHint(QPainter::NonCosmeticDefaultPen);
308 #endif
309 }
310 
311 /*!
312   Sets the pen of the painter and applies certain fixes to it, depending on the mode of this
313   QCPPainter.
314 
315   \note this function hides the non-virtual base class implementation.
316 */
setPen(const QPen & pen)317 void QCPPainter::setPen(const QPen &pen)
318 {
319   QPainter::setPen(pen);
320   if (mModes.testFlag(pmNonCosmetic))
321     makeNonCosmetic();
322 }
323 
324 /*! \overload
325 
326   Sets the pen (by color) of the painter and applies certain fixes to it, depending on the mode of
327   this QCPPainter.
328 
329   \note this function hides the non-virtual base class implementation.
330 */
setPen(const QColor & color)331 void QCPPainter::setPen(const QColor &color)
332 {
333   QPainter::setPen(color);
334   if (mModes.testFlag(pmNonCosmetic))
335     makeNonCosmetic();
336 }
337 
338 /*! \overload
339 
340   Sets the pen (by style) of the painter and applies certain fixes to it, depending on the mode of
341   this QCPPainter.
342 
343   \note this function hides the non-virtual base class implementation.
344 */
setPen(Qt::PenStyle penStyle)345 void QCPPainter::setPen(Qt::PenStyle penStyle)
346 {
347   QPainter::setPen(penStyle);
348   if (mModes.testFlag(pmNonCosmetic))
349     makeNonCosmetic();
350 }
351 
352 /*! \overload
353 
354   Works around a Qt bug introduced with Qt 4.8 which makes drawing QLineF unpredictable when
355   antialiasing is disabled. Thus when antialiasing is disabled, it rounds the \a line to
356   integer coordinates and then passes it to the original drawLine.
357 
358   \note this function hides the non-virtual base class implementation.
359 */
drawLine(const QLineF & line)360 void QCPPainter::drawLine(const QLineF &line)
361 {
362   if (mIsAntialiasing || mModes.testFlag(pmVectorized))
363     QPainter::drawLine(line);
364   else
365     QPainter::drawLine(line.toLine());
366 }
367 
368 /*!
369   Sets whether painting uses antialiasing or not. Use this method instead of using setRenderHint
370   with QPainter::Antialiasing directly, as it allows QCPPainter to regain pixel exactness between
371   antialiased and non-antialiased painting (Since Qt < 5.0 uses slightly different coordinate systems for
372   AA/Non-AA painting).
373 */
setAntialiasing(bool enabled)374 void QCPPainter::setAntialiasing(bool enabled)
375 {
376   setRenderHint(QPainter::Antialiasing, enabled);
377   if (mIsAntialiasing != enabled)
378   {
379     mIsAntialiasing = enabled;
380     if (!mModes.testFlag(pmVectorized)) // antialiasing half-pixel shift only needed for rasterized outputs
381     {
382       if (mIsAntialiasing)
383         translate(0.5, 0.5);
384       else
385         translate(-0.5, -0.5);
386     }
387   }
388 }
389 
390 /*!
391   Sets the mode of the painter. This controls whether the painter shall adjust its
392   fixes/workarounds optimized for certain output devices.
393 */
setModes(QCPPainter::PainterModes modes)394 void QCPPainter::setModes(QCPPainter::PainterModes modes)
395 {
396   mModes = modes;
397 }
398 
399 /*!
400   Sets the QPainter::NonCosmeticDefaultPen in Qt versions before Qt5 after beginning painting on \a
401   device. This is necessary to get cosmetic pen consistency across Qt versions, because since Qt5,
402   all pens are non-cosmetic by default, and in Qt4 this render hint must be set to get that
403   behaviour.
404 
405   The Constructor \ref QCPPainter(QPaintDevice *device) which directly starts painting also sets
406   the render hint as appropriate.
407 
408   \note this function hides the non-virtual base class implementation.
409 */
begin(QPaintDevice * device)410 bool QCPPainter::begin(QPaintDevice *device)
411 {
412   bool result = QPainter::begin(device);
413 #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) // before Qt5, default pens used to be cosmetic if NonCosmeticDefaultPen flag isn't set. So we set it to get consistency across Qt versions.
414   if (result)
415     setRenderHint(QPainter::NonCosmeticDefaultPen);
416 #endif
417   return result;
418 }
419 
420 /*! \overload
421 
422   Sets the mode of the painter. This controls whether the painter shall adjust its
423   fixes/workarounds optimized for certain output devices.
424 */
setMode(QCPPainter::PainterMode mode,bool enabled)425 void QCPPainter::setMode(QCPPainter::PainterMode mode, bool enabled)
426 {
427   if (!enabled && mModes.testFlag(mode))
428     mModes &= ~mode;
429   else if (enabled && !mModes.testFlag(mode))
430     mModes |= mode;
431 }
432 
433 /*!
434   Saves the painter (see QPainter::save). Since QCPPainter adds some new internal state to
435   QPainter, the save/restore functions are reimplemented to also save/restore those members.
436 
437   \note this function hides the non-virtual base class implementation.
438 
439   \see restore
440 */
save()441 void QCPPainter::save()
442 {
443   mAntialiasingStack.push(mIsAntialiasing);
444   QPainter::save();
445 }
446 
447 /*!
448   Restores the painter (see QPainter::restore). Since QCPPainter adds some new internal state to
449   QPainter, the save/restore functions are reimplemented to also save/restore those members.
450 
451   \note this function hides the non-virtual base class implementation.
452 
453   \see save
454 */
restore()455 void QCPPainter::restore()
456 {
457   if (!mAntialiasingStack.isEmpty())
458     mIsAntialiasing = mAntialiasingStack.pop();
459   else
460     qDebug() << Q_FUNC_INFO << "Unbalanced save/restore";
461   QPainter::restore();
462 }
463 
464 /*!
465   Changes the pen width to 1 if it currently is 0. This function is called in the \ref setPen
466   overrides when the \ref pmNonCosmetic mode is set.
467 */
makeNonCosmetic()468 void QCPPainter::makeNonCosmetic()
469 {
470   if (qFuzzyIsNull(pen().widthF()))
471   {
472     QPen p = pen();
473     p.setWidth(1);
474     QPainter::setPen(p);
475   }
476 }
477 /* end of 'src/painter.cpp' */
478 
479 
480 /* including file 'src/paintbuffer.cpp', size 18502                          */
481 /* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
482 
483 ////////////////////////////////////////////////////////////////////////////////////////////////////
484 //////////////////// QCPAbstractPaintBuffer
485 ////////////////////////////////////////////////////////////////////////////////////////////////////
486 
487 /*! \class QCPAbstractPaintBuffer
488   \brief The abstract base class for paint buffers, which define the rendering backend
489 
490   This abstract base class defines the basic interface that a paint buffer needs to provide in
491   order to be usable by QCustomPlot.
492 
493   A paint buffer manages both a surface to draw onto, and the matching paint device. The size of
494   the surface can be changed via \ref setSize. External classes (\ref QCustomPlot and \ref
495   QCPLayer) request a painter via \ref startPainting and then perform the draw calls. Once the
496   painting is complete, \ref donePainting is called, so the paint buffer implementation can do
497   clean up if necessary. Before rendering a frame, each paint buffer is usually filled with a color
498   using \ref clear (usually the color is \c Qt::transparent), to remove the contents of the
499   previous frame.
500 
501   The simplest paint buffer implementation is \ref QCPPaintBufferPixmap which allows regular
502   software rendering via the raster engine. Hardware accelerated rendering via pixel buffers and
503   frame buffer objects is provided by \ref QCPPaintBufferGlPbuffer and \ref QCPPaintBufferGlFbo.
504   They are used automatically if \ref QCustomPlot::setOpenGl is enabled.
505 */
506 
507 /* start documentation of pure virtual functions */
508 
509 /*! \fn virtual QCPPainter *QCPAbstractPaintBuffer::startPainting() = 0
510 
511   Returns a \ref QCPPainter which is ready to draw to this buffer. The ownership and thus the
512   responsibility to delete the painter after the painting operations are complete is given to the
513   caller of this method.
514 
515   Once you are done using the painter, delete the painter and call \ref donePainting.
516 
517   While a painter generated with this method is active, you must not call \ref setSize, \ref
518   setDevicePixelRatio or \ref clear.
519 
520   This method may return 0, if a painter couldn't be activated on the buffer. This usually
521   indicates a problem with the respective painting backend.
522 */
523 
524 /*! \fn virtual void QCPAbstractPaintBuffer::draw(QCPPainter *painter) const = 0
525 
526   Draws the contents of this buffer with the provided \a painter. This is the method that is used
527   to finally join all paint buffers and draw them onto the screen.
528 */
529 
530 /*! \fn virtual void QCPAbstractPaintBuffer::clear(const QColor &color) = 0
531 
532   Fills the entire buffer with the provided \a color. To have an empty transparent buffer, use the
533   named color \c Qt::transparent.
534 
535   This method must not be called if there is currently a painter (acquired with \ref startPainting)
536   active.
537 */
538 
539 /*! \fn virtual void QCPAbstractPaintBuffer::reallocateBuffer() = 0
540 
541   Reallocates the internal buffer with the currently configured size (\ref setSize) and device
542   pixel ratio, if applicable (\ref setDevicePixelRatio). It is called as soon as any of those
543   properties are changed on this paint buffer.
544 
545   \note Subclasses of \ref QCPAbstractPaintBuffer must call their reimplementation of this method
546   in their constructor, to perform the first allocation (this can not be done by the base class
547   because calling pure virtual methods in base class constructors is not possible).
548 */
549 
550 /* end documentation of pure virtual functions */
551 /* start documentation of inline functions */
552 
553 /*! \fn virtual void QCPAbstractPaintBuffer::donePainting()
554 
555   If you have acquired a \ref QCPPainter to paint onto this paint buffer via \ref startPainting,
556   call this method as soon as you are done with the painting operations and have deleted the
557   painter.
558 
559   paint buffer subclasses may use this method to perform any type of cleanup that is necessary. The
560   default implementation does nothing.
561 */
562 
563 /* end documentation of inline functions */
564 
565 /*!
566   Creates a paint buffer and initializes it with the provided \a size and \a devicePixelRatio.
567 
568   Subclasses must call their \ref reallocateBuffer implementation in their respective constructors.
569 */
QCPAbstractPaintBuffer(const QSize & size,double devicePixelRatio)570 QCPAbstractPaintBuffer::QCPAbstractPaintBuffer(const QSize &size, double devicePixelRatio) :
571   mSize(size),
572   mDevicePixelRatio(devicePixelRatio),
573   mInvalidated(true)
574 {
575 }
576 
~QCPAbstractPaintBuffer()577 QCPAbstractPaintBuffer::~QCPAbstractPaintBuffer()
578 {
579 }
580 
581 /*!
582   Sets the paint buffer size.
583 
584   The buffer is reallocated (by calling \ref reallocateBuffer), so any painters that were obtained
585   by \ref startPainting are invalidated and must not be used after calling this method.
586 
587   If \a size is already the current buffer size, this method does nothing.
588 */
setSize(const QSize & size)589 void QCPAbstractPaintBuffer::setSize(const QSize &size)
590 {
591   if (mSize != size)
592   {
593     mSize = size;
594     reallocateBuffer();
595   }
596 }
597 
598 /*!
599   Sets the invalidated flag to \a invalidated.
600 
601   This mechanism is used internally in conjunction with isolated replotting of \ref QCPLayer
602   instances (in \ref QCPLayer::lmBuffered mode). If \ref QCPLayer::replot is called on a buffered
603   layer, i.e. an isolated repaint of only that layer (and its dedicated paint buffer) is requested,
604   QCustomPlot will decide depending on the invalidated flags of other paint buffers whether it also
605   replots them, instead of only the layer on which the replot was called.
606 
607   The invalidated flag is set to true when \ref QCPLayer association has changed, i.e. if layers
608   were added or removed from this buffer, or if they were reordered. It is set to false as soon as
609   all associated \ref QCPLayer instances are drawn onto the buffer.
610 
611   Under normal circumstances, it is not necessary to manually call this method.
612 */
setInvalidated(bool invalidated)613 void QCPAbstractPaintBuffer::setInvalidated(bool invalidated)
614 {
615   mInvalidated = invalidated;
616 }
617 
618 /*!
619   Sets the the device pixel ratio to \a ratio. This is useful to render on high-DPI output devices.
620   The ratio is automatically set to the device pixel ratio used by the parent QCustomPlot instance.
621 
622   The buffer is reallocated (by calling \ref reallocateBuffer), so any painters that were obtained
623   by \ref startPainting are invalidated and must not be used after calling this method.
624 
625   \note This method is only available for Qt versions 5.4 and higher.
626 */
setDevicePixelRatio(double ratio)627 void QCPAbstractPaintBuffer::setDevicePixelRatio(double ratio)
628 {
629   if (!qFuzzyCompare(ratio, mDevicePixelRatio))
630   {
631 #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
632     mDevicePixelRatio = ratio;
633     reallocateBuffer();
634 #else
635     qDebug() << Q_FUNC_INFO << "Device pixel ratios not supported for Qt versions before 5.4";
636     mDevicePixelRatio = 1.0;
637 #endif
638   }
639 }
640 
641 ////////////////////////////////////////////////////////////////////////////////////////////////////
642 //////////////////// QCPPaintBufferPixmap
643 ////////////////////////////////////////////////////////////////////////////////////////////////////
644 
645 /*! \class QCPPaintBufferPixmap
646   \brief A paint buffer based on QPixmap, using software raster rendering
647 
648   This paint buffer is the default and fall-back paint buffer which uses software rendering and
649   QPixmap as internal buffer. It is used if \ref QCustomPlot::setOpenGl is false.
650 */
651 
652 /*!
653   Creates a pixmap paint buffer instancen with the specified \a size and \a devicePixelRatio, if
654   applicable.
655 */
QCPPaintBufferPixmap(const QSize & size,double devicePixelRatio)656 QCPPaintBufferPixmap::QCPPaintBufferPixmap(const QSize &size, double devicePixelRatio) :
657   QCPAbstractPaintBuffer(size, devicePixelRatio)
658 {
659   QCPPaintBufferPixmap::reallocateBuffer();
660 }
661 
~QCPPaintBufferPixmap()662 QCPPaintBufferPixmap::~QCPPaintBufferPixmap()
663 {
664 }
665 
666 /* inherits documentation from base class */
startPainting()667 QCPPainter *QCPPaintBufferPixmap::startPainting()
668 {
669   QCPPainter *result = new QCPPainter(&mBuffer);
670   result->setRenderHint(QPainter::HighQualityAntialiasing);
671   return result;
672 }
673 
674 /* inherits documentation from base class */
draw(QCPPainter * painter) const675 void QCPPaintBufferPixmap::draw(QCPPainter *painter) const
676 {
677   if (painter && painter->isActive())
678     painter->drawPixmap(0, 0, mBuffer);
679   else
680     qDebug() << Q_FUNC_INFO << "invalid or inactive painter passed";
681 }
682 
683 /* inherits documentation from base class */
clear(const QColor & color)684 void QCPPaintBufferPixmap::clear(const QColor &color)
685 {
686   mBuffer.fill(color);
687 }
688 
689 /* inherits documentation from base class */
reallocateBuffer()690 void QCPPaintBufferPixmap::reallocateBuffer()
691 {
692   setInvalidated();
693   if (!qFuzzyCompare(1.0, mDevicePixelRatio))
694   {
695 #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
696     mBuffer = QPixmap(mSize*mDevicePixelRatio);
697     mBuffer.setDevicePixelRatio(mDevicePixelRatio);
698 #else
699     qDebug() << Q_FUNC_INFO << "Device pixel ratios not supported for Qt versions before 5.4";
700     mDevicePixelRatio = 1.0;
701     mBuffer = QPixmap(mSize);
702 #endif
703   } else
704   {
705     mBuffer = QPixmap(mSize);
706   }
707 }
708 
709 
710 #ifdef QCP_OPENGL_PBUFFER
711 ////////////////////////////////////////////////////////////////////////////////////////////////////
712 //////////////////// QCPPaintBufferGlPbuffer
713 ////////////////////////////////////////////////////////////////////////////////////////////////////
714 
715 /*! \class QCPPaintBufferGlPbuffer
716   \brief A paint buffer based on OpenGL pixel buffers, using hardware accelerated rendering
717 
718   This paint buffer is one of the OpenGL paint buffers which facilitate hardware accelerated plot
719   rendering. It is based on OpenGL pixel buffers (pbuffer) and is used in Qt versions before 5.0.
720   (See \ref QCPPaintBufferGlFbo used in newer Qt versions.)
721 
722   The OpenGL paint buffers are used if \ref QCustomPlot::setOpenGl is set to true, and if they are
723   supported by the system.
724 */
725 
726 /*!
727   Creates a \ref QCPPaintBufferGlPbuffer instance with the specified \a size and \a
728   devicePixelRatio, if applicable.
729 
730   The parameter \a multisamples defines how many samples are used per pixel. Higher values thus
731   result in higher quality antialiasing. If the specified \a multisamples value exceeds the
732   capability of the graphics hardware, the highest supported multisampling is used.
733 */
QCPPaintBufferGlPbuffer(const QSize & size,double devicePixelRatio,int multisamples)734 QCPPaintBufferGlPbuffer::QCPPaintBufferGlPbuffer(const QSize &size, double devicePixelRatio, int multisamples) :
735   QCPAbstractPaintBuffer(size, devicePixelRatio),
736   mGlPBuffer(0),
737   mMultisamples(qMax(0, multisamples))
738 {
739   QCPPaintBufferGlPbuffer::reallocateBuffer();
740 }
741 
~QCPPaintBufferGlPbuffer()742 QCPPaintBufferGlPbuffer::~QCPPaintBufferGlPbuffer()
743 {
744   if (mGlPBuffer)
745     delete mGlPBuffer;
746 }
747 
748 /* inherits documentation from base class */
startPainting()749 QCPPainter *QCPPaintBufferGlPbuffer::startPainting()
750 {
751   if (!mGlPBuffer->isValid())
752   {
753     qDebug() << Q_FUNC_INFO << "OpenGL frame buffer object doesn't exist, reallocateBuffer was not called?";
754     return 0;
755   }
756 
757   QCPPainter *result = new QCPPainter(mGlPBuffer);
758   result->setRenderHint(QPainter::HighQualityAntialiasing);
759   return result;
760 }
761 
762 /* inherits documentation from base class */
draw(QCPPainter * painter) const763 void QCPPaintBufferGlPbuffer::draw(QCPPainter *painter) const
764 {
765   if (!painter || !painter->isActive())
766   {
767     qDebug() << Q_FUNC_INFO << "invalid or inactive painter passed";
768     return;
769   }
770   if (!mGlPBuffer->isValid())
771   {
772     qDebug() << Q_FUNC_INFO << "OpenGL pbuffer isn't valid, reallocateBuffer was not called?";
773     return;
774   }
775   painter->drawImage(0, 0, mGlPBuffer->toImage());
776 }
777 
778 /* inherits documentation from base class */
clear(const QColor & color)779 void QCPPaintBufferGlPbuffer::clear(const QColor &color)
780 {
781   if (mGlPBuffer->isValid())
782   {
783     mGlPBuffer->makeCurrent();
784     glClearColor(color.redF(), color.greenF(), color.blueF(), color.alphaF());
785     glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
786     mGlPBuffer->doneCurrent();
787   } else
788     qDebug() << Q_FUNC_INFO << "OpenGL pbuffer invalid or context not current";
789 }
790 
791 /* inherits documentation from base class */
reallocateBuffer()792 void QCPPaintBufferGlPbuffer::reallocateBuffer()
793 {
794   if (mGlPBuffer)
795     delete mGlPBuffer;
796 
797   QGLFormat format;
798   format.setAlpha(true);
799   format.setSamples(mMultisamples);
800   mGlPBuffer = new QGLPixelBuffer(mSize, format);
801 }
802 #endif // QCP_OPENGL_PBUFFER
803 
804 
805 #ifdef QCP_OPENGL_FBO
806 ////////////////////////////////////////////////////////////////////////////////////////////////////
807 //////////////////// QCPPaintBufferGlFbo
808 ////////////////////////////////////////////////////////////////////////////////////////////////////
809 
810 /*! \class QCPPaintBufferGlFbo
811   \brief A paint buffer based on OpenGL frame buffers objects, using hardware accelerated rendering
812 
813   This paint buffer is one of the OpenGL paint buffers which facilitate hardware accelerated plot
814   rendering. It is based on OpenGL frame buffer objects (fbo) and is used in Qt versions 5.0 and
815   higher. (See \ref QCPPaintBufferGlPbuffer used in older Qt versions.)
816 
817   The OpenGL paint buffers are used if \ref QCustomPlot::setOpenGl is set to true, and if they are
818   supported by the system.
819 */
820 
821 /*!
822   Creates a \ref QCPPaintBufferGlFbo instance with the specified \a size and \a devicePixelRatio,
823   if applicable.
824 
825   All frame buffer objects shall share one OpenGL context and paint device, which need to be set up
826   externally and passed via \a glContext and \a glPaintDevice. The set-up is done in \ref
827   QCustomPlot::setupOpenGl and the context and paint device are managed by the parent QCustomPlot
828   instance.
829 */
QCPPaintBufferGlFbo(const QSize & size,double devicePixelRatio,QWeakPointer<QOpenGLContext> glContext,QWeakPointer<QOpenGLPaintDevice> glPaintDevice)830 QCPPaintBufferGlFbo::QCPPaintBufferGlFbo(const QSize &size, double devicePixelRatio, QWeakPointer<QOpenGLContext> glContext, QWeakPointer<QOpenGLPaintDevice> glPaintDevice) :
831   QCPAbstractPaintBuffer(size, devicePixelRatio),
832   mGlContext(glContext),
833   mGlPaintDevice(glPaintDevice),
834   mGlFrameBuffer(0)
835 {
836   QCPPaintBufferGlFbo::reallocateBuffer();
837 }
838 
~QCPPaintBufferGlFbo()839 QCPPaintBufferGlFbo::~QCPPaintBufferGlFbo()
840 {
841   if (mGlFrameBuffer)
842     delete mGlFrameBuffer;
843 }
844 
845 /* inherits documentation from base class */
startPainting()846 QCPPainter *QCPPaintBufferGlFbo::startPainting()
847 {
848   if (mGlPaintDevice.isNull())
849   {
850     qDebug() << Q_FUNC_INFO << "OpenGL paint device doesn't exist";
851     return 0;
852   }
853   if (!mGlFrameBuffer)
854   {
855     qDebug() << Q_FUNC_INFO << "OpenGL frame buffer object doesn't exist, reallocateBuffer was not called?";
856     return 0;
857   }
858 
859   if (QOpenGLContext::currentContext() != mGlContext.data())
860     mGlContext.data()->makeCurrent(mGlContext.data()->surface());
861   mGlFrameBuffer->bind();
862   QCPPainter *result = new QCPPainter(mGlPaintDevice.data());
863   result->setRenderHint(QPainter::HighQualityAntialiasing);
864   return result;
865 }
866 
867 /* inherits documentation from base class */
donePainting()868 void QCPPaintBufferGlFbo::donePainting()
869 {
870   if (mGlFrameBuffer && mGlFrameBuffer->isBound())
871     mGlFrameBuffer->release();
872   else
873     qDebug() << Q_FUNC_INFO << "Either OpenGL frame buffer not valid or was not bound";
874 }
875 
876 /* inherits documentation from base class */
draw(QCPPainter * painter) const877 void QCPPaintBufferGlFbo::draw(QCPPainter *painter) const
878 {
879   if (!painter || !painter->isActive())
880   {
881     qDebug() << Q_FUNC_INFO << "invalid or inactive painter passed";
882     return;
883   }
884   if (!mGlFrameBuffer)
885   {
886     qDebug() << Q_FUNC_INFO << "OpenGL frame buffer object doesn't exist, reallocateBuffer was not called?";
887     return;
888   }
889   painter->drawImage(0, 0, mGlFrameBuffer->toImage());
890 }
891 
892 /* inherits documentation from base class */
clear(const QColor & color)893 void QCPPaintBufferGlFbo::clear(const QColor &color)
894 {
895   if (mGlContext.isNull())
896   {
897     qDebug() << Q_FUNC_INFO << "OpenGL context doesn't exist";
898     return;
899   }
900   if (!mGlFrameBuffer)
901   {
902     qDebug() << Q_FUNC_INFO << "OpenGL frame buffer object doesn't exist, reallocateBuffer was not called?";
903     return;
904   }
905 
906   if (QOpenGLContext::currentContext() != mGlContext.data())
907     mGlContext.data()->makeCurrent(mGlContext.data()->surface());
908   mGlFrameBuffer->bind();
909   glClearColor(color.redF(), color.greenF(), color.blueF(), color.alphaF());
910   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
911   mGlFrameBuffer->release();
912 }
913 
914 /* inherits documentation from base class */
reallocateBuffer()915 void QCPPaintBufferGlFbo::reallocateBuffer()
916 {
917   // release and delete possibly existing framebuffer:
918   if (mGlFrameBuffer)
919   {
920     if (mGlFrameBuffer->isBound())
921       mGlFrameBuffer->release();
922     delete mGlFrameBuffer;
923     mGlFrameBuffer = 0;
924   }
925 
926   if (mGlContext.isNull())
927   {
928     qDebug() << Q_FUNC_INFO << "OpenGL context doesn't exist";
929     return;
930   }
931   if (mGlPaintDevice.isNull())
932   {
933     qDebug() << Q_FUNC_INFO << "OpenGL paint device doesn't exist";
934     return;
935   }
936 
937   // create new fbo with appropriate size:
938   mGlContext.data()->makeCurrent(mGlContext.data()->surface());
939   QOpenGLFramebufferObjectFormat frameBufferFormat;
940   frameBufferFormat.setSamples(mGlContext.data()->format().samples());
941   frameBufferFormat.setAttachment(QOpenGLFramebufferObject::CombinedDepthStencil);
942   mGlFrameBuffer = new QOpenGLFramebufferObject(mSize*mDevicePixelRatio, frameBufferFormat);
943   if (mGlPaintDevice.data()->size() != mSize*mDevicePixelRatio)
944     mGlPaintDevice.data()->setSize(mSize*mDevicePixelRatio);
945 #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
946   mGlPaintDevice.data()->setDevicePixelRatio(mDevicePixelRatio);
947 #endif
948 }
949 #endif // QCP_OPENGL_FBO
950 /* end of 'src/paintbuffer.cpp' */
951 
952 
953 /* including file 'src/layer.cpp', size 37064                                */
954 /* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
955 
956 ////////////////////////////////////////////////////////////////////////////////////////////////////
957 //////////////////// QCPLayer
958 ////////////////////////////////////////////////////////////////////////////////////////////////////
959 
960 /*! \class QCPLayer
961   \brief A layer that may contain objects, to control the rendering order
962 
963   The Layering system of QCustomPlot is the mechanism to control the rendering order of the
964   elements inside the plot.
965 
966   It is based on the two classes QCPLayer and QCPLayerable. QCustomPlot holds an ordered list of
967   one or more instances of QCPLayer (see QCustomPlot::addLayer, QCustomPlot::layer,
968   QCustomPlot::moveLayer, etc.). When replotting, QCustomPlot goes through the list of layers
969   bottom to top and successively draws the layerables of the layers into the paint buffer(s).
970 
971   A QCPLayer contains an ordered list of QCPLayerable instances. QCPLayerable is an abstract base
972   class from which almost all visible objects derive, like axes, grids, graphs, items, etc.
973 
974   \section qcplayer-defaultlayers Default layers
975 
976   Initially, QCustomPlot has six layers: "background", "grid", "main", "axes", "legend" and
977   "overlay" (in that order). On top is the "overlay" layer, which only contains the QCustomPlot's
978   selection rect (\ref QCustomPlot::selectionRect). The next two layers "axes" and "legend" contain
979   the default axes and legend, so they will be drawn above plottables. In the middle, there is the
980   "main" layer. It is initially empty and set as the current layer (see
981   QCustomPlot::setCurrentLayer). This means, all new plottables, items etc. are created on this
982   layer by default. Then comes the "grid" layer which contains the QCPGrid instances (which belong
983   tightly to QCPAxis, see \ref QCPAxis::grid). The Axis rect background shall be drawn behind
984   everything else, thus the default QCPAxisRect instance is placed on the "background" layer. Of
985   course, the layer affiliation of the individual objects can be changed as required (\ref
986   QCPLayerable::setLayer).
987 
988   \section qcplayer-ordering Controlling the rendering order via layers
989 
990   Controlling the ordering of layerables in the plot is easy: Create a new layer in the position
991   you want the layerable to be in, e.g. above "main", with \ref QCustomPlot::addLayer. Then set the
992   current layer with \ref QCustomPlot::setCurrentLayer to that new layer and finally create the
993   objects normally. They will be placed on the new layer automatically, due to the current layer
994   setting. Alternatively you could have also ignored the current layer setting and just moved the
995   objects with \ref QCPLayerable::setLayer to the desired layer after creating them.
996 
997   It is also possible to move whole layers. For example, If you want the grid to be shown in front
998   of all plottables/items on the "main" layer, just move it above "main" with
999   QCustomPlot::moveLayer.
1000 
1001   The rendering order within one layer is simply by order of creation or insertion. The item
1002   created last (or added last to the layer), is drawn on top of all other objects on that layer.
1003 
1004   When a layer is deleted, the objects on it are not deleted with it, but fall on the layer below
1005   the deleted layer, see QCustomPlot::removeLayer.
1006 
1007   \section qcplayer-buffering Replotting only a specific layer
1008 
1009   If the layer mode (\ref setMode) is set to \ref lmBuffered, you can replot only this specific
1010   layer by calling \ref replot. In certain situations this can provide better replot performance,
1011   compared with a full replot of all layers. Upon creation of a new layer, the layer mode is
1012   initialized to \ref lmLogical. The only layer that is set to \ref lmBuffered in a new \ref
1013   QCustomPlot instance is the "overlay" layer, containing the selection rect.
1014 */
1015 
1016 /* start documentation of inline functions */
1017 
1018 /*! \fn QList<QCPLayerable*> QCPLayer::children() const
1019 
1020   Returns a list of all layerables on this layer. The order corresponds to the rendering order:
1021   layerables with higher indices are drawn above layerables with lower indices.
1022 */
1023 
1024 /*! \fn int QCPLayer::index() const
1025 
1026   Returns the index this layer has in the QCustomPlot. The index is the integer number by which this layer can be
1027   accessed via \ref QCustomPlot::layer.
1028 
1029   Layers with higher indices will be drawn above layers with lower indices.
1030 */
1031 
1032 /* end documentation of inline functions */
1033 
1034 /*!
1035   Creates a new QCPLayer instance.
1036 
1037   Normally you shouldn't directly instantiate layers, use \ref QCustomPlot::addLayer instead.
1038 
1039   \warning It is not checked that \a layerName is actually a unique layer name in \a parentPlot.
1040   This check is only performed by \ref QCustomPlot::addLayer.
1041 */
QCPLayer(QCustomPlot * parentPlot,const QString & layerName)1042 QCPLayer::QCPLayer(QCustomPlot *parentPlot, const QString &layerName) :
1043   QObject(parentPlot),
1044   mParentPlot(parentPlot),
1045   mName(layerName),
1046   mIndex(-1), // will be set to a proper value by the QCustomPlot layer creation function
1047   mVisible(true),
1048   mMode(lmLogical)
1049 {
1050   // Note: no need to make sure layerName is unique, because layer
1051   // management is done with QCustomPlot functions.
1052 }
1053 
~QCPLayer()1054 QCPLayer::~QCPLayer()
1055 {
1056   // If child layerables are still on this layer, detach them, so they don't try to reach back to this
1057   // then invalid layer once they get deleted/moved themselves. This only happens when layers are deleted
1058   // directly, like in the QCustomPlot destructor. (The regular layer removal procedure for the user is to
1059   // call QCustomPlot::removeLayer, which moves all layerables off this layer before deleting it.)
1060 
1061   while (!mChildren.isEmpty())
1062     mChildren.last()->setLayer(0); // removes itself from mChildren via removeChild()
1063 
1064   if (mParentPlot->currentLayer() == this)
1065     qDebug() << Q_FUNC_INFO << "The parent plot's mCurrentLayer will be a dangling pointer. Should have been set to a valid layer or 0 beforehand.";
1066 }
1067 
1068 /*!
1069   Sets whether this layer is visible or not. If \a visible is set to false, all layerables on this
1070   layer will be invisible.
1071 
1072   This function doesn't change the visibility property of the layerables (\ref
1073   QCPLayerable::setVisible), but the \ref QCPLayerable::realVisibility of each layerable takes the
1074   visibility of the parent layer into account.
1075 */
setVisible(bool visible)1076 void QCPLayer::setVisible(bool visible)
1077 {
1078   mVisible = visible;
1079 }
1080 
1081 /*!
1082   Sets the rendering mode of this layer.
1083 
1084   If \a mode is set to \ref lmBuffered for a layer, it will be given a dedicated paint buffer by
1085   the parent QCustomPlot instance. This means it may be replotted individually by calling \ref
1086   QCPLayer::replot, without needing to replot all other layers.
1087 
1088   Layers which are set to \ref lmLogical (the default) are used only to define the rendering order
1089   and can't be replotted individually.
1090 
1091   Note that each layer which is set to \ref lmBuffered requires additional paint buffers for the
1092   layers below, above and for the layer itself. This increases the memory consumption and
1093   (slightly) decreases the repainting speed because multiple paint buffers need to be joined. So
1094   you should carefully choose which layers benefit from having their own paint buffer. A typical
1095   example would be a layer which contains certain layerables (e.g. items) that need to be changed
1096   and thus replotted regularly, while all other layerables on other layers stay static. By default,
1097   only the topmost layer called "overlay" is in mode \ref lmBuffered, and contains the selection
1098   rect.
1099 
1100   \see replot
1101 */
setMode(QCPLayer::LayerMode mode)1102 void QCPLayer::setMode(QCPLayer::LayerMode mode)
1103 {
1104   if (mMode != mode)
1105   {
1106     mMode = mode;
1107     if (auto paint_buffer = mPaintBuffer.toStrongRef())
1108       paint_buffer->setInvalidated();
1109   }
1110 }
1111 
1112 /*! \internal
1113 
1114   Draws the contents of this layer with the provided \a painter.
1115 
1116   \see replot, drawToPaintBuffer
1117 */
draw(QCPPainter * painter)1118 void QCPLayer::draw(QCPPainter *painter)
1119 {
1120   foreach (QCPLayerable *child, mChildren)
1121   {
1122     if (child->realVisibility())
1123     {
1124       painter->save();
1125       painter->setClipRect(child->clipRect().translated(0, -1));
1126       child->applyDefaultAntialiasingHint(painter);
1127       child->draw(painter);
1128       painter->restore();
1129     }
1130   }
1131 }
1132 
1133 /*! \internal
1134 
1135   Draws the contents of this layer into the paint buffer which is associated with this layer. The
1136   association is established by the parent QCustomPlot, which manages all paint buffers (see \ref
1137   QCustomPlot::setupPaintBuffers).
1138 
1139   \see draw
1140 */
drawToPaintBuffer()1141 void QCPLayer::drawToPaintBuffer()
1142 {
1143   if (auto paint_buffer = mPaintBuffer.toStrongRef()) {
1144     if (auto painter = paint_buffer->startPainting())
1145     {
1146       if (painter->isActive())
1147         draw(painter);
1148       else
1149         qDebug() << Q_FUNC_INFO << "paint buffer returned inactive painter";
1150       delete painter;
1151       paint_buffer->donePainting();
1152     } else
1153       qDebug() << Q_FUNC_INFO << "paint buffer returned zero painter";
1154   } else
1155     qDebug() << Q_FUNC_INFO << "no valid paint buffer associated with this layer";
1156 }
1157 
1158 /*!
1159   If the layer mode (\ref setMode) is set to \ref lmBuffered, this method allows replotting only
1160   the layerables on this specific layer, without the need to replot all other layers (as a call to
1161   \ref QCustomPlot::replot would do).
1162 
1163   If the layer mode is \ref lmLogical however, this method simply calls \ref QCustomPlot::replot on
1164   the parent QCustomPlot instance.
1165 
1166   QCustomPlot also makes sure to replot all layers instead of only this one, if the layer ordering
1167   has changed since the last full replot and the other paint buffers were thus invalidated.
1168 
1169   \see draw
1170 */
replot()1171 void QCPLayer::replot()
1172 {
1173   if (mMode == lmBuffered && !mParentPlot->hasInvalidatedPaintBuffers())
1174   {
1175     if (auto paint_buffer = mPaintBuffer.toStrongRef())
1176     {
1177       paint_buffer->clear(Qt::transparent);
1178       drawToPaintBuffer();
1179       paint_buffer->setInvalidated(false);
1180       mParentPlot->update();
1181     } else
1182       qDebug() << Q_FUNC_INFO << "no valid paint buffer associated with this layer";
1183   } else if (mMode == lmLogical)
1184     mParentPlot->replot();
1185 }
1186 
1187 /*! \internal
1188 
1189   Adds the \a layerable to the list of this layer. If \a prepend is set to true, the layerable will
1190   be prepended to the list, i.e. be drawn beneath the other layerables already in the list.
1191 
1192   This function does not change the \a mLayer member of \a layerable to this layer. (Use
1193   QCPLayerable::setLayer to change the layer of an object, not this function.)
1194 
1195   \see removeChild
1196 */
addChild(QCPLayerable * layerable,bool prepend)1197 void QCPLayer::addChild(QCPLayerable *layerable, bool prepend)
1198 {
1199   if (!mChildren.contains(layerable))
1200   {
1201     if (prepend)
1202       mChildren.prepend(layerable);
1203     else
1204       mChildren.append(layerable);
1205     if (auto paint_buffer = mPaintBuffer.toStrongRef())
1206       paint_buffer->setInvalidated();
1207   } else
1208     qDebug() << Q_FUNC_INFO << "layerable is already child of this layer" << reinterpret_cast<quintptr>(layerable);
1209 }
1210 
1211 /*! \internal
1212 
1213   Removes the \a layerable from the list of this layer.
1214 
1215   This function does not change the \a mLayer member of \a layerable. (Use QCPLayerable::setLayer
1216   to change the layer of an object, not this function.)
1217 
1218   \see addChild
1219 */
removeChild(QCPLayerable * layerable)1220 void QCPLayer::removeChild(QCPLayerable *layerable)
1221 {
1222   if (mChildren.removeOne(layerable))
1223   {
1224     if (auto paint_buffer = mPaintBuffer.toStrongRef())
1225       paint_buffer->setInvalidated();
1226   } else
1227     qDebug() << Q_FUNC_INFO << "layerable is not child of this layer" << reinterpret_cast<quintptr>(layerable);
1228 }
1229 
1230 
1231 ////////////////////////////////////////////////////////////////////////////////////////////////////
1232 //////////////////// QCPLayerable
1233 ////////////////////////////////////////////////////////////////////////////////////////////////////
1234 
1235 /*! \class QCPLayerable
1236   \brief Base class for all drawable objects
1237 
1238   This is the abstract base class most visible objects derive from, e.g. plottables, axes, grid
1239   etc.
1240 
1241   Every layerable is on a layer (QCPLayer) which allows controlling the rendering order by stacking
1242   the layers accordingly.
1243 
1244   For details about the layering mechanism, see the QCPLayer documentation.
1245 */
1246 
1247 /* start documentation of inline functions */
1248 
1249 /*! \fn QCPLayerable *QCPLayerable::parentLayerable() const
1250 
1251   Returns the parent layerable of this layerable. The parent layerable is used to provide
1252   visibility hierarchies in conjunction with the method \ref realVisibility. This way, layerables
1253   only get drawn if their parent layerables are visible, too.
1254 
1255   Note that a parent layerable is not necessarily also the QObject parent for memory management.
1256   Further, a layerable doesn't always have a parent layerable, so this function may return 0.
1257 
1258   A parent layerable is set implicitly when placed inside layout elements and doesn't need to be
1259   set manually by the user.
1260 */
1261 
1262 /* end documentation of inline functions */
1263 /* start documentation of pure virtual functions */
1264 
1265 /*! \fn virtual void QCPLayerable::applyDefaultAntialiasingHint(QCPPainter *painter) const = 0
1266   \internal
1267 
1268   This function applies the default antialiasing setting to the specified \a painter, using the
1269   function \ref applyAntialiasingHint. It is the antialiasing state the painter is put in, when
1270   \ref draw is called on the layerable. If the layerable has multiple entities whose antialiasing
1271   setting may be specified individually, this function should set the antialiasing state of the
1272   most prominent entity. In this case however, the \ref draw function usually calls the specialized
1273   versions of this function before drawing each entity, effectively overriding the setting of the
1274   default antialiasing hint.
1275 
1276   <b>First example:</b> QCPGraph has multiple entities that have an antialiasing setting: The graph
1277   line, fills and scatters. Those can be configured via QCPGraph::setAntialiased,
1278   QCPGraph::setAntialiasedFill and QCPGraph::setAntialiasedScatters. Consequently, there isn't only
1279   the QCPGraph::applyDefaultAntialiasingHint function (which corresponds to the graph line's
1280   antialiasing), but specialized ones like QCPGraph::applyFillAntialiasingHint and
1281   QCPGraph::applyScattersAntialiasingHint. So before drawing one of those entities, QCPGraph::draw
1282   calls the respective specialized applyAntialiasingHint function.
1283 
1284   <b>Second example:</b> QCPItemLine consists only of a line so there is only one antialiasing
1285   setting which can be controlled with QCPItemLine::setAntialiased. (This function is inherited by
1286   all layerables. The specialized functions, as seen on QCPGraph, must be added explicitly to the
1287   respective layerable subclass.) Consequently it only has the normal
1288   QCPItemLine::applyDefaultAntialiasingHint. The \ref QCPItemLine::draw function doesn't need to
1289   care about setting any antialiasing states, because the default antialiasing hint is already set
1290   on the painter when the \ref draw function is called, and that's the state it wants to draw the
1291   line with.
1292 */
1293 
1294 /*! \fn virtual void QCPLayerable::draw(QCPPainter *painter) const = 0
1295   \internal
1296 
1297   This function draws the layerable with the specified \a painter. It is only called by
1298   QCustomPlot, if the layerable is visible (\ref setVisible).
1299 
1300   Before this function is called, the painter's antialiasing state is set via \ref
1301   applyDefaultAntialiasingHint, see the documentation there. Further, the clipping rectangle was
1302   set to \ref clipRect.
1303 */
1304 
1305 /* end documentation of pure virtual functions */
1306 /* start documentation of signals */
1307 
1308 /*! \fn void QCPLayerable::layerChanged(QCPLayer *newLayer);
1309 
1310   This signal is emitted when the layer of this layerable changes, i.e. this layerable is moved to
1311   a different layer.
1312 
1313   \see setLayer
1314 */
1315 
1316 /* end documentation of signals */
1317 
1318 /*!
1319   Creates a new QCPLayerable instance.
1320 
1321   Since QCPLayerable is an abstract base class, it can't be instantiated directly. Use one of the
1322   derived classes.
1323 
1324   If \a plot is provided, it automatically places itself on the layer named \a targetLayer. If \a
1325   targetLayer is an empty string, it places itself on the current layer of the plot (see \ref
1326   QCustomPlot::setCurrentLayer).
1327 
1328   It is possible to provide 0 as \a plot. In that case, you should assign a parent plot at a later
1329   time with \ref initializeParentPlot.
1330 
1331   The layerable's parent layerable is set to \a parentLayerable, if provided. Direct layerable
1332   parents are mainly used to control visibility in a hierarchy of layerables. This means a
1333   layerable is only drawn, if all its ancestor layerables are also visible. Note that \a
1334   parentLayerable does not become the QObject-parent (for memory management) of this layerable, \a
1335   plot does. It is not uncommon to set the QObject-parent to something else in the constructors of
1336   QCPLayerable subclasses, to guarantee a working destruction hierarchy.
1337 */
QCPLayerable(QCustomPlot * plot,QString targetLayer,QCPLayerable * parentLayerable)1338 QCPLayerable::QCPLayerable(QCustomPlot *plot, QString targetLayer, QCPLayerable *parentLayerable) :
1339   QObject(plot),
1340   mVisible(true),
1341   mParentPlot(plot),
1342   mParentLayerable(parentLayerable),
1343   mLayer(0),
1344   mAntialiased(true)
1345 {
1346   if (mParentPlot)
1347   {
1348     if (targetLayer.isEmpty())
1349       setLayer(mParentPlot->currentLayer());
1350     else if (!setLayer(targetLayer))
1351       qDebug() << Q_FUNC_INFO << "setting QCPlayerable initial layer to" << targetLayer << "failed.";
1352   }
1353 }
1354 
~QCPLayerable()1355 QCPLayerable::~QCPLayerable()
1356 {
1357   if (mLayer)
1358   {
1359     mLayer->removeChild(this);
1360     mLayer = 0;
1361   }
1362 }
1363 
1364 /*!
1365   Sets the visibility of this layerable object. If an object is not visible, it will not be drawn
1366   on the QCustomPlot surface, and user interaction with it (e.g. click and selection) is not
1367   possible.
1368 */
setVisible(bool on)1369 void QCPLayerable::setVisible(bool on)
1370 {
1371   mVisible = on;
1372 }
1373 
1374 /*!
1375   Sets the \a layer of this layerable object. The object will be placed on top of the other objects
1376   already on \a layer.
1377 
1378   If \a layer is 0, this layerable will not be on any layer and thus not appear in the plot (or
1379   interact/receive events).
1380 
1381   Returns true if the layer of this layerable was successfully changed to \a layer.
1382 */
setLayer(QCPLayer * layer)1383 bool QCPLayerable::setLayer(QCPLayer *layer)
1384 {
1385   return moveToLayer(layer, false);
1386 }
1387 
1388 /*! \overload
1389   Sets the layer of this layerable object by name
1390 
1391   Returns true on success, i.e. if \a layerName is a valid layer name.
1392 */
setLayer(const QString & layerName)1393 bool QCPLayerable::setLayer(const QString &layerName)
1394 {
1395   if (!mParentPlot)
1396   {
1397     qDebug() << Q_FUNC_INFO << "no parent QCustomPlot set";
1398     return false;
1399   }
1400   if (QCPLayer *layer = mParentPlot->layer(layerName))
1401   {
1402     return setLayer(layer);
1403   } else
1404   {
1405     qDebug() << Q_FUNC_INFO << "there is no layer with name" << layerName;
1406     return false;
1407   }
1408 }
1409 
1410 /*!
1411   Sets whether this object will be drawn antialiased or not.
1412 
1413   Note that antialiasing settings may be overridden by QCustomPlot::setAntialiasedElements and
1414   QCustomPlot::setNotAntialiasedElements.
1415 */
setAntialiased(bool enabled)1416 void QCPLayerable::setAntialiased(bool enabled)
1417 {
1418   mAntialiased = enabled;
1419 }
1420 
1421 /*!
1422   Returns whether this layerable is visible, taking the visibility of the layerable parent and the
1423   visibility of this layerable's layer into account. This is the method that is consulted to decide
1424   whether a layerable shall be drawn or not.
1425 
1426   If this layerable has a direct layerable parent (usually set via hierarchies implemented in
1427   subclasses, like in the case of \ref QCPLayoutElement), this function returns true only if this
1428   layerable has its visibility set to true and the parent layerable's \ref realVisibility returns
1429   true.
1430 */
realVisibility() const1431 bool QCPLayerable::realVisibility() const
1432 {
1433   return mVisible && (!mLayer || mLayer->visible()) && (!mParentLayerable || mParentLayerable.data()->realVisibility());
1434 }
1435 
1436 /*!
1437   This function is used to decide whether a click hits a layerable object or not.
1438 
1439   \a pos is a point in pixel coordinates on the QCustomPlot surface. This function returns the
1440   shortest pixel distance of this point to the object. If the object is either invisible or the
1441   distance couldn't be determined, -1.0 is returned. Further, if \a onlySelectable is true and the
1442   object is not selectable, -1.0 is returned, too.
1443 
1444   If the object is represented not by single lines but by an area like a \ref QCPItemText or the
1445   bars of a \ref QCPBars plottable, a click inside the area should also be considered a hit. In
1446   these cases this function thus returns a constant value greater zero but still below the parent
1447   plot's selection tolerance. (typically the selectionTolerance multiplied by 0.99).
1448 
1449   Providing a constant value for area objects allows selecting line objects even when they are
1450   obscured by such area objects, by clicking close to the lines (i.e. closer than
1451   0.99*selectionTolerance).
1452 
1453   The actual setting of the selection state is not done by this function. This is handled by the
1454   parent QCustomPlot when the mouseReleaseEvent occurs, and the finally selected object is notified
1455   via the \ref selectEvent/\ref deselectEvent methods.
1456 
1457   \a details is an optional output parameter. Every layerable subclass may place any information
1458   in \a details. This information will be passed to \ref selectEvent when the parent QCustomPlot
1459   decides on the basis of this selectTest call, that the object was successfully selected. The
1460   subsequent call to \ref selectEvent will carry the \a details. This is useful for multi-part
1461   objects (like QCPAxis). This way, a possibly complex calculation to decide which part was clicked
1462   is only done once in \ref selectTest. The result (i.e. the actually clicked part) can then be
1463   placed in \a details. So in the subsequent \ref selectEvent, the decision which part was
1464   selected doesn't have to be done a second time for a single selection operation.
1465 
1466   You may pass 0 as \a details to indicate that you are not interested in those selection details.
1467 
1468   \see selectEvent, deselectEvent, mousePressEvent, wheelEvent, QCustomPlot::setInteractions
1469 */
selectTest(const QPointF & pos,bool onlySelectable,QVariant * details) const1470 double QCPLayerable::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
1471 {
1472   Q_UNUSED(pos)
1473   Q_UNUSED(onlySelectable)
1474   Q_UNUSED(details)
1475   return -1.0;
1476 }
1477 
1478 /*! \internal
1479 
1480   Sets the parent plot of this layerable. Use this function once to set the parent plot if you have
1481   passed 0 in the constructor. It can not be used to move a layerable from one QCustomPlot to
1482   another one.
1483 
1484   Note that, unlike when passing a non-null parent plot in the constructor, this function does not
1485   make \a parentPlot the QObject-parent of this layerable. If you want this, call
1486   QObject::setParent(\a parentPlot) in addition to this function.
1487 
1488   Further, you will probably want to set a layer (\ref setLayer) after calling this function, to
1489   make the layerable appear on the QCustomPlot.
1490 
1491   The parent plot change will be propagated to subclasses via a call to \ref parentPlotInitialized
1492   so they can react accordingly (e.g. also initialize the parent plot of child layerables, like
1493   QCPLayout does).
1494 */
initializeParentPlot(QCustomPlot * parentPlot)1495 void QCPLayerable::initializeParentPlot(QCustomPlot *parentPlot)
1496 {
1497   if (mParentPlot)
1498   {
1499     qDebug() << Q_FUNC_INFO << "called with mParentPlot already initialized";
1500     return;
1501   }
1502 
1503   if (!parentPlot)
1504     qDebug() << Q_FUNC_INFO << "called with parentPlot zero";
1505 
1506   mParentPlot = parentPlot;
1507   parentPlotInitialized(mParentPlot);
1508 }
1509 
1510 /*! \internal
1511 
1512   Sets the parent layerable of this layerable to \a parentLayerable. Note that \a parentLayerable does not
1513   become the QObject-parent (for memory management) of this layerable.
1514 
1515   The parent layerable has influence on the return value of the \ref realVisibility method. Only
1516   layerables with a fully visible parent tree will return true for \ref realVisibility, and thus be
1517   drawn.
1518 
1519   \see realVisibility
1520 */
setParentLayerable(QCPLayerable * parentLayerable)1521 void QCPLayerable::setParentLayerable(QCPLayerable *parentLayerable)
1522 {
1523   mParentLayerable = parentLayerable;
1524 }
1525 
1526 /*! \internal
1527 
1528   Moves this layerable object to \a layer. If \a prepend is true, this object will be prepended to
1529   the new layer's list, i.e. it will be drawn below the objects already on the layer. If it is
1530   false, the object will be appended.
1531 
1532   Returns true on success, i.e. if \a layer is a valid layer.
1533 */
moveToLayer(QCPLayer * layer,bool prepend)1534 bool QCPLayerable::moveToLayer(QCPLayer *layer, bool prepend)
1535 {
1536   if (layer && !mParentPlot)
1537   {
1538     qDebug() << Q_FUNC_INFO << "no parent QCustomPlot set";
1539     return false;
1540   }
1541   if (layer && layer->parentPlot() != mParentPlot)
1542   {
1543     qDebug() << Q_FUNC_INFO << "layer" << layer->name() << "is not in same QCustomPlot as this layerable";
1544     return false;
1545   }
1546 
1547   QCPLayer *oldLayer = mLayer;
1548   if (mLayer)
1549     mLayer->removeChild(this);
1550   mLayer = layer;
1551   if (mLayer)
1552     mLayer->addChild(this, prepend);
1553   if (mLayer != oldLayer)
1554     emit layerChanged(mLayer);
1555   return true;
1556 }
1557 
1558 /*! \internal
1559 
1560   Sets the QCPainter::setAntialiasing state on the provided \a painter, depending on the \a
1561   localAntialiased value as well as the overrides \ref QCustomPlot::setAntialiasedElements and \ref
1562   QCustomPlot::setNotAntialiasedElements. Which override enum this function takes into account is
1563   controlled via \a overrideElement.
1564 */
applyAntialiasingHint(QCPPainter * painter,bool localAntialiased,QCP::AntialiasedElement overrideElement) const1565 void QCPLayerable::applyAntialiasingHint(QCPPainter *painter, bool localAntialiased, QCP::AntialiasedElement overrideElement) const
1566 {
1567   if (mParentPlot && mParentPlot->notAntialiasedElements().testFlag(overrideElement))
1568     painter->setAntialiasing(false);
1569   else if (mParentPlot && mParentPlot->antialiasedElements().testFlag(overrideElement))
1570     painter->setAntialiasing(true);
1571   else
1572     painter->setAntialiasing(localAntialiased);
1573 }
1574 
1575 /*! \internal
1576 
1577   This function is called by \ref initializeParentPlot, to allow subclasses to react on the setting
1578   of a parent plot. This is the case when 0 was passed as parent plot in the constructor, and the
1579   parent plot is set at a later time.
1580 
1581   For example, QCPLayoutElement/QCPLayout hierarchies may be created independently of any
1582   QCustomPlot at first. When they are then added to a layout inside the QCustomPlot, the top level
1583   element of the hierarchy gets its parent plot initialized with \ref initializeParentPlot. To
1584   propagate the parent plot to all the children of the hierarchy, the top level element then uses
1585   this function to pass the parent plot on to its child elements.
1586 
1587   The default implementation does nothing.
1588 
1589   \see initializeParentPlot
1590 */
parentPlotInitialized(QCustomPlot * parentPlot)1591 void QCPLayerable::parentPlotInitialized(QCustomPlot *parentPlot)
1592 {
1593    Q_UNUSED(parentPlot)
1594 }
1595 
1596 /*! \internal
1597 
1598   Returns the selection category this layerable shall belong to. The selection category is used in
1599   conjunction with \ref QCustomPlot::setInteractions to control which objects are selectable and
1600   which aren't.
1601 
1602   Subclasses that don't fit any of the normal \ref QCP::Interaction values can use \ref
1603   QCP::iSelectOther. This is what the default implementation returns.
1604 
1605   \see QCustomPlot::setInteractions
1606 */
selectionCategory() const1607 QCP::Interaction QCPLayerable::selectionCategory() const
1608 {
1609   return QCP::iSelectOther;
1610 }
1611 
1612 /*! \internal
1613 
1614   Returns the clipping rectangle of this layerable object. By default, this is the viewport of the
1615   parent QCustomPlot. Specific subclasses may reimplement this function to provide different
1616   clipping rects.
1617 
1618   The returned clipping rect is set on the painter before the draw function of the respective
1619   object is called.
1620 */
clipRect() const1621 QRect QCPLayerable::clipRect() const
1622 {
1623   if (mParentPlot)
1624     return mParentPlot->viewport();
1625   else
1626     return QRect();
1627 }
1628 
1629 /*! \internal
1630 
1631   This event is called when the layerable shall be selected, as a consequence of a click by the
1632   user. Subclasses should react to it by setting their selection state appropriately. The default
1633   implementation does nothing.
1634 
1635   \a event is the mouse event that caused the selection. \a additive indicates, whether the user
1636   was holding the multi-select-modifier while performing the selection (see \ref
1637   QCustomPlot::setMultiSelectModifier). if \a additive is true, the selection state must be toggled
1638   (i.e. become selected when unselected and unselected when selected).
1639 
1640   Every selectEvent is preceded by a call to \ref selectTest, which has returned positively (i.e.
1641   returned a value greater than 0 and less than the selection tolerance of the parent QCustomPlot).
1642   The \a details data you output from \ref selectTest is fed back via \a details here. You may
1643   use it to transport any kind of information from the selectTest to the possibly subsequent
1644   selectEvent. Usually \a details is used to transfer which part was clicked, if it is a layerable
1645   that has multiple individually selectable parts (like QCPAxis). This way selectEvent doesn't need
1646   to do the calculation again to find out which part was actually clicked.
1647 
1648   \a selectionStateChanged is an output parameter. If the pointer is non-null, this function must
1649   set the value either to true or false, depending on whether the selection state of this layerable
1650   was actually changed. For layerables that only are selectable as a whole and not in parts, this
1651   is simple: if \a additive is true, \a selectionStateChanged must also be set to true, because the
1652   selection toggles. If \a additive is false, \a selectionStateChanged is only set to true, if the
1653   layerable was previously unselected and now is switched to the selected state.
1654 
1655   \see selectTest, deselectEvent
1656 */
selectEvent(QMouseEvent * event,bool additive,const QVariant & details,bool * selectionStateChanged)1657 void QCPLayerable::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
1658 {
1659   Q_UNUSED(event)
1660   Q_UNUSED(additive)
1661   Q_UNUSED(details)
1662   Q_UNUSED(selectionStateChanged)
1663 }
1664 
1665 /*! \internal
1666 
1667   This event is called when the layerable shall be deselected, either as consequence of a user
1668   interaction or a call to \ref QCustomPlot::deselectAll. Subclasses should react to it by
1669   unsetting their selection appropriately.
1670 
1671   just as in \ref selectEvent, the output parameter \a selectionStateChanged (if non-null), must
1672   return true or false when the selection state of this layerable has changed or not changed,
1673   respectively.
1674 
1675   \see selectTest, selectEvent
1676 */
deselectEvent(bool * selectionStateChanged)1677 void QCPLayerable::deselectEvent(bool *selectionStateChanged)
1678 {
1679   Q_UNUSED(selectionStateChanged)
1680 }
1681 
1682 /*!
1683   This event gets called when the user presses a mouse button while the cursor is over the
1684   layerable. Whether a cursor is over the layerable is decided by a preceding call to \ref
1685   selectTest.
1686 
1687   The current pixel position of the cursor on the QCustomPlot widget is accessible via \c
1688   event->pos(). The parameter \a details contains layerable-specific details about the hit, which
1689   were generated in the previous call to \ref selectTest. For example, One-dimensional plottables
1690   like \ref QCPGraph or \ref QCPBars convey the clicked data point in the \a details parameter, as
1691   \ref QCPDataSelection packed as QVariant. Multi-part objects convey the specific \c
1692   SelectablePart that was hit (e.g. \ref QCPAxis::SelectablePart in the case of axes).
1693 
1694   QCustomPlot uses an event propagation system that works the same as Qt's system. If your
1695   layerable doesn't reimplement the \ref mousePressEvent or explicitly calls \c event->ignore() in
1696   its reimplementation, the event will be propagated to the next layerable in the stacking order.
1697 
1698   Once a layerable has accepted the \ref mousePressEvent, it is considered the mouse grabber and
1699   will receive all following calls to \ref mouseMoveEvent or \ref mouseReleaseEvent for this mouse
1700   interaction (a "mouse interaction" in this context ends with the release).
1701 
1702   The default implementation does nothing except explicitly ignoring the event with \c
1703   event->ignore().
1704 
1705   \see mouseMoveEvent, mouseReleaseEvent, mouseDoubleClickEvent, wheelEvent
1706 */
mousePressEvent(QMouseEvent * event,const QVariant & details)1707 void QCPLayerable::mousePressEvent(QMouseEvent *event, const QVariant &details)
1708 {
1709   Q_UNUSED(details)
1710   event->ignore();
1711 }
1712 
1713 /*!
1714   This event gets called when the user moves the mouse while holding a mouse button, after this
1715   layerable has become the mouse grabber by accepting the preceding \ref mousePressEvent.
1716 
1717   The current pixel position of the cursor on the QCustomPlot widget is accessible via \c
1718   event->pos(). The parameter \a startPos indicates the position where the initial \ref
1719   mousePressEvent occured, that started the mouse interaction.
1720 
1721   The default implementation does nothing.
1722 
1723   \see mousePressEvent, mouseReleaseEvent, mouseDoubleClickEvent, wheelEvent
1724 */
mouseMoveEvent(QMouseEvent * event,const QPointF & startPos)1725 void QCPLayerable::mouseMoveEvent(QMouseEvent *event, const QPointF &startPos)
1726 {
1727   Q_UNUSED(startPos)
1728   event->ignore();
1729 }
1730 
1731 /*!
1732   This event gets called when the user releases the mouse button, after this layerable has become
1733   the mouse grabber by accepting the preceding \ref mousePressEvent.
1734 
1735   The current pixel position of the cursor on the QCustomPlot widget is accessible via \c
1736   event->pos(). The parameter \a startPos indicates the position where the initial \ref
1737   mousePressEvent occured, that started the mouse interaction.
1738 
1739   The default implementation does nothing.
1740 
1741   \see mousePressEvent, mouseMoveEvent, mouseDoubleClickEvent, wheelEvent
1742 */
mouseReleaseEvent(QMouseEvent * event,const QPointF & startPos)1743 void QCPLayerable::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos)
1744 {
1745   Q_UNUSED(startPos)
1746   event->ignore();
1747 }
1748 
1749 /*!
1750   This event gets called when the user presses the mouse button a second time in a double-click,
1751   while the cursor is over the layerable. Whether a cursor is over the layerable is decided by a
1752   preceding call to \ref selectTest.
1753 
1754   The \ref mouseDoubleClickEvent is called instead of the second \ref mousePressEvent. So in the
1755   case of a double-click, the event succession is
1756   <i>pressEvent &ndash; releaseEvent &ndash; doubleClickEvent &ndash; releaseEvent</i>.
1757 
1758   The current pixel position of the cursor on the QCustomPlot widget is accessible via \c
1759   event->pos(). The parameter \a details contains layerable-specific details about the hit, which
1760   were generated in the previous call to \ref selectTest. For example, One-dimensional plottables
1761   like \ref QCPGraph or \ref QCPBars convey the clicked data point in the \a details parameter, as
1762   \ref QCPDataSelection packed as QVariant. Multi-part objects convey the specific \c
1763   SelectablePart that was hit (e.g. \ref QCPAxis::SelectablePart in the case of axes).
1764 
1765   Similarly to \ref mousePressEvent, once a layerable has accepted the \ref mouseDoubleClickEvent,
1766   it is considered the mouse grabber and will receive all following calls to \ref mouseMoveEvent
1767   and \ref mouseReleaseEvent for this mouse interaction (a "mouse interaction" in this context ends
1768   with the release).
1769 
1770   The default implementation does nothing except explicitly ignoring the event with \c
1771   event->ignore().
1772 
1773   \see mousePressEvent, mouseMoveEvent, mouseReleaseEvent, wheelEvent
1774 */
mouseDoubleClickEvent(QMouseEvent * event,const QVariant & details)1775 void QCPLayerable::mouseDoubleClickEvent(QMouseEvent *event, const QVariant &details)
1776 {
1777   Q_UNUSED(details)
1778   event->ignore();
1779 }
1780 
1781 /*!
1782   This event gets called when the user turns the mouse scroll wheel while the cursor is over the
1783   layerable. Whether a cursor is over the layerable is decided by a preceding call to \ref
1784   selectTest.
1785 
1786   The current pixel position of the cursor on the QCustomPlot widget is accessible via \c
1787   event->pos().
1788 
1789   The \c event->delta() indicates how far the mouse wheel was turned, which is usually +/- 120 for
1790   single rotation steps. However, if the mouse wheel is turned rapidly, multiple steps may
1791   accumulate to one event, making \c event->delta() larger. On the other hand, if the wheel has
1792   very smooth steps or none at all, the delta may be smaller.
1793 
1794   The default implementation does nothing.
1795 
1796   \see mousePressEvent, mouseMoveEvent, mouseReleaseEvent, mouseDoubleClickEvent
1797 */
wheelEvent(QWheelEvent * event)1798 void QCPLayerable::wheelEvent(QWheelEvent *event)
1799 {
1800   event->ignore();
1801 }
1802 /* end of 'src/layer.cpp' */
1803 
1804 
1805 /* including file 'src/axis/range.cpp', size 12221                           */
1806 /* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
1807 
1808 ////////////////////////////////////////////////////////////////////////////////////////////////////
1809 //////////////////// QCPRange
1810 ////////////////////////////////////////////////////////////////////////////////////////////////////
1811 /*! \class QCPRange
1812   \brief Represents the range an axis is encompassing.
1813 
1814   contains a \a lower and \a upper double value and provides convenience input, output and
1815   modification functions.
1816 
1817   \see QCPAxis::setRange
1818 */
1819 
1820 /* start of documentation of inline functions */
1821 
1822 /*! \fn double QCPRange::size() const
1823 
1824   Returns the size of the range, i.e. \a upper-\a lower
1825 */
1826 
1827 /*! \fn double QCPRange::center() const
1828 
1829   Returns the center of the range, i.e. (\a upper+\a lower)*0.5
1830 */
1831 
1832 /*! \fn void QCPRange::normalize()
1833 
1834   Makes sure \a lower is numerically smaller than \a upper. If this is not the case, the values are
1835   swapped.
1836 */
1837 
1838 /*! \fn bool QCPRange::contains(double value) const
1839 
1840   Returns true when \a value lies within or exactly on the borders of the range.
1841 */
1842 
1843 /*! \fn QCPRange &QCPRange::operator+=(const double& value)
1844 
1845   Adds \a value to both boundaries of the range.
1846 */
1847 
1848 /*! \fn QCPRange &QCPRange::operator-=(const double& value)
1849 
1850   Subtracts \a value from both boundaries of the range.
1851 */
1852 
1853 /*! \fn QCPRange &QCPRange::operator*=(const double& value)
1854 
1855   Multiplies both boundaries of the range by \a value.
1856 */
1857 
1858 /*! \fn QCPRange &QCPRange::operator/=(const double& value)
1859 
1860   Divides both boundaries of the range by \a value.
1861 */
1862 
1863 /* end of documentation of inline functions */
1864 
1865 /*!
1866   Minimum range size (\a upper - \a lower) the range changing functions will accept. Smaller
1867   intervals would cause errors due to the 11-bit exponent of double precision numbers,
1868   corresponding to a minimum magnitude of roughly 1e-308.
1869 
1870   \warning Do not use this constant to indicate "arbitrarily small" values in plotting logic (as
1871   values that will appear in the plot)! It is intended only as a bound to compare against, e.g. to
1872   prevent axis ranges from obtaining underflowing ranges.
1873 
1874   \see validRange, maxRange
1875 */
1876 const double QCPRange::minRange = 1e-280;
1877 
1878 /*!
1879   Maximum values (negative and positive) the range will accept in range-changing functions.
1880   Larger absolute values would cause errors due to the 11-bit exponent of double precision numbers,
1881   corresponding to a maximum magnitude of roughly 1e308.
1882 
1883   \warning Do not use this constant to indicate "arbitrarily large" values in plotting logic (as
1884   values that will appear in the plot)! It is intended only as a bound to compare against, e.g. to
1885   prevent axis ranges from obtaining overflowing ranges.
1886 
1887   \see validRange, minRange
1888 */
1889 const double QCPRange::maxRange = 1e250;
1890 
1891 /*!
1892   Constructs a range with \a lower and \a upper set to zero.
1893 */
QCPRange()1894 QCPRange::QCPRange() :
1895   lower(0),
1896   upper(0)
1897 {
1898 }
1899 
1900 /*! \overload
1901 
1902   Constructs a range with the specified \a lower and \a upper values.
1903 
1904   The resulting range will be normalized (see \ref normalize), so if \a lower is not numerically
1905   smaller than \a upper, they will be swapped.
1906 */
QCPRange(double lower,double upper)1907 QCPRange::QCPRange(double lower, double upper) :
1908   lower(lower),
1909   upper(upper)
1910 {
1911   normalize();
1912 }
1913 
1914 /*! \overload
1915 
1916   Expands this range such that \a otherRange is contained in the new range. It is assumed that both
1917   this range and \a otherRange are normalized (see \ref normalize).
1918 
1919   If this range contains NaN as lower or upper bound, it will be replaced by the respective bound
1920   of \a otherRange.
1921 
1922   If \a otherRange is already inside the current range, this function does nothing.
1923 
1924   \see expanded
1925 */
expand(const QCPRange & otherRange)1926 void QCPRange::expand(const QCPRange &otherRange)
1927 {
1928   if (lower > otherRange.lower || qIsNaN(lower))
1929     lower = otherRange.lower;
1930   if (upper < otherRange.upper || qIsNaN(upper))
1931     upper = otherRange.upper;
1932 }
1933 
1934 /*! \overload
1935 
1936   Expands this range such that \a includeCoord is contained in the new range. It is assumed that
1937   this range is normalized (see \ref normalize).
1938 
1939   If this range contains NaN as lower or upper bound, the respective bound will be set to \a
1940   includeCoord.
1941 
1942   If \a includeCoord is already inside the current range, this function does nothing.
1943 
1944   \see expand
1945 */
expand(double includeCoord)1946 void QCPRange::expand(double includeCoord)
1947 {
1948   if (lower > includeCoord || qIsNaN(lower))
1949     lower = includeCoord;
1950   if (upper < includeCoord || qIsNaN(upper))
1951     upper = includeCoord;
1952 }
1953 
1954 
1955 /*! \overload
1956 
1957   Returns an expanded range that contains this and \a otherRange. It is assumed that both this
1958   range and \a otherRange are normalized (see \ref normalize).
1959 
1960   If this range contains NaN as lower or upper bound, the returned range's bound will be taken from
1961   \a otherRange.
1962 
1963   \see expand
1964 */
expanded(const QCPRange & otherRange) const1965 QCPRange QCPRange::expanded(const QCPRange &otherRange) const
1966 {
1967   QCPRange result = *this;
1968   result.expand(otherRange);
1969   return result;
1970 }
1971 
1972 /*! \overload
1973 
1974   Returns an expanded range that includes the specified \a includeCoord. It is assumed that this
1975   range is normalized (see \ref normalize).
1976 
1977   If this range contains NaN as lower or upper bound, the returned range's bound will be set to \a
1978   includeCoord.
1979 
1980   \see expand
1981 */
expanded(double includeCoord) const1982 QCPRange QCPRange::expanded(double includeCoord) const
1983 {
1984   QCPRange result = *this;
1985   result.expand(includeCoord);
1986   return result;
1987 }
1988 
1989 /*!
1990   Returns this range, possibly modified to not exceed the bounds provided as \a lowerBound and \a
1991   upperBound. If possible, the size of the current range is preserved in the process.
1992 
1993   If the range shall only be bounded at the lower side, you can set \a upperBound to \ref
1994   QCPRange::maxRange. If it shall only be bounded at the upper side, set \a lowerBound to -\ref
1995   QCPRange::maxRange.
1996 */
bounded(double lowerBound,double upperBound) const1997 QCPRange QCPRange::bounded(double lowerBound, double upperBound) const
1998 {
1999   if (lowerBound > upperBound)
2000     qSwap(lowerBound, upperBound);
2001 
2002   QCPRange result(lower, upper);
2003   if (result.lower < lowerBound)
2004   {
2005     result.lower = lowerBound;
2006     result.upper = lowerBound + size();
2007     if (result.upper > upperBound || qFuzzyCompare(size(), upperBound-lowerBound))
2008       result.upper = upperBound;
2009   } else if (result.upper > upperBound)
2010   {
2011     result.upper = upperBound;
2012     result.lower = upperBound - size();
2013     if (result.lower < lowerBound || qFuzzyCompare(size(), upperBound-lowerBound))
2014       result.lower = lowerBound;
2015   }
2016 
2017   return result;
2018 }
2019 
2020 /*!
2021   Returns a sanitized version of the range. Sanitized means for logarithmic scales, that
2022   the range won't span the positive and negative sign domain, i.e. contain zero. Further
2023   \a lower will always be numerically smaller (or equal) to \a upper.
2024 
2025   If the original range does span positive and negative sign domains or contains zero,
2026   the returned range will try to approximate the original range as good as possible.
2027   If the positive interval of the original range is wider than the negative interval, the
2028   returned range will only contain the positive interval, with lower bound set to \a rangeFac or
2029   \a rangeFac *\a upper, whichever is closer to zero. Same procedure is used if the negative interval
2030   is wider than the positive interval, this time by changing the \a upper bound.
2031 */
sanitizedForLogScale() const2032 QCPRange QCPRange::sanitizedForLogScale() const
2033 {
2034   double rangeFac = 1e-3;
2035   QCPRange sanitizedRange(lower, upper);
2036   sanitizedRange.normalize();
2037   // can't have range spanning negative and positive values in log plot, so change range to fix it
2038   //if (qFuzzyCompare(sanitizedRange.lower+1, 1) && !qFuzzyCompare(sanitizedRange.upper+1, 1))
2039   if (sanitizedRange.lower == 0.0 && sanitizedRange.upper != 0.0)
2040   {
2041     // case lower is 0
2042     if (rangeFac < sanitizedRange.upper*rangeFac)
2043       sanitizedRange.lower = rangeFac;
2044     else
2045       sanitizedRange.lower = sanitizedRange.upper*rangeFac;
2046   } //else if (!qFuzzyCompare(lower+1, 1) && qFuzzyCompare(upper+1, 1))
2047   else if (sanitizedRange.lower != 0.0 && sanitizedRange.upper == 0.0)
2048   {
2049     // case upper is 0
2050     if (-rangeFac > sanitizedRange.lower*rangeFac)
2051       sanitizedRange.upper = -rangeFac;
2052     else
2053       sanitizedRange.upper = sanitizedRange.lower*rangeFac;
2054   } else if (sanitizedRange.lower < 0 && sanitizedRange.upper > 0)
2055   {
2056     // find out whether negative or positive interval is wider to decide which sign domain will be chosen
2057     if (-sanitizedRange.lower > sanitizedRange.upper)
2058     {
2059       // negative is wider, do same as in case upper is 0
2060       if (-rangeFac > sanitizedRange.lower*rangeFac)
2061         sanitizedRange.upper = -rangeFac;
2062       else
2063         sanitizedRange.upper = sanitizedRange.lower*rangeFac;
2064     } else
2065     {
2066       // positive is wider, do same as in case lower is 0
2067       if (rangeFac < sanitizedRange.upper*rangeFac)
2068         sanitizedRange.lower = rangeFac;
2069       else
2070         sanitizedRange.lower = sanitizedRange.upper*rangeFac;
2071     }
2072   }
2073   // due to normalization, case lower>0 && upper<0 should never occur, because that implies upper<lower
2074   return sanitizedRange;
2075 }
2076 
2077 /*!
2078   Returns a sanitized version of the range. Sanitized means for linear scales, that
2079   \a lower will always be numerically smaller (or equal) to \a upper.
2080 */
sanitizedForLinScale() const2081 QCPRange QCPRange::sanitizedForLinScale() const
2082 {
2083   QCPRange sanitizedRange(lower, upper);
2084   sanitizedRange.normalize();
2085   return sanitizedRange;
2086 }
2087 
2088 /*!
2089   Checks, whether the specified range is within valid bounds, which are defined
2090   as QCPRange::maxRange and QCPRange::minRange.
2091   A valid range means:
2092   \li range bounds within -maxRange and maxRange
2093   \li range size above minRange
2094   \li range size below maxRange
2095 */
validRange(double lower,double upper)2096 bool QCPRange::validRange(double lower, double upper)
2097 {
2098   return (lower > -maxRange &&
2099           upper < maxRange &&
2100           qAbs(lower-upper) > minRange &&
2101           qAbs(lower-upper) < maxRange &&
2102           !(lower > 0 && qIsInf(upper/lower)) &&
2103           !(upper < 0 && qIsInf(lower/upper)));
2104 }
2105 
2106 /*!
2107   \overload
2108   Checks, whether the specified range is within valid bounds, which are defined
2109   as QCPRange::maxRange and QCPRange::minRange.
2110   A valid range means:
2111   \li range bounds within -maxRange and maxRange
2112   \li range size above minRange
2113   \li range size below maxRange
2114 */
validRange(const QCPRange & range)2115 bool QCPRange::validRange(const QCPRange &range)
2116 {
2117   return (range.lower > -maxRange &&
2118           range.upper < maxRange &&
2119           qAbs(range.lower-range.upper) > minRange &&
2120           qAbs(range.lower-range.upper) < maxRange &&
2121           !(range.lower > 0 && qIsInf(range.upper/range.lower)) &&
2122           !(range.upper < 0 && qIsInf(range.lower/range.upper)));
2123 }
2124 /* end of 'src/axis/range.cpp' */
2125 
2126 
2127 /* including file 'src/selection.cpp', size 21898                            */
2128 /* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
2129 
2130 ////////////////////////////////////////////////////////////////////////////////////////////////////
2131 //////////////////// QCPDataRange
2132 ////////////////////////////////////////////////////////////////////////////////////////////////////
2133 
2134 /*! \class QCPDataRange
2135   \brief Describes a data range given by begin and end index
2136 
2137   QCPDataRange holds two integers describing the begin (\ref setBegin) and end (\ref setEnd) index
2138   of a contiguous set of data points. The end index points to the data point above the last data point that's part of
2139   the data range, similarly to the nomenclature used in standard iterators.
2140 
2141   Data Ranges are not bound to a certain plottable, thus they can be freely exchanged, created and
2142   modified. If a non-contiguous data set shall be described, the class \ref QCPDataSelection is
2143   used, which holds and manages multiple instances of \ref QCPDataRange. In most situations, \ref
2144   QCPDataSelection is thus used.
2145 
2146   Both \ref QCPDataRange and \ref QCPDataSelection offer convenience methods to work with them,
2147   e.g. \ref bounded, \ref expanded, \ref intersects, \ref intersection, \ref adjusted, \ref
2148   contains. Further, addition and subtraction operators (defined in \ref QCPDataSelection) can be
2149   used to join/subtract data ranges and data selections (or mixtures), to retrieve a corresponding
2150   \ref QCPDataSelection.
2151 
2152   %QCustomPlot's \ref dataselection "data selection mechanism" is based on \ref QCPDataSelection and
2153   QCPDataRange.
2154 
2155   \note Do not confuse \ref QCPDataRange with \ref QCPRange. A \ref QCPRange describes an interval
2156   in floating point plot coordinates, e.g. the current axis range.
2157 */
2158 
2159 /* start documentation of inline functions */
2160 
2161 /*! \fn int QCPDataRange::size() const
2162 
2163   Returns the number of data points described by this data range. This is equal to the end index
2164   minus the begin index.
2165 
2166   \see length
2167 */
2168 
2169 /*! \fn int QCPDataRange::length() const
2170 
2171   Returns the number of data points described by this data range. Equivalent to \ref size.
2172 */
2173 
2174 /*! \fn void QCPDataRange::setBegin(int begin)
2175 
2176   Sets the begin of this data range. The \a begin index points to the first data point that is part
2177   of the data range.
2178 
2179   No checks or corrections are made to ensure the resulting range is valid (\ref isValid).
2180 
2181   \see setEnd
2182 */
2183 
2184 /*! \fn void QCPDataRange::setEnd(int end)
2185 
2186   Sets the end of this data range. The \a end index points to the data point just above the last
2187   data point that is part of the data range.
2188 
2189   No checks or corrections are made to ensure the resulting range is valid (\ref isValid).
2190 
2191   \see setBegin
2192 */
2193 
2194 /*! \fn bool QCPDataRange::isValid() const
2195 
2196   Returns whether this range is valid. A valid range has a begin index greater or equal to 0, and
2197   an end index greater or equal to the begin index.
2198 
2199   \note Invalid ranges should be avoided and are never the result of any of QCustomPlot's methods
2200   (unless they are themselves fed with invalid ranges). Do not pass invalid ranges to QCustomPlot's
2201   methods. The invalid range is not inherently prevented in QCPDataRange, to allow temporary
2202   invalid begin/end values while manipulating the range. An invalid range is not necessarily empty
2203   (\ref isEmpty), since its \ref length can be negative and thus non-zero.
2204 */
2205 
2206 /*! \fn bool QCPDataRange::isEmpty() const
2207 
2208   Returns whether this range is empty, i.e. whether its begin index equals its end index.
2209 
2210   \see size, length
2211 */
2212 
2213 /*! \fn QCPDataRange QCPDataRange::adjusted(int changeBegin, int changeEnd) const
2214 
2215   Returns a data range where \a changeBegin and \a changeEnd were added to the begin and end
2216   indices, respectively.
2217 */
2218 
2219 /* end documentation of inline functions */
2220 
2221 /*!
2222   Creates an empty QCPDataRange, with begin and end set to 0.
2223 */
QCPDataRange()2224 QCPDataRange::QCPDataRange() :
2225   mBegin(0),
2226   mEnd(0)
2227 {
2228 }
2229 
2230 /*!
2231   Creates a QCPDataRange, initialized with the specified \a begin and \a end.
2232 
2233   No checks or corrections are made to ensure the resulting range is valid (\ref isValid).
2234 */
QCPDataRange(int begin,int end)2235 QCPDataRange::QCPDataRange(int begin, int end) :
2236   mBegin(begin),
2237   mEnd(end)
2238 {
2239 }
2240 
2241 /*!
2242   Returns a data range that matches this data range, except that parts exceeding \a other are
2243   excluded.
2244 
2245   This method is very similar to \ref intersection, with one distinction: If this range and the \a
2246   other range share no intersection, the returned data range will be empty with begin and end set
2247   to the respective boundary side of \a other, at which this range is residing. (\ref intersection
2248   would just return a range with begin and end set to 0.)
2249 */
bounded(const QCPDataRange & other) const2250 QCPDataRange QCPDataRange::bounded(const QCPDataRange &other) const
2251 {
2252   QCPDataRange result(intersection(other));
2253   if (result.isEmpty()) // no intersection, preserve respective bounding side of otherRange as both begin and end of return value
2254   {
2255     if (mEnd <= other.mBegin)
2256       result = QCPDataRange(other.mBegin, other.mBegin);
2257     else
2258       result = QCPDataRange(other.mEnd, other.mEnd);
2259   }
2260   return result;
2261 }
2262 
2263 /*!
2264   Returns a data range that contains both this data range as well as \a other.
2265 */
expanded(const QCPDataRange & other) const2266 QCPDataRange QCPDataRange::expanded(const QCPDataRange &other) const
2267 {
2268   return QCPDataRange(qMin(mBegin, other.mBegin), qMax(mEnd, other.mEnd));
2269 }
2270 
2271 /*!
2272   Returns the data range which is contained in both this data range and \a other.
2273 
2274   This method is very similar to \ref bounded, with one distinction: If this range and the \a other
2275   range share no intersection, the returned data range will be empty with begin and end set to 0.
2276   (\ref bounded would return a range with begin and end set to one of the boundaries of \a other,
2277   depending on which side this range is on.)
2278 
2279   \see QCPDataSelection::intersection
2280 */
intersection(const QCPDataRange & other) const2281 QCPDataRange QCPDataRange::intersection(const QCPDataRange &other) const
2282 {
2283   QCPDataRange result(qMax(mBegin, other.mBegin), qMin(mEnd, other.mEnd));
2284   if (result.isValid())
2285     return result;
2286   else
2287     return QCPDataRange();
2288 }
2289 
2290 /*!
2291   Returns whether this data range and \a other share common data points.
2292 
2293   \see intersection, contains
2294 */
intersects(const QCPDataRange & other) const2295 bool QCPDataRange::intersects(const QCPDataRange &other) const
2296 {
2297    return !( (mBegin > other.mBegin && mBegin >= other.mEnd) ||
2298              (mEnd <= other.mBegin && mEnd < other.mEnd) );
2299 }
2300 
2301 /*!
2302   Returns whether all data points described by this data range are also in \a other.
2303 
2304   \see intersects
2305 */
contains(const QCPDataRange & other) const2306 bool QCPDataRange::contains(const QCPDataRange &other) const
2307 {
2308   return mBegin <= other.mBegin && mEnd >= other.mEnd;
2309 }
2310 
2311 
2312 
2313 ////////////////////////////////////////////////////////////////////////////////////////////////////
2314 //////////////////// QCPDataSelection
2315 ////////////////////////////////////////////////////////////////////////////////////////////////////
2316 
2317 /*! \class QCPDataSelection
2318   \brief Describes a data set by holding multiple QCPDataRange instances
2319 
2320   QCPDataSelection manages multiple instances of QCPDataRange in order to represent any (possibly
2321   disjoint) set of data selection.
2322 
2323   The data selection can be modified with addition and subtraction operators which take
2324   QCPDataSelection and QCPDataRange instances, as well as methods such as \ref addDataRange and
2325   \ref clear. Read access is provided by \ref dataRange, \ref dataRanges, \ref dataRangeCount, etc.
2326 
2327   The method \ref simplify is used to join directly adjacent or even overlapping QCPDataRange
2328   instances. QCPDataSelection automatically simplifies when using the addition/subtraction
2329   operators. The only case when \ref simplify is left to the user, is when calling \ref
2330   addDataRange, with the parameter \a simplify explicitly set to false. This is useful if many data
2331   ranges will be added to the selection successively and the overhead for simplifying after each
2332   iteration shall be avoided. In this case, you should make sure to call \ref simplify after
2333   completing the operation.
2334 
2335   Use \ref enforceType to bring the data selection into a state complying with the constraints for
2336   selections defined in \ref QCP::SelectionType.
2337 
2338   %QCustomPlot's \ref dataselection "data selection mechanism" is based on QCPDataSelection and
2339   QCPDataRange.
2340 
2341   \section qcpdataselection-iterating Iterating over a data selection
2342 
2343   As an example, the following code snippet calculates the average value of a graph's data
2344   \ref QCPAbstractPlottable::selection "selection":
2345 
2346   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpdataselection-iterating-1
2347 
2348 */
2349 
2350 /* start documentation of inline functions */
2351 
2352 /*! \fn int QCPDataSelection::dataRangeCount() const
2353 
2354   Returns the number of ranges that make up the data selection. The ranges can be accessed by \ref
2355   dataRange via their index.
2356 
2357   \see dataRange, dataPointCount
2358 */
2359 
2360 /*! \fn QList<QCPDataRange> QCPDataSelection::dataRanges() const
2361 
2362   Returns all data ranges that make up the data selection. If the data selection is simplified (the
2363   usual state of the selection, see \ref simplify), the ranges are sorted by ascending data point
2364   index.
2365 
2366   \see dataRange
2367 */
2368 
2369 /*! \fn bool QCPDataSelection::isEmpty() const
2370 
2371   Returns true if there are no data ranges, and thus no data points, in this QCPDataSelection
2372   instance.
2373 
2374   \see dataRangeCount
2375 */
2376 
2377 /* end documentation of inline functions */
2378 
2379 /*!
2380   Creates an empty QCPDataSelection.
2381 */
QCPDataSelection()2382 QCPDataSelection::QCPDataSelection()
2383 {
2384 }
2385 
2386 /*!
2387   Creates a QCPDataSelection containing the provided \a range.
2388 */
QCPDataSelection(const QCPDataRange & range)2389 QCPDataSelection::QCPDataSelection(const QCPDataRange &range)
2390 {
2391   mDataRanges.append(range);
2392 }
2393 
2394 /*!
2395   Returns true if this selection is identical (contains the same data ranges with the same begin
2396   and end indices) to \a other.
2397 
2398   Note that both data selections must be in simplified state (the usual state of the selection, see
2399   \ref simplify) for this operator to return correct results.
2400 */
operator ==(const QCPDataSelection & other) const2401 bool QCPDataSelection::operator==(const QCPDataSelection &other) const
2402 {
2403   if (mDataRanges.size() != other.mDataRanges.size())
2404     return false;
2405   for (int i=0; i<mDataRanges.size(); ++i)
2406   {
2407     if (mDataRanges.at(i) != other.mDataRanges.at(i))
2408       return false;
2409   }
2410   return true;
2411 }
2412 
2413 /*!
2414   Adds the data selection of \a other to this data selection, and then simplifies this data
2415   selection (see \ref simplify).
2416 */
operator +=(const QCPDataSelection & other)2417 QCPDataSelection &QCPDataSelection::operator+=(const QCPDataSelection &other)
2418 {
2419   mDataRanges << other.mDataRanges;
2420   simplify();
2421   return *this;
2422 }
2423 
2424 /*!
2425   Adds the data range \a other to this data selection, and then simplifies this data selection (see
2426   \ref simplify).
2427 */
operator +=(const QCPDataRange & other)2428 QCPDataSelection &QCPDataSelection::operator+=(const QCPDataRange &other)
2429 {
2430   addDataRange(other);
2431   return *this;
2432 }
2433 
2434 /*!
2435   Removes all data point indices that are described by \a other from this data range.
2436 */
operator -=(const QCPDataSelection & other)2437 QCPDataSelection &QCPDataSelection::operator-=(const QCPDataSelection &other)
2438 {
2439   for (int i=0; i<other.dataRangeCount(); ++i)
2440     *this -= other.dataRange(i);
2441 
2442   return *this;
2443 }
2444 
2445 /*!
2446   Removes all data point indices that are described by \a other from this data range.
2447 */
operator -=(const QCPDataRange & other)2448 QCPDataSelection &QCPDataSelection::operator-=(const QCPDataRange &other)
2449 {
2450   if (other.isEmpty() || isEmpty())
2451     return *this;
2452 
2453   simplify();
2454   int i=0;
2455   while (i < mDataRanges.size())
2456   {
2457     const int thisBegin = mDataRanges.at(i).begin();
2458     const int thisEnd = mDataRanges.at(i).end();
2459     if (thisBegin >= other.end())
2460       break; // since data ranges are sorted after the simplify() call, no ranges which contain other will come after this
2461 
2462     if (thisEnd > other.begin()) // ranges which don't fulfill this are entirely before other and can be ignored
2463     {
2464       if (thisBegin >= other.begin()) // range leading segment is encompassed
2465       {
2466         if (thisEnd <= other.end()) // range fully encompassed, remove completely
2467         {
2468           mDataRanges.removeAt(i);
2469           continue;
2470         } else // only leading segment is encompassed, trim accordingly
2471           mDataRanges[i].setBegin(other.end());
2472       } else // leading segment is not encompassed
2473       {
2474         if (thisEnd <= other.end()) // only trailing segment is encompassed, trim accordingly
2475         {
2476           mDataRanges[i].setEnd(other.begin());
2477         } else // other lies inside this range, so split range
2478         {
2479           mDataRanges[i].setEnd(other.begin());
2480           mDataRanges.insert(i+1, QCPDataRange(other.end(), thisEnd));
2481           break; // since data ranges are sorted (and don't overlap) after simplify() call, we're done here
2482         }
2483       }
2484     }
2485     ++i;
2486   }
2487 
2488   return *this;
2489 }
2490 
2491 /*!
2492   Returns the total number of data points contained in all data ranges that make up this data
2493   selection.
2494 */
dataPointCount() const2495 int QCPDataSelection::dataPointCount() const
2496 {
2497   int result = 0;
2498   for (int i=0; i<mDataRanges.size(); ++i)
2499     result += mDataRanges.at(i).length();
2500   return result;
2501 }
2502 
2503 /*!
2504   Returns the data range with the specified \a index.
2505 
2506   If the data selection is simplified (the usual state of the selection, see \ref simplify), the
2507   ranges are sorted by ascending data point index.
2508 
2509   \see dataRangeCount
2510 */
dataRange(int index) const2511 QCPDataRange QCPDataSelection::dataRange(int index) const
2512 {
2513   if (index >= 0 && index < mDataRanges.size())
2514   {
2515     return mDataRanges.at(index);
2516   } else
2517   {
2518     qDebug() << Q_FUNC_INFO << "index out of range:" << index;
2519     return QCPDataRange();
2520   }
2521 }
2522 
2523 /*!
2524   Returns a \ref QCPDataRange which spans the entire data selection, including possible
2525   intermediate segments which are not part of the original data selection.
2526 */
span() const2527 QCPDataRange QCPDataSelection::span() const
2528 {
2529   if (isEmpty())
2530     return QCPDataRange();
2531   else
2532     return QCPDataRange(mDataRanges.first().begin(), mDataRanges.last().end());
2533 }
2534 
2535 /*!
2536   Adds the given \a dataRange to this data selection. This is equivalent to the += operator but
2537   allows disabling immediate simplification by setting \a simplify to false. This can improve
2538   performance if adding a very large amount of data ranges successively. In this case, make sure to
2539   call \ref simplify manually, after the operation.
2540 */
addDataRange(const QCPDataRange & dataRange,bool simplify)2541 void QCPDataSelection::addDataRange(const QCPDataRange &dataRange, bool simplify)
2542 {
2543   mDataRanges.append(dataRange);
2544   if (simplify)
2545     this->simplify();
2546 }
2547 
2548 /*!
2549   Removes all data ranges. The data selection then contains no data points.
2550 
2551   \ref isEmpty
2552 */
clear()2553 void QCPDataSelection::clear()
2554 {
2555   mDataRanges.clear();
2556 }
2557 
2558 /*!
2559   Sorts all data ranges by range begin index in ascending order, and then joins directly adjacent
2560   or overlapping ranges. This can reduce the number of individual data ranges in the selection, and
2561   prevents possible double-counting when iterating over the data points held by the data ranges.
2562 
2563   This method is automatically called when using the addition/subtraction operators. The only case
2564   when \ref simplify is left to the user, is when calling \ref addDataRange, with the parameter \a
2565   simplify explicitly set to false.
2566 */
simplify()2567 void QCPDataSelection::simplify()
2568 {
2569   // remove any empty ranges:
2570   for (int i=mDataRanges.size()-1; i>=0; --i)
2571   {
2572     if (mDataRanges.at(i).isEmpty())
2573       mDataRanges.removeAt(i);
2574   }
2575   if (mDataRanges.isEmpty())
2576     return;
2577 
2578   // sort ranges by starting value, ascending:
2579   std::sort(mDataRanges.begin(), mDataRanges.end(), lessThanDataRangeBegin);
2580 
2581   // join overlapping/contiguous ranges:
2582   int i = 1;
2583   while (i < mDataRanges.size())
2584   {
2585     if (mDataRanges.at(i-1).end() >= mDataRanges.at(i).begin()) // range i overlaps/joins with i-1, so expand range i-1 appropriately and remove range i from list
2586     {
2587       mDataRanges[i-1].setEnd(qMax(mDataRanges.at(i-1).end(), mDataRanges.at(i).end()));
2588       mDataRanges.removeAt(i);
2589     } else
2590       ++i;
2591   }
2592 }
2593 
2594 /*!
2595   Makes sure this data selection conforms to the specified \a type selection type. Before the type
2596   is enforced, \ref simplify is called.
2597 
2598   Depending on \a type, enforcing means adding new data points that were previously not part of the
2599   selection, or removing data points from the selection. If the current selection already conforms
2600   to \a type, the data selection is not changed.
2601 
2602   \see QCP::SelectionType
2603 */
enforceType(QCP::SelectionType type)2604 void QCPDataSelection::enforceType(QCP::SelectionType type)
2605 {
2606   simplify();
2607   switch (type)
2608   {
2609     case QCP::stNone:
2610     {
2611       mDataRanges.clear();
2612       break;
2613     }
2614     case QCP::stWhole:
2615     {
2616       // whole selection isn't defined by data range, so don't change anything (is handled in plottable methods)
2617       break;
2618     }
2619     case QCP::stSingleData:
2620     {
2621       // reduce all data ranges to the single first data point:
2622       if (!mDataRanges.isEmpty())
2623       {
2624         if (mDataRanges.size() > 1)
2625           mDataRanges = QList<QCPDataRange>() << mDataRanges.first();
2626         if (mDataRanges.first().length() > 1)
2627           mDataRanges.first().setEnd(mDataRanges.first().begin()+1);
2628       }
2629       break;
2630     }
2631     case QCP::stDataRange:
2632     {
2633       mDataRanges = QList<QCPDataRange>() << span();
2634       break;
2635     }
2636     case QCP::stMultipleDataRanges:
2637     {
2638       // this is the selection type that allows all concievable combinations of ranges, so do nothing
2639       break;
2640     }
2641   }
2642 }
2643 
2644 /*!
2645   Returns true if the data selection \a other is contained entirely in this data selection, i.e.
2646   all data point indices that are in \a other are also in this data selection.
2647 
2648   \see QCPDataRange::contains
2649 */
contains(const QCPDataSelection & other) const2650 bool QCPDataSelection::contains(const QCPDataSelection &other) const
2651 {
2652   if (other.isEmpty()) return false;
2653 
2654   int otherIndex = 0;
2655   int thisIndex = 0;
2656   while (thisIndex < mDataRanges.size() && otherIndex < other.mDataRanges.size())
2657   {
2658     if (mDataRanges.at(thisIndex).contains(other.mDataRanges.at(otherIndex)))
2659       ++otherIndex;
2660     else
2661       ++thisIndex;
2662   }
2663   return thisIndex < mDataRanges.size(); // if thisIndex ran all the way to the end to find a containing range for the current otherIndex, other is not contained in this
2664 }
2665 
2666 /*!
2667   Returns a data selection containing the points which are both in this data selection and in the
2668   data range \a other.
2669 
2670   A common use case is to limit an unknown data selection to the valid range of a data container,
2671   using \ref QCPDataContainer::dataRange as \a other. One can then safely iterate over the returned
2672   data selection without exceeding the data container's bounds.
2673 */
intersection(const QCPDataRange & other) const2674 QCPDataSelection QCPDataSelection::intersection(const QCPDataRange &other) const
2675 {
2676   QCPDataSelection result;
2677   for (int i=0; i<mDataRanges.size(); ++i)
2678     result.addDataRange(mDataRanges.at(i).intersection(other), false);
2679   result.simplify();
2680   return result;
2681 }
2682 
2683 /*!
2684   Returns a data selection containing the points which are both in this data selection and in the
2685   data selection \a other.
2686 */
intersection(const QCPDataSelection & other) const2687 QCPDataSelection QCPDataSelection::intersection(const QCPDataSelection &other) const
2688 {
2689   QCPDataSelection result;
2690   for (int i=0; i<other.dataRangeCount(); ++i)
2691     result += intersection(other.dataRange(i));
2692   result.simplify();
2693   return result;
2694 }
2695 
2696 /*!
2697   Returns a data selection which is the exact inverse of this data selection, with \a outerRange
2698   defining the base range on which to invert. If \a outerRange is smaller than the \ref span of
2699   this data selection, it is expanded accordingly.
2700 
2701   For example, this method can be used to retrieve all unselected segments by setting \a outerRange
2702   to the full data range of the plottable, and calling this method on a data selection holding the
2703   selected segments.
2704 */
inverse(const QCPDataRange & outerRange) const2705 QCPDataSelection QCPDataSelection::inverse(const QCPDataRange &outerRange) const
2706 {
2707   if (isEmpty())
2708     return QCPDataSelection(outerRange);
2709   QCPDataRange fullRange = outerRange.expanded(span());
2710 
2711   QCPDataSelection result;
2712   // first unselected segment:
2713   if (mDataRanges.first().begin() != fullRange.begin())
2714     result.addDataRange(QCPDataRange(fullRange.begin(), mDataRanges.first().begin()), false);
2715   // intermediate unselected segments:
2716   for (int i=1; i<mDataRanges.size(); ++i)
2717     result.addDataRange(QCPDataRange(mDataRanges.at(i-1).end(), mDataRanges.at(i).begin()), false);
2718   // last unselected segment:
2719   if (mDataRanges.last().end() != fullRange.end())
2720     result.addDataRange(QCPDataRange(mDataRanges.last().end(), fullRange.end()), false);
2721   result.simplify();
2722   return result;
2723 }
2724 /* end of 'src/selection.cpp' */
2725 
2726 
2727 /* including file 'src/selectionrect.cpp', size 9224                         */
2728 /* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
2729 
2730 ////////////////////////////////////////////////////////////////////////////////////////////////////
2731 //////////////////// QCPSelectionRect
2732 ////////////////////////////////////////////////////////////////////////////////////////////////////
2733 
2734 /*! \class QCPSelectionRect
2735   \brief Provides rect/rubber-band data selection and range zoom interaction
2736 
2737   QCPSelectionRect is used by QCustomPlot when the \ref QCustomPlot::setSelectionRectMode is not
2738   \ref QCP::srmNone. When the user drags the mouse across the plot, the current selection rect
2739   instance (\ref QCustomPlot::setSelectionRect) is forwarded these events and makes sure an
2740   according rect shape is drawn. At the begin, during, and after completion of the interaction, it
2741   emits the corresponding signals \ref started, \ref changed, \ref canceled, and \ref accepted.
2742 
2743   The QCustomPlot instance connects own slots to the current selection rect instance, in order to
2744   react to an accepted selection rect interaction accordingly.
2745 
2746   \ref isActive can be used to check whether the selection rect is currently active. An ongoing
2747   selection interaction can be cancelled programmatically via calling \ref cancel at any time.
2748 
2749   The appearance of the selection rect can be controlled via \ref setPen and \ref setBrush.
2750 
2751   If you wish to provide custom behaviour, e.g. a different visual representation of the selection
2752   rect (\ref QCPSelectionRect::draw), you can subclass QCPSelectionRect and pass an instance of
2753   your subclass to \ref QCustomPlot::setSelectionRect.
2754 */
2755 
2756 /* start of documentation of inline functions */
2757 
2758 /*! \fn bool QCPSelectionRect::isActive() const
2759 
2760   Returns true if there is currently a selection going on, i.e. the user has started dragging a
2761   selection rect, but hasn't released the mouse button yet.
2762 
2763   \see cancel
2764 */
2765 
2766 /* end of documentation of inline functions */
2767 /* start documentation of signals */
2768 
2769 /*! \fn void QCPSelectionRect::started(QMouseEvent *event);
2770 
2771   This signal is emitted when a selection rect interaction was initiated, i.e. the user just
2772   started dragging the selection rect with the mouse.
2773 */
2774 
2775 /*! \fn void QCPSelectionRect::changed(const QRect &rect, QMouseEvent *event);
2776 
2777   This signal is emitted while the selection rect interaction is ongoing and the \a rect has
2778   changed its size due to the user moving the mouse.
2779 
2780   Note that \a rect may have a negative width or height, if the selection is being dragged to the
2781   upper or left side of the selection rect origin.
2782 */
2783 
2784 /*! \fn void QCPSelectionRect::canceled(const QRect &rect, QInputEvent *event);
2785 
2786   This signal is emitted when the selection interaction was cancelled. Note that \a event is 0 if
2787   the selection interaction was cancelled programmatically, by a call to \ref cancel.
2788 
2789   The user may cancel the selection interaction by pressing the escape key. In this case, \a event
2790   holds the respective input event.
2791 
2792   Note that \a rect may have a negative width or height, if the selection is being dragged to the
2793   upper or left side of the selection rect origin.
2794 */
2795 
2796 /*! \fn void QCPSelectionRect::accepted(const QRect &rect, QMouseEvent *event);
2797 
2798   This signal is emitted when the selection interaction was completed by the user releasing the
2799   mouse button.
2800 
2801   Note that \a rect may have a negative width or height, if the selection is being dragged to the
2802   upper or left side of the selection rect origin.
2803 */
2804 
2805 /* end documentation of signals */
2806 
2807 /*!
2808   Creates a new QCPSelectionRect instance. To make QCustomPlot use the selection rect instance,
2809   pass it to \ref QCustomPlot::setSelectionRect. \a parentPlot should be set to the same
2810   QCustomPlot widget.
2811 */
QCPSelectionRect(QCustomPlot * parentPlot)2812 QCPSelectionRect::QCPSelectionRect(QCustomPlot *parentPlot) :
2813   QCPLayerable(parentPlot),
2814   mPen(QBrush(Qt::gray), 0, Qt::DashLine),
2815   mBrush(Qt::NoBrush),
2816   mActive(false)
2817 {
2818 }
2819 
~QCPSelectionRect()2820 QCPSelectionRect::~QCPSelectionRect()
2821 {
2822   cancel();
2823 }
2824 
2825 /*!
2826   A convenience function which returns the coordinate range of the provided \a axis, that this
2827   selection rect currently encompasses.
2828 */
range(const QCPAxis * axis) const2829 QCPRange QCPSelectionRect::range(const QCPAxis *axis) const
2830 {
2831   if (axis)
2832   {
2833     if (axis->orientation() == Qt::Horizontal)
2834       return QCPRange(axis->pixelToCoord(mRect.left()), axis->pixelToCoord(mRect.left()+mRect.width()));
2835     else
2836       return QCPRange(axis->pixelToCoord(mRect.top()+mRect.height()), axis->pixelToCoord(mRect.top()));
2837   } else
2838   {
2839     qDebug() << Q_FUNC_INFO << "called with axis zero";
2840     return QCPRange();
2841   }
2842 }
2843 
2844 /*!
2845   Sets the pen that will be used to draw the selection rect outline.
2846 
2847   \see setBrush
2848 */
setPen(const QPen & pen)2849 void QCPSelectionRect::setPen(const QPen &pen)
2850 {
2851   mPen = pen;
2852 }
2853 
2854 /*!
2855   Sets the brush that will be used to fill the selection rect. By default the selection rect is not
2856   filled, i.e. \a brush is <tt>Qt::NoBrush</tt>.
2857 
2858   \see setPen
2859 */
setBrush(const QBrush & brush)2860 void QCPSelectionRect::setBrush(const QBrush &brush)
2861 {
2862   mBrush = brush;
2863 }
2864 
2865 /*!
2866   If there is currently a selection interaction going on (\ref isActive), the interaction is
2867   canceled. The selection rect will emit the \ref canceled signal.
2868 */
cancel()2869 void QCPSelectionRect::cancel()
2870 {
2871   if (mActive)
2872   {
2873     mActive = false;
2874     emit canceled(mRect, 0);
2875   }
2876 }
2877 
2878 /*! \internal
2879 
2880   This method is called by QCustomPlot to indicate that a selection rect interaction was initiated.
2881   The default implementation sets the selection rect to active, initializes the selection rect
2882   geometry and emits the \ref started signal.
2883 */
startSelection(QMouseEvent * event)2884 void QCPSelectionRect::startSelection(QMouseEvent *event)
2885 {
2886   mActive = true;
2887   mRect = QRect(event->pos(), event->pos());
2888   emit started(event);
2889 }
2890 
2891 /*! \internal
2892 
2893   This method is called by QCustomPlot to indicate that an ongoing selection rect interaction needs
2894   to update its geometry. The default implementation updates the rect and emits the \ref changed
2895   signal.
2896 */
moveSelection(QMouseEvent * event)2897 void QCPSelectionRect::moveSelection(QMouseEvent *event)
2898 {
2899   mRect.setBottomRight(event->pos());
2900   emit changed(mRect, event);
2901   layer()->replot();
2902 }
2903 
2904 /*! \internal
2905 
2906   This method is called by QCustomPlot to indicate that an ongoing selection rect interaction has
2907   finished by the user releasing the mouse button. The default implementation deactivates the
2908   selection rect and emits the \ref accepted signal.
2909 */
endSelection(QMouseEvent * event)2910 void QCPSelectionRect::endSelection(QMouseEvent *event)
2911 {
2912   mRect.setBottomRight(event->pos());
2913   mActive = false;
2914   emit accepted(mRect, event);
2915 }
2916 
2917 /*! \internal
2918 
2919   This method is called by QCustomPlot when a key has been pressed by the user while the selection
2920   rect interaction is active. The default implementation allows to \ref cancel the interaction by
2921   hitting the escape key.
2922 */
keyPressEvent(QKeyEvent * event)2923 void QCPSelectionRect::keyPressEvent(QKeyEvent *event)
2924 {
2925   if (event->key() == Qt::Key_Escape && mActive)
2926   {
2927     mActive = false;
2928     emit canceled(mRect, event);
2929   }
2930 }
2931 
2932 /* inherits documentation from base class */
applyDefaultAntialiasingHint(QCPPainter * painter) const2933 void QCPSelectionRect::applyDefaultAntialiasingHint(QCPPainter *painter) const
2934 {
2935   applyAntialiasingHint(painter, mAntialiased, QCP::aeOther);
2936 }
2937 
2938 /*! \internal
2939 
2940   If the selection rect is active (\ref isActive), draws the selection rect defined by \a mRect.
2941 
2942   \seebaseclassmethod
2943 */
draw(QCPPainter * painter)2944 void QCPSelectionRect::draw(QCPPainter *painter)
2945 {
2946   if (mActive)
2947   {
2948     painter->setPen(mPen);
2949     painter->setBrush(mBrush);
2950     painter->drawRect(mRect);
2951   }
2952 }
2953 /* end of 'src/selectionrect.cpp' */
2954 
2955 
2956 /* including file 'src/layout.cpp', size 74302                               */
2957 /* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
2958 
2959 ////////////////////////////////////////////////////////////////////////////////////////////////////
2960 //////////////////// QCPMarginGroup
2961 ////////////////////////////////////////////////////////////////////////////////////////////////////
2962 
2963 /*! \class QCPMarginGroup
2964   \brief A margin group allows synchronization of margin sides if working with multiple layout elements.
2965 
2966   QCPMarginGroup allows you to tie a margin side of two or more layout elements together, such that
2967   they will all have the same size, based on the largest required margin in the group.
2968 
2969   \n
2970   \image html QCPMarginGroup.png "Demonstration of QCPMarginGroup"
2971   \n
2972 
2973   In certain situations it is desirable that margins at specific sides are synchronized across
2974   layout elements. For example, if one QCPAxisRect is below another one in a grid layout, it will
2975   provide a cleaner look to the user if the left and right margins of the two axis rects are of the
2976   same size. The left axis of the top axis rect will then be at the same horizontal position as the
2977   left axis of the lower axis rect, making them appear aligned. The same applies for the right
2978   axes. This is what QCPMarginGroup makes possible.
2979 
2980   To add/remove a specific side of a layout element to/from a margin group, use the \ref
2981   QCPLayoutElement::setMarginGroup method. To completely break apart the margin group, either call
2982   \ref clear, or just delete the margin group.
2983 
2984   \section QCPMarginGroup-example Example
2985 
2986   First create a margin group:
2987   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpmargingroup-creation-1
2988   Then set this group on the layout element sides:
2989   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpmargingroup-creation-2
2990   Here, we've used the first two axis rects of the plot and synchronized their left margins with
2991   each other and their right margins with each other.
2992 */
2993 
2994 /* start documentation of inline functions */
2995 
2996 /*! \fn QList<QCPLayoutElement*> QCPMarginGroup::elements(QCP::MarginSide side) const
2997 
2998   Returns a list of all layout elements that have their margin \a side associated with this margin
2999   group.
3000 */
3001 
3002 /* end documentation of inline functions */
3003 
3004 /*!
3005   Creates a new QCPMarginGroup instance in \a parentPlot.
3006 */
QCPMarginGroup(QCustomPlot * parentPlot)3007 QCPMarginGroup::QCPMarginGroup(QCustomPlot *parentPlot) :
3008   QObject(parentPlot),
3009   mParentPlot(parentPlot)
3010 {
3011   mChildren.insert(QCP::msLeft, QList<QCPLayoutElement*>());
3012   mChildren.insert(QCP::msRight, QList<QCPLayoutElement*>());
3013   mChildren.insert(QCP::msTop, QList<QCPLayoutElement*>());
3014   mChildren.insert(QCP::msBottom, QList<QCPLayoutElement*>());
3015 }
3016 
~QCPMarginGroup()3017 QCPMarginGroup::~QCPMarginGroup()
3018 {
3019   clear();
3020 }
3021 
3022 /*!
3023   Returns whether this margin group is empty. If this function returns true, no layout elements use
3024   this margin group to synchronize margin sides.
3025 */
isEmpty() const3026 bool QCPMarginGroup::isEmpty() const
3027 {
3028   QHashIterator<QCP::MarginSide, QList<QCPLayoutElement*> > it(mChildren);
3029   while (it.hasNext())
3030   {
3031     it.next();
3032     if (!it.value().isEmpty())
3033       return false;
3034   }
3035   return true;
3036 }
3037 
3038 /*!
3039   Clears this margin group. The synchronization of the margin sides that use this margin group is
3040   lifted and they will use their individual margin sizes again.
3041 */
clear()3042 void QCPMarginGroup::clear()
3043 {
3044   // make all children remove themselves from this margin group:
3045   QHashIterator<QCP::MarginSide, QList<QCPLayoutElement*> > it(mChildren);
3046   while (it.hasNext())
3047   {
3048     it.next();
3049     const QList<QCPLayoutElement*> elements = it.value();
3050     for (int i=elements.size()-1; i>=0; --i)
3051       elements.at(i)->setMarginGroup(it.key(), 0); // removes itself from mChildren via removeChild
3052   }
3053 }
3054 
3055 /*! \internal
3056 
3057   Returns the synchronized common margin for \a side. This is the margin value that will be used by
3058   the layout element on the respective side, if it is part of this margin group.
3059 
3060   The common margin is calculated by requesting the automatic margin (\ref
3061   QCPLayoutElement::calculateAutoMargin) of each element associated with \a side in this margin
3062   group, and choosing the largest returned value. (QCPLayoutElement::minimumMargins is taken into
3063   account, too.)
3064 */
commonMargin(QCP::MarginSide side) const3065 int QCPMarginGroup::commonMargin(QCP::MarginSide side) const
3066 {
3067   // query all automatic margins of the layout elements in this margin group side and find maximum:
3068   int result = 0;
3069   const QList<QCPLayoutElement*> elements = mChildren.value(side);
3070   for (int i=0; i<elements.size(); ++i)
3071   {
3072     if (!elements.at(i)->autoMargins().testFlag(side))
3073       continue;
3074     int m = qMax(elements.at(i)->calculateAutoMargin(side), QCP::getMarginValue(elements.at(i)->minimumMargins(), side));
3075     if (m > result)
3076       result = m;
3077   }
3078   return result;
3079 }
3080 
3081 /*! \internal
3082 
3083   Adds \a element to the internal list of child elements, for the margin \a side.
3084 
3085   This function does not modify the margin group property of \a element.
3086 */
addChild(QCP::MarginSide side,QCPLayoutElement * element)3087 void QCPMarginGroup::addChild(QCP::MarginSide side, QCPLayoutElement *element)
3088 {
3089   if (!mChildren[side].contains(element))
3090     mChildren[side].append(element);
3091   else
3092     qDebug() << Q_FUNC_INFO << "element is already child of this margin group side" << reinterpret_cast<quintptr>(element);
3093 }
3094 
3095 /*! \internal
3096 
3097   Removes \a element from the internal list of child elements, for the margin \a side.
3098 
3099   This function does not modify the margin group property of \a element.
3100 */
removeChild(QCP::MarginSide side,QCPLayoutElement * element)3101 void QCPMarginGroup::removeChild(QCP::MarginSide side, QCPLayoutElement *element)
3102 {
3103   if (!mChildren[side].removeOne(element))
3104     qDebug() << Q_FUNC_INFO << "element is not child of this margin group side" << reinterpret_cast<quintptr>(element);
3105 }
3106 
3107 
3108 ////////////////////////////////////////////////////////////////////////////////////////////////////
3109 //////////////////// QCPLayoutElement
3110 ////////////////////////////////////////////////////////////////////////////////////////////////////
3111 
3112 /*! \class QCPLayoutElement
3113   \brief The abstract base class for all objects that form \ref thelayoutsystem "the layout system".
3114 
3115   This is an abstract base class. As such, it can't be instantiated directly, rather use one of its subclasses.
3116 
3117   A Layout element is a rectangular object which can be placed in layouts. It has an outer rect
3118   (QCPLayoutElement::outerRect) and an inner rect (\ref QCPLayoutElement::rect). The difference
3119   between outer and inner rect is called its margin. The margin can either be set to automatic or
3120   manual (\ref setAutoMargins) on a per-side basis. If a side is set to manual, that margin can be
3121   set explicitly with \ref setMargins and will stay fixed at that value. If it's set to automatic,
3122   the layout element subclass will control the value itself (via \ref calculateAutoMargin).
3123 
3124   Layout elements can be placed in layouts (base class QCPLayout) like QCPLayoutGrid. The top level
3125   layout is reachable via \ref QCustomPlot::plotLayout, and is a \ref QCPLayoutGrid. Since \ref
3126   QCPLayout itself derives from \ref QCPLayoutElement, layouts can be nested.
3127 
3128   Thus in QCustomPlot one can divide layout elements into two categories: The ones that are
3129   invisible by themselves, because they don't draw anything. Their only purpose is to manage the
3130   position and size of other layout elements. This category of layout elements usually use
3131   QCPLayout as base class. Then there is the category of layout elements which actually draw
3132   something. For example, QCPAxisRect, QCPLegend and QCPTextElement are of this category. This does
3133   not necessarily mean that the latter category can't have child layout elements. QCPLegend for
3134   instance, actually derives from QCPLayoutGrid and the individual legend items are child layout
3135   elements in the grid layout.
3136 */
3137 
3138 /* start documentation of inline functions */
3139 
3140 /*! \fn QCPLayout *QCPLayoutElement::layout() const
3141 
3142   Returns the parent layout of this layout element.
3143 */
3144 
3145 /*! \fn QRect QCPLayoutElement::rect() const
3146 
3147   Returns the inner rect of this layout element. The inner rect is the outer rect (\ref
3148   setOuterRect) shrinked by the margins (\ref setMargins, \ref setAutoMargins).
3149 
3150   In some cases, the area between outer and inner rect is left blank. In other cases the margin
3151   area is used to display peripheral graphics while the main content is in the inner rect. This is
3152   where automatic margin calculation becomes interesting because it allows the layout element to
3153   adapt the margins to the peripheral graphics it wants to draw. For example, \ref QCPAxisRect
3154   draws the axis labels and tick labels in the margin area, thus needs to adjust the margins (if
3155   \ref setAutoMargins is enabled) according to the space required by the labels of the axes.
3156 */
3157 
3158 /* end documentation of inline functions */
3159 
3160 /*!
3161   Creates an instance of QCPLayoutElement and sets default values.
3162 */
QCPLayoutElement(QCustomPlot * parentPlot)3163 QCPLayoutElement::QCPLayoutElement(QCustomPlot *parentPlot) :
3164   QCPLayerable(parentPlot), // parenthood is changed as soon as layout element gets inserted into a layout (except for top level layout)
3165   mParentLayout(0),
3166   mMinimumSize(),
3167   mMaximumSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX),
3168   mRect(0, 0, 0, 0),
3169   mOuterRect(0, 0, 0, 0),
3170   mMargins(0, 0, 0, 0),
3171   mMinimumMargins(0, 0, 0, 0),
3172   mAutoMargins(QCP::msAll)
3173 {
3174 }
3175 
~QCPLayoutElement()3176 QCPLayoutElement::~QCPLayoutElement()
3177 {
3178   setMarginGroup(QCP::msAll, 0); // unregister at margin groups, if there are any
3179   // unregister at layout:
3180   if (qobject_cast<QCPLayout*>(mParentLayout)) // the qobject_cast is just a safeguard in case the layout forgets to call clear() in its dtor and this dtor is called by QObject dtor
3181     mParentLayout->take(this);
3182 }
3183 
3184 /*!
3185   Sets the outer rect of this layout element. If the layout element is inside a layout, the layout
3186   sets the position and size of this layout element using this function.
3187 
3188   Calling this function externally has no effect, since the layout will overwrite any changes to
3189   the outer rect upon the next replot.
3190 
3191   The layout element will adapt its inner \ref rect by applying the margins inward to the outer rect.
3192 
3193   \see rect
3194 */
setOuterRect(const QRect & rect)3195 void QCPLayoutElement::setOuterRect(const QRect &rect)
3196 {
3197   if (mOuterRect != rect)
3198   {
3199     mOuterRect = rect;
3200     mRect = mOuterRect.adjusted(mMargins.left(), mMargins.top(), -mMargins.right(), -mMargins.bottom());
3201   }
3202 }
3203 
3204 /*!
3205   Sets the margins of this layout element. If \ref setAutoMargins is disabled for some or all
3206   sides, this function is used to manually set the margin on those sides. Sides that are still set
3207   to be handled automatically are ignored and may have any value in \a margins.
3208 
3209   The margin is the distance between the outer rect (controlled by the parent layout via \ref
3210   setOuterRect) and the inner \ref rect (which usually contains the main content of this layout
3211   element).
3212 
3213   \see setAutoMargins
3214 */
setMargins(const QMargins & margins)3215 void QCPLayoutElement::setMargins(const QMargins &margins)
3216 {
3217   if (mMargins != margins)
3218   {
3219     mMargins = margins;
3220     mRect = mOuterRect.adjusted(mMargins.left(), mMargins.top(), -mMargins.right(), -mMargins.bottom());
3221   }
3222 }
3223 
3224 /*!
3225   If \ref setAutoMargins is enabled on some or all margins, this function is used to provide
3226   minimum values for those margins.
3227 
3228   The minimum values are not enforced on margin sides that were set to be under manual control via
3229   \ref setAutoMargins.
3230 
3231   \see setAutoMargins
3232 */
setMinimumMargins(const QMargins & margins)3233 void QCPLayoutElement::setMinimumMargins(const QMargins &margins)
3234 {
3235   if (mMinimumMargins != margins)
3236   {
3237     mMinimumMargins = margins;
3238   }
3239 }
3240 
3241 /*!
3242   Sets on which sides the margin shall be calculated automatically. If a side is calculated
3243   automatically, a minimum margin value may be provided with \ref setMinimumMargins. If a side is
3244   set to be controlled manually, the value may be specified with \ref setMargins.
3245 
3246   Margin sides that are under automatic control may participate in a \ref QCPMarginGroup (see \ref
3247   setMarginGroup), to synchronize (align) it with other layout elements in the plot.
3248 
3249   \see setMinimumMargins, setMargins, QCP::MarginSide
3250 */
setAutoMargins(QCP::MarginSides sides)3251 void QCPLayoutElement::setAutoMargins(QCP::MarginSides sides)
3252 {
3253   mAutoMargins = sides;
3254 }
3255 
3256 /*!
3257   Sets the minimum size for the inner \ref rect of this layout element. A parent layout tries to
3258   respect the \a size here by changing row/column sizes in the layout accordingly.
3259 
3260   If the parent layout size is not sufficient to satisfy all minimum size constraints of its child
3261   layout elements, the layout may set a size that is actually smaller than \a size. QCustomPlot
3262   propagates the layout's size constraints to the outside by setting its own minimum QWidget size
3263   accordingly, so violations of \a size should be exceptions.
3264 */
setMinimumSize(const QSize & size)3265 void QCPLayoutElement::setMinimumSize(const QSize &size)
3266 {
3267   if (mMinimumSize != size)
3268   {
3269     mMinimumSize = size;
3270     if (mParentLayout)
3271       mParentLayout->sizeConstraintsChanged();
3272   }
3273 }
3274 
3275 /*! \overload
3276 
3277   Sets the minimum size for the inner \ref rect of this layout element.
3278 */
setMinimumSize(int width,int height)3279 void QCPLayoutElement::setMinimumSize(int width, int height)
3280 {
3281   setMinimumSize(QSize(width, height));
3282 }
3283 
3284 /*!
3285   Sets the maximum size for the inner \ref rect of this layout element. A parent layout tries to
3286   respect the \a size here by changing row/column sizes in the layout accordingly.
3287 */
setMaximumSize(const QSize & size)3288 void QCPLayoutElement::setMaximumSize(const QSize &size)
3289 {
3290   if (mMaximumSize != size)
3291   {
3292     mMaximumSize = size;
3293     if (mParentLayout)
3294       mParentLayout->sizeConstraintsChanged();
3295   }
3296 }
3297 
3298 /*! \overload
3299 
3300   Sets the maximum size for the inner \ref rect of this layout element.
3301 */
setMaximumSize(int width,int height)3302 void QCPLayoutElement::setMaximumSize(int width, int height)
3303 {
3304   setMaximumSize(QSize(width, height));
3305 }
3306 
3307 /*!
3308   Sets the margin \a group of the specified margin \a sides.
3309 
3310   Margin groups allow synchronizing specified margins across layout elements, see the documentation
3311   of \ref QCPMarginGroup.
3312 
3313   To unset the margin group of \a sides, set \a group to 0.
3314 
3315   Note that margin groups only work for margin sides that are set to automatic (\ref
3316   setAutoMargins).
3317 
3318   \see QCP::MarginSide
3319 */
setMarginGroup(QCP::MarginSides sides,QCPMarginGroup * group)3320 void QCPLayoutElement::setMarginGroup(QCP::MarginSides sides, QCPMarginGroup *group)
3321 {
3322   QVector<QCP::MarginSide> sideVector;
3323   if (sides.testFlag(QCP::msLeft)) sideVector.append(QCP::msLeft);
3324   if (sides.testFlag(QCP::msRight)) sideVector.append(QCP::msRight);
3325   if (sides.testFlag(QCP::msTop)) sideVector.append(QCP::msTop);
3326   if (sides.testFlag(QCP::msBottom)) sideVector.append(QCP::msBottom);
3327 
3328   for (int i=0; i<sideVector.size(); ++i)
3329   {
3330     QCP::MarginSide side = sideVector.at(i);
3331     if (marginGroup(side) != group)
3332     {
3333       QCPMarginGroup *oldGroup = marginGroup(side);
3334       if (oldGroup) // unregister at old group
3335         oldGroup->removeChild(side, this);
3336 
3337       if (!group) // if setting to 0, remove hash entry. Else set hash entry to new group and register there
3338       {
3339         mMarginGroups.remove(side);
3340       } else // setting to a new group
3341       {
3342         mMarginGroups[side] = group;
3343         group->addChild(side, this);
3344       }
3345     }
3346   }
3347 }
3348 
3349 /*!
3350   Updates the layout element and sub-elements. This function is automatically called before every
3351   replot by the parent layout element. It is called multiple times, once for every \ref
3352   UpdatePhase. The phases are run through in the order of the enum values. For details about what
3353   happens at the different phases, see the documentation of \ref UpdatePhase.
3354 
3355   Layout elements that have child elements should call the \ref update method of their child
3356   elements, and pass the current \a phase unchanged.
3357 
3358   The default implementation executes the automatic margin mechanism in the \ref upMargins phase.
3359   Subclasses should make sure to call the base class implementation.
3360 */
update(UpdatePhase phase)3361 void QCPLayoutElement::update(UpdatePhase phase)
3362 {
3363   if (phase == upMargins)
3364   {
3365     if (mAutoMargins != QCP::msNone)
3366     {
3367       // set the margins of this layout element according to automatic margin calculation, either directly or via a margin group:
3368       QMargins newMargins = mMargins;
3369       QList<QCP::MarginSide> allMarginSides = QList<QCP::MarginSide>() << QCP::msLeft << QCP::msRight << QCP::msTop << QCP::msBottom;
3370       foreach (QCP::MarginSide side, allMarginSides)
3371       {
3372         if (mAutoMargins.testFlag(side)) // this side's margin shall be calculated automatically
3373         {
3374           if (mMarginGroups.contains(side))
3375             QCP::setMarginValue(newMargins, side, mMarginGroups[side]->commonMargin(side)); // this side is part of a margin group, so get the margin value from that group
3376           else
3377             QCP::setMarginValue(newMargins, side, calculateAutoMargin(side)); // this side is not part of a group, so calculate the value directly
3378           // apply minimum margin restrictions:
3379           if (QCP::getMarginValue(newMargins, side) < QCP::getMarginValue(mMinimumMargins, side))
3380             QCP::setMarginValue(newMargins, side, QCP::getMarginValue(mMinimumMargins, side));
3381         }
3382       }
3383       setMargins(newMargins);
3384     }
3385   }
3386 }
3387 
3388 /*!
3389   Returns the minimum size this layout element (the inner \ref rect) may be compressed to.
3390 
3391   if a minimum size (\ref setMinimumSize) was not set manually, parent layouts consult this
3392   function to determine the minimum allowed size of this layout element. (A manual minimum size is
3393   considered set if it is non-zero.)
3394 */
minimumSizeHint() const3395 QSize QCPLayoutElement::minimumSizeHint() const
3396 {
3397   return mMinimumSize;
3398 }
3399 
3400 /*!
3401   Returns the maximum size this layout element (the inner \ref rect) may be expanded to.
3402 
3403   if a maximum size (\ref setMaximumSize) was not set manually, parent layouts consult this
3404   function to determine the maximum allowed size of this layout element. (A manual maximum size is
3405   considered set if it is smaller than Qt's QWIDGETSIZE_MAX.)
3406 */
maximumSizeHint() const3407 QSize QCPLayoutElement::maximumSizeHint() const
3408 {
3409   return mMaximumSize;
3410 }
3411 
3412 /*!
3413   Returns a list of all child elements in this layout element. If \a recursive is true, all
3414   sub-child elements are included in the list, too.
3415 
3416   \warning There may be entries with value 0 in the returned list. (For example, QCPLayoutGrid may have
3417   empty cells which yield 0 at the respective index.)
3418 */
elements(bool recursive) const3419 QList<QCPLayoutElement*> QCPLayoutElement::elements(bool recursive) const
3420 {
3421   Q_UNUSED(recursive)
3422   return QList<QCPLayoutElement*>();
3423 }
3424 
3425 /*!
3426   Layout elements are sensitive to events inside their outer rect. If \a pos is within the outer
3427   rect, this method returns a value corresponding to 0.99 times the parent plot's selection
3428   tolerance. However, layout elements are not selectable by default. So if \a onlySelectable is
3429   true, -1.0 is returned.
3430 
3431   See \ref QCPLayerable::selectTest for a general explanation of this virtual method.
3432 
3433   QCPLayoutElement subclasses may reimplement this method to provide more specific selection test
3434   behaviour.
3435 */
selectTest(const QPointF & pos,bool onlySelectable,QVariant * details) const3436 double QCPLayoutElement::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
3437 {
3438   Q_UNUSED(details)
3439 
3440   if (onlySelectable)
3441     return -1;
3442 
3443   if (QRectF(mOuterRect).contains(pos))
3444   {
3445     if (mParentPlot)
3446       return mParentPlot->selectionTolerance()*0.99;
3447     else
3448     {
3449       qDebug() << Q_FUNC_INFO << "parent plot not defined";
3450       return -1;
3451     }
3452   } else
3453     return -1;
3454 }
3455 
3456 /*! \internal
3457 
3458   propagates the parent plot initialization to all child elements, by calling \ref
3459   QCPLayerable::initializeParentPlot on them.
3460 */
parentPlotInitialized(QCustomPlot * parentPlot)3461 void QCPLayoutElement::parentPlotInitialized(QCustomPlot *parentPlot)
3462 {
3463   foreach (QCPLayoutElement* el, elements(false))
3464   {
3465     if (!el->parentPlot())
3466       el->initializeParentPlot(parentPlot);
3467   }
3468 }
3469 
3470 /*! \internal
3471 
3472   Returns the margin size for this \a side. It is used if automatic margins is enabled for this \a
3473   side (see \ref setAutoMargins). If a minimum margin was set with \ref setMinimumMargins, the
3474   returned value will not be smaller than the specified minimum margin.
3475 
3476   The default implementation just returns the respective manual margin (\ref setMargins) or the
3477   minimum margin, whichever is larger.
3478 */
calculateAutoMargin(QCP::MarginSide side)3479 int QCPLayoutElement::calculateAutoMargin(QCP::MarginSide side)
3480 {
3481   return qMax(QCP::getMarginValue(mMargins, side), QCP::getMarginValue(mMinimumMargins, side));
3482 }
3483 
3484 /*! \internal
3485 
3486   This virtual method is called when this layout element was moved to a different QCPLayout, or
3487   when this layout element has changed its logical position (e.g. row and/or column) within the
3488   same QCPLayout. Subclasses may use this to react accordingly.
3489 
3490   Since this method is called after the completion of the move, you can access the new parent
3491   layout via \ref layout().
3492 
3493   The default implementation does nothing.
3494 */
layoutChanged()3495 void QCPLayoutElement::layoutChanged()
3496 {
3497 }
3498 
3499 ////////////////////////////////////////////////////////////////////////////////////////////////////
3500 //////////////////// QCPLayout
3501 ////////////////////////////////////////////////////////////////////////////////////////////////////
3502 
3503 /*! \class QCPLayout
3504   \brief The abstract base class for layouts
3505 
3506   This is an abstract base class for layout elements whose main purpose is to define the position
3507   and size of other child layout elements. In most cases, layouts don't draw anything themselves
3508   (but there are exceptions to this, e.g. QCPLegend).
3509 
3510   QCPLayout derives from QCPLayoutElement, and thus can itself be nested in other layouts.
3511 
3512   QCPLayout introduces a common interface for accessing and manipulating the child elements. Those
3513   functions are most notably \ref elementCount, \ref elementAt, \ref takeAt, \ref take, \ref
3514   simplify, \ref removeAt, \ref remove and \ref clear. Individual subclasses may add more functions
3515   to this interface which are more specialized to the form of the layout. For example, \ref
3516   QCPLayoutGrid adds functions that take row and column indices to access cells of the layout grid
3517   more conveniently.
3518 
3519   Since this is an abstract base class, you can't instantiate it directly. Rather use one of its
3520   subclasses like QCPLayoutGrid or QCPLayoutInset.
3521 
3522   For a general introduction to the layout system, see the dedicated documentation page \ref
3523   thelayoutsystem "The Layout System".
3524 */
3525 
3526 /* start documentation of pure virtual functions */
3527 
3528 /*! \fn virtual int QCPLayout::elementCount() const = 0
3529 
3530   Returns the number of elements/cells in the layout.
3531 
3532   \see elements, elementAt
3533 */
3534 
3535 /*! \fn virtual QCPLayoutElement* QCPLayout::elementAt(int index) const = 0
3536 
3537   Returns the element in the cell with the given \a index. If \a index is invalid, returns 0.
3538 
3539   Note that even if \a index is valid, the respective cell may be empty in some layouts (e.g.
3540   QCPLayoutGrid), so this function may return 0 in those cases. You may use this function to check
3541   whether a cell is empty or not.
3542 
3543   \see elements, elementCount, takeAt
3544 */
3545 
3546 /*! \fn virtual QCPLayoutElement* QCPLayout::takeAt(int index) = 0
3547 
3548   Removes the element with the given \a index from the layout and returns it.
3549 
3550   If the \a index is invalid or the cell with that index is empty, returns 0.
3551 
3552   Note that some layouts don't remove the respective cell right away but leave an empty cell after
3553   successful removal of the layout element. To collapse empty cells, use \ref simplify.
3554 
3555   \see elementAt, take
3556 */
3557 
3558 /*! \fn virtual bool QCPLayout::take(QCPLayoutElement* element) = 0
3559 
3560   Removes the specified \a element from the layout and returns true on success.
3561 
3562   If the \a element isn't in this layout, returns false.
3563 
3564   Note that some layouts don't remove the respective cell right away but leave an empty cell after
3565   successful removal of the layout element. To collapse empty cells, use \ref simplify.
3566 
3567   \see takeAt
3568 */
3569 
3570 /* end documentation of pure virtual functions */
3571 
3572 /*!
3573   Creates an instance of QCPLayout and sets default values. Note that since QCPLayout
3574   is an abstract base class, it can't be instantiated directly.
3575 */
QCPLayout()3576 QCPLayout::QCPLayout()
3577 {
3578 }
3579 
3580 /*!
3581   First calls the QCPLayoutElement::update base class implementation to update the margins on this
3582   layout.
3583 
3584   Then calls \ref updateLayout which subclasses reimplement to reposition and resize their cells.
3585 
3586   Finally, \ref update is called on all child elements.
3587 */
update(UpdatePhase phase)3588 void QCPLayout::update(UpdatePhase phase)
3589 {
3590   QCPLayoutElement::update(phase);
3591 
3592   // set child element rects according to layout:
3593   if (phase == upLayout)
3594     updateLayout();
3595 
3596   // propagate update call to child elements:
3597   const int elCount = elementCount();
3598   for (int i=0; i<elCount; ++i)
3599   {
3600     if (QCPLayoutElement *el = elementAt(i))
3601       el->update(phase);
3602   }
3603 }
3604 
3605 /* inherits documentation from base class */
elements(bool recursive) const3606 QList<QCPLayoutElement*> QCPLayout::elements(bool recursive) const
3607 {
3608   const int c = elementCount();
3609   QList<QCPLayoutElement*> result;
3610 #if QT_VERSION >= QT_VERSION_CHECK(4, 7, 0)
3611   result.reserve(c);
3612 #endif
3613   for (int i=0; i<c; ++i)
3614     result.append(elementAt(i));
3615   if (recursive)
3616   {
3617     for (int i=0; i<c; ++i)
3618     {
3619       if (result.at(i))
3620         result << result.at(i)->elements(recursive);
3621     }
3622   }
3623   return result;
3624 }
3625 
3626 /*!
3627   Simplifies the layout by collapsing empty cells. The exact behavior depends on subclasses, the
3628   default implementation does nothing.
3629 
3630   Not all layouts need simplification. For example, QCPLayoutInset doesn't use explicit
3631   simplification while QCPLayoutGrid does.
3632 */
simplify()3633 void QCPLayout::simplify()
3634 {
3635 }
3636 
3637 /*!
3638   Removes and deletes the element at the provided \a index. Returns true on success. If \a index is
3639   invalid or points to an empty cell, returns false.
3640 
3641   This function internally uses \ref takeAt to remove the element from the layout and then deletes
3642   the returned element. Note that some layouts don't remove the respective cell right away but leave an
3643   empty cell after successful removal of the layout element. To collapse empty cells, use \ref
3644   simplify.
3645 
3646   \see remove, takeAt
3647 */
removeAt(int index)3648 bool QCPLayout::removeAt(int index)
3649 {
3650   if (QCPLayoutElement *el = takeAt(index))
3651   {
3652     delete el;
3653     return true;
3654   } else
3655     return false;
3656 }
3657 
3658 /*!
3659   Removes and deletes the provided \a element. Returns true on success. If \a element is not in the
3660   layout, returns false.
3661 
3662   This function internally uses \ref takeAt to remove the element from the layout and then deletes
3663   the element. Note that some layouts don't remove the respective cell right away but leave an
3664   empty cell after successful removal of the layout element. To collapse empty cells, use \ref
3665   simplify.
3666 
3667   \see removeAt, take
3668 */
remove(QCPLayoutElement * element)3669 bool QCPLayout::remove(QCPLayoutElement *element)
3670 {
3671   if (take(element))
3672   {
3673     delete element;
3674     return true;
3675   } else
3676     return false;
3677 }
3678 
3679 /*!
3680   Removes and deletes all layout elements in this layout. Finally calls \ref simplify to make sure
3681   all empty cells are collapsed.
3682 
3683   \see remove, removeAt
3684 */
clear()3685 void QCPLayout::clear()
3686 {
3687   for (int i=elementCount()-1; i>=0; --i)
3688   {
3689     if (elementAt(i))
3690       removeAt(i);
3691   }
3692   simplify();
3693 }
3694 
3695 /*!
3696   Subclasses call this method to report changed (minimum/maximum) size constraints.
3697 
3698   If the parent of this layout is again a QCPLayout, forwards the call to the parent's \ref
3699   sizeConstraintsChanged. If the parent is a QWidget (i.e. is the \ref QCustomPlot::plotLayout of
3700   QCustomPlot), calls QWidget::updateGeometry, so if the QCustomPlot widget is inside a Qt QLayout,
3701   it may update itself and resize cells accordingly.
3702 */
sizeConstraintsChanged() const3703 void QCPLayout::sizeConstraintsChanged() const
3704 {
3705   if (QWidget *w = qobject_cast<QWidget*>(parent()))
3706     w->updateGeometry();
3707   else if (QCPLayout *l = qobject_cast<QCPLayout*>(parent()))
3708     l->sizeConstraintsChanged();
3709 }
3710 
3711 /*! \internal
3712 
3713   Subclasses reimplement this method to update the position and sizes of the child elements/cells
3714   via calling their \ref QCPLayoutElement::setOuterRect. The default implementation does nothing.
3715 
3716   The geometry used as a reference is the inner \ref rect of this layout. Child elements should stay
3717   within that rect.
3718 
3719   \ref getSectionSizes may help with the reimplementation of this function.
3720 
3721   \see update
3722 */
updateLayout()3723 void QCPLayout::updateLayout()
3724 {
3725 }
3726 
3727 
3728 /*! \internal
3729 
3730   Associates \a el with this layout. This is done by setting the \ref QCPLayoutElement::layout, the
3731   \ref QCPLayerable::parentLayerable and the QObject parent to this layout.
3732 
3733   Further, if \a el didn't previously have a parent plot, calls \ref
3734   QCPLayerable::initializeParentPlot on \a el to set the paret plot.
3735 
3736   This method is used by subclass specific methods that add elements to the layout. Note that this
3737   method only changes properties in \a el. The removal from the old layout and the insertion into
3738   the new layout must be done additionally.
3739 */
adoptElement(QCPLayoutElement * el)3740 void QCPLayout::adoptElement(QCPLayoutElement *el)
3741 {
3742   if (el)
3743   {
3744     el->mParentLayout = this;
3745     el->setParentLayerable(this);
3746     el->setParent(this);
3747     if (!el->parentPlot())
3748       el->initializeParentPlot(mParentPlot);
3749     el->layoutChanged();
3750   } else
3751     qDebug() << Q_FUNC_INFO << "Null element passed";
3752 }
3753 
3754 /*! \internal
3755 
3756   Disassociates \a el from this layout. This is done by setting the \ref QCPLayoutElement::layout
3757   and the \ref QCPLayerable::parentLayerable to zero. The QObject parent is set to the parent
3758   QCustomPlot.
3759 
3760   This method is used by subclass specific methods that remove elements from the layout (e.g. \ref
3761   take or \ref takeAt). Note that this method only changes properties in \a el. The removal from
3762   the old layout must be done additionally.
3763 */
releaseElement(QCPLayoutElement * el)3764 void QCPLayout::releaseElement(QCPLayoutElement *el)
3765 {
3766   if (el)
3767   {
3768     el->mParentLayout = 0;
3769     el->setParentLayerable(0);
3770     el->setParent(mParentPlot);
3771     // Note: Don't initializeParentPlot(0) here, because layout element will stay in same parent plot
3772   } else
3773     qDebug() << Q_FUNC_INFO << "Null element passed";
3774 }
3775 
3776 /*! \internal
3777 
3778   This is a helper function for the implementation of \ref updateLayout in subclasses.
3779 
3780   It calculates the sizes of one-dimensional sections with provided constraints on maximum section
3781   sizes, minimum section sizes, relative stretch factors and the final total size of all sections.
3782 
3783   The QVector entries refer to the sections. Thus all QVectors must have the same size.
3784 
3785   \a maxSizes gives the maximum allowed size of each section. If there shall be no maximum size
3786   imposed, set all vector values to Qt's QWIDGETSIZE_MAX.
3787 
3788   \a minSizes gives the minimum allowed size of each section. If there shall be no minimum size
3789   imposed, set all vector values to zero. If the \a minSizes entries add up to a value greater than
3790   \a totalSize, sections will be scaled smaller than the proposed minimum sizes. (In other words,
3791   not exceeding the allowed total size is taken to be more important than not going below minimum
3792   section sizes.)
3793 
3794   \a stretchFactors give the relative proportions of the sections to each other. If all sections
3795   shall be scaled equally, set all values equal. If the first section shall be double the size of
3796   each individual other section, set the first number of \a stretchFactors to double the value of
3797   the other individual values (e.g. {2, 1, 1, 1}).
3798 
3799   \a totalSize is the value that the final section sizes will add up to. Due to rounding, the
3800   actual sum may differ slightly. If you want the section sizes to sum up to exactly that value,
3801   you could distribute the remaining difference on the sections.
3802 
3803   The return value is a QVector containing the section sizes.
3804 */
getSectionSizes(QVector<int> maxSizes,QVector<int> minSizes,QVector<double> stretchFactors,int totalSize) const3805 QVector<int> QCPLayout::getSectionSizes(QVector<int> maxSizes, QVector<int> minSizes, QVector<double> stretchFactors, int totalSize) const
3806 {
3807   if (maxSizes.size() != minSizes.size() || minSizes.size() != stretchFactors.size())
3808   {
3809     qDebug() << Q_FUNC_INFO << "Passed vector sizes aren't equal:" << maxSizes << minSizes << stretchFactors;
3810     return QVector<int>();
3811   }
3812   if (stretchFactors.isEmpty())
3813     return QVector<int>();
3814   int sectionCount = stretchFactors.size();
3815   QVector<double> sectionSizes(sectionCount);
3816   // if provided total size is forced smaller than total minimum size, ignore minimum sizes (squeeze sections):
3817   int minSizeSum = 0;
3818   for (int i=0; i<sectionCount; ++i)
3819     minSizeSum += minSizes.at(i);
3820   if (totalSize < minSizeSum)
3821   {
3822     // new stretch factors are minimum sizes and minimum sizes are set to zero:
3823     for (int i=0; i<sectionCount; ++i)
3824     {
3825       stretchFactors[i] = minSizes.at(i);
3826       minSizes[i] = 0;
3827     }
3828   }
3829 
3830   QList<int> minimumLockedSections;
3831   QList<int> unfinishedSections;
3832   for (int i=0; i<sectionCount; ++i)
3833     unfinishedSections.append(i);
3834   double freeSize = totalSize;
3835 
3836   int outerIterations = 0;
3837   while (!unfinishedSections.isEmpty() && outerIterations < sectionCount*2) // the iteration check ist just a failsafe in case something really strange happens
3838   {
3839     ++outerIterations;
3840     int innerIterations = 0;
3841     while (!unfinishedSections.isEmpty() && innerIterations < sectionCount*2) // the iteration check ist just a failsafe in case something really strange happens
3842     {
3843       ++innerIterations;
3844       // find section that hits its maximum next:
3845       int nextId = -1;
3846       double nextMax = 1e12;
3847       for (int i=0; i<unfinishedSections.size(); ++i)
3848       {
3849         int secId = unfinishedSections.at(i);
3850         double hitsMaxAt = (maxSizes.at(secId)-sectionSizes.at(secId))/stretchFactors.at(secId);
3851         if (hitsMaxAt < nextMax)
3852         {
3853           nextMax = hitsMaxAt;
3854           nextId = secId;
3855         }
3856       }
3857       // check if that maximum is actually within the bounds of the total size (i.e. can we stretch all remaining sections so far that the found section
3858       // actually hits its maximum, without exceeding the total size when we add up all sections)
3859       double stretchFactorSum = 0;
3860       for (int i=0; i<unfinishedSections.size(); ++i)
3861         stretchFactorSum += stretchFactors.at(unfinishedSections.at(i));
3862       double nextMaxLimit = freeSize/stretchFactorSum;
3863       if (nextMax < nextMaxLimit) // next maximum is actually hit, move forward to that point and fix the size of that section
3864       {
3865         for (int i=0; i<unfinishedSections.size(); ++i)
3866         {
3867           sectionSizes[unfinishedSections.at(i)] += nextMax*stretchFactors.at(unfinishedSections.at(i)); // increment all sections
3868           freeSize -= nextMax*stretchFactors.at(unfinishedSections.at(i));
3869         }
3870         unfinishedSections.removeOne(nextId); // exclude the section that is now at maximum from further changes
3871       } else // next maximum isn't hit, just distribute rest of free space on remaining sections
3872       {
3873         for (int i=0; i<unfinishedSections.size(); ++i)
3874           sectionSizes[unfinishedSections.at(i)] += nextMaxLimit*stretchFactors.at(unfinishedSections.at(i)); // increment all sections
3875         unfinishedSections.clear();
3876       }
3877     }
3878     if (innerIterations == sectionCount*2)
3879       qDebug() << Q_FUNC_INFO << "Exceeded maximum expected inner iteration count, layouting aborted. Input was:" << maxSizes << minSizes << stretchFactors << totalSize;
3880 
3881     // now check whether the resulting section sizes violate minimum restrictions:
3882     bool foundMinimumViolation = false;
3883     for (int i=0; i<sectionSizes.size(); ++i)
3884     {
3885       if (minimumLockedSections.contains(i))
3886         continue;
3887       if (sectionSizes.at(i) < minSizes.at(i)) // section violates minimum
3888       {
3889         sectionSizes[i] = minSizes.at(i); // set it to minimum
3890         foundMinimumViolation = true; // make sure we repeat the whole optimization process
3891         minimumLockedSections.append(i);
3892       }
3893     }
3894     if (foundMinimumViolation)
3895     {
3896       freeSize = totalSize;
3897       for (int i=0; i<sectionCount; ++i)
3898       {
3899         if (!minimumLockedSections.contains(i)) // only put sections that haven't hit their minimum back into the pool
3900           unfinishedSections.append(i);
3901         else
3902           freeSize -= sectionSizes.at(i); // remove size of minimum locked sections from available space in next round
3903       }
3904       // reset all section sizes to zero that are in unfinished sections (all others have been set to their minimum):
3905       for (int i=0; i<unfinishedSections.size(); ++i)
3906         sectionSizes[unfinishedSections.at(i)] = 0;
3907     }
3908   }
3909   if (outerIterations == sectionCount*2)
3910     qDebug() << Q_FUNC_INFO << "Exceeded maximum expected outer iteration count, layouting aborted. Input was:" << maxSizes << minSizes << stretchFactors << totalSize;
3911 
3912   QVector<int> result(sectionCount);
3913   for (int i=0; i<sectionCount; ++i)
3914     result[i] = qRound(sectionSizes.at(i));
3915   return result;
3916 }
3917 
3918 
3919 ////////////////////////////////////////////////////////////////////////////////////////////////////
3920 //////////////////// QCPLayoutGrid
3921 ////////////////////////////////////////////////////////////////////////////////////////////////////
3922 
3923 /*! \class QCPLayoutGrid
3924   \brief A layout that arranges child elements in a grid
3925 
3926   Elements are laid out in a grid with configurable stretch factors (\ref setColumnStretchFactor,
3927   \ref setRowStretchFactor) and spacing (\ref setColumnSpacing, \ref setRowSpacing).
3928 
3929   Elements can be added to cells via \ref addElement. The grid is expanded if the specified row or
3930   column doesn't exist yet. Whether a cell contains a valid layout element can be checked with \ref
3931   hasElement, that element can be retrieved with \ref element. If rows and columns that only have
3932   empty cells shall be removed, call \ref simplify. Removal of elements is either done by just
3933   adding the element to a different layout or by using the QCPLayout interface \ref take or \ref
3934   remove.
3935 
3936   If you use \ref addElement(QCPLayoutElement*) without explicit parameters for \a row and \a
3937   column, the grid layout will choose the position according to the current \ref setFillOrder and
3938   the wrapping (\ref setWrap).
3939 
3940   Row and column insertion can be performed with \ref insertRow and \ref insertColumn.
3941 */
3942 
3943 /* start documentation of inline functions */
3944 
3945 /*! \fn int QCPLayoutGrid::rowCount() const
3946 
3947   Returns the number of rows in the layout.
3948 
3949   \see columnCount
3950 */
3951 
3952 /*! \fn int QCPLayoutGrid::columnCount() const
3953 
3954   Returns the number of columns in the layout.
3955 
3956   \see rowCount
3957 */
3958 
3959 /* end documentation of inline functions */
3960 
3961 /*!
3962   Creates an instance of QCPLayoutGrid and sets default values.
3963 */
QCPLayoutGrid()3964 QCPLayoutGrid::QCPLayoutGrid() :
3965   mColumnSpacing(5),
3966   mRowSpacing(5),
3967   mWrap(0),
3968   mFillOrder(foRowsFirst)
3969 {
3970 }
3971 
~QCPLayoutGrid()3972 QCPLayoutGrid::~QCPLayoutGrid()
3973 {
3974   // clear all child layout elements. This is important because only the specific layouts know how
3975   // to handle removing elements (clear calls virtual removeAt method to do that).
3976   clear();
3977 }
3978 
3979 /*!
3980   Returns the element in the cell in \a row and \a column.
3981 
3982   Returns 0 if either the row/column is invalid or if the cell is empty. In those cases, a qDebug
3983   message is printed. To check whether a cell exists and isn't empty, use \ref hasElement.
3984 
3985   \see addElement, hasElement
3986 */
element(int row,int column) const3987 QCPLayoutElement *QCPLayoutGrid::element(int row, int column) const
3988 {
3989   if (row >= 0 && row < mElements.size())
3990   {
3991     if (column >= 0 && column < mElements.first().size())
3992     {
3993       if (QCPLayoutElement *result = mElements.at(row).at(column))
3994         return result;
3995       else
3996         qDebug() << Q_FUNC_INFO << "Requested cell is empty. Row:" << row << "Column:" << column;
3997     } else
3998       qDebug() << Q_FUNC_INFO << "Invalid column. Row:" << row << "Column:" << column;
3999   } else
4000     qDebug() << Q_FUNC_INFO << "Invalid row. Row:" << row << "Column:" << column;
4001   return 0;
4002 }
4003 
4004 
4005 /*! \overload
4006 
4007   Adds the \a element to cell with \a row and \a column. If \a element is already in a layout, it
4008   is first removed from there. If \a row or \a column don't exist yet, the layout is expanded
4009   accordingly.
4010 
4011   Returns true if the element was added successfully, i.e. if the cell at \a row and \a column
4012   didn't already have an element.
4013 
4014   Use the overload of this method without explicit row/column index to place the element according
4015   to the configured fill order and wrapping settings.
4016 
4017   \see element, hasElement, take, remove
4018 */
addElement(int row,int column,QCPLayoutElement * element)4019 bool QCPLayoutGrid::addElement(int row, int column, QCPLayoutElement *element)
4020 {
4021   if (!hasElement(row, column))
4022   {
4023     if (element && element->layout()) // remove from old layout first
4024       element->layout()->take(element);
4025     expandTo(row+1, column+1);
4026     mElements[row][column] = element;
4027     if (element)
4028       adoptElement(element);
4029     return true;
4030   } else
4031     qDebug() << Q_FUNC_INFO << "There is already an element in the specified row/column:" << row << column;
4032   return false;
4033 }
4034 
4035 /*! \overload
4036 
4037   Adds the \a element to the next empty cell according to the current fill order (\ref
4038   setFillOrder) and wrapping (\ref setWrap). If \a element is already in a layout, it is first
4039   removed from there. If necessary, the layout is expanded to hold the new element.
4040 
4041   Returns true if the element was added successfully.
4042 
4043   \see setFillOrder, setWrap, element, hasElement, take, remove
4044 */
addElement(QCPLayoutElement * element)4045 bool QCPLayoutGrid::addElement(QCPLayoutElement *element)
4046 {
4047   int rowIndex = 0;
4048   int colIndex = 0;
4049   if (mFillOrder == foColumnsFirst)
4050   {
4051     while (hasElement(rowIndex, colIndex))
4052     {
4053       ++colIndex;
4054       if (colIndex >= mWrap && mWrap > 0)
4055       {
4056         colIndex = 0;
4057         ++rowIndex;
4058       }
4059     }
4060   } else
4061   {
4062     while (hasElement(rowIndex, colIndex))
4063     {
4064       ++rowIndex;
4065       if (rowIndex >= mWrap && mWrap > 0)
4066       {
4067         rowIndex = 0;
4068         ++colIndex;
4069       }
4070     }
4071   }
4072   return addElement(rowIndex, colIndex, element);
4073 }
4074 
4075 /*!
4076   Returns whether the cell at \a row and \a column exists and contains a valid element, i.e. isn't
4077   empty.
4078 
4079   \see element
4080 */
hasElement(int row,int column)4081 bool QCPLayoutGrid::hasElement(int row, int column)
4082 {
4083   if (row >= 0 && row < rowCount() && column >= 0 && column < columnCount())
4084     return mElements.at(row).at(column);
4085   else
4086     return false;
4087 }
4088 
4089 /*!
4090   Sets the stretch \a factor of \a column.
4091 
4092   Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond
4093   their minimum and maximum widths/heights (\ref QCPLayoutElement::setMinimumSize, \ref
4094   QCPLayoutElement::setMaximumSize), regardless of the stretch factor.
4095 
4096   The default stretch factor of newly created rows/columns is 1.
4097 
4098   \see setColumnStretchFactors, setRowStretchFactor
4099 */
setColumnStretchFactor(int column,double factor)4100 void QCPLayoutGrid::setColumnStretchFactor(int column, double factor)
4101 {
4102   if (column >= 0 && column < columnCount())
4103   {
4104     if (factor > 0)
4105       mColumnStretchFactors[column] = factor;
4106     else
4107       qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << factor;
4108   } else
4109     qDebug() << Q_FUNC_INFO << "Invalid column:" << column;
4110 }
4111 
4112 /*!
4113   Sets the stretch \a factors of all columns. \a factors must have the size \ref columnCount.
4114 
4115   Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond
4116   their minimum and maximum widths/heights (\ref QCPLayoutElement::setMinimumSize, \ref
4117   QCPLayoutElement::setMaximumSize), regardless of the stretch factor.
4118 
4119   The default stretch factor of newly created rows/columns is 1.
4120 
4121   \see setColumnStretchFactor, setRowStretchFactors
4122 */
setColumnStretchFactors(const QList<double> & factors)4123 void QCPLayoutGrid::setColumnStretchFactors(const QList<double> &factors)
4124 {
4125   if (factors.size() == mColumnStretchFactors.size())
4126   {
4127     mColumnStretchFactors = factors;
4128     for (int i=0; i<mColumnStretchFactors.size(); ++i)
4129     {
4130       if (mColumnStretchFactors.at(i) <= 0)
4131       {
4132         qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << mColumnStretchFactors.at(i);
4133         mColumnStretchFactors[i] = 1;
4134       }
4135     }
4136   } else
4137     qDebug() << Q_FUNC_INFO << "Column count not equal to passed stretch factor count:" << factors;
4138 }
4139 
4140 /*!
4141   Sets the stretch \a factor of \a row.
4142 
4143   Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond
4144   their minimum and maximum widths/heights (\ref QCPLayoutElement::setMinimumSize, \ref
4145   QCPLayoutElement::setMaximumSize), regardless of the stretch factor.
4146 
4147   The default stretch factor of newly created rows/columns is 1.
4148 
4149   \see setColumnStretchFactors, setRowStretchFactor
4150 */
setRowStretchFactor(int row,double factor)4151 void QCPLayoutGrid::setRowStretchFactor(int row, double factor)
4152 {
4153   if (row >= 0 && row < rowCount())
4154   {
4155     if (factor > 0)
4156       mRowStretchFactors[row] = factor;
4157     else
4158       qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << factor;
4159   } else
4160     qDebug() << Q_FUNC_INFO << "Invalid row:" << row;
4161 }
4162 
4163 /*!
4164   Sets the stretch \a factors of all rows. \a factors must have the size \ref rowCount.
4165 
4166   Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond
4167   their minimum and maximum widths/heights (\ref QCPLayoutElement::setMinimumSize, \ref
4168   QCPLayoutElement::setMaximumSize), regardless of the stretch factor.
4169 
4170   The default stretch factor of newly created rows/columns is 1.
4171 
4172   \see setRowStretchFactor, setColumnStretchFactors
4173 */
setRowStretchFactors(const QList<double> & factors)4174 void QCPLayoutGrid::setRowStretchFactors(const QList<double> &factors)
4175 {
4176   if (factors.size() == mRowStretchFactors.size())
4177   {
4178     mRowStretchFactors = factors;
4179     for (int i=0; i<mRowStretchFactors.size(); ++i)
4180     {
4181       if (mRowStretchFactors.at(i) <= 0)
4182       {
4183         qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << mRowStretchFactors.at(i);
4184         mRowStretchFactors[i] = 1;
4185       }
4186     }
4187   } else
4188     qDebug() << Q_FUNC_INFO << "Row count not equal to passed stretch factor count:" << factors;
4189 }
4190 
4191 /*!
4192   Sets the gap that is left blank between columns to \a pixels.
4193 
4194   \see setRowSpacing
4195 */
setColumnSpacing(int pixels)4196 void QCPLayoutGrid::setColumnSpacing(int pixels)
4197 {
4198   mColumnSpacing = pixels;
4199 }
4200 
4201 /*!
4202   Sets the gap that is left blank between rows to \a pixels.
4203 
4204   \see setColumnSpacing
4205 */
setRowSpacing(int pixels)4206 void QCPLayoutGrid::setRowSpacing(int pixels)
4207 {
4208   mRowSpacing = pixels;
4209 }
4210 
4211 /*!
4212   Sets the maximum number of columns or rows that are used, before new elements added with \ref
4213   addElement(QCPLayoutElement*) will start to fill the next row or column, respectively. It depends
4214   on \ref setFillOrder, whether rows or columns are wrapped.
4215 
4216   If \a count is set to zero, no wrapping will ever occur.
4217 
4218   If you wish to re-wrap the elements currently in the layout, call \ref setFillOrder with \a
4219   rearrange set to true (the actual fill order doesn't need to be changed for the rearranging to be
4220   done).
4221 
4222   Note that the method \ref addElement(int row, int column, QCPLayoutElement *element) with
4223   explicitly stated row and column is not subject to wrapping and can place elements even beyond
4224   the specified wrapping point.
4225 
4226   \see setFillOrder
4227 */
setWrap(int count)4228 void QCPLayoutGrid::setWrap(int count)
4229 {
4230   mWrap = qMax(0, count);
4231 }
4232 
4233 /*!
4234   Sets the filling order and wrapping behaviour that is used when adding new elements with the
4235   method \ref addElement(QCPLayoutElement*).
4236 
4237   The specified \a order defines whether rows or columns are filled first. Using \ref setWrap, you
4238   can control at which row/column count wrapping into the next column/row will occur. If you set it
4239   to zero, no wrapping will ever occur. Changing the fill order also changes the meaning of the
4240   linear index used e.g. in \ref elementAt and \ref takeAt.
4241 
4242   If you want to have all current elements arranged in the new order, set \a rearrange to true. The
4243   elements will be rearranged in a way that tries to preserve their linear index. However, empty
4244   cells are skipped during build-up of the new cell order, which shifts the succeding element's
4245   index. The rearranging is performed even if the specified \a order is already the current fill
4246   order. Thus this method can be used to re-wrap the current elements.
4247 
4248   If \a rearrange is false, the current element arrangement is not changed, which means the
4249   linear indexes change (because the linear index is dependent on the fill order).
4250 
4251   Note that the method \ref addElement(int row, int column, QCPLayoutElement *element) with
4252   explicitly stated row and column is not subject to wrapping and can place elements even beyond
4253   the specified wrapping point.
4254 
4255   \see setWrap, addElement(QCPLayoutElement*)
4256 */
setFillOrder(FillOrder order,bool rearrange)4257 void QCPLayoutGrid::setFillOrder(FillOrder order, bool rearrange)
4258 {
4259   // if rearranging, take all elements via linear index of old fill order:
4260   const int elCount = elementCount();
4261   QVector<QCPLayoutElement*> tempElements;
4262   if (rearrange)
4263   {
4264     tempElements.reserve(elCount);
4265     for (int i=0; i<elCount; ++i)
4266     {
4267       if (elementAt(i))
4268         tempElements.append(takeAt(i));
4269     }
4270     simplify();
4271   }
4272   // change fill order as requested:
4273   mFillOrder = order;
4274   // if rearranging, re-insert via linear index according to new fill order:
4275   if (rearrange)
4276   {
4277     for (int i=0; i<tempElements.size(); ++i)
4278       addElement(tempElements.at(i));
4279   }
4280 }
4281 
4282 /*!
4283   Expands the layout to have \a newRowCount rows and \a newColumnCount columns. So the last valid
4284   row index will be \a newRowCount-1, the last valid column index will be \a newColumnCount-1.
4285 
4286   If the current column/row count is already larger or equal to \a newColumnCount/\a newRowCount,
4287   this function does nothing in that dimension.
4288 
4289   Newly created cells are empty, new rows and columns have the stretch factor 1.
4290 
4291   Note that upon a call to \ref addElement, the layout is expanded automatically to contain the
4292   specified row and column, using this function.
4293 
4294   \see simplify
4295 */
expandTo(int newRowCount,int newColumnCount)4296 void QCPLayoutGrid::expandTo(int newRowCount, int newColumnCount)
4297 {
4298   // add rows as necessary:
4299   while (rowCount() < newRowCount)
4300   {
4301     mElements.append(QList<QCPLayoutElement*>());
4302     mRowStretchFactors.append(1);
4303   }
4304   // go through rows and expand columns as necessary:
4305   int newColCount = qMax(columnCount(), newColumnCount);
4306   for (int i=0; i<rowCount(); ++i)
4307   {
4308     while (mElements.at(i).size() < newColCount)
4309       mElements[i].append(0);
4310   }
4311   while (mColumnStretchFactors.size() < newColCount)
4312     mColumnStretchFactors.append(1);
4313 }
4314 
4315 /*!
4316   Inserts a new row with empty cells at the row index \a newIndex. Valid values for \a newIndex
4317   range from 0 (inserts a row at the top) to \a rowCount (appends a row at the bottom).
4318 
4319   \see insertColumn
4320 */
insertRow(int newIndex)4321 void QCPLayoutGrid::insertRow(int newIndex)
4322 {
4323   if (mElements.isEmpty() || mElements.first().isEmpty()) // if grid is completely empty, add first cell
4324   {
4325     expandTo(1, 1);
4326     return;
4327   }
4328 
4329   if (newIndex < 0)
4330     newIndex = 0;
4331   if (newIndex > rowCount())
4332     newIndex = rowCount();
4333 
4334   mRowStretchFactors.insert(newIndex, 1);
4335   QList<QCPLayoutElement*> newRow;
4336   for (int col=0; col<columnCount(); ++col)
4337     newRow.append((QCPLayoutElement*)0);
4338   mElements.insert(newIndex, newRow);
4339 }
4340 
4341 /*!
4342   Inserts a new column with empty cells at the column index \a newIndex. Valid values for \a
4343   newIndex range from 0 (inserts a row at the left) to \a rowCount (appends a row at the right).
4344 
4345   \see insertRow
4346 */
insertColumn(int newIndex)4347 void QCPLayoutGrid::insertColumn(int newIndex)
4348 {
4349   if (mElements.isEmpty() || mElements.first().isEmpty()) // if grid is completely empty, add first cell
4350   {
4351     expandTo(1, 1);
4352     return;
4353   }
4354 
4355   if (newIndex < 0)
4356     newIndex = 0;
4357   if (newIndex > columnCount())
4358     newIndex = columnCount();
4359 
4360   mColumnStretchFactors.insert(newIndex, 1);
4361   for (int row=0; row<rowCount(); ++row)
4362     mElements[row].insert(newIndex, (QCPLayoutElement*)0);
4363 }
4364 
4365 /*!
4366   Converts the given \a row and \a column to the linear index used by some methods of \ref
4367   QCPLayoutGrid and \ref QCPLayout.
4368 
4369   The way the cells are indexed depends on \ref setFillOrder. If it is \ref foRowsFirst, the
4370   indices increase left to right and then top to bottom. If it is \ref foColumnsFirst, the indices
4371   increase top to bottom and then left to right.
4372 
4373   For the returned index to be valid, \a row and \a column must be valid indices themselves, i.e.
4374   greater or equal to zero and smaller than the current \ref rowCount/\ref columnCount.
4375 
4376   \see indexToRowCol
4377 */
rowColToIndex(int row,int column) const4378 int QCPLayoutGrid::rowColToIndex(int row, int column) const
4379 {
4380   if (row >= 0 && row < rowCount())
4381   {
4382     if (column >= 0 && column < columnCount())
4383     {
4384       switch (mFillOrder)
4385       {
4386         case foRowsFirst: return column*rowCount() + row;
4387         case foColumnsFirst: return row*columnCount() + column;
4388       }
4389     } else
4390       qDebug() << Q_FUNC_INFO << "row index out of bounds:" << row;
4391   } else
4392     qDebug() << Q_FUNC_INFO << "column index out of bounds:" << column;
4393   return 0;
4394 }
4395 
4396 /*!
4397   Converts the linear index to row and column indices and writes the result to \a row and \a
4398   column.
4399 
4400   The way the cells are indexed depends on \ref setFillOrder. If it is \ref foRowsFirst, the
4401   indices increase left to right and then top to bottom. If it is \ref foColumnsFirst, the indices
4402   increase top to bottom and then left to right.
4403 
4404   If there are no cells (i.e. column or row count is zero), sets \a row and \a column to -1.
4405 
4406   For the retrieved \a row and \a column to be valid, the passed \a index must be valid itself,
4407   i.e. greater or equal to zero and smaller than the current \ref elementCount.
4408 
4409   \see rowColToIndex
4410 */
indexToRowCol(int index,int & row,int & column) const4411 void QCPLayoutGrid::indexToRowCol(int index, int &row, int &column) const
4412 {
4413   row = -1;
4414   column = -1;
4415   if (columnCount() == 0 || rowCount() == 0)
4416     return;
4417   if (index < 0 || index >= elementCount())
4418   {
4419     qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
4420     return;
4421   }
4422 
4423   switch (mFillOrder)
4424   {
4425     case foRowsFirst:
4426     {
4427       column = index / rowCount();
4428       row = index % rowCount();
4429       break;
4430     }
4431     case foColumnsFirst:
4432     {
4433       row = index / columnCount();
4434       column = index % columnCount();
4435       break;
4436     }
4437   }
4438 }
4439 
4440 /* inherits documentation from base class */
updateLayout()4441 void QCPLayoutGrid::updateLayout()
4442 {
4443   QVector<int> minColWidths, minRowHeights, maxColWidths, maxRowHeights;
4444   getMinimumRowColSizes(&minColWidths, &minRowHeights);
4445   getMaximumRowColSizes(&maxColWidths, &maxRowHeights);
4446 
4447   int totalRowSpacing = (rowCount()-1) * mRowSpacing;
4448   int totalColSpacing = (columnCount()-1) * mColumnSpacing;
4449   QVector<int> colWidths = getSectionSizes(maxColWidths, minColWidths, mColumnStretchFactors.toVector(), mRect.width()-totalColSpacing);
4450   QVector<int> rowHeights = getSectionSizes(maxRowHeights, minRowHeights, mRowStretchFactors.toVector(), mRect.height()-totalRowSpacing);
4451 
4452   // go through cells and set rects accordingly:
4453   int yOffset = mRect.top();
4454   for (int row=0; row<rowCount(); ++row)
4455   {
4456     if (row > 0)
4457       yOffset += rowHeights.at(row-1)+mRowSpacing;
4458     int xOffset = mRect.left();
4459     for (int col=0; col<columnCount(); ++col)
4460     {
4461       if (col > 0)
4462         xOffset += colWidths.at(col-1)+mColumnSpacing;
4463       if (mElements.at(row).at(col))
4464         mElements.at(row).at(col)->setOuterRect(QRect(xOffset, yOffset, colWidths.at(col), rowHeights.at(row)));
4465     }
4466   }
4467 }
4468 
4469 /*!
4470   \seebaseclassmethod
4471 
4472   Note that the association of the linear \a index to the row/column based cells depends on the
4473   current setting of \ref setFillOrder.
4474 
4475   \see rowColToIndex
4476 */
elementAt(int index) const4477 QCPLayoutElement *QCPLayoutGrid::elementAt(int index) const
4478 {
4479   if (index >= 0 && index < elementCount())
4480   {
4481     int row, col;
4482     indexToRowCol(index, row, col);
4483     return mElements.at(row).at(col);
4484   } else
4485     return 0;
4486 }
4487 
4488 /*!
4489   \seebaseclassmethod
4490 
4491   Note that the association of the linear \a index to the row/column based cells depends on the
4492   current setting of \ref setFillOrder.
4493 
4494   \see rowColToIndex
4495 */
takeAt(int index)4496 QCPLayoutElement *QCPLayoutGrid::takeAt(int index)
4497 {
4498   if (QCPLayoutElement *el = elementAt(index))
4499   {
4500     releaseElement(el);
4501     int row, col;
4502     indexToRowCol(index, row, col);
4503     mElements[row][col] = 0;
4504     return el;
4505   } else
4506   {
4507     qDebug() << Q_FUNC_INFO << "Attempt to take invalid index:" << index;
4508     return 0;
4509   }
4510 }
4511 
4512 /* inherits documentation from base class */
take(QCPLayoutElement * element)4513 bool QCPLayoutGrid::take(QCPLayoutElement *element)
4514 {
4515   if (element)
4516   {
4517     for (int i=0; i<elementCount(); ++i)
4518     {
4519       if (elementAt(i) == element)
4520       {
4521         takeAt(i);
4522         return true;
4523       }
4524     }
4525     qDebug() << Q_FUNC_INFO << "Element not in this layout, couldn't take";
4526   } else
4527     qDebug() << Q_FUNC_INFO << "Can't take null element";
4528   return false;
4529 }
4530 
4531 /* inherits documentation from base class */
elements(bool recursive) const4532 QList<QCPLayoutElement*> QCPLayoutGrid::elements(bool recursive) const
4533 {
4534   QList<QCPLayoutElement*> result;
4535   const int elCount = elementCount();
4536 #if QT_VERSION >= QT_VERSION_CHECK(4, 7, 0)
4537   result.reserve(elCount);
4538 #endif
4539   for (int i=0; i<elCount; ++i)
4540     result.append(elementAt(i));
4541   if (recursive)
4542   {
4543     for (int i=0; i<elCount; ++i)
4544     {
4545       if (result.at(i))
4546         result << result.at(i)->elements(recursive);
4547     }
4548   }
4549   return result;
4550 }
4551 
4552 /*!
4553   Simplifies the layout by collapsing rows and columns which only contain empty cells.
4554 */
simplify()4555 void QCPLayoutGrid::simplify()
4556 {
4557   // remove rows with only empty cells:
4558   for (int row=rowCount()-1; row>=0; --row)
4559   {
4560     bool hasElements = false;
4561     for (int col=0; col<columnCount(); ++col)
4562     {
4563       if (mElements.at(row).at(col))
4564       {
4565         hasElements = true;
4566         break;
4567       }
4568     }
4569     if (!hasElements)
4570     {
4571       mRowStretchFactors.removeAt(row);
4572       mElements.removeAt(row);
4573       if (mElements.isEmpty()) // removed last element, also remove stretch factor (wouldn't happen below because also columnCount changed to 0 now)
4574         mColumnStretchFactors.clear();
4575     }
4576   }
4577 
4578   // remove columns with only empty cells:
4579   for (int col=columnCount()-1; col>=0; --col)
4580   {
4581     bool hasElements = false;
4582     for (int row=0; row<rowCount(); ++row)
4583     {
4584       if (mElements.at(row).at(col))
4585       {
4586         hasElements = true;
4587         break;
4588       }
4589     }
4590     if (!hasElements)
4591     {
4592       mColumnStretchFactors.removeAt(col);
4593       for (int row=0; row<rowCount(); ++row)
4594         mElements[row].removeAt(col);
4595     }
4596   }
4597 }
4598 
4599 /* inherits documentation from base class */
minimumSizeHint() const4600 QSize QCPLayoutGrid::minimumSizeHint() const
4601 {
4602   QVector<int> minColWidths, minRowHeights;
4603   getMinimumRowColSizes(&minColWidths, &minRowHeights);
4604   QSize result(0, 0);
4605   for (int i=0; i<minColWidths.size(); ++i)
4606     result.rwidth() += minColWidths.at(i);
4607   for (int i=0; i<minRowHeights.size(); ++i)
4608     result.rheight() += minRowHeights.at(i);
4609   result.rwidth() += qMax(0, columnCount()-1) * mColumnSpacing + mMargins.left() + mMargins.right();
4610   result.rheight() += qMax(0, rowCount()-1) * mRowSpacing + mMargins.top() + mMargins.bottom();
4611   return result;
4612 }
4613 
4614 /* inherits documentation from base class */
maximumSizeHint() const4615 QSize QCPLayoutGrid::maximumSizeHint() const
4616 {
4617   QVector<int> maxColWidths, maxRowHeights;
4618   getMaximumRowColSizes(&maxColWidths, &maxRowHeights);
4619 
4620   QSize result(0, 0);
4621   for (int i=0; i<maxColWidths.size(); ++i)
4622     result.setWidth(qMin(result.width()+maxColWidths.at(i), QWIDGETSIZE_MAX));
4623   for (int i=0; i<maxRowHeights.size(); ++i)
4624     result.setHeight(qMin(result.height()+maxRowHeights.at(i), QWIDGETSIZE_MAX));
4625   result.rwidth() += qMax(0, columnCount()-1) * mColumnSpacing + mMargins.left() + mMargins.right();
4626   result.rheight() += qMax(0, rowCount()-1) * mRowSpacing + mMargins.top() + mMargins.bottom();
4627   return result;
4628 }
4629 
4630 /*! \internal
4631 
4632   Places the minimum column widths and row heights into \a minColWidths and \a minRowHeights
4633   respectively.
4634 
4635   The minimum height of a row is the largest minimum height of any element in that row. The minimum
4636   width of a column is the largest minimum width of any element in that column.
4637 
4638   This is a helper function for \ref updateLayout.
4639 
4640   \see getMaximumRowColSizes
4641 */
getMinimumRowColSizes(QVector<int> * minColWidths,QVector<int> * minRowHeights) const4642 void QCPLayoutGrid::getMinimumRowColSizes(QVector<int> *minColWidths, QVector<int> *minRowHeights) const
4643 {
4644   *minColWidths = QVector<int>(columnCount(), 0);
4645   *minRowHeights = QVector<int>(rowCount(), 0);
4646   for (int row=0; row<rowCount(); ++row)
4647   {
4648     for (int col=0; col<columnCount(); ++col)
4649     {
4650       if (mElements.at(row).at(col))
4651       {
4652         QSize minHint = mElements.at(row).at(col)->minimumSizeHint();
4653         QSize min = mElements.at(row).at(col)->minimumSize();
4654         QSize final(min.width() > 0 ? min.width() : minHint.width(), min.height() > 0 ? min.height() : minHint.height());
4655         if (minColWidths->at(col) < final.width())
4656           (*minColWidths)[col] = final.width();
4657         if (minRowHeights->at(row) < final.height())
4658           (*minRowHeights)[row] = final.height();
4659       }
4660     }
4661   }
4662 }
4663 
4664 /*! \internal
4665 
4666   Places the maximum column widths and row heights into \a maxColWidths and \a maxRowHeights
4667   respectively.
4668 
4669   The maximum height of a row is the smallest maximum height of any element in that row. The
4670   maximum width of a column is the smallest maximum width of any element in that column.
4671 
4672   This is a helper function for \ref updateLayout.
4673 
4674   \see getMinimumRowColSizes
4675 */
getMaximumRowColSizes(QVector<int> * maxColWidths,QVector<int> * maxRowHeights) const4676 void QCPLayoutGrid::getMaximumRowColSizes(QVector<int> *maxColWidths, QVector<int> *maxRowHeights) const
4677 {
4678   *maxColWidths = QVector<int>(columnCount(), QWIDGETSIZE_MAX);
4679   *maxRowHeights = QVector<int>(rowCount(), QWIDGETSIZE_MAX);
4680   for (int row=0; row<rowCount(); ++row)
4681   {
4682     for (int col=0; col<columnCount(); ++col)
4683     {
4684       if (mElements.at(row).at(col))
4685       {
4686         QSize maxHint = mElements.at(row).at(col)->maximumSizeHint();
4687         QSize max = mElements.at(row).at(col)->maximumSize();
4688         QSize final(max.width() < QWIDGETSIZE_MAX ? max.width() : maxHint.width(), max.height() < QWIDGETSIZE_MAX ? max.height() : maxHint.height());
4689         if (maxColWidths->at(col) > final.width())
4690           (*maxColWidths)[col] = final.width();
4691         if (maxRowHeights->at(row) > final.height())
4692           (*maxRowHeights)[row] = final.height();
4693       }
4694     }
4695   }
4696 }
4697 
4698 
4699 ////////////////////////////////////////////////////////////////////////////////////////////////////
4700 //////////////////// QCPLayoutInset
4701 ////////////////////////////////////////////////////////////////////////////////////////////////////
4702 /*! \class QCPLayoutInset
4703   \brief A layout that places child elements aligned to the border or arbitrarily positioned
4704 
4705   Elements are placed either aligned to the border or at arbitrary position in the area of the
4706   layout. Which placement applies is controlled with the \ref InsetPlacement (\ref
4707   setInsetPlacement).
4708 
4709   Elements are added via \ref addElement(QCPLayoutElement *element, Qt::Alignment alignment) or
4710   addElement(QCPLayoutElement *element, const QRectF &rect). If the first method is used, the inset
4711   placement will default to \ref ipBorderAligned and the element will be aligned according to the
4712   \a alignment parameter. The second method defaults to \ref ipFree and allows placing elements at
4713   arbitrary position and size, defined by \a rect.
4714 
4715   The alignment or rect can be set via \ref setInsetAlignment or \ref setInsetRect, respectively.
4716 
4717   This is the layout that every QCPAxisRect has as \ref QCPAxisRect::insetLayout.
4718 */
4719 
4720 /* start documentation of inline functions */
4721 
4722 /*! \fn virtual void QCPLayoutInset::simplify()
4723 
4724   The QCPInsetLayout does not need simplification since it can never have empty cells due to its
4725   linear index structure. This method does nothing.
4726 */
4727 
4728 /* end documentation of inline functions */
4729 
4730 /*!
4731   Creates an instance of QCPLayoutInset and sets default values.
4732 */
QCPLayoutInset()4733 QCPLayoutInset::QCPLayoutInset()
4734 {
4735 }
4736 
~QCPLayoutInset()4737 QCPLayoutInset::~QCPLayoutInset()
4738 {
4739   // clear all child layout elements. This is important because only the specific layouts know how
4740   // to handle removing elements (clear calls virtual removeAt method to do that).
4741   clear();
4742 }
4743 
4744 /*!
4745   Returns the placement type of the element with the specified \a index.
4746 */
insetPlacement(int index) const4747 QCPLayoutInset::InsetPlacement QCPLayoutInset::insetPlacement(int index) const
4748 {
4749   if (elementAt(index))
4750     return mInsetPlacement.at(index);
4751   else
4752   {
4753     qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
4754     return ipFree;
4755   }
4756 }
4757 
4758 /*!
4759   Returns the alignment of the element with the specified \a index. The alignment only has a
4760   meaning, if the inset placement (\ref setInsetPlacement) is \ref ipBorderAligned.
4761 */
insetAlignment(int index) const4762 Qt::Alignment QCPLayoutInset::insetAlignment(int index) const
4763 {
4764   if (elementAt(index))
4765     return mInsetAlignment.at(index);
4766   else
4767   {
4768     qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
4769     return Qt::Alignment {};
4770   }
4771 }
4772 
4773 /*!
4774   Returns the rect of the element with the specified \a index. The rect only has a
4775   meaning, if the inset placement (\ref setInsetPlacement) is \ref ipFree.
4776 */
insetRect(int index) const4777 QRectF QCPLayoutInset::insetRect(int index) const
4778 {
4779   if (elementAt(index))
4780     return mInsetRect.at(index);
4781   else
4782   {
4783     qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
4784     return QRectF();
4785   }
4786 }
4787 
4788 /*!
4789   Sets the inset placement type of the element with the specified \a index to \a placement.
4790 
4791   \see InsetPlacement
4792 */
setInsetPlacement(int index,QCPLayoutInset::InsetPlacement placement)4793 void QCPLayoutInset::setInsetPlacement(int index, QCPLayoutInset::InsetPlacement placement)
4794 {
4795   if (elementAt(index))
4796     mInsetPlacement[index] = placement;
4797   else
4798     qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
4799 }
4800 
4801 /*!
4802   If the inset placement (\ref setInsetPlacement) is \ref ipBorderAligned, this function
4803   is used to set the alignment of the element with the specified \a index to \a alignment.
4804 
4805   \a alignment is an or combination of the following alignment flags: Qt::AlignLeft,
4806   Qt::AlignHCenter, Qt::AlighRight, Qt::AlignTop, Qt::AlignVCenter, Qt::AlignBottom. Any other
4807   alignment flags will be ignored.
4808 */
setInsetAlignment(int index,Qt::Alignment alignment)4809 void QCPLayoutInset::setInsetAlignment(int index, Qt::Alignment alignment)
4810 {
4811   if (elementAt(index))
4812     mInsetAlignment[index] = alignment;
4813   else
4814     qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
4815 }
4816 
4817 /*!
4818   If the inset placement (\ref setInsetPlacement) is \ref ipFree, this function is used to set the
4819   position and size of the element with the specified \a index to \a rect.
4820 
4821   \a rect is given in fractions of the whole inset layout rect. So an inset with rect (0, 0, 1, 1)
4822   will span the entire layout. An inset with rect (0.6, 0.1, 0.35, 0.35) will be in the top right
4823   corner of the layout, with 35% width and height of the parent layout.
4824 
4825   Note that the minimum and maximum sizes of the embedded element (\ref
4826   QCPLayoutElement::setMinimumSize, \ref QCPLayoutElement::setMaximumSize) are enforced.
4827 */
setInsetRect(int index,const QRectF & rect)4828 void QCPLayoutInset::setInsetRect(int index, const QRectF &rect)
4829 {
4830   if (elementAt(index))
4831     mInsetRect[index] = rect;
4832   else
4833     qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
4834 }
4835 
4836 /* inherits documentation from base class */
updateLayout()4837 void QCPLayoutInset::updateLayout()
4838 {
4839   for (int i=0; i<mElements.size(); ++i)
4840   {
4841     QRect insetRect;
4842     QSize finalMinSize, finalMaxSize;
4843     QSize minSizeHint = mElements.at(i)->minimumSizeHint();
4844     QSize maxSizeHint = mElements.at(i)->maximumSizeHint();
4845     finalMinSize.setWidth(mElements.at(i)->minimumSize().width() > 0 ? mElements.at(i)->minimumSize().width() : minSizeHint.width());
4846     finalMinSize.setHeight(mElements.at(i)->minimumSize().height() > 0 ? mElements.at(i)->minimumSize().height() : minSizeHint.height());
4847     finalMaxSize.setWidth(mElements.at(i)->maximumSize().width() < QWIDGETSIZE_MAX ? mElements.at(i)->maximumSize().width() : maxSizeHint.width());
4848     finalMaxSize.setHeight(mElements.at(i)->maximumSize().height() < QWIDGETSIZE_MAX ? mElements.at(i)->maximumSize().height() : maxSizeHint.height());
4849     if (mInsetPlacement.at(i) == ipFree)
4850     {
4851       insetRect = QRect(rect().x()+rect().width()*mInsetRect.at(i).x(),
4852                         rect().y()+rect().height()*mInsetRect.at(i).y(),
4853                         rect().width()*mInsetRect.at(i).width(),
4854                         rect().height()*mInsetRect.at(i).height());
4855       if (insetRect.size().width() < finalMinSize.width())
4856         insetRect.setWidth(finalMinSize.width());
4857       if (insetRect.size().height() < finalMinSize.height())
4858         insetRect.setHeight(finalMinSize.height());
4859       if (insetRect.size().width() > finalMaxSize.width())
4860         insetRect.setWidth(finalMaxSize.width());
4861       if (insetRect.size().height() > finalMaxSize.height())
4862         insetRect.setHeight(finalMaxSize.height());
4863     } else if (mInsetPlacement.at(i) == ipBorderAligned)
4864     {
4865       insetRect.setSize(finalMinSize);
4866       Qt::Alignment al = mInsetAlignment.at(i);
4867       if (al.testFlag(Qt::AlignLeft)) insetRect.moveLeft(rect().x());
4868       else if (al.testFlag(Qt::AlignRight)) insetRect.moveRight(rect().x()+rect().width());
4869       else insetRect.moveLeft(rect().x()+rect().width()*0.5-finalMinSize.width()*0.5); // default to Qt::AlignHCenter
4870       if (al.testFlag(Qt::AlignTop)) insetRect.moveTop(rect().y());
4871       else if (al.testFlag(Qt::AlignBottom)) insetRect.moveBottom(rect().y()+rect().height());
4872       else insetRect.moveTop(rect().y()+rect().height()*0.5-finalMinSize.height()*0.5); // default to Qt::AlignVCenter
4873     }
4874     mElements.at(i)->setOuterRect(insetRect);
4875   }
4876 }
4877 
4878 /* inherits documentation from base class */
elementCount() const4879 int QCPLayoutInset::elementCount() const
4880 {
4881   return mElements.size();
4882 }
4883 
4884 /* inherits documentation from base class */
elementAt(int index) const4885 QCPLayoutElement *QCPLayoutInset::elementAt(int index) const
4886 {
4887   if (index >= 0 && index < mElements.size())
4888     return mElements.at(index);
4889   else
4890     return 0;
4891 }
4892 
4893 /* inherits documentation from base class */
takeAt(int index)4894 QCPLayoutElement *QCPLayoutInset::takeAt(int index)
4895 {
4896   if (QCPLayoutElement *el = elementAt(index))
4897   {
4898     releaseElement(el);
4899     mElements.removeAt(index);
4900     mInsetPlacement.removeAt(index);
4901     mInsetAlignment.removeAt(index);
4902     mInsetRect.removeAt(index);
4903     return el;
4904   } else
4905   {
4906     qDebug() << Q_FUNC_INFO << "Attempt to take invalid index:" << index;
4907     return 0;
4908   }
4909 }
4910 
4911 /* inherits documentation from base class */
take(QCPLayoutElement * element)4912 bool QCPLayoutInset::take(QCPLayoutElement *element)
4913 {
4914   if (element)
4915   {
4916     for (int i=0; i<elementCount(); ++i)
4917     {
4918       if (elementAt(i) == element)
4919       {
4920         takeAt(i);
4921         return true;
4922       }
4923     }
4924     qDebug() << Q_FUNC_INFO << "Element not in this layout, couldn't take";
4925   } else
4926     qDebug() << Q_FUNC_INFO << "Can't take null element";
4927   return false;
4928 }
4929 
4930 /*!
4931   The inset layout is sensitive to events only at areas where its (visible) child elements are
4932   sensitive. If the selectTest method of any of the child elements returns a positive number for \a
4933   pos, this method returns a value corresponding to 0.99 times the parent plot's selection
4934   tolerance. The inset layout is not selectable itself by default. So if \a onlySelectable is true,
4935   -1.0 is returned.
4936 
4937   See \ref QCPLayerable::selectTest for a general explanation of this virtual method.
4938 */
selectTest(const QPointF & pos,bool onlySelectable,QVariant * details) const4939 double QCPLayoutInset::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
4940 {
4941   Q_UNUSED(details)
4942   if (onlySelectable)
4943     return -1;
4944 
4945   for (int i=0; i<mElements.size(); ++i)
4946   {
4947     // inset layout shall only return positive selectTest, if actually an inset object is at pos
4948     // else it would block the entire underlying QCPAxisRect with its surface.
4949     if (mElements.at(i)->realVisibility() && mElements.at(i)->selectTest(pos, onlySelectable) >= 0)
4950       return mParentPlot->selectionTolerance()*0.99;
4951   }
4952   return -1;
4953 }
4954 
4955 /*!
4956   Adds the specified \a element to the layout as an inset aligned at the border (\ref
4957   setInsetAlignment is initialized with \ref ipBorderAligned). The alignment is set to \a
4958   alignment.
4959 
4960   \a alignment is an or combination of the following alignment flags: Qt::AlignLeft,
4961   Qt::AlignHCenter, Qt::AlighRight, Qt::AlignTop, Qt::AlignVCenter, Qt::AlignBottom. Any other
4962   alignment flags will be ignored.
4963 
4964   \see addElement(QCPLayoutElement *element, const QRectF &rect)
4965 */
addElement(QCPLayoutElement * element,Qt::Alignment alignment)4966 void QCPLayoutInset::addElement(QCPLayoutElement *element, Qt::Alignment alignment)
4967 {
4968   if (element)
4969   {
4970     if (element->layout()) // remove from old layout first
4971       element->layout()->take(element);
4972     mElements.append(element);
4973     mInsetPlacement.append(ipBorderAligned);
4974     mInsetAlignment.append(alignment);
4975     mInsetRect.append(QRectF(0.6, 0.6, 0.4, 0.4));
4976     adoptElement(element);
4977   } else
4978     qDebug() << Q_FUNC_INFO << "Can't add null element";
4979 }
4980 
4981 /*!
4982   Adds the specified \a element to the layout as an inset with free positioning/sizing (\ref
4983   setInsetAlignment is initialized with \ref ipFree). The position and size is set to \a
4984   rect.
4985 
4986   \a rect is given in fractions of the whole inset layout rect. So an inset with rect (0, 0, 1, 1)
4987   will span the entire layout. An inset with rect (0.6, 0.1, 0.35, 0.35) will be in the top right
4988   corner of the layout, with 35% width and height of the parent layout.
4989 
4990   \see addElement(QCPLayoutElement *element, Qt::Alignment alignment)
4991 */
addElement(QCPLayoutElement * element,const QRectF & rect)4992 void QCPLayoutInset::addElement(QCPLayoutElement *element, const QRectF &rect)
4993 {
4994   if (element)
4995   {
4996     if (element->layout()) // remove from old layout first
4997       element->layout()->take(element);
4998     mElements.append(element);
4999     mInsetPlacement.append(ipFree);
5000     mInsetAlignment.append(Qt::AlignRight|Qt::AlignTop);
5001     mInsetRect.append(rect);
5002     adoptElement(element);
5003   } else
5004     qDebug() << Q_FUNC_INFO << "Can't add null element";
5005 }
5006 /* end of 'src/layout.cpp' */
5007 
5008 
5009 /* including file 'src/lineending.cpp', size 11536                           */
5010 /* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
5011 
5012 ////////////////////////////////////////////////////////////////////////////////////////////////////
5013 //////////////////// QCPLineEnding
5014 ////////////////////////////////////////////////////////////////////////////////////////////////////
5015 
5016 /*! \class QCPLineEnding
5017   \brief Handles the different ending decorations for line-like items
5018 
5019   \image html QCPLineEnding.png "The various ending styles currently supported"
5020 
5021   For every ending a line-like item has, an instance of this class exists. For example, QCPItemLine
5022   has two endings which can be set with QCPItemLine::setHead and QCPItemLine::setTail.
5023 
5024   The styles themselves are defined via the enum QCPLineEnding::EndingStyle. Most decorations can
5025   be modified regarding width and length, see \ref setWidth and \ref setLength. The direction of
5026   the ending decoration (e.g. direction an arrow is pointing) is controlled by the line-like item.
5027   For example, when both endings of a QCPItemLine are set to be arrows, they will point to opposite
5028   directions, e.g. "outward". This can be changed by \ref setInverted, which would make the
5029   respective arrow point inward.
5030 
5031   Note that due to the overloaded QCPLineEnding constructor, you may directly specify a
5032   QCPLineEnding::EndingStyle where actually a QCPLineEnding is expected, e.g.
5033   \snippet documentation/doc-code-snippets/mainwindow.cpp qcplineending-sethead
5034 */
5035 
5036 /*!
5037   Creates a QCPLineEnding instance with default values (style \ref esNone).
5038 */
QCPLineEnding()5039 QCPLineEnding::QCPLineEnding() :
5040   mStyle(esNone),
5041   mWidth(8),
5042   mLength(10),
5043   mInverted(false)
5044 {
5045 }
5046 
5047 /*!
5048   Creates a QCPLineEnding instance with the specified values.
5049 */
QCPLineEnding(QCPLineEnding::EndingStyle style,double width,double length,bool inverted)5050 QCPLineEnding::QCPLineEnding(QCPLineEnding::EndingStyle style, double width, double length, bool inverted) :
5051   mStyle(style),
5052   mWidth(width),
5053   mLength(length),
5054   mInverted(inverted)
5055 {
5056 }
5057 
5058 /*!
5059   Sets the style of the ending decoration.
5060 */
setStyle(QCPLineEnding::EndingStyle style)5061 void QCPLineEnding::setStyle(QCPLineEnding::EndingStyle style)
5062 {
5063   mStyle = style;
5064 }
5065 
5066 /*!
5067   Sets the width of the ending decoration, if the style supports it. On arrows, for example, the
5068   width defines the size perpendicular to the arrow's pointing direction.
5069 
5070   \see setLength
5071 */
setWidth(double width)5072 void QCPLineEnding::setWidth(double width)
5073 {
5074   mWidth = width;
5075 }
5076 
5077 /*!
5078   Sets the length of the ending decoration, if the style supports it. On arrows, for example, the
5079   length defines the size in pointing direction.
5080 
5081   \see setWidth
5082 */
setLength(double length)5083 void QCPLineEnding::setLength(double length)
5084 {
5085   mLength = length;
5086 }
5087 
5088 /*!
5089   Sets whether the ending decoration shall be inverted. For example, an arrow decoration will point
5090   inward when \a inverted is set to true.
5091 
5092   Note that also the \a width direction is inverted. For symmetrical ending styles like arrows or
5093   discs, this doesn't make a difference. However, asymmetric styles like \ref esHalfBar are
5094   affected by it, which can be used to control to which side the half bar points to.
5095 */
setInverted(bool inverted)5096 void QCPLineEnding::setInverted(bool inverted)
5097 {
5098   mInverted = inverted;
5099 }
5100 
5101 /*! \internal
5102 
5103   Returns the maximum pixel radius the ending decoration might cover, starting from the position
5104   the decoration is drawn at (typically a line ending/\ref QCPItemPosition of an item).
5105 
5106   This is relevant for clipping. Only omit painting of the decoration when the position where the
5107   decoration is supposed to be drawn is farther away from the clipping rect than the returned
5108   distance.
5109 */
boundingDistance() const5110 double QCPLineEnding::boundingDistance() const
5111 {
5112   switch (mStyle)
5113   {
5114     case esNone:
5115       return 0;
5116 
5117     case esFlatArrow:
5118     case esSpikeArrow:
5119     case esLineArrow:
5120     case esSkewedBar:
5121       return qSqrt(mWidth*mWidth+mLength*mLength); // items that have width and length
5122 
5123     case esDisc:
5124     case esSquare:
5125     case esDiamond:
5126     case esBar:
5127     case esHalfBar:
5128       return mWidth*1.42; // items that only have a width -> width*sqrt(2)
5129 
5130   }
5131   return 0;
5132 }
5133 
5134 /*!
5135   Starting from the origin of this line ending (which is style specific), returns the length
5136   covered by the line ending symbol, in backward direction.
5137 
5138   For example, the \ref esSpikeArrow has a shorter real length than a \ref esFlatArrow, even if
5139   both have the same \ref setLength value, because the spike arrow has an inward curved back, which
5140   reduces the length along its center axis (the drawing origin for arrows is at the tip).
5141 
5142   This function is used for precise, style specific placement of line endings, for example in
5143   QCPAxes.
5144 */
realLength() const5145 double QCPLineEnding::realLength() const
5146 {
5147   switch (mStyle)
5148   {
5149     case esNone:
5150     case esLineArrow:
5151     case esSkewedBar:
5152     case esBar:
5153     case esHalfBar:
5154       return 0;
5155 
5156     case esFlatArrow:
5157       return mLength;
5158 
5159     case esDisc:
5160     case esSquare:
5161     case esDiamond:
5162       return mWidth*0.5;
5163 
5164     case esSpikeArrow:
5165       return mLength*0.8;
5166   }
5167   return 0;
5168 }
5169 
5170 /*! \internal
5171 
5172   Draws the line ending with the specified \a painter at the position \a pos. The direction of the
5173   line ending is controlled with \a dir.
5174 */
draw(QCPPainter * painter,const QCPVector2D & pos,const QCPVector2D & dir) const5175 void QCPLineEnding::draw(QCPPainter *painter, const QCPVector2D &pos, const QCPVector2D &dir) const
5176 {
5177   if (mStyle == esNone)
5178     return;
5179 
5180   QCPVector2D lengthVec = dir.normalized() * mLength*(mInverted ? -1 : 1);
5181   if (lengthVec.isNull())
5182     lengthVec = QCPVector2D(1, 0);
5183   QCPVector2D widthVec = dir.normalized().perpendicular() * mWidth*0.5*(mInverted ? -1 : 1);
5184 
5185   QPen penBackup = painter->pen();
5186   QBrush brushBackup = painter->brush();
5187   QPen miterPen = penBackup;
5188   miterPen.setJoinStyle(Qt::MiterJoin); // to make arrow heads spikey
5189   QBrush brush(painter->pen().color(), Qt::SolidPattern);
5190   switch (mStyle)
5191   {
5192     case esNone: break;
5193     case esFlatArrow:
5194     {
5195       QPointF points[3] = {pos.toPointF(),
5196                            (pos-lengthVec+widthVec).toPointF(),
5197                            (pos-lengthVec-widthVec).toPointF()
5198                           };
5199       painter->setPen(miterPen);
5200       painter->setBrush(brush);
5201       painter->drawConvexPolygon(points, 3);
5202       painter->setBrush(brushBackup);
5203       painter->setPen(penBackup);
5204       break;
5205     }
5206     case esSpikeArrow:
5207     {
5208       QPointF points[4] = {pos.toPointF(),
5209                            (pos-lengthVec+widthVec).toPointF(),
5210                            (pos-lengthVec*0.8).toPointF(),
5211                            (pos-lengthVec-widthVec).toPointF()
5212                           };
5213       painter->setPen(miterPen);
5214       painter->setBrush(brush);
5215       painter->drawConvexPolygon(points, 4);
5216       painter->setBrush(brushBackup);
5217       painter->setPen(penBackup);
5218       break;
5219     }
5220     case esLineArrow:
5221     {
5222       QPointF points[3] = {(pos-lengthVec+widthVec).toPointF(),
5223                            pos.toPointF(),
5224                            (pos-lengthVec-widthVec).toPointF()
5225                           };
5226       painter->setPen(miterPen);
5227       painter->drawPolyline(points, 3);
5228       painter->setPen(penBackup);
5229       break;
5230     }
5231     case esDisc:
5232     {
5233       painter->setBrush(brush);
5234       painter->drawEllipse(pos.toPointF(),  mWidth*0.5, mWidth*0.5);
5235       painter->setBrush(brushBackup);
5236       break;
5237     }
5238     case esSquare:
5239     {
5240       QCPVector2D widthVecPerp = widthVec.perpendicular();
5241       QPointF points[4] = {(pos-widthVecPerp+widthVec).toPointF(),
5242                            (pos-widthVecPerp-widthVec).toPointF(),
5243                            (pos+widthVecPerp-widthVec).toPointF(),
5244                            (pos+widthVecPerp+widthVec).toPointF()
5245                           };
5246       painter->setPen(miterPen);
5247       painter->setBrush(brush);
5248       painter->drawConvexPolygon(points, 4);
5249       painter->setBrush(brushBackup);
5250       painter->setPen(penBackup);
5251       break;
5252     }
5253     case esDiamond:
5254     {
5255       QCPVector2D widthVecPerp = widthVec.perpendicular();
5256       QPointF points[4] = {(pos-widthVecPerp).toPointF(),
5257                            (pos-widthVec).toPointF(),
5258                            (pos+widthVecPerp).toPointF(),
5259                            (pos+widthVec).toPointF()
5260                           };
5261       painter->setPen(miterPen);
5262       painter->setBrush(brush);
5263       painter->drawConvexPolygon(points, 4);
5264       painter->setBrush(brushBackup);
5265       painter->setPen(penBackup);
5266       break;
5267     }
5268     case esBar:
5269     {
5270       painter->drawLine((pos+widthVec).toPointF(), (pos-widthVec).toPointF());
5271       break;
5272     }
5273     case esHalfBar:
5274     {
5275       painter->drawLine((pos+widthVec).toPointF(), pos.toPointF());
5276       break;
5277     }
5278     case esSkewedBar:
5279     {
5280       if (qFuzzyIsNull(painter->pen().widthF()) && !painter->modes().testFlag(QCPPainter::pmNonCosmetic))
5281       {
5282         // if drawing with cosmetic pen (perfectly thin stroke, happens only in vector exports), draw bar exactly on tip of line
5283         painter->drawLine((pos+widthVec+lengthVec*0.2*(mInverted?-1:1)).toPointF(),
5284                           (pos-widthVec-lengthVec*0.2*(mInverted?-1:1)).toPointF());
5285       } else
5286       {
5287         // if drawing with thick (non-cosmetic) pen, shift bar a little in line direction to prevent line from sticking through bar slightly
5288         painter->drawLine((pos+widthVec+lengthVec*0.2*(mInverted?-1:1)+dir.normalized()*qMax(1.0f, (float)painter->pen().widthF())*0.5f).toPointF(),
5289                           (pos-widthVec-lengthVec*0.2*(mInverted?-1:1)+dir.normalized()*qMax(1.0f, (float)painter->pen().widthF())*0.5f).toPointF());
5290       }
5291       break;
5292     }
5293   }
5294 }
5295 
5296 /*! \internal
5297   \overload
5298 
5299   Draws the line ending. The direction is controlled with the \a angle parameter in radians.
5300 */
draw(QCPPainter * painter,const QCPVector2D & pos,double angle) const5301 void QCPLineEnding::draw(QCPPainter *painter, const QCPVector2D &pos, double angle) const
5302 {
5303   draw(painter, pos, QCPVector2D(qCos(angle), qSin(angle)));
5304 }
5305 /* end of 'src/lineending.cpp' */
5306 
5307 
5308 /* including file 'src/axis/axisticker.cpp', size 18664                      */
5309 /* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
5310 
5311 ////////////////////////////////////////////////////////////////////////////////////////////////////
5312 //////////////////// QCPAxisTicker
5313 ////////////////////////////////////////////////////////////////////////////////////////////////////
5314 /*! \class QCPAxisTicker
5315   \brief The base class tick generator used by QCPAxis to create tick positions and tick labels
5316 
5317   Each QCPAxis has an internal QCPAxisTicker (or a subclass) in order to generate tick positions
5318   and tick labels for the current axis range. The ticker of an axis can be set via \ref
5319   QCPAxis::setTicker. Since that method takes a <tt>QSharedPointer<QCPAxisTicker></tt>, multiple
5320   axes can share the same ticker instance.
5321 
5322   This base class generates normal tick coordinates and numeric labels for linear axes. It picks a
5323   reasonable tick step (the separation between ticks) which results in readable tick labels. The
5324   number of ticks that should be approximately generated can be set via \ref setTickCount.
5325   Depending on the current tick step strategy (\ref setTickStepStrategy), the algorithm either
5326   sacrifices readability to better match the specified tick count (\ref
5327   QCPAxisTicker::tssMeetTickCount) or relaxes the tick count in favor of better tick steps (\ref
5328   QCPAxisTicker::tssReadability), which is the default.
5329 
5330   The following more specialized axis ticker subclasses are available, see details in the
5331   respective class documentation:
5332 
5333   <center>
5334   <table>
5335   <tr><td style="text-align:right; padding: 0 1em">QCPAxisTickerFixed</td><td>\image html axisticker-fixed.png</td></tr>
5336   <tr><td style="text-align:right; padding: 0 1em">QCPAxisTickerLog</td><td>\image html axisticker-log.png</td></tr>
5337   <tr><td style="text-align:right; padding: 0 1em">QCPAxisTickerPi</td><td>\image html axisticker-pi.png</td></tr>
5338   <tr><td style="text-align:right; padding: 0 1em">QCPAxisTickerText</td><td>\image html axisticker-text.png</td></tr>
5339   <tr><td style="text-align:right; padding: 0 1em">QCPAxisTickerDateTime</td><td>\image html axisticker-datetime.png</td></tr>
5340   <tr><td style="text-align:right; padding: 0 1em">QCPAxisTickerTime</td><td>\image html axisticker-time.png
5341     \image html axisticker-time2.png</td></tr>
5342   </table>
5343   </center>
5344 
5345   \section axisticker-subclassing Creating own axis tickers
5346 
5347   Creating own axis tickers can be achieved very easily by sublassing QCPAxisTicker and
5348   reimplementing some or all of the available virtual methods.
5349 
5350   In the simplest case you might wish to just generate different tick steps than the other tickers,
5351   so you only reimplement the method \ref getTickStep. If you additionally want control over the
5352   string that will be shown as tick label, reimplement \ref getTickLabel.
5353 
5354   If you wish to have complete control, you can generate the tick vectors and tick label vectors
5355   yourself by reimplementing \ref createTickVector and \ref createLabelVector. The default
5356   implementations use the previously mentioned virtual methods \ref getTickStep and \ref
5357   getTickLabel, but your reimplementations don't necessarily need to do so. For example in the case
5358   of unequal tick steps, the method \ref getTickStep loses its usefulness and can be ignored.
5359 
5360   The sub tick count between major ticks can be controlled with \ref getSubTickCount. Full sub tick
5361   placement control is obtained by reimplementing \ref createSubTickVector.
5362 
5363   See the documentation of all these virtual methods in QCPAxisTicker for detailed information
5364   about the parameters and expected return values.
5365 */
5366 
5367 /*!
5368   Constructs the ticker and sets reasonable default values. Axis tickers are commonly created
5369   managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker.
5370 */
QCPAxisTicker()5371 QCPAxisTicker::QCPAxisTicker() :
5372   mTickStepStrategy(tssReadability),
5373   mTickCount(5),
5374   mTickOrigin(0)
5375 {
5376 }
5377 
~QCPAxisTicker()5378 QCPAxisTicker::~QCPAxisTicker()
5379 {
5380 
5381 }
5382 
5383 /*!
5384   Sets which strategy the axis ticker follows when choosing the size of the tick step. For the
5385   available strategies, see \ref TickStepStrategy.
5386 */
setTickStepStrategy(QCPAxisTicker::TickStepStrategy strategy)5387 void QCPAxisTicker::setTickStepStrategy(QCPAxisTicker::TickStepStrategy strategy)
5388 {
5389   mTickStepStrategy = strategy;
5390 }
5391 
5392 /*!
5393   Sets how many ticks this ticker shall aim to generate across the axis range. Note that \a count
5394   is not guaranteed to be matched exactly, as generating readable tick intervals may conflict with
5395   the requested number of ticks.
5396 
5397   Whether the readability has priority over meeting the requested \a count can be specified with
5398   \ref setTickStepStrategy.
5399 */
setTickCount(int count)5400 void QCPAxisTicker::setTickCount(int count)
5401 {
5402   if (count > 0)
5403     mTickCount = count;
5404   else
5405     qDebug() << Q_FUNC_INFO << "tick count must be greater than zero:" << count;
5406 }
5407 
5408 /*!
5409   Sets the mathematical coordinate (or "offset") of the zeroth tick. This tick coordinate is just a
5410   concept and doesn't need to be inside the currently visible axis range.
5411 
5412   By default \a origin is zero, which for example yields ticks {-5, 0, 5, 10, 15,...} when the tick
5413   step is five. If \a origin is now set to 1 instead, the correspondingly generated ticks would be
5414   {-4, 1, 6, 11, 16,...}.
5415 */
setTickOrigin(double origin)5416 void QCPAxisTicker::setTickOrigin(double origin)
5417 {
5418   mTickOrigin = origin;
5419 }
5420 
5421 /*!
5422   This is the method called by QCPAxis in order to actually generate tick coordinates (\a ticks),
5423   tick label strings (\a tickLabels) and sub tick coordinates (\a subTicks).
5424 
5425   The ticks are generated for the specified \a range. The generated labels typically follow the
5426   specified \a locale, \a formatChar and number \a precision, however this might be different (or
5427   even irrelevant) for certain QCPAxisTicker subclasses.
5428 
5429   The output parameter \a ticks is filled with the generated tick positions in axis coordinates.
5430   The output parameters \a subTicks and \a tickLabels are optional (set them to 0 if not needed)
5431   and are respectively filled with sub tick coordinates, and tick label strings belonging to \a
5432   ticks by index.
5433 */
generate(const QCPRange & range,const QLocale & locale,QChar formatChar,int precision,QVector<double> & ticks,QVector<double> * subTicks,QVector<QString> * tickLabels)5434 void QCPAxisTicker::generate(const QCPRange &range, const QLocale &locale, QChar formatChar, int precision, QVector<double> &ticks, QVector<double> *subTicks, QVector<QString> *tickLabels)
5435 {
5436   // generate (major) ticks:
5437   double tickStep = getTickStep(range);
5438   ticks = createTickVector(tickStep, range);
5439   trimTicks(range, ticks, true); // trim ticks to visible range plus one outer tick on each side (incase a subclass createTickVector creates more)
5440 
5441   // generate sub ticks between major ticks:
5442   if (subTicks)
5443   {
5444     if (ticks.size() > 0)
5445     {
5446       *subTicks = createSubTickVector(getSubTickCount(tickStep), ticks);
5447       trimTicks(range, *subTicks, false);
5448     } else
5449       *subTicks = QVector<double>();
5450   }
5451 
5452   // finally trim also outliers (no further clipping happens in axis drawing):
5453   trimTicks(range, ticks, false);
5454   // generate labels for visible ticks if requested:
5455   if (tickLabels)
5456     *tickLabels = createLabelVector(ticks, locale, formatChar, precision);
5457 }
5458 
5459 /*! \internal
5460 
5461   Takes the entire currently visible axis range and returns a sensible tick step in
5462   order to provide readable tick labels as well as a reasonable number of tick counts (see \ref
5463   setTickCount, \ref setTickStepStrategy).
5464 
5465   If a QCPAxisTicker subclass only wants a different tick step behaviour than the default
5466   implementation, it should reimplement this method. See \ref cleanMantissa for a possible helper
5467   function.
5468 */
getTickStep(const QCPRange & range)5469 double QCPAxisTicker::getTickStep(const QCPRange &range)
5470 {
5471   double exactStep = range.size()/(double)(mTickCount+1e-10); // mTickCount ticks on average, the small addition is to prevent jitter on exact integers
5472   return cleanMantissa(exactStep);
5473 }
5474 
5475 /*! \internal
5476 
5477   Takes the \a tickStep, i.e. the distance between two consecutive ticks, and returns
5478   an appropriate number of sub ticks for that specific tick step.
5479 
5480   Note that a returned sub tick count of e.g. 4 will split each tick interval into 5 sections.
5481 */
getSubTickCount(double tickStep)5482 int QCPAxisTicker::getSubTickCount(double tickStep)
5483 {
5484   int result = 1; // default to 1, if no proper value can be found
5485 
5486   // separate integer and fractional part of mantissa:
5487   double epsilon = 0.01;
5488   double intPartf;
5489   int intPart;
5490   double fracPart = modf(getMantissa(tickStep), &intPartf);
5491   intPart = intPartf;
5492 
5493   // handle cases with (almost) integer mantissa:
5494   if (fracPart < epsilon || 1.0-fracPart < epsilon)
5495   {
5496     if (1.0-fracPart < epsilon)
5497       ++intPart;
5498     switch (intPart)
5499     {
5500       case 1: result = 4; break; // 1.0 -> 0.2 substep
5501       case 2: result = 3; break; // 2.0 -> 0.5 substep
5502       case 3: result = 2; break; // 3.0 -> 1.0 substep
5503       case 4: result = 3; break; // 4.0 -> 1.0 substep
5504       case 5: result = 4; break; // 5.0 -> 1.0 substep
5505       case 6: result = 2; break; // 6.0 -> 2.0 substep
5506       case 7: result = 6; break; // 7.0 -> 1.0 substep
5507       case 8: result = 3; break; // 8.0 -> 2.0 substep
5508       case 9: result = 2; break; // 9.0 -> 3.0 substep
5509     }
5510   } else
5511   {
5512     // handle cases with significantly fractional mantissa:
5513     if (qAbs(fracPart-0.5) < epsilon) // *.5 mantissa
5514     {
5515       switch (intPart)
5516       {
5517         case 1: result = 2; break; // 1.5 -> 0.5 substep
5518         case 2: result = 4; break; // 2.5 -> 0.5 substep
5519         case 3: result = 4; break; // 3.5 -> 0.7 substep
5520         case 4: result = 2; break; // 4.5 -> 1.5 substep
5521         case 5: result = 4; break; // 5.5 -> 1.1 substep (won't occur with default getTickStep from here on)
5522         case 6: result = 4; break; // 6.5 -> 1.3 substep
5523         case 7: result = 2; break; // 7.5 -> 2.5 substep
5524         case 8: result = 4; break; // 8.5 -> 1.7 substep
5525         case 9: result = 4; break; // 9.5 -> 1.9 substep
5526       }
5527     }
5528     // if mantissa fraction isn't 0.0 or 0.5, don't bother finding good sub tick marks, leave default
5529   }
5530 
5531   return result;
5532 }
5533 
5534 /*! \internal
5535 
5536   This method returns the tick label string as it should be printed under the \a tick coordinate.
5537   If a textual number is returned, it should respect the provided \a locale, \a formatChar and \a
5538   precision.
5539 
5540   If the returned value contains exponentials of the form "2e5" and beautifully typeset powers is
5541   enabled in the QCPAxis number format (\ref QCPAxis::setNumberFormat), the exponential part will
5542   be formatted accordingly using multiplication symbol and superscript during rendering of the
5543   label automatically.
5544 */
getTickLabel(double tick,const QLocale & locale,QChar formatChar,int precision)5545 QString QCPAxisTicker::getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision)
5546 {
5547   return locale.toString(tick, formatChar.toLatin1(), precision);
5548 }
5549 
5550 /*! \internal
5551 
5552   Returns a vector containing all coordinates of sub ticks that should be drawn. It generates \a
5553   subTickCount sub ticks between each tick pair given in \a ticks.
5554 
5555   If a QCPAxisTicker subclass needs maximal control over the generated sub ticks, it should
5556   reimplement this method. Depending on the purpose of the subclass it doesn't necessarily need to
5557   base its result on \a subTickCount or \a ticks.
5558 */
createSubTickVector(int subTickCount,const QVector<double> & ticks)5559 QVector<double> QCPAxisTicker::createSubTickVector(int subTickCount, const QVector<double> &ticks)
5560 {
5561   QVector<double> result;
5562   if (subTickCount <= 0 || ticks.size() < 2)
5563     return result;
5564 
5565   result.reserve((ticks.size()-1)*subTickCount);
5566   for (int i=1; i<ticks.size(); ++i)
5567   {
5568     double subTickStep = (ticks.at(i)-ticks.at(i-1))/(double)(subTickCount+1);
5569     for (int k=1; k<=subTickCount; ++k)
5570       result.append(ticks.at(i-1) + k*subTickStep);
5571   }
5572   return result;
5573 }
5574 
5575 /*! \internal
5576 
5577   Returns a vector containing all coordinates of ticks that should be drawn. The default
5578   implementation generates ticks with a spacing of \a tickStep (mathematically starting at the tick
5579   step origin, see \ref setTickOrigin) distributed over the passed \a range.
5580 
5581   In order for the axis ticker to generate proper sub ticks, it is necessary that the first and
5582   last tick coordinates returned by this method are just below/above the provided \a range.
5583   Otherwise the outer intervals won't contain any sub ticks.
5584 
5585   If a QCPAxisTicker subclass needs maximal control over the generated ticks, it should reimplement
5586   this method. Depending on the purpose of the subclass it doesn't necessarily need to base its
5587   result on \a tickStep, e.g. when the ticks are spaced unequally like in the case of
5588   QCPAxisTickerLog.
5589 */
createTickVector(double tickStep,const QCPRange & range)5590 QVector<double> QCPAxisTicker::createTickVector(double tickStep, const QCPRange &range)
5591 {
5592   QVector<double> result;
5593   // Generate tick positions according to tickStep:
5594   qint64 firstStep = floor((range.lower-mTickOrigin)/tickStep); // do not use qFloor here, or we'll lose 64 bit precision
5595   qint64 lastStep = ceil((range.upper-mTickOrigin)/tickStep); // do not use qCeil here, or we'll lose 64 bit precision
5596   int tickcount = lastStep-firstStep+1;
5597   if (tickcount < 0) tickcount = 0;
5598   result.resize(tickcount);
5599   for (int i=0; i<tickcount; ++i)
5600     result[i] = mTickOrigin + (firstStep+i)*tickStep;
5601   return result;
5602 }
5603 
5604 /*! \internal
5605 
5606   Returns a vector containing all tick label strings corresponding to the tick coordinates provided
5607   in \a ticks. The default implementation calls \ref getTickLabel to generate the respective
5608   strings.
5609 
5610   It is possible but uncommon for QCPAxisTicker subclasses to reimplement this method, as
5611   reimplementing \ref getTickLabel often achieves the intended result easier.
5612 */
createLabelVector(const QVector<double> & ticks,const QLocale & locale,QChar formatChar,int precision)5613 QVector<QString> QCPAxisTicker::createLabelVector(const QVector<double> &ticks, const QLocale &locale, QChar formatChar, int precision)
5614 {
5615   QVector<QString> result;
5616   result.reserve(ticks.size());
5617   for (int i=0; i<ticks.size(); ++i)
5618     result.append(getTickLabel(ticks.at(i), locale, formatChar, precision));
5619   return result;
5620 }
5621 
5622 /*! \internal
5623 
5624   Removes tick coordinates from \a ticks which lie outside the specified \a range. If \a
5625   keepOneOutlier is true, it preserves one tick just outside the range on both sides, if present.
5626 
5627   The passed \a ticks must be sorted in ascending order.
5628 */
trimTicks(const QCPRange & range,QVector<double> & ticks,bool keepOneOutlier) const5629 void QCPAxisTicker::trimTicks(const QCPRange &range, QVector<double> &ticks, bool keepOneOutlier) const
5630 {
5631   bool lowFound = false;
5632   bool highFound = false;
5633   int lowIndex = 0;
5634   int highIndex = -1;
5635 
5636   for (int i=0; i < ticks.size(); ++i)
5637   {
5638     if (ticks.at(i) >= range.lower)
5639     {
5640       lowFound = true;
5641       lowIndex = i;
5642       break;
5643     }
5644   }
5645   for (int i=ticks.size()-1; i >= 0; --i)
5646   {
5647     if (ticks.at(i) <= range.upper)
5648     {
5649       highFound = true;
5650       highIndex = i;
5651       break;
5652     }
5653   }
5654 
5655   if (highFound && lowFound)
5656   {
5657     int trimFront = qMax(0, lowIndex-(keepOneOutlier ? 1 : 0));
5658     int trimBack = qMax(0, ticks.size()-(keepOneOutlier ? 2 : 1)-highIndex);
5659     if (trimFront > 0 || trimBack > 0)
5660       ticks = ticks.mid(trimFront, ticks.size()-trimFront-trimBack);
5661   } else // all ticks are either all below or all above the range
5662     ticks.clear();
5663 }
5664 
5665 /*! \internal
5666 
5667   Returns the coordinate contained in \a candidates which is closest to the provided \a target.
5668 
5669   This method assumes \a candidates is not empty and sorted in ascending order.
5670 */
pickClosest(double target,const QVector<double> & candidates) const5671 double QCPAxisTicker::pickClosest(double target, const QVector<double> &candidates) const
5672 {
5673   if (candidates.size() == 1)
5674     return candidates.first();
5675   QVector<double>::const_iterator it = std::lower_bound(candidates.constBegin(), candidates.constEnd(), target);
5676   if (it == candidates.constEnd())
5677     return *(it-1);
5678   else if (it == candidates.constBegin())
5679     return *it;
5680   else
5681     return target-*(it-1) < *it-target ? *(it-1) : *it;
5682 }
5683 
5684 /*! \internal
5685 
5686   Returns the decimal mantissa of \a input. Optionally, if \a magnitude is not set to zero, it also
5687   returns the magnitude of \a input as a power of 10.
5688 
5689   For example, an input of 142.6 will return a mantissa of 1.426 and a magnitude of 100.
5690 */
getMantissa(double input,double * magnitude) const5691 double QCPAxisTicker::getMantissa(double input, double *magnitude) const
5692 {
5693   const double mag = qPow(10.0, qFloor(qLn(input)/qLn(10.0)));
5694   if (magnitude) *magnitude = mag;
5695   return input/mag;
5696 }
5697 
5698 /*! \internal
5699 
5700   Returns a number that is close to \a input but has a clean, easier human readable mantissa. How
5701   strongly the mantissa is altered, and thus how strong the result deviates from the original \a
5702   input, depends on the current tick step strategy (see \ref setTickStepStrategy).
5703 */
cleanMantissa(double input) const5704 double QCPAxisTicker::cleanMantissa(double input) const
5705 {
5706   double magnitude;
5707   const double mantissa = getMantissa(input, &magnitude);
5708   switch (mTickStepStrategy)
5709   {
5710     case tssReadability:
5711     {
5712       return pickClosest(mantissa, QVector<double>() << 1.0 << 2.0 << 2.5 << 5.0 << 10.0)*magnitude;
5713     }
5714     case tssMeetTickCount:
5715     {
5716       // this gives effectively a mantissa of 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 6.0, 8.0, 10.0
5717       if (mantissa <= 5.0)
5718         return (int)(mantissa*2)/2.0*magnitude; // round digit after decimal point to 0.5
5719       else
5720         return (int)(mantissa/2.0)*2.0*magnitude; // round to first digit in multiples of 2
5721     }
5722   }
5723   return input;
5724 }
5725 /* end of 'src/axis/axisticker.cpp' */
5726 
5727 
5728 /* including file 'src/axis/axistickerdatetime.cpp', size 14443              */
5729 /* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
5730 
5731 ////////////////////////////////////////////////////////////////////////////////////////////////////
5732 //////////////////// QCPAxisTickerDateTime
5733 ////////////////////////////////////////////////////////////////////////////////////////////////////
5734 /*! \class QCPAxisTickerDateTime
5735   \brief Specialized axis ticker for calendar dates and times as axis ticks
5736 
5737   \image html axisticker-datetime.png
5738 
5739   This QCPAxisTicker subclass generates ticks that correspond to real calendar dates and times. The
5740   plot axis coordinate is interpreted as Unix Time, so seconds since Epoch (January 1, 1970, 00:00
5741   UTC). This is also used for example by QDateTime in the <tt>toTime_t()/setTime_t()</tt> methods
5742   with a precision of one second. Since Qt 4.7, millisecond accuracy can be obtained from QDateTime
5743   by using <tt>QDateTime::fromMSecsSinceEpoch()/1000.0</tt>. The static methods \ref dateTimeToKey
5744   and \ref keyToDateTime conveniently perform this conversion achieving a precision of one
5745   millisecond on all Qt versions.
5746 
5747   The format of the date/time display in the tick labels is controlled with \ref setDateTimeFormat.
5748   If a different time spec (time zone) shall be used, see \ref setDateTimeSpec.
5749 
5750   This ticker produces unequal tick spacing in order to provide intuitive date and time-of-day
5751   ticks. For example, if the axis range spans a few years such that there is one tick per year,
5752   ticks will be positioned on 1. January of every year. This is intuitive but, due to leap years,
5753   will result in slightly unequal tick intervals (visually unnoticeable). The same can be seen in
5754   the image above: even though the number of days varies month by month, this ticker generates
5755   ticks on the same day of each month.
5756 
5757   If you would like to change the date/time that is used as a (mathematical) starting date for the
5758   ticks, use the \ref setTickOrigin(const QDateTime &origin) method overload, which takes a
5759   QDateTime. If you pass 15. July, 9:45 to this method, the yearly ticks will end up on 15. July at
5760   9:45 of every year.
5761 
5762   The ticker can be created and assigned to an axis like this:
5763   \snippet documentation/doc-image-generator/mainwindow.cpp axistickerdatetime-creation
5764 
5765   \note If you rather wish to display relative times in terms of days, hours, minutes, seconds and
5766   milliseconds, and are not interested in the intricacies of real calendar dates with months and
5767   (leap) years, have a look at QCPAxisTickerTime instead.
5768 */
5769 
5770 /*!
5771   Constructs the ticker and sets reasonable default values. Axis tickers are commonly created
5772   managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker.
5773 */
QCPAxisTickerDateTime()5774 QCPAxisTickerDateTime::QCPAxisTickerDateTime() :
5775   mDateTimeFormat(QLatin1String("hh:mm:ss\ndd.MM.yy")),
5776   mDateTimeSpec(Qt::LocalTime),
5777   mDateStrategy(dsNone)
5778 {
5779   setTickCount(4);
5780 }
5781 
5782 /*!
5783   Sets the format in which dates and times are displayed as tick labels. For details about the \a
5784   format string, see the documentation of QDateTime::toString().
5785 
5786   Newlines can be inserted with "\n".
5787 
5788   \see setDateTimeSpec
5789 */
setDateTimeFormat(const QString & format)5790 void QCPAxisTickerDateTime::setDateTimeFormat(const QString &format)
5791 {
5792   mDateTimeFormat = format;
5793 }
5794 
5795 /*!
5796   Sets the time spec that is used for creating the tick labels from corresponding dates/times.
5797 
5798   The default value of QDateTime objects (and also QCPAxisTickerDateTime) is
5799   <tt>Qt::LocalTime</tt>. However, if the date time values passed to QCustomPlot (e.g. in the form
5800   of axis ranges or keys of a plottable) are given in the UTC spec, set \a spec to <tt>Qt::UTC</tt>
5801   to get the correct axis labels.
5802 
5803   \see setDateTimeFormat
5804 */
setDateTimeSpec(Qt::TimeSpec spec)5805 void QCPAxisTickerDateTime::setDateTimeSpec(Qt::TimeSpec spec)
5806 {
5807   mDateTimeSpec = spec;
5808 }
5809 
5810 /*!
5811   Sets the tick origin (see \ref QCPAxisTicker::setTickOrigin) in seconds since Epoch (1. Jan 1970,
5812   00:00 UTC). For the date time ticker it might be more intuitive to use the overload which
5813   directly takes a QDateTime, see \ref setTickOrigin(const QDateTime &origin).
5814 
5815   This is useful to define the month/day/time recurring at greater tick interval steps. For
5816   example, If you pass 15. July, 9:45 to this method and the tick interval happens to be one tick
5817   per year, the ticks will end up on 15. July at 9:45 of every year.
5818 */
setTickOrigin(double origin)5819 void QCPAxisTickerDateTime::setTickOrigin(double origin)
5820 {
5821   QCPAxisTicker::setTickOrigin(origin);
5822 }
5823 
5824 /*!
5825   Sets the tick origin (see \ref QCPAxisTicker::setTickOrigin) as a QDateTime \a origin.
5826 
5827   This is useful to define the month/day/time recurring at greater tick interval steps. For
5828   example, If you pass 15. July, 9:45 to this method and the tick interval happens to be one tick
5829   per year, the ticks will end up on 15. July at 9:45 of every year.
5830 */
setTickOrigin(const QDateTime & origin)5831 void QCPAxisTickerDateTime::setTickOrigin(const QDateTime &origin)
5832 {
5833   setTickOrigin(dateTimeToKey(origin));
5834 }
5835 
5836 /*! \internal
5837 
5838   Returns a sensible tick step with intervals appropriate for a date-time-display, such as weekly,
5839   monthly, bi-monthly, etc.
5840 
5841   Note that this tick step isn't used exactly when generating the tick vector in \ref
5842   createTickVector, but only as a guiding value requiring some correction for each individual tick
5843   interval. Otherwise this would lead to unintuitive date displays, e.g. jumping between first day
5844   in the month to the last day in the previous month from tick to tick, due to the non-uniform
5845   length of months. The same problem arises with leap years.
5846 
5847   \seebaseclassmethod
5848 */
getTickStep(const QCPRange & range)5849 double QCPAxisTickerDateTime::getTickStep(const QCPRange &range)
5850 {
5851   double result = range.size()/(double)(mTickCount+1e-10); // mTickCount ticks on average, the small addition is to prevent jitter on exact integers
5852 
5853   mDateStrategy = dsNone;
5854   if (result < 1) // ideal tick step is below 1 second -> use normal clean mantissa algorithm in units of seconds
5855   {
5856     result = cleanMantissa(result);
5857   } else if (result < 86400*30.4375*12) // below a year
5858   {
5859     result = pickClosest(result, QVector<double>()
5860                              << 1 << 2.5 << 5 << 10 << 15 << 30 << 60 << 2.5*60 << 5*60 << 10*60 << 15*60 << 30*60 << 60*60 // second, minute, hour range
5861                              << 3600*2 << 3600*3 << 3600*6 << 3600*12 << 3600*24 // hour to day range
5862                              << 86400*2 << 86400*5 << 86400*7 << 86400*14 << 86400*30.4375 << 86400*30.4375*2 << 86400*30.4375*3 << 86400*30.4375*6 << 86400*30.4375*12); // day, week, month range (avg. days per month includes leap years)
5863     if (result > 86400*30.4375-1) // month tick intervals or larger
5864       mDateStrategy = dsUniformDayInMonth;
5865     else if (result > 3600*24-1) // day tick intervals or larger
5866       mDateStrategy = dsUniformTimeInDay;
5867   } else // more than a year, go back to normal clean mantissa algorithm but in units of years
5868   {
5869     const double secondsPerYear = 86400*30.4375*12; // average including leap years
5870     result = cleanMantissa(result/secondsPerYear)*secondsPerYear;
5871     mDateStrategy = dsUniformDayInMonth;
5872   }
5873   return result;
5874 }
5875 
5876 /*! \internal
5877 
5878   Returns a sensible sub tick count with intervals appropriate for a date-time-display, such as weekly,
5879   monthly, bi-monthly, etc.
5880 
5881   \seebaseclassmethod
5882 */
getSubTickCount(double tickStep)5883 int QCPAxisTickerDateTime::getSubTickCount(double tickStep)
5884 {
5885   int result = QCPAxisTicker::getSubTickCount(tickStep);
5886   switch (qRound(tickStep)) // hand chosen subticks for specific minute/hour/day/week/month range (as specified in getTickStep)
5887   {
5888     case 5*60: result = 4; break;
5889     case 10*60: result = 1; break;
5890     case 15*60: result = 2; break;
5891     case 30*60: result = 1; break;
5892     case 60*60: result = 3; break;
5893     case 3600*2: result = 3; break;
5894     case 3600*3: result = 2; break;
5895     case 3600*6: result = 1; break;
5896     case 3600*12: result = 3; break;
5897     case 3600*24: result = 3; break;
5898     case 86400*2: result = 1; break;
5899     case 86400*5: result = 4; break;
5900     case 86400*7: result = 6; break;
5901     case 86400*14: result = 1; break;
5902     case (int)(86400*30.4375+0.5): result = 3; break;
5903     case (int)(86400*30.4375*2+0.5): result = 1; break;
5904     case (int)(86400*30.4375*3+0.5): result = 2; break;
5905     case (int)(86400*30.4375*6+0.5): result = 5; break;
5906     case (int)(86400*30.4375*12+0.5): result = 3; break;
5907   }
5908   return result;
5909 }
5910 
5911 /*! \internal
5912 
5913   Generates a date/time tick label for tick coordinate \a tick, based on the currently set format
5914   (\ref setDateTimeFormat) and time spec (\ref setDateTimeSpec).
5915 
5916   \seebaseclassmethod
5917 */
getTickLabel(double tick,const QLocale & locale,QChar formatChar,int precision)5918 QString QCPAxisTickerDateTime::getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision)
5919 {
5920   Q_UNUSED(precision)
5921   Q_UNUSED(formatChar)
5922   return locale.toString(keyToDateTime(tick).toTimeSpec(mDateTimeSpec), mDateTimeFormat);
5923 }
5924 
5925 /*! \internal
5926 
5927   Uses the passed \a tickStep as a guiding value and applies corrections in order to obtain
5928   non-uniform tick intervals but intuitive tick labels, e.g. falling on the same day of each month.
5929 
5930   \seebaseclassmethod
5931 */
createTickVector(double tickStep,const QCPRange & range)5932 QVector<double> QCPAxisTickerDateTime::createTickVector(double tickStep, const QCPRange &range)
5933 {
5934   QVector<double> result = QCPAxisTicker::createTickVector(tickStep, range);
5935   if (!result.isEmpty())
5936   {
5937     if (mDateStrategy == dsUniformTimeInDay)
5938     {
5939       QDateTime uniformDateTime = keyToDateTime(mTickOrigin); // the time of this datetime will be set for all other ticks, if possible
5940       QDateTime tickDateTime;
5941       for (int i=0; i<result.size(); ++i)
5942       {
5943         tickDateTime = keyToDateTime(result.at(i));
5944         tickDateTime.setTime(uniformDateTime.time());
5945         result[i] = dateTimeToKey(tickDateTime);
5946       }
5947     } else if (mDateStrategy == dsUniformDayInMonth)
5948     {
5949       QDateTime uniformDateTime = keyToDateTime(mTickOrigin); // this day (in month) and time will be set for all other ticks, if possible
5950       QDateTime tickDateTime;
5951       for (int i=0; i<result.size(); ++i)
5952       {
5953         tickDateTime = keyToDateTime(result.at(i));
5954         tickDateTime.setTime(uniformDateTime.time());
5955         int thisUniformDay = uniformDateTime.date().day() <= tickDateTime.date().daysInMonth() ? uniformDateTime.date().day() : tickDateTime.date().daysInMonth(); // don't exceed month (e.g. try to set day 31 in February)
5956         if (thisUniformDay-tickDateTime.date().day() < -15) // with leap years involved, date month may jump backwards or forwards, and needs to be corrected before setting day
5957           tickDateTime = tickDateTime.addMonths(1);
5958         else if (thisUniformDay-tickDateTime.date().day() > 15) // with leap years involved, date month may jump backwards or forwards, and needs to be corrected before setting day
5959           tickDateTime = tickDateTime.addMonths(-1);
5960         tickDateTime.setDate(QDate(tickDateTime.date().year(), tickDateTime.date().month(), thisUniformDay));
5961         result[i] = dateTimeToKey(tickDateTime);
5962       }
5963     }
5964   }
5965   return result;
5966 }
5967 
5968 /*!
5969   A convenience method which turns \a key (in seconds since Epoch 1. Jan 1970, 00:00 UTC) into a
5970   QDateTime object. This can be used to turn axis coordinates to actual QDateTimes.
5971 
5972   The accuracy achieved by this method is one millisecond, irrespective of the used Qt version (it
5973   works around the lack of a QDateTime::fromMSecsSinceEpoch in Qt 4.6)
5974 
5975   \see dateTimeToKey
5976 */
keyToDateTime(double key)5977 QDateTime QCPAxisTickerDateTime::keyToDateTime(double key)
5978 {
5979 # if QT_VERSION < QT_VERSION_CHECK(4, 7, 0)
5980   return QDateTime::fromTime_t(key).addMSecs((key-(qint64)key)*1000);
5981 # else
5982   return QDateTime::fromMSecsSinceEpoch(key*1000.0);
5983 # endif
5984 }
5985 
5986 /*! \overload
5987 
5988   A convenience method which turns a QDateTime object into a double value that corresponds to
5989   seconds since Epoch (1. Jan 1970, 00:00 UTC). This is the format used as axis coordinates by
5990   QCPAxisTickerDateTime.
5991 
5992   The accuracy achieved by this method is one millisecond, irrespective of the used Qt version (it
5993   works around the lack of a QDateTime::toMSecsSinceEpoch in Qt 4.6)
5994 
5995   \see keyToDateTime
5996 */
dateTimeToKey(const QDateTime dateTime)5997 double QCPAxisTickerDateTime::dateTimeToKey(const QDateTime dateTime)
5998 {
5999 # if QT_VERSION < QT_VERSION_CHECK(4, 7, 0)
6000   return dateTime.toTime_t()+dateTime.time().msec()/1000.0;
6001 # else
6002   return dateTime.toMSecsSinceEpoch()/1000.0;
6003 # endif
6004 }
6005 
6006 /*! \overload
6007 
6008   A convenience method which turns a QDate object into a double value that corresponds to
6009   seconds since Epoch (1. Jan 1970, 00:00 UTC). This is the format used as axis coordinates by
6010   QCPAxisTickerDateTime.
6011 
6012   \see keyToDateTime
6013 */
dateTimeToKey(const QDate date)6014 double QCPAxisTickerDateTime::dateTimeToKey(const QDate date)
6015 {
6016 #if QT_VERSION < QT_VERSION_CHECK(4, 7, 0)
6017   return QDateTime(date).toTime_t();
6018 #elif QT_VERSION < QT_VERSION_CHECK(5, 14, 0)
6019   return QDateTime(date).toMSecsSinceEpoch()/1000.0;
6020 #else
6021   return date.startOfDay().toMSecsSinceEpoch()/1000.0;
6022 #endif
6023 }
6024 /* end of 'src/axis/axistickerdatetime.cpp' */
6025 
6026 
6027 /* including file 'src/axis/axistickertime.cpp', size 11747                  */
6028 /* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
6029 
6030 ////////////////////////////////////////////////////////////////////////////////////////////////////
6031 //////////////////// QCPAxisTickerTime
6032 ////////////////////////////////////////////////////////////////////////////////////////////////////
6033 /*! \class QCPAxisTickerTime
6034   \brief Specialized axis ticker for time spans in units of milliseconds to days
6035 
6036   \image html axisticker-time.png
6037 
6038   This QCPAxisTicker subclass generates ticks that corresponds to time intervals.
6039 
6040   The format of the time display in the tick labels is controlled with \ref setTimeFormat and \ref
6041   setFieldWidth. The time coordinate is in the unit of seconds with respect to the time coordinate
6042   zero. Unlike with QCPAxisTickerDateTime, the ticks don't correspond to a specific calendar date
6043   and time.
6044 
6045   The time can be displayed in milliseconds, seconds, minutes, hours and days. Depending on the
6046   largest available unit in the format specified with \ref setTimeFormat, any time spans above will
6047   be carried in that largest unit. So for example if the format string is "%m:%s" and a tick at
6048   coordinate value 7815 (being 2 hours, 10 minutes and 15 seconds) is created, the resulting tick
6049   label will show "130:15" (130 minutes, 15 seconds). If the format string is "%h:%m:%s", the hour
6050   unit will be used and the label will thus be "02:10:15". Negative times with respect to the axis
6051   zero will carry a leading minus sign.
6052 
6053   The ticker can be created and assigned to an axis like this:
6054   \snippet documentation/doc-image-generator/mainwindow.cpp axistickertime-creation
6055 
6056   Here is an example of a time axis providing time information in days, hours and minutes. Due to
6057   the axis range spanning a few days and the wanted tick count (\ref setTickCount), the ticker
6058   decided to use tick steps of 12 hours:
6059 
6060   \image html axisticker-time2.png
6061 
6062   The format string for this example is
6063   \snippet documentation/doc-image-generator/mainwindow.cpp axistickertime-creation-2
6064 
6065   \note If you rather wish to display calendar dates and times, have a look at QCPAxisTickerDateTime
6066   instead.
6067 */
6068 
6069 /*!
6070   Constructs the ticker and sets reasonable default values. Axis tickers are commonly created
6071   managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker.
6072 */
QCPAxisTickerTime()6073 QCPAxisTickerTime::QCPAxisTickerTime() :
6074   mTimeFormat(QLatin1String("%h:%m:%s")),
6075   mSmallestUnit(tuSeconds),
6076   mBiggestUnit(tuHours)
6077 {
6078   setTickCount(4);
6079   mFieldWidth[tuMilliseconds] = 3;
6080   mFieldWidth[tuSeconds] = 2;
6081   mFieldWidth[tuMinutes] = 2;
6082   mFieldWidth[tuHours] = 2;
6083   mFieldWidth[tuDays] = 1;
6084 
6085   mFormatPattern[tuMilliseconds] = QLatin1String("%z");
6086   mFormatPattern[tuSeconds] = QLatin1String("%s");
6087   mFormatPattern[tuMinutes] = QLatin1String("%m");
6088   mFormatPattern[tuHours] = QLatin1String("%h");
6089   mFormatPattern[tuDays] = QLatin1String("%d");
6090 }
6091 
6092 /*!
6093   Sets the format that will be used to display time in the tick labels.
6094 
6095   The available patterns are:
6096   - %%z for milliseconds
6097   - %%s for seconds
6098   - %%m for minutes
6099   - %%h for hours
6100   - %%d for days
6101 
6102   The field width (zero padding) can be controlled for each unit with \ref setFieldWidth.
6103 
6104   The largest unit that appears in \a format will carry all the remaining time of a certain tick
6105   coordinate, even if it overflows the natural limit of the unit. For example, if %%m is the
6106   largest unit it might become larger than 59 in order to consume larger time values. If on the
6107   other hand %%h is available, the minutes will wrap around to zero after 59 and the time will
6108   carry to the hour digit.
6109 */
setTimeFormat(const QString & format)6110 void QCPAxisTickerTime::setTimeFormat(const QString &format)
6111 {
6112   mTimeFormat = format;
6113 
6114   // determine smallest and biggest unit in format, to optimize unit replacement and allow biggest
6115   // unit to consume remaining time of a tick value and grow beyond its modulo (e.g. min > 59)
6116   mSmallestUnit = tuMilliseconds;
6117   mBiggestUnit = tuMilliseconds;
6118   bool hasSmallest = false;
6119   for (int i = tuMilliseconds; i <= tuDays; ++i)
6120   {
6121     TimeUnit unit = static_cast<TimeUnit>(i);
6122     if (mTimeFormat.contains(mFormatPattern.value(unit)))
6123     {
6124       if (!hasSmallest)
6125       {
6126         mSmallestUnit = unit;
6127         hasSmallest = true;
6128       }
6129       mBiggestUnit = unit;
6130     }
6131   }
6132 }
6133 
6134 /*!
6135   Sets the field widh of the specified \a unit to be \a width digits, when displayed in the tick
6136   label. If the number for the specific unit is shorter than \a width, it will be padded with an
6137   according number of zeros to the left in order to reach the field width.
6138 
6139   \see setTimeFormat
6140 */
setFieldWidth(QCPAxisTickerTime::TimeUnit unit,int width)6141 void QCPAxisTickerTime::setFieldWidth(QCPAxisTickerTime::TimeUnit unit, int width)
6142 {
6143   mFieldWidth[unit] = qMax(width, 1);
6144 }
6145 
6146 /*! \internal
6147 
6148   Returns the tick step appropriate for time displays, depending on the provided \a range and the
6149   smallest available time unit in the current format (\ref setTimeFormat). For example if the unit
6150   of seconds isn't available in the format, this method will not generate steps (like 2.5 minutes)
6151   that require sub-minute precision to be displayed correctly.
6152 
6153   \seebaseclassmethod
6154 */
getTickStep(const QCPRange & range)6155 double QCPAxisTickerTime::getTickStep(const QCPRange &range)
6156 {
6157   double result = range.size()/(double)(mTickCount+1e-10); // mTickCount ticks on average, the small addition is to prevent jitter on exact integers
6158 
6159   if (result < 1) // ideal tick step is below 1 second -> use normal clean mantissa algorithm in units of seconds
6160   {
6161     if (mSmallestUnit == tuMilliseconds)
6162       result = qMax(cleanMantissa(result), 0.001); // smallest tick step is 1 millisecond
6163     else // have no milliseconds available in format, so stick with 1 second tickstep
6164       result = 1.0;
6165   } else if (result < 3600*24) // below a day
6166   {
6167     // the filling of availableSteps seems a bit contorted but it fills in a sorted fashion and thus saves a post-fill sorting run
6168     QVector<double> availableSteps;
6169     // seconds range:
6170     if (mSmallestUnit <= tuSeconds)
6171       availableSteps << 1;
6172     if (mSmallestUnit == tuMilliseconds)
6173       availableSteps << 2.5; // only allow half second steps if milliseconds are there to display it
6174     else if (mSmallestUnit == tuSeconds)
6175       availableSteps << 2;
6176     if (mSmallestUnit <= tuSeconds)
6177       availableSteps << 5 << 10 << 15 << 30;
6178     // minutes range:
6179     if (mSmallestUnit <= tuMinutes)
6180       availableSteps << 1*60;
6181     if (mSmallestUnit <= tuSeconds)
6182       availableSteps << 2.5*60; // only allow half minute steps if seconds are there to display it
6183     else if (mSmallestUnit == tuMinutes)
6184       availableSteps << 2*60;
6185     if (mSmallestUnit <= tuMinutes)
6186       availableSteps << 5*60 << 10*60 << 15*60 << 30*60;
6187     // hours range:
6188     if (mSmallestUnit <= tuHours)
6189       availableSteps << 1*3600 << 2*3600 << 3*3600 << 6*3600 << 12*3600 << 24*3600;
6190     // pick available step that is most appropriate to approximate ideal step:
6191     result = pickClosest(result, availableSteps);
6192   } else // more than a day, go back to normal clean mantissa algorithm but in units of days
6193   {
6194     const double secondsPerDay = 3600*24;
6195     result = cleanMantissa(result/secondsPerDay)*secondsPerDay;
6196   }
6197   return result;
6198 }
6199 
6200 /*! \internal
6201 
6202   Returns the sub tick count appropriate for the provided \a tickStep and time displays.
6203 
6204   \seebaseclassmethod
6205 */
getSubTickCount(double tickStep)6206 int QCPAxisTickerTime::getSubTickCount(double tickStep)
6207 {
6208   int result = QCPAxisTicker::getSubTickCount(tickStep);
6209   switch (qRound(tickStep)) // hand chosen subticks for specific minute/hour/day range (as specified in getTickStep)
6210   {
6211     case 5*60: result = 4; break;
6212     case 10*60: result = 1; break;
6213     case 15*60: result = 2; break;
6214     case 30*60: result = 1; break;
6215     case 60*60: result = 3; break;
6216     case 3600*2: result = 3; break;
6217     case 3600*3: result = 2; break;
6218     case 3600*6: result = 1; break;
6219     case 3600*12: result = 3; break;
6220     case 3600*24: result = 3; break;
6221   }
6222   return result;
6223 }
6224 
6225 /*! \internal
6226 
6227   Returns the tick label corresponding to the provided \a tick and the configured format and field
6228   widths (\ref setTimeFormat, \ref setFieldWidth).
6229 
6230   \seebaseclassmethod
6231 */
getTickLabel(double tick,const QLocale & locale,QChar formatChar,int precision)6232 QString QCPAxisTickerTime::getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision)
6233 {
6234   Q_UNUSED(precision)
6235   Q_UNUSED(formatChar)
6236   Q_UNUSED(locale)
6237   bool negative = tick < 0;
6238   if (negative) tick *= -1;
6239   double values[tuDays+1]; // contains the msec/sec/min/... value with its respective modulo (e.g. minute 0..59)
6240   double restValues[tuDays+1]; // contains the msec/sec/min/... value as if it's the largest available unit and thus consumes the remaining time
6241 
6242   restValues[tuMilliseconds] = tick*1000;
6243   values[tuMilliseconds] = modf(restValues[tuMilliseconds]/1000, &restValues[tuSeconds])*1000;
6244   values[tuSeconds] = modf(restValues[tuSeconds]/60, &restValues[tuMinutes])*60;
6245   values[tuMinutes] = modf(restValues[tuMinutes]/60, &restValues[tuHours])*60;
6246   values[tuHours] = modf(restValues[tuHours]/24, &restValues[tuDays])*24;
6247   // no need to set values[tuDays] because days are always a rest value (there is no higher unit so it consumes all remaining time)
6248 
6249   QString result = mTimeFormat;
6250   for (int i = mSmallestUnit; i <= mBiggestUnit; ++i)
6251   {
6252     TimeUnit iUnit = static_cast<TimeUnit>(i);
6253     replaceUnit(result, iUnit, qRound(iUnit == mBiggestUnit ? restValues[iUnit] : values[iUnit]));
6254   }
6255   if (negative)
6256     result.prepend(QLatin1Char('-'));
6257   return result;
6258 }
6259 
6260 /*! \internal
6261 
6262   Replaces all occurrences of the format pattern belonging to \a unit in \a text with the specified
6263   \a value, using the field width as specified with \ref setFieldWidth for the \a unit.
6264 */
replaceUnit(QString & text,QCPAxisTickerTime::TimeUnit unit,int value) const6265 void QCPAxisTickerTime::replaceUnit(QString &text, QCPAxisTickerTime::TimeUnit unit, int value) const
6266 {
6267   QString valueStr = QString::number(value);
6268   while (valueStr.size() < mFieldWidth.value(unit))
6269     valueStr.prepend(QLatin1Char('0'));
6270 
6271   text.replace(mFormatPattern.value(unit), valueStr);
6272 }
6273 /* end of 'src/axis/axistickertime.cpp' */
6274 
6275 
6276 /* including file 'src/axis/axistickerfixed.cpp', size 5583                  */
6277 /* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
6278 
6279 ////////////////////////////////////////////////////////////////////////////////////////////////////
6280 //////////////////// QCPAxisTickerFixed
6281 ////////////////////////////////////////////////////////////////////////////////////////////////////
6282 /*! \class QCPAxisTickerFixed
6283   \brief Specialized axis ticker with a fixed tick step
6284 
6285   \image html axisticker-fixed.png
6286 
6287   This QCPAxisTicker subclass generates ticks with a fixed tick step set with \ref setTickStep. It
6288   is also possible to allow integer multiples and integer powers of the specified tick step with
6289   \ref setScaleStrategy.
6290 
6291   A typical application of this ticker is to make an axis only display integers, by setting the
6292   tick step of the ticker to 1.0 and the scale strategy to \ref ssMultiples.
6293 
6294   Another case is when a certain number has a special meaning and axis ticks should only appear at
6295   multiples of that value. In this case you might also want to consider \ref QCPAxisTickerPi
6296   because despite the name it is not limited to only pi symbols/values.
6297 
6298   The ticker can be created and assigned to an axis like this:
6299   \snippet documentation/doc-image-generator/mainwindow.cpp axistickerfixed-creation
6300 */
6301 
6302 /*!
6303   Constructs the ticker and sets reasonable default values. Axis tickers are commonly created
6304   managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker.
6305 */
QCPAxisTickerFixed()6306 QCPAxisTickerFixed::QCPAxisTickerFixed() :
6307   mTickStep(1.0),
6308   mScaleStrategy(ssNone)
6309 {
6310 }
6311 
6312 /*!
6313   Sets the fixed tick interval to \a step.
6314 
6315   The axis ticker will only use this tick step when generating axis ticks. This might cause a very
6316   high tick density and overlapping labels if the axis range is zoomed out. Using \ref
6317   setScaleStrategy it is possible to relax the fixed step and also allow multiples or powers of \a
6318   step. This will enable the ticker to reduce the number of ticks to a reasonable amount (see \ref
6319   setTickCount).
6320 */
setTickStep(double step)6321 void QCPAxisTickerFixed::setTickStep(double step)
6322 {
6323   if (step > 0)
6324     mTickStep = step;
6325   else
6326     qDebug() << Q_FUNC_INFO << "tick step must be greater than zero:" << step;
6327 }
6328 
6329 /*!
6330   Sets whether the specified tick step (\ref setTickStep) is absolutely fixed or whether
6331   modifications may be applied to it before calculating the finally used tick step, such as
6332   permitting multiples or powers. See \ref ScaleStrategy for details.
6333 
6334   The default strategy is \ref ssNone, which means the tick step is absolutely fixed.
6335 */
setScaleStrategy(QCPAxisTickerFixed::ScaleStrategy strategy)6336 void QCPAxisTickerFixed::setScaleStrategy(QCPAxisTickerFixed::ScaleStrategy strategy)
6337 {
6338   mScaleStrategy = strategy;
6339 }
6340 
6341 /*! \internal
6342 
6343   Determines the actually used tick step from the specified tick step and scale strategy (\ref
6344   setTickStep, \ref setScaleStrategy).
6345 
6346   This method either returns the specified tick step exactly, or, if the scale strategy is not \ref
6347   ssNone, a modification of it to allow varying the number of ticks in the current axis range.
6348 
6349   \seebaseclassmethod
6350 */
getTickStep(const QCPRange & range)6351 double QCPAxisTickerFixed::getTickStep(const QCPRange &range)
6352 {
6353   switch (mScaleStrategy)
6354   {
6355     case ssNone:
6356     {
6357       return mTickStep;
6358     }
6359     case ssMultiples:
6360     {
6361       double exactStep = range.size()/(double)(mTickCount+1e-10); // mTickCount ticks on average, the small addition is to prevent jitter on exact integers
6362       if (exactStep < mTickStep)
6363         return mTickStep;
6364       else
6365         return (qint64)(cleanMantissa(exactStep/mTickStep)+0.5)*mTickStep;
6366     }
6367     case ssPowers:
6368     {
6369       double exactStep = range.size()/(double)(mTickCount+1e-10); // mTickCount ticks on average, the small addition is to prevent jitter on exact integers
6370       return qPow(mTickStep, (int)(qLn(exactStep)/qLn(mTickStep)+0.5));
6371     }
6372   }
6373   return mTickStep;
6374 }
6375 /* end of 'src/axis/axistickerfixed.cpp' */
6376 
6377 
6378 /* including file 'src/axis/axistickertext.cpp', size 8653                   */
6379 /* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
6380 
6381 ////////////////////////////////////////////////////////////////////////////////////////////////////
6382 //////////////////// QCPAxisTickerText
6383 ////////////////////////////////////////////////////////////////////////////////////////////////////
6384 /*! \class QCPAxisTickerText
6385   \brief Specialized axis ticker which allows arbitrary labels at specified coordinates
6386 
6387   \image html axisticker-text.png
6388 
6389   This QCPAxisTicker subclass generates ticks which can be directly specified by the user as
6390   coordinates and associated strings. They can be passed as a whole with \ref setTicks or one at a
6391   time with \ref addTick. Alternatively you can directly access the internal storage via \ref ticks
6392   and modify the tick/label data there.
6393 
6394   This is useful for cases where the axis represents categories rather than numerical values.
6395 
6396   If you are updating the ticks of this ticker regularly and in a dynamic fasion (e.g. dependent on
6397   the axis range), it is a sign that you should probably create an own ticker by subclassing
6398   QCPAxisTicker, instead of using this one.
6399 
6400   The ticker can be created and assigned to an axis like this:
6401   \snippet documentation/doc-image-generator/mainwindow.cpp axistickertext-creation
6402 */
6403 
6404 /* start of documentation of inline functions */
6405 
6406 /*! \fn QMap<double, QString> &QCPAxisTickerText::ticks()
6407 
6408   Returns a non-const reference to the internal map which stores the tick coordinates and their
6409   labels.
6410 
6411   You can access the map directly in order to add, remove or manipulate ticks, as an alternative to
6412   using the methods provided by QCPAxisTickerText, such as \ref setTicks and \ref addTick.
6413 */
6414 
6415 /* end of documentation of inline functions */
6416 
6417 /*!
6418   Constructs the ticker and sets reasonable default values. Axis tickers are commonly created
6419   managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker.
6420 */
QCPAxisTickerText()6421 QCPAxisTickerText::QCPAxisTickerText() :
6422   mSubTickCount(0)
6423 {
6424 }
6425 
6426 /*! \overload
6427 
6428   Sets the ticks that shall appear on the axis. The map key of \a ticks corresponds to the axis
6429   coordinate, and the map value is the string that will appear as tick label.
6430 
6431   An alternative to manipulate ticks is to directly access the internal storage with the \ref ticks
6432   getter.
6433 
6434   \see addTicks, addTick, clear
6435 */
setTicks(const QMap<double,QString> & ticks)6436 void QCPAxisTickerText::setTicks(const QMap<double, QString> &ticks)
6437 {
6438   mTicks = ticks;
6439 }
6440 
6441 /*! \overload
6442 
6443   Sets the ticks that shall appear on the axis. The entries of \a positions correspond to the axis
6444   coordinates, and the entries of \a labels are the respective strings that will appear as tick
6445   labels.
6446 
6447   \see addTicks, addTick, clear
6448 */
setTicks(const QVector<double> & positions,const QVector<QString> labels)6449 void QCPAxisTickerText::setTicks(const QVector<double> &positions, const QVector<QString> labels)
6450 {
6451   clear();
6452   addTicks(positions, labels);
6453 }
6454 
6455 /*!
6456   Sets the number of sub ticks that shall appear between ticks. For QCPAxisTickerText, there is no
6457   automatic sub tick count calculation. So if sub ticks are needed, they must be configured with this
6458   method.
6459 */
setSubTickCount(int subTicks)6460 void QCPAxisTickerText::setSubTickCount(int subTicks)
6461 {
6462   if (subTicks >= 0)
6463     mSubTickCount = subTicks;
6464   else
6465     qDebug() << Q_FUNC_INFO << "sub tick count can't be negative:" << subTicks;
6466 }
6467 
6468 /*!
6469   Clears all ticks.
6470 
6471   An alternative to manipulate ticks is to directly access the internal storage with the \ref ticks
6472   getter.
6473 
6474   \see setTicks, addTicks, addTick
6475 */
clear()6476 void QCPAxisTickerText::clear()
6477 {
6478   mTicks.clear();
6479 }
6480 
6481 /*!
6482   Adds a single tick to the axis at the given axis coordinate \a position, with the provided tick \a
6483   label.
6484 
6485   \see addTicks, setTicks, clear
6486 */
addTick(double position,QString label)6487 void QCPAxisTickerText::addTick(double position, QString label)
6488 {
6489   mTicks.insert(position, label);
6490 }
6491 
6492 /*! \overload
6493 
6494   Adds the provided \a ticks to the ones already existing. The map key of \a ticks corresponds to
6495   the axis coordinate, and the map value is the string that will appear as tick label.
6496 
6497   An alternative to manipulate ticks is to directly access the internal storage with the \ref ticks
6498   getter.
6499 
6500   \see addTick, setTicks, clear
6501 */
addTicks(const QMap<double,QString> & ticks)6502 void QCPAxisTickerText::addTicks(const QMap<double, QString> &ticks)
6503 {
6504 # if QT_VERSION < QT_VERSION_CHECK(5, 15, 0)
6505   mTicks.unite(ticks);
6506 #else
6507   mTicks.insert(ticks);
6508 #endif
6509 }
6510 
6511 /*! \overload
6512 
6513   Adds the provided ticks to the ones already existing. The entries of \a positions correspond to
6514   the axis coordinates, and the entries of \a labels are the respective strings that will appear as
6515   tick labels.
6516 
6517   An alternative to manipulate ticks is to directly access the internal storage with the \ref ticks
6518   getter.
6519 
6520   \see addTick, setTicks, clear
6521 */
addTicks(const QVector<double> & positions,const QVector<QString> & labels)6522 void QCPAxisTickerText::addTicks(const QVector<double> &positions, const QVector<QString> &labels)
6523 {
6524   if (positions.size() != labels.size())
6525     qDebug() << Q_FUNC_INFO << "passed unequal length vectors for positions and labels:" << positions.size() << labels.size();
6526   int n = qMin(positions.size(), labels.size());
6527   for (int i=0; i<n; ++i)
6528     mTicks.insert(positions.at(i), labels.at(i));
6529 }
6530 
6531 /*!
6532   Since the tick coordinates are provided externally, this method implementation does nothing.
6533 
6534   \seebaseclassmethod
6535 */
getTickStep(const QCPRange & range)6536 double QCPAxisTickerText::getTickStep(const QCPRange &range)
6537 {
6538   // text axis ticker has manual tick positions, so doesn't need this method
6539   Q_UNUSED(range)
6540   return 1.0;
6541 }
6542 
6543 /*!
6544   Returns the sub tick count that was configured with \ref setSubTickCount.
6545 
6546   \seebaseclassmethod
6547 */
getSubTickCount(double tickStep)6548 int QCPAxisTickerText::getSubTickCount(double tickStep)
6549 {
6550   Q_UNUSED(tickStep)
6551   return mSubTickCount;
6552 }
6553 
6554 /*!
6555   Returns the tick label which corresponds to the key \a tick in the internal tick storage. Since
6556   the labels are provided externally, \a locale, \a formatChar, and \a precision are ignored.
6557 
6558   \seebaseclassmethod
6559 */
getTickLabel(double tick,const QLocale & locale,QChar formatChar,int precision)6560 QString QCPAxisTickerText::getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision)
6561 {
6562   Q_UNUSED(locale)
6563   Q_UNUSED(formatChar)
6564   Q_UNUSED(precision)
6565   return mTicks.value(tick);
6566 }
6567 
6568 /*!
6569   Returns the externally provided tick coordinates which are in the specified \a range. If
6570   available, one tick above and below the range is provided in addition, to allow possible sub tick
6571   calculation. The parameter \a tickStep is ignored.
6572 
6573   \seebaseclassmethod
6574 */
createTickVector(double tickStep,const QCPRange & range)6575 QVector<double> QCPAxisTickerText::createTickVector(double tickStep, const QCPRange &range)
6576 {
6577   Q_UNUSED(tickStep)
6578   QVector<double> result;
6579   if (mTicks.isEmpty())
6580     return result;
6581 
6582   QMap<double, QString>::const_iterator start = mTicks.lowerBound(range.lower);
6583   QMap<double, QString>::const_iterator end = mTicks.upperBound(range.upper);
6584   // this method should try to give one tick outside of range so proper subticks can be generated:
6585   if (start != mTicks.constBegin()) --start;
6586   if (end != mTicks.constEnd()) ++end;
6587   for (QMap<double, QString>::const_iterator it = start; it != end; ++it)
6588     result.append(it.key());
6589 
6590   return result;
6591 }
6592 /* end of 'src/axis/axistickertext.cpp' */
6593 
6594 
6595 /* including file 'src/axis/axistickerpi.cpp', size 11170                    */
6596 /* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
6597 
6598 ////////////////////////////////////////////////////////////////////////////////////////////////////
6599 //////////////////// QCPAxisTickerPi
6600 ////////////////////////////////////////////////////////////////////////////////////////////////////
6601 /*! \class QCPAxisTickerPi
6602   \brief Specialized axis ticker to display ticks in units of an arbitrary constant, for example pi
6603 
6604   \image html axisticker-pi.png
6605 
6606   This QCPAxisTicker subclass generates ticks that are expressed with respect to a given symbolic
6607   constant with a numerical value specified with \ref setPiValue and an appearance in the tick
6608   labels specified with \ref setPiSymbol.
6609 
6610   Ticks may be generated at fractions of the symbolic constant. How these fractions appear in the
6611   tick label can be configured with \ref setFractionStyle.
6612 
6613   The ticker can be created and assigned to an axis like this:
6614   \snippet documentation/doc-image-generator/mainwindow.cpp axistickerpi-creation
6615 */
6616 
6617 /*!
6618   Constructs the ticker and sets reasonable default values. Axis tickers are commonly created
6619   managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker.
6620 */
QCPAxisTickerPi()6621 QCPAxisTickerPi::QCPAxisTickerPi() :
6622   mPiSymbol(QLatin1String(" ")+QChar(0x03C0)),
6623   mPiValue(M_PI),
6624   mPeriodicity(0),
6625   mFractionStyle(fsUnicodeFractions),
6626   mPiTickStep(0)
6627 {
6628   setTickCount(4);
6629 }
6630 
6631 /*!
6632   Sets how the symbol part (which is always a suffix to the number) shall appear in the axis tick
6633   label.
6634 
6635   If a space shall appear between the number and the symbol, make sure the space is contained in \a
6636   symbol.
6637 */
setPiSymbol(QString symbol)6638 void QCPAxisTickerPi::setPiSymbol(QString symbol)
6639 {
6640   mPiSymbol = symbol;
6641 }
6642 
6643 /*!
6644   Sets the numerical value that the symbolic constant has.
6645 
6646   This will be used to place the appropriate fractions of the symbol at the respective axis
6647   coordinates.
6648 */
setPiValue(double pi)6649 void QCPAxisTickerPi::setPiValue(double pi)
6650 {
6651   mPiValue = pi;
6652 }
6653 
6654 /*!
6655   Sets whether the axis labels shall appear periodicly and if so, at which multiplicity of the
6656   symbolic constant.
6657 
6658   To disable periodicity, set \a multiplesOfPi to zero.
6659 
6660   For example, an axis that identifies 0 with 2pi would set \a multiplesOfPi to two.
6661 */
setPeriodicity(int multiplesOfPi)6662 void QCPAxisTickerPi::setPeriodicity(int multiplesOfPi)
6663 {
6664   mPeriodicity = qAbs(multiplesOfPi);
6665 }
6666 
6667 /*!
6668   Sets how the numerical/fractional part preceding the symbolic constant is displayed in tick
6669   labels. See \ref FractionStyle for the various options.
6670 */
setFractionStyle(QCPAxisTickerPi::FractionStyle style)6671 void QCPAxisTickerPi::setFractionStyle(QCPAxisTickerPi::FractionStyle style)
6672 {
6673   mFractionStyle = style;
6674 }
6675 
6676 /*! \internal
6677 
6678   Returns the tick step, using the constant's value (\ref setPiValue) as base unit. In consequence
6679   the numerical/fractional part preceding the symbolic constant is made to have a readable
6680   mantissa.
6681 
6682   \seebaseclassmethod
6683 */
getTickStep(const QCPRange & range)6684 double QCPAxisTickerPi::getTickStep(const QCPRange &range)
6685 {
6686   mPiTickStep = range.size()/mPiValue/(double)(mTickCount+1e-10); // mTickCount ticks on average, the small addition is to prevent jitter on exact integers
6687   mPiTickStep = cleanMantissa(mPiTickStep);
6688   return mPiTickStep*mPiValue;
6689 }
6690 
6691 /*! \internal
6692 
6693   Returns the sub tick count, using the constant's value (\ref setPiValue) as base unit. In
6694   consequence the sub ticks divide the numerical/fractional part preceding the symbolic constant
6695   reasonably, and not the total tick coordinate.
6696 
6697   \seebaseclassmethod
6698 */
getSubTickCount(double tickStep)6699 int QCPAxisTickerPi::getSubTickCount(double tickStep)
6700 {
6701   return QCPAxisTicker::getSubTickCount(tickStep/mPiValue);
6702 }
6703 
6704 /*! \internal
6705 
6706   Returns the tick label as a fractional/numerical part and a symbolic string as suffix. The
6707   formatting of the fraction is done according to the specified \ref setFractionStyle. The appended
6708   symbol is specified with \ref setPiSymbol.
6709 
6710   \seebaseclassmethod
6711 */
getTickLabel(double tick,const QLocale & locale,QChar formatChar,int precision)6712 QString QCPAxisTickerPi::getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision)
6713 {
6714   double tickInPis = tick/mPiValue;
6715   if (mPeriodicity > 0)
6716     tickInPis = fmod(tickInPis, mPeriodicity);
6717 
6718   if (mFractionStyle != fsFloatingPoint && mPiTickStep > 0.09 && mPiTickStep < 50)
6719   {
6720     // simply construct fraction from decimal like 1.234 -> 1234/1000 and then simplify fraction, smaller digits are irrelevant due to mPiTickStep conditional above
6721     int denominator = 1000;
6722     int numerator = qRound(tickInPis*denominator);
6723     simplifyFraction(numerator, denominator);
6724     if (qAbs(numerator) == 1 && denominator == 1)
6725       return (numerator < 0 ? QLatin1String("-") : QLatin1String("")) + mPiSymbol.trimmed();
6726     else if (numerator == 0)
6727       return QLatin1String("0");
6728     else
6729       return fractionToString(numerator, denominator) + mPiSymbol;
6730   } else
6731   {
6732     if (qFuzzyIsNull(tickInPis))
6733       return QLatin1String("0");
6734     else if (qFuzzyCompare(qAbs(tickInPis), 1.0))
6735       return (tickInPis < 0 ? QLatin1String("-") : QLatin1String("")) + mPiSymbol.trimmed();
6736     else
6737       return QCPAxisTicker::getTickLabel(tickInPis, locale, formatChar, precision) + mPiSymbol;
6738   }
6739 }
6740 
6741 /*! \internal
6742 
6743   Takes the fraction given by \a numerator and \a denominator and modifies the values to make sure
6744   the fraction is in irreducible form, i.e. numerator and denominator don't share any common
6745   factors which could be cancelled.
6746 */
simplifyFraction(int & numerator,int & denominator) const6747 void QCPAxisTickerPi::simplifyFraction(int &numerator, int &denominator) const
6748 {
6749   if (numerator == 0 || denominator == 0)
6750     return;
6751 
6752   int num = numerator;
6753   int denom = denominator;
6754   while (denom != 0) // euclidean gcd algorithm
6755   {
6756     int oldDenom = denom;
6757     denom = num % denom;
6758     num = oldDenom;
6759   }
6760   // num is now gcd of numerator and denominator
6761   numerator /= num;
6762   denominator /= num;
6763 }
6764 
6765 /*! \internal
6766 
6767   Takes the fraction given by \a numerator and \a denominator and returns a string representation.
6768   The result depends on the configured fraction style (\ref setFractionStyle).
6769 
6770   This method is used to format the numerical/fractional part when generating tick labels. It
6771   simplifies the passed fraction to an irreducible form using \ref simplifyFraction and factors out
6772   any integer parts of the fraction (e.g. "10/4" becomes "2 1/2").
6773 */
fractionToString(int numerator,int denominator) const6774 QString QCPAxisTickerPi::fractionToString(int numerator, int denominator) const
6775 {
6776   if (denominator == 0)
6777   {
6778     qDebug() << Q_FUNC_INFO << "called with zero denominator";
6779     return QString();
6780   }
6781   if (mFractionStyle == fsFloatingPoint) // should never be the case when calling this function
6782   {
6783     qDebug() << Q_FUNC_INFO << "shouldn't be called with fraction style fsDecimal";
6784     return QString::number(numerator/(double)denominator); // failsafe
6785   }
6786   int sign = numerator*denominator < 0 ? -1 : 1;
6787   numerator = qAbs(numerator);
6788   denominator = qAbs(denominator);
6789 
6790   if (denominator == 1)
6791   {
6792     return QString::number(sign*numerator);
6793   } else
6794   {
6795     int integerPart = numerator/denominator;
6796     int remainder = numerator%denominator;
6797     if (remainder == 0)
6798     {
6799       return QString::number(sign*integerPart);
6800     } else
6801     {
6802       if (mFractionStyle == fsAsciiFractions)
6803       {
6804         return QString(QLatin1String("%1%2%3/%4"))
6805             .arg(sign == -1 ? QLatin1String("-") : QLatin1String(""))
6806             .arg(integerPart > 0 ? QString::number(integerPart)+QLatin1String(" ") : QLatin1String(""))
6807             .arg(remainder)
6808             .arg(denominator);
6809       } else if (mFractionStyle == fsUnicodeFractions)
6810       {
6811         return QString(QLatin1String("%1%2%3"))
6812             .arg(sign == -1 ? QLatin1String("-") : QLatin1String(""))
6813             .arg(integerPart > 0 ? QString::number(integerPart) : QLatin1String(""))
6814             .arg(unicodeFraction(remainder, denominator));
6815       }
6816     }
6817   }
6818   return QString();
6819 }
6820 
6821 /*! \internal
6822 
6823   Returns the unicode string representation of the fraction given by \a numerator and \a
6824   denominator. This is the representation used in \ref fractionToString when the fraction style
6825   (\ref setFractionStyle) is \ref fsUnicodeFractions.
6826 
6827   This method doesn't use the single-character common fractions but builds each fraction from a
6828   superscript unicode number, the unicode fraction character, and a subscript unicode number.
6829 */
unicodeFraction(int numerator,int denominator) const6830 QString QCPAxisTickerPi::unicodeFraction(int numerator, int denominator) const
6831 {
6832   return unicodeSuperscript(numerator)+QChar(0x2044)+unicodeSubscript(denominator);
6833 }
6834 
6835 /*! \internal
6836 
6837   Returns the unicode string representing \a number as superscript. This is used to build
6838   unicode fractions in \ref unicodeFraction.
6839 */
unicodeSuperscript(int number) const6840 QString QCPAxisTickerPi::unicodeSuperscript(int number) const
6841 {
6842   if (number == 0)
6843     return QString(QChar(0x2070));
6844 
6845   QString result;
6846   while (number > 0)
6847   {
6848     const int digit = number%10;
6849     switch (digit)
6850     {
6851       case 1: { result.prepend(QChar(0x00B9)); break; }
6852       case 2: { result.prepend(QChar(0x00B2)); break; }
6853       case 3: { result.prepend(QChar(0x00B3)); break; }
6854       default: { result.prepend(QChar(0x2070+digit)); break; }
6855     }
6856     number /= 10;
6857   }
6858   return result;
6859 }
6860 
6861 /*! \internal
6862 
6863   Returns the unicode string representing \a number as subscript. This is used to build unicode
6864   fractions in \ref unicodeFraction.
6865 */
unicodeSubscript(int number) const6866 QString QCPAxisTickerPi::unicodeSubscript(int number) const
6867 {
6868   if (number == 0)
6869     return QString(QChar(0x2080));
6870 
6871   QString result;
6872   while (number > 0)
6873   {
6874     result.prepend(QChar(0x2080+number%10));
6875     number /= 10;
6876   }
6877   return result;
6878 }
6879 /* end of 'src/axis/axistickerpi.cpp' */
6880 
6881 
6882 /* including file 'src/axis/axistickerlog.cpp', size 7106                    */
6883 /* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
6884 
6885 ////////////////////////////////////////////////////////////////////////////////////////////////////
6886 //////////////////// QCPAxisTickerLog
6887 ////////////////////////////////////////////////////////////////////////////////////////////////////
6888 /*! \class QCPAxisTickerLog
6889   \brief Specialized axis ticker suited for logarithmic axes
6890 
6891   \image html axisticker-log.png
6892 
6893   This QCPAxisTicker subclass generates ticks with unequal tick intervals suited for logarithmic
6894   axis scales. The ticks are placed at powers of the specified log base (\ref setLogBase).
6895 
6896   Especially in the case of a log base equal to 10 (the default), it might be desirable to have
6897   tick labels in the form of powers of ten without mantissa display. To achieve this, set the
6898   number precision (\ref QCPAxis::setNumberPrecision) to zero and the number format (\ref
6899   QCPAxis::setNumberFormat) to scientific (exponential) display with beautifully typeset decimal
6900   powers, so a format string of <tt>"eb"</tt>. This will result in the following axis tick labels:
6901 
6902   \image html axisticker-log-powers.png
6903 
6904   The ticker can be created and assigned to an axis like this:
6905   \snippet documentation/doc-image-generator/mainwindow.cpp axistickerlog-creation
6906 */
6907 
6908 /*!
6909   Constructs the ticker and sets reasonable default values. Axis tickers are commonly created
6910   managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker.
6911 */
QCPAxisTickerLog()6912 QCPAxisTickerLog::QCPAxisTickerLog() :
6913   mLogBase(10.0),
6914   mSubTickCount(8), // generates 10 intervals
6915   mLogBaseLnInv(1.0/qLn(mLogBase))
6916 {
6917 }
6918 
6919 /*!
6920   Sets the logarithm base used for tick coordinate generation. The ticks will be placed at integer
6921   powers of \a base.
6922 */
setLogBase(double base)6923 void QCPAxisTickerLog::setLogBase(double base)
6924 {
6925   if (base > 0)
6926   {
6927     mLogBase = base;
6928     mLogBaseLnInv = 1.0/qLn(mLogBase);
6929   } else
6930     qDebug() << Q_FUNC_INFO << "log base has to be greater than zero:" << base;
6931 }
6932 
6933 /*!
6934   Sets the number of sub ticks in a tick interval. Within each interval, the sub ticks are spaced
6935   linearly to provide a better visual guide, so the sub tick density increases toward the higher
6936   tick.
6937 
6938   Note that \a subTicks is the number of sub ticks (not sub intervals) in one tick interval. So in
6939   the case of logarithm base 10 an intuitive sub tick spacing would be achieved with eight sub
6940   ticks (the default). This means e.g. between the ticks 10 and 100 there will be eight ticks,
6941   namely at 20, 30, 40, 50, 60, 70, 80 and 90.
6942 */
setSubTickCount(int subTicks)6943 void QCPAxisTickerLog::setSubTickCount(int subTicks)
6944 {
6945   if (subTicks >= 0)
6946     mSubTickCount = subTicks;
6947   else
6948     qDebug() << Q_FUNC_INFO << "sub tick count can't be negative:" << subTicks;
6949 }
6950 
6951 /*! \internal
6952 
6953   Since logarithmic tick steps are necessarily different for each tick interval, this method does
6954   nothing in the case of QCPAxisTickerLog
6955 
6956   \seebaseclassmethod
6957 */
getTickStep(const QCPRange & range)6958 double QCPAxisTickerLog::getTickStep(const QCPRange &range)
6959 {
6960   // Logarithmic axis ticker has unequal tick spacing, so doesn't need this method
6961   Q_UNUSED(range)
6962   return 1.0;
6963 }
6964 
6965 /*! \internal
6966 
6967   Returns the sub tick count specified in \ref setSubTickCount. For QCPAxisTickerLog, there is no
6968   automatic sub tick count calculation necessary.
6969 
6970   \seebaseclassmethod
6971 */
getSubTickCount(double tickStep)6972 int QCPAxisTickerLog::getSubTickCount(double tickStep)
6973 {
6974   Q_UNUSED(tickStep)
6975   return mSubTickCount;
6976 }
6977 
6978 /*! \internal
6979 
6980   Creates ticks with a spacing given by the logarithm base and an increasing integer power in the
6981   provided \a range. The step in which the power increases tick by tick is chosen in order to keep
6982   the total number of ticks as close as possible to the tick count (\ref setTickCount). The
6983   parameter \a tickStep is ignored for QCPAxisTickerLog
6984 
6985   \seebaseclassmethod
6986 */
createTickVector(double tickStep,const QCPRange & range)6987 QVector<double> QCPAxisTickerLog::createTickVector(double tickStep, const QCPRange &range)
6988 {
6989   Q_UNUSED(tickStep)
6990   QVector<double> result;
6991   if (range.lower > 0 && range.upper > 0) // positive range
6992   {
6993     double exactPowerStep =  qLn(range.upper/range.lower)*mLogBaseLnInv/(double)(mTickCount+1e-10);
6994     double newLogBase = qPow(mLogBase, qMax((int)cleanMantissa(exactPowerStep), 1));
6995     double currentTick = qPow(newLogBase, qFloor(qLn(range.lower)/qLn(newLogBase)));
6996     result.append(currentTick);
6997     while (currentTick < range.upper && currentTick > 0) // currentMag might be zero for ranges ~1e-300, just cancel in that case
6998     {
6999       currentTick *= newLogBase;
7000       result.append(currentTick);
7001     }
7002   } else if (range.lower < 0 && range.upper < 0) // negative range
7003   {
7004     double exactPowerStep =  qLn(range.lower/range.upper)*mLogBaseLnInv/(double)(mTickCount+1e-10);
7005     double newLogBase = qPow(mLogBase, qMax((int)cleanMantissa(exactPowerStep), 1));
7006     double currentTick = -qPow(newLogBase, qCeil(qLn(-range.lower)/qLn(newLogBase)));
7007     result.append(currentTick);
7008     while (currentTick < range.upper && currentTick < 0) // currentMag might be zero for ranges ~1e-300, just cancel in that case
7009     {
7010       currentTick /= newLogBase;
7011       result.append(currentTick);
7012     }
7013   } else // invalid range for logarithmic scale, because lower and upper have different sign
7014   {
7015     qDebug() << Q_FUNC_INFO << "Invalid range for logarithmic plot: " << range.lower << ".." << range.upper;
7016   }
7017 
7018   return result;
7019 }
7020 /* end of 'src/axis/axistickerlog.cpp' */
7021 
7022 
7023 /* including file 'src/axis/axis.cpp', size 94458                            */
7024 /* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
7025 
7026 
7027 ////////////////////////////////////////////////////////////////////////////////////////////////////
7028 //////////////////// QCPGrid
7029 ////////////////////////////////////////////////////////////////////////////////////////////////////
7030 
7031 /*! \class QCPGrid
7032   \brief Responsible for drawing the grid of a QCPAxis.
7033 
7034   This class is tightly bound to QCPAxis. Every axis owns a grid instance and uses it to draw the
7035   grid lines, sub grid lines and zero-line. You can interact with the grid of an axis via \ref
7036   QCPAxis::grid. Normally, you don't need to create an instance of QCPGrid yourself.
7037 
7038   The axis and grid drawing was split into two classes to allow them to be placed on different
7039   layers (both QCPAxis and QCPGrid inherit from QCPLayerable). Thus it is possible to have the grid
7040   in the background and the axes in the foreground, and any plottables/items in between. This
7041   described situation is the default setup, see the QCPLayer documentation.
7042 */
7043 
7044 /*!
7045   Creates a QCPGrid instance and sets default values.
7046 
7047   You shouldn't instantiate grids on their own, since every QCPAxis brings its own QCPGrid.
7048 */
QCPGrid(QCPAxis * parentAxis)7049 QCPGrid::QCPGrid(QCPAxis *parentAxis) :
7050   QCPLayerable(parentAxis->parentPlot(), QString(), parentAxis),
7051   mParentAxis(parentAxis)
7052 {
7053   // warning: this is called in QCPAxis constructor, so parentAxis members should not be accessed/called
7054   setParent(parentAxis);
7055   setPen(QPen(QColor(200,200,200), 0, Qt::DotLine));
7056   setSubGridPen(QPen(QColor(220,220,220), 0, Qt::DotLine));
7057   setZeroLinePen(QPen(QColor(200,200,200), 0, Qt::SolidLine));
7058   setSubGridVisible(false);
7059   setAntialiased(false);
7060   setAntialiasedSubGrid(false);
7061   setAntialiasedZeroLine(false);
7062 }
7063 
7064 /*!
7065   Sets whether grid lines at sub tick marks are drawn.
7066 
7067   \see setSubGridPen
7068 */
setSubGridVisible(bool visible)7069 void QCPGrid::setSubGridVisible(bool visible)
7070 {
7071   mSubGridVisible = visible;
7072 }
7073 
7074 /*!
7075   Sets whether sub grid lines are drawn antialiased.
7076 */
setAntialiasedSubGrid(bool enabled)7077 void QCPGrid::setAntialiasedSubGrid(bool enabled)
7078 {
7079   mAntialiasedSubGrid = enabled;
7080 }
7081 
7082 /*!
7083   Sets whether zero lines are drawn antialiased.
7084 */
setAntialiasedZeroLine(bool enabled)7085 void QCPGrid::setAntialiasedZeroLine(bool enabled)
7086 {
7087   mAntialiasedZeroLine = enabled;
7088 }
7089 
7090 /*!
7091   Sets the pen with which (major) grid lines are drawn.
7092 */
setPen(const QPen & pen)7093 void QCPGrid::setPen(const QPen &pen)
7094 {
7095   mPen = pen;
7096 }
7097 
7098 /*!
7099   Sets the pen with which sub grid lines are drawn.
7100 */
setSubGridPen(const QPen & pen)7101 void QCPGrid::setSubGridPen(const QPen &pen)
7102 {
7103   mSubGridPen = pen;
7104 }
7105 
7106 /*!
7107   Sets the pen with which zero lines are drawn.
7108 
7109   Zero lines are lines at value coordinate 0 which may be drawn with a different pen than other grid
7110   lines. To disable zero lines and just draw normal grid lines at zero, set \a pen to Qt::NoPen.
7111 */
setZeroLinePen(const QPen & pen)7112 void QCPGrid::setZeroLinePen(const QPen &pen)
7113 {
7114   mZeroLinePen = pen;
7115 }
7116 
7117 /*! \internal
7118 
7119   A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
7120   before drawing the major grid lines.
7121 
7122   This is the antialiasing state the painter passed to the \ref draw method is in by default.
7123 
7124   This function takes into account the local setting of the antialiasing flag as well as the
7125   overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
7126   QCustomPlot::setNotAntialiasedElements.
7127 
7128   \see setAntialiased
7129 */
applyDefaultAntialiasingHint(QCPPainter * painter) const7130 void QCPGrid::applyDefaultAntialiasingHint(QCPPainter *painter) const
7131 {
7132   applyAntialiasingHint(painter, mAntialiased, QCP::aeGrid);
7133 }
7134 
7135 /*! \internal
7136 
7137   Draws grid lines and sub grid lines at the positions of (sub) ticks of the parent axis, spanning
7138   over the complete axis rect. Also draws the zero line, if appropriate (\ref setZeroLinePen).
7139 */
draw(QCPPainter * painter)7140 void QCPGrid::draw(QCPPainter *painter)
7141 {
7142   if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; }
7143 
7144   if (mParentAxis->subTicks() && mSubGridVisible)
7145     drawSubGridLines(painter);
7146   drawGridLines(painter);
7147 }
7148 
7149 /*! \internal
7150 
7151   Draws the main grid lines and possibly a zero line with the specified painter.
7152 
7153   This is a helper function called by \ref draw.
7154 */
drawGridLines(QCPPainter * painter) const7155 void QCPGrid::drawGridLines(QCPPainter *painter) const
7156 {
7157   if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; }
7158 
7159   const int tickCount = mParentAxis->mTickVector.size();
7160   double t; // helper variable, result of coordinate-to-pixel transforms
7161   if (mParentAxis->orientation() == Qt::Horizontal)
7162   {
7163     // draw zeroline:
7164     int zeroLineIndex = -1;
7165     if (mZeroLinePen.style() != Qt::NoPen && mParentAxis->mRange.lower < 0 && mParentAxis->mRange.upper > 0)
7166     {
7167       applyAntialiasingHint(painter, mAntialiasedZeroLine, QCP::aeZeroLine);
7168       painter->setPen(mZeroLinePen);
7169       double epsilon = mParentAxis->range().size()*1E-6; // for comparing double to zero
7170       for (int i=0; i<tickCount; ++i)
7171       {
7172         if (qAbs(mParentAxis->mTickVector.at(i)) < epsilon)
7173         {
7174           zeroLineIndex = i;
7175           t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // x
7176           painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top()));
7177           break;
7178         }
7179       }
7180     }
7181     // draw grid lines:
7182     applyDefaultAntialiasingHint(painter);
7183     painter->setPen(mPen);
7184     for (int i=0; i<tickCount; ++i)
7185     {
7186       if (i == zeroLineIndex) continue; // don't draw a gridline on top of the zeroline
7187       t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // x
7188       painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top()));
7189     }
7190   } else
7191   {
7192     // draw zeroline:
7193     int zeroLineIndex = -1;
7194     if (mZeroLinePen.style() != Qt::NoPen && mParentAxis->mRange.lower < 0 && mParentAxis->mRange.upper > 0)
7195     {
7196       applyAntialiasingHint(painter, mAntialiasedZeroLine, QCP::aeZeroLine);
7197       painter->setPen(mZeroLinePen);
7198       double epsilon = mParentAxis->mRange.size()*1E-6; // for comparing double to zero
7199       for (int i=0; i<tickCount; ++i)
7200       {
7201         if (qAbs(mParentAxis->mTickVector.at(i)) < epsilon)
7202         {
7203           zeroLineIndex = i;
7204           t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // y
7205           painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t));
7206           break;
7207         }
7208       }
7209     }
7210     // draw grid lines:
7211     applyDefaultAntialiasingHint(painter);
7212     painter->setPen(mPen);
7213     for (int i=0; i<tickCount; ++i)
7214     {
7215       if (i == zeroLineIndex) continue; // don't draw a gridline on top of the zeroline
7216       t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // y
7217       painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t));
7218     }
7219   }
7220 }
7221 
7222 /*! \internal
7223 
7224   Draws the sub grid lines with the specified painter.
7225 
7226   This is a helper function called by \ref draw.
7227 */
drawSubGridLines(QCPPainter * painter) const7228 void QCPGrid::drawSubGridLines(QCPPainter *painter) const
7229 {
7230   if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; }
7231 
7232   applyAntialiasingHint(painter, mAntialiasedSubGrid, QCP::aeSubGrid);
7233   double t; // helper variable, result of coordinate-to-pixel transforms
7234   painter->setPen(mSubGridPen);
7235   if (mParentAxis->orientation() == Qt::Horizontal)
7236   {
7237     for (int i=0; i<mParentAxis->mSubTickVector.size(); ++i)
7238     {
7239       t = mParentAxis->coordToPixel(mParentAxis->mSubTickVector.at(i)); // x
7240       painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top()));
7241     }
7242   } else
7243   {
7244     for (int i=0; i<mParentAxis->mSubTickVector.size(); ++i)
7245     {
7246       t = mParentAxis->coordToPixel(mParentAxis->mSubTickVector.at(i)); // y
7247       painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t));
7248     }
7249   }
7250 }
7251 
7252 
7253 ////////////////////////////////////////////////////////////////////////////////////////////////////
7254 //////////////////// QCPAxis
7255 ////////////////////////////////////////////////////////////////////////////////////////////////////
7256 
7257 /*! \class QCPAxis
7258   \brief Manages a single axis inside a QCustomPlot.
7259 
7260   Usually doesn't need to be instantiated externally. Access %QCustomPlot's default four axes via
7261   QCustomPlot::xAxis (bottom), QCustomPlot::yAxis (left), QCustomPlot::xAxis2 (top) and
7262   QCustomPlot::yAxis2 (right).
7263 
7264   Axes are always part of an axis rect, see QCPAxisRect.
7265   \image html AxisNamesOverview.png
7266   <center>Naming convention of axis parts</center>
7267   \n
7268 
7269   \image html AxisRectSpacingOverview.png
7270   <center>Overview of the spacings and paddings that define the geometry of an axis. The dashed gray line
7271   on the left represents the QCustomPlot widget border.</center>
7272 
7273   Each axis holds an instance of QCPAxisTicker which is used to generate the tick coordinates and
7274   tick labels. You can access the currently installed \ref ticker or set a new one (possibly one of
7275   the specialized subclasses, or your own subclass) via \ref setTicker. For details, see the
7276   documentation of QCPAxisTicker.
7277 */
7278 
7279 /* start of documentation of inline functions */
7280 
7281 /*! \fn Qt::Orientation QCPAxis::orientation() const
7282 
7283   Returns the orientation of this axis. The axis orientation (horizontal or vertical) is deduced
7284   from the axis type (left, top, right or bottom).
7285 
7286   \see orientation(AxisType type), pixelOrientation
7287 */
7288 
7289 /*! \fn QCPGrid *QCPAxis::grid() const
7290 
7291   Returns the \ref QCPGrid instance belonging to this axis. Access it to set details about the way the
7292   grid is displayed.
7293 */
7294 
7295 /*! \fn static Qt::Orientation QCPAxis::orientation(AxisType type)
7296 
7297   Returns the orientation of the specified axis type
7298 
7299   \see orientation(), pixelOrientation
7300 */
7301 
7302 /*! \fn int QCPAxis::pixelOrientation() const
7303 
7304   Returns which direction points towards higher coordinate values/keys, in pixel space.
7305 
7306   This method returns either 1 or -1. If it returns 1, then going in the positive direction along
7307   the orientation of the axis in pixels corresponds to going from lower to higher axis coordinates.
7308   On the other hand, if this method returns -1, going to smaller pixel values corresponds to going
7309   from lower to higher axis coordinates.
7310 
7311   For example, this is useful to easily shift axis coordinates by a certain amount given in pixels,
7312   without having to care about reversed or vertically aligned axes:
7313 
7314   \code
7315   double newKey = keyAxis->pixelToCoord(keyAxis->coordToPixel(oldKey)+10*keyAxis->pixelOrientation());
7316   \endcode
7317 
7318   \a newKey will then contain a key that is ten pixels towards higher keys, starting from \a oldKey.
7319 */
7320 
7321 /*! \fn QSharedPointer<QCPAxisTicker> QCPAxis::ticker() const
7322 
7323   Returns a modifiable shared pointer to the currently installed axis ticker. The axis ticker is
7324   responsible for generating the tick positions and tick labels of this axis. You can access the
7325   \ref QCPAxisTicker with this method and modify basic properties such as the approximate tick count
7326   (\ref QCPAxisTicker::setTickCount).
7327 
7328   You can gain more control over the axis ticks by setting a different \ref QCPAxisTicker subclass, see
7329   the documentation there. A new axis ticker can be set with \ref setTicker.
7330 
7331   Since the ticker is stored in the axis as a shared pointer, multiple axes may share the same axis
7332   ticker simply by passing the same shared pointer to multiple axes.
7333 
7334   \see setTicker
7335 */
7336 
7337 /* end of documentation of inline functions */
7338 /* start of documentation of signals */
7339 
7340 /*! \fn void QCPAxis::rangeChanged(const QCPRange &newRange)
7341 
7342   This signal is emitted when the range of this axis has changed. You can connect it to the \ref
7343   setRange slot of another axis to communicate the new range to the other axis, in order for it to
7344   be synchronized.
7345 
7346   You may also manipulate/correct the range with \ref setRange in a slot connected to this signal.
7347   This is useful if for example a maximum range span shall not be exceeded, or if the lower/upper
7348   range shouldn't go beyond certain values (see \ref QCPRange::bounded). For example, the following
7349   slot would limit the x axis to ranges between 0 and 10:
7350   \code
7351   customPlot->xAxis->setRange(newRange.bounded(0, 10))
7352   \endcode
7353 */
7354 
7355 /*! \fn void QCPAxis::rangeChanged(const QCPRange &newRange, const QCPRange &oldRange)
7356   \overload
7357 
7358   Additionally to the new range, this signal also provides the previous range held by the axis as
7359   \a oldRange.
7360 */
7361 
7362 /*! \fn void QCPAxis::scaleTypeChanged(QCPAxis::ScaleType scaleType);
7363 
7364   This signal is emitted when the scale type changes, by calls to \ref setScaleType
7365 */
7366 
7367 /*! \fn void QCPAxis::selectionChanged(QCPAxis::SelectableParts selection)
7368 
7369   This signal is emitted when the selection state of this axis has changed, either by user interaction
7370   or by a direct call to \ref setSelectedParts.
7371 */
7372 
7373 /*! \fn void QCPAxis::selectableChanged(const QCPAxis::SelectableParts &parts);
7374 
7375   This signal is emitted when the selectability changes, by calls to \ref setSelectableParts
7376 */
7377 
7378 /* end of documentation of signals */
7379 
7380 /*!
7381   Constructs an Axis instance of Type \a type for the axis rect \a parent.
7382 
7383   Usually it isn't necessary to instantiate axes directly, because you can let QCustomPlot create
7384   them for you with \ref QCPAxisRect::addAxis. If you want to use own QCPAxis-subclasses however,
7385   create them manually and then inject them also via \ref QCPAxisRect::addAxis.
7386 */
QCPAxis(QCPAxisRect * parent,AxisType type)7387 QCPAxis::QCPAxis(QCPAxisRect *parent, AxisType type) :
7388   QCPLayerable(parent->parentPlot(), QString(), parent),
7389   // axis base:
7390   mAxisType(type),
7391   mAxisRect(parent),
7392   mPadding(5),
7393   mOrientation(orientation(type)),
7394   mSelectableParts(spAxis | spTickLabels | spAxisLabel),
7395   mSelectedParts(spNone),
7396   mBasePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
7397   mSelectedBasePen(QPen(Qt::blue, 2)),
7398   // axis label:
7399   mLabel(),
7400   mLabelFont(mParentPlot->font()),
7401   mSelectedLabelFont(QFont(mLabelFont.family(), mLabelFont.pointSize(), QFont::Bold)),
7402   mLabelColor(Qt::black),
7403   mSelectedLabelColor(Qt::blue),
7404   // tick labels:
7405   mTickLabels(true),
7406   mTickLabelFont(mParentPlot->font()),
7407   mSelectedTickLabelFont(QFont(mTickLabelFont.family(), mTickLabelFont.pointSize(), QFont::Bold)),
7408   mTickLabelColor(Qt::black),
7409   mSelectedTickLabelColor(Qt::blue),
7410   mNumberPrecision(6),
7411   mNumberFormatChar('g'),
7412   mNumberBeautifulPowers(true),
7413   // ticks and subticks:
7414   mTicks(true),
7415   mSubTicks(true),
7416   mTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
7417   mSelectedTickPen(QPen(Qt::blue, 2)),
7418   mSubTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
7419   mSelectedSubTickPen(QPen(Qt::blue, 2)),
7420   // scale and range:
7421   mRange(0, 5),
7422   mRangeReversed(false),
7423   mScaleType(stLinear),
7424   // internal members:
7425   mGrid(new QCPGrid(this)),
7426   mAxisPainter(new QCPAxisPainterPrivate(parent->parentPlot())),
7427   mTicker(new QCPAxisTicker),
7428   mCachedMarginValid(false),
7429   mCachedMargin(0)
7430 {
7431   setParent(parent);
7432   mGrid->setVisible(false);
7433   setAntialiased(false);
7434   setLayer(mParentPlot->currentLayer()); // it's actually on that layer already, but we want it in front of the grid, so we place it on there again
7435 
7436   if (type == atTop)
7437   {
7438     setTickLabelPadding(3);
7439     setLabelPadding(6);
7440   } else if (type == atRight)
7441   {
7442     setTickLabelPadding(7);
7443     setLabelPadding(12);
7444   } else if (type == atBottom)
7445   {
7446     setTickLabelPadding(3);
7447     setLabelPadding(3);
7448   } else if (type == atLeft)
7449   {
7450     setTickLabelPadding(5);
7451     setLabelPadding(10);
7452   }
7453 }
7454 
~QCPAxis()7455 QCPAxis::~QCPAxis()
7456 {
7457   delete mAxisPainter;
7458   delete mGrid; // delete grid here instead of via parent ~QObject for better defined deletion order
7459 }
7460 
7461 /* No documentation as it is a property getter */
tickLabelPadding() const7462 int QCPAxis::tickLabelPadding() const
7463 {
7464   return mAxisPainter->tickLabelPadding;
7465 }
7466 
7467 /* No documentation as it is a property getter */
tickLabelRotation() const7468 double QCPAxis::tickLabelRotation() const
7469 {
7470   return mAxisPainter->tickLabelRotation;
7471 }
7472 
7473 /* No documentation as it is a property getter */
tickLabelSide() const7474 QCPAxis::LabelSide QCPAxis::tickLabelSide() const
7475 {
7476   return mAxisPainter->tickLabelSide;
7477 }
7478 
7479 /* No documentation as it is a property getter */
numberFormat() const7480 QString QCPAxis::numberFormat() const
7481 {
7482   QString result;
7483   result.append(mNumberFormatChar);
7484   if (mNumberBeautifulPowers)
7485   {
7486     result.append(QLatin1Char('b'));
7487     if (mAxisPainter->numberMultiplyCross)
7488       result.append(QLatin1Char('c'));
7489   }
7490   return result;
7491 }
7492 
7493 /* No documentation as it is a property getter */
tickLengthIn() const7494 int QCPAxis::tickLengthIn() const
7495 {
7496   return mAxisPainter->tickLengthIn;
7497 }
7498 
7499 /* No documentation as it is a property getter */
tickLengthOut() const7500 int QCPAxis::tickLengthOut() const
7501 {
7502   return mAxisPainter->tickLengthOut;
7503 }
7504 
7505 /* No documentation as it is a property getter */
subTickLengthIn() const7506 int QCPAxis::subTickLengthIn() const
7507 {
7508   return mAxisPainter->subTickLengthIn;
7509 }
7510 
7511 /* No documentation as it is a property getter */
subTickLengthOut() const7512 int QCPAxis::subTickLengthOut() const
7513 {
7514   return mAxisPainter->subTickLengthOut;
7515 }
7516 
7517 /* No documentation as it is a property getter */
labelPadding() const7518 int QCPAxis::labelPadding() const
7519 {
7520   return mAxisPainter->labelPadding;
7521 }
7522 
7523 /* No documentation as it is a property getter */
offset() const7524 int QCPAxis::offset() const
7525 {
7526   return mAxisPainter->offset;
7527 }
7528 
7529 /* No documentation as it is a property getter */
lowerEnding() const7530 QCPLineEnding QCPAxis::lowerEnding() const
7531 {
7532   return mAxisPainter->lowerEnding;
7533 }
7534 
7535 /* No documentation as it is a property getter */
upperEnding() const7536 QCPLineEnding QCPAxis::upperEnding() const
7537 {
7538   return mAxisPainter->upperEnding;
7539 }
7540 
7541 /*!
7542   Sets whether the axis uses a linear scale or a logarithmic scale.
7543 
7544   Note that this method controls the coordinate transformation. You will likely also want to use a
7545   logarithmic tick spacing and labeling, which can be achieved by setting an instance of \ref
7546   QCPAxisTickerLog via \ref setTicker. See the documentation of \ref QCPAxisTickerLog about the
7547   details of logarithmic axis tick creation.
7548 
7549   \ref setNumberPrecision
7550 */
setScaleType(QCPAxis::ScaleType type)7551 void QCPAxis::setScaleType(QCPAxis::ScaleType type)
7552 {
7553   if (mScaleType != type)
7554   {
7555     mScaleType = type;
7556     if (mScaleType == stLogarithmic)
7557       setRange(mRange.sanitizedForLogScale());
7558     mCachedMarginValid = false;
7559     emit scaleTypeChanged(mScaleType);
7560   }
7561 }
7562 
7563 /*!
7564   Sets the range of the axis.
7565 
7566   This slot may be connected with the \ref rangeChanged signal of another axis so this axis
7567   is always synchronized with the other axis range, when it changes.
7568 
7569   To invert the direction of an axis, use \ref setRangeReversed.
7570 */
setRange(const QCPRange & range)7571 void QCPAxis::setRange(const QCPRange &range)
7572 {
7573   if (range.lower == mRange.lower && range.upper == mRange.upper)
7574     return;
7575 
7576   if (!QCPRange::validRange(range)) return;
7577   QCPRange oldRange = mRange;
7578   if (mScaleType == stLogarithmic)
7579   {
7580     mRange = range.sanitizedForLogScale();
7581   } else
7582   {
7583     mRange = range.sanitizedForLinScale();
7584   }
7585   emit rangeChanged(mRange);
7586   emit rangeChanged(mRange, oldRange);
7587 }
7588 
7589 /*!
7590   Sets whether the user can (de-)select the parts in \a selectable by clicking on the QCustomPlot surface.
7591   (When \ref QCustomPlot::setInteractions contains iSelectAxes.)
7592 
7593   However, even when \a selectable is set to a value not allowing the selection of a specific part,
7594   it is still possible to set the selection of this part manually, by calling \ref setSelectedParts
7595   directly.
7596 
7597   \see SelectablePart, setSelectedParts
7598 */
setSelectableParts(const SelectableParts & selectable)7599 void QCPAxis::setSelectableParts(const SelectableParts &selectable)
7600 {
7601   if (mSelectableParts != selectable)
7602   {
7603     mSelectableParts = selectable;
7604     emit selectableChanged(mSelectableParts);
7605   }
7606 }
7607 
7608 /*!
7609   Sets the selected state of the respective axis parts described by \ref SelectablePart. When a part
7610   is selected, it uses a different pen/font.
7611 
7612   The entire selection mechanism for axes is handled automatically when \ref
7613   QCustomPlot::setInteractions contains iSelectAxes. You only need to call this function when you
7614   wish to change the selection state manually.
7615 
7616   This function can change the selection state of a part, independent of the \ref setSelectableParts setting.
7617 
7618   emits the \ref selectionChanged signal when \a selected is different from the previous selection state.
7619 
7620   \see SelectablePart, setSelectableParts, selectTest, setSelectedBasePen, setSelectedTickPen, setSelectedSubTickPen,
7621   setSelectedTickLabelFont, setSelectedLabelFont, setSelectedTickLabelColor, setSelectedLabelColor
7622 */
setSelectedParts(const SelectableParts & selected)7623 void QCPAxis::setSelectedParts(const SelectableParts &selected)
7624 {
7625   if (mSelectedParts != selected)
7626   {
7627     mSelectedParts = selected;
7628     emit selectionChanged(mSelectedParts);
7629   }
7630 }
7631 
7632 /*!
7633   \overload
7634 
7635   Sets the lower and upper bound of the axis range.
7636 
7637   To invert the direction of an axis, use \ref setRangeReversed.
7638 
7639   There is also a slot to set a range, see \ref setRange(const QCPRange &range).
7640 */
setRange(double lower,double upper)7641 void QCPAxis::setRange(double lower, double upper)
7642 {
7643   if (lower == mRange.lower && upper == mRange.upper)
7644     return;
7645 
7646   if (!QCPRange::validRange(lower, upper)) return;
7647   QCPRange oldRange = mRange;
7648   mRange.lower = lower;
7649   mRange.upper = upper;
7650   if (mScaleType == stLogarithmic)
7651   {
7652     mRange = mRange.sanitizedForLogScale();
7653   } else
7654   {
7655     mRange = mRange.sanitizedForLinScale();
7656   }
7657   emit rangeChanged(mRange);
7658   emit rangeChanged(mRange, oldRange);
7659 }
7660 
7661 /*!
7662   \overload
7663 
7664   Sets the range of the axis.
7665 
7666   The \a position coordinate indicates together with the \a alignment parameter, where the new
7667   range will be positioned. \a size defines the size of the new axis range. \a alignment may be
7668   Qt::AlignLeft, Qt::AlignRight or Qt::AlignCenter. This will cause the left border, right border,
7669   or center of the range to be aligned with \a position. Any other values of \a alignment will
7670   default to Qt::AlignCenter.
7671 */
setRange(double position,double size,Qt::AlignmentFlag alignment)7672 void QCPAxis::setRange(double position, double size, Qt::AlignmentFlag alignment)
7673 {
7674   if (alignment == Qt::AlignLeft)
7675     setRange(position, position+size);
7676   else if (alignment == Qt::AlignRight)
7677     setRange(position-size, position);
7678   else // alignment == Qt::AlignCenter
7679     setRange(position-size/2.0, position+size/2.0);
7680 }
7681 
7682 /*!
7683   Sets the lower bound of the axis range. The upper bound is not changed.
7684   \see setRange
7685 */
setRangeLower(double lower)7686 void QCPAxis::setRangeLower(double lower)
7687 {
7688   if (mRange.lower == lower)
7689     return;
7690 
7691   QCPRange oldRange = mRange;
7692   mRange.lower = lower;
7693   if (mScaleType == stLogarithmic)
7694   {
7695     mRange = mRange.sanitizedForLogScale();
7696   } else
7697   {
7698     mRange = mRange.sanitizedForLinScale();
7699   }
7700   emit rangeChanged(mRange);
7701   emit rangeChanged(mRange, oldRange);
7702 }
7703 
7704 /*!
7705   Sets the upper bound of the axis range. The lower bound is not changed.
7706   \see setRange
7707 */
setRangeUpper(double upper)7708 void QCPAxis::setRangeUpper(double upper)
7709 {
7710   if (mRange.upper == upper)
7711     return;
7712 
7713   QCPRange oldRange = mRange;
7714   mRange.upper = upper;
7715   if (mScaleType == stLogarithmic)
7716   {
7717     mRange = mRange.sanitizedForLogScale();
7718   } else
7719   {
7720     mRange = mRange.sanitizedForLinScale();
7721   }
7722   emit rangeChanged(mRange);
7723   emit rangeChanged(mRange, oldRange);
7724 }
7725 
7726 /*!
7727   Sets whether the axis range (direction) is displayed reversed. Normally, the values on horizontal
7728   axes increase left to right, on vertical axes bottom to top. When \a reversed is set to true, the
7729   direction of increasing values is inverted.
7730 
7731   Note that the range and data interface stays the same for reversed axes, e.g. the \a lower part
7732   of the \ref setRange interface will still reference the mathematically smaller number than the \a
7733   upper part.
7734 */
setRangeReversed(bool reversed)7735 void QCPAxis::setRangeReversed(bool reversed)
7736 {
7737   mRangeReversed = reversed;
7738 }
7739 
7740 /*!
7741   The axis ticker is responsible for generating the tick positions and tick labels. See the
7742   documentation of QCPAxisTicker for details on how to work with axis tickers.
7743 
7744   You can change the tick positioning/labeling behaviour of this axis by setting a different
7745   QCPAxisTicker subclass using this method. If you only wish to modify the currently installed axis
7746   ticker, access it via \ref ticker.
7747 
7748   Since the ticker is stored in the axis as a shared pointer, multiple axes may share the same axis
7749   ticker simply by passing the same shared pointer to multiple axes.
7750 
7751   \see ticker
7752 */
setTicker(QSharedPointer<QCPAxisTicker> ticker)7753 void QCPAxis::setTicker(QSharedPointer<QCPAxisTicker> ticker)
7754 {
7755   if (ticker)
7756     mTicker = ticker;
7757   else
7758     qDebug() << Q_FUNC_INFO << "can not set 0 as axis ticker";
7759   // no need to invalidate margin cache here because produced tick labels are checked for changes in setupTickVector
7760 }
7761 
7762 /*!
7763   Sets whether tick marks are displayed.
7764 
7765   Note that setting \a show to false does not imply that tick labels are invisible, too. To achieve
7766   that, see \ref setTickLabels.
7767 
7768   \see setSubTicks
7769 */
setTicks(bool show)7770 void QCPAxis::setTicks(bool show)
7771 {
7772   if (mTicks != show)
7773   {
7774     mTicks = show;
7775     mCachedMarginValid = false;
7776   }
7777 }
7778 
7779 /*!
7780   Sets whether tick labels are displayed. Tick labels are the numbers drawn next to tick marks.
7781 */
setTickLabels(bool show)7782 void QCPAxis::setTickLabels(bool show)
7783 {
7784   if (mTickLabels != show)
7785   {
7786     mTickLabels = show;
7787     mCachedMarginValid = false;
7788     if (!mTickLabels)
7789       mTickVectorLabels.clear();
7790   }
7791 }
7792 
7793 /*!
7794   Sets the distance between the axis base line (including any outward ticks) and the tick labels.
7795   \see setLabelPadding, setPadding
7796 */
setTickLabelPadding(int padding)7797 void QCPAxis::setTickLabelPadding(int padding)
7798 {
7799   if (mAxisPainter->tickLabelPadding != padding)
7800   {
7801     mAxisPainter->tickLabelPadding = padding;
7802     mCachedMarginValid = false;
7803   }
7804 }
7805 
7806 /*!
7807   Sets the font of the tick labels.
7808 
7809   \see setTickLabels, setTickLabelColor
7810 */
setTickLabelFont(const QFont & font)7811 void QCPAxis::setTickLabelFont(const QFont &font)
7812 {
7813   if (font != mTickLabelFont)
7814   {
7815     mTickLabelFont = font;
7816     mCachedMarginValid = false;
7817   }
7818 }
7819 
7820 /*!
7821   Sets the color of the tick labels.
7822 
7823   \see setTickLabels, setTickLabelFont
7824 */
setTickLabelColor(const QColor & color)7825 void QCPAxis::setTickLabelColor(const QColor &color)
7826 {
7827   mTickLabelColor = color;
7828 }
7829 
7830 /*!
7831   Sets the rotation of the tick labels. If \a degrees is zero, the labels are drawn normally. Else,
7832   the tick labels are drawn rotated by \a degrees clockwise. The specified angle is bound to values
7833   from -90 to 90 degrees.
7834 
7835   If \a degrees is exactly -90, 0 or 90, the tick labels are centered on the tick coordinate. For
7836   other angles, the label is drawn with an offset such that it seems to point toward or away from
7837   the tick mark.
7838 */
setTickLabelRotation(double degrees)7839 void QCPAxis::setTickLabelRotation(double degrees)
7840 {
7841   if (!qFuzzyIsNull(degrees-mAxisPainter->tickLabelRotation))
7842   {
7843     mAxisPainter->tickLabelRotation = qBound(-90.0, degrees, 90.0);
7844     mCachedMarginValid = false;
7845   }
7846 }
7847 
7848 /*!
7849   Sets whether the tick labels (numbers) shall appear inside or outside the axis rect.
7850 
7851   The usual and default setting is \ref lsOutside. Very compact plots sometimes require tick labels
7852   to be inside the axis rect, to save space. If \a side is set to \ref lsInside, the tick labels
7853   appear on the inside are additionally clipped to the axis rect.
7854 */
setTickLabelSide(LabelSide side)7855 void QCPAxis::setTickLabelSide(LabelSide side)
7856 {
7857   mAxisPainter->tickLabelSide = side;
7858   mCachedMarginValid = false;
7859 }
7860 
7861 /*!
7862   Sets the number format for the numbers in tick labels. This \a formatCode is an extended version
7863   of the format code used e.g. by QString::number() and QLocale::toString(). For reference about
7864   that, see the "Argument Formats" section in the detailed description of the QString class.
7865 
7866   \a formatCode is a string of one, two or three characters. The first character is identical to
7867   the normal format code used by Qt. In short, this means: 'e'/'E' scientific format, 'f' fixed
7868   format, 'g'/'G' scientific or fixed, whichever is shorter.
7869 
7870   The second and third characters are optional and specific to QCustomPlot:\n
7871   If the first char was 'e' or 'g', numbers are/might be displayed in the scientific format, e.g.
7872   "5.5e9", which is ugly in a plot. So when the second char of \a formatCode is set to 'b' (for
7873   "beautiful"), those exponential numbers are formatted in a more natural way, i.e. "5.5
7874   [multiplication sign] 10 [superscript] 9". By default, the multiplication sign is a centered dot.
7875   If instead a cross should be shown (as is usual in the USA), the third char of \a formatCode can
7876   be set to 'c'. The inserted multiplication signs are the UTF-8 characters 215 (0xD7) for the
7877   cross and 183 (0xB7) for the dot.
7878 
7879   Examples for \a formatCode:
7880   \li \c g normal format code behaviour. If number is small, fixed format is used, if number is large,
7881   normal scientific format is used
7882   \li \c gb If number is small, fixed format is used, if number is large, scientific format is used with
7883   beautifully typeset decimal powers and a dot as multiplication sign
7884   \li \c ebc All numbers are in scientific format with beautifully typeset decimal power and a cross as
7885   multiplication sign
7886   \li \c fb illegal format code, since fixed format doesn't support (or need) beautifully typeset decimal
7887   powers. Format code will be reduced to 'f'.
7888   \li \c hello illegal format code, since first char is not 'e', 'E', 'f', 'g' or 'G'. Current format
7889   code will not be changed.
7890 */
setNumberFormat(const QString & formatCode)7891 void QCPAxis::setNumberFormat(const QString &formatCode)
7892 {
7893   if (formatCode.isEmpty())
7894   {
7895     qDebug() << Q_FUNC_INFO << "Passed formatCode is empty";
7896     return;
7897   }
7898   mCachedMarginValid = false;
7899 
7900   // interpret first char as number format char:
7901   QString allowedFormatChars(QLatin1String("eEfgG"));
7902   if (allowedFormatChars.contains(formatCode.at(0)))
7903   {
7904     mNumberFormatChar = QLatin1Char(formatCode.at(0).toLatin1());
7905   } else
7906   {
7907     qDebug() << Q_FUNC_INFO << "Invalid number format code (first char not in 'eEfgG'):" << formatCode;
7908     return;
7909   }
7910   if (formatCode.length() < 2)
7911   {
7912     mNumberBeautifulPowers = false;
7913     mAxisPainter->numberMultiplyCross = false;
7914     return;
7915   }
7916 
7917   // interpret second char as indicator for beautiful decimal powers:
7918   if (formatCode.at(1) == QLatin1Char('b') && (mNumberFormatChar == QLatin1Char('e') || mNumberFormatChar == QLatin1Char('g')))
7919   {
7920     mNumberBeautifulPowers = true;
7921   } else
7922   {
7923     qDebug() << Q_FUNC_INFO << "Invalid number format code (second char not 'b' or first char neither 'e' nor 'g'):" << formatCode;
7924     return;
7925   }
7926   if (formatCode.length() < 3)
7927   {
7928     mAxisPainter->numberMultiplyCross = false;
7929     return;
7930   }
7931 
7932   // interpret third char as indicator for dot or cross multiplication symbol:
7933   if (formatCode.at(2) == QLatin1Char('c'))
7934   {
7935     mAxisPainter->numberMultiplyCross = true;
7936   } else if (formatCode.at(2) == QLatin1Char('d'))
7937   {
7938     mAxisPainter->numberMultiplyCross = false;
7939   } else
7940   {
7941     qDebug() << Q_FUNC_INFO << "Invalid number format code (third char neither 'c' nor 'd'):" << formatCode;
7942     return;
7943   }
7944 }
7945 
7946 /*!
7947   Sets the precision of the tick label numbers. See QLocale::toString(double i, char f, int prec)
7948   for details. The effect of precisions are most notably for number Formats starting with 'e', see
7949   \ref setNumberFormat
7950 */
setNumberPrecision(int precision)7951 void QCPAxis::setNumberPrecision(int precision)
7952 {
7953   if (mNumberPrecision != precision)
7954   {
7955     mNumberPrecision = precision;
7956     mCachedMarginValid = false;
7957   }
7958 }
7959 
7960 /*!
7961   Sets the length of the ticks in pixels. \a inside is the length the ticks will reach inside the
7962   plot and \a outside is the length they will reach outside the plot. If \a outside is greater than
7963   zero, the tick labels and axis label will increase their distance to the axis accordingly, so
7964   they won't collide with the ticks.
7965 
7966   \see setSubTickLength, setTickLengthIn, setTickLengthOut
7967 */
setTickLength(int inside,int outside)7968 void QCPAxis::setTickLength(int inside, int outside)
7969 {
7970   setTickLengthIn(inside);
7971   setTickLengthOut(outside);
7972 }
7973 
7974 /*!
7975   Sets the length of the inward ticks in pixels. \a inside is the length the ticks will reach
7976   inside the plot.
7977 
7978   \see setTickLengthOut, setTickLength, setSubTickLength
7979 */
setTickLengthIn(int inside)7980 void QCPAxis::setTickLengthIn(int inside)
7981 {
7982   if (mAxisPainter->tickLengthIn != inside)
7983   {
7984     mAxisPainter->tickLengthIn = inside;
7985   }
7986 }
7987 
7988 /*!
7989   Sets the length of the outward ticks in pixels. \a outside is the length the ticks will reach
7990   outside the plot. If \a outside is greater than zero, the tick labels and axis label will
7991   increase their distance to the axis accordingly, so they won't collide with the ticks.
7992 
7993   \see setTickLengthIn, setTickLength, setSubTickLength
7994 */
setTickLengthOut(int outside)7995 void QCPAxis::setTickLengthOut(int outside)
7996 {
7997   if (mAxisPainter->tickLengthOut != outside)
7998   {
7999     mAxisPainter->tickLengthOut = outside;
8000     mCachedMarginValid = false; // only outside tick length can change margin
8001   }
8002 }
8003 
8004 /*!
8005   Sets whether sub tick marks are displayed.
8006 
8007   Sub ticks are only potentially visible if (major) ticks are also visible (see \ref setTicks)
8008 
8009   \see setTicks
8010 */
setSubTicks(bool show)8011 void QCPAxis::setSubTicks(bool show)
8012 {
8013   if (mSubTicks != show)
8014   {
8015     mSubTicks = show;
8016     mCachedMarginValid = false;
8017   }
8018 }
8019 
8020 /*!
8021   Sets the length of the subticks in pixels. \a inside is the length the subticks will reach inside
8022   the plot and \a outside is the length they will reach outside the plot. If \a outside is greater
8023   than zero, the tick labels and axis label will increase their distance to the axis accordingly,
8024   so they won't collide with the ticks.
8025 
8026   \see setTickLength, setSubTickLengthIn, setSubTickLengthOut
8027 */
setSubTickLength(int inside,int outside)8028 void QCPAxis::setSubTickLength(int inside, int outside)
8029 {
8030   setSubTickLengthIn(inside);
8031   setSubTickLengthOut(outside);
8032 }
8033 
8034 /*!
8035   Sets the length of the inward subticks in pixels. \a inside is the length the subticks will reach inside
8036   the plot.
8037 
8038   \see setSubTickLengthOut, setSubTickLength, setTickLength
8039 */
setSubTickLengthIn(int inside)8040 void QCPAxis::setSubTickLengthIn(int inside)
8041 {
8042   if (mAxisPainter->subTickLengthIn != inside)
8043   {
8044     mAxisPainter->subTickLengthIn = inside;
8045   }
8046 }
8047 
8048 /*!
8049   Sets the length of the outward subticks in pixels. \a outside is the length the subticks will reach
8050   outside the plot. If \a outside is greater than zero, the tick labels will increase their
8051   distance to the axis accordingly, so they won't collide with the ticks.
8052 
8053   \see setSubTickLengthIn, setSubTickLength, setTickLength
8054 */
setSubTickLengthOut(int outside)8055 void QCPAxis::setSubTickLengthOut(int outside)
8056 {
8057   if (mAxisPainter->subTickLengthOut != outside)
8058   {
8059     mAxisPainter->subTickLengthOut = outside;
8060     mCachedMarginValid = false; // only outside tick length can change margin
8061   }
8062 }
8063 
8064 /*!
8065   Sets the pen, the axis base line is drawn with.
8066 
8067   \see setTickPen, setSubTickPen
8068 */
setBasePen(const QPen & pen)8069 void QCPAxis::setBasePen(const QPen &pen)
8070 {
8071   mBasePen = pen;
8072 }
8073 
8074 /*!
8075   Sets the pen, tick marks will be drawn with.
8076 
8077   \see setTickLength, setBasePen
8078 */
setTickPen(const QPen & pen)8079 void QCPAxis::setTickPen(const QPen &pen)
8080 {
8081   mTickPen = pen;
8082 }
8083 
8084 /*!
8085   Sets the pen, subtick marks will be drawn with.
8086 
8087   \see setSubTickCount, setSubTickLength, setBasePen
8088 */
setSubTickPen(const QPen & pen)8089 void QCPAxis::setSubTickPen(const QPen &pen)
8090 {
8091   mSubTickPen = pen;
8092 }
8093 
8094 /*!
8095   Sets the font of the axis label.
8096 
8097   \see setLabelColor
8098 */
setLabelFont(const QFont & font)8099 void QCPAxis::setLabelFont(const QFont &font)
8100 {
8101   if (mLabelFont != font)
8102   {
8103     mLabelFont = font;
8104     mCachedMarginValid = false;
8105   }
8106 }
8107 
8108 /*!
8109   Sets the color of the axis label.
8110 
8111   \see setLabelFont
8112 */
setLabelColor(const QColor & color)8113 void QCPAxis::setLabelColor(const QColor &color)
8114 {
8115   mLabelColor = color;
8116 }
8117 
8118 /*!
8119   Sets the text of the axis label that will be shown below/above or next to the axis, depending on
8120   its orientation. To disable axis labels, pass an empty string as \a str.
8121 */
setLabel(const QString & str)8122 void QCPAxis::setLabel(const QString &str)
8123 {
8124   if (mLabel != str)
8125   {
8126     mLabel = str;
8127     mCachedMarginValid = false;
8128   }
8129 }
8130 
8131 /*!
8132   Sets the distance between the tick labels and the axis label.
8133 
8134   \see setTickLabelPadding, setPadding
8135 */
setLabelPadding(int padding)8136 void QCPAxis::setLabelPadding(int padding)
8137 {
8138   if (mAxisPainter->labelPadding != padding)
8139   {
8140     mAxisPainter->labelPadding = padding;
8141     mCachedMarginValid = false;
8142   }
8143 }
8144 
8145 /*!
8146   Sets the padding of the axis.
8147 
8148   When \ref QCPAxisRect::setAutoMargins is enabled, the padding is the additional outer most space,
8149   that is left blank.
8150 
8151   The axis padding has no meaning if \ref QCPAxisRect::setAutoMargins is disabled.
8152 
8153   \see setLabelPadding, setTickLabelPadding
8154 */
setPadding(int padding)8155 void QCPAxis::setPadding(int padding)
8156 {
8157   if (mPadding != padding)
8158   {
8159     mPadding = padding;
8160     mCachedMarginValid = false;
8161   }
8162 }
8163 
8164 /*!
8165   Sets the offset the axis has to its axis rect side.
8166 
8167   If an axis rect side has multiple axes and automatic margin calculation is enabled for that side,
8168   only the offset of the inner most axis has meaning (even if it is set to be invisible). The
8169   offset of the other, outer axes is controlled automatically, to place them at appropriate
8170   positions.
8171 */
setOffset(int offset)8172 void QCPAxis::setOffset(int offset)
8173 {
8174   mAxisPainter->offset = offset;
8175 }
8176 
8177 /*!
8178   Sets the font that is used for tick labels when they are selected.
8179 
8180   \see setTickLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
8181 */
setSelectedTickLabelFont(const QFont & font)8182 void QCPAxis::setSelectedTickLabelFont(const QFont &font)
8183 {
8184   if (font != mSelectedTickLabelFont)
8185   {
8186     mSelectedTickLabelFont = font;
8187     // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts
8188   }
8189 }
8190 
8191 /*!
8192   Sets the font that is used for the axis label when it is selected.
8193 
8194   \see setLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
8195 */
setSelectedLabelFont(const QFont & font)8196 void QCPAxis::setSelectedLabelFont(const QFont &font)
8197 {
8198   mSelectedLabelFont = font;
8199   // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts
8200 }
8201 
8202 /*!
8203   Sets the color that is used for tick labels when they are selected.
8204 
8205   \see setTickLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
8206 */
setSelectedTickLabelColor(const QColor & color)8207 void QCPAxis::setSelectedTickLabelColor(const QColor &color)
8208 {
8209   if (color != mSelectedTickLabelColor)
8210   {
8211     mSelectedTickLabelColor = color;
8212   }
8213 }
8214 
8215 /*!
8216   Sets the color that is used for the axis label when it is selected.
8217 
8218   \see setLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
8219 */
setSelectedLabelColor(const QColor & color)8220 void QCPAxis::setSelectedLabelColor(const QColor &color)
8221 {
8222   mSelectedLabelColor = color;
8223 }
8224 
8225 /*!
8226   Sets the pen that is used to draw the axis base line when selected.
8227 
8228   \see setBasePen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
8229 */
setSelectedBasePen(const QPen & pen)8230 void QCPAxis::setSelectedBasePen(const QPen &pen)
8231 {
8232   mSelectedBasePen = pen;
8233 }
8234 
8235 /*!
8236   Sets the pen that is used to draw the (major) ticks when selected.
8237 
8238   \see setTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
8239 */
setSelectedTickPen(const QPen & pen)8240 void QCPAxis::setSelectedTickPen(const QPen &pen)
8241 {
8242   mSelectedTickPen = pen;
8243 }
8244 
8245 /*!
8246   Sets the pen that is used to draw the subticks when selected.
8247 
8248   \see setSubTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
8249 */
setSelectedSubTickPen(const QPen & pen)8250 void QCPAxis::setSelectedSubTickPen(const QPen &pen)
8251 {
8252   mSelectedSubTickPen = pen;
8253 }
8254 
8255 /*!
8256   Sets the style for the lower axis ending. See the documentation of QCPLineEnding for available
8257   styles.
8258 
8259   For horizontal axes, this method refers to the left ending, for vertical axes the bottom ending.
8260   Note that this meaning does not change when the axis range is reversed with \ref
8261   setRangeReversed.
8262 
8263   \see setUpperEnding
8264 */
setLowerEnding(const QCPLineEnding & ending)8265 void QCPAxis::setLowerEnding(const QCPLineEnding &ending)
8266 {
8267   mAxisPainter->lowerEnding = ending;
8268 }
8269 
8270 /*!
8271   Sets the style for the upper axis ending. See the documentation of QCPLineEnding for available
8272   styles.
8273 
8274   For horizontal axes, this method refers to the right ending, for vertical axes the top ending.
8275   Note that this meaning does not change when the axis range is reversed with \ref
8276   setRangeReversed.
8277 
8278   \see setLowerEnding
8279 */
setUpperEnding(const QCPLineEnding & ending)8280 void QCPAxis::setUpperEnding(const QCPLineEnding &ending)
8281 {
8282   mAxisPainter->upperEnding = ending;
8283 }
8284 
8285 /*!
8286   If the scale type (\ref setScaleType) is \ref stLinear, \a diff is added to the lower and upper
8287   bounds of the range. The range is simply moved by \a diff.
8288 
8289   If the scale type is \ref stLogarithmic, the range bounds are multiplied by \a diff. This
8290   corresponds to an apparent "linear" move in logarithmic scaling by a distance of log(diff).
8291 */
moveRange(double diff)8292 void QCPAxis::moveRange(double diff)
8293 {
8294   QCPRange oldRange = mRange;
8295   if (mScaleType == stLinear)
8296   {
8297     mRange.lower += diff;
8298     mRange.upper += diff;
8299   } else // mScaleType == stLogarithmic
8300   {
8301     mRange.lower *= diff;
8302     mRange.upper *= diff;
8303   }
8304   emit rangeChanged(mRange);
8305   emit rangeChanged(mRange, oldRange);
8306 }
8307 
8308 /*!
8309   Scales the range of this axis by \a factor around the center of the current axis range. For
8310   example, if \a factor is 2.0, then the axis range will double its size, and the point at the axis
8311   range center won't have changed its position in the QCustomPlot widget (i.e. coordinates around
8312   the center will have moved symmetrically closer).
8313 
8314   If you wish to scale around a different coordinate than the current axis range center, use the
8315   overload \ref scaleRange(double factor, double center).
8316 */
scaleRange(double factor)8317 void QCPAxis::scaleRange(double factor)
8318 {
8319   scaleRange(factor, range().center());
8320 }
8321 
8322 /*! \overload
8323 
8324   Scales the range of this axis by \a factor around the coordinate \a center. For example, if \a
8325   factor is 2.0, \a center is 1.0, then the axis range will double its size, and the point at
8326   coordinate 1.0 won't have changed its position in the QCustomPlot widget (i.e. coordinates
8327   around 1.0 will have moved symmetrically closer to 1.0).
8328 
8329   \see scaleRange(double factor)
8330 */
scaleRange(double factor,double center)8331 void QCPAxis::scaleRange(double factor, double center)
8332 {
8333   QCPRange oldRange = mRange;
8334   if (mScaleType == stLinear)
8335   {
8336     QCPRange newRange;
8337     newRange.lower = (mRange.lower-center)*factor + center;
8338     newRange.upper = (mRange.upper-center)*factor + center;
8339     if (QCPRange::validRange(newRange))
8340       mRange = newRange.sanitizedForLinScale();
8341   } else // mScaleType == stLogarithmic
8342   {
8343     if ((mRange.upper < 0 && center < 0) || (mRange.upper > 0 && center > 0)) // make sure center has same sign as range
8344     {
8345       QCPRange newRange;
8346       newRange.lower = qPow(mRange.lower/center, factor)*center;
8347       newRange.upper = qPow(mRange.upper/center, factor)*center;
8348       if (QCPRange::validRange(newRange))
8349         mRange = newRange.sanitizedForLogScale();
8350     } else
8351       qDebug() << Q_FUNC_INFO << "Center of scaling operation doesn't lie in same logarithmic sign domain as range:" << center;
8352   }
8353   emit rangeChanged(mRange);
8354   emit rangeChanged(mRange, oldRange);
8355 }
8356 
8357 /*!
8358   Scales the range of this axis to have a certain scale \a ratio to \a otherAxis. The scaling will
8359   be done around the center of the current axis range.
8360 
8361   For example, if \a ratio is 1, this axis is the \a yAxis and \a otherAxis is \a xAxis, graphs
8362   plotted with those axes will appear in a 1:1 aspect ratio, independent of the aspect ratio the
8363   axis rect has.
8364 
8365   This is an operation that changes the range of this axis once, it doesn't fix the scale ratio
8366   indefinitely. Note that calling this function in the constructor of the QCustomPlot's parent
8367   won't have the desired effect, since the widget dimensions aren't defined yet, and a resizeEvent
8368   will follow.
8369 */
setScaleRatio(const QCPAxis * otherAxis,double ratio)8370 void QCPAxis::setScaleRatio(const QCPAxis *otherAxis, double ratio)
8371 {
8372   int otherPixelSize, ownPixelSize;
8373 
8374   if (otherAxis->orientation() == Qt::Horizontal)
8375     otherPixelSize = otherAxis->axisRect()->width();
8376   else
8377     otherPixelSize = otherAxis->axisRect()->height();
8378 
8379   if (orientation() == Qt::Horizontal)
8380     ownPixelSize = axisRect()->width();
8381   else
8382     ownPixelSize = axisRect()->height();
8383 
8384   double newRangeSize = ratio*otherAxis->range().size()*ownPixelSize/(double)otherPixelSize;
8385   setRange(range().center(), newRangeSize, Qt::AlignCenter);
8386 }
8387 
8388 /*!
8389   Changes the axis range such that all plottables associated with this axis are fully visible in
8390   that dimension.
8391 
8392   \see QCPAbstractPlottable::rescaleAxes, QCustomPlot::rescaleAxes
8393 */
rescale(bool onlyVisiblePlottables)8394 void QCPAxis::rescale(bool onlyVisiblePlottables)
8395 {
8396   QList<QCPAbstractPlottable*> p = plottables();
8397   QCPRange newRange;
8398   bool haveRange = false;
8399   for (int i=0; i<p.size(); ++i)
8400   {
8401     if (!p.at(i)->realVisibility() && onlyVisiblePlottables)
8402       continue;
8403     QCPRange plottableRange;
8404     bool currentFoundRange;
8405     QCP::SignDomain signDomain = QCP::sdBoth;
8406     if (mScaleType == stLogarithmic)
8407       signDomain = (mRange.upper < 0 ? QCP::sdNegative : QCP::sdPositive);
8408     if (p.at(i)->keyAxis() == this)
8409       plottableRange = p.at(i)->getKeyRange(currentFoundRange, signDomain);
8410     else
8411       plottableRange = p.at(i)->getValueRange(currentFoundRange, signDomain);
8412     if (currentFoundRange)
8413     {
8414       if (!haveRange)
8415         newRange = plottableRange;
8416       else
8417         newRange.expand(plottableRange);
8418       haveRange = true;
8419     }
8420   }
8421   if (haveRange)
8422   {
8423     if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable
8424     {
8425       double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason
8426       if (mScaleType == stLinear)
8427       {
8428         newRange.lower = center-mRange.size()/2.0;
8429         newRange.upper = center+mRange.size()/2.0;
8430       } else // mScaleType == stLogarithmic
8431       {
8432         newRange.lower = center/qSqrt(mRange.upper/mRange.lower);
8433         newRange.upper = center*qSqrt(mRange.upper/mRange.lower);
8434       }
8435     }
8436     setRange(newRange);
8437   }
8438 }
8439 
8440 /*!
8441   Transforms \a value, in pixel coordinates of the QCustomPlot widget, to axis coordinates.
8442 */
pixelToCoord(double value) const8443 double QCPAxis::pixelToCoord(double value) const
8444 {
8445   if (orientation() == Qt::Horizontal)
8446   {
8447     if (mScaleType == stLinear)
8448     {
8449       if (!mRangeReversed)
8450         return (value-mAxisRect->left())/(double)mAxisRect->width()*mRange.size()+mRange.lower;
8451       else
8452         return -(value-mAxisRect->left())/(double)mAxisRect->width()*mRange.size()+mRange.upper;
8453     } else // mScaleType == stLogarithmic
8454     {
8455       if (!mRangeReversed)
8456         return qPow(mRange.upper/mRange.lower, (value-mAxisRect->left())/(double)mAxisRect->width())*mRange.lower;
8457       else
8458         return qPow(mRange.upper/mRange.lower, (mAxisRect->left()-value)/(double)mAxisRect->width())*mRange.upper;
8459     }
8460   } else // orientation() == Qt::Vertical
8461   {
8462     if (mScaleType == stLinear)
8463     {
8464       if (!mRangeReversed)
8465         return (mAxisRect->bottom()-value)/(double)mAxisRect->height()*mRange.size()+mRange.lower;
8466       else
8467         return -(mAxisRect->bottom()-value)/(double)mAxisRect->height()*mRange.size()+mRange.upper;
8468     } else // mScaleType == stLogarithmic
8469     {
8470       if (!mRangeReversed)
8471         return qPow(mRange.upper/mRange.lower, (mAxisRect->bottom()-value)/(double)mAxisRect->height())*mRange.lower;
8472       else
8473         return qPow(mRange.upper/mRange.lower, (value-mAxisRect->bottom())/(double)mAxisRect->height())*mRange.upper;
8474     }
8475   }
8476 }
8477 
8478 /*!
8479   Transforms \a value, in coordinates of the axis, to pixel coordinates of the QCustomPlot widget.
8480 */
coordToPixel(double value) const8481 double QCPAxis::coordToPixel(double value) const
8482 {
8483   if (orientation() == Qt::Horizontal)
8484   {
8485     if (mScaleType == stLinear)
8486     {
8487       if (!mRangeReversed)
8488         return (value-mRange.lower)/mRange.size()*mAxisRect->width()+mAxisRect->left();
8489       else
8490         return (mRange.upper-value)/mRange.size()*mAxisRect->width()+mAxisRect->left();
8491     } else // mScaleType == stLogarithmic
8492     {
8493       if (value >= 0 && mRange.upper < 0) // invalid value for logarithmic scale, just draw it outside visible range
8494         return !mRangeReversed ? mAxisRect->right()+200 : mAxisRect->left()-200;
8495       else if (value <= 0 && mRange.upper > 0) // invalid value for logarithmic scale, just draw it outside visible range
8496         return !mRangeReversed ? mAxisRect->left()-200 : mAxisRect->right()+200;
8497       else
8498       {
8499         if (!mRangeReversed)
8500           return qLn(value/mRange.lower)/qLn(mRange.upper/mRange.lower)*mAxisRect->width()+mAxisRect->left();
8501         else
8502           return qLn(mRange.upper/value)/qLn(mRange.upper/mRange.lower)*mAxisRect->width()+mAxisRect->left();
8503       }
8504     }
8505   } else // orientation() == Qt::Vertical
8506   {
8507     if (mScaleType == stLinear)
8508     {
8509       if (!mRangeReversed)
8510         return mAxisRect->bottom()-(value-mRange.lower)/mRange.size()*mAxisRect->height();
8511       else
8512         return mAxisRect->bottom()-(mRange.upper-value)/mRange.size()*mAxisRect->height();
8513     } else // mScaleType == stLogarithmic
8514     {
8515       if (value >= 0 && mRange.upper < 0) // invalid value for logarithmic scale, just draw it outside visible range
8516         return !mRangeReversed ? mAxisRect->top()-200 : mAxisRect->bottom()+200;
8517       else if (value <= 0 && mRange.upper > 0) // invalid value for logarithmic scale, just draw it outside visible range
8518         return !mRangeReversed ? mAxisRect->bottom()+200 : mAxisRect->top()-200;
8519       else
8520       {
8521         if (!mRangeReversed)
8522           return mAxisRect->bottom()-qLn(value/mRange.lower)/qLn(mRange.upper/mRange.lower)*mAxisRect->height();
8523         else
8524           return mAxisRect->bottom()-qLn(mRange.upper/value)/qLn(mRange.upper/mRange.lower)*mAxisRect->height();
8525       }
8526     }
8527   }
8528 }
8529 
8530 /*!
8531   Returns the part of the axis that is hit by \a pos (in pixels). The return value of this function
8532   is independent of the user-selectable parts defined with \ref setSelectableParts. Further, this
8533   function does not change the current selection state of the axis.
8534 
8535   If the axis is not visible (\ref setVisible), this function always returns \ref spNone.
8536 
8537   \see setSelectedParts, setSelectableParts, QCustomPlot::setInteractions
8538 */
getPartAt(const QPointF & pos) const8539 QCPAxis::SelectablePart QCPAxis::getPartAt(const QPointF &pos) const
8540 {
8541   if (!mVisible)
8542     return spNone;
8543 
8544   if (mAxisPainter->axisSelectionBox().contains(pos.toPoint()))
8545     return spAxis;
8546   else if (mAxisPainter->tickLabelsSelectionBox().contains(pos.toPoint()))
8547     return spTickLabels;
8548   else if (mAxisPainter->labelSelectionBox().contains(pos.toPoint()))
8549     return spAxisLabel;
8550   else
8551     return spNone;
8552 }
8553 
8554 /* inherits documentation from base class */
selectTest(const QPointF & pos,bool onlySelectable,QVariant * details) const8555 double QCPAxis::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
8556 {
8557   if (!mParentPlot) return -1;
8558   SelectablePart part = getPartAt(pos);
8559   if ((onlySelectable && !mSelectableParts.testFlag(part)) || part == spNone)
8560     return -1;
8561 
8562   if (details)
8563     details->setValue(part);
8564   return mParentPlot->selectionTolerance()*0.99;
8565 }
8566 
8567 /*!
8568   Returns a list of all the plottables that have this axis as key or value axis.
8569 
8570   If you are only interested in plottables of type QCPGraph, see \ref graphs.
8571 
8572   \see graphs, items
8573 */
plottables() const8574 QList<QCPAbstractPlottable*> QCPAxis::plottables() const
8575 {
8576   QList<QCPAbstractPlottable*> result;
8577   if (!mParentPlot) return result;
8578 
8579   for (int i=0; i<mParentPlot->mPlottables.size(); ++i)
8580   {
8581     if (mParentPlot->mPlottables.at(i)->keyAxis() == this ||mParentPlot->mPlottables.at(i)->valueAxis() == this)
8582       result.append(mParentPlot->mPlottables.at(i));
8583   }
8584   return result;
8585 }
8586 
8587 /*!
8588   Returns a list of all the graphs that have this axis as key or value axis.
8589 
8590   \see plottables, items
8591 */
graphs() const8592 QList<QCPGraph*> QCPAxis::graphs() const
8593 {
8594   QList<QCPGraph*> result;
8595   if (!mParentPlot) return result;
8596 
8597   for (int i=0; i<mParentPlot->mGraphs.size(); ++i)
8598   {
8599     if (mParentPlot->mGraphs.at(i)->keyAxis() == this || mParentPlot->mGraphs.at(i)->valueAxis() == this)
8600       result.append(mParentPlot->mGraphs.at(i));
8601   }
8602   return result;
8603 }
8604 
8605 /*!
8606   Returns a list of all the items that are associated with this axis. An item is considered
8607   associated with an axis if at least one of its positions uses the axis as key or value axis.
8608 
8609   \see plottables, graphs
8610 */
items() const8611 QList<QCPAbstractItem*> QCPAxis::items() const
8612 {
8613   QList<QCPAbstractItem*> result;
8614   if (!mParentPlot) return result;
8615 
8616   for (int itemId=0; itemId<mParentPlot->mItems.size(); ++itemId)
8617   {
8618     QList<QCPItemPosition*> positions = mParentPlot->mItems.at(itemId)->positions();
8619     for (int posId=0; posId<positions.size(); ++posId)
8620     {
8621       if (positions.at(posId)->keyAxis() == this || positions.at(posId)->valueAxis() == this)
8622       {
8623         result.append(mParentPlot->mItems.at(itemId));
8624         break;
8625       }
8626     }
8627   }
8628   return result;
8629 }
8630 
8631 /*!
8632   Transforms a margin side to the logically corresponding axis type. (QCP::msLeft to
8633   QCPAxis::atLeft, QCP::msRight to QCPAxis::atRight, etc.)
8634 */
marginSideToAxisType(QCP::MarginSide side)8635 QCPAxis::AxisType QCPAxis::marginSideToAxisType(QCP::MarginSide side)
8636 {
8637   switch (side)
8638   {
8639     case QCP::msLeft: return atLeft;
8640     case QCP::msRight: return atRight;
8641     case QCP::msTop: return atTop;
8642     case QCP::msBottom: return atBottom;
8643     default: break;
8644   }
8645   qDebug() << Q_FUNC_INFO << "Invalid margin side passed:" << (int)side;
8646   return atLeft;
8647 }
8648 
8649 /*!
8650   Returns the axis type that describes the opposite axis of an axis with the specified \a type.
8651 */
opposite(QCPAxis::AxisType type)8652 QCPAxis::AxisType QCPAxis::opposite(QCPAxis::AxisType type)
8653 {
8654   switch (type)
8655   {
8656     case atLeft: return atRight; break;
8657     case atRight: return atLeft; break;
8658     case atBottom: return atTop; break;
8659     case atTop: return atBottom; break;
8660     default: qDebug() << Q_FUNC_INFO << "invalid axis type"; return atLeft; break;
8661   }
8662 }
8663 
8664 /* inherits documentation from base class */
selectEvent(QMouseEvent * event,bool additive,const QVariant & details,bool * selectionStateChanged)8665 void QCPAxis::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
8666 {
8667   Q_UNUSED(event)
8668   SelectablePart part = details.value<SelectablePart>();
8669   if (mSelectableParts.testFlag(part))
8670   {
8671     SelectableParts selBefore = mSelectedParts;
8672     setSelectedParts(additive ? mSelectedParts^part : part);
8673     if (selectionStateChanged)
8674       *selectionStateChanged = mSelectedParts != selBefore;
8675   }
8676 }
8677 
8678 /* inherits documentation from base class */
deselectEvent(bool * selectionStateChanged)8679 void QCPAxis::deselectEvent(bool *selectionStateChanged)
8680 {
8681   SelectableParts selBefore = mSelectedParts;
8682   setSelectedParts(mSelectedParts & ~mSelectableParts);
8683   if (selectionStateChanged)
8684     *selectionStateChanged = mSelectedParts != selBefore;
8685 }
8686 
8687 /*! \internal
8688 
8689   A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
8690   before drawing axis lines.
8691 
8692   This is the antialiasing state the painter passed to the \ref draw method is in by default.
8693 
8694   This function takes into account the local setting of the antialiasing flag as well as the
8695   overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
8696   QCustomPlot::setNotAntialiasedElements.
8697 
8698   \seebaseclassmethod
8699 
8700   \see setAntialiased
8701 */
applyDefaultAntialiasingHint(QCPPainter * painter) const8702 void QCPAxis::applyDefaultAntialiasingHint(QCPPainter *painter) const
8703 {
8704   applyAntialiasingHint(painter, mAntialiased, QCP::aeAxes);
8705 }
8706 
8707 /*! \internal
8708 
8709   Draws the axis with the specified \a painter, using the internal QCPAxisPainterPrivate instance.
8710 
8711   \seebaseclassmethod
8712 */
draw(QCPPainter * painter)8713 void QCPAxis::draw(QCPPainter *painter)
8714 {
8715   QVector<double> subTickPositions; // the final coordToPixel transformed vector passed to QCPAxisPainter
8716   QVector<double> tickPositions; // the final coordToPixel transformed vector passed to QCPAxisPainter
8717   QVector<QString> tickLabels; // the final vector passed to QCPAxisPainter
8718   tickPositions.reserve(mTickVector.size());
8719   tickLabels.reserve(mTickVector.size());
8720   subTickPositions.reserve(mSubTickVector.size());
8721 
8722   if (mTicks)
8723   {
8724     for (int i=0; i<mTickVector.size(); ++i)
8725     {
8726       tickPositions.append(coordToPixel(mTickVector.at(i)));
8727       if (mTickLabels)
8728         tickLabels.append(mTickVectorLabels.at(i));
8729     }
8730 
8731     if (mSubTicks)
8732     {
8733       const int subTickCount = mSubTickVector.size();
8734       for (int i=0; i<subTickCount; ++i)
8735         subTickPositions.append(coordToPixel(mSubTickVector.at(i)));
8736     }
8737   }
8738 
8739   // transfer all properties of this axis to QCPAxisPainterPrivate which it needs to draw the axis.
8740   // Note that some axis painter properties are already set by direct feed-through with QCPAxis setters
8741   mAxisPainter->type = mAxisType;
8742   mAxisPainter->basePen = getBasePen();
8743   mAxisPainter->labelFont = getLabelFont();
8744   mAxisPainter->labelColor = getLabelColor();
8745   mAxisPainter->label = mLabel;
8746   mAxisPainter->substituteExponent = mNumberBeautifulPowers;
8747   mAxisPainter->tickPen = getTickPen();
8748   mAxisPainter->subTickPen = getSubTickPen();
8749   mAxisPainter->tickLabelFont = getTickLabelFont();
8750   mAxisPainter->tickLabelColor = getTickLabelColor();
8751   mAxisPainter->axisRect = mAxisRect->rect();
8752   mAxisPainter->viewportRect = mParentPlot->viewport();
8753   mAxisPainter->abbreviateDecimalPowers = mScaleType == stLogarithmic;
8754   mAxisPainter->reversedEndings = mRangeReversed;
8755   mAxisPainter->tickPositions = tickPositions;
8756   mAxisPainter->tickLabels = tickLabels;
8757   mAxisPainter->subTickPositions = subTickPositions;
8758   mAxisPainter->draw(painter);
8759 }
8760 
8761 /*! \internal
8762 
8763   Prepares the internal tick vector, sub tick vector and tick label vector. This is done by calling
8764   QCPAxisTicker::generate on the currently installed ticker.
8765 
8766   If a change in the label text/count is detected, the cached axis margin is invalidated to make
8767   sure the next margin calculation recalculates the label sizes and returns an up-to-date value.
8768 */
setupTickVectors()8769 void QCPAxis::setupTickVectors()
8770 {
8771   if (!mParentPlot) return;
8772   if ((!mTicks && !mTickLabels && !mGrid->visible()) || mRange.size() <= 0) return;
8773 
8774   QVector<QString> oldLabels = mTickVectorLabels;
8775   mTicker->generate(mRange, mParentPlot->locale(), mNumberFormatChar, mNumberPrecision, mTickVector, mSubTicks ? &mSubTickVector : 0, mTickLabels ? &mTickVectorLabels : 0);
8776   mCachedMarginValid &= mTickVectorLabels == oldLabels; // if labels have changed, margin might have changed, too
8777 }
8778 
8779 /*! \internal
8780 
8781   Returns the pen that is used to draw the axis base line. Depending on the selection state, this
8782   is either mSelectedBasePen or mBasePen.
8783 */
getBasePen() const8784 QPen QCPAxis::getBasePen() const
8785 {
8786   return mSelectedParts.testFlag(spAxis) ? mSelectedBasePen : mBasePen;
8787 }
8788 
8789 /*! \internal
8790 
8791   Returns the pen that is used to draw the (major) ticks. Depending on the selection state, this
8792   is either mSelectedTickPen or mTickPen.
8793 */
getTickPen() const8794 QPen QCPAxis::getTickPen() const
8795 {
8796   return mSelectedParts.testFlag(spAxis) ? mSelectedTickPen : mTickPen;
8797 }
8798 
8799 /*! \internal
8800 
8801   Returns the pen that is used to draw the subticks. Depending on the selection state, this
8802   is either mSelectedSubTickPen or mSubTickPen.
8803 */
getSubTickPen() const8804 QPen QCPAxis::getSubTickPen() const
8805 {
8806   return mSelectedParts.testFlag(spAxis) ? mSelectedSubTickPen : mSubTickPen;
8807 }
8808 
8809 /*! \internal
8810 
8811   Returns the font that is used to draw the tick labels. Depending on the selection state, this
8812   is either mSelectedTickLabelFont or mTickLabelFont.
8813 */
getTickLabelFont() const8814 QFont QCPAxis::getTickLabelFont() const
8815 {
8816   return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelFont : mTickLabelFont;
8817 }
8818 
8819 /*! \internal
8820 
8821   Returns the font that is used to draw the axis label. Depending on the selection state, this
8822   is either mSelectedLabelFont or mLabelFont.
8823 */
getLabelFont() const8824 QFont QCPAxis::getLabelFont() const
8825 {
8826   return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelFont : mLabelFont;
8827 }
8828 
8829 /*! \internal
8830 
8831   Returns the color that is used to draw the tick labels. Depending on the selection state, this
8832   is either mSelectedTickLabelColor or mTickLabelColor.
8833 */
getTickLabelColor() const8834 QColor QCPAxis::getTickLabelColor() const
8835 {
8836   return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelColor : mTickLabelColor;
8837 }
8838 
8839 /*! \internal
8840 
8841   Returns the color that is used to draw the axis label. Depending on the selection state, this
8842   is either mSelectedLabelColor or mLabelColor.
8843 */
getLabelColor() const8844 QColor QCPAxis::getLabelColor() const
8845 {
8846   return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelColor : mLabelColor;
8847 }
8848 
8849 /*! \internal
8850 
8851   Returns the appropriate outward margin for this axis. It is needed if \ref
8852   QCPAxisRect::setAutoMargins is set to true on the parent axis rect. An axis with axis type \ref
8853   atLeft will return an appropriate left margin, \ref atBottom will return an appropriate bottom
8854   margin and so forth. For the calculation, this function goes through similar steps as \ref draw,
8855   so changing one function likely requires the modification of the other one as well.
8856 
8857   The margin consists of the outward tick length, tick label padding, tick label size, label
8858   padding, label size, and padding.
8859 
8860   The margin is cached internally, so repeated calls while leaving the axis range, fonts, etc.
8861   unchanged are very fast.
8862 */
calculateMargin()8863 int QCPAxis::calculateMargin()
8864 {
8865   if (!mVisible) // if not visible, directly return 0, don't cache 0 because we can't react to setVisible in QCPAxis
8866     return 0;
8867 
8868   if (mCachedMarginValid)
8869     return mCachedMargin;
8870 
8871   // run through similar steps as QCPAxis::draw, and calculate margin needed to fit axis and its labels
8872   int margin = 0;
8873 
8874   QVector<double> tickPositions; // the final coordToPixel transformed vector passed to QCPAxisPainter
8875   QVector<QString> tickLabels; // the final vector passed to QCPAxisPainter
8876   tickPositions.reserve(mTickVector.size());
8877   tickLabels.reserve(mTickVector.size());
8878 
8879   if (mTicks)
8880   {
8881     for (int i=0; i<mTickVector.size(); ++i)
8882     {
8883       tickPositions.append(coordToPixel(mTickVector.at(i)));
8884       if (mTickLabels)
8885         tickLabels.append(mTickVectorLabels.at(i));
8886     }
8887   }
8888   // transfer all properties of this axis to QCPAxisPainterPrivate which it needs to calculate the size.
8889   // Note that some axis painter properties are already set by direct feed-through with QCPAxis setters
8890   mAxisPainter->type = mAxisType;
8891   mAxisPainter->labelFont = getLabelFont();
8892   mAxisPainter->label = mLabel;
8893   mAxisPainter->tickLabelFont = mTickLabelFont;
8894   mAxisPainter->axisRect = mAxisRect->rect();
8895   mAxisPainter->viewportRect = mParentPlot->viewport();
8896   mAxisPainter->tickPositions = tickPositions;
8897   mAxisPainter->tickLabels = tickLabels;
8898   margin += mAxisPainter->size();
8899   margin += mPadding;
8900 
8901   mCachedMargin = margin;
8902   mCachedMarginValid = true;
8903   return margin;
8904 }
8905 
8906 /* inherits documentation from base class */
selectionCategory() const8907 QCP::Interaction QCPAxis::selectionCategory() const
8908 {
8909   return QCP::iSelectAxes;
8910 }
8911 
8912 
8913 ////////////////////////////////////////////////////////////////////////////////////////////////////
8914 //////////////////// QCPAxisPainterPrivate
8915 ////////////////////////////////////////////////////////////////////////////////////////////////////
8916 
8917 /*! \class QCPAxisPainterPrivate
8918 
8919   \internal
8920   \brief (Private)
8921 
8922   This is a private class and not part of the public QCustomPlot interface.
8923 
8924   It is used by QCPAxis to do the low-level drawing of axis backbone, tick marks, tick labels and
8925   axis label. It also buffers the labels to reduce replot times. The parameters are configured by
8926   directly accessing the public member variables.
8927 */
8928 
8929 /*!
8930   Constructs a QCPAxisPainterPrivate instance. Make sure to not create a new instance on every
8931   redraw, to utilize the caching mechanisms.
8932 */
QCPAxisPainterPrivate(QCustomPlot * parentPlot)8933 QCPAxisPainterPrivate::QCPAxisPainterPrivate(QCustomPlot *parentPlot) :
8934   type(QCPAxis::atLeft),
8935   basePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
8936   lowerEnding(QCPLineEnding::esNone),
8937   upperEnding(QCPLineEnding::esNone),
8938   labelPadding(0),
8939   tickLabelPadding(0),
8940   tickLabelRotation(0),
8941   tickLabelSide(QCPAxis::lsOutside),
8942   substituteExponent(true),
8943   numberMultiplyCross(false),
8944   tickLengthIn(5),
8945   tickLengthOut(0),
8946   subTickLengthIn(2),
8947   subTickLengthOut(0),
8948   tickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
8949   subTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
8950   offset(0),
8951   abbreviateDecimalPowers(false),
8952   reversedEndings(false),
8953   mParentPlot(parentPlot),
8954   mLabelCache(16) // cache at most 16 (tick) labels
8955 {
8956 }
8957 
~QCPAxisPainterPrivate()8958 QCPAxisPainterPrivate::~QCPAxisPainterPrivate()
8959 {
8960 }
8961 
8962 /*! \internal
8963 
8964   Draws the axis with the specified \a painter.
8965 
8966   The selection boxes (mAxisSelectionBox, mTickLabelsSelectionBox, mLabelSelectionBox) are set
8967   here, too.
8968 */
draw(QCPPainter * painter)8969 void QCPAxisPainterPrivate::draw(QCPPainter *painter)
8970 {
8971   QByteArray newHash = generateLabelParameterHash();
8972   if (newHash != mLabelParameterHash)
8973   {
8974     mLabelCache.clear();
8975     mLabelParameterHash = newHash;
8976   }
8977 
8978   QPoint origin;
8979   switch (type)
8980   {
8981     case QCPAxis::atLeft:   origin = axisRect.bottomLeft() +QPoint(-offset, 0); break;
8982     case QCPAxis::atRight:  origin = axisRect.bottomRight()+QPoint(+offset, 0); break;
8983     case QCPAxis::atTop:    origin = axisRect.topLeft()    +QPoint(0, -offset); break;
8984     case QCPAxis::atBottom: origin = axisRect.bottomLeft() +QPoint(0, +offset); break;
8985   }
8986 
8987   double xCor = 0, yCor = 0; // paint system correction, for pixel exact matches (affects baselines and ticks of top/right axes)
8988   switch (type)
8989   {
8990     case QCPAxis::atTop: yCor = -1; break;
8991     case QCPAxis::atRight: xCor = 1; break;
8992     default: break;
8993   }
8994   int margin = 0;
8995   // draw baseline:
8996   QLineF baseLine;
8997   painter->setPen(basePen);
8998   if (QCPAxis::orientation(type) == Qt::Horizontal)
8999     baseLine.setPoints(origin+QPointF(xCor, yCor), origin+QPointF(axisRect.width()+xCor, yCor));
9000   else
9001     baseLine.setPoints(origin+QPointF(xCor, yCor), origin+QPointF(xCor, -axisRect.height()+yCor));
9002   if (reversedEndings)
9003     baseLine = QLineF(baseLine.p2(), baseLine.p1()); // won't make a difference for line itself, but for line endings later
9004   painter->drawLine(baseLine);
9005 
9006   // draw ticks:
9007   if (!tickPositions.isEmpty())
9008   {
9009     painter->setPen(tickPen);
9010     int tickDir = (type == QCPAxis::atBottom || type == QCPAxis::atRight) ? -1 : 1; // direction of ticks ("inward" is right for left axis and left for right axis)
9011     if (QCPAxis::orientation(type) == Qt::Horizontal)
9012     {
9013       for (int i=0; i<tickPositions.size(); ++i)
9014         painter->drawLine(QLineF(tickPositions.at(i)+xCor, origin.y()-tickLengthOut*tickDir+yCor, tickPositions.at(i)+xCor, origin.y()+tickLengthIn*tickDir+yCor));
9015     } else
9016     {
9017       for (int i=0; i<tickPositions.size(); ++i)
9018         painter->drawLine(QLineF(origin.x()-tickLengthOut*tickDir+xCor, tickPositions.at(i)+yCor, origin.x()+tickLengthIn*tickDir+xCor, tickPositions.at(i)+yCor));
9019     }
9020   }
9021 
9022   // draw subticks:
9023   if (!subTickPositions.isEmpty())
9024   {
9025     painter->setPen(subTickPen);
9026     // direction of ticks ("inward" is right for left axis and left for right axis)
9027     int tickDir = (type == QCPAxis::atBottom || type == QCPAxis::atRight) ? -1 : 1;
9028     if (QCPAxis::orientation(type) == Qt::Horizontal)
9029     {
9030       for (int i=0; i<subTickPositions.size(); ++i)
9031         painter->drawLine(QLineF(subTickPositions.at(i)+xCor, origin.y()-subTickLengthOut*tickDir+yCor, subTickPositions.at(i)+xCor, origin.y()+subTickLengthIn*tickDir+yCor));
9032     } else
9033     {
9034       for (int i=0; i<subTickPositions.size(); ++i)
9035         painter->drawLine(QLineF(origin.x()-subTickLengthOut*tickDir+xCor, subTickPositions.at(i)+yCor, origin.x()+subTickLengthIn*tickDir+xCor, subTickPositions.at(i)+yCor));
9036     }
9037   }
9038   margin += qMax(0, qMax(tickLengthOut, subTickLengthOut));
9039 
9040   // draw axis base endings:
9041   bool antialiasingBackup = painter->antialiasing();
9042   painter->setAntialiasing(true); // always want endings to be antialiased, even if base and ticks themselves aren't
9043   painter->setBrush(QBrush(basePen.color()));
9044   QCPVector2D baseLineVector(baseLine.dx(), baseLine.dy());
9045   if (lowerEnding.style() != QCPLineEnding::esNone)
9046     lowerEnding.draw(painter, QCPVector2D(baseLine.p1())-baseLineVector.normalized()*lowerEnding.realLength()*(lowerEnding.inverted()?-1:1), -baseLineVector);
9047   if (upperEnding.style() != QCPLineEnding::esNone)
9048     upperEnding.draw(painter, QCPVector2D(baseLine.p2())+baseLineVector.normalized()*upperEnding.realLength()*(upperEnding.inverted()?-1:1), baseLineVector);
9049   painter->setAntialiasing(antialiasingBackup);
9050 
9051   // tick labels:
9052   QRect oldClipRect;
9053   if (tickLabelSide == QCPAxis::lsInside) // if using inside labels, clip them to the axis rect
9054   {
9055     oldClipRect = painter->clipRegion().boundingRect();
9056     painter->setClipRect(axisRect);
9057   }
9058   QSize tickLabelsSize(0, 0); // size of largest tick label, for offset calculation of axis label
9059   if (!tickLabels.isEmpty())
9060   {
9061     if (tickLabelSide == QCPAxis::lsOutside)
9062       margin += tickLabelPadding;
9063     painter->setFont(tickLabelFont);
9064     painter->setPen(QPen(tickLabelColor));
9065     const int maxLabelIndex = qMin(tickPositions.size(), tickLabels.size());
9066     int distanceToAxis = margin;
9067     if (tickLabelSide == QCPAxis::lsInside)
9068       distanceToAxis = -(qMax(tickLengthIn, subTickLengthIn)+tickLabelPadding);
9069     for (int i=0; i<maxLabelIndex; ++i)
9070       placeTickLabel(painter, tickPositions.at(i), distanceToAxis, tickLabels.at(i), &tickLabelsSize);
9071     if (tickLabelSide == QCPAxis::lsOutside)
9072       margin += (QCPAxis::orientation(type) == Qt::Horizontal) ? tickLabelsSize.height() : tickLabelsSize.width();
9073   }
9074   if (tickLabelSide == QCPAxis::lsInside)
9075     painter->setClipRect(oldClipRect);
9076 
9077   // axis label:
9078   QRect labelBounds;
9079   if (!label.isEmpty())
9080   {
9081     margin += labelPadding;
9082     painter->setFont(labelFont);
9083     painter->setPen(QPen(labelColor));
9084     labelBounds = painter->fontMetrics().boundingRect(0, 0, 0, 0, Qt::TextDontClip, label);
9085     if (type == QCPAxis::atLeft)
9086     {
9087       QTransform oldTransform = painter->transform();
9088       painter->translate((origin.x()-margin-labelBounds.height()), origin.y());
9089       painter->rotate(-90);
9090       painter->drawText(0, 0, axisRect.height(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label);
9091       painter->setTransform(oldTransform);
9092     }
9093     else if (type == QCPAxis::atRight)
9094     {
9095       QTransform oldTransform = painter->transform();
9096       painter->translate((origin.x()+margin+labelBounds.height()), origin.y()-axisRect.height());
9097       painter->rotate(90);
9098       painter->drawText(0, 0, axisRect.height(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label);
9099       painter->setTransform(oldTransform);
9100     }
9101     else if (type == QCPAxis::atTop)
9102       painter->drawText(origin.x(), origin.y()-margin-labelBounds.height(), axisRect.width(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label);
9103     else if (type == QCPAxis::atBottom)
9104       painter->drawText(origin.x(), origin.y()+margin, axisRect.width(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label);
9105   }
9106 
9107   // set selection boxes:
9108   int selectionTolerance = 0;
9109   if (mParentPlot)
9110     selectionTolerance = mParentPlot->selectionTolerance();
9111   else
9112     qDebug() << Q_FUNC_INFO << "mParentPlot is null";
9113   int selAxisOutSize = qMax(qMax(tickLengthOut, subTickLengthOut), selectionTolerance);
9114   int selAxisInSize = selectionTolerance;
9115   int selTickLabelSize;
9116   int selTickLabelOffset;
9117   if (tickLabelSide == QCPAxis::lsOutside)
9118   {
9119     selTickLabelSize = (QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width());
9120     selTickLabelOffset = qMax(tickLengthOut, subTickLengthOut)+tickLabelPadding;
9121   } else
9122   {
9123     selTickLabelSize = -(QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width());
9124     selTickLabelOffset = -(qMax(tickLengthIn, subTickLengthIn)+tickLabelPadding);
9125   }
9126   int selLabelSize = labelBounds.height();
9127   int selLabelOffset = qMax(tickLengthOut, subTickLengthOut)+(!tickLabels.isEmpty() && tickLabelSide == QCPAxis::lsOutside ? tickLabelPadding+selTickLabelSize : 0)+labelPadding;
9128   if (type == QCPAxis::atLeft)
9129   {
9130     mAxisSelectionBox.setCoords(origin.x()-selAxisOutSize, axisRect.top(), origin.x()+selAxisInSize, axisRect.bottom());
9131     mTickLabelsSelectionBox.setCoords(origin.x()-selTickLabelOffset-selTickLabelSize, axisRect.top(), origin.x()-selTickLabelOffset, axisRect.bottom());
9132     mLabelSelectionBox.setCoords(origin.x()-selLabelOffset-selLabelSize, axisRect.top(), origin.x()-selLabelOffset, axisRect.bottom());
9133   } else if (type == QCPAxis::atRight)
9134   {
9135     mAxisSelectionBox.setCoords(origin.x()-selAxisInSize, axisRect.top(), origin.x()+selAxisOutSize, axisRect.bottom());
9136     mTickLabelsSelectionBox.setCoords(origin.x()+selTickLabelOffset+selTickLabelSize, axisRect.top(), origin.x()+selTickLabelOffset, axisRect.bottom());
9137     mLabelSelectionBox.setCoords(origin.x()+selLabelOffset+selLabelSize, axisRect.top(), origin.x()+selLabelOffset, axisRect.bottom());
9138   } else if (type == QCPAxis::atTop)
9139   {
9140     mAxisSelectionBox.setCoords(axisRect.left(), origin.y()-selAxisOutSize, axisRect.right(), origin.y()+selAxisInSize);
9141     mTickLabelsSelectionBox.setCoords(axisRect.left(), origin.y()-selTickLabelOffset-selTickLabelSize, axisRect.right(), origin.y()-selTickLabelOffset);
9142     mLabelSelectionBox.setCoords(axisRect.left(), origin.y()-selLabelOffset-selLabelSize, axisRect.right(), origin.y()-selLabelOffset);
9143   } else if (type == QCPAxis::atBottom)
9144   {
9145     mAxisSelectionBox.setCoords(axisRect.left(), origin.y()-selAxisInSize, axisRect.right(), origin.y()+selAxisOutSize);
9146     mTickLabelsSelectionBox.setCoords(axisRect.left(), origin.y()+selTickLabelOffset+selTickLabelSize, axisRect.right(), origin.y()+selTickLabelOffset);
9147     mLabelSelectionBox.setCoords(axisRect.left(), origin.y()+selLabelOffset+selLabelSize, axisRect.right(), origin.y()+selLabelOffset);
9148   }
9149   mAxisSelectionBox = mAxisSelectionBox.normalized();
9150   mTickLabelsSelectionBox = mTickLabelsSelectionBox.normalized();
9151   mLabelSelectionBox = mLabelSelectionBox.normalized();
9152   // draw hitboxes for debug purposes:
9153   //painter->setBrush(Qt::NoBrush);
9154   //painter->drawRects(QVector<QRect>() << mAxisSelectionBox << mTickLabelsSelectionBox << mLabelSelectionBox);
9155 }
9156 
9157 /*! \internal
9158 
9159   Returns the size ("margin" in QCPAxisRect context, so measured perpendicular to the axis backbone
9160   direction) needed to fit the axis.
9161 */
size() const9162 int QCPAxisPainterPrivate::size() const
9163 {
9164   int result = 0;
9165 
9166   // get length of tick marks pointing outwards:
9167   if (!tickPositions.isEmpty())
9168     result += qMax(0, qMax(tickLengthOut, subTickLengthOut));
9169 
9170   // calculate size of tick labels:
9171   if (tickLabelSide == QCPAxis::lsOutside)
9172   {
9173     QSize tickLabelsSize(0, 0);
9174     if (!tickLabels.isEmpty())
9175     {
9176       for (int i=0; i<tickLabels.size(); ++i)
9177         getMaxTickLabelSize(tickLabelFont, tickLabels.at(i), &tickLabelsSize);
9178       result += QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width();
9179     result += tickLabelPadding;
9180     }
9181   }
9182 
9183   // calculate size of axis label (only height needed, because left/right labels are rotated by 90 degrees):
9184   if (!label.isEmpty())
9185   {
9186     QFontMetrics fontMetrics(labelFont);
9187     QRect bounds;
9188     bounds = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip | Qt::AlignHCenter | Qt::AlignVCenter, label);
9189     result += bounds.height() + labelPadding;
9190   }
9191 
9192   return result;
9193 }
9194 
9195 /*! \internal
9196 
9197   Clears the internal label cache. Upon the next \ref draw, all labels will be created new. This
9198   method is called automatically in \ref draw, if any parameters have changed that invalidate the
9199   cached labels, such as font, color, etc.
9200 */
clearCache()9201 void QCPAxisPainterPrivate::clearCache()
9202 {
9203   mLabelCache.clear();
9204 }
9205 
9206 /*! \internal
9207 
9208   Returns a hash that allows uniquely identifying whether the label parameters have changed such
9209   that the cached labels must be refreshed (\ref clearCache). It is used in \ref draw. If the
9210   return value of this method hasn't changed since the last redraw, the respective label parameters
9211   haven't changed and cached labels may be used.
9212 */
generateLabelParameterHash() const9213 QByteArray QCPAxisPainterPrivate::generateLabelParameterHash() const
9214 {
9215   QByteArray result;
9216   result.append(QByteArray::number(mParentPlot->bufferDevicePixelRatio()));
9217   result.append(QByteArray::number(tickLabelRotation));
9218   result.append(QByteArray::number((int)tickLabelSide));
9219   result.append(QByteArray::number((int)substituteExponent));
9220   result.append(QByteArray::number((int)numberMultiplyCross));
9221   result.append(tickLabelColor.name().toLatin1()+QByteArray::number(tickLabelColor.alpha(), 16));
9222   result.append(tickLabelFont.toString().toLatin1());
9223   return result;
9224 }
9225 
9226 /*! \internal
9227 
9228   Draws a single tick label with the provided \a painter, utilizing the internal label cache to
9229   significantly speed up drawing of labels that were drawn in previous calls. The tick label is
9230   always bound to an axis, the distance to the axis is controllable via \a distanceToAxis in
9231   pixels. The pixel position in the axis direction is passed in the \a position parameter. Hence
9232   for the bottom axis, \a position would indicate the horizontal pixel position (not coordinate),
9233   at which the label should be drawn.
9234 
9235   In order to later draw the axis label in a place that doesn't overlap with the tick labels, the
9236   largest tick label size is needed. This is acquired by passing a \a tickLabelsSize to the \ref
9237   drawTickLabel calls during the process of drawing all tick labels of one axis. In every call, \a
9238   tickLabelsSize is expanded, if the drawn label exceeds the value \a tickLabelsSize currently
9239   holds.
9240 
9241   The label is drawn with the font and pen that are currently set on the \a painter. To draw
9242   superscripted powers, the font is temporarily made smaller by a fixed factor (see \ref
9243   getTickLabelData).
9244 */
placeTickLabel(QCPPainter * painter,double position,int distanceToAxis,const QString & text,QSize * tickLabelsSize)9245 void QCPAxisPainterPrivate::placeTickLabel(QCPPainter *painter, double position, int distanceToAxis, const QString &text, QSize *tickLabelsSize)
9246 {
9247   // warning: if you change anything here, also adapt getMaxTickLabelSize() accordingly!
9248   if (text.isEmpty()) return;
9249   QSize finalSize;
9250   QPointF labelAnchor;
9251   switch (type)
9252   {
9253     case QCPAxis::atLeft:   labelAnchor = QPointF(axisRect.left()-distanceToAxis-offset, position); break;
9254     case QCPAxis::atRight:  labelAnchor = QPointF(axisRect.right()+distanceToAxis+offset, position); break;
9255     case QCPAxis::atTop:    labelAnchor = QPointF(position, axisRect.top()-distanceToAxis-offset); break;
9256     case QCPAxis::atBottom: labelAnchor = QPointF(position, axisRect.bottom()+distanceToAxis+offset); break;
9257   }
9258   if (mParentPlot->plottingHints().testFlag(QCP::phCacheLabels) && !painter->modes().testFlag(QCPPainter::pmNoCaching)) // label caching enabled
9259   {
9260     CachedLabel *cachedLabel = mLabelCache.take(text); // attempt to get label from cache
9261     if (!cachedLabel)  // no cached label existed, create it
9262     {
9263       cachedLabel = new CachedLabel;
9264       TickLabelData labelData = getTickLabelData(painter->font(), text);
9265       cachedLabel->offset = getTickLabelDrawOffset(labelData)+labelData.rotatedTotalBounds.topLeft();
9266       if (!qFuzzyCompare(1.0, mParentPlot->bufferDevicePixelRatio()))
9267       {
9268         cachedLabel->pixmap = QPixmap(labelData.rotatedTotalBounds.size()*mParentPlot->bufferDevicePixelRatio());
9269 #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
9270         cachedLabel->pixmap.setDevicePixelRatio(mParentPlot->devicePixelRatio());
9271 #endif
9272       } else
9273         cachedLabel->pixmap = QPixmap(labelData.rotatedTotalBounds.size());
9274       cachedLabel->pixmap = QPixmap(labelData.rotatedTotalBounds.size());
9275       cachedLabel->pixmap.fill(Qt::transparent);
9276       QCPPainter cachePainter(&cachedLabel->pixmap);
9277       cachePainter.setPen(painter->pen());
9278       drawTickLabel(&cachePainter, -labelData.rotatedTotalBounds.topLeft().x(), -labelData.rotatedTotalBounds.topLeft().y(), labelData);
9279     }
9280     // if label would be partly clipped by widget border on sides, don't draw it (only for outside tick labels):
9281     bool labelClippedByBorder = false;
9282     if (tickLabelSide == QCPAxis::lsOutside)
9283     {
9284       if (QCPAxis::orientation(type) == Qt::Horizontal)
9285         labelClippedByBorder = labelAnchor.x()+cachedLabel->offset.x()+cachedLabel->pixmap.width()/mParentPlot->bufferDevicePixelRatio() > viewportRect.right() || labelAnchor.x()+cachedLabel->offset.x() < viewportRect.left();
9286       else
9287         labelClippedByBorder = labelAnchor.y()+cachedLabel->offset.y()+cachedLabel->pixmap.height()/mParentPlot->bufferDevicePixelRatio() > viewportRect.bottom() || labelAnchor.y()+cachedLabel->offset.y() < viewportRect.top();
9288     }
9289     if (!labelClippedByBorder)
9290     {
9291       painter->drawPixmap(labelAnchor+cachedLabel->offset, cachedLabel->pixmap);
9292       finalSize = cachedLabel->pixmap.size()/mParentPlot->bufferDevicePixelRatio();
9293     }
9294     mLabelCache.insert(text, cachedLabel); // return label to cache or insert for the first time if newly created
9295   } else // label caching disabled, draw text directly on surface:
9296   {
9297     TickLabelData labelData = getTickLabelData(painter->font(), text);
9298     QPointF finalPosition = labelAnchor + getTickLabelDrawOffset(labelData);
9299     // if label would be partly clipped by widget border on sides, don't draw it (only for outside tick labels):
9300      bool labelClippedByBorder = false;
9301     if (tickLabelSide == QCPAxis::lsOutside)
9302     {
9303       if (QCPAxis::orientation(type) == Qt::Horizontal)
9304         labelClippedByBorder = finalPosition.x()+(labelData.rotatedTotalBounds.width()+labelData.rotatedTotalBounds.left()) > viewportRect.right() || finalPosition.x()+labelData.rotatedTotalBounds.left() < viewportRect.left();
9305       else
9306         labelClippedByBorder = finalPosition.y()+(labelData.rotatedTotalBounds.height()+labelData.rotatedTotalBounds.top()) > viewportRect.bottom() || finalPosition.y()+labelData.rotatedTotalBounds.top() < viewportRect.top();
9307     }
9308     if (!labelClippedByBorder)
9309     {
9310       drawTickLabel(painter, finalPosition.x(), finalPosition.y(), labelData);
9311       finalSize = labelData.rotatedTotalBounds.size();
9312     }
9313   }
9314 
9315   // expand passed tickLabelsSize if current tick label is larger:
9316   if (finalSize.width() > tickLabelsSize->width())
9317     tickLabelsSize->setWidth(finalSize.width());
9318   if (finalSize.height() > tickLabelsSize->height())
9319     tickLabelsSize->setHeight(finalSize.height());
9320 }
9321 
9322 /*! \internal
9323 
9324   This is a \ref placeTickLabel helper function.
9325 
9326   Draws the tick label specified in \a labelData with \a painter at the pixel positions \a x and \a
9327   y. This function is used by \ref placeTickLabel to create new tick labels for the cache, or to
9328   directly draw the labels on the QCustomPlot surface when label caching is disabled, i.e. when
9329   QCP::phCacheLabels plotting hint is not set.
9330 */
drawTickLabel(QCPPainter * painter,double x,double y,const TickLabelData & labelData) const9331 void QCPAxisPainterPrivate::drawTickLabel(QCPPainter *painter, double x, double y, const TickLabelData &labelData) const
9332 {
9333   // backup painter settings that we're about to change:
9334   QTransform oldTransform = painter->transform();
9335   QFont oldFont = painter->font();
9336 
9337   // transform painter to position/rotation:
9338   painter->translate(x, y);
9339   if (!qFuzzyIsNull(tickLabelRotation))
9340     painter->rotate(tickLabelRotation);
9341 
9342   // draw text:
9343   if (!labelData.expPart.isEmpty()) // indicator that beautiful powers must be used
9344   {
9345     painter->setFont(labelData.baseFont);
9346     painter->drawText(0, 0, 0, 0, Qt::TextDontClip, labelData.basePart);
9347     if (!labelData.suffixPart.isEmpty())
9348       painter->drawText(labelData.baseBounds.width()+1+labelData.expBounds.width(), 0, 0, 0, Qt::TextDontClip, labelData.suffixPart);
9349     painter->setFont(labelData.expFont);
9350     painter->drawText(labelData.baseBounds.width()+1, 0, labelData.expBounds.width(), labelData.expBounds.height(), Qt::TextDontClip,  labelData.expPart);
9351   } else
9352   {
9353     painter->setFont(labelData.baseFont);
9354     painter->drawText(0, 0, labelData.totalBounds.width(), labelData.totalBounds.height(), Qt::TextDontClip | Qt::AlignHCenter, labelData.basePart);
9355   }
9356 
9357   // reset painter settings to what it was before:
9358   painter->setTransform(oldTransform);
9359   painter->setFont(oldFont);
9360 }
9361 
9362 /*! \internal
9363 
9364   This is a \ref placeTickLabel helper function.
9365 
9366   Transforms the passed \a text and \a font to a tickLabelData structure that can then be further
9367   processed by \ref getTickLabelDrawOffset and \ref drawTickLabel. It splits the text into base and
9368   exponent if necessary (member substituteExponent) and calculates appropriate bounding boxes.
9369 */
getTickLabelData(const QFont & font,const QString & text) const9370 QCPAxisPainterPrivate::TickLabelData QCPAxisPainterPrivate::getTickLabelData(const QFont &font, const QString &text) const
9371 {
9372   TickLabelData result;
9373 
9374   // determine whether beautiful decimal powers should be used
9375   bool useBeautifulPowers = false;
9376   int ePos = -1; // first index of exponent part, text before that will be basePart, text until eLast will be expPart
9377   int eLast = -1; // last index of exponent part, rest of text after this will be suffixPart
9378   if (substituteExponent)
9379   {
9380     ePos = text.indexOf(QLatin1Char('e'));
9381     if (ePos > 0 && text.at(ePos-1).isDigit())
9382     {
9383       eLast = ePos;
9384       while (eLast+1 < text.size() && (text.at(eLast+1) == QLatin1Char('+') || text.at(eLast+1) == QLatin1Char('-') || text.at(eLast+1).isDigit()))
9385         ++eLast;
9386       if (eLast > ePos) // only if also to right of 'e' is a digit/+/- interpret it as beautifiable power
9387         useBeautifulPowers = true;
9388     }
9389   }
9390 
9391   // calculate text bounding rects and do string preparation for beautiful decimal powers:
9392   result.baseFont = font;
9393   if (result.baseFont.pointSizeF() > 0) // might return -1 if specified with setPixelSize, in that case we can't do correction in next line
9394     result.baseFont.setPointSizeF(result.baseFont.pointSizeF()+0.05); // QFontMetrics.boundingRect has a bug for exact point sizes that make the results oscillate due to internal rounding
9395   if (useBeautifulPowers)
9396   {
9397     // split text into parts of number/symbol that will be drawn normally and part that will be drawn as exponent:
9398     result.basePart = text.left(ePos);
9399     result.suffixPart = text.mid(eLast+1); // also drawn normally but after exponent
9400     // in log scaling, we want to turn "1*10^n" into "10^n", else add multiplication sign and decimal base:
9401     if (abbreviateDecimalPowers && result.basePart == QLatin1String("1"))
9402       result.basePart = QLatin1String("10");
9403     else
9404       result.basePart += (numberMultiplyCross ? QString(QChar(215)) : QString(QChar(183))) + QLatin1String("10");
9405     result.expPart = text.mid(ePos+1, eLast-ePos);
9406     // clip "+" and leading zeros off expPart:
9407     while (result.expPart.length() > 2 && result.expPart.at(1) == QLatin1Char('0')) // length > 2 so we leave one zero when numberFormatChar is 'e'
9408       result.expPart.remove(1, 1);
9409     if (!result.expPart.isEmpty() && result.expPart.at(0) == QLatin1Char('+'))
9410       result.expPart.remove(0, 1);
9411     // prepare smaller font for exponent:
9412     result.expFont = font;
9413     if (result.expFont.pointSize() > 0)
9414       result.expFont.setPointSize(result.expFont.pointSize()*0.75);
9415     else
9416       result.expFont.setPixelSize(result.expFont.pixelSize()*0.75);
9417     // calculate bounding rects of base part(s), exponent part and total one:
9418     result.baseBounds = QFontMetrics(result.baseFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.basePart);
9419     result.expBounds = QFontMetrics(result.expFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.expPart);
9420     if (!result.suffixPart.isEmpty())
9421       result.suffixBounds = QFontMetrics(result.baseFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.suffixPart);
9422     result.totalBounds = result.baseBounds.adjusted(0, 0, result.expBounds.width()+result.suffixBounds.width()+2, 0); // +2 consists of the 1 pixel spacing between base and exponent (see drawTickLabel) and an extra pixel to include AA
9423   } else // useBeautifulPowers == false
9424   {
9425     result.basePart = text;
9426     result.totalBounds = QFontMetrics(result.baseFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip | Qt::AlignHCenter, result.basePart);
9427   }
9428   result.totalBounds.moveTopLeft(QPoint(0, 0)); // want bounding box aligned top left at origin, independent of how it was created, to make further processing simpler
9429 
9430   // calculate possibly different bounding rect after rotation:
9431   result.rotatedTotalBounds = result.totalBounds;
9432   if (!qFuzzyIsNull(tickLabelRotation))
9433   {
9434     QTransform transform;
9435     transform.rotate(tickLabelRotation);
9436     result.rotatedTotalBounds = transform.mapRect(result.rotatedTotalBounds);
9437   }
9438 
9439   return result;
9440 }
9441 
9442 /*! \internal
9443 
9444   This is a \ref placeTickLabel helper function.
9445 
9446   Calculates the offset at which the top left corner of the specified tick label shall be drawn.
9447   The offset is relative to a point right next to the tick the label belongs to.
9448 
9449   This function is thus responsible for e.g. centering tick labels under ticks and positioning them
9450   appropriately when they are rotated.
9451 */
getTickLabelDrawOffset(const TickLabelData & labelData) const9452 QPointF QCPAxisPainterPrivate::getTickLabelDrawOffset(const TickLabelData &labelData) const
9453 {
9454   /*
9455     calculate label offset from base point at tick (non-trivial, for best visual appearance): short
9456     explanation for bottom axis: The anchor, i.e. the point in the label that is placed
9457     horizontally under the corresponding tick is always on the label side that is closer to the
9458     axis (e.g. the left side of the text when we're rotating clockwise). On that side, the height
9459     is halved and the resulting point is defined the anchor. This way, a 90 degree rotated text
9460     will be centered under the tick (i.e. displaced horizontally by half its height). At the same
9461     time, a 45 degree rotated text will "point toward" its tick, as is typical for rotated tick
9462     labels.
9463   */
9464   bool doRotation = !qFuzzyIsNull(tickLabelRotation);
9465   bool flip = qFuzzyCompare(qAbs(tickLabelRotation), 90.0); // perfect +/-90 degree flip. Indicates vertical label centering on vertical axes.
9466   double radians = tickLabelRotation/180.0*M_PI;
9467   int x=0, y=0;
9468   if ((type == QCPAxis::atLeft && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atRight && tickLabelSide == QCPAxis::lsInside)) // Anchor at right side of tick label
9469   {
9470     if (doRotation)
9471     {
9472       if (tickLabelRotation > 0)
9473       {
9474         x = -qCos(radians)*labelData.totalBounds.width();
9475         y = flip ? -labelData.totalBounds.width()/2.0 : -qSin(radians)*labelData.totalBounds.width()-qCos(radians)*labelData.totalBounds.height()/2.0;
9476       } else
9477       {
9478         x = -qCos(-radians)*labelData.totalBounds.width()-qSin(-radians)*labelData.totalBounds.height();
9479         y = flip ? +labelData.totalBounds.width()/2.0 : +qSin(-radians)*labelData.totalBounds.width()-qCos(-radians)*labelData.totalBounds.height()/2.0;
9480       }
9481     } else
9482     {
9483       x = -labelData.totalBounds.width();
9484       y = -labelData.totalBounds.height()/2.0;
9485     }
9486   } else if ((type == QCPAxis::atRight && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atLeft && tickLabelSide == QCPAxis::lsInside)) // Anchor at left side of tick label
9487   {
9488     if (doRotation)
9489     {
9490       if (tickLabelRotation > 0)
9491       {
9492         x = +qSin(radians)*labelData.totalBounds.height();
9493         y = flip ? -labelData.totalBounds.width()/2.0 : -qCos(radians)*labelData.totalBounds.height()/2.0;
9494       } else
9495       {
9496         x = 0;
9497         y = flip ? +labelData.totalBounds.width()/2.0 : -qCos(-radians)*labelData.totalBounds.height()/2.0;
9498       }
9499     } else
9500     {
9501       x = 0;
9502       y = -labelData.totalBounds.height()/2.0;
9503     }
9504   } else if ((type == QCPAxis::atTop && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atBottom && tickLabelSide == QCPAxis::lsInside)) // Anchor at bottom side of tick label
9505   {
9506     if (doRotation)
9507     {
9508       if (tickLabelRotation > 0)
9509       {
9510         x = -qCos(radians)*labelData.totalBounds.width()+qSin(radians)*labelData.totalBounds.height()/2.0;
9511         y = -qSin(radians)*labelData.totalBounds.width()-qCos(radians)*labelData.totalBounds.height();
9512       } else
9513       {
9514         x = -qSin(-radians)*labelData.totalBounds.height()/2.0;
9515         y = -qCos(-radians)*labelData.totalBounds.height();
9516       }
9517     } else
9518     {
9519       x = -labelData.totalBounds.width()/2.0;
9520       y = -labelData.totalBounds.height();
9521     }
9522   } else if ((type == QCPAxis::atBottom && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atTop && tickLabelSide == QCPAxis::lsInside)) // Anchor at top side of tick label
9523   {
9524     if (doRotation)
9525     {
9526       if (tickLabelRotation > 0)
9527       {
9528         x = +qSin(radians)*labelData.totalBounds.height()/2.0;
9529         y = 0;
9530       } else
9531       {
9532         x = -qCos(-radians)*labelData.totalBounds.width()-qSin(-radians)*labelData.totalBounds.height()/2.0;
9533         y = +qSin(-radians)*labelData.totalBounds.width();
9534       }
9535     } else
9536     {
9537       x = -labelData.totalBounds.width()/2.0;
9538       y = 0;
9539     }
9540   }
9541 
9542   return QPointF(x, y);
9543 }
9544 
9545 /*! \internal
9546 
9547   Simulates the steps done by \ref placeTickLabel by calculating bounding boxes of the text label
9548   to be drawn, depending on number format etc. Since only the largest tick label is wanted for the
9549   margin calculation, the passed \a tickLabelsSize is only expanded, if it's currently set to a
9550   smaller width/height.
9551 */
getMaxTickLabelSize(const QFont & font,const QString & text,QSize * tickLabelsSize) const9552 void QCPAxisPainterPrivate::getMaxTickLabelSize(const QFont &font, const QString &text,  QSize *tickLabelsSize) const
9553 {
9554   // note: this function must return the same tick label sizes as the placeTickLabel function.
9555   QSize finalSize;
9556   if (mParentPlot->plottingHints().testFlag(QCP::phCacheLabels) && mLabelCache.contains(text)) // label caching enabled and have cached label
9557   {
9558     const CachedLabel *cachedLabel = mLabelCache.object(text);
9559     finalSize = cachedLabel->pixmap.size()/mParentPlot->bufferDevicePixelRatio();
9560   } else // label caching disabled or no label with this text cached:
9561   {
9562     TickLabelData labelData = getTickLabelData(font, text);
9563     finalSize = labelData.rotatedTotalBounds.size();
9564   }
9565 
9566   // expand passed tickLabelsSize if current tick label is larger:
9567   if (finalSize.width() > tickLabelsSize->width())
9568     tickLabelsSize->setWidth(finalSize.width());
9569   if (finalSize.height() > tickLabelsSize->height())
9570     tickLabelsSize->setHeight(finalSize.height());
9571 }
9572 /* end of 'src/axis/axis.cpp' */
9573 
9574 
9575 /* including file 'src/scatterstyle.cpp', size 17420                         */
9576 /* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
9577 
9578 ////////////////////////////////////////////////////////////////////////////////////////////////////
9579 //////////////////// QCPScatterStyle
9580 ////////////////////////////////////////////////////////////////////////////////////////////////////
9581 
9582 /*! \class QCPScatterStyle
9583   \brief Represents the visual appearance of scatter points
9584 
9585   This class holds information about shape, color and size of scatter points. In plottables like
9586   QCPGraph it is used to store how scatter points shall be drawn. For example, \ref
9587   QCPGraph::setScatterStyle takes a QCPScatterStyle instance.
9588 
9589   A scatter style consists of a shape (\ref setShape), a line color (\ref setPen) and possibly a
9590   fill (\ref setBrush), if the shape provides a fillable area. Further, the size of the shape can
9591   be controlled with \ref setSize.
9592 
9593   \section QCPScatterStyle-defining Specifying a scatter style
9594 
9595   You can set all these configurations either by calling the respective functions on an instance:
9596   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpscatterstyle-creation-1
9597 
9598   Or you can use one of the various constructors that take different parameter combinations, making
9599   it easy to specify a scatter style in a single call, like so:
9600   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpscatterstyle-creation-2
9601 
9602   \section QCPScatterStyle-undefinedpen Leaving the color/pen up to the plottable
9603 
9604   There are two constructors which leave the pen undefined: \ref QCPScatterStyle() and \ref
9605   QCPScatterStyle(ScatterShape shape, double size). If those constructors are used, a call to \ref
9606   isPenDefined will return false. It leads to scatter points that inherit the pen from the
9607   plottable that uses the scatter style. Thus, if such a scatter style is passed to QCPGraph, the line
9608   color of the graph (\ref QCPGraph::setPen) will be used by the scatter points. This makes
9609   it very convenient to set up typical scatter settings:
9610 
9611   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpscatterstyle-shortcreation
9612 
9613   Notice that it wasn't even necessary to explicitly call a QCPScatterStyle constructor. This works
9614   because QCPScatterStyle provides a constructor that can transform a \ref ScatterShape directly
9615   into a QCPScatterStyle instance (that's the \ref QCPScatterStyle(ScatterShape shape, double size)
9616   constructor with a default for \a size). In those cases, C++ allows directly supplying a \ref
9617   ScatterShape, where actually a QCPScatterStyle is expected.
9618 
9619   \section QCPScatterStyle-custompath-and-pixmap Custom shapes and pixmaps
9620 
9621   QCPScatterStyle supports drawing custom shapes and arbitrary pixmaps as scatter points.
9622 
9623   For custom shapes, you can provide a QPainterPath with the desired shape to the \ref
9624   setCustomPath function or call the constructor that takes a painter path. The scatter shape will
9625   automatically be set to \ref ssCustom.
9626 
9627   For pixmaps, you call \ref setPixmap with the desired QPixmap. Alternatively you can use the
9628   constructor that takes a QPixmap. The scatter shape will automatically be set to \ref ssPixmap.
9629   Note that \ref setSize does not influence the appearance of the pixmap.
9630 */
9631 
9632 /* start documentation of inline functions */
9633 
9634 /*! \fn bool QCPScatterStyle::isNone() const
9635 
9636   Returns whether the scatter shape is \ref ssNone.
9637 
9638   \see setShape
9639 */
9640 
9641 /*! \fn bool QCPScatterStyle::isPenDefined() const
9642 
9643   Returns whether a pen has been defined for this scatter style.
9644 
9645   The pen is undefined if a constructor is called that does not carry \a pen as parameter. Those
9646   are \ref QCPScatterStyle() and \ref QCPScatterStyle(ScatterShape shape, double size). If the pen
9647   is undefined, the pen of the respective plottable will be used for drawing scatters.
9648 
9649   If a pen was defined for this scatter style instance, and you now wish to undefine the pen, call
9650   \ref undefinePen.
9651 
9652   \see setPen
9653 */
9654 
9655 /* end documentation of inline functions */
9656 
9657 /*!
9658   Creates a new QCPScatterStyle instance with size set to 6. No shape, pen or brush is defined.
9659 
9660   Since the pen is undefined (\ref isPenDefined returns false), the scatter color will be inherited
9661   from the plottable that uses this scatter style.
9662 */
QCPScatterStyle()9663 QCPScatterStyle::QCPScatterStyle() :
9664   mSize(6),
9665   mShape(ssNone),
9666   mPen(Qt::NoPen),
9667   mBrush(Qt::NoBrush),
9668   mPenDefined(false)
9669 {
9670 }
9671 
9672 /*!
9673   Creates a new QCPScatterStyle instance with shape set to \a shape and size to \a size. No pen or
9674   brush is defined.
9675 
9676   Since the pen is undefined (\ref isPenDefined returns false), the scatter color will be inherited
9677   from the plottable that uses this scatter style.
9678 */
QCPScatterStyle(ScatterShape shape,double size)9679 QCPScatterStyle::QCPScatterStyle(ScatterShape shape, double size) :
9680   mSize(size),
9681   mShape(shape),
9682   mPen(Qt::NoPen),
9683   mBrush(Qt::NoBrush),
9684   mPenDefined(false)
9685 {
9686 }
9687 
9688 /*!
9689   Creates a new QCPScatterStyle instance with shape set to \a shape, the pen color set to \a color,
9690   and size to \a size. No brush is defined, i.e. the scatter point will not be filled.
9691 */
QCPScatterStyle(ScatterShape shape,const QColor & color,double size)9692 QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QColor &color, double size) :
9693   mSize(size),
9694   mShape(shape),
9695   mPen(QPen(color)),
9696   mBrush(Qt::NoBrush),
9697   mPenDefined(true)
9698 {
9699 }
9700 
9701 /*!
9702   Creates a new QCPScatterStyle instance with shape set to \a shape, the pen color set to \a color,
9703   the brush color to \a fill (with a solid pattern), and size to \a size.
9704 */
QCPScatterStyle(ScatterShape shape,const QColor & color,const QColor & fill,double size)9705 QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QColor &color, const QColor &fill, double size) :
9706   mSize(size),
9707   mShape(shape),
9708   mPen(QPen(color)),
9709   mBrush(QBrush(fill)),
9710   mPenDefined(true)
9711 {
9712 }
9713 
9714 /*!
9715   Creates a new QCPScatterStyle instance with shape set to \a shape, the pen set to \a pen, the
9716   brush to \a brush, and size to \a size.
9717 
9718   \warning In some cases it might be tempting to directly use a pen style like <tt>Qt::NoPen</tt> as \a pen
9719   and a color like <tt>Qt::blue</tt> as \a brush. Notice however, that the corresponding call\n
9720   <tt>QCPScatterStyle(QCPScatterShape::ssCircle, Qt::NoPen, Qt::blue, 5)</tt>\n
9721   doesn't necessarily lead C++ to use this constructor in some cases, but might mistake
9722   <tt>Qt::NoPen</tt> for a QColor and use the
9723   \ref QCPScatterStyle(ScatterShape shape, const QColor &color, const QColor &fill, double size)
9724   constructor instead (which will lead to an unexpected look of the scatter points). To prevent
9725   this, be more explicit with the parameter types. For example, use <tt>QBrush(Qt::blue)</tt>
9726   instead of just <tt>Qt::blue</tt>, to clearly point out to the compiler that this constructor is
9727   wanted.
9728 */
QCPScatterStyle(ScatterShape shape,const QPen & pen,const QBrush & brush,double size)9729 QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QPen &pen, const QBrush &brush, double size) :
9730   mSize(size),
9731   mShape(shape),
9732   mPen(pen),
9733   mBrush(brush),
9734   mPenDefined(pen.style() != Qt::NoPen)
9735 {
9736 }
9737 
9738 /*!
9739   Creates a new QCPScatterStyle instance which will show the specified \a pixmap. The scatter shape
9740   is set to \ref ssPixmap.
9741 */
QCPScatterStyle(const QPixmap & pixmap)9742 QCPScatterStyle::QCPScatterStyle(const QPixmap &pixmap) :
9743   mSize(5),
9744   mShape(ssPixmap),
9745   mPen(Qt::NoPen),
9746   mBrush(Qt::NoBrush),
9747   mPixmap(pixmap),
9748   mPenDefined(false)
9749 {
9750 }
9751 
9752 /*!
9753   Creates a new QCPScatterStyle instance with a custom shape that is defined via \a customPath. The
9754   scatter shape is set to \ref ssCustom.
9755 
9756   The custom shape line will be drawn with \a pen and filled with \a brush. The size has a slightly
9757   different meaning than for built-in scatter points: The custom path will be drawn scaled by a
9758   factor of \a size/6.0. Since the default \a size is 6, the custom path will appear at a its
9759   natural size by default. To double the size of the path for example, set \a size to 12.
9760 */
QCPScatterStyle(const QPainterPath & customPath,const QPen & pen,const QBrush & brush,double size)9761 QCPScatterStyle::QCPScatterStyle(const QPainterPath &customPath, const QPen &pen, const QBrush &brush, double size) :
9762   mSize(size),
9763   mShape(ssCustom),
9764   mPen(pen),
9765   mBrush(brush),
9766   mCustomPath(customPath),
9767   mPenDefined(pen.style() != Qt::NoPen)
9768 {
9769 }
9770 
9771 /*!
9772   Copies the specified \a properties from the \a other scatter style to this scatter style.
9773 */
setFromOther(const QCPScatterStyle & other,ScatterProperties properties)9774 void QCPScatterStyle::setFromOther(const QCPScatterStyle &other, ScatterProperties properties)
9775 {
9776   if (properties.testFlag(spPen))
9777   {
9778     setPen(other.pen());
9779     if (!other.isPenDefined())
9780       undefinePen();
9781   }
9782   if (properties.testFlag(spBrush))
9783     setBrush(other.brush());
9784   if (properties.testFlag(spSize))
9785     setSize(other.size());
9786   if (properties.testFlag(spShape))
9787   {
9788     setShape(other.shape());
9789     if (other.shape() == ssPixmap)
9790       setPixmap(other.pixmap());
9791     else if (other.shape() == ssCustom)
9792       setCustomPath(other.customPath());
9793   }
9794 }
9795 
9796 /*!
9797   Sets the size (pixel diameter) of the drawn scatter points to \a size.
9798 
9799   \see setShape
9800 */
setSize(double size)9801 void QCPScatterStyle::setSize(double size)
9802 {
9803   mSize = size;
9804 }
9805 
9806 /*!
9807   Sets the shape to \a shape.
9808 
9809   Note that the calls \ref setPixmap and \ref setCustomPath automatically set the shape to \ref
9810   ssPixmap and \ref ssCustom, respectively.
9811 
9812   \see setSize
9813 */
setShape(QCPScatterStyle::ScatterShape shape)9814 void QCPScatterStyle::setShape(QCPScatterStyle::ScatterShape shape)
9815 {
9816   mShape = shape;
9817 }
9818 
9819 /*!
9820   Sets the pen that will be used to draw scatter points to \a pen.
9821 
9822   If the pen was previously undefined (see \ref isPenDefined), the pen is considered defined after
9823   a call to this function, even if \a pen is <tt>Qt::NoPen</tt>. If you have defined a pen
9824   previously by calling this function and now wish to undefine the pen, call \ref undefinePen.
9825 
9826   \see setBrush
9827 */
setPen(const QPen & pen)9828 void QCPScatterStyle::setPen(const QPen &pen)
9829 {
9830   mPenDefined = true;
9831   mPen = pen;
9832 }
9833 
9834 /*!
9835   Sets the brush that will be used to fill scatter points to \a brush. Note that not all scatter
9836   shapes have fillable areas. For example, \ref ssPlus does not while \ref ssCircle does.
9837 
9838   \see setPen
9839 */
setBrush(const QBrush & brush)9840 void QCPScatterStyle::setBrush(const QBrush &brush)
9841 {
9842   mBrush = brush;
9843 }
9844 
9845 /*!
9846   Sets the pixmap that will be drawn as scatter point to \a pixmap.
9847 
9848   Note that \ref setSize does not influence the appearance of the pixmap.
9849 
9850   The scatter shape is automatically set to \ref ssPixmap.
9851 */
setPixmap(const QPixmap & pixmap)9852 void QCPScatterStyle::setPixmap(const QPixmap &pixmap)
9853 {
9854   setShape(ssPixmap);
9855   mPixmap = pixmap;
9856 }
9857 
9858 /*!
9859   Sets the custom shape that will be drawn as scatter point to \a customPath.
9860 
9861   The scatter shape is automatically set to \ref ssCustom.
9862 */
setCustomPath(const QPainterPath & customPath)9863 void QCPScatterStyle::setCustomPath(const QPainterPath &customPath)
9864 {
9865   setShape(ssCustom);
9866   mCustomPath = customPath;
9867 }
9868 
9869 /*!
9870   Sets this scatter style to have an undefined pen (see \ref isPenDefined for what an undefined pen
9871   implies).
9872 
9873   A call to \ref setPen will define a pen.
9874 */
undefinePen()9875 void QCPScatterStyle::undefinePen()
9876 {
9877   mPenDefined = false;
9878 }
9879 
9880 /*!
9881   Applies the pen and the brush of this scatter style to \a painter. If this scatter style has an
9882   undefined pen (\ref isPenDefined), sets the pen of \a painter to \a defaultPen instead.
9883 
9884   This function is used by plottables (or any class that wants to draw scatters) just before a
9885   number of scatters with this style shall be drawn with the \a painter.
9886 
9887   \see drawShape
9888 */
applyTo(QCPPainter * painter,const QPen & defaultPen) const9889 void QCPScatterStyle::applyTo(QCPPainter *painter, const QPen &defaultPen) const
9890 {
9891   painter->setPen(mPenDefined ? mPen : defaultPen);
9892   painter->setBrush(mBrush);
9893 }
9894 
9895 /*!
9896   Draws the scatter shape with \a painter at position \a pos.
9897 
9898   This function does not modify the pen or the brush on the painter, as \ref applyTo is meant to be
9899   called before scatter points are drawn with \ref drawShape.
9900 
9901   \see applyTo
9902 */
drawShape(QCPPainter * painter,const QPointF & pos) const9903 void QCPScatterStyle::drawShape(QCPPainter *painter, const QPointF &pos) const
9904 {
9905   drawShape(painter, pos.x(), pos.y());
9906 }
9907 
9908 /*! \overload
9909   Draws the scatter shape with \a painter at position \a x and \a y.
9910 */
drawShape(QCPPainter * painter,double x,double y) const9911 void QCPScatterStyle::drawShape(QCPPainter *painter, double x, double y) const
9912 {
9913   double w = mSize/2.0;
9914   switch (mShape)
9915   {
9916     case ssNone: break;
9917     case ssDot:
9918     {
9919       painter->drawLine(QPointF(x, y), QPointF(x+0.0001, y));
9920       break;
9921     }
9922     case ssCross:
9923     {
9924       painter->drawLine(QLineF(x-w, y-w, x+w, y+w));
9925       painter->drawLine(QLineF(x-w, y+w, x+w, y-w));
9926       break;
9927     }
9928     case ssPlus:
9929     {
9930       painter->drawLine(QLineF(x-w,   y, x+w,   y));
9931       painter->drawLine(QLineF(  x, y+w,   x, y-w));
9932       break;
9933     }
9934     case ssCircle:
9935     {
9936       painter->drawEllipse(QPointF(x , y), w, w);
9937       break;
9938     }
9939     case ssDisc:
9940     {
9941       QBrush b = painter->brush();
9942       painter->setBrush(painter->pen().color());
9943       painter->drawEllipse(QPointF(x , y), w, w);
9944       painter->setBrush(b);
9945       break;
9946     }
9947     case ssSquare:
9948     {
9949       painter->drawRect(QRectF(x-w, y-w, mSize, mSize));
9950       break;
9951     }
9952     case ssDiamond:
9953     {
9954       painter->drawLine(QLineF(x-w,   y,   x, y-w));
9955       painter->drawLine(QLineF(  x, y-w, x+w,   y));
9956       painter->drawLine(QLineF(x+w,   y,   x, y+w));
9957       painter->drawLine(QLineF(  x, y+w, x-w,   y));
9958       break;
9959     }
9960     case ssStar:
9961     {
9962       painter->drawLine(QLineF(x-w,   y, x+w,   y));
9963       painter->drawLine(QLineF(  x, y+w,   x, y-w));
9964       painter->drawLine(QLineF(x-w*0.707, y-w*0.707, x+w*0.707, y+w*0.707));
9965       painter->drawLine(QLineF(x-w*0.707, y+w*0.707, x+w*0.707, y-w*0.707));
9966       break;
9967     }
9968     case ssTriangle:
9969     {
9970        painter->drawLine(QLineF(x-w, y+0.755*w, x+w, y+0.755*w));
9971        painter->drawLine(QLineF(x+w, y+0.755*w,   x, y-0.977*w));
9972        painter->drawLine(QLineF(  x, y-0.977*w, x-w, y+0.755*w));
9973       break;
9974     }
9975     case ssTriangleInverted:
9976     {
9977        painter->drawLine(QLineF(x-w, y-0.755*w, x+w, y-0.755*w));
9978        painter->drawLine(QLineF(x+w, y-0.755*w,   x, y+0.977*w));
9979        painter->drawLine(QLineF(  x, y+0.977*w, x-w, y-0.755*w));
9980       break;
9981     }
9982     case ssCrossSquare:
9983     {
9984        painter->drawLine(QLineF(x-w, y-w, x+w*0.95, y+w*0.95));
9985        painter->drawLine(QLineF(x-w, y+w*0.95, x+w*0.95, y-w));
9986        painter->drawRect(QRectF(x-w, y-w, mSize, mSize));
9987       break;
9988     }
9989     case ssPlusSquare:
9990     {
9991        painter->drawLine(QLineF(x-w,   y, x+w*0.95,   y));
9992        painter->drawLine(QLineF(  x, y+w,        x, y-w));
9993        painter->drawRect(QRectF(x-w, y-w, mSize, mSize));
9994       break;
9995     }
9996     case ssCrossCircle:
9997     {
9998        painter->drawLine(QLineF(x-w*0.707, y-w*0.707, x+w*0.670, y+w*0.670));
9999        painter->drawLine(QLineF(x-w*0.707, y+w*0.670, x+w*0.670, y-w*0.707));
10000        painter->drawEllipse(QPointF(x, y), w, w);
10001       break;
10002     }
10003     case ssPlusCircle:
10004     {
10005        painter->drawLine(QLineF(x-w,   y, x+w,   y));
10006        painter->drawLine(QLineF(  x, y+w,   x, y-w));
10007        painter->drawEllipse(QPointF(x, y), w, w);
10008       break;
10009     }
10010     case ssPeace:
10011     {
10012        painter->drawLine(QLineF(x, y-w,         x,       y+w));
10013        painter->drawLine(QLineF(x,   y, x-w*0.707, y+w*0.707));
10014        painter->drawLine(QLineF(x,   y, x+w*0.707, y+w*0.707));
10015        painter->drawEllipse(QPointF(x, y), w, w);
10016       break;
10017     }
10018     case ssPixmap:
10019     {
10020       const double widthHalf = mPixmap.width()*0.5;
10021       const double heightHalf = mPixmap.height()*0.5;
10022 #if QT_VERSION < QT_VERSION_CHECK(4, 8, 0)
10023       const QRectF clipRect = painter->clipRegion().boundingRect().adjusted(-widthHalf, -heightHalf, widthHalf, heightHalf);
10024 #else
10025       const QRectF clipRect = painter->clipBoundingRect().adjusted(-widthHalf, -heightHalf, widthHalf, heightHalf);
10026 #endif
10027       if (clipRect.contains(x, y))
10028         painter->drawPixmap(x-widthHalf, y-heightHalf, mPixmap);
10029       break;
10030     }
10031     case ssCustom:
10032     {
10033       QTransform oldTransform = painter->transform();
10034       painter->translate(x, y);
10035       painter->scale(mSize/6.0, mSize/6.0);
10036       painter->drawPath(mCustomPath);
10037       painter->setTransform(oldTransform);
10038       break;
10039     }
10040   }
10041 }
10042 /* end of 'src/scatterstyle.cpp' */
10043 
10044 //amalgamation: add datacontainer.cpp
10045 
10046 /* including file 'src/plottable.cpp', size 38861                            */
10047 /* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
10048 
10049 ////////////////////////////////////////////////////////////////////////////////////////////////////
10050 //////////////////// QCPSelectionDecorator
10051 ////////////////////////////////////////////////////////////////////////////////////////////////////
10052 
10053 /*! \class QCPSelectionDecorator
10054   \brief Controls how a plottable's data selection is drawn
10055 
10056   Each \ref QCPAbstractPlottable instance has one \ref QCPSelectionDecorator (accessible via \ref
10057   QCPAbstractPlottable::selectionDecorator) and uses it when drawing selected segments of its data.
10058 
10059   The selection decorator controls both pen (\ref setPen) and brush (\ref setBrush), as well as the
10060   scatter style (\ref setScatterStyle) if the plottable draws scatters. Since a \ref
10061   QCPScatterStyle is itself composed of different properties such as color shape and size, the
10062   decorator allows specifying exactly which of those properties shall be used for the selected data
10063   point, via \ref setUsedScatterProperties.
10064 
10065   A \ref QCPSelectionDecorator subclass instance can be passed to a plottable via \ref
10066   QCPAbstractPlottable::setSelectionDecorator, allowing greater customizability of the appearance
10067   of selected segments.
10068 
10069   Use \ref copyFrom to easily transfer the settings of one decorator to another one. This is
10070   especially useful since plottables take ownership of the passed selection decorator, and thus the
10071   same decorator instance can not be passed to multiple plottables.
10072 
10073   Selection decorators can also themselves perform drawing operations by reimplementing \ref
10074   drawDecoration, which is called by the plottable's draw method. The base class \ref
10075   QCPSelectionDecorator does not make use of this however. For example, \ref
10076   QCPSelectionDecoratorBracket draws brackets around selected data segments.
10077 */
10078 
10079 /*!
10080   Creates a new QCPSelectionDecorator instance with default values
10081 */
QCPSelectionDecorator()10082 QCPSelectionDecorator::QCPSelectionDecorator() :
10083   mPen(QColor(80, 80, 255), 2.5),
10084   mBrush(Qt::NoBrush),
10085   mScatterStyle(QCPScatterStyle::ssNone, QPen(Qt::blue, 2), Qt::NoBrush, 6.0),
10086   mUsedScatterProperties(QCPScatterStyle::spPen),
10087   mPlottable(0)
10088 {
10089 }
10090 
~QCPSelectionDecorator()10091 QCPSelectionDecorator::~QCPSelectionDecorator()
10092 {
10093 }
10094 
10095 /*!
10096   Sets the pen that will be used by the parent plottable to draw selected data segments.
10097 */
setPen(const QPen & pen)10098 void QCPSelectionDecorator::setPen(const QPen &pen)
10099 {
10100   mPen = pen;
10101 }
10102 
10103 /*!
10104   Sets the brush that will be used by the parent plottable to draw selected data segments.
10105 */
setBrush(const QBrush & brush)10106 void QCPSelectionDecorator::setBrush(const QBrush &brush)
10107 {
10108   mBrush = brush;
10109 }
10110 
10111 /*!
10112   Sets the scatter style that will be used by the parent plottable to draw scatters in selected
10113   data segments.
10114 
10115   \a usedProperties specifies which parts of the passed \a scatterStyle will be used by the
10116   plottable. The used properties can also be changed via \ref setUsedScatterProperties.
10117 */
setScatterStyle(const QCPScatterStyle & scatterStyle,QCPScatterStyle::ScatterProperties usedProperties)10118 void QCPSelectionDecorator::setScatterStyle(const QCPScatterStyle &scatterStyle, QCPScatterStyle::ScatterProperties usedProperties)
10119 {
10120   mScatterStyle = scatterStyle;
10121   setUsedScatterProperties(usedProperties);
10122 }
10123 
10124 /*!
10125   Use this method to define which properties of the scatter style (set via \ref setScatterStyle)
10126   will be used for selected data segments. All properties of the scatter style that are not
10127   specified in \a properties will remain as specified in the plottable's original scatter style.
10128 */
setUsedScatterProperties(const QCPScatterStyle::ScatterProperties & properties)10129 void QCPSelectionDecorator::setUsedScatterProperties(const QCPScatterStyle::ScatterProperties &properties)
10130 {
10131   mUsedScatterProperties = properties;
10132 }
10133 
10134 /*!
10135   Sets the pen of \a painter to the pen of this selection decorator.
10136 
10137   \see applyBrush, getFinalScatterStyle
10138 */
applyPen(QCPPainter * painter) const10139 void QCPSelectionDecorator::applyPen(QCPPainter *painter) const
10140 {
10141   painter->setPen(mPen);
10142 }
10143 
10144 /*!
10145   Sets the brush of \a painter to the brush of this selection decorator.
10146 
10147   \see applyPen, getFinalScatterStyle
10148 */
applyBrush(QCPPainter * painter) const10149 void QCPSelectionDecorator::applyBrush(QCPPainter *painter) const
10150 {
10151   painter->setBrush(mBrush);
10152 }
10153 
10154 /*!
10155   Returns the scatter style that the parent plottable shall use for selected scatter points. The
10156   plottable's original (unselected) scatter style must be passed as \a unselectedStyle. Depending
10157   on the setting of \ref setUsedScatterProperties, the returned scatter style is a mixture of this
10158   selecion decorator's scatter style (\ref setScatterStyle), and \a unselectedStyle.
10159 
10160   \see applyPen, applyBrush, setScatterStyle
10161 */
getFinalScatterStyle(const QCPScatterStyle & unselectedStyle) const10162 QCPScatterStyle QCPSelectionDecorator::getFinalScatterStyle(const QCPScatterStyle &unselectedStyle) const
10163 {
10164   QCPScatterStyle result(unselectedStyle);
10165   result.setFromOther(mScatterStyle, mUsedScatterProperties);
10166 
10167   // if style shall inherit pen from plottable (has no own pen defined), give it the selected
10168   // plottable pen explicitly, so it doesn't use the unselected plottable pen when used in the
10169   // plottable:
10170   if (!result.isPenDefined())
10171     result.setPen(mPen);
10172 
10173   return result;
10174 }
10175 
10176 /*!
10177   Copies all properties (e.g. color, fill, scatter style) of the \a other selection decorator to
10178   this selection decorator.
10179 */
copyFrom(const QCPSelectionDecorator * other)10180 void QCPSelectionDecorator::copyFrom(const QCPSelectionDecorator *other)
10181 {
10182   setPen(other->pen());
10183   setBrush(other->brush());
10184   setScatterStyle(other->scatterStyle(), other->usedScatterProperties());
10185 }
10186 
10187 /*!
10188   This method is called by all plottables' draw methods to allow custom selection decorations to be
10189   drawn. Use the passed \a painter to perform the drawing operations. \a selection carries the data
10190   selection for which the decoration shall be drawn.
10191 
10192   The default base class implementation of \ref QCPSelectionDecorator has no special decoration, so
10193   this method does nothing.
10194 */
drawDecoration(QCPPainter * painter,QCPDataSelection selection)10195 void QCPSelectionDecorator::drawDecoration(QCPPainter *painter, QCPDataSelection selection)
10196 {
10197   Q_UNUSED(painter)
10198   Q_UNUSED(selection)
10199 }
10200 
10201 /*! \internal
10202 
10203   This method is called as soon as a selection decorator is associated with a plottable, by a call
10204   to \ref QCPAbstractPlottable::setSelectionDecorator. This way the selection decorator can obtain a pointer to the plottable that uses it (e.g. to access
10205   data points via the \ref QCPAbstractPlottable::interface1D interface).
10206 
10207   If the selection decorator was already added to a different plottable before, this method aborts
10208   the registration and returns false.
10209 */
registerWithPlottable(QCPAbstractPlottable * plottable)10210 bool QCPSelectionDecorator::registerWithPlottable(QCPAbstractPlottable *plottable)
10211 {
10212   if (!mPlottable)
10213   {
10214     mPlottable = plottable;
10215     return true;
10216   } else
10217   {
10218     qDebug() << Q_FUNC_INFO << "This selection decorator is already registered with plottable:" << reinterpret_cast<quintptr>(mPlottable);
10219     return false;
10220   }
10221 }
10222 
10223 
10224 ////////////////////////////////////////////////////////////////////////////////////////////////////
10225 //////////////////// QCPAbstractPlottable
10226 ////////////////////////////////////////////////////////////////////////////////////////////////////
10227 
10228 /*! \class QCPAbstractPlottable
10229   \brief The abstract base class for all data representing objects in a plot.
10230 
10231   It defines a very basic interface like name, pen, brush, visibility etc. Since this class is
10232   abstract, it can't be instantiated. Use one of the subclasses or create a subclass yourself to
10233   create new ways of displaying data (see "Creating own plottables" below). Plottables that display
10234   one-dimensional data (i.e. data points have a single key dimension and one or multiple values at
10235   each key) are based off of the template subclass \ref QCPAbstractPlottable1D, see details
10236   there.
10237 
10238   All further specifics are in the subclasses, for example:
10239   \li A normal graph with possibly a line and/or scatter points \ref QCPGraph
10240   (typically created with \ref QCustomPlot::addGraph)
10241   \li A parametric curve: \ref QCPCurve
10242   \li A bar chart: \ref QCPBars
10243   \li A statistical box plot: \ref QCPStatisticalBox
10244   \li A color encoded two-dimensional map: \ref QCPColorMap
10245   \li An OHLC/Candlestick chart: \ref QCPFinancial
10246 
10247   \section plottables-subclassing Creating own plottables
10248 
10249   Subclassing directly from QCPAbstractPlottable is only recommended if you wish to display
10250   two-dimensional data like \ref QCPColorMap, i.e. two logical key dimensions and one (or more)
10251   data dimensions. If you want to display data with only one logical key dimension, you should
10252   rather derive from \ref QCPAbstractPlottable1D.
10253 
10254   If subclassing QCPAbstractPlottable directly, these are the pure virtual functions you must
10255   implement:
10256   \li \ref selectTest
10257   \li \ref draw
10258   \li \ref drawLegendIcon
10259   \li \ref getKeyRange
10260   \li \ref getValueRange
10261 
10262   See the documentation of those functions for what they need to do.
10263 
10264   For drawing your plot, you can use the \ref coordsToPixels functions to translate a point in plot
10265   coordinates to pixel coordinates. This function is quite convenient, because it takes the
10266   orientation of the key and value axes into account for you (x and y are swapped when the key axis
10267   is vertical and the value axis horizontal). If you are worried about performance (i.e. you need
10268   to translate many points in a loop like QCPGraph), you can directly use \ref
10269   QCPAxis::coordToPixel. However, you must then take care about the orientation of the axis
10270   yourself.
10271 
10272   Here are some important members you inherit from QCPAbstractPlottable:
10273   <table>
10274   <tr>
10275     <td>QCustomPlot *\b mParentPlot</td>
10276     <td>A pointer to the parent QCustomPlot instance. The parent plot is inferred from the axes that are passed in the constructor.</td>
10277   </tr><tr>
10278     <td>QString \b mName</td>
10279     <td>The name of the plottable.</td>
10280   </tr><tr>
10281     <td>QPen \b mPen</td>
10282     <td>The generic pen of the plottable. You should use this pen for the most prominent data representing lines in the plottable
10283         (e.g QCPGraph uses this pen for its graph lines and scatters)</td>
10284   </tr><tr>
10285     <td>QBrush \b mBrush</td>
10286     <td>The generic brush of the plottable. You should use this brush for the most prominent fillable structures in the plottable
10287         (e.g. QCPGraph uses this brush to control filling under the graph)</td>
10288   </tr><tr>
10289     <td>QPointer<\ref QCPAxis> \b mKeyAxis, \b mValueAxis</td>
10290     <td>The key and value axes this plottable is attached to. Call their QCPAxis::coordToPixel functions to translate coordinates
10291         to pixels in either the key or value dimension. Make sure to check whether the pointer is null before using it. If one of
10292         the axes is null, don't draw the plottable.</td>
10293   </tr><tr>
10294     <td>\ref QCPSelectionDecorator \b mSelectionDecorator</td>
10295     <td>The currently set selection decorator which specifies how selected data of the plottable shall be drawn and decorated.
10296         When drawing your data, you must consult this decorator for the appropriate pen/brush before drawing unselected/selected data segments.
10297         Finally, you should call its \ref QCPSelectionDecorator::drawDecoration method at the end of your \ref draw implementation.</td>
10298   </tr><tr>
10299     <td>\ref QCP::SelectionType \b mSelectable</td>
10300     <td>In which composition, if at all, this plottable's data may be selected. Enforcing this setting on the data selection is done
10301         by QCPAbstractPlottable automatically.</td>
10302   </tr><tr>
10303     <td>\ref QCPDataSelection \b mSelection</td>
10304     <td>Holds the current selection state of the plottable's data, i.e. the selected data ranges (\ref QCPDataRange).</td>
10305   </tr>
10306   </table>
10307 */
10308 
10309 /* start of documentation of inline functions */
10310 
10311 /*! \fn QCPSelectionDecorator *QCPAbstractPlottable::selectionDecorator() const
10312 
10313   Provides access to the selection decorator of this plottable. The selection decorator controls
10314   how selected data ranges are drawn (e.g. their pen color and fill), see \ref
10315   QCPSelectionDecorator for details.
10316 
10317   If you wish to use an own \ref QCPSelectionDecorator subclass, pass an instance of it to \ref
10318   setSelectionDecorator.
10319 */
10320 
10321 /*! \fn bool QCPAbstractPlottable::selected() const
10322 
10323   Returns true if there are any data points of the plottable currently selected. Use \ref selection
10324   to retrieve the current \ref QCPDataSelection.
10325 */
10326 
10327 /*! \fn QCPDataSelection QCPAbstractPlottable::selection() const
10328 
10329   Returns a \ref QCPDataSelection encompassing all the data points that are currently selected on
10330   this plottable.
10331 
10332   \see selected, setSelection, setSelectable
10333 */
10334 
10335 /*! \fn virtual QCPPlottableInterface1D *QCPAbstractPlottable::interface1D()
10336 
10337   If this plottable is a one-dimensional plottable, i.e. it implements the \ref
10338   QCPPlottableInterface1D, returns the \a this pointer with that type. Otherwise (e.g. in the case
10339   of a \ref QCPColorMap) returns zero.
10340 
10341   You can use this method to gain read access to data coordinates while holding a pointer to the
10342   abstract base class only.
10343 */
10344 
10345 /* end of documentation of inline functions */
10346 /* start of documentation of pure virtual functions */
10347 
10348 /*! \fn void QCPAbstractPlottable::drawLegendIcon(QCPPainter *painter, const QRect &rect) const = 0
10349   \internal
10350 
10351   called by QCPLegend::draw (via QCPPlottableLegendItem::draw) to create a graphical representation
10352   of this plottable inside \a rect, next to the plottable name.
10353 
10354   The passed \a painter has its cliprect set to \a rect, so painting outside of \a rect won't
10355   appear outside the legend icon border.
10356 */
10357 
10358 /*! \fn QCPRange QCPAbstractPlottable::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const = 0
10359 
10360   Returns the coordinate range that all data in this plottable span in the key axis dimension. For
10361   logarithmic plots, one can set \a inSignDomain to either \ref QCP::sdNegative or \ref
10362   QCP::sdPositive in order to restrict the returned range to that sign domain. E.g. when only
10363   negative range is wanted, set \a inSignDomain to \ref QCP::sdNegative and all positive points
10364   will be ignored for range calculation. For no restriction, just set \a inSignDomain to \ref
10365   QCP::sdBoth (default). \a foundRange is an output parameter that indicates whether a range could
10366   be found or not. If this is false, you shouldn't use the returned range (e.g. no points in data).
10367 
10368   Note that \a foundRange is not the same as \ref QCPRange::validRange, since the range returned by
10369   this function may have size zero (e.g. when there is only one data point). In this case \a
10370   foundRange would return true, but the returned range is not a valid range in terms of \ref
10371   QCPRange::validRange.
10372 
10373   \see rescaleAxes, getValueRange
10374 */
10375 
10376 /*! \fn QCPRange QCPAbstractPlottable::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const = 0
10377 
10378   Returns the coordinate range that the data points in the specified key range (\a inKeyRange) span
10379   in the value axis dimension. For logarithmic plots, one can set \a inSignDomain to either \ref
10380   QCP::sdNegative or \ref QCP::sdPositive in order to restrict the returned range to that sign
10381   domain. E.g. when only negative range is wanted, set \a inSignDomain to \ref QCP::sdNegative and
10382   all positive points will be ignored for range calculation. For no restriction, just set \a
10383   inSignDomain to \ref QCP::sdBoth (default). \a foundRange is an output parameter that indicates
10384   whether a range could be found or not. If this is false, you shouldn't use the returned range
10385   (e.g. no points in data).
10386 
10387   If \a inKeyRange has both lower and upper bound set to zero (is equal to <tt>QCPRange()</tt>),
10388   all data points are considered, without any restriction on the keys.
10389 
10390   Note that \a foundRange is not the same as \ref QCPRange::validRange, since the range returned by
10391   this function may have size zero (e.g. when there is only one data point). In this case \a
10392   foundRange would return true, but the returned range is not a valid range in terms of \ref
10393   QCPRange::validRange.
10394 
10395   \see rescaleAxes, getKeyRange
10396 */
10397 
10398 /* end of documentation of pure virtual functions */
10399 /* start of documentation of signals */
10400 
10401 /*! \fn void QCPAbstractPlottable::selectionChanged(bool selected)
10402 
10403   This signal is emitted when the selection state of this plottable has changed, either by user
10404   interaction or by a direct call to \ref setSelection. The parameter \a selected indicates whether
10405   there are any points selected or not.
10406 
10407   \see selectionChanged(const QCPDataSelection &selection)
10408 */
10409 
10410 /*! \fn void QCPAbstractPlottable::selectionChanged(const QCPDataSelection &selection)
10411 
10412   This signal is emitted when the selection state of this plottable has changed, either by user
10413   interaction or by a direct call to \ref setSelection. The parameter \a selection holds the
10414   currently selected data ranges.
10415 
10416   \see selectionChanged(bool selected)
10417 */
10418 
10419 /*! \fn void QCPAbstractPlottable::selectableChanged(QCP::SelectionType selectable);
10420 
10421   This signal is emitted when the selectability of this plottable has changed.
10422 
10423   \see setSelectable
10424 */
10425 
10426 /* end of documentation of signals */
10427 
10428 /*!
10429   Constructs an abstract plottable which uses \a keyAxis as its key axis ("x") and \a valueAxis as
10430   its value axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance
10431   and have perpendicular orientations. If either of these restrictions is violated, a corresponding
10432   message is printed to the debug output (qDebug), the construction is not aborted, though.
10433 
10434   Since QCPAbstractPlottable is an abstract class that defines the basic interface to plottables,
10435   it can't be directly instantiated.
10436 
10437   You probably want one of the subclasses like \ref QCPGraph or \ref QCPCurve instead.
10438 */
QCPAbstractPlottable(QCPAxis * keyAxis,QCPAxis * valueAxis)10439 QCPAbstractPlottable::QCPAbstractPlottable(QCPAxis *keyAxis, QCPAxis *valueAxis) :
10440   QCPLayerable(keyAxis->parentPlot(), QString(), keyAxis->axisRect()),
10441   mName(),
10442   mAntialiasedFill(true),
10443   mAntialiasedScatters(true),
10444   mPen(Qt::black),
10445   mBrush(Qt::NoBrush),
10446   mKeyAxis(keyAxis),
10447   mValueAxis(valueAxis),
10448   mSelectable(QCP::stWhole),
10449   mSelectionDecorator(0)
10450 {
10451   if (keyAxis->parentPlot() != valueAxis->parentPlot())
10452     qDebug() << Q_FUNC_INFO << "Parent plot of keyAxis is not the same as that of valueAxis.";
10453   if (keyAxis->orientation() == valueAxis->orientation())
10454     qDebug() << Q_FUNC_INFO << "keyAxis and valueAxis must be orthogonal to each other.";
10455 
10456   mParentPlot->registerPlottable(this);
10457   setSelectionDecorator(new QCPSelectionDecorator);
10458 }
10459 
~QCPAbstractPlottable()10460 QCPAbstractPlottable::~QCPAbstractPlottable()
10461 {
10462   if (mSelectionDecorator)
10463   {
10464     delete mSelectionDecorator;
10465     mSelectionDecorator = 0;
10466   }
10467 }
10468 
10469 /*!
10470    The name is the textual representation of this plottable as it is displayed in the legend
10471    (\ref QCPLegend). It may contain any UTF-8 characters, including newlines.
10472 */
setName(const QString & name)10473 void QCPAbstractPlottable::setName(const QString &name)
10474 {
10475   mName = name;
10476 }
10477 
10478 /*!
10479   Sets whether fills of this plottable are drawn antialiased or not.
10480 
10481   Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref
10482   QCustomPlot::setNotAntialiasedElements.
10483 */
setAntialiasedFill(bool enabled)10484 void QCPAbstractPlottable::setAntialiasedFill(bool enabled)
10485 {
10486   mAntialiasedFill = enabled;
10487 }
10488 
10489 /*!
10490   Sets whether the scatter symbols of this plottable are drawn antialiased or not.
10491 
10492   Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref
10493   QCustomPlot::setNotAntialiasedElements.
10494 */
setAntialiasedScatters(bool enabled)10495 void QCPAbstractPlottable::setAntialiasedScatters(bool enabled)
10496 {
10497   mAntialiasedScatters = enabled;
10498 }
10499 
10500 /*!
10501   The pen is used to draw basic lines that make up the plottable representation in the
10502   plot.
10503 
10504   For example, the \ref QCPGraph subclass draws its graph lines with this pen.
10505 
10506   \see setBrush
10507 */
setPen(const QPen & pen)10508 void QCPAbstractPlottable::setPen(const QPen &pen)
10509 {
10510   mPen = pen;
10511 }
10512 
10513 /*!
10514   The brush is used to draw basic fills of the plottable representation in the
10515   plot. The Fill can be a color, gradient or texture, see the usage of QBrush.
10516 
10517   For example, the \ref QCPGraph subclass draws the fill under the graph with this brush, when
10518   it's not set to Qt::NoBrush.
10519 
10520   \see setPen
10521 */
setBrush(const QBrush & brush)10522 void QCPAbstractPlottable::setBrush(const QBrush &brush)
10523 {
10524   mBrush = brush;
10525 }
10526 
10527 /*!
10528   The key axis of a plottable can be set to any axis of a QCustomPlot, as long as it is orthogonal
10529   to the plottable's value axis. This function performs no checks to make sure this is the case.
10530   The typical mathematical choice is to use the x-axis (QCustomPlot::xAxis) as key axis and the
10531   y-axis (QCustomPlot::yAxis) as value axis.
10532 
10533   Normally, the key and value axes are set in the constructor of the plottable (or \ref
10534   QCustomPlot::addGraph when working with QCPGraphs through the dedicated graph interface).
10535 
10536   \see setValueAxis
10537 */
setKeyAxis(QCPAxis * axis)10538 void QCPAbstractPlottable::setKeyAxis(QCPAxis *axis)
10539 {
10540   mKeyAxis = axis;
10541 }
10542 
10543 /*!
10544   The value axis of a plottable can be set to any axis of a QCustomPlot, as long as it is
10545   orthogonal to the plottable's key axis. This function performs no checks to make sure this is the
10546   case. The typical mathematical choice is to use the x-axis (QCustomPlot::xAxis) as key axis and
10547   the y-axis (QCustomPlot::yAxis) as value axis.
10548 
10549   Normally, the key and value axes are set in the constructor of the plottable (or \ref
10550   QCustomPlot::addGraph when working with QCPGraphs through the dedicated graph interface).
10551 
10552   \see setKeyAxis
10553 */
setValueAxis(QCPAxis * axis)10554 void QCPAbstractPlottable::setValueAxis(QCPAxis *axis)
10555 {
10556   mValueAxis = axis;
10557 }
10558 
10559 
10560 /*!
10561   Sets which data ranges of this plottable are selected. Selected data ranges are drawn differently
10562   (e.g. color) in the plot. This can be controlled via the selection decorator (see \ref
10563   selectionDecorator).
10564 
10565   The entire selection mechanism for plottables is handled automatically when \ref
10566   QCustomPlot::setInteractions contains iSelectPlottables. You only need to call this function when
10567   you wish to change the selection state programmatically.
10568 
10569   Using \ref setSelectable you can further specify for each plottable whether and to which
10570   granularity it is selectable. If \a selection is not compatible with the current \ref
10571   QCP::SelectionType set via \ref setSelectable, the resulting selection will be adjusted
10572   accordingly (see \ref QCPDataSelection::enforceType).
10573 
10574   emits the \ref selectionChanged signal when \a selected is different from the previous selection state.
10575 
10576   \see setSelectable, selectTest
10577 */
setSelection(QCPDataSelection selection)10578 void QCPAbstractPlottable::setSelection(QCPDataSelection selection)
10579 {
10580   selection.enforceType(mSelectable);
10581   if (mSelection != selection)
10582   {
10583     mSelection = selection;
10584     emit selectionChanged(selected());
10585     emit selectionChanged(mSelection);
10586   }
10587 }
10588 
10589 /*!
10590   Use this method to set an own QCPSelectionDecorator (subclass) instance. This allows you to
10591   customize the visual representation of selected data ranges further than by using the default
10592   QCPSelectionDecorator.
10593 
10594   The plottable takes ownership of the \a decorator.
10595 
10596   The currently set decorator can be accessed via \ref selectionDecorator.
10597 */
setSelectionDecorator(QCPSelectionDecorator * decorator)10598 void QCPAbstractPlottable::setSelectionDecorator(QCPSelectionDecorator *decorator)
10599 {
10600   if (decorator)
10601   {
10602     if (decorator->registerWithPlottable(this))
10603     {
10604       if (mSelectionDecorator) // delete old decorator if necessary
10605         delete mSelectionDecorator;
10606       mSelectionDecorator = decorator;
10607     }
10608   } else if (mSelectionDecorator) // just clear decorator
10609   {
10610     delete mSelectionDecorator;
10611     mSelectionDecorator = 0;
10612   }
10613 }
10614 
10615 /*!
10616   Sets whether and to which granularity this plottable can be selected.
10617 
10618   A selection can happen by clicking on the QCustomPlot surface (When \ref
10619   QCustomPlot::setInteractions contains \ref QCP::iSelectPlottables), by dragging a selection rect
10620   (When \ref QCustomPlot::setSelectionRectMode is \ref QCP::srmSelect), or programmatically by
10621   calling \ref setSelection.
10622 
10623   \see setSelection, QCP::SelectionType
10624 */
setSelectable(QCP::SelectionType selectable)10625 void QCPAbstractPlottable::setSelectable(QCP::SelectionType selectable)
10626 {
10627   if (mSelectable != selectable)
10628   {
10629     mSelectable = selectable;
10630     QCPDataSelection oldSelection = mSelection;
10631     mSelection.enforceType(mSelectable);
10632     emit selectableChanged(mSelectable);
10633     if (mSelection != oldSelection)
10634     {
10635       emit selectionChanged(selected());
10636       emit selectionChanged(mSelection);
10637     }
10638   }
10639 }
10640 
10641 
10642 /*!
10643   Convenience function for transforming a key/value pair to pixels on the QCustomPlot surface,
10644   taking the orientations of the axes associated with this plottable into account (e.g. whether key
10645   represents x or y).
10646 
10647   \a key and \a value are transformed to the coodinates in pixels and are written to \a x and \a y.
10648 
10649   \see pixelsToCoords, QCPAxis::coordToPixel
10650 */
coordsToPixels(double key,double value,double & x,double & y) const10651 void QCPAbstractPlottable::coordsToPixels(double key, double value, double &x, double &y) const
10652 {
10653   QCPAxis *keyAxis = mKeyAxis.data();
10654   QCPAxis *valueAxis = mValueAxis.data();
10655   if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
10656 
10657   if (keyAxis->orientation() == Qt::Horizontal)
10658   {
10659     x = keyAxis->coordToPixel(key);
10660     y = valueAxis->coordToPixel(value);
10661   } else
10662   {
10663     y = keyAxis->coordToPixel(key);
10664     x = valueAxis->coordToPixel(value);
10665   }
10666 }
10667 
10668 /*! \overload
10669 
10670   Transforms the given \a key and \a value to pixel coordinates and returns them in a QPointF.
10671 */
coordsToPixels(double key,double value) const10672 const QPointF QCPAbstractPlottable::coordsToPixels(double key, double value) const
10673 {
10674   QCPAxis *keyAxis = mKeyAxis.data();
10675   QCPAxis *valueAxis = mValueAxis.data();
10676   if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPointF(); }
10677 
10678   if (keyAxis->orientation() == Qt::Horizontal)
10679     return QPointF(keyAxis->coordToPixel(key), valueAxis->coordToPixel(value));
10680   else
10681     return QPointF(valueAxis->coordToPixel(value), keyAxis->coordToPixel(key));
10682 }
10683 
10684 /*!
10685   Convenience function for transforming a x/y pixel pair on the QCustomPlot surface to plot coordinates,
10686   taking the orientations of the axes associated with this plottable into account (e.g. whether key
10687   represents x or y).
10688 
10689   \a x and \a y are transformed to the plot coodinates and are written to \a key and \a value.
10690 
10691   \see coordsToPixels, QCPAxis::coordToPixel
10692 */
pixelsToCoords(double x,double y,double & key,double & value) const10693 void QCPAbstractPlottable::pixelsToCoords(double x, double y, double &key, double &value) const
10694 {
10695   QCPAxis *keyAxis = mKeyAxis.data();
10696   QCPAxis *valueAxis = mValueAxis.data();
10697   if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
10698 
10699   if (keyAxis->orientation() == Qt::Horizontal)
10700   {
10701     key = keyAxis->pixelToCoord(x);
10702     value = valueAxis->pixelToCoord(y);
10703   } else
10704   {
10705     key = keyAxis->pixelToCoord(y);
10706     value = valueAxis->pixelToCoord(x);
10707   }
10708 }
10709 
10710 /*! \overload
10711 
10712   Returns the pixel input \a pixelPos as plot coordinates \a key and \a value.
10713 */
pixelsToCoords(const QPointF & pixelPos,double & key,double & value) const10714 void QCPAbstractPlottable::pixelsToCoords(const QPointF &pixelPos, double &key, double &value) const
10715 {
10716   pixelsToCoords(pixelPos.x(), pixelPos.y(), key, value);
10717 }
10718 
10719 /*!
10720   Rescales the key and value axes associated with this plottable to contain all displayed data, so
10721   the whole plottable is visible. If the scaling of an axis is logarithmic, rescaleAxes will make
10722   sure not to rescale to an illegal range i.e. a range containing different signs and/or zero.
10723   Instead it will stay in the current sign domain and ignore all parts of the plottable that lie
10724   outside of that domain.
10725 
10726   \a onlyEnlarge makes sure the ranges are only expanded, never reduced. So it's possible to show
10727   multiple plottables in their entirety by multiple calls to rescaleAxes where the first call has
10728   \a onlyEnlarge set to false (the default), and all subsequent set to true.
10729 
10730   \see rescaleKeyAxis, rescaleValueAxis, QCustomPlot::rescaleAxes, QCPAxis::rescale
10731 */
rescaleAxes(bool onlyEnlarge) const10732 void QCPAbstractPlottable::rescaleAxes(bool onlyEnlarge) const
10733 {
10734   rescaleKeyAxis(onlyEnlarge);
10735   rescaleValueAxis(onlyEnlarge);
10736 }
10737 
10738 /*!
10739   Rescales the key axis of the plottable so the whole plottable is visible.
10740 
10741   See \ref rescaleAxes for detailed behaviour.
10742 */
rescaleKeyAxis(bool onlyEnlarge) const10743 void QCPAbstractPlottable::rescaleKeyAxis(bool onlyEnlarge) const
10744 {
10745   QCPAxis *keyAxis = mKeyAxis.data();
10746   if (!keyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; }
10747 
10748   QCP::SignDomain signDomain = QCP::sdBoth;
10749   if (keyAxis->scaleType() == QCPAxis::stLogarithmic)
10750     signDomain = (keyAxis->range().upper < 0 ? QCP::sdNegative : QCP::sdPositive);
10751 
10752   bool foundRange;
10753   QCPRange newRange = getKeyRange(foundRange, signDomain);
10754   if (foundRange)
10755   {
10756     if (onlyEnlarge)
10757       newRange.expand(keyAxis->range());
10758     if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable
10759     {
10760       double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason
10761       if (keyAxis->scaleType() == QCPAxis::stLinear)
10762       {
10763         newRange.lower = center-keyAxis->range().size()/2.0;
10764         newRange.upper = center+keyAxis->range().size()/2.0;
10765       } else // scaleType() == stLogarithmic
10766       {
10767         newRange.lower = center/qSqrt(keyAxis->range().upper/keyAxis->range().lower);
10768         newRange.upper = center*qSqrt(keyAxis->range().upper/keyAxis->range().lower);
10769       }
10770     }
10771     keyAxis->setRange(newRange);
10772   }
10773 }
10774 
10775 /*!
10776   Rescales the value axis of the plottable so the whole plottable is visible. If \a inKeyRange is
10777   set to true, only the data points which are in the currently visible key axis range are
10778   considered.
10779 
10780   Returns true if the axis was actually scaled. This might not be the case if this plottable has an
10781   invalid range, e.g. because it has no data points.
10782 
10783   See \ref rescaleAxes for detailed behaviour.
10784 */
rescaleValueAxis(bool onlyEnlarge,bool inKeyRange) const10785 void QCPAbstractPlottable::rescaleValueAxis(bool onlyEnlarge, bool inKeyRange) const
10786 {
10787   QCPAxis *keyAxis = mKeyAxis.data();
10788   QCPAxis *valueAxis = mValueAxis.data();
10789   if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
10790 
10791   QCP::SignDomain signDomain = QCP::sdBoth;
10792   if (valueAxis->scaleType() == QCPAxis::stLogarithmic)
10793     signDomain = (valueAxis->range().upper < 0 ? QCP::sdNegative : QCP::sdPositive);
10794 
10795   bool foundRange;
10796   QCPRange newRange = getValueRange(foundRange, signDomain, inKeyRange ? keyAxis->range() : QCPRange());
10797   if (foundRange)
10798   {
10799     if (onlyEnlarge)
10800       newRange.expand(valueAxis->range());
10801     if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable
10802     {
10803       double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason
10804       if (valueAxis->scaleType() == QCPAxis::stLinear)
10805       {
10806         newRange.lower = center-valueAxis->range().size()/2.0;
10807         newRange.upper = center+valueAxis->range().size()/2.0;
10808       } else // scaleType() == stLogarithmic
10809       {
10810         newRange.lower = center/qSqrt(valueAxis->range().upper/valueAxis->range().lower);
10811         newRange.upper = center*qSqrt(valueAxis->range().upper/valueAxis->range().lower);
10812       }
10813     }
10814     valueAxis->setRange(newRange);
10815   }
10816 }
10817 
10818 /*! \overload
10819 
10820   Adds this plottable to the specified \a legend.
10821 
10822   Creates a QCPPlottableLegendItem which is inserted into the legend. Returns true on success, i.e.
10823   when the legend exists and a legend item associated with this plottable isn't already in the
10824   legend.
10825 
10826   If the plottable needs a more specialized representation in the legend, you can create a
10827   corresponding subclass of \ref QCPPlottableLegendItem and add it to the legend manually instead
10828   of calling this method.
10829 
10830   \see removeFromLegend, QCPLegend::addItem
10831 */
addToLegend(QCPLegend * legend)10832 bool QCPAbstractPlottable::addToLegend(QCPLegend *legend)
10833 {
10834   if (!legend)
10835   {
10836     qDebug() << Q_FUNC_INFO << "passed legend is null";
10837     return false;
10838   }
10839   if (legend->parentPlot() != mParentPlot)
10840   {
10841     qDebug() << Q_FUNC_INFO << "passed legend isn't in the same QCustomPlot as this plottable";
10842     return false;
10843   }
10844 
10845   if (!legend->hasItemWithPlottable(this))
10846   {
10847     legend->addItem(new QCPPlottableLegendItem(legend, this));
10848     return true;
10849   } else
10850     return false;
10851 }
10852 
10853 /*! \overload
10854 
10855   Adds this plottable to the legend of the parent QCustomPlot (\ref QCustomPlot::legend).
10856 
10857   \see removeFromLegend
10858 */
addToLegend()10859 bool QCPAbstractPlottable::addToLegend()
10860 {
10861   if (!mParentPlot || !mParentPlot->legend)
10862     return false;
10863   else
10864     return addToLegend(mParentPlot->legend);
10865 }
10866 
10867 /*! \overload
10868 
10869   Removes the plottable from the specifed \a legend. This means the \ref QCPPlottableLegendItem
10870   that is associated with this plottable is removed.
10871 
10872   Returns true on success, i.e. if the legend exists and a legend item associated with this
10873   plottable was found and removed.
10874 
10875   \see addToLegend, QCPLegend::removeItem
10876 */
removeFromLegend(QCPLegend * legend) const10877 bool QCPAbstractPlottable::removeFromLegend(QCPLegend *legend) const
10878 {
10879   if (!legend)
10880   {
10881     qDebug() << Q_FUNC_INFO << "passed legend is null";
10882     return false;
10883   }
10884 
10885   if (QCPPlottableLegendItem *lip = legend->itemWithPlottable(this))
10886     return legend->removeItem(lip);
10887   else
10888     return false;
10889 }
10890 
10891 /*! \overload
10892 
10893   Removes the plottable from the legend of the parent QCustomPlot.
10894 
10895   \see addToLegend
10896 */
removeFromLegend() const10897 bool QCPAbstractPlottable::removeFromLegend() const
10898 {
10899   if (!mParentPlot || !mParentPlot->legend)
10900     return false;
10901   else
10902     return removeFromLegend(mParentPlot->legend);
10903 }
10904 
10905 /* inherits documentation from base class */
clipRect() const10906 QRect QCPAbstractPlottable::clipRect() const
10907 {
10908   if (mKeyAxis && mValueAxis)
10909     return mKeyAxis.data()->axisRect()->rect() & mValueAxis.data()->axisRect()->rect();
10910   else
10911     return QRect();
10912 }
10913 
10914 /* inherits documentation from base class */
selectionCategory() const10915 QCP::Interaction QCPAbstractPlottable::selectionCategory() const
10916 {
10917   return QCP::iSelectPlottables;
10918 }
10919 
10920 /*! \internal
10921 
10922   A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
10923   before drawing plottable lines.
10924 
10925   This is the antialiasing state the painter passed to the \ref draw method is in by default.
10926 
10927   This function takes into account the local setting of the antialiasing flag as well as the
10928   overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
10929   QCustomPlot::setNotAntialiasedElements.
10930 
10931   \seebaseclassmethod
10932 
10933   \see setAntialiased, applyFillAntialiasingHint, applyScattersAntialiasingHint
10934 */
applyDefaultAntialiasingHint(QCPPainter * painter) const10935 void QCPAbstractPlottable::applyDefaultAntialiasingHint(QCPPainter *painter) const
10936 {
10937   applyAntialiasingHint(painter, mAntialiased, QCP::aePlottables);
10938 }
10939 
10940 /*! \internal
10941 
10942   A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
10943   before drawing plottable fills.
10944 
10945   This function takes into account the local setting of the antialiasing flag as well as the
10946   overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
10947   QCustomPlot::setNotAntialiasedElements.
10948 
10949   \see setAntialiased, applyDefaultAntialiasingHint, applyScattersAntialiasingHint
10950 */
applyFillAntialiasingHint(QCPPainter * painter) const10951 void QCPAbstractPlottable::applyFillAntialiasingHint(QCPPainter *painter) const
10952 {
10953   applyAntialiasingHint(painter, mAntialiasedFill, QCP::aeFills);
10954 }
10955 
10956 /*! \internal
10957 
10958   A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
10959   before drawing plottable scatter points.
10960 
10961   This function takes into account the local setting of the antialiasing flag as well as the
10962   overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
10963   QCustomPlot::setNotAntialiasedElements.
10964 
10965   \see setAntialiased, applyFillAntialiasingHint, applyDefaultAntialiasingHint
10966 */
applyScattersAntialiasingHint(QCPPainter * painter) const10967 void QCPAbstractPlottable::applyScattersAntialiasingHint(QCPPainter *painter) const
10968 {
10969   applyAntialiasingHint(painter, mAntialiasedScatters, QCP::aeScatters);
10970 }
10971 
10972 /* inherits documentation from base class */
selectEvent(QMouseEvent * event,bool additive,const QVariant & details,bool * selectionStateChanged)10973 void QCPAbstractPlottable::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
10974 {
10975   Q_UNUSED(event)
10976 
10977   if (mSelectable != QCP::stNone)
10978   {
10979     QCPDataSelection newSelection = details.value<QCPDataSelection>();
10980     QCPDataSelection selectionBefore = mSelection;
10981     if (additive)
10982     {
10983       if (mSelectable == QCP::stWhole) // in whole selection mode, we toggle to no selection even if currently unselected point was hit
10984       {
10985         if (selected())
10986           setSelection(QCPDataSelection());
10987         else
10988           setSelection(newSelection);
10989       } else // in all other selection modes we toggle selections of homogeneously selected/unselected segments
10990       {
10991         if (mSelection.contains(newSelection)) // if entire newSelection is already selected, toggle selection
10992           setSelection(mSelection-newSelection);
10993         else
10994           setSelection(mSelection+newSelection);
10995       }
10996     } else
10997       setSelection(newSelection);
10998     if (selectionStateChanged)
10999       *selectionStateChanged = mSelection != selectionBefore;
11000   }
11001 }
11002 
11003 /* inherits documentation from base class */
deselectEvent(bool * selectionStateChanged)11004 void QCPAbstractPlottable::deselectEvent(bool *selectionStateChanged)
11005 {
11006   if (mSelectable != QCP::stNone)
11007   {
11008     QCPDataSelection selectionBefore = mSelection;
11009     setSelection(QCPDataSelection());
11010     if (selectionStateChanged)
11011       *selectionStateChanged = mSelection != selectionBefore;
11012   }
11013 }
11014 /* end of 'src/plottable.cpp' */
11015 
11016 
11017 /* including file 'src/item.cpp', size 49269                                 */
11018 /* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
11019 
11020 ////////////////////////////////////////////////////////////////////////////////////////////////////
11021 //////////////////// QCPItemAnchor
11022 ////////////////////////////////////////////////////////////////////////////////////////////////////
11023 
11024 /*! \class QCPItemAnchor
11025   \brief An anchor of an item to which positions can be attached to.
11026 
11027   An item (QCPAbstractItem) may have one or more anchors. Unlike QCPItemPosition, an anchor doesn't
11028   control anything on its item, but provides a way to tie other items via their positions to the
11029   anchor.
11030 
11031   For example, a QCPItemRect is defined by its positions \a topLeft and \a bottomRight.
11032   Additionally it has various anchors like \a top, \a topRight or \a bottomLeft etc. So you can
11033   attach the \a start (which is a QCPItemPosition) of a QCPItemLine to one of the anchors by
11034   calling QCPItemPosition::setParentAnchor on \a start, passing the wanted anchor of the
11035   QCPItemRect. This way the start of the line will now always follow the respective anchor location
11036   on the rect item.
11037 
11038   Note that QCPItemPosition derives from QCPItemAnchor, so every position can also serve as an
11039   anchor to other positions.
11040 
11041   To learn how to provide anchors in your own item subclasses, see the subclassing section of the
11042   QCPAbstractItem documentation.
11043 */
11044 
11045 /* start documentation of inline functions */
11046 
11047 /*! \fn virtual QCPItemPosition *QCPItemAnchor::toQCPItemPosition()
11048 
11049   Returns 0 if this instance is merely a QCPItemAnchor, and a valid pointer of type QCPItemPosition* if
11050   it actually is a QCPItemPosition (which is a subclass of QCPItemAnchor).
11051 
11052   This safe downcast functionality could also be achieved with a dynamic_cast. However, QCustomPlot avoids
11053   dynamic_cast to work with projects that don't have RTTI support enabled (e.g. -fno-rtti flag with
11054   gcc compiler).
11055 */
11056 
11057 /* end documentation of inline functions */
11058 
11059 /*!
11060   Creates a new QCPItemAnchor. You shouldn't create QCPItemAnchor instances directly, even if
11061   you want to make a new item subclass. Use \ref QCPAbstractItem::createAnchor instead, as
11062   explained in the subclassing section of the QCPAbstractItem documentation.
11063 */
QCPItemAnchor(QCustomPlot * parentPlot,QCPAbstractItem * parentItem,const QString & name,int anchorId)11064 QCPItemAnchor::QCPItemAnchor(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString &name, int anchorId) :
11065   mName(name),
11066   mParentPlot(parentPlot),
11067   mParentItem(parentItem),
11068   mAnchorId(anchorId)
11069 {
11070 }
11071 
~QCPItemAnchor()11072 QCPItemAnchor::~QCPItemAnchor()
11073 {
11074   // unregister as parent at children:
11075   foreach (QCPItemPosition *child, mChildrenX.values())
11076   {
11077     if (child->parentAnchorX() == this)
11078       child->setParentAnchorX(0); // this acts back on this anchor and child removes itself from mChildrenX
11079   }
11080   foreach (QCPItemPosition *child, mChildrenY.values())
11081   {
11082     if (child->parentAnchorY() == this)
11083       child->setParentAnchorY(0); // this acts back on this anchor and child removes itself from mChildrenY
11084   }
11085 }
11086 
11087 /*!
11088   Returns the final absolute pixel position of the QCPItemAnchor on the QCustomPlot surface.
11089 
11090   The pixel information is internally retrieved via QCPAbstractItem::anchorPixelPosition of the
11091   parent item, QCPItemAnchor is just an intermediary.
11092 */
pixelPosition() const11093 QPointF QCPItemAnchor::pixelPosition() const
11094 {
11095   if (mParentItem)
11096   {
11097     if (mAnchorId > -1)
11098     {
11099       return mParentItem->anchorPixelPosition(mAnchorId);
11100     } else
11101     {
11102       qDebug() << Q_FUNC_INFO << "no valid anchor id set:" << mAnchorId;
11103       return QPointF();
11104     }
11105   } else
11106   {
11107     qDebug() << Q_FUNC_INFO << "no parent item set";
11108     return QPointF();
11109   }
11110 }
11111 
11112 /*! \internal
11113 
11114   Adds \a pos to the childX list of this anchor, which keeps track of which children use this
11115   anchor as parent anchor for the respective coordinate. This is necessary to notify the children
11116   prior to destruction of the anchor.
11117 
11118   Note that this function does not change the parent setting in \a pos.
11119 */
addChildX(QCPItemPosition * pos)11120 void QCPItemAnchor::addChildX(QCPItemPosition *pos)
11121 {
11122   if (!mChildrenX.contains(pos))
11123     mChildrenX.insert(pos);
11124   else
11125     qDebug() << Q_FUNC_INFO << "provided pos is child already" << reinterpret_cast<quintptr>(pos);
11126 }
11127 
11128 /*! \internal
11129 
11130   Removes \a pos from the childX list of this anchor.
11131 
11132   Note that this function does not change the parent setting in \a pos.
11133 */
removeChildX(QCPItemPosition * pos)11134 void QCPItemAnchor::removeChildX(QCPItemPosition *pos)
11135 {
11136   if (!mChildrenX.remove(pos))
11137     qDebug() << Q_FUNC_INFO << "provided pos isn't child" << reinterpret_cast<quintptr>(pos);
11138 }
11139 
11140 /*! \internal
11141 
11142   Adds \a pos to the childY list of this anchor, which keeps track of which children use this
11143   anchor as parent anchor for the respective coordinate. This is necessary to notify the children
11144   prior to destruction of the anchor.
11145 
11146   Note that this function does not change the parent setting in \a pos.
11147 */
addChildY(QCPItemPosition * pos)11148 void QCPItemAnchor::addChildY(QCPItemPosition *pos)
11149 {
11150   if (!mChildrenY.contains(pos))
11151     mChildrenY.insert(pos);
11152   else
11153     qDebug() << Q_FUNC_INFO << "provided pos is child already" << reinterpret_cast<quintptr>(pos);
11154 }
11155 
11156 /*! \internal
11157 
11158   Removes \a pos from the childY list of this anchor.
11159 
11160   Note that this function does not change the parent setting in \a pos.
11161 */
removeChildY(QCPItemPosition * pos)11162 void QCPItemAnchor::removeChildY(QCPItemPosition *pos)
11163 {
11164   if (!mChildrenY.remove(pos))
11165     qDebug() << Q_FUNC_INFO << "provided pos isn't child" << reinterpret_cast<quintptr>(pos);
11166 }
11167 
11168 
11169 ////////////////////////////////////////////////////////////////////////////////////////////////////
11170 //////////////////// QCPItemPosition
11171 ////////////////////////////////////////////////////////////////////////////////////////////////////
11172 
11173 /*! \class QCPItemPosition
11174   \brief Manages the position of an item.
11175 
11176   Every item has at least one public QCPItemPosition member pointer which provides ways to position the
11177   item on the QCustomPlot surface. Some items have multiple positions, for example QCPItemRect has two:
11178   \a topLeft and \a bottomRight.
11179 
11180   QCPItemPosition has a type (\ref PositionType) that can be set with \ref setType. This type
11181   defines how coordinates passed to \ref setCoords are to be interpreted, e.g. as absolute pixel
11182   coordinates, as plot coordinates of certain axes, etc. For more advanced plots it is also
11183   possible to assign different types per X/Y coordinate of the position (see \ref setTypeX, \ref
11184   setTypeY). This way an item could be positioned at a fixed pixel distance from the top in the Y
11185   direction, while following a plot coordinate in the X direction.
11186 
11187   A QCPItemPosition may have a parent QCPItemAnchor, see \ref setParentAnchor. This way you can tie
11188   multiple items together. If the QCPItemPosition has a parent, its coordinates (\ref setCoords)
11189   are considered to be absolute pixels in the reference frame of the parent anchor, where (0, 0)
11190   means directly ontop of the parent anchor. For example, You could attach the \a start position of
11191   a QCPItemLine to the \a bottom anchor of a QCPItemText to make the starting point of the line
11192   always be centered under the text label, no matter where the text is moved to. For more advanced
11193   plots, it is possible to assign different parent anchors per X/Y coordinate of the position, see
11194   \ref setParentAnchorX, \ref setParentAnchorY. This way an item could follow another item in the X
11195   direction but stay at a fixed position in the Y direction. Or even follow item A in X, and item B
11196   in Y.
11197 
11198   Note that every QCPItemPosition inherits from QCPItemAnchor and thus can itself be used as parent
11199   anchor for other positions.
11200 
11201   To set the apparent pixel position on the QCustomPlot surface directly, use \ref setPixelPosition. This
11202   works no matter what type this QCPItemPosition is or what parent-child situation it is in, as \ref
11203   setPixelPosition transforms the coordinates appropriately, to make the position appear at the specified
11204   pixel values.
11205 */
11206 
11207 /* start documentation of inline functions */
11208 
11209 /*! \fn QCPItemPosition::PositionType *QCPItemPosition::type() const
11210 
11211   Returns the current position type.
11212 
11213   If different types were set for X and Y (\ref setTypeX, \ref setTypeY), this method returns the
11214   type of the X coordinate. In that case rather use \a typeX() and \a typeY().
11215 
11216   \see setType
11217 */
11218 
11219 /*! \fn QCPItemAnchor *QCPItemPosition::parentAnchor() const
11220 
11221   Returns the current parent anchor.
11222 
11223   If different parent anchors were set for X and Y (\ref setParentAnchorX, \ref setParentAnchorY),
11224   this method returns the parent anchor of the Y coordinate. In that case rather use \a
11225   parentAnchorX() and \a parentAnchorY().
11226 
11227   \see setParentAnchor
11228 */
11229 
11230 /* end documentation of inline functions */
11231 
11232 /*!
11233   Creates a new QCPItemPosition. You shouldn't create QCPItemPosition instances directly, even if
11234   you want to make a new item subclass. Use \ref QCPAbstractItem::createPosition instead, as
11235   explained in the subclassing section of the QCPAbstractItem documentation.
11236 */
QCPItemPosition(QCustomPlot * parentPlot,QCPAbstractItem * parentItem,const QString & name)11237 QCPItemPosition::QCPItemPosition(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString &name) :
11238   QCPItemAnchor(parentPlot, parentItem, name),
11239   mPositionTypeX(ptAbsolute),
11240   mPositionTypeY(ptAbsolute),
11241   mKey(0),
11242   mValue(0),
11243   mParentAnchorX(0),
11244   mParentAnchorY(0)
11245 {
11246 }
11247 
~QCPItemPosition()11248 QCPItemPosition::~QCPItemPosition()
11249 {
11250   // unregister as parent at children:
11251   // Note: this is done in ~QCPItemAnchor again, but it's important QCPItemPosition does it itself, because only then
11252   //       the setParentAnchor(0) call the correct QCPItemPosition::pixelPosition function instead of QCPItemAnchor::pixelPosition
11253   foreach (QCPItemPosition *child, mChildrenX.values())
11254   {
11255     if (child->parentAnchorX() == this)
11256       child->setParentAnchorX(0); // this acts back on this anchor and child removes itself from mChildrenX
11257   }
11258   foreach (QCPItemPosition *child, mChildrenY.values())
11259   {
11260     if (child->parentAnchorY() == this)
11261       child->setParentAnchorY(0); // this acts back on this anchor and child removes itself from mChildrenY
11262   }
11263   // unregister as child in parent:
11264   if (mParentAnchorX)
11265     mParentAnchorX->removeChildX(this);
11266   if (mParentAnchorY)
11267     mParentAnchorY->removeChildY(this);
11268 }
11269 
11270 /* can't make this a header inline function, because QPointer breaks with forward declared types, see QTBUG-29588 */
axisRect() const11271 QCPAxisRect *QCPItemPosition::axisRect() const
11272 {
11273   return mAxisRect.data();
11274 }
11275 
11276 /*!
11277   Sets the type of the position. The type defines how the coordinates passed to \ref setCoords
11278   should be handled and how the QCPItemPosition should behave in the plot.
11279 
11280   The possible values for \a type can be separated in two main categories:
11281 
11282   \li The position is regarded as a point in plot coordinates. This corresponds to \ref ptPlotCoords
11283   and requires two axes that define the plot coordinate system. They can be specified with \ref setAxes.
11284   By default, the QCustomPlot's x- and yAxis are used.
11285 
11286   \li The position is fixed on the QCustomPlot surface, i.e. independent of axis ranges. This
11287   corresponds to all other types, i.e. \ref ptAbsolute, \ref ptViewportRatio and \ref
11288   ptAxisRectRatio. They differ only in the way the absolute position is described, see the
11289   documentation of \ref PositionType for details. For \ref ptAxisRectRatio, note that you can specify
11290   the axis rect with \ref setAxisRect. By default this is set to the main axis rect.
11291 
11292   Note that the position type \ref ptPlotCoords is only available (and sensible) when the position
11293   has no parent anchor (\ref setParentAnchor).
11294 
11295   If the type is changed, the apparent pixel position on the plot is preserved. This means
11296   the coordinates as retrieved with coords() and set with \ref setCoords may change in the process.
11297 
11298   This method sets the type for both X and Y directions. It is also possible to set different types
11299   for X and Y, see \ref setTypeX, \ref setTypeY.
11300 */
setType(QCPItemPosition::PositionType type)11301 void QCPItemPosition::setType(QCPItemPosition::PositionType type)
11302 {
11303   setTypeX(type);
11304   setTypeY(type);
11305 }
11306 
11307 /*!
11308   This method sets the position type of the X coordinate to \a type.
11309 
11310   For a detailed description of what a position type is, see the documentation of \ref setType.
11311 
11312   \see setType, setTypeY
11313 */
setTypeX(QCPItemPosition::PositionType type)11314 void QCPItemPosition::setTypeX(QCPItemPosition::PositionType type)
11315 {
11316   if (mPositionTypeX != type)
11317   {
11318     // if switching from or to coordinate type that isn't valid (e.g. because axes or axis rect
11319     // were deleted), don't try to recover the pixelPosition() because it would output a qDebug warning.
11320     bool retainPixelPosition = true;
11321     if ((mPositionTypeX == ptPlotCoords || type == ptPlotCoords) && (!mKeyAxis || !mValueAxis))
11322       retainPixelPosition = false;
11323     if ((mPositionTypeX == ptAxisRectRatio || type == ptAxisRectRatio) && (!mAxisRect))
11324       retainPixelPosition = false;
11325 
11326     QPointF pixel;
11327     if (retainPixelPosition)
11328       pixel = pixelPosition();
11329 
11330     mPositionTypeX = type;
11331 
11332     if (retainPixelPosition)
11333       setPixelPosition(pixel);
11334   }
11335 }
11336 
11337 /*!
11338   This method sets the position type of the Y coordinate to \a type.
11339 
11340   For a detailed description of what a position type is, see the documentation of \ref setType.
11341 
11342   \see setType, setTypeX
11343 */
setTypeY(QCPItemPosition::PositionType type)11344 void QCPItemPosition::setTypeY(QCPItemPosition::PositionType type)
11345 {
11346   if (mPositionTypeY != type)
11347   {
11348     // if switching from or to coordinate type that isn't valid (e.g. because axes or axis rect
11349     // were deleted), don't try to recover the pixelPosition() because it would output a qDebug warning.
11350     bool retainPixelPosition = true;
11351     if ((mPositionTypeY == ptPlotCoords || type == ptPlotCoords) && (!mKeyAxis || !mValueAxis))
11352       retainPixelPosition = false;
11353     if ((mPositionTypeY == ptAxisRectRatio || type == ptAxisRectRatio) && (!mAxisRect))
11354       retainPixelPosition = false;
11355 
11356     QPointF pixel;
11357     if (retainPixelPosition)
11358       pixel = pixelPosition();
11359 
11360     mPositionTypeY = type;
11361 
11362     if (retainPixelPosition)
11363       setPixelPosition(pixel);
11364   }
11365 }
11366 
11367 /*!
11368   Sets the parent of this QCPItemPosition to \a parentAnchor. This means the position will now
11369   follow any position changes of the anchor. The local coordinate system of positions with a parent
11370   anchor always is absolute pixels, with (0, 0) being exactly on top of the parent anchor. (Hence
11371   the type shouldn't be set to \ref ptPlotCoords for positions with parent anchors.)
11372 
11373   if \a keepPixelPosition is true, the current pixel position of the QCPItemPosition is preserved
11374   during reparenting. If it's set to false, the coordinates are set to (0, 0), i.e. the position
11375   will be exactly on top of the parent anchor.
11376 
11377   To remove this QCPItemPosition from any parent anchor, set \a parentAnchor to 0.
11378 
11379   If the QCPItemPosition previously had no parent and the type is \ref ptPlotCoords, the type is
11380   set to \ref ptAbsolute, to keep the position in a valid state.
11381 
11382   This method sets the parent anchor for both X and Y directions. It is also possible to set
11383   different parents for X and Y, see \ref setParentAnchorX, \ref setParentAnchorY.
11384 */
setParentAnchor(QCPItemAnchor * parentAnchor,bool keepPixelPosition)11385 bool QCPItemPosition::setParentAnchor(QCPItemAnchor *parentAnchor, bool keepPixelPosition)
11386 {
11387   bool successX = setParentAnchorX(parentAnchor, keepPixelPosition);
11388   bool successY = setParentAnchorY(parentAnchor, keepPixelPosition);
11389   return successX && successY;
11390 }
11391 
11392 /*!
11393   This method sets the parent anchor of the X coordinate to \a parentAnchor.
11394 
11395   For a detailed description of what a parent anchor is, see the documentation of \ref setParentAnchor.
11396 
11397   \see setParentAnchor, setParentAnchorY
11398 */
setParentAnchorX(QCPItemAnchor * parentAnchor,bool keepPixelPosition)11399 bool QCPItemPosition::setParentAnchorX(QCPItemAnchor *parentAnchor, bool keepPixelPosition)
11400 {
11401   // make sure self is not assigned as parent:
11402   if (parentAnchor == this)
11403   {
11404     qDebug() << Q_FUNC_INFO << "can't set self as parent anchor" << reinterpret_cast<quintptr>(parentAnchor);
11405     return false;
11406   }
11407   // make sure no recursive parent-child-relationships are created:
11408   QCPItemAnchor *currentParent = parentAnchor;
11409   while (currentParent)
11410   {
11411     if (QCPItemPosition *currentParentPos = currentParent->toQCPItemPosition())
11412     {
11413       // is a QCPItemPosition, might have further parent, so keep iterating
11414       if (currentParentPos == this)
11415       {
11416         qDebug() << Q_FUNC_INFO << "can't create recursive parent-child-relationship" << reinterpret_cast<quintptr>(parentAnchor);
11417         return false;
11418       }
11419       currentParent = currentParentPos->parentAnchorX();
11420     } else
11421     {
11422       // is a QCPItemAnchor, can't have further parent. Now make sure the parent items aren't the
11423       // same, to prevent a position being child of an anchor which itself depends on the position,
11424       // because they're both on the same item:
11425       if (currentParent->mParentItem == mParentItem)
11426       {
11427         qDebug() << Q_FUNC_INFO << "can't set parent to be an anchor which itself depends on this position" << reinterpret_cast<quintptr>(parentAnchor);
11428         return false;
11429       }
11430       break;
11431     }
11432   }
11433 
11434   // if previously no parent set and PosType is still ptPlotCoords, set to ptAbsolute:
11435   if (!mParentAnchorX && mPositionTypeX == ptPlotCoords)
11436     setTypeX(ptAbsolute);
11437 
11438   // save pixel position:
11439   QPointF pixelP;
11440   if (keepPixelPosition)
11441     pixelP = pixelPosition();
11442   // unregister at current parent anchor:
11443   if (mParentAnchorX)
11444     mParentAnchorX->removeChildX(this);
11445   // register at new parent anchor:
11446   if (parentAnchor)
11447     parentAnchor->addChildX(this);
11448   mParentAnchorX = parentAnchor;
11449   // restore pixel position under new parent:
11450   if (keepPixelPosition)
11451     setPixelPosition(pixelP);
11452   else
11453     setCoords(0, coords().y());
11454   return true;
11455 }
11456 
11457 /*!
11458   This method sets the parent anchor of the Y coordinate to \a parentAnchor.
11459 
11460   For a detailed description of what a parent anchor is, see the documentation of \ref setParentAnchor.
11461 
11462   \see setParentAnchor, setParentAnchorX
11463 */
setParentAnchorY(QCPItemAnchor * parentAnchor,bool keepPixelPosition)11464 bool QCPItemPosition::setParentAnchorY(QCPItemAnchor *parentAnchor, bool keepPixelPosition)
11465 {
11466   // make sure self is not assigned as parent:
11467   if (parentAnchor == this)
11468   {
11469     qDebug() << Q_FUNC_INFO << "can't set self as parent anchor" << reinterpret_cast<quintptr>(parentAnchor);
11470     return false;
11471   }
11472   // make sure no recursive parent-child-relationships are created:
11473   QCPItemAnchor *currentParent = parentAnchor;
11474   while (currentParent)
11475   {
11476     if (QCPItemPosition *currentParentPos = currentParent->toQCPItemPosition())
11477     {
11478       // is a QCPItemPosition, might have further parent, so keep iterating
11479       if (currentParentPos == this)
11480       {
11481         qDebug() << Q_FUNC_INFO << "can't create recursive parent-child-relationship" << reinterpret_cast<quintptr>(parentAnchor);
11482         return false;
11483       }
11484       currentParent = currentParentPos->parentAnchorY();
11485     } else
11486     {
11487       // is a QCPItemAnchor, can't have further parent. Now make sure the parent items aren't the
11488       // same, to prevent a position being child of an anchor which itself depends on the position,
11489       // because they're both on the same item:
11490       if (currentParent->mParentItem == mParentItem)
11491       {
11492         qDebug() << Q_FUNC_INFO << "can't set parent to be an anchor which itself depends on this position" << reinterpret_cast<quintptr>(parentAnchor);
11493         return false;
11494       }
11495       break;
11496     }
11497   }
11498 
11499   // if previously no parent set and PosType is still ptPlotCoords, set to ptAbsolute:
11500   if (!mParentAnchorY && mPositionTypeY == ptPlotCoords)
11501     setTypeY(ptAbsolute);
11502 
11503   // save pixel position:
11504   QPointF pixelP;
11505   if (keepPixelPosition)
11506     pixelP = pixelPosition();
11507   // unregister at current parent anchor:
11508   if (mParentAnchorY)
11509     mParentAnchorY->removeChildY(this);
11510   // register at new parent anchor:
11511   if (parentAnchor)
11512     parentAnchor->addChildY(this);
11513   mParentAnchorY = parentAnchor;
11514   // restore pixel position under new parent:
11515   if (keepPixelPosition)
11516     setPixelPosition(pixelP);
11517   else
11518     setCoords(coords().x(), 0);
11519   return true;
11520 }
11521 
11522 /*!
11523   Sets the coordinates of this QCPItemPosition. What the coordinates mean, is defined by the type
11524   (\ref setType, \ref setTypeX, \ref setTypeY).
11525 
11526   For example, if the type is \ref ptAbsolute, \a key and \a value mean the x and y pixel position
11527   on the QCustomPlot surface. In that case the origin (0, 0) is in the top left corner of the
11528   QCustomPlot viewport. If the type is \ref ptPlotCoords, \a key and \a value mean a point in the
11529   plot coordinate system defined by the axes set by \ref setAxes. By default those are the
11530   QCustomPlot's xAxis and yAxis. See the documentation of \ref setType for other available
11531   coordinate types and their meaning.
11532 
11533   If different types were configured for X and Y (\ref setTypeX, \ref setTypeY), \a key and \a
11534   value must also be provided in the different coordinate systems. Here, the X type refers to \a
11535   key, and the Y type refers to \a value.
11536 
11537   \see setPixelPosition
11538 */
setCoords(double key,double value)11539 void QCPItemPosition::setCoords(double key, double value)
11540 {
11541   mKey = key;
11542   mValue = value;
11543 }
11544 
11545 /*! \overload
11546 
11547   Sets the coordinates as a QPointF \a pos where pos.x has the meaning of \a key and pos.y the
11548   meaning of \a value of the \ref setCoords(double key, double value) method.
11549 */
setCoords(const QPointF & pos)11550 void QCPItemPosition::setCoords(const QPointF &pos)
11551 {
11552   setCoords(pos.x(), pos.y());
11553 }
11554 
11555 /*!
11556   Returns the final absolute pixel position of the QCPItemPosition on the QCustomPlot surface. It
11557   includes all effects of type (\ref setType) and possible parent anchors (\ref setParentAnchor).
11558 
11559   \see setPixelPosition
11560 */
pixelPosition() const11561 QPointF QCPItemPosition::pixelPosition() const
11562 {
11563   QPointF result;
11564 
11565   // determine X:
11566   switch (mPositionTypeX)
11567   {
11568     case ptAbsolute:
11569     {
11570       result.rx() = mKey;
11571       if (mParentAnchorX)
11572         result.rx() += mParentAnchorX->pixelPosition().x();
11573       break;
11574     }
11575     case ptViewportRatio:
11576     {
11577       result.rx() = mKey*mParentPlot->viewport().width();
11578       if (mParentAnchorX)
11579         result.rx() += mParentAnchorX->pixelPosition().x();
11580       else
11581         result.rx() += mParentPlot->viewport().left();
11582       break;
11583     }
11584     case ptAxisRectRatio:
11585     {
11586       if (mAxisRect)
11587       {
11588         result.rx() = mKey*mAxisRect.data()->width();
11589         if (mParentAnchorX)
11590           result.rx() += mParentAnchorX->pixelPosition().x();
11591         else
11592           result.rx() += mAxisRect.data()->left();
11593       } else
11594         qDebug() << Q_FUNC_INFO << "Item position type x is ptAxisRectRatio, but no axis rect was defined";
11595       break;
11596     }
11597     case ptPlotCoords:
11598     {
11599       if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Horizontal)
11600         result.rx() = mKeyAxis.data()->coordToPixel(mKey);
11601       else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Horizontal)
11602         result.rx() = mValueAxis.data()->coordToPixel(mValue);
11603       else
11604         qDebug() << Q_FUNC_INFO << "Item position type x is ptPlotCoords, but no axes were defined";
11605       break;
11606     }
11607   }
11608 
11609   // determine Y:
11610   switch (mPositionTypeY)
11611   {
11612     case ptAbsolute:
11613     {
11614       result.ry() = mValue;
11615       if (mParentAnchorY)
11616         result.ry() += mParentAnchorY->pixelPosition().y();
11617       break;
11618     }
11619     case ptViewportRatio:
11620     {
11621       result.ry() = mValue*mParentPlot->viewport().height();
11622       if (mParentAnchorY)
11623         result.ry() += mParentAnchorY->pixelPosition().y();
11624       else
11625         result.ry() += mParentPlot->viewport().top();
11626       break;
11627     }
11628     case ptAxisRectRatio:
11629     {
11630       if (mAxisRect)
11631       {
11632         result.ry() = mValue*mAxisRect.data()->height();
11633         if (mParentAnchorY)
11634           result.ry() += mParentAnchorY->pixelPosition().y();
11635         else
11636           result.ry() += mAxisRect.data()->top();
11637       } else
11638         qDebug() << Q_FUNC_INFO << "Item position type y is ptAxisRectRatio, but no axis rect was defined";
11639       break;
11640     }
11641     case ptPlotCoords:
11642     {
11643       if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Vertical)
11644         result.ry() = mKeyAxis.data()->coordToPixel(mKey);
11645       else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Vertical)
11646         result.ry() = mValueAxis.data()->coordToPixel(mValue);
11647       else
11648         qDebug() << Q_FUNC_INFO << "Item position type y is ptPlotCoords, but no axes were defined";
11649       break;
11650     }
11651   }
11652 
11653   return result;
11654 }
11655 
11656 /*!
11657   When \ref setType is \ref ptPlotCoords, this function may be used to specify the axes the
11658   coordinates set with \ref setCoords relate to. By default they are set to the initial xAxis and
11659   yAxis of the QCustomPlot.
11660 */
setAxes(QCPAxis * keyAxis,QCPAxis * valueAxis)11661 void QCPItemPosition::setAxes(QCPAxis *keyAxis, QCPAxis *valueAxis)
11662 {
11663   mKeyAxis = keyAxis;
11664   mValueAxis = valueAxis;
11665 }
11666 
11667 /*!
11668   When \ref setType is \ref ptAxisRectRatio, this function may be used to specify the axis rect the
11669   coordinates set with \ref setCoords relate to. By default this is set to the main axis rect of
11670   the QCustomPlot.
11671 */
setAxisRect(QCPAxisRect * axisRect)11672 void QCPItemPosition::setAxisRect(QCPAxisRect *axisRect)
11673 {
11674   mAxisRect = axisRect;
11675 }
11676 
11677 /*!
11678   Sets the apparent pixel position. This works no matter what type (\ref setType) this
11679   QCPItemPosition is or what parent-child situation it is in, as coordinates are transformed
11680   appropriately, to make the position finally appear at the specified pixel values.
11681 
11682   Only if the type is \ref ptAbsolute and no parent anchor is set, this function's effect is
11683   identical to that of \ref setCoords.
11684 
11685   \see pixelPosition, setCoords
11686 */
setPixelPosition(const QPointF & pixelPosition)11687 void QCPItemPosition::setPixelPosition(const QPointF &pixelPosition)
11688 {
11689   double x = pixelPosition.x();
11690   double y = pixelPosition.y();
11691 
11692   switch (mPositionTypeX)
11693   {
11694     case ptAbsolute:
11695     {
11696       if (mParentAnchorX)
11697         x -= mParentAnchorX->pixelPosition().x();
11698       break;
11699     }
11700     case ptViewportRatio:
11701     {
11702       if (mParentAnchorX)
11703         x -= mParentAnchorX->pixelPosition().x();
11704       else
11705         x -= mParentPlot->viewport().left();
11706       x /= (double)mParentPlot->viewport().width();
11707       break;
11708     }
11709     case ptAxisRectRatio:
11710     {
11711       if (mAxisRect)
11712       {
11713         if (mParentAnchorX)
11714           x -= mParentAnchorX->pixelPosition().x();
11715         else
11716           x -= mAxisRect.data()->left();
11717         x /= (double)mAxisRect.data()->width();
11718       } else
11719         qDebug() << Q_FUNC_INFO << "Item position type x is ptAxisRectRatio, but no axis rect was defined";
11720       break;
11721     }
11722     case ptPlotCoords:
11723     {
11724       if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Horizontal)
11725         x = mKeyAxis.data()->pixelToCoord(x);
11726       else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Horizontal)
11727         y = mValueAxis.data()->pixelToCoord(x);
11728       else
11729         qDebug() << Q_FUNC_INFO << "Item position type x is ptPlotCoords, but no axes were defined";
11730       break;
11731     }
11732   }
11733 
11734   switch (mPositionTypeY)
11735   {
11736     case ptAbsolute:
11737     {
11738       if (mParentAnchorY)
11739         y -= mParentAnchorY->pixelPosition().y();
11740       break;
11741     }
11742     case ptViewportRatio:
11743     {
11744       if (mParentAnchorY)
11745         y -= mParentAnchorY->pixelPosition().y();
11746       else
11747         y -= mParentPlot->viewport().top();
11748       y /= (double)mParentPlot->viewport().height();
11749       break;
11750     }
11751     case ptAxisRectRatio:
11752     {
11753       if (mAxisRect)
11754       {
11755         if (mParentAnchorY)
11756           y -= mParentAnchorY->pixelPosition().y();
11757         else
11758           y -= mAxisRect.data()->top();
11759         y /= (double)mAxisRect.data()->height();
11760       } else
11761         qDebug() << Q_FUNC_INFO << "Item position type y is ptAxisRectRatio, but no axis rect was defined";
11762       break;
11763     }
11764     case ptPlotCoords:
11765     {
11766       if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Vertical)
11767         x = mKeyAxis.data()->pixelToCoord(y);
11768       else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Vertical)
11769         y = mValueAxis.data()->pixelToCoord(y);
11770       else
11771         qDebug() << Q_FUNC_INFO << "Item position type y is ptPlotCoords, but no axes were defined";
11772       break;
11773     }
11774   }
11775 
11776   setCoords(x, y);
11777 }
11778 
11779 
11780 ////////////////////////////////////////////////////////////////////////////////////////////////////
11781 //////////////////// QCPAbstractItem
11782 ////////////////////////////////////////////////////////////////////////////////////////////////////
11783 
11784 /*! \class QCPAbstractItem
11785   \brief The abstract base class for all items in a plot.
11786 
11787   In QCustomPlot, items are supplemental graphical elements that are neither plottables
11788   (QCPAbstractPlottable) nor axes (QCPAxis). While plottables are always tied to two axes and thus
11789   plot coordinates, items can also be placed in absolute coordinates independent of any axes. Each
11790   specific item has at least one QCPItemPosition member which controls the positioning. Some items
11791   are defined by more than one coordinate and thus have two or more QCPItemPosition members (For
11792   example, QCPItemRect has \a topLeft and \a bottomRight).
11793 
11794   This abstract base class defines a very basic interface like visibility and clipping. Since this
11795   class is abstract, it can't be instantiated. Use one of the subclasses or create a subclass
11796   yourself to create new items.
11797 
11798   The built-in items are:
11799   <table>
11800   <tr><td>QCPItemLine</td><td>A line defined by a start and an end point. May have different ending styles on each side (e.g. arrows).</td></tr>
11801   <tr><td>QCPItemStraightLine</td><td>A straight line defined by a start and a direction point. Unlike QCPItemLine, the straight line is infinitely long and has no endings.</td></tr>
11802   <tr><td>QCPItemCurve</td><td>A curve defined by start, end and two intermediate control points. May have different ending styles on each side (e.g. arrows).</td></tr>
11803   <tr><td>QCPItemRect</td><td>A rectangle</td></tr>
11804   <tr><td>QCPItemEllipse</td><td>An ellipse</td></tr>
11805   <tr><td>QCPItemPixmap</td><td>An arbitrary pixmap</td></tr>
11806   <tr><td>QCPItemText</td><td>A text label</td></tr>
11807   <tr><td>QCPItemBracket</td><td>A bracket which may be used to reference/highlight certain parts in the plot.</td></tr>
11808   <tr><td>QCPItemTracer</td><td>An item that can be attached to a QCPGraph and sticks to its data points, given a key coordinate.</td></tr>
11809   </table>
11810 
11811   \section items-clipping Clipping
11812 
11813   Items are by default clipped to the main axis rect (they are only visible inside the axis rect).
11814   To make an item visible outside that axis rect, disable clipping via \ref setClipToAxisRect
11815   "setClipToAxisRect(false)".
11816 
11817   On the other hand if you want the item to be clipped to a different axis rect, specify it via
11818   \ref setClipAxisRect. This clipAxisRect property of an item is only used for clipping behaviour, and
11819   in principle is independent of the coordinate axes the item might be tied to via its position
11820   members (\ref QCPItemPosition::setAxes). However, it is common that the axis rect for clipping
11821   also contains the axes used for the item positions.
11822 
11823   \section items-using Using items
11824 
11825   First you instantiate the item you want to use and add it to the plot:
11826   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-1
11827   by default, the positions of the item are bound to the x- and y-Axis of the plot. So we can just
11828   set the plot coordinates where the line should start/end:
11829   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-2
11830   If we don't want the line to be positioned in plot coordinates but a different coordinate system,
11831   e.g. absolute pixel positions on the QCustomPlot surface, we need to change the position type like this:
11832   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-3
11833   Then we can set the coordinates, this time in pixels:
11834   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-4
11835   and make the line visible on the entire QCustomPlot, by disabling clipping to the axis rect:
11836   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-5
11837 
11838   For more advanced plots, it is even possible to set different types and parent anchors per X/Y
11839   coordinate of an item position, using for example \ref QCPItemPosition::setTypeX or \ref
11840   QCPItemPosition::setParentAnchorX. For details, see the documentation of \ref QCPItemPosition.
11841 
11842   \section items-subclassing Creating own items
11843 
11844   To create an own item, you implement a subclass of QCPAbstractItem. These are the pure
11845   virtual functions, you must implement:
11846   \li \ref selectTest
11847   \li \ref draw
11848 
11849   See the documentation of those functions for what they need to do.
11850 
11851   \subsection items-positioning Allowing the item to be positioned
11852 
11853   As mentioned, item positions are represented by QCPItemPosition members. Let's assume the new item shall
11854   have only one point as its position (as opposed to two like a rect or multiple like a polygon). You then add
11855   a public member of type QCPItemPosition like so:
11856 
11857   \code QCPItemPosition * const myPosition;\endcode
11858 
11859   the const makes sure the pointer itself can't be modified from the user of your new item (the QCPItemPosition
11860   instance it points to, can be modified, of course).
11861   The initialization of this pointer is made easy with the \ref createPosition function. Just assign
11862   the return value of this function to each QCPItemPosition in the constructor of your item. \ref createPosition
11863   takes a string which is the name of the position, typically this is identical to the variable name.
11864   For example, the constructor of QCPItemExample could look like this:
11865 
11866   \code
11867   QCPItemExample::QCPItemExample(QCustomPlot *parentPlot) :
11868     QCPAbstractItem(parentPlot),
11869     myPosition(createPosition("myPosition"))
11870   {
11871     // other constructor code
11872   }
11873   \endcode
11874 
11875   \subsection items-drawing The draw function
11876 
11877   To give your item a visual representation, reimplement the \ref draw function and use the passed
11878   QCPPainter to draw the item. You can retrieve the item position in pixel coordinates from the
11879   position member(s) via \ref QCPItemPosition::pixelPosition.
11880 
11881   To optimize performance you should calculate a bounding rect first (don't forget to take the pen
11882   width into account), check whether it intersects the \ref clipRect, and only draw the item at all
11883   if this is the case.
11884 
11885   \subsection items-selection The selectTest function
11886 
11887   Your implementation of the \ref selectTest function may use the helpers \ref
11888   QCPVector2D::distanceSquaredToLine and \ref rectDistance. With these, the implementation of the
11889   selection test becomes significantly simpler for most items. See the documentation of \ref
11890   selectTest for what the function parameters mean and what the function should return.
11891 
11892   \subsection anchors Providing anchors
11893 
11894   Providing anchors (QCPItemAnchor) starts off like adding a position. First you create a public
11895   member, e.g.
11896 
11897   \code QCPItemAnchor * const bottom;\endcode
11898 
11899   and create it in the constructor with the \ref createAnchor function, assigning it a name and an
11900   anchor id (an integer enumerating all anchors on the item, you may create an own enum for this).
11901   Since anchors can be placed anywhere, relative to the item's position(s), your item needs to
11902   provide the position of every anchor with the reimplementation of the \ref anchorPixelPosition(int
11903   anchorId) function.
11904 
11905   In essence the QCPItemAnchor is merely an intermediary that itself asks your item for the pixel
11906   position when anything attached to the anchor needs to know the coordinates.
11907 */
11908 
11909 /* start of documentation of inline functions */
11910 
11911 /*! \fn QList<QCPItemPosition*> QCPAbstractItem::positions() const
11912 
11913   Returns all positions of the item in a list.
11914 
11915   \see anchors, position
11916 */
11917 
11918 /*! \fn QList<QCPItemAnchor*> QCPAbstractItem::anchors() const
11919 
11920   Returns all anchors of the item in a list. Note that since a position (QCPItemPosition) is always
11921   also an anchor, the list will also contain the positions of this item.
11922 
11923   \see positions, anchor
11924 */
11925 
11926 /* end of documentation of inline functions */
11927 /* start documentation of pure virtual functions */
11928 
11929 /*! \fn void QCPAbstractItem::draw(QCPPainter *painter) = 0
11930   \internal
11931 
11932   Draws this item with the provided \a painter.
11933 
11934   The cliprect of the provided painter is set to the rect returned by \ref clipRect before this
11935   function is called. The clipRect depends on the clipping settings defined by \ref
11936   setClipToAxisRect and \ref setClipAxisRect.
11937 */
11938 
11939 /* end documentation of pure virtual functions */
11940 /* start documentation of signals */
11941 
11942 /*! \fn void QCPAbstractItem::selectionChanged(bool selected)
11943   This signal is emitted when the selection state of this item has changed, either by user interaction
11944   or by a direct call to \ref setSelected.
11945 */
11946 
11947 /* end documentation of signals */
11948 
11949 /*!
11950   Base class constructor which initializes base class members.
11951 */
QCPAbstractItem(QCustomPlot * parentPlot)11952 QCPAbstractItem::QCPAbstractItem(QCustomPlot *parentPlot) :
11953   QCPLayerable(parentPlot),
11954   mClipToAxisRect(false),
11955   mSelectable(true),
11956   mSelected(false)
11957 {
11958   parentPlot->registerItem(this);
11959 
11960   QList<QCPAxisRect*> rects = parentPlot->axisRects();
11961   if (rects.size() > 0)
11962   {
11963     setClipToAxisRect(true);
11964     setClipAxisRect(rects.first());
11965   }
11966 }
11967 
~QCPAbstractItem()11968 QCPAbstractItem::~QCPAbstractItem()
11969 {
11970   // don't delete mPositions because every position is also an anchor and thus in mAnchors
11971   qDeleteAll(mAnchors);
11972 }
11973 
11974 /* can't make this a header inline function, because QPointer breaks with forward declared types, see QTBUG-29588 */
clipAxisRect() const11975 QCPAxisRect *QCPAbstractItem::clipAxisRect() const
11976 {
11977   return mClipAxisRect.data();
11978 }
11979 
11980 /*!
11981   Sets whether the item shall be clipped to an axis rect or whether it shall be visible on the
11982   entire QCustomPlot. The axis rect can be set with \ref setClipAxisRect.
11983 
11984   \see setClipAxisRect
11985 */
setClipToAxisRect(bool clip)11986 void QCPAbstractItem::setClipToAxisRect(bool clip)
11987 {
11988   mClipToAxisRect = clip;
11989   if (mClipToAxisRect)
11990     setParentLayerable(mClipAxisRect.data());
11991 }
11992 
11993 /*!
11994   Sets the clip axis rect. It defines the rect that will be used to clip the item when \ref
11995   setClipToAxisRect is set to true.
11996 
11997   \see setClipToAxisRect
11998 */
setClipAxisRect(QCPAxisRect * rect)11999 void QCPAbstractItem::setClipAxisRect(QCPAxisRect *rect)
12000 {
12001   mClipAxisRect = rect;
12002   if (mClipToAxisRect)
12003     setParentLayerable(mClipAxisRect.data());
12004 }
12005 
12006 /*!
12007   Sets whether the user can (de-)select this item by clicking on the QCustomPlot surface.
12008   (When \ref QCustomPlot::setInteractions contains QCustomPlot::iSelectItems.)
12009 
12010   However, even when \a selectable was set to false, it is possible to set the selection manually,
12011   by calling \ref setSelected.
12012 
12013   \see QCustomPlot::setInteractions, setSelected
12014 */
setSelectable(bool selectable)12015 void QCPAbstractItem::setSelectable(bool selectable)
12016 {
12017   if (mSelectable != selectable)
12018   {
12019     mSelectable = selectable;
12020     emit selectableChanged(mSelectable);
12021   }
12022 }
12023 
12024 /*!
12025   Sets whether this item is selected or not. When selected, it might use a different visual
12026   appearance (e.g. pen and brush), this depends on the specific item though.
12027 
12028   The entire selection mechanism for items is handled automatically when \ref
12029   QCustomPlot::setInteractions contains QCustomPlot::iSelectItems. You only need to call this
12030   function when you wish to change the selection state manually.
12031 
12032   This function can change the selection state even when \ref setSelectable was set to false.
12033 
12034   emits the \ref selectionChanged signal when \a selected is different from the previous selection state.
12035 
12036   \see setSelectable, selectTest
12037 */
setSelected(bool selected)12038 void QCPAbstractItem::setSelected(bool selected)
12039 {
12040   if (mSelected != selected)
12041   {
12042     mSelected = selected;
12043     emit selectionChanged(mSelected);
12044   }
12045 }
12046 
12047 /*!
12048   Returns the QCPItemPosition with the specified \a name. If this item doesn't have a position by
12049   that name, returns 0.
12050 
12051   This function provides an alternative way to access item positions. Normally, you access
12052   positions direcly by their member pointers (which typically have the same variable name as \a
12053   name).
12054 
12055   \see positions, anchor
12056 */
position(const QString & name) const12057 QCPItemPosition *QCPAbstractItem::position(const QString &name) const
12058 {
12059   for (int i=0; i<mPositions.size(); ++i)
12060   {
12061     if (mPositions.at(i)->name() == name)
12062       return mPositions.at(i);
12063   }
12064   qDebug() << Q_FUNC_INFO << "position with name not found:" << name;
12065   return 0;
12066 }
12067 
12068 /*!
12069   Returns the QCPItemAnchor with the specified \a name. If this item doesn't have an anchor by
12070   that name, returns 0.
12071 
12072   This function provides an alternative way to access item anchors. Normally, you access
12073   anchors direcly by their member pointers (which typically have the same variable name as \a
12074   name).
12075 
12076   \see anchors, position
12077 */
anchor(const QString & name) const12078 QCPItemAnchor *QCPAbstractItem::anchor(const QString &name) const
12079 {
12080   for (int i=0; i<mAnchors.size(); ++i)
12081   {
12082     if (mAnchors.at(i)->name() == name)
12083       return mAnchors.at(i);
12084   }
12085   qDebug() << Q_FUNC_INFO << "anchor with name not found:" << name;
12086   return 0;
12087 }
12088 
12089 /*!
12090   Returns whether this item has an anchor with the specified \a name.
12091 
12092   Note that you can check for positions with this function, too. This is because every position is
12093   also an anchor (QCPItemPosition inherits from QCPItemAnchor).
12094 
12095   \see anchor, position
12096 */
hasAnchor(const QString & name) const12097 bool QCPAbstractItem::hasAnchor(const QString &name) const
12098 {
12099   for (int i=0; i<mAnchors.size(); ++i)
12100   {
12101     if (mAnchors.at(i)->name() == name)
12102       return true;
12103   }
12104   return false;
12105 }
12106 
12107 /*! \internal
12108 
12109   Returns the rect the visual representation of this item is clipped to. This depends on the
12110   current setting of \ref setClipToAxisRect as well as the axis rect set with \ref setClipAxisRect.
12111 
12112   If the item is not clipped to an axis rect, QCustomPlot's viewport rect is returned.
12113 
12114   \see draw
12115 */
clipRect() const12116 QRect QCPAbstractItem::clipRect() const
12117 {
12118   if (mClipToAxisRect && mClipAxisRect)
12119     return mClipAxisRect.data()->rect();
12120   else
12121     return mParentPlot->viewport();
12122 }
12123 
12124 /*! \internal
12125 
12126   A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
12127   before drawing item lines.
12128 
12129   This is the antialiasing state the painter passed to the \ref draw method is in by default.
12130 
12131   This function takes into account the local setting of the antialiasing flag as well as the
12132   overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
12133   QCustomPlot::setNotAntialiasedElements.
12134 
12135   \see setAntialiased
12136 */
applyDefaultAntialiasingHint(QCPPainter * painter) const12137 void QCPAbstractItem::applyDefaultAntialiasingHint(QCPPainter *painter) const
12138 {
12139   applyAntialiasingHint(painter, mAntialiased, QCP::aeItems);
12140 }
12141 
12142 /*! \internal
12143 
12144   A convenience function which returns the selectTest value for a specified \a rect and a specified
12145   click position \a pos. \a filledRect defines whether a click inside the rect should also be
12146   considered a hit or whether only the rect border is sensitive to hits.
12147 
12148   This function may be used to help with the implementation of the \ref selectTest function for
12149   specific items.
12150 
12151   For example, if your item consists of four rects, call this function four times, once for each
12152   rect, in your \ref selectTest reimplementation. Finally, return the minimum (non -1) of all four
12153   returned values.
12154 */
rectDistance(const QRectF & rect,const QPointF & pos,bool filledRect) const12155 double QCPAbstractItem::rectDistance(const QRectF &rect, const QPointF &pos, bool filledRect) const
12156 {
12157   double result = -1;
12158 
12159   // distance to border:
12160   QList<QLineF> lines;
12161   lines << QLineF(rect.topLeft(), rect.topRight()) << QLineF(rect.bottomLeft(), rect.bottomRight())
12162         << QLineF(rect.topLeft(), rect.bottomLeft()) << QLineF(rect.topRight(), rect.bottomRight());
12163   double minDistSqr = std::numeric_limits<double>::max();
12164   for (int i=0; i<lines.size(); ++i)
12165   {
12166     double distSqr = QCPVector2D(pos).distanceSquaredToLine(lines.at(i).p1(), lines.at(i).p2());
12167     if (distSqr < minDistSqr)
12168       minDistSqr = distSqr;
12169   }
12170   result = qSqrt(minDistSqr);
12171 
12172   // filled rect, allow click inside to count as hit:
12173   if (filledRect && result > mParentPlot->selectionTolerance()*0.99)
12174   {
12175     if (rect.contains(pos))
12176       result = mParentPlot->selectionTolerance()*0.99;
12177   }
12178   return result;
12179 }
12180 
12181 /*! \internal
12182 
12183   Returns the pixel position of the anchor with Id \a anchorId. This function must be reimplemented in
12184   item subclasses if they want to provide anchors (QCPItemAnchor).
12185 
12186   For example, if the item has two anchors with id 0 and 1, this function takes one of these anchor
12187   ids and returns the respective pixel points of the specified anchor.
12188 
12189   \see createAnchor
12190 */
anchorPixelPosition(int anchorId) const12191 QPointF QCPAbstractItem::anchorPixelPosition(int anchorId) const
12192 {
12193   qDebug() << Q_FUNC_INFO << "called on item which shouldn't have any anchors (this method not reimplemented). anchorId" << anchorId;
12194   return QPointF();
12195 }
12196 
12197 /*! \internal
12198 
12199   Creates a QCPItemPosition, registers it with this item and returns a pointer to it. The specified
12200   \a name must be a unique string that is usually identical to the variable name of the position
12201   member (This is needed to provide the name-based \ref position access to positions).
12202 
12203   Don't delete positions created by this function manually, as the item will take care of it.
12204 
12205   Use this function in the constructor (initialization list) of the specific item subclass to
12206   create each position member. Don't create QCPItemPositions with \b new yourself, because they
12207   won't be registered with the item properly.
12208 
12209   \see createAnchor
12210 */
createPosition(const QString & name)12211 QCPItemPosition *QCPAbstractItem::createPosition(const QString &name)
12212 {
12213   if (hasAnchor(name))
12214     qDebug() << Q_FUNC_INFO << "anchor/position with name exists already:" << name;
12215   QCPItemPosition *newPosition = new QCPItemPosition(mParentPlot, this, name);
12216   mPositions.append(newPosition);
12217   mAnchors.append(newPosition); // every position is also an anchor
12218   newPosition->setAxes(mParentPlot->xAxis, mParentPlot->yAxis);
12219   newPosition->setType(QCPItemPosition::ptPlotCoords);
12220   if (mParentPlot->axisRect())
12221     newPosition->setAxisRect(mParentPlot->axisRect());
12222   newPosition->setCoords(0, 0);
12223   return newPosition;
12224 }
12225 
12226 /*! \internal
12227 
12228   Creates a QCPItemAnchor, registers it with this item and returns a pointer to it. The specified
12229   \a name must be a unique string that is usually identical to the variable name of the anchor
12230   member (This is needed to provide the name based \ref anchor access to anchors).
12231 
12232   The \a anchorId must be a number identifying the created anchor. It is recommended to create an
12233   enum (e.g. "AnchorIndex") for this on each item that uses anchors. This id is used by the anchor
12234   to identify itself when it calls QCPAbstractItem::anchorPixelPosition. That function then returns
12235   the correct pixel coordinates for the passed anchor id.
12236 
12237   Don't delete anchors created by this function manually, as the item will take care of it.
12238 
12239   Use this function in the constructor (initialization list) of the specific item subclass to
12240   create each anchor member. Don't create QCPItemAnchors with \b new yourself, because then they
12241   won't be registered with the item properly.
12242 
12243   \see createPosition
12244 */
createAnchor(const QString & name,int anchorId)12245 QCPItemAnchor *QCPAbstractItem::createAnchor(const QString &name, int anchorId)
12246 {
12247   if (hasAnchor(name))
12248     qDebug() << Q_FUNC_INFO << "anchor/position with name exists already:" << name;
12249   QCPItemAnchor *newAnchor = new QCPItemAnchor(mParentPlot, this, name, anchorId);
12250   mAnchors.append(newAnchor);
12251   return newAnchor;
12252 }
12253 
12254 /* inherits documentation from base class */
selectEvent(QMouseEvent * event,bool additive,const QVariant & details,bool * selectionStateChanged)12255 void QCPAbstractItem::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
12256 {
12257   Q_UNUSED(event)
12258   Q_UNUSED(details)
12259   if (mSelectable)
12260   {
12261     bool selBefore = mSelected;
12262     setSelected(additive ? !mSelected : true);
12263     if (selectionStateChanged)
12264       *selectionStateChanged = mSelected != selBefore;
12265   }
12266 }
12267 
12268 /* inherits documentation from base class */
deselectEvent(bool * selectionStateChanged)12269 void QCPAbstractItem::deselectEvent(bool *selectionStateChanged)
12270 {
12271   if (mSelectable)
12272   {
12273     bool selBefore = mSelected;
12274     setSelected(false);
12275     if (selectionStateChanged)
12276       *selectionStateChanged = mSelected != selBefore;
12277   }
12278 }
12279 
12280 /* inherits documentation from base class */
selectionCategory() const12281 QCP::Interaction QCPAbstractItem::selectionCategory() const
12282 {
12283   return QCP::iSelectItems;
12284 }
12285 /* end of 'src/item.cpp' */
12286 
12287 
12288 /* including file 'src/core.cpp', size 124243                                */
12289 /* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
12290 
12291 ////////////////////////////////////////////////////////////////////////////////////////////////////
12292 //////////////////// QCustomPlot
12293 ////////////////////////////////////////////////////////////////////////////////////////////////////
12294 
12295 /*! \class QCustomPlot
12296 
12297   \brief The central class of the library. This is the QWidget which displays the plot and
12298   interacts with the user.
12299 
12300   For tutorials on how to use QCustomPlot, see the website\n
12301   http://www.qcustomplot.com/
12302 */
12303 
12304 /* start of documentation of inline functions */
12305 
12306 /*! \fn QCPSelectionRect *QCustomPlot::selectionRect() const
12307 
12308   Allows access to the currently used QCPSelectionRect instance (or subclass thereof), that is used
12309   to handle and draw selection rect interactions (see \ref setSelectionRectMode).
12310 
12311   \see setSelectionRect
12312 */
12313 
12314 /*! \fn QCPLayoutGrid *QCustomPlot::plotLayout() const
12315 
12316   Returns the top level layout of this QCustomPlot instance. It is a \ref QCPLayoutGrid, initially containing just
12317   one cell with the main QCPAxisRect inside.
12318 */
12319 
12320 /* end of documentation of inline functions */
12321 /* start of documentation of signals */
12322 
12323 /*! \fn void QCustomPlot::mouseDoubleClick(QMouseEvent *event)
12324 
12325   This signal is emitted when the QCustomPlot receives a mouse double click event.
12326 */
12327 
12328 /*! \fn void QCustomPlot::mousePress(QMouseEvent *event)
12329 
12330   This signal is emitted when the QCustomPlot receives a mouse press event.
12331 
12332   It is emitted before QCustomPlot handles any other mechanism like range dragging. So a slot
12333   connected to this signal can still influence the behaviour e.g. with \ref QCPAxisRect::setRangeDrag or \ref
12334   QCPAxisRect::setRangeDragAxes.
12335 */
12336 
12337 /*! \fn void QCustomPlot::mouseMove(QMouseEvent *event)
12338 
12339   This signal is emitted when the QCustomPlot receives a mouse move event.
12340 
12341   It is emitted before QCustomPlot handles any other mechanism like range dragging. So a slot
12342   connected to this signal can still influence the behaviour e.g. with \ref QCPAxisRect::setRangeDrag or \ref
12343   QCPAxisRect::setRangeDragAxes.
12344 
12345   \warning It is discouraged to change the drag-axes with \ref QCPAxisRect::setRangeDragAxes here,
12346   because the dragging starting point was saved the moment the mouse was pressed. Thus it only has
12347   a meaning for the range drag axes that were set at that moment. If you want to change the drag
12348   axes, consider doing this in the \ref mousePress signal instead.
12349 */
12350 
12351 /*! \fn void QCustomPlot::mouseRelease(QMouseEvent *event)
12352 
12353   This signal is emitted when the QCustomPlot receives a mouse release event.
12354 
12355   It is emitted before QCustomPlot handles any other mechanisms like object selection. So a
12356   slot connected to this signal can still influence the behaviour e.g. with \ref setInteractions or
12357   \ref QCPAbstractPlottable::setSelectable.
12358 */
12359 
12360 /*! \fn void QCustomPlot::mouseWheel(QMouseEvent *event)
12361 
12362   This signal is emitted when the QCustomPlot receives a mouse wheel event.
12363 
12364   It is emitted before QCustomPlot handles any other mechanisms like range zooming. So a slot
12365   connected to this signal can still influence the behaviour e.g. with \ref QCPAxisRect::setRangeZoom, \ref
12366   QCPAxisRect::setRangeZoomAxes or \ref QCPAxisRect::setRangeZoomFactor.
12367 */
12368 
12369 /*! \fn void QCustomPlot::plottableClick(QCPAbstractPlottable *plottable, int dataIndex, QMouseEvent *event)
12370 
12371   This signal is emitted when a plottable is clicked.
12372 
12373   \a event is the mouse event that caused the click and \a plottable is the plottable that received
12374   the click. The parameter \a dataIndex indicates the data point that was closest to the click
12375   position.
12376 
12377   \see plottableDoubleClick
12378 */
12379 
12380 /*! \fn void QCustomPlot::plottableDoubleClick(QCPAbstractPlottable *plottable, int dataIndex, QMouseEvent *event)
12381 
12382   This signal is emitted when a plottable is double clicked.
12383 
12384   \a event is the mouse event that caused the click and \a plottable is the plottable that received
12385   the click. The parameter \a dataIndex indicates the data point that was closest to the click
12386   position.
12387 
12388   \see plottableClick
12389 */
12390 
12391 /*! \fn void QCustomPlot::itemClick(QCPAbstractItem *item, QMouseEvent *event)
12392 
12393   This signal is emitted when an item is clicked.
12394 
12395   \a event is the mouse event that caused the click and \a item is the item that received the
12396   click.
12397 
12398   \see itemDoubleClick
12399 */
12400 
12401 /*! \fn void QCustomPlot::itemDoubleClick(QCPAbstractItem *item, QMouseEvent *event)
12402 
12403   This signal is emitted when an item is double clicked.
12404 
12405   \a event is the mouse event that caused the click and \a item is the item that received the
12406   click.
12407 
12408   \see itemClick
12409 */
12410 
12411 /*! \fn void QCustomPlot::axisClick(QCPAxis *axis, QCPAxis::SelectablePart part, QMouseEvent *event)
12412 
12413   This signal is emitted when an axis is clicked.
12414 
12415   \a event is the mouse event that caused the click, \a axis is the axis that received the click and
12416   \a part indicates the part of the axis that was clicked.
12417 
12418   \see axisDoubleClick
12419 */
12420 
12421 /*! \fn void QCustomPlot::axisDoubleClick(QCPAxis *axis, QCPAxis::SelectablePart part, QMouseEvent *event)
12422 
12423   This signal is emitted when an axis is double clicked.
12424 
12425   \a event is the mouse event that caused the click, \a axis is the axis that received the click and
12426   \a part indicates the part of the axis that was clicked.
12427 
12428   \see axisClick
12429 */
12430 
12431 /*! \fn void QCustomPlot::legendClick(QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event)
12432 
12433   This signal is emitted when a legend (item) is clicked.
12434 
12435   \a event is the mouse event that caused the click, \a legend is the legend that received the
12436   click and \a item is the legend item that received the click. If only the legend and no item is
12437   clicked, \a item is 0. This happens for a click inside the legend padding or the space between
12438   two items.
12439 
12440   \see legendDoubleClick
12441 */
12442 
12443 /*! \fn void QCustomPlot::legendDoubleClick(QCPLegend *legend,  QCPAbstractLegendItem *item, QMouseEvent *event)
12444 
12445   This signal is emitted when a legend (item) is double clicked.
12446 
12447   \a event is the mouse event that caused the click, \a legend is the legend that received the
12448   click and \a item is the legend item that received the click. If only the legend and no item is
12449   clicked, \a item is 0. This happens for a click inside the legend padding or the space between
12450   two items.
12451 
12452   \see legendClick
12453 */
12454 
12455 /*! \fn void QCustomPlot::selectionChangedByUser()
12456 
12457   This signal is emitted after the user has changed the selection in the QCustomPlot, e.g. by
12458   clicking. It is not emitted when the selection state of an object has changed programmatically by
12459   a direct call to <tt>setSelected()</tt>/<tt>setSelection()</tt> on an object or by calling \ref
12460   deselectAll.
12461 
12462   In addition to this signal, selectable objects also provide individual signals, for example \ref
12463   QCPAxis::selectionChanged or \ref QCPAbstractPlottable::selectionChanged. Note that those signals
12464   are emitted even if the selection state is changed programmatically.
12465 
12466   See the documentation of \ref setInteractions for details about the selection mechanism.
12467 
12468   \see selectedPlottables, selectedGraphs, selectedItems, selectedAxes, selectedLegends
12469 */
12470 
12471 /*! \fn void QCustomPlot::beforeReplot()
12472 
12473   This signal is emitted immediately before a replot takes place (caused by a call to the slot \ref
12474   replot).
12475 
12476   It is safe to mutually connect the replot slot with this signal on two QCustomPlots to make them
12477   replot synchronously, it won't cause an infinite recursion.
12478 
12479   \see replot, afterReplot
12480 */
12481 
12482 /*! \fn void QCustomPlot::afterReplot()
12483 
12484   This signal is emitted immediately after a replot has taken place (caused by a call to the slot \ref
12485   replot).
12486 
12487   It is safe to mutually connect the replot slot with this signal on two QCustomPlots to make them
12488   replot synchronously, it won't cause an infinite recursion.
12489 
12490   \see replot, beforeReplot
12491 */
12492 
12493 /* end of documentation of signals */
12494 /* start of documentation of public members */
12495 
12496 /*! \var QCPAxis *QCustomPlot::xAxis
12497 
12498   A pointer to the primary x Axis (bottom) of the main axis rect of the plot.
12499 
12500   QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref
12501   yAxis2) and the \ref legend. They make it very easy working with plots that only have a single
12502   axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the
12503   layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref
12504   QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the
12505   default legend is removed due to manipulation of the layout system (e.g. by removing the main
12506   axis rect), the corresponding pointers become 0.
12507 
12508   If an axis convenience pointer is currently zero and a new axis rect or a corresponding axis is
12509   added in the place of the main axis rect, QCustomPlot resets the convenience pointers to the
12510   according new axes. Similarly the \ref legend convenience pointer will be reset if a legend is
12511   added after the main legend was removed before.
12512 */
12513 
12514 /*! \var QCPAxis *QCustomPlot::yAxis
12515 
12516   A pointer to the primary y Axis (left) of the main axis rect of the plot.
12517 
12518   QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref
12519   yAxis2) and the \ref legend. They make it very easy working with plots that only have a single
12520   axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the
12521   layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref
12522   QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the
12523   default legend is removed due to manipulation of the layout system (e.g. by removing the main
12524   axis rect), the corresponding pointers become 0.
12525 
12526   If an axis convenience pointer is currently zero and a new axis rect or a corresponding axis is
12527   added in the place of the main axis rect, QCustomPlot resets the convenience pointers to the
12528   according new axes. Similarly the \ref legend convenience pointer will be reset if a legend is
12529   added after the main legend was removed before.
12530 */
12531 
12532 /*! \var QCPAxis *QCustomPlot::xAxis2
12533 
12534   A pointer to the secondary x Axis (top) of the main axis rect of the plot. Secondary axes are
12535   invisible by default. Use QCPAxis::setVisible to change this (or use \ref
12536   QCPAxisRect::setupFullAxesBox).
12537 
12538   QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref
12539   yAxis2) and the \ref legend. They make it very easy working with plots that only have a single
12540   axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the
12541   layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref
12542   QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the
12543   default legend is removed due to manipulation of the layout system (e.g. by removing the main
12544   axis rect), the corresponding pointers become 0.
12545 
12546   If an axis convenience pointer is currently zero and a new axis rect or a corresponding axis is
12547   added in the place of the main axis rect, QCustomPlot resets the convenience pointers to the
12548   according new axes. Similarly the \ref legend convenience pointer will be reset if a legend is
12549   added after the main legend was removed before.
12550 */
12551 
12552 /*! \var QCPAxis *QCustomPlot::yAxis2
12553 
12554   A pointer to the secondary y Axis (right) of the main axis rect of the plot. Secondary axes are
12555   invisible by default. Use QCPAxis::setVisible to change this (or use \ref
12556   QCPAxisRect::setupFullAxesBox).
12557 
12558   QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref
12559   yAxis2) and the \ref legend. They make it very easy working with plots that only have a single
12560   axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the
12561   layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref
12562   QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the
12563   default legend is removed due to manipulation of the layout system (e.g. by removing the main
12564   axis rect), the corresponding pointers become 0.
12565 
12566   If an axis convenience pointer is currently zero and a new axis rect or a corresponding axis is
12567   added in the place of the main axis rect, QCustomPlot resets the convenience pointers to the
12568   according new axes. Similarly the \ref legend convenience pointer will be reset if a legend is
12569   added after the main legend was removed before.
12570 */
12571 
12572 /*! \var QCPLegend *QCustomPlot::legend
12573 
12574   A pointer to the default legend of the main axis rect. The legend is invisible by default. Use
12575   QCPLegend::setVisible to change this.
12576 
12577   QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref
12578   yAxis2) and the \ref legend. They make it very easy working with plots that only have a single
12579   axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the
12580   layout system\endlink to add multiple legends to the plot, use the layout system interface to
12581   access the new legend. For example, legends can be placed inside an axis rect's \ref
12582   QCPAxisRect::insetLayout "inset layout", and must then also be accessed via the inset layout. If
12583   the default legend is removed due to manipulation of the layout system (e.g. by removing the main
12584   axis rect), the corresponding pointer becomes 0.
12585 
12586   If an axis convenience pointer is currently zero and a new axis rect or a corresponding axis is
12587   added in the place of the main axis rect, QCustomPlot resets the convenience pointers to the
12588   according new axes. Similarly the \ref legend convenience pointer will be reset if a legend is
12589   added after the main legend was removed before.
12590 */
12591 
12592 /* end of documentation of public members */
12593 
12594 /*!
12595   Constructs a QCustomPlot and sets reasonable default values.
12596 */
QCustomPlot(QWidget * parent)12597 QCustomPlot::QCustomPlot(QWidget *parent) :
12598   QWidget(parent),
12599   xAxis(0),
12600   yAxis(0),
12601   xAxis2(0),
12602   yAxis2(0),
12603   legend(0),
12604   mBufferDevicePixelRatio(1.0), // will be adapted to primary screen below
12605   mPlotLayout(0),
12606   mAutoAddPlottableToLegend(true),
12607 #if QT_VERSION < QT_VERSION_CHECK(5, 15, 0)
12608   mAntialiasedElements(QCP::aeNone),
12609   mNotAntialiasedElements(QCP::aeNone),
12610   mInteractions(0),
12611 #endif
12612   mSelectionTolerance(8),
12613   mNoAntialiasingOnDrag(false),
12614   mBackgroundBrush(Qt::white, Qt::SolidPattern),
12615   mBackgroundScaled(true),
12616   mBackgroundScaledMode(Qt::KeepAspectRatioByExpanding),
12617   mCurrentLayer(0),
12618   mPlottingHints(QCP::phCacheLabels|QCP::phImmediateRefresh),
12619   mMultiSelectModifier(Qt::ControlModifier),
12620   mSelectionRectMode(QCP::srmNone),
12621   mSelectionRect(0),
12622   mOpenGl(false),
12623   mMouseHasMoved(false),
12624   mMouseEventLayerable(0),
12625   mReplotting(false),
12626   mReplotQueued(false),
12627   mOpenGlMultisamples(16),
12628 #if QT_VERSION < QT_VERSION_CHECK(5, 15, 0)
12629   mOpenGlAntialiasedElementsBackup(QCP::aeNone),
12630 #endif
12631   mOpenGlCacheLabelsBackup(true)
12632 {
12633   setAttribute(Qt::WA_NoMousePropagation);
12634   setAttribute(Qt::WA_OpaquePaintEvent);
12635   setFocusPolicy(Qt::ClickFocus);
12636   setMouseTracking(true);
12637   QLocale currentLocale = locale();
12638   currentLocale.setNumberOptions(QLocale::OmitGroupSeparator);
12639   setLocale(currentLocale);
12640 #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
12641   setBufferDevicePixelRatio(QWidget::devicePixelRatio());
12642 #endif
12643 
12644   mOpenGlAntialiasedElementsBackup = mAntialiasedElements;
12645   mOpenGlCacheLabelsBackup = mPlottingHints.testFlag(QCP::phCacheLabels);
12646   // create initial layers:
12647   mLayers.append(new QCPLayer(this, QLatin1String("background")));
12648   mLayers.append(new QCPLayer(this, QLatin1String("grid")));
12649   mLayers.append(new QCPLayer(this, QLatin1String("main")));
12650   mLayers.append(new QCPLayer(this, QLatin1String("axes")));
12651   mLayers.append(new QCPLayer(this, QLatin1String("legend")));
12652   mLayers.append(new QCPLayer(this, QLatin1String("overlay")));
12653   updateLayerIndices();
12654   setCurrentLayer(QLatin1String("main"));
12655   layer(QLatin1String("overlay"))->setMode(QCPLayer::lmBuffered);
12656 
12657   // create initial layout, axis rect and legend:
12658   mPlotLayout = new QCPLayoutGrid;
12659   mPlotLayout->initializeParentPlot(this);
12660   mPlotLayout->setParent(this); // important because if parent is QWidget, QCPLayout::sizeConstraintsChanged will call QWidget::updateGeometry
12661   mPlotLayout->setLayer(QLatin1String("main"));
12662   QCPAxisRect *defaultAxisRect = new QCPAxisRect(this, true);
12663   mPlotLayout->addElement(0, 0, defaultAxisRect);
12664   xAxis = defaultAxisRect->axis(QCPAxis::atBottom);
12665   yAxis = defaultAxisRect->axis(QCPAxis::atLeft);
12666   xAxis2 = defaultAxisRect->axis(QCPAxis::atTop);
12667   yAxis2 = defaultAxisRect->axis(QCPAxis::atRight);
12668   legend = new QCPLegend;
12669   legend->setVisible(false);
12670   defaultAxisRect->insetLayout()->addElement(legend, Qt::AlignRight|Qt::AlignTop);
12671   defaultAxisRect->insetLayout()->setMargins(QMargins(12, 12, 12, 12));
12672 
12673   defaultAxisRect->setLayer(QLatin1String("background"));
12674   xAxis->setLayer(QLatin1String("axes"));
12675   yAxis->setLayer(QLatin1String("axes"));
12676   xAxis2->setLayer(QLatin1String("axes"));
12677   yAxis2->setLayer(QLatin1String("axes"));
12678   xAxis->grid()->setLayer(QLatin1String("grid"));
12679   yAxis->grid()->setLayer(QLatin1String("grid"));
12680   xAxis2->grid()->setLayer(QLatin1String("grid"));
12681   yAxis2->grid()->setLayer(QLatin1String("grid"));
12682   legend->setLayer(QLatin1String("legend"));
12683 
12684   // create selection rect instance:
12685   mSelectionRect = new QCPSelectionRect(this);
12686   mSelectionRect->setLayer(QLatin1String("overlay"));
12687 
12688   setViewport(rect()); // needs to be called after mPlotLayout has been created
12689 
12690   replot(rpQueuedReplot);
12691 }
12692 
~QCustomPlot()12693 QCustomPlot::~QCustomPlot()
12694 {
12695   clearPlottables();
12696   clearItems();
12697 
12698   if (mPlotLayout)
12699   {
12700     delete mPlotLayout;
12701     mPlotLayout = 0;
12702   }
12703 
12704   mCurrentLayer = 0;
12705   qDeleteAll(mLayers); // don't use removeLayer, because it would prevent the last layer to be removed
12706   mLayers.clear();
12707 }
12708 
12709 /*!
12710   Sets which elements are forcibly drawn antialiased as an \a or combination of QCP::AntialiasedElement.
12711 
12712   This overrides the antialiasing settings for whole element groups, normally controlled with the
12713   \a setAntialiasing function on the individual elements. If an element is neither specified in
12714   \ref setAntialiasedElements nor in \ref setNotAntialiasedElements, the antialiasing setting on
12715   each individual element instance is used.
12716 
12717   For example, if \a antialiasedElements contains \ref QCP::aePlottables, all plottables will be
12718   drawn antialiased, no matter what the specific QCPAbstractPlottable::setAntialiased value was set
12719   to.
12720 
12721   if an element in \a antialiasedElements is already set in \ref setNotAntialiasedElements, it is
12722   removed from there.
12723 
12724   \see setNotAntialiasedElements
12725 */
setAntialiasedElements(const QCP::AntialiasedElements & antialiasedElements)12726 void QCustomPlot::setAntialiasedElements(const QCP::AntialiasedElements &antialiasedElements)
12727 {
12728   mAntialiasedElements = antialiasedElements;
12729 
12730   // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously:
12731   if ((mNotAntialiasedElements & mAntialiasedElements) != 0)
12732     mNotAntialiasedElements |= ~mAntialiasedElements;
12733 }
12734 
12735 /*!
12736   Sets whether the specified \a antialiasedElement is forcibly drawn antialiased.
12737 
12738   See \ref setAntialiasedElements for details.
12739 
12740   \see setNotAntialiasedElement
12741 */
setAntialiasedElement(QCP::AntialiasedElement antialiasedElement,bool enabled)12742 void QCustomPlot::setAntialiasedElement(QCP::AntialiasedElement antialiasedElement, bool enabled)
12743 {
12744   if (!enabled && mAntialiasedElements.testFlag(antialiasedElement))
12745     mAntialiasedElements &= ~antialiasedElement;
12746   else if (enabled && !mAntialiasedElements.testFlag(antialiasedElement))
12747     mAntialiasedElements |= antialiasedElement;
12748 
12749   // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously:
12750   if ((mNotAntialiasedElements & mAntialiasedElements) != 0)
12751     mNotAntialiasedElements |= ~mAntialiasedElements;
12752 }
12753 
12754 /*!
12755   Sets which elements are forcibly drawn not antialiased as an \a or combination of
12756   QCP::AntialiasedElement.
12757 
12758   This overrides the antialiasing settings for whole element groups, normally controlled with the
12759   \a setAntialiasing function on the individual elements. If an element is neither specified in
12760   \ref setAntialiasedElements nor in \ref setNotAntialiasedElements, the antialiasing setting on
12761   each individual element instance is used.
12762 
12763   For example, if \a notAntialiasedElements contains \ref QCP::aePlottables, no plottables will be
12764   drawn antialiased, no matter what the specific QCPAbstractPlottable::setAntialiased value was set
12765   to.
12766 
12767   if an element in \a notAntialiasedElements is already set in \ref setAntialiasedElements, it is
12768   removed from there.
12769 
12770   \see setAntialiasedElements
12771 */
setNotAntialiasedElements(const QCP::AntialiasedElements & notAntialiasedElements)12772 void QCustomPlot::setNotAntialiasedElements(const QCP::AntialiasedElements &notAntialiasedElements)
12773 {
12774   mNotAntialiasedElements = notAntialiasedElements;
12775 
12776   // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously:
12777   if ((mNotAntialiasedElements & mAntialiasedElements) != 0)
12778     mAntialiasedElements |= ~mNotAntialiasedElements;
12779 }
12780 
12781 /*!
12782   Sets whether the specified \a notAntialiasedElement is forcibly drawn not antialiased.
12783 
12784   See \ref setNotAntialiasedElements for details.
12785 
12786   \see setAntialiasedElement
12787 */
setNotAntialiasedElement(QCP::AntialiasedElement notAntialiasedElement,bool enabled)12788 void QCustomPlot::setNotAntialiasedElement(QCP::AntialiasedElement notAntialiasedElement, bool enabled)
12789 {
12790   if (!enabled && mNotAntialiasedElements.testFlag(notAntialiasedElement))
12791     mNotAntialiasedElements &= ~notAntialiasedElement;
12792   else if (enabled && !mNotAntialiasedElements.testFlag(notAntialiasedElement))
12793     mNotAntialiasedElements |= notAntialiasedElement;
12794 
12795   // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously:
12796   if ((mNotAntialiasedElements & mAntialiasedElements) != 0)
12797     mAntialiasedElements |= ~mNotAntialiasedElements;
12798 }
12799 
12800 /*!
12801   If set to true, adding a plottable (e.g. a graph) to the QCustomPlot automatically also adds the
12802   plottable to the legend (QCustomPlot::legend).
12803 
12804   \see addGraph, QCPLegend::addItem
12805 */
setAutoAddPlottableToLegend(bool on)12806 void QCustomPlot::setAutoAddPlottableToLegend(bool on)
12807 {
12808   mAutoAddPlottableToLegend = on;
12809 }
12810 
12811 /*!
12812   Sets the possible interactions of this QCustomPlot as an or-combination of \ref QCP::Interaction
12813   enums. There are the following types of interactions:
12814 
12815   <b>Axis range manipulation</b> is controlled via \ref QCP::iRangeDrag and \ref QCP::iRangeZoom. When the
12816   respective interaction is enabled, the user may drag axes ranges and zoom with the mouse wheel.
12817   For details how to control which axes the user may drag/zoom and in what orientations, see \ref
12818   QCPAxisRect::setRangeDrag, \ref QCPAxisRect::setRangeZoom, \ref QCPAxisRect::setRangeDragAxes,
12819   \ref QCPAxisRect::setRangeZoomAxes.
12820 
12821   <b>Plottable data selection</b> is controlled by \ref QCP::iSelectPlottables. If \ref
12822   QCP::iSelectPlottables is set, the user may select plottables (graphs, curves, bars,...) and
12823   their data by clicking on them or in their vicinity (\ref setSelectionTolerance). Whether the
12824   user can actually select a plottable and its data can further be restricted with the \ref
12825   QCPAbstractPlottable::setSelectable method on the specific plottable. For details, see the
12826   special page about the \ref dataselection "data selection mechanism". To retrieve a list of all
12827   currently selected plottables, call \ref selectedPlottables. If you're only interested in
12828   QCPGraphs, you may use the convenience function \ref selectedGraphs.
12829 
12830   <b>Item selection</b> is controlled by \ref QCP::iSelectItems. If \ref QCP::iSelectItems is set, the user
12831   may select items (QCPItemLine, QCPItemText,...) by clicking on them or in their vicinity. To find
12832   out whether a specific item is selected, call QCPAbstractItem::selected(). To retrieve a list of
12833   all currently selected items, call \ref selectedItems.
12834 
12835   <b>Axis selection</b> is controlled with \ref QCP::iSelectAxes. If \ref QCP::iSelectAxes is set, the user
12836   may select parts of the axes by clicking on them. What parts exactly (e.g. Axis base line, tick
12837   labels, axis label) are selectable can be controlled via \ref QCPAxis::setSelectableParts for
12838   each axis. To retrieve a list of all axes that currently contain selected parts, call \ref
12839   selectedAxes. Which parts of an axis are selected, can be retrieved with QCPAxis::selectedParts().
12840 
12841   <b>Legend selection</b> is controlled with \ref QCP::iSelectLegend. If this is set, the user may
12842   select the legend itself or individual items by clicking on them. What parts exactly are
12843   selectable can be controlled via \ref QCPLegend::setSelectableParts. To find out whether the
12844   legend or any of its child items are selected, check the value of QCPLegend::selectedParts. To
12845   find out which child items are selected, call \ref QCPLegend::selectedItems.
12846 
12847   <b>All other selectable elements</b> The selection of all other selectable objects (e.g.
12848   QCPTextElement, or your own layerable subclasses) is controlled with \ref QCP::iSelectOther. If set, the
12849   user may select those objects by clicking on them. To find out which are currently selected, you
12850   need to check their selected state explicitly.
12851 
12852   If the selection state has changed by user interaction, the \ref selectionChangedByUser signal is
12853   emitted. Each selectable object additionally emits an individual selectionChanged signal whenever
12854   their selection state has changed, i.e. not only by user interaction.
12855 
12856   To allow multiple objects to be selected by holding the selection modifier (\ref
12857   setMultiSelectModifier), set the flag \ref QCP::iMultiSelect.
12858 
12859   \note In addition to the selection mechanism presented here, QCustomPlot always emits
12860   corresponding signals, when an object is clicked or double clicked. see \ref plottableClick and
12861   \ref plottableDoubleClick for example.
12862 
12863   \see setInteraction, setSelectionTolerance
12864 */
setInteractions(const QCP::Interactions & interactions)12865 void QCustomPlot::setInteractions(const QCP::Interactions &interactions)
12866 {
12867   mInteractions = interactions;
12868 }
12869 
12870 /*!
12871   Sets the single \a interaction of this QCustomPlot to \a enabled.
12872 
12873   For details about the interaction system, see \ref setInteractions.
12874 
12875   \see setInteractions
12876 */
setInteraction(const QCP::Interaction & interaction,bool enabled)12877 void QCustomPlot::setInteraction(const QCP::Interaction &interaction, bool enabled)
12878 {
12879   if (!enabled && mInteractions.testFlag(interaction))
12880     mInteractions &= ~interaction;
12881   else if (enabled && !mInteractions.testFlag(interaction))
12882     mInteractions |= interaction;
12883 }
12884 
12885 /*!
12886   Sets the tolerance that is used to decide whether a click selects an object (e.g. a plottable) or
12887   not.
12888 
12889   If the user clicks in the vicinity of the line of e.g. a QCPGraph, it's only regarded as a
12890   potential selection when the minimum distance between the click position and the graph line is
12891   smaller than \a pixels. Objects that are defined by an area (e.g. QCPBars) only react to clicks
12892   directly inside the area and ignore this selection tolerance. In other words, it only has meaning
12893   for parts of objects that are too thin to exactly hit with a click and thus need such a
12894   tolerance.
12895 
12896   \see setInteractions, QCPLayerable::selectTest
12897 */
setSelectionTolerance(int pixels)12898 void QCustomPlot::setSelectionTolerance(int pixels)
12899 {
12900   mSelectionTolerance = pixels;
12901 }
12902 
12903 /*!
12904   Sets whether antialiasing is disabled for this QCustomPlot while the user is dragging axes
12905   ranges. If many objects, especially plottables, are drawn antialiased, this greatly improves
12906   performance during dragging. Thus it creates a more responsive user experience. As soon as the
12907   user stops dragging, the last replot is done with normal antialiasing, to restore high image
12908   quality.
12909 
12910   \see setAntialiasedElements, setNotAntialiasedElements
12911 */
setNoAntialiasingOnDrag(bool enabled)12912 void QCustomPlot::setNoAntialiasingOnDrag(bool enabled)
12913 {
12914   mNoAntialiasingOnDrag = enabled;
12915 }
12916 
12917 /*!
12918   Sets the plotting hints for this QCustomPlot instance as an \a or combination of QCP::PlottingHint.
12919 
12920   \see setPlottingHint
12921 */
setPlottingHints(const QCP::PlottingHints & hints)12922 void QCustomPlot::setPlottingHints(const QCP::PlottingHints &hints)
12923 {
12924   mPlottingHints = hints;
12925 }
12926 
12927 /*!
12928   Sets the specified plotting \a hint to \a enabled.
12929 
12930   \see setPlottingHints
12931 */
setPlottingHint(QCP::PlottingHint hint,bool enabled)12932 void QCustomPlot::setPlottingHint(QCP::PlottingHint hint, bool enabled)
12933 {
12934   QCP::PlottingHints newHints = mPlottingHints;
12935   if (!enabled)
12936     newHints &= ~hint;
12937   else
12938     newHints |= hint;
12939 
12940   if (newHints != mPlottingHints)
12941     setPlottingHints(newHints);
12942 }
12943 
12944 /*!
12945   Sets the keyboard modifier that will be recognized as multi-select-modifier.
12946 
12947   If \ref QCP::iMultiSelect is specified in \ref setInteractions, the user may select multiple
12948   objects (or data points) by clicking on them one after the other while holding down \a modifier.
12949 
12950   By default the multi-select-modifier is set to Qt::ControlModifier.
12951 
12952   \see setInteractions
12953 */
setMultiSelectModifier(Qt::KeyboardModifier modifier)12954 void QCustomPlot::setMultiSelectModifier(Qt::KeyboardModifier modifier)
12955 {
12956   mMultiSelectModifier = modifier;
12957 }
12958 
12959 /*!
12960   Sets how QCustomPlot processes mouse click-and-drag interactions by the user.
12961 
12962   If \a mode is \ref QCP::srmNone, the mouse drag is forwarded to the underlying objects. For
12963   example, QCPAxisRect may process a mouse drag by dragging axis ranges, see \ref
12964   QCPAxisRect::setRangeDrag. If \a mode is not \ref QCP::srmNone, the current selection rect (\ref
12965   selectionRect) becomes activated and allows e.g. rect zooming and data point selection.
12966 
12967   If you wish to provide your user both with axis range dragging and data selection/range zooming,
12968   use this method to switch between the modes just before the interaction is processed, e.g. in
12969   reaction to the \ref mousePress or \ref mouseMove signals. For example you could check whether
12970   the user is holding a certain keyboard modifier, and then decide which \a mode shall be set.
12971 
12972   If a selection rect interaction is currently active, and \a mode is set to \ref QCP::srmNone, the
12973   interaction is canceled (\ref QCPSelectionRect::cancel). Switching between any of the other modes
12974   will keep the selection rect active. Upon completion of the interaction, the behaviour is as
12975   defined by the currently set \a mode, not the mode that was set when the interaction started.
12976 
12977   \see setInteractions, setSelectionRect, QCPSelectionRect
12978 */
setSelectionRectMode(QCP::SelectionRectMode mode)12979 void QCustomPlot::setSelectionRectMode(QCP::SelectionRectMode mode)
12980 {
12981   if (mSelectionRect)
12982   {
12983     if (mode == QCP::srmNone)
12984       mSelectionRect->cancel(); // when switching to none, we immediately want to abort a potentially active selection rect
12985 
12986     // disconnect old connections:
12987     if (mSelectionRectMode == QCP::srmSelect)
12988       disconnect(mSelectionRect, SIGNAL(accepted(QRect,QMouseEvent*)), this, SLOT(processRectSelection(QRect,QMouseEvent*)));
12989     else if (mSelectionRectMode == QCP::srmZoom)
12990       disconnect(mSelectionRect, SIGNAL(accepted(QRect,QMouseEvent*)), this, SLOT(processRectZoom(QRect,QMouseEvent*)));
12991 
12992     // establish new ones:
12993     if (mode == QCP::srmSelect)
12994       connect(mSelectionRect, SIGNAL(accepted(QRect,QMouseEvent*)), this, SLOT(processRectSelection(QRect,QMouseEvent*)));
12995     else if (mode == QCP::srmZoom)
12996       connect(mSelectionRect, SIGNAL(accepted(QRect,QMouseEvent*)), this, SLOT(processRectZoom(QRect,QMouseEvent*)));
12997   }
12998 
12999   mSelectionRectMode = mode;
13000 }
13001 
13002 /*!
13003   Sets the \ref QCPSelectionRect instance that QCustomPlot will use if \a mode is not \ref
13004   QCP::srmNone and the user performs a click-and-drag interaction. QCustomPlot takes ownership of
13005   the passed \a selectionRect. It can be accessed later via \ref selectionRect.
13006 
13007   This method is useful if you wish to replace the default QCPSelectionRect instance with an
13008   instance of a QCPSelectionRect subclass, to introduce custom behaviour of the selection rect.
13009 
13010   \see setSelectionRectMode
13011 */
setSelectionRect(QCPSelectionRect * selectionRect)13012 void QCustomPlot::setSelectionRect(QCPSelectionRect *selectionRect)
13013 {
13014   if (mSelectionRect)
13015     delete mSelectionRect;
13016 
13017   mSelectionRect = selectionRect;
13018 
13019   if (mSelectionRect)
13020   {
13021     // establish connections with new selection rect:
13022     if (mSelectionRectMode == QCP::srmSelect)
13023       connect(mSelectionRect, SIGNAL(accepted(QRect,QMouseEvent*)), this, SLOT(processRectSelection(QRect,QMouseEvent*)));
13024     else if (mSelectionRectMode == QCP::srmZoom)
13025       connect(mSelectionRect, SIGNAL(accepted(QRect,QMouseEvent*)), this, SLOT(processRectZoom(QRect,QMouseEvent*)));
13026   }
13027 }
13028 
13029 /*!
13030   This method allows to enable OpenGL plot rendering, for increased plotting performance of
13031   graphically demanding plots (thick lines, translucent fills, etc.).
13032 
13033   If \a enabled is set to true, QCustomPlot will try to initialize OpenGL and, if successful,
13034   continue plotting with hardware acceleration. The parameter \a multisampling controls how many
13035   samples will be used per pixel, it essentially controls the antialiasing quality. If \a
13036   multisampling is set too high for the current graphics hardware, the maximum allowed value will
13037   be used.
13038 
13039   You can test whether switching to OpenGL rendering was successful by checking whether the
13040   according getter \a QCustomPlot::openGl() returns true. If the OpenGL initialization fails,
13041   rendering continues with the regular software rasterizer, and an according qDebug output is
13042   generated.
13043 
13044   If switching to OpenGL was successful, this method disables label caching (\ref setPlottingHint
13045   "setPlottingHint(QCP::phCacheLabels, false)") and turns on QCustomPlot's antialiasing override
13046   for all elements (\ref setAntialiasedElements "setAntialiasedElements(QCP::aeAll)"), leading to a
13047   higher quality output. The antialiasing override allows for pixel-grid aligned drawing in the
13048   OpenGL paint device. As stated before, in OpenGL rendering the actual antialiasing of the plot is
13049   controlled with \a multisampling. If \a enabled is set to false, the antialiasing/label caching
13050   settings are restored to what they were before OpenGL was enabled, if they weren't altered in the
13051   meantime.
13052 
13053   \note OpenGL support is only enabled if QCustomPlot is compiled with the macro \c QCUSTOMPLOT_USE_OPENGL
13054   defined. This define must be set before including the QCustomPlot header both during compilation
13055   of the QCustomPlot library as well as when compiling your application. It is best to just include
13056   the line <tt>DEFINES += QCUSTOMPLOT_USE_OPENGL</tt> in the respective qmake project files.
13057   \note If you are using a Qt version before 5.0, you must also add the module "opengl" to your \c
13058   QT variable in the qmake project files. For Qt versions 5.0 and higher, QCustomPlot switches to a
13059   newer OpenGL interface which is already in the "gui" module.
13060 */
setOpenGl(bool enabled,int multisampling)13061 void QCustomPlot::setOpenGl(bool enabled, int multisampling)
13062 {
13063   mOpenGlMultisamples = qMax(0, multisampling);
13064 #ifdef QCUSTOMPLOT_USE_OPENGL
13065   mOpenGl = enabled;
13066   if (mOpenGl)
13067   {
13068     if (setupOpenGl())
13069     {
13070       // backup antialiasing override and labelcaching setting so we can restore upon disabling OpenGL
13071       mOpenGlAntialiasedElementsBackup = mAntialiasedElements;
13072       mOpenGlCacheLabelsBackup = mPlottingHints.testFlag(QCP::phCacheLabels);
13073       // set antialiasing override to antialias all (aligns gl pixel grid properly), and disable label caching (would use software rasterizer for pixmap caches):
13074       setAntialiasedElements(QCP::aeAll);
13075       setPlottingHint(QCP::phCacheLabels, false);
13076     } else
13077     {
13078       qDebug() << Q_FUNC_INFO << "Failed to enable OpenGL, continuing plotting without hardware acceleration.";
13079       mOpenGl = false;
13080     }
13081   } else
13082   {
13083     // restore antialiasing override and labelcaching to what it was before enabling OpenGL, if nobody changed it in the meantime:
13084     if (mAntialiasedElements == QCP::aeAll)
13085       setAntialiasedElements(mOpenGlAntialiasedElementsBackup);
13086     if (!mPlottingHints.testFlag(QCP::phCacheLabels))
13087       setPlottingHint(QCP::phCacheLabels, mOpenGlCacheLabelsBackup);
13088     freeOpenGl();
13089   }
13090   // recreate all paint buffers:
13091   mPaintBuffers.clear();
13092   setupPaintBuffers();
13093 #else
13094   Q_UNUSED(enabled)
13095   qDebug() << Q_FUNC_INFO << "QCustomPlot can't use OpenGL because QCUSTOMPLOT_USE_OPENGL was not defined during compilation (add 'DEFINES += QCUSTOMPLOT_USE_OPENGL' to your qmake .pro file)";
13096 #endif
13097 }
13098 
13099 /*!
13100   Sets the viewport of this QCustomPlot. Usually users of QCustomPlot don't need to change the
13101   viewport manually.
13102 
13103   The viewport is the area in which the plot is drawn. All mechanisms, e.g. margin caluclation take
13104   the viewport to be the outer border of the plot. The viewport normally is the rect() of the
13105   QCustomPlot widget, i.e. a rect with top left (0, 0) and size of the QCustomPlot widget.
13106 
13107   Don't confuse the viewport with the axis rect (QCustomPlot::axisRect). An axis rect is typically
13108   an area enclosed by four axes, where the graphs/plottables are drawn in. The viewport is larger
13109   and contains also the axes themselves, their tick numbers, their labels, or even additional axis
13110   rects, color scales and other layout elements.
13111 
13112   This function is used to allow arbitrary size exports with \ref toPixmap, \ref savePng, \ref
13113   savePdf, etc. by temporarily changing the viewport size.
13114 */
setViewport(const QRect & rect)13115 void QCustomPlot::setViewport(const QRect &rect)
13116 {
13117   mViewport = rect;
13118   if (mPlotLayout)
13119     mPlotLayout->setOuterRect(mViewport);
13120 }
13121 
13122 /*!
13123   Sets the device pixel ratio used by the paint buffers of this QCustomPlot instance.
13124 
13125   Normally, this doesn't need to be set manually, because it is initialized with the regular \a
13126   QWidget::devicePixelRatio which is configured by Qt to fit the display device (e.g. 1 for normal
13127   displays, 2 for High-DPI displays).
13128 
13129   Device pixel ratios are supported by Qt only for Qt versions since 5.4. If this method is called
13130   when QCustomPlot is being used with older Qt versions, outputs an according qDebug message and
13131   leaves the internal buffer device pixel ratio at 1.0.
13132 */
setBufferDevicePixelRatio(double ratio)13133 void QCustomPlot::setBufferDevicePixelRatio(double ratio)
13134 {
13135   if (!qFuzzyCompare(ratio, mBufferDevicePixelRatio))
13136   {
13137 #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
13138     mBufferDevicePixelRatio = ratio;
13139     for (int i=0; i<mPaintBuffers.size(); ++i)
13140       mPaintBuffers.at(i)->setDevicePixelRatio(mBufferDevicePixelRatio);
13141     // Note: axis label cache has devicePixelRatio as part of cache hash, so no need to manually clear cache here
13142 #else
13143     qDebug() << Q_FUNC_INFO << "Device pixel ratios not supported for Qt versions before 5.4";
13144     mBufferDevicePixelRatio = 1.0;
13145 #endif
13146   }
13147 }
13148 
13149 /*!
13150   Sets \a pm as the viewport background pixmap (see \ref setViewport). The pixmap is always drawn
13151   below all other objects in the plot.
13152 
13153   For cases where the provided pixmap doesn't have the same size as the viewport, scaling can be
13154   enabled with \ref setBackgroundScaled and the scaling mode (whether and how the aspect ratio is
13155   preserved) can be set with \ref setBackgroundScaledMode. To set all these options in one call,
13156   consider using the overloaded version of this function.
13157 
13158   If a background brush was set with \ref setBackground(const QBrush &brush), the viewport will
13159   first be filled with that brush, before drawing the background pixmap. This can be useful for
13160   background pixmaps with translucent areas.
13161 
13162   \see setBackgroundScaled, setBackgroundScaledMode
13163 */
setBackground(const QPixmap & pm)13164 void QCustomPlot::setBackground(const QPixmap &pm)
13165 {
13166   mBackgroundPixmap = pm;
13167   mScaledBackgroundPixmap = QPixmap();
13168 }
13169 
13170 /*!
13171   Sets the background brush of the viewport (see \ref setViewport).
13172 
13173   Before drawing everything else, the background is filled with \a brush. If a background pixmap
13174   was set with \ref setBackground(const QPixmap &pm), this brush will be used to fill the viewport
13175   before the background pixmap is drawn. This can be useful for background pixmaps with translucent
13176   areas.
13177 
13178   Set \a brush to Qt::NoBrush or Qt::Transparent to leave background transparent. This can be
13179   useful for exporting to image formats which support transparency, e.g. \ref savePng.
13180 
13181   \see setBackgroundScaled, setBackgroundScaledMode
13182 */
setBackground(const QBrush & brush)13183 void QCustomPlot::setBackground(const QBrush &brush)
13184 {
13185   mBackgroundBrush = brush;
13186 }
13187 
13188 /*! \overload
13189 
13190   Allows setting the background pixmap of the viewport, whether it shall be scaled and how it
13191   shall be scaled in one call.
13192 
13193   \see setBackground(const QPixmap &pm), setBackgroundScaled, setBackgroundScaledMode
13194 */
setBackground(const QPixmap & pm,bool scaled,Qt::AspectRatioMode mode)13195 void QCustomPlot::setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode)
13196 {
13197   mBackgroundPixmap = pm;
13198   mScaledBackgroundPixmap = QPixmap();
13199   mBackgroundScaled = scaled;
13200   mBackgroundScaledMode = mode;
13201 }
13202 
13203 /*!
13204   Sets whether the viewport background pixmap shall be scaled to fit the viewport. If \a scaled is
13205   set to true, control whether and how the aspect ratio of the original pixmap is preserved with
13206   \ref setBackgroundScaledMode.
13207 
13208   Note that the scaled version of the original pixmap is buffered, so there is no performance
13209   penalty on replots. (Except when the viewport dimensions are changed continuously.)
13210 
13211   \see setBackground, setBackgroundScaledMode
13212 */
setBackgroundScaled(bool scaled)13213 void QCustomPlot::setBackgroundScaled(bool scaled)
13214 {
13215   mBackgroundScaled = scaled;
13216 }
13217 
13218 /*!
13219   If scaling of the viewport background pixmap is enabled (\ref setBackgroundScaled), use this
13220   function to define whether and how the aspect ratio of the original pixmap is preserved.
13221 
13222   \see setBackground, setBackgroundScaled
13223 */
setBackgroundScaledMode(Qt::AspectRatioMode mode)13224 void QCustomPlot::setBackgroundScaledMode(Qt::AspectRatioMode mode)
13225 {
13226   mBackgroundScaledMode = mode;
13227 }
13228 
13229 /*!
13230   Returns the plottable with \a index. If the index is invalid, returns 0.
13231 
13232   There is an overloaded version of this function with no parameter which returns the last added
13233   plottable, see QCustomPlot::plottable()
13234 
13235   \see plottableCount
13236 */
plottable(int index)13237 QCPAbstractPlottable *QCustomPlot::plottable(int index)
13238 {
13239   if (index >= 0 && index < mPlottables.size())
13240   {
13241     return mPlottables.at(index);
13242   } else
13243   {
13244     qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
13245     return 0;
13246   }
13247 }
13248 
13249 /*! \overload
13250 
13251   Returns the last plottable that was added to the plot. If there are no plottables in the plot,
13252   returns 0.
13253 
13254   \see plottableCount
13255 */
plottable()13256 QCPAbstractPlottable *QCustomPlot::plottable()
13257 {
13258   if (!mPlottables.isEmpty())
13259   {
13260     return mPlottables.last();
13261   } else
13262     return 0;
13263 }
13264 
13265 /*!
13266   Removes the specified plottable from the plot and deletes it. If necessary, the corresponding
13267   legend item is also removed from the default legend (QCustomPlot::legend).
13268 
13269   Returns true on success.
13270 
13271   \see clearPlottables
13272 */
removePlottable(QCPAbstractPlottable * plottable)13273 bool QCustomPlot::removePlottable(QCPAbstractPlottable *plottable)
13274 {
13275   if (!mPlottables.contains(plottable))
13276   {
13277     qDebug() << Q_FUNC_INFO << "plottable not in list:" << reinterpret_cast<quintptr>(plottable);
13278     return false;
13279   }
13280 
13281   // remove plottable from legend:
13282   plottable->removeFromLegend();
13283   // special handling for QCPGraphs to maintain the simple graph interface:
13284   if (QCPGraph *graph = qobject_cast<QCPGraph*>(plottable))
13285     mGraphs.removeOne(graph);
13286   // remove plottable:
13287   delete plottable;
13288   mPlottables.removeOne(plottable);
13289   return true;
13290 }
13291 
13292 /*! \overload
13293 
13294   Removes and deletes the plottable by its \a index.
13295 */
removePlottable(int index)13296 bool QCustomPlot::removePlottable(int index)
13297 {
13298   if (index >= 0 && index < mPlottables.size())
13299     return removePlottable(mPlottables[index]);
13300   else
13301   {
13302     qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
13303     return false;
13304   }
13305 }
13306 
13307 /*!
13308   Removes all plottables from the plot and deletes them. Corresponding legend items are also
13309   removed from the default legend (QCustomPlot::legend).
13310 
13311   Returns the number of plottables removed.
13312 
13313   \see removePlottable
13314 */
clearPlottables()13315 int QCustomPlot::clearPlottables()
13316 {
13317   int c = mPlottables.size();
13318   for (int i=c-1; i >= 0; --i)
13319     removePlottable(mPlottables[i]);
13320   return c;
13321 }
13322 
13323 /*!
13324   Returns the number of currently existing plottables in the plot
13325 
13326   \see plottable
13327 */
plottableCount() const13328 int QCustomPlot::plottableCount() const
13329 {
13330   return mPlottables.size();
13331 }
13332 
13333 /*!
13334   Returns a list of the selected plottables. If no plottables are currently selected, the list is empty.
13335 
13336   There is a convenience function if you're only interested in selected graphs, see \ref selectedGraphs.
13337 
13338   \see setInteractions, QCPAbstractPlottable::setSelectable, QCPAbstractPlottable::setSelection
13339 */
selectedPlottables() const13340 QList<QCPAbstractPlottable*> QCustomPlot::selectedPlottables() const
13341 {
13342   QList<QCPAbstractPlottable*> result;
13343   foreach (QCPAbstractPlottable *plottable, mPlottables)
13344   {
13345     if (plottable->selected())
13346       result.append(plottable);
13347   }
13348   return result;
13349 }
13350 
13351 /*!
13352   Returns the plottable at the pixel position \a pos. Plottables that only consist of single lines
13353   (like graphs) have a tolerance band around them, see \ref setSelectionTolerance. If multiple
13354   plottables come into consideration, the one closest to \a pos is returned.
13355 
13356   If \a onlySelectable is true, only plottables that are selectable
13357   (QCPAbstractPlottable::setSelectable) are considered.
13358 
13359   If there is no plottable at \a pos, the return value is 0.
13360 
13361   \see itemAt, layoutElementAt
13362 */
plottableAt(const QPointF & pos,bool onlySelectable) const13363 QCPAbstractPlottable *QCustomPlot::plottableAt(const QPointF &pos, bool onlySelectable) const
13364 {
13365   QCPAbstractPlottable *resultPlottable = 0;
13366   double resultDistance = mSelectionTolerance; // only regard clicks with distances smaller than mSelectionTolerance as selections, so initialize with that value
13367 
13368   foreach (QCPAbstractPlottable *plottable, mPlottables)
13369   {
13370     if (onlySelectable && !plottable->selectable()) // we could have also passed onlySelectable to the selectTest function, but checking here is faster, because we have access to QCPabstractPlottable::selectable
13371       continue;
13372     if ((plottable->keyAxis()->axisRect()->rect() & plottable->valueAxis()->axisRect()->rect()).contains(pos.toPoint())) // only consider clicks inside the rect that is spanned by the plottable's key/value axes
13373     {
13374       double currentDistance = plottable->selectTest(pos, false);
13375       if (currentDistance >= 0 && currentDistance < resultDistance)
13376       {
13377         resultPlottable = plottable;
13378         resultDistance = currentDistance;
13379       }
13380     }
13381   }
13382 
13383   return resultPlottable;
13384 }
13385 
13386 /*!
13387   Returns whether this QCustomPlot instance contains the \a plottable.
13388 */
hasPlottable(QCPAbstractPlottable * plottable) const13389 bool QCustomPlot::hasPlottable(QCPAbstractPlottable *plottable) const
13390 {
13391   return mPlottables.contains(plottable);
13392 }
13393 
13394 /*!
13395   Returns the graph with \a index. If the index is invalid, returns 0.
13396 
13397   There is an overloaded version of this function with no parameter which returns the last created
13398   graph, see QCustomPlot::graph()
13399 
13400   \see graphCount, addGraph
13401 */
graph(int index) const13402 QCPGraph *QCustomPlot::graph(int index) const
13403 {
13404   if (index >= 0 && index < mGraphs.size())
13405   {
13406     return mGraphs.at(index);
13407   } else
13408   {
13409     qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
13410     return 0;
13411   }
13412 }
13413 
13414 /*! \overload
13415 
13416   Returns the last graph, that was created with \ref addGraph. If there are no graphs in the plot,
13417   returns 0.
13418 
13419   \see graphCount, addGraph
13420 */
graph() const13421 QCPGraph *QCustomPlot::graph() const
13422 {
13423   if (!mGraphs.isEmpty())
13424   {
13425     return mGraphs.last();
13426   } else
13427     return 0;
13428 }
13429 
13430 /*!
13431   Creates a new graph inside the plot. If \a keyAxis and \a valueAxis are left unspecified (0), the
13432   bottom (xAxis) is used as key and the left (yAxis) is used as value axis. If specified, \a
13433   keyAxis and \a valueAxis must reside in this QCustomPlot.
13434 
13435   \a keyAxis will be used as key axis (typically "x") and \a valueAxis as value axis (typically
13436   "y") for the graph.
13437 
13438   Returns a pointer to the newly created graph, or 0 if adding the graph failed.
13439 
13440   \see graph, graphCount, removeGraph, clearGraphs
13441 */
addGraph(QCPAxis * keyAxis,QCPAxis * valueAxis)13442 QCPGraph *QCustomPlot::addGraph(QCPAxis *keyAxis, QCPAxis *valueAxis)
13443 {
13444   if (!keyAxis) keyAxis = xAxis;
13445   if (!valueAxis) valueAxis = yAxis;
13446   if (!keyAxis || !valueAxis)
13447   {
13448     qDebug() << Q_FUNC_INFO << "can't use default QCustomPlot xAxis or yAxis, because at least one is invalid (has been deleted)";
13449     return 0;
13450   }
13451   if (keyAxis->parentPlot() != this || valueAxis->parentPlot() != this)
13452   {
13453     qDebug() << Q_FUNC_INFO << "passed keyAxis or valueAxis doesn't have this QCustomPlot as parent";
13454     return 0;
13455   }
13456 
13457   QCPGraph *newGraph = new QCPGraph(keyAxis, valueAxis);
13458   newGraph->setName(QLatin1String("Graph ")+QString::number(mGraphs.size()));
13459   return newGraph;
13460 }
13461 
13462 /*!
13463   Removes the specified \a graph from the plot and deletes it. If necessary, the corresponding
13464   legend item is also removed from the default legend (QCustomPlot::legend). If any other graphs in
13465   the plot have a channel fill set towards the removed graph, the channel fill property of those
13466   graphs is reset to zero (no channel fill).
13467 
13468   Returns true on success.
13469 
13470   \see clearGraphs
13471 */
removeGraph(QCPGraph * graph)13472 bool QCustomPlot::removeGraph(QCPGraph *graph)
13473 {
13474   return removePlottable(graph);
13475 }
13476 
13477 /*! \overload
13478 
13479   Removes and deletes the graph by its \a index.
13480 */
removeGraph(int index)13481 bool QCustomPlot::removeGraph(int index)
13482 {
13483   if (index >= 0 && index < mGraphs.size())
13484     return removeGraph(mGraphs[index]);
13485   else
13486     return false;
13487 }
13488 
13489 /*!
13490   Removes all graphs from the plot and deletes them. Corresponding legend items are also removed
13491   from the default legend (QCustomPlot::legend).
13492 
13493   Returns the number of graphs removed.
13494 
13495   \see removeGraph
13496 */
clearGraphs()13497 int QCustomPlot::clearGraphs()
13498 {
13499   int c = mGraphs.size();
13500   for (int i=c-1; i >= 0; --i)
13501     removeGraph(mGraphs[i]);
13502   return c;
13503 }
13504 
13505 /*!
13506   Returns the number of currently existing graphs in the plot
13507 
13508   \see graph, addGraph
13509 */
graphCount() const13510 int QCustomPlot::graphCount() const
13511 {
13512   return mGraphs.size();
13513 }
13514 
13515 /*!
13516   Returns a list of the selected graphs. If no graphs are currently selected, the list is empty.
13517 
13518   If you are not only interested in selected graphs but other plottables like QCPCurve, QCPBars,
13519   etc., use \ref selectedPlottables.
13520 
13521   \see setInteractions, selectedPlottables, QCPAbstractPlottable::setSelectable, QCPAbstractPlottable::setSelection
13522 */
selectedGraphs() const13523 QList<QCPGraph*> QCustomPlot::selectedGraphs() const
13524 {
13525   QList<QCPGraph*> result;
13526   foreach (QCPGraph *graph, mGraphs)
13527   {
13528     if (graph->selected())
13529       result.append(graph);
13530   }
13531   return result;
13532 }
13533 
13534 /*!
13535   Returns the item with \a index. If the index is invalid, returns 0.
13536 
13537   There is an overloaded version of this function with no parameter which returns the last added
13538   item, see QCustomPlot::item()
13539 
13540   \see itemCount
13541 */
item(int index) const13542 QCPAbstractItem *QCustomPlot::item(int index) const
13543 {
13544   if (index >= 0 && index < mItems.size())
13545   {
13546     return mItems.at(index);
13547   } else
13548   {
13549     qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
13550     return 0;
13551   }
13552 }
13553 
13554 /*! \overload
13555 
13556   Returns the last item that was added to this plot. If there are no items in the plot,
13557   returns 0.
13558 
13559   \see itemCount
13560 */
item() const13561 QCPAbstractItem *QCustomPlot::item() const
13562 {
13563   if (!mItems.isEmpty())
13564   {
13565     return mItems.last();
13566   } else
13567     return 0;
13568 }
13569 
13570 /*!
13571   Removes the specified item from the plot and deletes it.
13572 
13573   Returns true on success.
13574 
13575   \see clearItems
13576 */
removeItem(QCPAbstractItem * item)13577 bool QCustomPlot::removeItem(QCPAbstractItem *item)
13578 {
13579   if (mItems.contains(item))
13580   {
13581     delete item;
13582     mItems.removeOne(item);
13583     return true;
13584   } else
13585   {
13586     qDebug() << Q_FUNC_INFO << "item not in list:" << reinterpret_cast<quintptr>(item);
13587     return false;
13588   }
13589 }
13590 
13591 /*! \overload
13592 
13593   Removes and deletes the item by its \a index.
13594 */
removeItem(int index)13595 bool QCustomPlot::removeItem(int index)
13596 {
13597   if (index >= 0 && index < mItems.size())
13598     return removeItem(mItems[index]);
13599   else
13600   {
13601     qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
13602     return false;
13603   }
13604 }
13605 
13606 /*!
13607   Removes all items from the plot and deletes them.
13608 
13609   Returns the number of items removed.
13610 
13611   \see removeItem
13612 */
clearItems()13613 int QCustomPlot::clearItems()
13614 {
13615   int c = mItems.size();
13616   for (int i=c-1; i >= 0; --i)
13617     removeItem(mItems[i]);
13618   return c;
13619 }
13620 
13621 /*!
13622   Returns the number of currently existing items in the plot
13623 
13624   \see item
13625 */
itemCount() const13626 int QCustomPlot::itemCount() const
13627 {
13628   return mItems.size();
13629 }
13630 
13631 /*!
13632   Returns a list of the selected items. If no items are currently selected, the list is empty.
13633 
13634   \see setInteractions, QCPAbstractItem::setSelectable, QCPAbstractItem::setSelected
13635 */
selectedItems() const13636 QList<QCPAbstractItem*> QCustomPlot::selectedItems() const
13637 {
13638   QList<QCPAbstractItem*> result;
13639   foreach (QCPAbstractItem *item, mItems)
13640   {
13641     if (item->selected())
13642       result.append(item);
13643   }
13644   return result;
13645 }
13646 
13647 /*!
13648   Returns the item at the pixel position \a pos. Items that only consist of single lines (e.g. \ref
13649   QCPItemLine or \ref QCPItemCurve) have a tolerance band around them, see \ref
13650   setSelectionTolerance. If multiple items come into consideration, the one closest to \a pos is
13651   returned.
13652 
13653   If \a onlySelectable is true, only items that are selectable (QCPAbstractItem::setSelectable) are
13654   considered.
13655 
13656   If there is no item at \a pos, the return value is 0.
13657 
13658   \see plottableAt, layoutElementAt
13659 */
itemAt(const QPointF & pos,bool onlySelectable) const13660 QCPAbstractItem *QCustomPlot::itemAt(const QPointF &pos, bool onlySelectable) const
13661 {
13662   QCPAbstractItem *resultItem = 0;
13663   double resultDistance = mSelectionTolerance; // only regard clicks with distances smaller than mSelectionTolerance as selections, so initialize with that value
13664 
13665   foreach (QCPAbstractItem *item, mItems)
13666   {
13667     if (onlySelectable && !item->selectable()) // we could have also passed onlySelectable to the selectTest function, but checking here is faster, because we have access to QCPAbstractItem::selectable
13668       continue;
13669     if (!item->clipToAxisRect() || item->clipRect().contains(pos.toPoint())) // only consider clicks inside axis cliprect of the item if actually clipped to it
13670     {
13671       double currentDistance = item->selectTest(pos, false);
13672       if (currentDistance >= 0 && currentDistance < resultDistance)
13673       {
13674         resultItem = item;
13675         resultDistance = currentDistance;
13676       }
13677     }
13678   }
13679 
13680   return resultItem;
13681 }
13682 
13683 /*!
13684   Returns whether this QCustomPlot contains the \a item.
13685 
13686   \see item
13687 */
hasItem(QCPAbstractItem * item) const13688 bool QCustomPlot::hasItem(QCPAbstractItem *item) const
13689 {
13690   return mItems.contains(item);
13691 }
13692 
13693 /*!
13694   Returns the layer with the specified \a name. If there is no layer with the specified name, 0 is
13695   returned.
13696 
13697   Layer names are case-sensitive.
13698 
13699   \see addLayer, moveLayer, removeLayer
13700 */
layer(const QString & name) const13701 QCPLayer *QCustomPlot::layer(const QString &name) const
13702 {
13703   foreach (QCPLayer *layer, mLayers)
13704   {
13705     if (layer->name() == name)
13706       return layer;
13707   }
13708   return 0;
13709 }
13710 
13711 /*! \overload
13712 
13713   Returns the layer by \a index. If the index is invalid, 0 is returned.
13714 
13715   \see addLayer, moveLayer, removeLayer
13716 */
layer(int index) const13717 QCPLayer *QCustomPlot::layer(int index) const
13718 {
13719   if (index >= 0 && index < mLayers.size())
13720   {
13721     return mLayers.at(index);
13722   } else
13723   {
13724     qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
13725     return 0;
13726   }
13727 }
13728 
13729 /*!
13730   Returns the layer that is set as current layer (see \ref setCurrentLayer).
13731 */
currentLayer() const13732 QCPLayer *QCustomPlot::currentLayer() const
13733 {
13734   return mCurrentLayer;
13735 }
13736 
13737 /*!
13738   Sets the layer with the specified \a name to be the current layer. All layerables (\ref
13739   QCPLayerable), e.g. plottables and items, are created on the current layer.
13740 
13741   Returns true on success, i.e. if there is a layer with the specified \a name in the QCustomPlot.
13742 
13743   Layer names are case-sensitive.
13744 
13745   \see addLayer, moveLayer, removeLayer, QCPLayerable::setLayer
13746 */
setCurrentLayer(const QString & name)13747 bool QCustomPlot::setCurrentLayer(const QString &name)
13748 {
13749   if (QCPLayer *newCurrentLayer = layer(name))
13750   {
13751     return setCurrentLayer(newCurrentLayer);
13752   } else
13753   {
13754     qDebug() << Q_FUNC_INFO << "layer with name doesn't exist:" << name;
13755     return false;
13756   }
13757 }
13758 
13759 /*! \overload
13760 
13761   Sets the provided \a layer to be the current layer.
13762 
13763   Returns true on success, i.e. when \a layer is a valid layer in the QCustomPlot.
13764 
13765   \see addLayer, moveLayer, removeLayer
13766 */
setCurrentLayer(QCPLayer * layer)13767 bool QCustomPlot::setCurrentLayer(QCPLayer *layer)
13768 {
13769   if (!mLayers.contains(layer))
13770   {
13771     qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(layer);
13772     return false;
13773   }
13774 
13775   mCurrentLayer = layer;
13776   return true;
13777 }
13778 
13779 /*!
13780   Returns the number of currently existing layers in the plot
13781 
13782   \see layer, addLayer
13783 */
layerCount() const13784 int QCustomPlot::layerCount() const
13785 {
13786   return mLayers.size();
13787 }
13788 
13789 /*!
13790   Adds a new layer to this QCustomPlot instance. The new layer will have the name \a name, which
13791   must be unique. Depending on \a insertMode, it is positioned either below or above \a otherLayer.
13792 
13793   Returns true on success, i.e. if there is no other layer named \a name and \a otherLayer is a
13794   valid layer inside this QCustomPlot.
13795 
13796   If \a otherLayer is 0, the highest layer in the QCustomPlot will be used.
13797 
13798   For an explanation of what layers are in QCustomPlot, see the documentation of \ref QCPLayer.
13799 
13800   \see layer, moveLayer, removeLayer
13801 */
addLayer(const QString & name,QCPLayer * otherLayer,QCustomPlot::LayerInsertMode insertMode)13802 bool QCustomPlot::addLayer(const QString &name, QCPLayer *otherLayer, QCustomPlot::LayerInsertMode insertMode)
13803 {
13804   if (!otherLayer)
13805     otherLayer = mLayers.last();
13806   if (!mLayers.contains(otherLayer))
13807   {
13808     qDebug() << Q_FUNC_INFO << "otherLayer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(otherLayer);
13809     return false;
13810   }
13811   if (layer(name))
13812   {
13813     qDebug() << Q_FUNC_INFO << "A layer exists already with the name" << name;
13814     return false;
13815   }
13816 
13817   QCPLayer *newLayer = new QCPLayer(this, name);
13818   mLayers.insert(otherLayer->index() + (insertMode==limAbove ? 1:0), newLayer);
13819   updateLayerIndices();
13820   setupPaintBuffers(); // associates new layer with the appropriate paint buffer
13821   return true;
13822 }
13823 
13824 /*!
13825   Removes the specified \a layer and returns true on success.
13826 
13827   All layerables (e.g. plottables and items) on the removed layer will be moved to the layer below
13828   \a layer. If \a layer is the bottom layer, the layerables are moved to the layer above. In both
13829   cases, the total rendering order of all layerables in the QCustomPlot is preserved.
13830 
13831   If \a layer is the current layer (\ref setCurrentLayer), the layer below (or above, if bottom
13832   layer) becomes the new current layer.
13833 
13834   It is not possible to remove the last layer of the plot.
13835 
13836   \see layer, addLayer, moveLayer
13837 */
removeLayer(QCPLayer * layer)13838 bool QCustomPlot::removeLayer(QCPLayer *layer)
13839 {
13840   if (!mLayers.contains(layer))
13841   {
13842     qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(layer);
13843     return false;
13844   }
13845   if (mLayers.size() < 2)
13846   {
13847     qDebug() << Q_FUNC_INFO << "can't remove last layer";
13848     return false;
13849   }
13850 
13851   // append all children of this layer to layer below (if this is lowest layer, prepend to layer above)
13852   int removedIndex = layer->index();
13853   bool isFirstLayer = removedIndex==0;
13854   QCPLayer *targetLayer = isFirstLayer ? mLayers.at(removedIndex+1) : mLayers.at(removedIndex-1);
13855   QList<QCPLayerable*> children = layer->children();
13856   if (isFirstLayer) // prepend in reverse order (so order relative to each other stays the same)
13857   {
13858     for (int i=children.size()-1; i>=0; --i)
13859       children.at(i)->moveToLayer(targetLayer, true);
13860   } else  // append normally
13861   {
13862     for (int i=0; i<children.size(); ++i)
13863       children.at(i)->moveToLayer(targetLayer, false);
13864   }
13865   // if removed layer is current layer, change current layer to layer below/above:
13866   if (layer == mCurrentLayer)
13867     setCurrentLayer(targetLayer);
13868   // invalidate the paint buffer that was responsible for this layer:
13869   if (auto paint_buffer = layer->mPaintBuffer.toStrongRef())
13870     paint_buffer->setInvalidated();
13871   // remove layer:
13872   delete layer;
13873   mLayers.removeOne(layer);
13874   updateLayerIndices();
13875   return true;
13876 }
13877 
13878 /*!
13879   Moves the specified \a layer either above or below \a otherLayer. Whether it's placed above or
13880   below is controlled with \a insertMode.
13881 
13882   Returns true on success, i.e. when both \a layer and \a otherLayer are valid layers in the
13883   QCustomPlot.
13884 
13885   \see layer, addLayer, moveLayer
13886 */
moveLayer(QCPLayer * layer,QCPLayer * otherLayer,QCustomPlot::LayerInsertMode insertMode)13887 bool QCustomPlot::moveLayer(QCPLayer *layer, QCPLayer *otherLayer, QCustomPlot::LayerInsertMode insertMode)
13888 {
13889   if (!mLayers.contains(layer))
13890   {
13891     qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(layer);
13892     return false;
13893   }
13894   if (!mLayers.contains(otherLayer))
13895   {
13896     qDebug() << Q_FUNC_INFO << "otherLayer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(otherLayer);
13897     return false;
13898   }
13899 
13900   if (layer->index() > otherLayer->index())
13901     mLayers.move(layer->index(), otherLayer->index() + (insertMode==limAbove ? 1:0));
13902   else if (layer->index() < otherLayer->index())
13903     mLayers.move(layer->index(), otherLayer->index() + (insertMode==limAbove ? 0:-1));
13904 
13905   // invalidate the paint buffers that are responsible for the layers:
13906   if (auto paint_buffer = layer->mPaintBuffer.toStrongRef())
13907     paint_buffer->setInvalidated();
13908   if (auto paint_buffer = otherLayer->mPaintBuffer.toStrongRef())
13909     paint_buffer->setInvalidated();
13910 
13911   updateLayerIndices();
13912   return true;
13913 }
13914 
13915 /*!
13916   Returns the number of axis rects in the plot.
13917 
13918   All axis rects can be accessed via QCustomPlot::axisRect().
13919 
13920   Initially, only one axis rect exists in the plot.
13921 
13922   \see axisRect, axisRects
13923 */
axisRectCount() const13924 int QCustomPlot::axisRectCount() const
13925 {
13926   return axisRects().size();
13927 }
13928 
13929 /*!
13930   Returns the axis rect with \a index.
13931 
13932   Initially, only one axis rect (with index 0) exists in the plot. If multiple axis rects were
13933   added, all of them may be accessed with this function in a linear fashion (even when they are
13934   nested in a layout hierarchy or inside other axis rects via QCPAxisRect::insetLayout).
13935 
13936   \see axisRectCount, axisRects
13937 */
axisRect(int index) const13938 QCPAxisRect *QCustomPlot::axisRect(int index) const
13939 {
13940   const QList<QCPAxisRect*> rectList = axisRects();
13941   if (index >= 0 && index < rectList.size())
13942   {
13943     return rectList.at(index);
13944   } else
13945   {
13946     qDebug() << Q_FUNC_INFO << "invalid axis rect index" << index;
13947     return 0;
13948   }
13949 }
13950 
13951 /*!
13952   Returns all axis rects in the plot.
13953 
13954   \see axisRectCount, axisRect
13955 */
axisRects() const13956 QList<QCPAxisRect*> QCustomPlot::axisRects() const
13957 {
13958   QList<QCPAxisRect*> result;
13959   QStack<QCPLayoutElement*> elementStack;
13960   if (mPlotLayout)
13961     elementStack.push(mPlotLayout);
13962 
13963   while (!elementStack.isEmpty())
13964   {
13965     foreach (QCPLayoutElement *element, elementStack.pop()->elements(false))
13966     {
13967       if (element)
13968       {
13969         elementStack.push(element);
13970         if (QCPAxisRect *ar = qobject_cast<QCPAxisRect*>(element))
13971           result.append(ar);
13972       }
13973     }
13974   }
13975 
13976   return result;
13977 }
13978 
13979 /*!
13980   Returns the layout element at pixel position \a pos. If there is no element at that position,
13981   returns 0.
13982 
13983   Only visible elements are used. If \ref QCPLayoutElement::setVisible on the element itself or on
13984   any of its parent elements is set to false, it will not be considered.
13985 
13986   \see itemAt, plottableAt
13987 */
layoutElementAt(const QPointF & pos) const13988 QCPLayoutElement *QCustomPlot::layoutElementAt(const QPointF &pos) const
13989 {
13990   QCPLayoutElement *currentElement = mPlotLayout;
13991   bool searchSubElements = true;
13992   while (searchSubElements && currentElement)
13993   {
13994     searchSubElements = false;
13995     foreach (QCPLayoutElement *subElement, currentElement->elements(false))
13996     {
13997       if (subElement && subElement->realVisibility() && subElement->selectTest(pos, false) >= 0)
13998       {
13999         currentElement = subElement;
14000         searchSubElements = true;
14001         break;
14002       }
14003     }
14004   }
14005   return currentElement;
14006 }
14007 
14008 /*!
14009   Returns the layout element of type \ref QCPAxisRect at pixel position \a pos. This method ignores
14010   other layout elements even if they are visually in front of the axis rect (e.g. a \ref
14011   QCPLegend). If there is no axis rect at that position, returns 0.
14012 
14013   Only visible axis rects are used. If \ref QCPLayoutElement::setVisible on the axis rect itself or
14014   on any of its parent elements is set to false, it will not be considered.
14015 
14016   \see layoutElementAt
14017 */
axisRectAt(const QPointF & pos) const14018 QCPAxisRect *QCustomPlot::axisRectAt(const QPointF &pos) const
14019 {
14020   QCPAxisRect *result = 0;
14021   QCPLayoutElement *currentElement = mPlotLayout;
14022   bool searchSubElements = true;
14023   while (searchSubElements && currentElement)
14024   {
14025     searchSubElements = false;
14026     foreach (QCPLayoutElement *subElement, currentElement->elements(false))
14027     {
14028       if (subElement && subElement->realVisibility() && subElement->selectTest(pos, false) >= 0)
14029       {
14030         currentElement = subElement;
14031         searchSubElements = true;
14032         if (QCPAxisRect *ar = qobject_cast<QCPAxisRect*>(currentElement))
14033           result = ar;
14034         break;
14035       }
14036     }
14037   }
14038   return result;
14039 }
14040 
14041 /*!
14042   Returns the axes that currently have selected parts, i.e. whose selection state is not \ref
14043   QCPAxis::spNone.
14044 
14045   \see selectedPlottables, selectedLegends, setInteractions, QCPAxis::setSelectedParts,
14046   QCPAxis::setSelectableParts
14047 */
selectedAxes() const14048 QList<QCPAxis*> QCustomPlot::selectedAxes() const
14049 {
14050   QList<QCPAxis*> result, allAxes;
14051   foreach (QCPAxisRect *rect, axisRects())
14052     allAxes << rect->axes();
14053 
14054   foreach (QCPAxis *axis, allAxes)
14055   {
14056     if (axis->selectedParts() != QCPAxis::spNone)
14057       result.append(axis);
14058   }
14059 
14060   return result;
14061 }
14062 
14063 /*!
14064   Returns the legends that currently have selected parts, i.e. whose selection state is not \ref
14065   QCPLegend::spNone.
14066 
14067   \see selectedPlottables, selectedAxes, setInteractions, QCPLegend::setSelectedParts,
14068   QCPLegend::setSelectableParts, QCPLegend::selectedItems
14069 */
selectedLegends() const14070 QList<QCPLegend*> QCustomPlot::selectedLegends() const
14071 {
14072   QList<QCPLegend*> result;
14073 
14074   QStack<QCPLayoutElement*> elementStack;
14075   if (mPlotLayout)
14076     elementStack.push(mPlotLayout);
14077 
14078   while (!elementStack.isEmpty())
14079   {
14080     foreach (QCPLayoutElement *subElement, elementStack.pop()->elements(false))
14081     {
14082       if (subElement)
14083       {
14084         elementStack.push(subElement);
14085         if (QCPLegend *leg = qobject_cast<QCPLegend*>(subElement))
14086         {
14087           if (leg->selectedParts() != QCPLegend::spNone)
14088             result.append(leg);
14089         }
14090       }
14091     }
14092   }
14093 
14094   return result;
14095 }
14096 
14097 /*!
14098   Deselects all layerables (plottables, items, axes, legends,...) of the QCustomPlot.
14099 
14100   Since calling this function is not a user interaction, this does not emit the \ref
14101   selectionChangedByUser signal. The individual selectionChanged signals are emitted though, if the
14102   objects were previously selected.
14103 
14104   \see setInteractions, selectedPlottables, selectedItems, selectedAxes, selectedLegends
14105 */
deselectAll()14106 void QCustomPlot::deselectAll()
14107 {
14108   foreach (QCPLayer *layer, mLayers)
14109   {
14110     foreach (QCPLayerable *layerable, layer->children())
14111       layerable->deselectEvent(0);
14112   }
14113 }
14114 
14115 /*!
14116   Causes a complete replot into the internal paint buffer(s). Finally, the widget surface is
14117   refreshed with the new buffer contents. This is the method that must be called to make changes to
14118   the plot, e.g. on the axis ranges or data points of graphs, visible.
14119 
14120   The parameter \a refreshPriority can be used to fine-tune the timing of the replot. For example
14121   if your application calls \ref replot very quickly in succession (e.g. multiple independent
14122   functions change some aspects of the plot and each wants to make sure the change gets replotted),
14123   it is advisable to set \a refreshPriority to \ref QCustomPlot::rpQueuedReplot. This way, the
14124   actual replotting is deferred to the next event loop iteration. Multiple successive calls of \ref
14125   replot with this priority will only cause a single replot, avoiding redundant replots and
14126   improving performance.
14127 
14128   Under a few circumstances, QCustomPlot causes a replot by itself. Those are resize events of the
14129   QCustomPlot widget and user interactions (object selection and range dragging/zooming).
14130 
14131   Before the replot happens, the signal \ref beforeReplot is emitted. After the replot, \ref
14132   afterReplot is emitted. It is safe to mutually connect the replot slot with any of those two
14133   signals on two QCustomPlots to make them replot synchronously, it won't cause an infinite
14134   recursion.
14135 
14136   If a layer is in mode \ref QCPLayer::lmBuffered (\ref QCPLayer::setMode), it is also possible to
14137   replot only that specific layer via \ref QCPLayer::replot. See the documentation there for
14138   details.
14139 */
replot(QCustomPlot::RefreshPriority refreshPriority)14140 void QCustomPlot::replot(QCustomPlot::RefreshPriority refreshPriority)
14141 {
14142   if (refreshPriority == QCustomPlot::rpQueuedReplot)
14143   {
14144     if (!mReplotQueued)
14145     {
14146       mReplotQueued = true;
14147       QTimer::singleShot(0, this, SLOT(replot()));
14148     }
14149     return;
14150   }
14151 
14152   if (mReplotting) // incase signals loop back to replot slot
14153     return;
14154   mReplotting = true;
14155   mReplotQueued = false;
14156   emit beforeReplot();
14157 
14158   updateLayout();
14159   // draw all layered objects (grid, axes, plottables, items, legend,...) into their buffers:
14160   setupPaintBuffers();
14161   foreach (QCPLayer *layer, mLayers)
14162     layer->drawToPaintBuffer();
14163   for (int i=0; i<mPaintBuffers.size(); ++i)
14164     mPaintBuffers.at(i)->setInvalidated(false);
14165 
14166   if ((refreshPriority == rpRefreshHint && mPlottingHints.testFlag(QCP::phImmediateRefresh)) || refreshPriority==rpImmediateRefresh)
14167     repaint();
14168   else
14169     update();
14170 
14171   emit afterReplot();
14172   mReplotting = false;
14173 }
14174 
14175 /*!
14176   Rescales the axes such that all plottables (like graphs) in the plot are fully visible.
14177 
14178   if \a onlyVisiblePlottables is set to true, only the plottables that have their visibility set to true
14179   (QCPLayerable::setVisible), will be used to rescale the axes.
14180 
14181   \see QCPAbstractPlottable::rescaleAxes, QCPAxis::rescale
14182 */
rescaleAxes(bool onlyVisiblePlottables)14183 void QCustomPlot::rescaleAxes(bool onlyVisiblePlottables)
14184 {
14185   QList<QCPAxis*> allAxes;
14186   foreach (QCPAxisRect *rect, axisRects())
14187     allAxes << rect->axes();
14188 
14189   foreach (QCPAxis *axis, allAxes)
14190     axis->rescale(onlyVisiblePlottables);
14191 }
14192 
14193 /*!
14194   Saves a PDF with the vectorized plot to the file \a fileName. The axis ratio as well as the scale
14195   of texts and lines will be derived from the specified \a width and \a height. This means, the
14196   output will look like the normal on-screen output of a QCustomPlot widget with the corresponding
14197   pixel width and height. If either \a width or \a height is zero, the exported image will have the
14198   same dimensions as the QCustomPlot widget currently has.
14199 
14200   Setting \a exportPen to \ref QCP::epNoCosmetic allows to disable the use of cosmetic pens when
14201   drawing to the PDF file. Cosmetic pens are pens with numerical width 0, which are always drawn as
14202   a one pixel wide line, no matter what zoom factor is set in the PDF-Viewer. For more information
14203   about cosmetic pens, see the QPainter and QPen documentation.
14204 
14205   The objects of the plot will appear in the current selection state. If you don't want any
14206   selected objects to be painted in their selected look, deselect everything with \ref deselectAll
14207   before calling this function.
14208 
14209   Returns true on success.
14210 
14211   \warning
14212   \li If you plan on editing the exported PDF file with a vector graphics editor like Inkscape, it
14213   is advised to set \a exportPen to \ref QCP::epNoCosmetic to avoid losing those cosmetic lines
14214   (which might be quite many, because cosmetic pens are the default for e.g. axes and tick marks).
14215   \li If calling this function inside the constructor of the parent of the QCustomPlot widget
14216   (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide
14217   explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this
14218   function uses the current width and height of the QCustomPlot widget. However, in Qt, these
14219   aren't defined yet inside the constructor, so you would get an image that has strange
14220   widths/heights.
14221 
14222   \a pdfCreator and \a pdfTitle may be used to set the according metadata fields in the resulting
14223   PDF file.
14224 
14225   \note On Android systems, this method does nothing and issues an according qDebug warning
14226   message. This is also the case if for other reasons the define flag \c QT_NO_PRINTER is set.
14227 
14228   \see savePng, saveBmp, saveJpg, saveRastered
14229 */
savePdf(const QString & fileName,int width,int height,QCP::ExportPen exportPen,const QString & pdfCreator,const QString & pdfTitle)14230 bool QCustomPlot::savePdf(const QString &fileName, int width, int height, QCP::ExportPen exportPen, const QString &pdfCreator, const QString &pdfTitle)
14231 {
14232   bool success = false;
14233 #ifdef QT_NO_PRINTER
14234   Q_UNUSED(fileName)
14235   Q_UNUSED(exportPen)
14236   Q_UNUSED(width)
14237   Q_UNUSED(height)
14238   Q_UNUSED(pdfCreator)
14239   Q_UNUSED(pdfTitle)
14240   qDebug() << Q_FUNC_INFO << "Qt was built without printer support (QT_NO_PRINTER). PDF not created.";
14241 #else
14242   int newWidth, newHeight;
14243   if (width == 0 || height == 0)
14244   {
14245     newWidth = this->width();
14246     newHeight = this->height();
14247   } else
14248   {
14249     newWidth = width;
14250     newHeight = height;
14251   }
14252 
14253   QPrinter printer(QPrinter::ScreenResolution);
14254   printer.setOutputFileName(fileName);
14255   printer.setOutputFormat(QPrinter::PdfFormat);
14256   printer.setColorMode(QPrinter::Color);
14257   printer.printEngine()->setProperty(QPrintEngine::PPK_Creator, pdfCreator);
14258   printer.printEngine()->setProperty(QPrintEngine::PPK_DocumentName, pdfTitle);
14259   QRect oldViewport = viewport();
14260   setViewport(QRect(0, 0, newWidth, newHeight));
14261 #if QT_VERSION < QT_VERSION_CHECK(5, 3, 0)
14262   printer.setFullPage(true);
14263   printer.setPaperSize(viewport().size(), QPrinter::DevicePixel);
14264 #else
14265   QPageLayout pageLayout;
14266   pageLayout.setMode(QPageLayout::FullPageMode);
14267   pageLayout.setOrientation(QPageLayout::Portrait);
14268   pageLayout.setMargins(QMarginsF(0, 0, 0, 0));
14269   pageLayout.setPageSize(QPageSize(viewport().size(), QPageSize::Point, QString(), QPageSize::ExactMatch));
14270   printer.setPageLayout(pageLayout);
14271 #endif
14272   QCPPainter printpainter;
14273   if (printpainter.begin(&printer))
14274   {
14275     printpainter.setMode(QCPPainter::pmVectorized);
14276     printpainter.setMode(QCPPainter::pmNoCaching);
14277     printpainter.setMode(QCPPainter::pmNonCosmetic, exportPen==QCP::epNoCosmetic);
14278     printpainter.setWindow(mViewport);
14279     if (mBackgroundBrush.style() != Qt::NoBrush &&
14280         mBackgroundBrush.color() != Qt::white &&
14281         mBackgroundBrush.color() != Qt::transparent &&
14282         mBackgroundBrush.color().alpha() > 0) // draw pdf background color if not white/transparent
14283       printpainter.fillRect(viewport(), mBackgroundBrush);
14284     draw(&printpainter);
14285     printpainter.end();
14286     success = true;
14287   }
14288   setViewport(oldViewport);
14289 #endif // QT_NO_PRINTER
14290   return success;
14291 }
14292 
14293 /*!
14294   Saves a PNG image file to \a fileName on disc. The output plot will have the dimensions \a width
14295   and \a height in pixels, multiplied by \a scale. If either \a width or \a height is zero, the
14296   current width and height of the QCustomPlot widget is used instead. Line widths and texts etc.
14297   are not scaled up when larger widths/heights are used. If you want that effect, use the \a scale
14298   parameter.
14299 
14300   For example, if you set both \a width and \a height to 100 and \a scale to 2, you will end up with an
14301   image file of size 200*200 in which all graphical elements are scaled up by factor 2 (line widths,
14302   texts, etc.). This scaling is not done by stretching a 100*100 image, the result will have full
14303   200*200 pixel resolution.
14304 
14305   If you use a high scaling factor, it is recommended to enable antialiasing for all elements by
14306   temporarily setting \ref QCustomPlot::setAntialiasedElements to \ref QCP::aeAll as this allows
14307   QCustomPlot to place objects with sub-pixel accuracy.
14308 
14309   image compression can be controlled with the \a quality parameter which must be between 0 and 100
14310   or -1 to use the default setting.
14311 
14312   The \a resolution will be written to the image file header and has no direct consequence for the
14313   quality or the pixel size. However, if opening the image with a tool which respects the metadata,
14314   it will be able to scale the image to match either a given size in real units of length (inch,
14315   centimeters, etc.), or the target display DPI. You can specify in which units \a resolution is
14316   given, by setting \a resolutionUnit. The \a resolution is converted to the format's expected
14317   resolution unit internally.
14318 
14319   Returns true on success. If this function fails, most likely the PNG format isn't supported by
14320   the system, see Qt docs about QImageWriter::supportedImageFormats().
14321 
14322   The objects of the plot will appear in the current selection state. If you don't want any selected
14323   objects to be painted in their selected look, deselect everything with \ref deselectAll before calling
14324   this function.
14325 
14326   If you want the PNG to have a transparent background, call \ref setBackground(const QBrush &brush)
14327   with no brush (Qt::NoBrush) or a transparent color (Qt::transparent), before saving.
14328 
14329   \warning If calling this function inside the constructor of the parent of the QCustomPlot widget
14330   (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide
14331   explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this
14332   function uses the current width and height of the QCustomPlot widget. However, in Qt, these
14333   aren't defined yet inside the constructor, so you would get an image that has strange
14334   widths/heights.
14335 
14336   \see savePdf, saveBmp, saveJpg, saveRastered
14337 */
savePng(const QString & fileName,int width,int height,double scale,int quality,int resolution,QCP::ResolutionUnit resolutionUnit)14338 bool QCustomPlot::savePng(const QString &fileName, int width, int height, double scale, int quality, int resolution, QCP::ResolutionUnit resolutionUnit)
14339 {
14340   return saveRastered(fileName, width, height, scale, "PNG", quality, resolution, resolutionUnit);
14341 }
14342 
14343 /*!
14344   Saves a JPEG image file to \a fileName on disc. The output plot will have the dimensions \a width
14345   and \a height in pixels, multiplied by \a scale. If either \a width or \a height is zero, the
14346   current width and height of the QCustomPlot widget is used instead. Line widths and texts etc.
14347   are not scaled up when larger widths/heights are used. If you want that effect, use the \a scale
14348   parameter.
14349 
14350   For example, if you set both \a width and \a height to 100 and \a scale to 2, you will end up with an
14351   image file of size 200*200 in which all graphical elements are scaled up by factor 2 (line widths,
14352   texts, etc.). This scaling is not done by stretching a 100*100 image, the result will have full
14353   200*200 pixel resolution.
14354 
14355   If you use a high scaling factor, it is recommended to enable antialiasing for all elements by
14356   temporarily setting \ref QCustomPlot::setAntialiasedElements to \ref QCP::aeAll as this allows
14357   QCustomPlot to place objects with sub-pixel accuracy.
14358 
14359   image compression can be controlled with the \a quality parameter which must be between 0 and 100
14360   or -1 to use the default setting.
14361 
14362   The \a resolution will be written to the image file header and has no direct consequence for the
14363   quality or the pixel size. However, if opening the image with a tool which respects the metadata,
14364   it will be able to scale the image to match either a given size in real units of length (inch,
14365   centimeters, etc.), or the target display DPI. You can specify in which units \a resolution is
14366   given, by setting \a resolutionUnit. The \a resolution is converted to the format's expected
14367   resolution unit internally.
14368 
14369   Returns true on success. If this function fails, most likely the JPEG format isn't supported by
14370   the system, see Qt docs about QImageWriter::supportedImageFormats().
14371 
14372   The objects of the plot will appear in the current selection state. If you don't want any selected
14373   objects to be painted in their selected look, deselect everything with \ref deselectAll before calling
14374   this function.
14375 
14376   \warning If calling this function inside the constructor of the parent of the QCustomPlot widget
14377   (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide
14378   explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this
14379   function uses the current width and height of the QCustomPlot widget. However, in Qt, these
14380   aren't defined yet inside the constructor, so you would get an image that has strange
14381   widths/heights.
14382 
14383   \see savePdf, savePng, saveBmp, saveRastered
14384 */
saveJpg(const QString & fileName,int width,int height,double scale,int quality,int resolution,QCP::ResolutionUnit resolutionUnit)14385 bool QCustomPlot::saveJpg(const QString &fileName, int width, int height, double scale, int quality, int resolution, QCP::ResolutionUnit resolutionUnit)
14386 {
14387   return saveRastered(fileName, width, height, scale, "JPG", quality, resolution, resolutionUnit);
14388 }
14389 
14390 /*!
14391   Saves a BMP image file to \a fileName on disc. The output plot will have the dimensions \a width
14392   and \a height in pixels, multiplied by \a scale. If either \a width or \a height is zero, the
14393   current width and height of the QCustomPlot widget is used instead. Line widths and texts etc.
14394   are not scaled up when larger widths/heights are used. If you want that effect, use the \a scale
14395   parameter.
14396 
14397   For example, if you set both \a width and \a height to 100 and \a scale to 2, you will end up with an
14398   image file of size 200*200 in which all graphical elements are scaled up by factor 2 (line widths,
14399   texts, etc.). This scaling is not done by stretching a 100*100 image, the result will have full
14400   200*200 pixel resolution.
14401 
14402   If you use a high scaling factor, it is recommended to enable antialiasing for all elements by
14403   temporarily setting \ref QCustomPlot::setAntialiasedElements to \ref QCP::aeAll as this allows
14404   QCustomPlot to place objects with sub-pixel accuracy.
14405 
14406   The \a resolution will be written to the image file header and has no direct consequence for the
14407   quality or the pixel size. However, if opening the image with a tool which respects the metadata,
14408   it will be able to scale the image to match either a given size in real units of length (inch,
14409   centimeters, etc.), or the target display DPI. You can specify in which units \a resolution is
14410   given, by setting \a resolutionUnit. The \a resolution is converted to the format's expected
14411   resolution unit internally.
14412 
14413   Returns true on success. If this function fails, most likely the BMP format isn't supported by
14414   the system, see Qt docs about QImageWriter::supportedImageFormats().
14415 
14416   The objects of the plot will appear in the current selection state. If you don't want any selected
14417   objects to be painted in their selected look, deselect everything with \ref deselectAll before calling
14418   this function.
14419 
14420   \warning If calling this function inside the constructor of the parent of the QCustomPlot widget
14421   (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide
14422   explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this
14423   function uses the current width and height of the QCustomPlot widget. However, in Qt, these
14424   aren't defined yet inside the constructor, so you would get an image that has strange
14425   widths/heights.
14426 
14427   \see savePdf, savePng, saveJpg, saveRastered
14428 */
saveBmp(const QString & fileName,int width,int height,double scale,int resolution,QCP::ResolutionUnit resolutionUnit)14429 bool QCustomPlot::saveBmp(const QString &fileName, int width, int height, double scale, int resolution, QCP::ResolutionUnit resolutionUnit)
14430 {
14431   return saveRastered(fileName, width, height, scale, "BMP", -1, resolution, resolutionUnit);
14432 }
14433 
14434 /*! \internal
14435 
14436   Returns a minimum size hint that corresponds to the minimum size of the top level layout
14437   (\ref plotLayout). To prevent QCustomPlot from being collapsed to size/width zero, set a minimum
14438   size (setMinimumSize) either on the whole QCustomPlot or on any layout elements inside the plot.
14439   This is especially important, when placed in a QLayout where other components try to take in as
14440   much space as possible (e.g. QMdiArea).
14441 */
minimumSizeHint() const14442 QSize QCustomPlot::minimumSizeHint() const
14443 {
14444   return mPlotLayout->minimumSizeHint();
14445 }
14446 
14447 /*! \internal
14448 
14449   Returns a size hint that is the same as \ref minimumSizeHint.
14450 
14451 */
sizeHint() const14452 QSize QCustomPlot::sizeHint() const
14453 {
14454   return mPlotLayout->minimumSizeHint();
14455 }
14456 
14457 /*! \internal
14458 
14459   Event handler for when the QCustomPlot widget needs repainting. This does not cause a \ref replot, but
14460   draws the internal buffer on the widget surface.
14461 */
paintEvent(QPaintEvent * event)14462 void QCustomPlot::paintEvent(QPaintEvent *event)
14463 {
14464   Q_UNUSED(event);
14465   QCPPainter painter(this);
14466   if (painter.isActive())
14467   {
14468     painter.setRenderHint(QPainter::HighQualityAntialiasing); // to make Antialiasing look good if using the OpenGL graphicssystem
14469     if (mBackgroundBrush.style() != Qt::NoBrush)
14470       painter.fillRect(mViewport, mBackgroundBrush);
14471     drawBackground(&painter);
14472     for (int bufferIndex = 0; bufferIndex < mPaintBuffers.size(); ++bufferIndex)
14473       mPaintBuffers.at(bufferIndex)->draw(&painter);
14474   }
14475 }
14476 
14477 /*! \internal
14478 
14479   Event handler for a resize of the QCustomPlot widget. The viewport (which becomes the outer rect
14480   of mPlotLayout) is resized appropriately. Finally a \ref replot is performed.
14481 */
resizeEvent(QResizeEvent * event)14482 void QCustomPlot::resizeEvent(QResizeEvent *event)
14483 {
14484   Q_UNUSED(event)
14485   // resize and repaint the buffer:
14486   setViewport(rect());
14487   replot(rpQueuedRefresh); // queued refresh is important here, to prevent painting issues in some contexts (e.g. MDI subwindow)
14488 }
14489 
14490 /*! \internal
14491 
14492  Event handler for when a double click occurs. Emits the \ref mouseDoubleClick signal, then
14493  determines the layerable under the cursor and forwards the event to it. Finally, emits the
14494  specialized signals when certain objecs are clicked (e.g. \ref plottableDoubleClick, \ref
14495  axisDoubleClick, etc.).
14496 
14497  \see mousePressEvent, mouseReleaseEvent
14498 */
mouseDoubleClickEvent(QMouseEvent * event)14499 void QCustomPlot::mouseDoubleClickEvent(QMouseEvent *event)
14500 {
14501   emit mouseDoubleClick(event);
14502   mMouseHasMoved = false;
14503   mMousePressPos = event->pos();
14504 
14505   // determine layerable under the cursor (this event is called instead of the second press event in a double-click):
14506   QList<QVariant> details;
14507   QList<QCPLayerable*> candidates = layerableListAt(mMousePressPos, false, &details);
14508   for (int i=0; i<candidates.size(); ++i)
14509   {
14510     event->accept(); // default impl of QCPLayerable's mouse events ignore the event, in that case propagate to next candidate in list
14511     candidates.at(i)->mouseDoubleClickEvent(event, details.at(i));
14512     if (event->isAccepted())
14513     {
14514       mMouseEventLayerable = candidates.at(i);
14515       mMouseEventLayerableDetails = details.at(i);
14516       break;
14517     }
14518   }
14519 
14520   // emit specialized object double click signals:
14521   if (!candidates.isEmpty())
14522   {
14523     if (QCPAbstractPlottable *ap = qobject_cast<QCPAbstractPlottable*>(candidates.first()))
14524     {
14525       int dataIndex = 0;
14526       if (!details.first().value<QCPDataSelection>().isEmpty())
14527         dataIndex = details.first().value<QCPDataSelection>().dataRange().begin();
14528       emit plottableDoubleClick(ap, dataIndex, event);
14529     } else if (QCPAxis *ax = qobject_cast<QCPAxis*>(candidates.first()))
14530       emit axisDoubleClick(ax, details.first().value<QCPAxis::SelectablePart>(), event);
14531     else if (QCPAbstractItem *ai = qobject_cast<QCPAbstractItem*>(candidates.first()))
14532       emit itemDoubleClick(ai, event);
14533     else if (QCPLegend *lg = qobject_cast<QCPLegend*>(candidates.first()))
14534       emit legendDoubleClick(lg, 0, event);
14535     else if (QCPAbstractLegendItem *li = qobject_cast<QCPAbstractLegendItem*>(candidates.first()))
14536       emit legendDoubleClick(li->parentLegend(), li, event);
14537   }
14538 
14539   event->accept(); // in case QCPLayerable reimplementation manipulates event accepted state. In QWidget event system, QCustomPlot wants to accept the event.
14540 }
14541 
14542 /*! \internal
14543 
14544   Event handler for when a mouse button is pressed. Emits the mousePress signal.
14545 
14546   If the current \ref setSelectionRectMode is not \ref QCP::srmNone, passes the event to the
14547   selection rect. Otherwise determines the layerable under the cursor and forwards the event to it.
14548 
14549   \see mouseMoveEvent, mouseReleaseEvent
14550 */
mousePressEvent(QMouseEvent * event)14551 void QCustomPlot::mousePressEvent(QMouseEvent *event)
14552 {
14553   emit mousePress(event);
14554   // save some state to tell in releaseEvent whether it was a click:
14555   mMouseHasMoved = false;
14556   mMousePressPos = event->pos();
14557 
14558   if (mSelectionRect && mSelectionRectMode != QCP::srmNone)
14559   {
14560     if (mSelectionRectMode != QCP::srmZoom || qobject_cast<QCPAxisRect*>(axisRectAt(mMousePressPos))) // in zoom mode only activate selection rect if on an axis rect
14561       mSelectionRect->startSelection(event);
14562   } else
14563   {
14564     // no selection rect interaction, so forward event to layerable under the cursor:
14565     QList<QVariant> details;
14566     QList<QCPLayerable*> candidates = layerableListAt(mMousePressPos, false, &details);
14567     for (int i=0; i<candidates.size(); ++i)
14568     {
14569       event->accept(); // default impl of QCPLayerable's mouse events ignore the event, in that case propagate to next candidate in list
14570       candidates.at(i)->mousePressEvent(event, details.at(i));
14571       if (event->isAccepted())
14572       {
14573         mMouseEventLayerable = candidates.at(i);
14574         mMouseEventLayerableDetails = details.at(i);
14575         break;
14576       }
14577     }
14578   }
14579 
14580   event->accept(); // in case QCPLayerable reimplementation manipulates event accepted state. In QWidget event system, QCustomPlot wants to accept the event.
14581 }
14582 
14583 /*! \internal
14584 
14585   Event handler for when the cursor is moved. Emits the \ref mouseMove signal.
14586 
14587   If the selection rect (\ref setSelectionRect) is currently active, the event is forwarded to it
14588   in order to update the rect geometry.
14589 
14590   Otherwise, if a layout element has mouse capture focus (a mousePressEvent happened on top of the
14591   layout element before), the mouseMoveEvent is forwarded to that element.
14592 
14593   \see mousePressEvent, mouseReleaseEvent
14594 */
mouseMoveEvent(QMouseEvent * event)14595 void QCustomPlot::mouseMoveEvent(QMouseEvent *event)
14596 {
14597   emit mouseMove(event);
14598 
14599   if (!mMouseHasMoved && (mMousePressPos-event->pos()).manhattanLength() > 3)
14600     mMouseHasMoved = true; // moved too far from mouse press position, don't handle as click on mouse release
14601 
14602   if (mSelectionRect && mSelectionRect->isActive())
14603     mSelectionRect->moveSelection(event);
14604   else if (mMouseEventLayerable) // call event of affected layerable:
14605     mMouseEventLayerable->mouseMoveEvent(event, mMousePressPos);
14606 
14607   event->accept(); // in case QCPLayerable reimplementation manipulates event accepted state. In QWidget event system, QCustomPlot wants to accept the event.
14608 }
14609 
14610 /*! \internal
14611 
14612   Event handler for when a mouse button is released. Emits the \ref mouseRelease signal.
14613 
14614   If the mouse was moved less than a certain threshold in any direction since the \ref
14615   mousePressEvent, it is considered a click which causes the selection mechanism (if activated via
14616   \ref setInteractions) to possibly change selection states accordingly. Further, specialized mouse
14617   click signals are emitted (e.g. \ref plottableClick, \ref axisClick, etc.)
14618 
14619   If a layerable is the mouse capturer (a \ref mousePressEvent happened on top of the layerable
14620   before), the \ref mouseReleaseEvent is forwarded to that element.
14621 
14622   \see mousePressEvent, mouseMoveEvent
14623 */
mouseReleaseEvent(QMouseEvent * event)14624 void QCustomPlot::mouseReleaseEvent(QMouseEvent *event)
14625 {
14626   emit mouseRelease(event);
14627 
14628   if (!mMouseHasMoved) // mouse hasn't moved (much) between press and release, so handle as click
14629   {
14630     if (mSelectionRect && mSelectionRect->isActive()) // a simple click shouldn't successfully finish a selection rect, so cancel it here
14631       mSelectionRect->cancel();
14632     if (event->button() == Qt::LeftButton)
14633       processPointSelection(event);
14634 
14635     // emit specialized click signals of QCustomPlot instance:
14636     if (QCPAbstractPlottable *ap = qobject_cast<QCPAbstractPlottable*>(mMouseEventLayerable))
14637     {
14638       int dataIndex = 0;
14639       if (!mMouseEventLayerableDetails.value<QCPDataSelection>().isEmpty())
14640         dataIndex = mMouseEventLayerableDetails.value<QCPDataSelection>().dataRange().begin();
14641       emit plottableClick(ap, dataIndex, event);
14642     } else if (QCPAxis *ax = qobject_cast<QCPAxis*>(mMouseEventLayerable))
14643       emit axisClick(ax, mMouseEventLayerableDetails.value<QCPAxis::SelectablePart>(), event);
14644     else if (QCPAbstractItem *ai = qobject_cast<QCPAbstractItem*>(mMouseEventLayerable))
14645       emit itemClick(ai, event);
14646     else if (QCPLegend *lg = qobject_cast<QCPLegend*>(mMouseEventLayerable))
14647       emit legendClick(lg, 0, event);
14648     else if (QCPAbstractLegendItem *li = qobject_cast<QCPAbstractLegendItem*>(mMouseEventLayerable))
14649       emit legendClick(li->parentLegend(), li, event);
14650   }
14651 
14652   if (mSelectionRect && mSelectionRect->isActive()) // Note: if a click was detected above, the selection rect is canceled there
14653   {
14654     // finish selection rect, the appropriate action will be taken via signal-slot connection:
14655     mSelectionRect->endSelection(event);
14656   } else
14657   {
14658     // call event of affected layerable:
14659     if (mMouseEventLayerable)
14660     {
14661       mMouseEventLayerable->mouseReleaseEvent(event, mMousePressPos);
14662       mMouseEventLayerable = 0;
14663     }
14664   }
14665 
14666   if (noAntialiasingOnDrag())
14667     replot(rpQueuedReplot);
14668 
14669   event->accept(); // in case QCPLayerable reimplementation manipulates event accepted state. In QWidget event system, QCustomPlot wants to accept the event.
14670 }
14671 
14672 /*! \internal
14673 
14674   Event handler for mouse wheel events. First, the \ref mouseWheel signal is emitted. Then
14675   determines the affected layerable and forwards the event to it.
14676 */
wheelEvent(QWheelEvent * event)14677 void QCustomPlot::wheelEvent(QWheelEvent *event)
14678 {
14679   emit mouseWheel(event);
14680   // forward event to layerable under cursor:
14681   QList<QCPLayerable*> candidates = layerableListAt(
14682 #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
14683                                                     event->pos()
14684 #elif QT_VERSION < QT_VERSION_CHECK(5, 15, 0)
14685                                                     event->posF()
14686 #else
14687                                                     event->position()
14688 #endif
14689                                                     , false);
14690   for (int i=0; i<candidates.size(); ++i)
14691   {
14692     event->accept(); // default impl of QCPLayerable's mouse events ignore the event, in that case propagate to next candidate in list
14693     candidates.at(i)->wheelEvent(event);
14694     if (event->isAccepted())
14695       break;
14696   }
14697   event->accept(); // in case QCPLayerable reimplementation manipulates event accepted state. In QWidget event system, QCustomPlot wants to accept the event.
14698 }
14699 
14700 /*! \internal
14701 
14702   This function draws the entire plot, including background pixmap, with the specified \a painter.
14703   It does not make use of the paint buffers like \ref replot, so this is the function typically
14704   used by saving/exporting methods such as \ref savePdf or \ref toPainter.
14705 
14706   Note that it does not fill the background with the background brush (as the user may specify with
14707   \ref setBackground(const QBrush &brush)), this is up to the respective functions calling this
14708   method.
14709 */
draw(QCPPainter * painter)14710 void QCustomPlot::draw(QCPPainter *painter)
14711 {
14712   updateLayout();
14713 
14714   // draw viewport background pixmap:
14715   drawBackground(painter);
14716 
14717   // draw all layered objects (grid, axes, plottables, items, legend,...):
14718   foreach (QCPLayer *layer, mLayers)
14719     layer->draw(painter);
14720 
14721   /* Debug code to draw all layout element rects
14722   foreach (QCPLayoutElement* el, findChildren<QCPLayoutElement*>())
14723   {
14724     painter->setBrush(Qt::NoBrush);
14725     painter->setPen(QPen(QColor(0, 0, 0, 100), 0, Qt::DashLine));
14726     painter->drawRect(el->rect());
14727     painter->setPen(QPen(QColor(255, 0, 0, 100), 0, Qt::DashLine));
14728     painter->drawRect(el->outerRect());
14729   }
14730   */
14731 }
14732 
14733 /*! \internal
14734 
14735   Performs the layout update steps defined by \ref QCPLayoutElement::UpdatePhase, by calling \ref
14736   QCPLayoutElement::update on the main plot layout.
14737 
14738   Here, the layout elements calculate their positions and margins, and prepare for the following
14739   draw call.
14740 */
updateLayout()14741 void QCustomPlot::updateLayout()
14742 {
14743   // run through layout phases:
14744   mPlotLayout->update(QCPLayoutElement::upPreparation);
14745   mPlotLayout->update(QCPLayoutElement::upMargins);
14746   mPlotLayout->update(QCPLayoutElement::upLayout);
14747 }
14748 
14749 /*! \internal
14750 
14751   Draws the viewport background pixmap of the plot.
14752 
14753   If a pixmap was provided via \ref setBackground, this function buffers the scaled version
14754   depending on \ref setBackgroundScaled and \ref setBackgroundScaledMode and then draws it inside
14755   the viewport with the provided \a painter. The scaled version is buffered in
14756   mScaledBackgroundPixmap to prevent expensive rescaling at every redraw. It is only updated, when
14757   the axis rect has changed in a way that requires a rescale of the background pixmap (this is
14758   dependent on the \ref setBackgroundScaledMode), or when a differend axis background pixmap was
14759   set.
14760 
14761   Note that this function does not draw a fill with the background brush
14762   (\ref setBackground(const QBrush &brush)) beneath the pixmap.
14763 
14764   \see setBackground, setBackgroundScaled, setBackgroundScaledMode
14765 */
drawBackground(QCPPainter * painter)14766 void QCustomPlot::drawBackground(QCPPainter *painter)
14767 {
14768   // Note: background color is handled in individual replot/save functions
14769 
14770   // draw background pixmap (on top of fill, if brush specified):
14771   if (!mBackgroundPixmap.isNull())
14772   {
14773     if (mBackgroundScaled)
14774     {
14775       // check whether mScaledBackground needs to be updated:
14776       QSize scaledSize(mBackgroundPixmap.size());
14777       scaledSize.scale(mViewport.size(), mBackgroundScaledMode);
14778       if (mScaledBackgroundPixmap.size() != scaledSize)
14779         mScaledBackgroundPixmap = mBackgroundPixmap.scaled(mViewport.size(), mBackgroundScaledMode, Qt::SmoothTransformation);
14780       painter->drawPixmap(mViewport.topLeft(), mScaledBackgroundPixmap, QRect(0, 0, mViewport.width(), mViewport.height()) & mScaledBackgroundPixmap.rect());
14781     } else
14782     {
14783       painter->drawPixmap(mViewport.topLeft(), mBackgroundPixmap, QRect(0, 0, mViewport.width(), mViewport.height()));
14784     }
14785   }
14786 }
14787 
14788 /*! \internal
14789 
14790   Goes through the layers and makes sure this QCustomPlot instance holds the correct number of
14791   paint buffers and that they have the correct configuration (size, pixel ratio, etc.).
14792   Allocations, reallocations and deletions of paint buffers are performed as necessary. It also
14793   associates the paint buffers with the layers, so they draw themselves into the right buffer when
14794   \ref QCPLayer::drawToPaintBuffer is called. This means it associates adjacent \ref
14795   QCPLayer::lmLogical layers to a mutual paint buffer and creates dedicated paint buffers for
14796   layers in \ref QCPLayer::lmBuffered mode.
14797 
14798   This method uses \ref createPaintBuffer to create new paint buffers.
14799 
14800   After this method, the paint buffers are empty (filled with \c Qt::transparent) and invalidated
14801   (so an attempt to replot only a single buffered layer causes a full replot).
14802 
14803   This method is called in every \ref replot call, prior to actually drawing the layers (into their
14804   associated paint buffer). If the paint buffers don't need changing/reallocating, this method
14805   basically leaves them alone and thus finishes very fast.
14806 */
setupPaintBuffers()14807 void QCustomPlot::setupPaintBuffers()
14808 {
14809   int bufferIndex = 0;
14810   if (mPaintBuffers.isEmpty())
14811     mPaintBuffers.append(QSharedPointer<QCPAbstractPaintBuffer>(createPaintBuffer()));
14812 
14813   for (int layerIndex = 0; layerIndex < mLayers.size(); ++layerIndex)
14814   {
14815     QCPLayer *layer = mLayers.at(layerIndex);
14816     if (layer->mode() == QCPLayer::lmLogical)
14817     {
14818       layer->mPaintBuffer = mPaintBuffers.at(bufferIndex).toWeakRef();
14819     } else if (layer->mode() == QCPLayer::lmBuffered)
14820     {
14821       ++bufferIndex;
14822       if (bufferIndex >= mPaintBuffers.size())
14823         mPaintBuffers.append(QSharedPointer<QCPAbstractPaintBuffer>(createPaintBuffer()));
14824       layer->mPaintBuffer = mPaintBuffers.at(bufferIndex).toWeakRef();
14825       if (layerIndex < mLayers.size()-1 && mLayers.at(layerIndex+1)->mode() == QCPLayer::lmLogical) // not last layer, and next one is logical, so prepare another buffer for next layerables
14826       {
14827         ++bufferIndex;
14828         if (bufferIndex >= mPaintBuffers.size())
14829           mPaintBuffers.append(QSharedPointer<QCPAbstractPaintBuffer>(createPaintBuffer()));
14830       }
14831     }
14832   }
14833   // remove unneeded buffers:
14834   while (mPaintBuffers.size()-1 > bufferIndex)
14835     mPaintBuffers.removeLast();
14836   // resize buffers to viewport size and clear contents:
14837   for (int i=0; i<mPaintBuffers.size(); ++i)
14838   {
14839     mPaintBuffers.at(i)->setSize(viewport().size()); // won't do anything if already correct size
14840     mPaintBuffers.at(i)->clear(Qt::transparent);
14841     mPaintBuffers.at(i)->setInvalidated();
14842   }
14843 }
14844 
14845 /*! \internal
14846 
14847   This method is used by \ref setupPaintBuffers when it needs to create new paint buffers.
14848 
14849   Depending on the current setting of \ref setOpenGl, and the current Qt version, different
14850   backends (subclasses of \ref QCPAbstractPaintBuffer) are created, initialized with the proper
14851   size and device pixel ratio, and returned.
14852 */
createPaintBuffer()14853 QCPAbstractPaintBuffer *QCustomPlot::createPaintBuffer()
14854 {
14855   if (mOpenGl)
14856   {
14857 #if defined(QCP_OPENGL_FBO)
14858     return new QCPPaintBufferGlFbo(viewport().size(), mBufferDevicePixelRatio, mGlContext, mGlPaintDevice);
14859 #elif defined(QCP_OPENGL_PBUFFER)
14860     return new QCPPaintBufferGlPbuffer(viewport().size(), mBufferDevicePixelRatio, mOpenGlMultisamples);
14861 #else
14862     qDebug() << Q_FUNC_INFO << "OpenGL enabled even though no support for it compiled in, this shouldn't have happened. Falling back to pixmap paint buffer.";
14863     return new QCPPaintBufferPixmap(viewport().size(), mBufferDevicePixelRatio);
14864 #endif
14865   } else
14866     return new QCPPaintBufferPixmap(viewport().size(), mBufferDevicePixelRatio);
14867 }
14868 
14869 /*!
14870   This method returns whether any of the paint buffers held by this QCustomPlot instance are
14871   invalidated.
14872 
14873   If any buffer is invalidated, a partial replot (\ref QCPLayer::replot) is not allowed and always
14874   causes a full replot (\ref QCustomPlot::replot) of all layers. This is the case when for example
14875   the layer order has changed, new layers were added, layers were removed, or layer modes were
14876   changed (\ref QCPLayer::setMode).
14877 
14878   \see QCPAbstractPaintBuffer::setInvalidated
14879 */
hasInvalidatedPaintBuffers()14880 bool QCustomPlot::hasInvalidatedPaintBuffers()
14881 {
14882   for (int i=0; i<mPaintBuffers.size(); ++i)
14883   {
14884     if (mPaintBuffers.at(i)->invalidated())
14885       return true;
14886   }
14887   return false;
14888 }
14889 
14890 /*! \internal
14891 
14892   When \ref setOpenGl is set to true, this method is used to initialize OpenGL (create a context,
14893   surface, paint device).
14894 
14895   Returns true on success.
14896 
14897   If this method is successful, all paint buffers should be deleted and then reallocated by calling
14898   \ref setupPaintBuffers, so the OpenGL-based paint buffer subclasses (\ref
14899   QCPPaintBufferGlPbuffer, \ref QCPPaintBufferGlFbo) are used for subsequent replots.
14900 
14901   \see freeOpenGl
14902 */
setupOpenGl()14903 bool QCustomPlot::setupOpenGl()
14904 {
14905 #ifdef QCP_OPENGL_FBO
14906   freeOpenGl();
14907   QSurfaceFormat proposedSurfaceFormat;
14908   proposedSurfaceFormat.setSamples(mOpenGlMultisamples);
14909 #ifdef QCP_OPENGL_OFFSCREENSURFACE
14910   QOffscreenSurface *surface = new QOffscreenSurface;
14911 #else
14912   QWindow *surface = new QWindow;
14913   surface->setSurfaceType(QSurface::OpenGLSurface);
14914 #endif
14915   surface->setFormat(proposedSurfaceFormat);
14916   surface->create();
14917   mGlSurface = QSharedPointer<QSurface>(surface);
14918   mGlContext = QSharedPointer<QOpenGLContext>(new QOpenGLContext);
14919   mGlContext->setFormat(mGlSurface->format());
14920   if (!mGlContext->create())
14921   {
14922     qDebug() << Q_FUNC_INFO << "Failed to create OpenGL context";
14923     mGlContext.clear();
14924     mGlSurface.clear();
14925     return false;
14926   }
14927   if (!mGlContext->makeCurrent(mGlSurface.data())) // context needs to be current to create paint device
14928   {
14929     qDebug() << Q_FUNC_INFO << "Failed to make opengl context current";
14930     mGlContext.clear();
14931     mGlSurface.clear();
14932     return false;
14933   }
14934   if (!QOpenGLFramebufferObject::hasOpenGLFramebufferObjects())
14935   {
14936     qDebug() << Q_FUNC_INFO << "OpenGL of this system doesn't support frame buffer objects";
14937     mGlContext.clear();
14938     mGlSurface.clear();
14939     return false;
14940   }
14941   mGlPaintDevice = QSharedPointer<QOpenGLPaintDevice>(new QOpenGLPaintDevice);
14942   return true;
14943 #elif defined(QCP_OPENGL_PBUFFER)
14944   return QGLFormat::hasOpenGL();
14945 #else
14946   return false;
14947 #endif
14948 }
14949 
14950 /*! \internal
14951 
14952   When \ref setOpenGl is set to false, this method is used to deinitialize OpenGL (releases the
14953   context and frees resources).
14954 
14955   After OpenGL is disabled, all paint buffers should be deleted and then reallocated by calling
14956   \ref setupPaintBuffers, so the standard software rendering paint buffer subclass (\ref
14957   QCPPaintBufferPixmap) is used for subsequent replots.
14958 
14959   \see setupOpenGl
14960 */
freeOpenGl()14961 void QCustomPlot::freeOpenGl()
14962 {
14963 #ifdef QCP_OPENGL_FBO
14964   mGlPaintDevice.clear();
14965   mGlContext.clear();
14966   mGlSurface.clear();
14967 #endif
14968 }
14969 
14970 /*! \internal
14971 
14972   This method is used by \ref QCPAxisRect::removeAxis to report removed axes to the QCustomPlot
14973   so it may clear its QCustomPlot::xAxis, yAxis, xAxis2 and yAxis2 members accordingly.
14974 */
axisRemoved(QCPAxis * axis)14975 void QCustomPlot::axisRemoved(QCPAxis *axis)
14976 {
14977   if (xAxis == axis)
14978     xAxis = 0;
14979   if (xAxis2 == axis)
14980     xAxis2 = 0;
14981   if (yAxis == axis)
14982     yAxis = 0;
14983   if (yAxis2 == axis)
14984     yAxis2 = 0;
14985 
14986   // Note: No need to take care of range drag axes and range zoom axes, because they are stored in smart pointers
14987 }
14988 
14989 /*! \internal
14990 
14991   This method is used by the QCPLegend destructor to report legend removal to the QCustomPlot so
14992   it may clear its QCustomPlot::legend member accordingly.
14993 */
legendRemoved(QCPLegend * legend)14994 void QCustomPlot::legendRemoved(QCPLegend *legend)
14995 {
14996   if (this->legend == legend)
14997     this->legend = 0;
14998 }
14999 
15000 /*! \internal
15001 
15002   This slot is connected to the selection rect's \ref QCPSelectionRect::accepted signal when \ref
15003   setSelectionRectMode is set to \ref QCP::srmSelect.
15004 
15005   First, it determines which axis rect was the origin of the selection rect judging by the starting
15006   point of the selection. Then it goes through the plottables (\ref QCPAbstractPlottable1D to be
15007   precise) associated with that axis rect and finds the data points that are in \a rect. It does
15008   this by querying their \ref QCPAbstractPlottable1D::selectTestRect method.
15009 
15010   Then, the actual selection is done by calling the plottables' \ref
15011   QCPAbstractPlottable::selectEvent, placing the found selected data points in the \a details
15012   parameter as <tt>QVariant(\ref QCPDataSelection)</tt>. All plottables that weren't touched by \a
15013   rect receive a \ref QCPAbstractPlottable::deselectEvent.
15014 
15015   \see processRectZoom
15016 */
processRectSelection(QRect rect,QMouseEvent * event)15017 void QCustomPlot::processRectSelection(QRect rect, QMouseEvent *event)
15018 {
15019   bool selectionStateChanged = false;
15020 
15021   if (mInteractions.testFlag(QCP::iSelectPlottables))
15022   {
15023     QMultiMap<int, QPair<QCPAbstractPlottable*, QCPDataSelection> > potentialSelections; // map key is number of selected data points, so we have selections sorted by size
15024     QRectF rectF(rect.normalized());
15025     if (QCPAxisRect *affectedAxisRect = axisRectAt(rectF.topLeft()))
15026     {
15027       // determine plottables that were hit by the rect and thus are candidates for selection:
15028       foreach (QCPAbstractPlottable *plottable, affectedAxisRect->plottables())
15029       {
15030         if (QCPPlottableInterface1D *plottableInterface = plottable->interface1D())
15031         {
15032           QCPDataSelection dataSel = plottableInterface->selectTestRect(rectF, true);
15033           if (!dataSel.isEmpty())
15034             potentialSelections.insert(dataSel.dataPointCount(), QPair<QCPAbstractPlottable*, QCPDataSelection>(plottable, dataSel));
15035         }
15036       }
15037 
15038       if (!mInteractions.testFlag(QCP::iMultiSelect))
15039       {
15040         // only leave plottable with most selected points in map, since we will only select a single plottable:
15041         if (!potentialSelections.isEmpty())
15042         {
15043           QMultiMap<int, QPair<QCPAbstractPlottable*, QCPDataSelection> >::iterator it = potentialSelections.begin();
15044           while (it != potentialSelections.end()-1) // erase all except last element
15045             it = potentialSelections.erase(it);
15046         }
15047       }
15048 
15049       bool additive = event->modifiers().testFlag(mMultiSelectModifier);
15050       // deselect all other layerables if not additive selection:
15051       if (!additive)
15052       {
15053         // emit deselection except to those plottables who will be selected afterwards:
15054         foreach (QCPLayer *layer, mLayers)
15055         {
15056           foreach (QCPLayerable *layerable, layer->children())
15057           {
15058             if ((potentialSelections.isEmpty() || potentialSelections.constBegin()->first != layerable) && mInteractions.testFlag(layerable->selectionCategory()))
15059             {
15060               bool selChanged = false;
15061               layerable->deselectEvent(&selChanged);
15062               selectionStateChanged |= selChanged;
15063             }
15064           }
15065         }
15066       }
15067 
15068       // go through selections in reverse (largest selection first) and emit select events:
15069       QMultiMap<int, QPair<QCPAbstractPlottable*, QCPDataSelection> >::const_iterator it = potentialSelections.constEnd();
15070       while (it != potentialSelections.constBegin())
15071       {
15072         --it;
15073         if (mInteractions.testFlag(it.value().first->selectionCategory()))
15074         {
15075           bool selChanged = false;
15076           it.value().first->selectEvent(event, additive, QVariant::fromValue(it.value().second), &selChanged);
15077           selectionStateChanged |= selChanged;
15078         }
15079       }
15080     }
15081   }
15082 
15083   if (selectionStateChanged)
15084   {
15085     emit selectionChangedByUser();
15086     replot(rpQueuedReplot);
15087   } else if (mSelectionRect)
15088     mSelectionRect->layer()->replot();
15089 }
15090 
15091 /*! \internal
15092 
15093   This slot is connected to the selection rect's \ref QCPSelectionRect::accepted signal when \ref
15094   setSelectionRectMode is set to \ref QCP::srmZoom.
15095 
15096   It determines which axis rect was the origin of the selection rect judging by the starting point
15097   of the selection, and then zooms the axes defined via \ref QCPAxisRect::setRangeZoomAxes to the
15098   provided \a rect (see \ref QCPAxisRect::zoom).
15099 
15100   \see processRectSelection
15101 */
processRectZoom(QRect rect,QMouseEvent * event)15102 void QCustomPlot::processRectZoom(QRect rect, QMouseEvent *event)
15103 {
15104   Q_UNUSED(event)
15105   if (QCPAxisRect *axisRect = axisRectAt(rect.topLeft()))
15106   {
15107     QList<QCPAxis*> affectedAxes = QList<QCPAxis*>() << axisRect->rangeZoomAxes(Qt::Horizontal) << axisRect->rangeZoomAxes(Qt::Vertical);
15108     affectedAxes.removeAll(static_cast<QCPAxis*>(0));
15109     axisRect->zoom(QRectF(rect), affectedAxes);
15110   }
15111   replot(rpQueuedReplot); // always replot to make selection rect disappear
15112 }
15113 
15114 /*! \internal
15115 
15116   This method is called when a simple left mouse click was detected on the QCustomPlot surface.
15117 
15118   It first determines the layerable that was hit by the click, and then calls its \ref
15119   QCPLayerable::selectEvent. All other layerables receive a QCPLayerable::deselectEvent (unless the
15120   multi-select modifier was pressed, see \ref setMultiSelectModifier).
15121 
15122   In this method the hit layerable is determined a second time using \ref layerableAt (after the
15123   one in \ref mousePressEvent), because we want \a onlySelectable set to true this time. This
15124   implies that the mouse event grabber (mMouseEventLayerable) may be a different one from the
15125   clicked layerable determined here. For example, if a non-selectable layerable is in front of a
15126   selectable layerable at the click position, the front layerable will receive mouse events but the
15127   selectable one in the back will receive the \ref QCPLayerable::selectEvent.
15128 
15129   \see processRectSelection, QCPLayerable::selectTest
15130 */
processPointSelection(QMouseEvent * event)15131 void QCustomPlot::processPointSelection(QMouseEvent *event)
15132 {
15133   QVariant details;
15134   QCPLayerable *clickedLayerable = layerableAt(event->pos(), true, &details);
15135   bool selectionStateChanged = false;
15136   bool additive = mInteractions.testFlag(QCP::iMultiSelect) && event->modifiers().testFlag(mMultiSelectModifier);
15137   // deselect all other layerables if not additive selection:
15138   if (!additive)
15139   {
15140     foreach (QCPLayer *layer, mLayers)
15141     {
15142       foreach (QCPLayerable *layerable, layer->children())
15143       {
15144         if (layerable != clickedLayerable && mInteractions.testFlag(layerable->selectionCategory()))
15145         {
15146           bool selChanged = false;
15147           layerable->deselectEvent(&selChanged);
15148           selectionStateChanged |= selChanged;
15149         }
15150       }
15151     }
15152   }
15153   if (clickedLayerable && mInteractions.testFlag(clickedLayerable->selectionCategory()))
15154   {
15155     // a layerable was actually clicked, call its selectEvent:
15156     bool selChanged = false;
15157     clickedLayerable->selectEvent(event, additive, details, &selChanged);
15158     selectionStateChanged |= selChanged;
15159   }
15160   if (selectionStateChanged)
15161   {
15162     emit selectionChangedByUser();
15163     replot(rpQueuedReplot);
15164   }
15165 }
15166 
15167 /*! \internal
15168 
15169   Registers the specified plottable with this QCustomPlot and, if \ref setAutoAddPlottableToLegend
15170   is enabled, adds it to the legend (QCustomPlot::legend). QCustomPlot takes ownership of the
15171   plottable.
15172 
15173   Returns true on success, i.e. when \a plottable isn't already in this plot and the parent plot of
15174   \a plottable is this QCustomPlot.
15175 
15176   This method is called automatically in the QCPAbstractPlottable base class constructor.
15177 */
registerPlottable(QCPAbstractPlottable * plottable)15178 bool QCustomPlot::registerPlottable(QCPAbstractPlottable *plottable)
15179 {
15180   if (mPlottables.contains(plottable))
15181   {
15182     qDebug() << Q_FUNC_INFO << "plottable already added to this QCustomPlot:" << reinterpret_cast<quintptr>(plottable);
15183     return false;
15184   }
15185   if (plottable->parentPlot() != this)
15186   {
15187     qDebug() << Q_FUNC_INFO << "plottable not created with this QCustomPlot as parent:" << reinterpret_cast<quintptr>(plottable);
15188     return false;
15189   }
15190 
15191   mPlottables.append(plottable);
15192   // possibly add plottable to legend:
15193   if (mAutoAddPlottableToLegend)
15194     plottable->addToLegend();
15195   if (!plottable->layer()) // usually the layer is already set in the constructor of the plottable (via QCPLayerable constructor)
15196     plottable->setLayer(currentLayer());
15197   return true;
15198 }
15199 
15200 /*! \internal
15201 
15202   In order to maintain the simplified graph interface of QCustomPlot, this method is called by the
15203   QCPGraph constructor to register itself with this QCustomPlot's internal graph list. Returns true
15204   on success, i.e. if \a graph is valid and wasn't already registered with this QCustomPlot.
15205 
15206   This graph specific registration happens in addition to the call to \ref registerPlottable by the
15207   QCPAbstractPlottable base class.
15208 */
registerGraph(QCPGraph * graph)15209 bool QCustomPlot::registerGraph(QCPGraph *graph)
15210 {
15211   if (!graph)
15212   {
15213     qDebug() << Q_FUNC_INFO << "passed graph is zero";
15214     return false;
15215   }
15216   if (mGraphs.contains(graph))
15217   {
15218     qDebug() << Q_FUNC_INFO << "graph already registered with this QCustomPlot";
15219     return false;
15220   }
15221 
15222   mGraphs.append(graph);
15223   return true;
15224 }
15225 
15226 
15227 /*! \internal
15228 
15229   Registers the specified item with this QCustomPlot. QCustomPlot takes ownership of the item.
15230 
15231   Returns true on success, i.e. when \a item wasn't already in the plot and the parent plot of \a
15232   item is this QCustomPlot.
15233 
15234   This method is called automatically in the QCPAbstractItem base class constructor.
15235 */
registerItem(QCPAbstractItem * item)15236 bool QCustomPlot::registerItem(QCPAbstractItem *item)
15237 {
15238   if (mItems.contains(item))
15239   {
15240     qDebug() << Q_FUNC_INFO << "item already added to this QCustomPlot:" << reinterpret_cast<quintptr>(item);
15241     return false;
15242   }
15243   if (item->parentPlot() != this)
15244   {
15245     qDebug() << Q_FUNC_INFO << "item not created with this QCustomPlot as parent:" << reinterpret_cast<quintptr>(item);
15246     return false;
15247   }
15248 
15249   mItems.append(item);
15250   if (!item->layer()) // usually the layer is already set in the constructor of the item (via QCPLayerable constructor)
15251     item->setLayer(currentLayer());
15252   return true;
15253 }
15254 
15255 /*! \internal
15256 
15257   Assigns all layers their index (QCPLayer::mIndex) in the mLayers list. This method is thus called
15258   after every operation that changes the layer indices, like layer removal, layer creation, layer
15259   moving.
15260 */
updateLayerIndices() const15261 void QCustomPlot::updateLayerIndices() const
15262 {
15263   for (int i=0; i<mLayers.size(); ++i)
15264     mLayers.at(i)->mIndex = i;
15265 }
15266 
15267 /*! \internal
15268 
15269   Returns the top-most layerable at pixel position \a pos. If \a onlySelectable is set to true,
15270   only those layerables that are selectable will be considered. (Layerable subclasses communicate
15271   their selectability via the QCPLayerable::selectTest method, by returning -1.)
15272 
15273   \a selectionDetails is an output parameter that contains selection specifics of the affected
15274   layerable. This is useful if the respective layerable shall be given a subsequent
15275   QCPLayerable::selectEvent (like in \ref mouseReleaseEvent). \a selectionDetails usually contains
15276   information about which part of the layerable was hit, in multi-part layerables (e.g.
15277   QCPAxis::SelectablePart). If the layerable is a plottable, \a selectionDetails contains a \ref
15278   QCPDataSelection instance with the single data point which is closest to \a pos.
15279 
15280   \see layerableListAt, layoutElementAt, axisRectAt
15281 */
layerableAt(const QPointF & pos,bool onlySelectable,QVariant * selectionDetails) const15282 QCPLayerable *QCustomPlot::layerableAt(const QPointF &pos, bool onlySelectable, QVariant *selectionDetails) const
15283 {
15284   QList<QVariant> details;
15285   QList<QCPLayerable*> candidates = layerableListAt(pos, onlySelectable, selectionDetails ? &details : 0);
15286   if (selectionDetails && !details.isEmpty())
15287     *selectionDetails = details.first();
15288   if (!candidates.isEmpty())
15289     return candidates.first();
15290   else
15291     return 0;
15292 }
15293 
15294 /*! \internal
15295 
15296   Returns the layerables at pixel position \a pos. If \a onlySelectable is set to true, only those
15297   layerables that are selectable will be considered. (Layerable subclasses communicate their
15298   selectability via the QCPLayerable::selectTest method, by returning -1.)
15299 
15300   The returned list is sorted by the layerable/drawing order. If you only need to know the top-most
15301   layerable, rather use \ref layerableAt.
15302 
15303   \a selectionDetails is an output parameter that contains selection specifics of the affected
15304   layerable. This is useful if the respective layerable shall be given a subsequent
15305   QCPLayerable::selectEvent (like in \ref mouseReleaseEvent). \a selectionDetails usually contains
15306   information about which part of the layerable was hit, in multi-part layerables (e.g.
15307   QCPAxis::SelectablePart). If the layerable is a plottable, \a selectionDetails contains a \ref
15308   QCPDataSelection instance with the single data point which is closest to \a pos.
15309 
15310   \see layerableAt, layoutElementAt, axisRectAt
15311 */
layerableListAt(const QPointF & pos,bool onlySelectable,QList<QVariant> * selectionDetails) const15312 QList<QCPLayerable*> QCustomPlot::layerableListAt(const QPointF &pos, bool onlySelectable, QList<QVariant> *selectionDetails) const
15313 {
15314   QList<QCPLayerable*> result;
15315   for (int layerIndex=mLayers.size()-1; layerIndex>=0; --layerIndex)
15316   {
15317     const QList<QCPLayerable*> layerables = mLayers.at(layerIndex)->children();
15318     for (int i=layerables.size()-1; i>=0; --i)
15319     {
15320       if (!layerables.at(i)->realVisibility())
15321         continue;
15322       QVariant details;
15323       double dist = layerables.at(i)->selectTest(pos, onlySelectable, selectionDetails ? &details : 0);
15324       if (dist >= 0 && dist < selectionTolerance())
15325       {
15326         result.append(layerables.at(i));
15327         if (selectionDetails)
15328           selectionDetails->append(details);
15329       }
15330     }
15331   }
15332   return result;
15333 }
15334 
15335 /*!
15336   Saves the plot to a rastered image file \a fileName in the image format \a format. The plot is
15337   sized to \a width and \a height in pixels and scaled with \a scale. (width 100 and scale 2.0 lead
15338   to a full resolution file with width 200.) If the \a format supports compression, \a quality may
15339   be between 0 and 100 to control it.
15340 
15341   Returns true on success. If this function fails, most likely the given \a format isn't supported
15342   by the system, see Qt docs about QImageWriter::supportedImageFormats().
15343 
15344   The \a resolution will be written to the image file header (if the file format supports this) and
15345   has no direct consequence for the quality or the pixel size. However, if opening the image with a
15346   tool which respects the metadata, it will be able to scale the image to match either a given size
15347   in real units of length (inch, centimeters, etc.), or the target display DPI. You can specify in
15348   which units \a resolution is given, by setting \a resolutionUnit. The \a resolution is converted
15349   to the format's expected resolution unit internally.
15350 
15351   \see saveBmp, saveJpg, savePng, savePdf
15352 */
saveRastered(const QString & fileName,int width,int height,double scale,const char * format,int quality,int resolution,QCP::ResolutionUnit resolutionUnit)15353 bool QCustomPlot::saveRastered(const QString &fileName, int width, int height, double scale, const char *format, int quality, int resolution, QCP::ResolutionUnit resolutionUnit)
15354 {
15355   QImage buffer = toPixmap(width, height, scale).toImage();
15356 
15357   int dotsPerMeter = 0;
15358   switch (resolutionUnit)
15359   {
15360     case QCP::ruDotsPerMeter: dotsPerMeter = resolution; break;
15361     case QCP::ruDotsPerCentimeter: dotsPerMeter = resolution*100; break;
15362     case QCP::ruDotsPerInch: dotsPerMeter = resolution/0.0254; break;
15363   }
15364   buffer.setDotsPerMeterX(dotsPerMeter); // this is saved together with some image formats, e.g. PNG, and is relevant when opening image in other tools
15365   buffer.setDotsPerMeterY(dotsPerMeter); // this is saved together with some image formats, e.g. PNG, and is relevant when opening image in other tools
15366   if (!buffer.isNull())
15367     return buffer.save(fileName, format, quality);
15368   else
15369     return false;
15370 }
15371 
15372 /*!
15373   Renders the plot to a pixmap and returns it.
15374 
15375   The plot is sized to \a width and \a height in pixels and scaled with \a scale. (width 100 and
15376   scale 2.0 lead to a full resolution pixmap with width 200.)
15377 
15378   \see toPainter, saveRastered, saveBmp, savePng, saveJpg, savePdf
15379 */
toPixmap(int width,int height,double scale)15380 QPixmap QCustomPlot::toPixmap(int width, int height, double scale)
15381 {
15382   // this method is somewhat similar to toPainter. Change something here, and a change in toPainter might be necessary, too.
15383   int newWidth, newHeight;
15384   if (width == 0 || height == 0)
15385   {
15386     newWidth = this->width();
15387     newHeight = this->height();
15388   } else
15389   {
15390     newWidth = width;
15391     newHeight = height;
15392   }
15393   int scaledWidth = qRound(scale*newWidth);
15394   int scaledHeight = qRound(scale*newHeight);
15395 
15396   QPixmap result(scaledWidth, scaledHeight);
15397   result.fill(mBackgroundBrush.style() == Qt::SolidPattern ? mBackgroundBrush.color() : Qt::transparent); // if using non-solid pattern, make transparent now and draw brush pattern later
15398   QCPPainter painter;
15399   painter.begin(&result);
15400   if (painter.isActive())
15401   {
15402     QRect oldViewport = viewport();
15403     setViewport(QRect(0, 0, newWidth, newHeight));
15404     painter.setMode(QCPPainter::pmNoCaching);
15405     if (!qFuzzyCompare(scale, 1.0))
15406     {
15407       if (scale > 1.0) // for scale < 1 we always want cosmetic pens where possible, because else lines might disappear for very small scales
15408         painter.setMode(QCPPainter::pmNonCosmetic);
15409       painter.scale(scale, scale);
15410     }
15411     if (mBackgroundBrush.style() != Qt::SolidPattern && mBackgroundBrush.style() != Qt::NoBrush) // solid fills were done a few lines above with QPixmap::fill
15412       painter.fillRect(mViewport, mBackgroundBrush);
15413     draw(&painter);
15414     setViewport(oldViewport);
15415     painter.end();
15416   } else // might happen if pixmap has width or height zero
15417   {
15418     qDebug() << Q_FUNC_INFO << "Couldn't activate painter on pixmap";
15419     return QPixmap();
15420   }
15421   return result;
15422 }
15423 
15424 /*!
15425   Renders the plot using the passed \a painter.
15426 
15427   The plot is sized to \a width and \a height in pixels. If the \a painter's scale is not 1.0, the resulting plot will
15428   appear scaled accordingly.
15429 
15430   \note If you are restricted to using a QPainter (instead of QCPPainter), create a temporary QPicture and open a QCPPainter
15431   on it. Then call \ref toPainter with this QCPPainter. After ending the paint operation on the picture, draw it with
15432   the QPainter. This will reproduce the painter actions the QCPPainter took, with a QPainter.
15433 
15434   \see toPixmap
15435 */
toPainter(QCPPainter * painter,int width,int height)15436 void QCustomPlot::toPainter(QCPPainter *painter, int width, int height)
15437 {
15438   // this method is somewhat similar to toPixmap. Change something here, and a change in toPixmap might be necessary, too.
15439   int newWidth, newHeight;
15440   if (width == 0 || height == 0)
15441   {
15442     newWidth = this->width();
15443     newHeight = this->height();
15444   } else
15445   {
15446     newWidth = width;
15447     newHeight = height;
15448   }
15449 
15450   if (painter->isActive())
15451   {
15452     QRect oldViewport = viewport();
15453     setViewport(QRect(0, 0, newWidth, newHeight));
15454     painter->setMode(QCPPainter::pmNoCaching);
15455     if (mBackgroundBrush.style() != Qt::NoBrush) // unlike in toPixmap, we can't do QPixmap::fill for Qt::SolidPattern brush style, so we also draw solid fills with fillRect here
15456       painter->fillRect(mViewport, mBackgroundBrush);
15457     draw(painter);
15458     setViewport(oldViewport);
15459   } else
15460     qDebug() << Q_FUNC_INFO << "Passed painter is not active";
15461 }
15462 /* end of 'src/core.cpp' */
15463 
15464 //amalgamation: add plottable1d.cpp
15465 
15466 /* including file 'src/colorgradient.cpp', size 24646                        */
15467 /* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
15468 
15469 
15470 ////////////////////////////////////////////////////////////////////////////////////////////////////
15471 //////////////////// QCPColorGradient
15472 ////////////////////////////////////////////////////////////////////////////////////////////////////
15473 
15474 /*! \class QCPColorGradient
15475   \brief Defines a color gradient for use with e.g. \ref QCPColorMap
15476 
15477   This class describes a color gradient which can be used to encode data with color. For example,
15478   QCPColorMap and QCPColorScale have \ref QCPColorMap::setGradient "setGradient" methods which
15479   take an instance of this class. Colors are set with \ref setColorStopAt(double position, const QColor &color)
15480   with a \a position from 0 to 1. In between these defined color positions, the
15481   color will be interpolated linearly either in RGB or HSV space, see \ref setColorInterpolation.
15482 
15483   Alternatively, load one of the preset color gradients shown in the image below, with \ref
15484   loadPreset, or by directly specifying the preset in the constructor.
15485 
15486   Apart from red, green and blue components, the gradient also interpolates the alpha values of the
15487   configured color stops. This allows to display some portions of the data range as transparent in
15488   the plot.
15489 
15490   \image html QCPColorGradient.png
15491 
15492   The \ref QCPColorGradient(GradientPreset preset) constructor allows directly converting a \ref
15493   GradientPreset to a QCPColorGradient. This means that you can directly pass \ref GradientPreset
15494   to all the \a setGradient methods, e.g.:
15495   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolorgradient-setgradient
15496 
15497   The total number of levels used in the gradient can be set with \ref setLevelCount. Whether the
15498   color gradient shall be applied periodically (wrapping around) to data values that lie outside
15499   the data range specified on the plottable instance can be controlled with \ref setPeriodic.
15500 */
15501 
15502 /*!
15503   Constructs a new, empty QCPColorGradient with no predefined color stops. You can add own color
15504   stops with \ref setColorStopAt.
15505 
15506   The color level count is initialized to 350.
15507 */
QCPColorGradient()15508 QCPColorGradient::QCPColorGradient() :
15509   mLevelCount(350),
15510   mColorInterpolation(ciRGB),
15511   mPeriodic(false),
15512   mColorBufferInvalidated(true)
15513 {
15514   mColorBuffer.fill(qRgb(0, 0, 0), mLevelCount);
15515 }
15516 
15517 /*!
15518   Constructs a new QCPColorGradient initialized with the colors and color interpolation according
15519   to \a preset.
15520 
15521   The color level count is initialized to 350.
15522 */
QCPColorGradient(GradientPreset preset)15523 QCPColorGradient::QCPColorGradient(GradientPreset preset) :
15524   mLevelCount(350),
15525   mColorInterpolation(ciRGB),
15526   mPeriodic(false),
15527   mColorBufferInvalidated(true)
15528 {
15529   mColorBuffer.fill(qRgb(0, 0, 0), mLevelCount);
15530   loadPreset(preset);
15531 }
15532 
15533 /* undocumented operator */
operator ==(const QCPColorGradient & other) const15534 bool QCPColorGradient::operator==(const QCPColorGradient &other) const
15535 {
15536   return ((other.mLevelCount == this->mLevelCount) &&
15537           (other.mColorInterpolation == this->mColorInterpolation) &&
15538           (other.mPeriodic == this->mPeriodic) &&
15539           (other.mColorStops == this->mColorStops));
15540 }
15541 
15542 /*!
15543   Sets the number of discretization levels of the color gradient to \a n. The default is 350 which
15544   is typically enough to create a smooth appearance. The minimum number of levels is 2.
15545 
15546   \image html QCPColorGradient-levelcount.png
15547 */
setLevelCount(int n)15548 void QCPColorGradient::setLevelCount(int n)
15549 {
15550   if (n < 2)
15551   {
15552     qDebug() << Q_FUNC_INFO << "n must be greater or equal 2 but was" << n;
15553     n = 2;
15554   }
15555   if (n != mLevelCount)
15556   {
15557     mLevelCount = n;
15558     mColorBufferInvalidated = true;
15559   }
15560 }
15561 
15562 /*!
15563   Sets at which positions from 0 to 1 which color shall occur. The positions are the keys, the
15564   colors are the values of the passed QMap \a colorStops. In between these color stops, the color
15565   is interpolated according to \ref setColorInterpolation.
15566 
15567   A more convenient way to create a custom gradient may be to clear all color stops with \ref
15568   clearColorStops (or creating a new, empty QCPColorGradient) and then adding them one by one with
15569   \ref setColorStopAt.
15570 
15571   \see clearColorStops
15572 */
setColorStops(const QMap<double,QColor> & colorStops)15573 void QCPColorGradient::setColorStops(const QMap<double, QColor> &colorStops)
15574 {
15575   mColorStops = colorStops;
15576   mColorBufferInvalidated = true;
15577 }
15578 
15579 /*!
15580   Sets the \a color the gradient will have at the specified \a position (from 0 to 1). In between
15581   these color stops, the color is interpolated according to \ref setColorInterpolation.
15582 
15583   \see setColorStops, clearColorStops
15584 */
setColorStopAt(double position,const QColor & color)15585 void QCPColorGradient::setColorStopAt(double position, const QColor &color)
15586 {
15587   mColorStops.insert(position, color);
15588   mColorBufferInvalidated = true;
15589 }
15590 
15591 /*!
15592   Sets whether the colors in between the configured color stops (see \ref setColorStopAt) shall be
15593   interpolated linearly in RGB or in HSV color space.
15594 
15595   For example, a sweep in RGB space from red to green will have a muddy brown intermediate color,
15596   whereas in HSV space the intermediate color is yellow.
15597 */
setColorInterpolation(QCPColorGradient::ColorInterpolation interpolation)15598 void QCPColorGradient::setColorInterpolation(QCPColorGradient::ColorInterpolation interpolation)
15599 {
15600   if (interpolation != mColorInterpolation)
15601   {
15602     mColorInterpolation = interpolation;
15603     mColorBufferInvalidated = true;
15604   }
15605 }
15606 
15607 /*!
15608   Sets whether data points that are outside the configured data range (e.g. \ref
15609   QCPColorMap::setDataRange) are colored by periodically repeating the color gradient or whether
15610   they all have the same color, corresponding to the respective gradient boundary color.
15611 
15612   \image html QCPColorGradient-periodic.png
15613 
15614   As shown in the image above, gradients that have the same start and end color are especially
15615   suitable for a periodic gradient mapping, since they produce smooth color transitions throughout
15616   the color map. A preset that has this property is \ref gpHues.
15617 
15618   In practice, using periodic color gradients makes sense when the data corresponds to a periodic
15619   dimension, such as an angle or a phase. If this is not the case, the color encoding might become
15620   ambiguous, because multiple different data values are shown as the same color.
15621 */
setPeriodic(bool enabled)15622 void QCPColorGradient::setPeriodic(bool enabled)
15623 {
15624   mPeriodic = enabled;
15625 }
15626 
15627 /*! \overload
15628 
15629   This method is used to quickly convert a \a data array to colors. The colors will be output in
15630   the array \a scanLine. Both \a data and \a scanLine must have the length \a n when passed to this
15631   function. The data range that shall be used for mapping the data value to the gradient is passed
15632   in \a range. \a logarithmic indicates whether the data values shall be mapped to colors
15633   logarithmically.
15634 
15635   if \a data actually contains 2D-data linearized via <tt>[row*columnCount + column]</tt>, you can
15636   set \a dataIndexFactor to <tt>columnCount</tt> to convert a column instead of a row of the data
15637   array, in \a scanLine. \a scanLine will remain a regular (1D) array. This works because \a data
15638   is addressed <tt>data[i*dataIndexFactor]</tt>.
15639 
15640   Use the overloaded method to additionally provide alpha map data.
15641 
15642   The QRgb values that are placed in \a scanLine have their r, g and b components premultiplied
15643   with alpha (see QImage::Format_ARGB32_Premultiplied).
15644 */
colorize(const double * data,const QCPRange & range,QRgb * scanLine,int n,int dataIndexFactor,bool logarithmic)15645 void QCPColorGradient::colorize(const double *data, const QCPRange &range, QRgb *scanLine, int n, int dataIndexFactor, bool logarithmic)
15646 {
15647   // If you change something here, make sure to also adapt color() and the other colorize() overload
15648   if (!data)
15649   {
15650     qDebug() << Q_FUNC_INFO << "null pointer given as data";
15651     return;
15652   }
15653   if (!scanLine)
15654   {
15655     qDebug() << Q_FUNC_INFO << "null pointer given as scanLine";
15656     return;
15657   }
15658   if (mColorBufferInvalidated)
15659     updateColorBuffer();
15660 
15661   if (!logarithmic)
15662   {
15663     const double posToIndexFactor = (mLevelCount-1)/range.size();
15664     if (mPeriodic)
15665     {
15666       for (int i=0; i<n; ++i)
15667       {
15668         int index = (int)((data[dataIndexFactor*i]-range.lower)*posToIndexFactor) % mLevelCount;
15669         if (index < 0)
15670           index += mLevelCount;
15671         scanLine[i] = mColorBuffer.at(index);
15672       }
15673     } else
15674     {
15675       for (int i=0; i<n; ++i)
15676       {
15677         int index = (data[dataIndexFactor*i]-range.lower)*posToIndexFactor;
15678         if (index < 0)
15679           index = 0;
15680         else if (index >= mLevelCount)
15681           index = mLevelCount-1;
15682         scanLine[i] = mColorBuffer.at(index);
15683       }
15684     }
15685   } else // logarithmic == true
15686   {
15687     if (mPeriodic)
15688     {
15689       for (int i=0; i<n; ++i)
15690       {
15691         int index = (int)(qLn(data[dataIndexFactor*i]/range.lower)/qLn(range.upper/range.lower)*(mLevelCount-1)) % mLevelCount;
15692         if (index < 0)
15693           index += mLevelCount;
15694         scanLine[i] = mColorBuffer.at(index);
15695       }
15696     } else
15697     {
15698       for (int i=0; i<n; ++i)
15699       {
15700         int index = qLn(data[dataIndexFactor*i]/range.lower)/qLn(range.upper/range.lower)*(mLevelCount-1);
15701         if (index < 0)
15702           index = 0;
15703         else if (index >= mLevelCount)
15704           index = mLevelCount-1;
15705         scanLine[i] = mColorBuffer.at(index);
15706       }
15707     }
15708   }
15709 }
15710 
15711 /*! \overload
15712 
15713   Additionally to the other overload of \ref colorize, this method takes the array \a alpha, which
15714   has the same size and structure as \a data and encodes the alpha information per data point.
15715 
15716   The QRgb values that are placed in \a scanLine have their r, g and b components premultiplied
15717   with alpha (see QImage::Format_ARGB32_Premultiplied).
15718 */
colorize(const double * data,const unsigned char * alpha,const QCPRange & range,QRgb * scanLine,int n,int dataIndexFactor,bool logarithmic)15719 void QCPColorGradient::colorize(const double *data, const unsigned char *alpha, const QCPRange &range, QRgb *scanLine, int n, int dataIndexFactor, bool logarithmic)
15720 {
15721   // If you change something here, make sure to also adapt color() and the other colorize() overload
15722   if (!data)
15723   {
15724     qDebug() << Q_FUNC_INFO << "null pointer given as data";
15725     return;
15726   }
15727   if (!alpha)
15728   {
15729     qDebug() << Q_FUNC_INFO << "null pointer given as alpha";
15730     return;
15731   }
15732   if (!scanLine)
15733   {
15734     qDebug() << Q_FUNC_INFO << "null pointer given as scanLine";
15735     return;
15736   }
15737   if (mColorBufferInvalidated)
15738     updateColorBuffer();
15739 
15740   if (!logarithmic)
15741   {
15742     const double posToIndexFactor = (mLevelCount-1)/range.size();
15743     if (mPeriodic)
15744     {
15745       for (int i=0; i<n; ++i)
15746       {
15747         int index = (int)((data[dataIndexFactor*i]-range.lower)*posToIndexFactor) % mLevelCount;
15748         if (index < 0)
15749           index += mLevelCount;
15750         if (alpha[dataIndexFactor*i] == 255)
15751         {
15752           scanLine[i] = mColorBuffer.at(index);
15753         } else
15754         {
15755           const QRgb rgb = mColorBuffer.at(index);
15756           const float alphaF = alpha[dataIndexFactor*i]/255.0f;
15757           scanLine[i] = qRgba(qRed(rgb)*alphaF, qGreen(rgb)*alphaF, qBlue(rgb)*alphaF, qAlpha(rgb)*alphaF);
15758         }
15759       }
15760     } else
15761     {
15762       for (int i=0; i<n; ++i)
15763       {
15764         int index = (data[dataIndexFactor*i]-range.lower)*posToIndexFactor;
15765         if (index < 0)
15766           index = 0;
15767         else if (index >= mLevelCount)
15768           index = mLevelCount-1;
15769         if (alpha[dataIndexFactor*i] == 255)
15770         {
15771           scanLine[i] = mColorBuffer.at(index);
15772         } else
15773         {
15774           const QRgb rgb = mColorBuffer.at(index);
15775           const float alphaF = alpha[dataIndexFactor*i]/255.0f;
15776           scanLine[i] = qRgba(qRed(rgb)*alphaF, qGreen(rgb)*alphaF, qBlue(rgb)*alphaF, qAlpha(rgb)*alphaF);
15777         }
15778       }
15779     }
15780   } else // logarithmic == true
15781   {
15782     if (mPeriodic)
15783     {
15784       for (int i=0; i<n; ++i)
15785       {
15786         int index = (int)(qLn(data[dataIndexFactor*i]/range.lower)/qLn(range.upper/range.lower)*(mLevelCount-1)) % mLevelCount;
15787         if (index < 0)
15788           index += mLevelCount;
15789         if (alpha[dataIndexFactor*i] == 255)
15790         {
15791           scanLine[i] = mColorBuffer.at(index);
15792         } else
15793         {
15794           const QRgb rgb = mColorBuffer.at(index);
15795           const float alphaF = alpha[dataIndexFactor*i]/255.0f;
15796           scanLine[i] = qRgba(qRed(rgb)*alphaF, qGreen(rgb)*alphaF, qBlue(rgb)*alphaF, qAlpha(rgb)*alphaF);
15797         }
15798       }
15799     } else
15800     {
15801       for (int i=0; i<n; ++i)
15802       {
15803         int index = qLn(data[dataIndexFactor*i]/range.lower)/qLn(range.upper/range.lower)*(mLevelCount-1);
15804         if (index < 0)
15805           index = 0;
15806         else if (index >= mLevelCount)
15807           index = mLevelCount-1;
15808         if (alpha[dataIndexFactor*i] == 255)
15809         {
15810           scanLine[i] = mColorBuffer.at(index);
15811         } else
15812         {
15813           const QRgb rgb = mColorBuffer.at(index);
15814           const float alphaF = alpha[dataIndexFactor*i]/255.0f;
15815           scanLine[i] = qRgba(qRed(rgb)*alphaF, qGreen(rgb)*alphaF, qBlue(rgb)*alphaF, qAlpha(rgb)*alphaF);
15816         }
15817       }
15818     }
15819   }
15820 }
15821 
15822 /*! \internal
15823 
15824   This method is used to colorize a single data value given in \a position, to colors. The data
15825   range that shall be used for mapping the data value to the gradient is passed in \a range. \a
15826   logarithmic indicates whether the data value shall be mapped to a color logarithmically.
15827 
15828   If an entire array of data values shall be converted, rather use \ref colorize, for better
15829   performance.
15830 
15831   The returned QRgb has its r, g and b components premultiplied with alpha (see
15832   QImage::Format_ARGB32_Premultiplied).
15833 */
color(double position,const QCPRange & range,bool logarithmic)15834 QRgb QCPColorGradient::color(double position, const QCPRange &range, bool logarithmic)
15835 {
15836   // If you change something here, make sure to also adapt ::colorize()
15837   if (mColorBufferInvalidated)
15838     updateColorBuffer();
15839   int index = 0;
15840   if (!logarithmic)
15841     index = (position-range.lower)*(mLevelCount-1)/range.size();
15842   else
15843     index = qLn(position/range.lower)/qLn(range.upper/range.lower)*(mLevelCount-1);
15844   if (mPeriodic)
15845   {
15846     index = index % mLevelCount;
15847     if (index < 0)
15848       index += mLevelCount;
15849   } else
15850   {
15851     if (index < 0)
15852       index = 0;
15853     else if (index >= mLevelCount)
15854       index = mLevelCount-1;
15855   }
15856   return mColorBuffer.at(index);
15857 }
15858 
15859 /*!
15860   Clears the current color stops and loads the specified \a preset. A preset consists of predefined
15861   color stops and the corresponding color interpolation method.
15862 
15863   The available presets are:
15864   \image html QCPColorGradient.png
15865 */
loadPreset(GradientPreset preset)15866 void QCPColorGradient::loadPreset(GradientPreset preset)
15867 {
15868   clearColorStops();
15869   switch (preset)
15870   {
15871     case gpGrayscale:
15872       setColorInterpolation(ciRGB);
15873       setColorStopAt(0, Qt::black);
15874       setColorStopAt(1, Qt::white);
15875       break;
15876     case gpHot:
15877       setColorInterpolation(ciRGB);
15878       setColorStopAt(0, QColor(50, 0, 0));
15879       setColorStopAt(0.2, QColor(180, 10, 0));
15880       setColorStopAt(0.4, QColor(245, 50, 0));
15881       setColorStopAt(0.6, QColor(255, 150, 10));
15882       setColorStopAt(0.8, QColor(255, 255, 50));
15883       setColorStopAt(1, QColor(255, 255, 255));
15884       break;
15885     case gpCold:
15886       setColorInterpolation(ciRGB);
15887       setColorStopAt(0, QColor(0, 0, 50));
15888       setColorStopAt(0.2, QColor(0, 10, 180));
15889       setColorStopAt(0.4, QColor(0, 50, 245));
15890       setColorStopAt(0.6, QColor(10, 150, 255));
15891       setColorStopAt(0.8, QColor(50, 255, 255));
15892       setColorStopAt(1, QColor(255, 255, 255));
15893       break;
15894     case gpNight:
15895       setColorInterpolation(ciHSV);
15896       setColorStopAt(0, QColor(10, 20, 30));
15897       setColorStopAt(1, QColor(250, 255, 250));
15898       break;
15899     case gpCandy:
15900       setColorInterpolation(ciHSV);
15901       setColorStopAt(0, QColor(0, 0, 255));
15902       setColorStopAt(1, QColor(255, 250, 250));
15903       break;
15904     case gpGeography:
15905       setColorInterpolation(ciRGB);
15906       setColorStopAt(0, QColor(70, 170, 210));
15907       setColorStopAt(0.20, QColor(90, 160, 180));
15908       setColorStopAt(0.25, QColor(45, 130, 175));
15909       setColorStopAt(0.30, QColor(100, 140, 125));
15910       setColorStopAt(0.5, QColor(100, 140, 100));
15911       setColorStopAt(0.6, QColor(130, 145, 120));
15912       setColorStopAt(0.7, QColor(140, 130, 120));
15913       setColorStopAt(0.9, QColor(180, 190, 190));
15914       setColorStopAt(1, QColor(210, 210, 230));
15915       break;
15916     case gpIon:
15917       setColorInterpolation(ciHSV);
15918       setColorStopAt(0, QColor(50, 10, 10));
15919       setColorStopAt(0.45, QColor(0, 0, 255));
15920       setColorStopAt(0.8, QColor(0, 255, 255));
15921       setColorStopAt(1, QColor(0, 255, 0));
15922       break;
15923     case gpThermal:
15924       setColorInterpolation(ciRGB);
15925       setColorStopAt(0, QColor(0, 0, 50));
15926       setColorStopAt(0.15, QColor(20, 0, 120));
15927       setColorStopAt(0.33, QColor(200, 30, 140));
15928       setColorStopAt(0.6, QColor(255, 100, 0));
15929       setColorStopAt(0.85, QColor(255, 255, 40));
15930       setColorStopAt(1, QColor(255, 255, 255));
15931       break;
15932     case gpPolar:
15933       setColorInterpolation(ciRGB);
15934       setColorStopAt(0, QColor(50, 255, 255));
15935       setColorStopAt(0.18, QColor(10, 70, 255));
15936       setColorStopAt(0.28, QColor(10, 10, 190));
15937       setColorStopAt(0.5, QColor(0, 0, 0));
15938       setColorStopAt(0.72, QColor(190, 10, 10));
15939       setColorStopAt(0.82, QColor(255, 70, 10));
15940       setColorStopAt(1, QColor(255, 255, 50));
15941       break;
15942     case gpSpectrum:
15943       setColorInterpolation(ciHSV);
15944       setColorStopAt(0, QColor(50, 0, 50));
15945       setColorStopAt(0.15, QColor(0, 0, 255));
15946       setColorStopAt(0.35, QColor(0, 255, 255));
15947       setColorStopAt(0.6, QColor(255, 255, 0));
15948       setColorStopAt(0.75, QColor(255, 30, 0));
15949       setColorStopAt(1, QColor(50, 0, 0));
15950       break;
15951     case gpJet:
15952       setColorInterpolation(ciRGB);
15953       setColorStopAt(0, QColor(0, 0, 100));
15954       setColorStopAt(0.15, QColor(0, 50, 255));
15955       setColorStopAt(0.35, QColor(0, 255, 255));
15956       setColorStopAt(0.65, QColor(255, 255, 0));
15957       setColorStopAt(0.85, QColor(255, 30, 0));
15958       setColorStopAt(1, QColor(100, 0, 0));
15959       break;
15960     case gpHues:
15961       setColorInterpolation(ciHSV);
15962       setColorStopAt(0, QColor(255, 0, 0));
15963       setColorStopAt(1.0/3.0, QColor(0, 0, 255));
15964       setColorStopAt(2.0/3.0, QColor(0, 255, 0));
15965       setColorStopAt(1, QColor(255, 0, 0));
15966       break;
15967   }
15968 }
15969 
15970 /*!
15971   Clears all color stops.
15972 
15973   \see setColorStops, setColorStopAt
15974 */
clearColorStops()15975 void QCPColorGradient::clearColorStops()
15976 {
15977   mColorStops.clear();
15978   mColorBufferInvalidated = true;
15979 }
15980 
15981 /*!
15982   Returns an inverted gradient. The inverted gradient has all properties as this \ref
15983   QCPColorGradient, but the order of the color stops is inverted.
15984 
15985   \see setColorStops, setColorStopAt
15986 */
inverted() const15987 QCPColorGradient QCPColorGradient::inverted() const
15988 {
15989   QCPColorGradient result(*this);
15990   result.clearColorStops();
15991   for (QMap<double, QColor>::const_iterator it=mColorStops.constBegin(); it!=mColorStops.constEnd(); ++it)
15992     result.setColorStopAt(1.0-it.key(), it.value());
15993   return result;
15994 }
15995 
15996 /*! \internal
15997 
15998   Returns true if the color gradient uses transparency, i.e. if any of the configured color stops
15999   has an alpha value below 255.
16000 */
stopsUseAlpha() const16001 bool QCPColorGradient::stopsUseAlpha() const
16002 {
16003   for (QMap<double, QColor>::const_iterator it=mColorStops.constBegin(); it!=mColorStops.constEnd(); ++it)
16004   {
16005     if (it.value().alpha() < 255)
16006       return true;
16007   }
16008   return false;
16009 }
16010 
16011 /*! \internal
16012 
16013   Updates the internal color buffer which will be used by \ref colorize and \ref color, to quickly
16014   convert positions to colors. This is where the interpolation between color stops is calculated.
16015 */
updateColorBuffer()16016 void QCPColorGradient::updateColorBuffer()
16017 {
16018   if (mColorBuffer.size() != mLevelCount)
16019     mColorBuffer.resize(mLevelCount);
16020   if (mColorStops.size() > 1)
16021   {
16022     double indexToPosFactor = 1.0/(double)(mLevelCount-1);
16023     const bool useAlpha = stopsUseAlpha();
16024     for (int i=0; i<mLevelCount; ++i)
16025     {
16026       double position = i*indexToPosFactor;
16027       QMap<double, QColor>::const_iterator it = mColorStops.lowerBound(position);
16028       if (it == mColorStops.constEnd()) // position is on or after last stop, use color of last stop
16029       {
16030         mColorBuffer[i] = (it-1).value().rgba();
16031       } else if (it == mColorStops.constBegin()) // position is on or before first stop, use color of first stop
16032       {
16033         mColorBuffer[i] = it.value().rgba();
16034       } else // position is in between stops (or on an intermediate stop), interpolate color
16035       {
16036         QMap<double, QColor>::const_iterator high = it;
16037         QMap<double, QColor>::const_iterator low = it-1;
16038         double t = (position-low.key())/(high.key()-low.key()); // interpolation factor 0..1
16039         switch (mColorInterpolation)
16040         {
16041           case ciRGB:
16042           {
16043             if (useAlpha)
16044             {
16045               const int alpha = (1-t)*low.value().alpha() + t*high.value().alpha();
16046               const float alphaPremultiplier = alpha/255.0f; // since we use QImage::Format_ARGB32_Premultiplied
16047               mColorBuffer[i] = qRgba(((1-t)*low.value().red() + t*high.value().red())*alphaPremultiplier,
16048                                       ((1-t)*low.value().green() + t*high.value().green())*alphaPremultiplier,
16049                                       ((1-t)*low.value().blue() + t*high.value().blue())*alphaPremultiplier,
16050                                       alpha);
16051             } else
16052             {
16053               mColorBuffer[i] = qRgb(((1-t)*low.value().red() + t*high.value().red()),
16054                                      ((1-t)*low.value().green() + t*high.value().green()),
16055                                      ((1-t)*low.value().blue() + t*high.value().blue()));
16056             }
16057             break;
16058           }
16059           case ciHSV:
16060           {
16061             QColor lowHsv = low.value().toHsv();
16062             QColor highHsv = high.value().toHsv();
16063             double hue = 0;
16064             double hueDiff = highHsv.hueF()-lowHsv.hueF();
16065             if (hueDiff > 0.5)
16066               hue = lowHsv.hueF() - t*(1.0-hueDiff);
16067             else if (hueDiff < -0.5)
16068               hue = lowHsv.hueF() + t*(1.0+hueDiff);
16069             else
16070               hue = lowHsv.hueF() + t*hueDiff;
16071             if (hue < 0) hue += 1.0;
16072             else if (hue >= 1.0) hue -= 1.0;
16073             if (useAlpha)
16074             {
16075               const QRgb rgb = QColor::fromHsvF(hue,
16076                                                 (1-t)*lowHsv.saturationF() + t*highHsv.saturationF(),
16077                                                 (1-t)*lowHsv.valueF() + t*highHsv.valueF()).rgb();
16078               const float alpha = (1-t)*lowHsv.alphaF() + t*highHsv.alphaF();
16079               mColorBuffer[i] = qRgba(qRed(rgb)*alpha, qGreen(rgb)*alpha, qBlue(rgb)*alpha, 255*alpha);
16080             }
16081             else
16082             {
16083               mColorBuffer[i] = QColor::fromHsvF(hue,
16084                                                  (1-t)*lowHsv.saturationF() + t*highHsv.saturationF(),
16085                                                  (1-t)*lowHsv.valueF() + t*highHsv.valueF()).rgb();
16086             }
16087             break;
16088           }
16089         }
16090       }
16091     }
16092   } else if (mColorStops.size() == 1)
16093   {
16094     const QRgb rgb = mColorStops.constBegin().value().rgb();
16095     const float alpha = mColorStops.constBegin().value().alphaF();
16096     mColorBuffer.fill(qRgba(qRed(rgb)*alpha, qGreen(rgb)*alpha, qBlue(rgb)*alpha, 255*alpha));
16097   } else // mColorStops is empty, fill color buffer with black
16098   {
16099     mColorBuffer.fill(qRgb(0, 0, 0));
16100   }
16101   mColorBufferInvalidated = false;
16102 }
16103 /* end of 'src/colorgradient.cpp' */
16104 
16105 
16106 /* including file 'src/selectiondecorator-bracket.cpp', size 12313           */
16107 /* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
16108 
16109 ////////////////////////////////////////////////////////////////////////////////////////////////////
16110 //////////////////// QCPSelectionDecoratorBracket
16111 ////////////////////////////////////////////////////////////////////////////////////////////////////
16112 
16113 /*! \class QCPSelectionDecoratorBracket
16114   \brief A selection decorator which draws brackets around each selected data segment
16115 
16116   Additionally to the regular highlighting of selected segments via color, fill and scatter style,
16117   this \ref QCPSelectionDecorator subclass draws markers at the begin and end of each selected data
16118   segment of the plottable.
16119 
16120   The shape of the markers can be controlled with \ref setBracketStyle, \ref setBracketWidth and
16121   \ref setBracketHeight. The color/fill can be controlled with \ref setBracketPen and \ref
16122   setBracketBrush.
16123 
16124   To introduce custom bracket styles, it is only necessary to sublcass \ref
16125   QCPSelectionDecoratorBracket and reimplement \ref drawBracket. The rest will be managed by the
16126   base class.
16127 */
16128 
16129 /*!
16130   Creates a new QCPSelectionDecoratorBracket instance with default values.
16131 */
QCPSelectionDecoratorBracket()16132 QCPSelectionDecoratorBracket::QCPSelectionDecoratorBracket() :
16133   mBracketPen(QPen(Qt::black)),
16134   mBracketBrush(Qt::NoBrush),
16135   mBracketWidth(5),
16136   mBracketHeight(50),
16137   mBracketStyle(bsSquareBracket),
16138   mTangentToData(false),
16139   mTangentAverage(2)
16140 {
16141 
16142 }
16143 
~QCPSelectionDecoratorBracket()16144 QCPSelectionDecoratorBracket::~QCPSelectionDecoratorBracket()
16145 {
16146 }
16147 
16148 /*!
16149   Sets the pen that will be used to draw the brackets at the beginning and end of each selected
16150   data segment.
16151 */
setBracketPen(const QPen & pen)16152 void QCPSelectionDecoratorBracket::setBracketPen(const QPen &pen)
16153 {
16154   mBracketPen = pen;
16155 }
16156 
16157 /*!
16158   Sets the brush that will be used to draw the brackets at the beginning and end of each selected
16159   data segment.
16160 */
setBracketBrush(const QBrush & brush)16161 void QCPSelectionDecoratorBracket::setBracketBrush(const QBrush &brush)
16162 {
16163   mBracketBrush = brush;
16164 }
16165 
16166 /*!
16167   Sets the width of the drawn bracket. The width dimension is always parallel to the key axis of
16168   the data, or the tangent direction of the current data slope, if \ref setTangentToData is
16169   enabled.
16170 */
setBracketWidth(int width)16171 void QCPSelectionDecoratorBracket::setBracketWidth(int width)
16172 {
16173   mBracketWidth = width;
16174 }
16175 
16176 /*!
16177   Sets the height of the drawn bracket. The height dimension is always perpendicular to the key axis
16178   of the data, or the tangent direction of the current data slope, if \ref setTangentToData is
16179   enabled.
16180 */
setBracketHeight(int height)16181 void QCPSelectionDecoratorBracket::setBracketHeight(int height)
16182 {
16183   mBracketHeight = height;
16184 }
16185 
16186 /*!
16187   Sets the shape that the bracket/marker will have.
16188 
16189   \see setBracketWidth, setBracketHeight
16190 */
setBracketStyle(QCPSelectionDecoratorBracket::BracketStyle style)16191 void QCPSelectionDecoratorBracket::setBracketStyle(QCPSelectionDecoratorBracket::BracketStyle style)
16192 {
16193   mBracketStyle = style;
16194 }
16195 
16196 /*!
16197   Sets whether the brackets will be rotated such that they align with the slope of the data at the
16198   position that they appear in.
16199 
16200   For noisy data, it might be more visually appealing to average the slope over multiple data
16201   points. This can be configured via \ref setTangentAverage.
16202 */
setTangentToData(bool enabled)16203 void QCPSelectionDecoratorBracket::setTangentToData(bool enabled)
16204 {
16205   mTangentToData = enabled;
16206 }
16207 
16208 /*!
16209   Controls over how many data points the slope shall be averaged, when brackets shall be aligned
16210   with the data (if \ref setTangentToData is true).
16211 
16212   From the position of the bracket, \a pointCount points towards the selected data range will be
16213   taken into account. The smallest value of \a pointCount is 1, which is effectively equivalent to
16214   disabling \ref setTangentToData.
16215 */
setTangentAverage(int pointCount)16216 void QCPSelectionDecoratorBracket::setTangentAverage(int pointCount)
16217 {
16218   mTangentAverage = pointCount;
16219   if (mTangentAverage < 1)
16220     mTangentAverage = 1;
16221 }
16222 
16223 /*!
16224   Draws the bracket shape with \a painter. The parameter \a direction is either -1 or 1 and
16225   indicates whether the bracket shall point to the left or the right (i.e. is a closing or opening
16226   bracket, respectively).
16227 
16228   The passed \a painter already contains all transformations that are necessary to position and
16229   rotate the bracket appropriately. Painting operations can be performed as if drawing upright
16230   brackets on flat data with horizontal key axis, with (0, 0) being the center of the bracket.
16231 
16232   If you wish to sublcass \ref QCPSelectionDecoratorBracket in order to provide custom bracket
16233   shapes (see \ref QCPSelectionDecoratorBracket::bsUserStyle), this is the method you should
16234   reimplement.
16235 */
drawBracket(QCPPainter * painter,int direction) const16236 void QCPSelectionDecoratorBracket::drawBracket(QCPPainter *painter, int direction) const
16237 {
16238   switch (mBracketStyle)
16239   {
16240     case bsSquareBracket:
16241     {
16242       painter->drawLine(QLineF(mBracketWidth*direction, -mBracketHeight*0.5, 0, -mBracketHeight*0.5));
16243       painter->drawLine(QLineF(mBracketWidth*direction, mBracketHeight*0.5, 0, mBracketHeight*0.5));
16244       painter->drawLine(QLineF(0, -mBracketHeight*0.5, 0, mBracketHeight*0.5));
16245       break;
16246     }
16247     case bsHalfEllipse:
16248     {
16249       painter->drawArc(-mBracketWidth*0.5, -mBracketHeight*0.5, mBracketWidth, mBracketHeight, -90*16, -180*16*direction);
16250       break;
16251     }
16252     case bsEllipse:
16253     {
16254       painter->drawEllipse(-mBracketWidth*0.5, -mBracketHeight*0.5, mBracketWidth, mBracketHeight);
16255       break;
16256     }
16257     case bsPlus:
16258     {
16259       painter->drawLine(QLineF(0, -mBracketHeight*0.5, 0, mBracketHeight*0.5));
16260       painter->drawLine(QLineF(-mBracketWidth*0.5, 0, mBracketWidth*0.5, 0));
16261       break;
16262     }
16263     default:
16264     {
16265       qDebug() << Q_FUNC_INFO << "unknown/custom bracket style can't be handeld by default implementation:" << static_cast<int>(mBracketStyle);
16266       break;
16267     }
16268   }
16269 }
16270 
16271 /*!
16272   Draws the bracket decoration on the data points at the begin and end of each selected data
16273   segment given in \a seletion.
16274 
16275   It uses the method \ref drawBracket to actually draw the shapes.
16276 
16277   \seebaseclassmethod
16278 */
drawDecoration(QCPPainter * painter,QCPDataSelection selection)16279 void QCPSelectionDecoratorBracket::drawDecoration(QCPPainter *painter, QCPDataSelection selection)
16280 {
16281   if (!mPlottable || selection.isEmpty()) return;
16282 
16283   if (QCPPlottableInterface1D *interface1d = mPlottable->interface1D())
16284   {
16285     foreach (const QCPDataRange &dataRange, selection.dataRanges())
16286     {
16287       // determine position and (if tangent mode is enabled) angle of brackets:
16288       int openBracketDir = (mPlottable->keyAxis() && !mPlottable->keyAxis()->rangeReversed()) ? 1 : -1;
16289       int closeBracketDir = -openBracketDir;
16290       QPointF openBracketPos = getPixelCoordinates(interface1d, dataRange.begin());
16291       QPointF closeBracketPos = getPixelCoordinates(interface1d, dataRange.end()-1);
16292       double openBracketAngle = 0;
16293       double closeBracketAngle = 0;
16294       if (mTangentToData)
16295       {
16296         openBracketAngle = getTangentAngle(interface1d, dataRange.begin(), openBracketDir);
16297         closeBracketAngle = getTangentAngle(interface1d, dataRange.end()-1, closeBracketDir);
16298       }
16299       // draw opening bracket:
16300       QTransform oldTransform = painter->transform();
16301       painter->setPen(mBracketPen);
16302       painter->setBrush(mBracketBrush);
16303       painter->translate(openBracketPos);
16304       painter->rotate(openBracketAngle/M_PI*180.0);
16305       drawBracket(painter, openBracketDir);
16306       painter->setTransform(oldTransform);
16307       // draw closing bracket:
16308       painter->setPen(mBracketPen);
16309       painter->setBrush(mBracketBrush);
16310       painter->translate(closeBracketPos);
16311       painter->rotate(closeBracketAngle/M_PI*180.0);
16312       drawBracket(painter, closeBracketDir);
16313       painter->setTransform(oldTransform);
16314     }
16315   }
16316 }
16317 
16318 /*! \internal
16319 
16320   If \ref setTangentToData is enabled, brackets need to be rotated according to the data slope.
16321   This method returns the angle in radians by which a bracket at the given \a dataIndex must be
16322   rotated.
16323 
16324   The parameter \a direction must be set to either -1 or 1, representing whether it is an opening
16325   or closing bracket. Since for slope calculation multiple data points are required, this defines
16326   the direction in which the algorithm walks, starting at \a dataIndex, to average those data
16327   points. (see \ref setTangentToData and \ref setTangentAverage)
16328 
16329   \a interface1d is the interface to the plottable's data which is used to query data coordinates.
16330 */
getTangentAngle(const QCPPlottableInterface1D * interface1d,int dataIndex,int direction) const16331 double QCPSelectionDecoratorBracket::getTangentAngle(const QCPPlottableInterface1D *interface1d, int dataIndex, int direction) const
16332 {
16333   if (!interface1d || dataIndex < 0 || dataIndex >= interface1d->dataCount())
16334     return 0;
16335   direction = direction < 0 ? -1 : 1; // enforce direction is either -1 or 1
16336 
16337   // how many steps we can actually go from index in the given direction without exceeding data bounds:
16338   int averageCount;
16339   if (direction < 0)
16340     averageCount = qMin(mTangentAverage, dataIndex);
16341   else
16342     averageCount = qMin(mTangentAverage, interface1d->dataCount()-1-dataIndex);
16343   qDebug() << averageCount;
16344   // calculate point average of averageCount points:
16345   QVector<QPointF> points(averageCount);
16346   QPointF pointsAverage;
16347   int currentIndex = dataIndex;
16348   for (int i=0; i<averageCount; ++i)
16349   {
16350     points[i] = getPixelCoordinates(interface1d, currentIndex);
16351     pointsAverage += points[i];
16352     currentIndex += direction;
16353   }
16354   pointsAverage /= (double)averageCount;
16355 
16356   // calculate slope of linear regression through points:
16357   double numSum = 0;
16358   double denomSum = 0;
16359   for (int i=0; i<averageCount; ++i)
16360   {
16361     const double dx = points.at(i).x()-pointsAverage.x();
16362     const double dy = points.at(i).y()-pointsAverage.y();
16363     numSum += dx*dy;
16364     denomSum += dx*dx;
16365   }
16366   if (!qFuzzyIsNull(denomSum) && !qFuzzyIsNull(numSum))
16367   {
16368     return qAtan2(numSum, denomSum);
16369   } else // undetermined angle, probably mTangentAverage == 1, so using only one data point
16370     return 0;
16371 }
16372 
16373 /*! \internal
16374 
16375   Returns the pixel coordinates of the data point at \a dataIndex, using \a interface1d to access
16376   the data points.
16377 */
getPixelCoordinates(const QCPPlottableInterface1D * interface1d,int dataIndex) const16378 QPointF QCPSelectionDecoratorBracket::getPixelCoordinates(const QCPPlottableInterface1D *interface1d, int dataIndex) const
16379 {
16380   QCPAxis *keyAxis = mPlottable->keyAxis();
16381   QCPAxis *valueAxis = mPlottable->valueAxis();
16382   if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPointF(0, 0); }
16383 
16384   if (keyAxis->orientation() == Qt::Horizontal)
16385     return QPointF(keyAxis->coordToPixel(interface1d->dataMainKey(dataIndex)), valueAxis->coordToPixel(interface1d->dataMainValue(dataIndex)));
16386   else
16387     return QPointF(valueAxis->coordToPixel(interface1d->dataMainValue(dataIndex)), keyAxis->coordToPixel(interface1d->dataMainKey(dataIndex)));
16388 }
16389 /* end of 'src/selectiondecorator-bracket.cpp' */
16390 
16391 
16392 /* including file 'src/layoutelements/layoutelement-axisrect.cpp', size 47509 */
16393 /* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200  */
16394 
16395 
16396 ////////////////////////////////////////////////////////////////////////////////////////////////////
16397 //////////////////// QCPAxisRect
16398 ////////////////////////////////////////////////////////////////////////////////////////////////////
16399 
16400 /*! \class QCPAxisRect
16401   \brief Holds multiple axes and arranges them in a rectangular shape.
16402 
16403   This class represents an axis rect, a rectangular area that is bounded on all sides with an
16404   arbitrary number of axes.
16405 
16406   Initially QCustomPlot has one axis rect, accessible via QCustomPlot::axisRect(). However, the
16407   layout system allows to have multiple axis rects, e.g. arranged in a grid layout
16408   (QCustomPlot::plotLayout).
16409 
16410   By default, QCPAxisRect comes with four axes, at bottom, top, left and right. They can be
16411   accessed via \ref axis by providing the respective axis type (\ref QCPAxis::AxisType) and index.
16412   If you need all axes in the axis rect, use \ref axes. The top and right axes are set to be
16413   invisible initially (QCPAxis::setVisible). To add more axes to a side, use \ref addAxis or \ref
16414   addAxes. To remove an axis, use \ref removeAxis.
16415 
16416   The axis rect layerable itself only draws a background pixmap or color, if specified (\ref
16417   setBackground). It is placed on the "background" layer initially (see \ref QCPLayer for an
16418   explanation of the QCustomPlot layer system). The axes that are held by the axis rect can be
16419   placed on other layers, independently of the axis rect.
16420 
16421   Every axis rect has a child layout of type \ref QCPLayoutInset. It is accessible via \ref
16422   insetLayout and can be used to have other layout elements (or even other layouts with multiple
16423   elements) hovering inside the axis rect.
16424 
16425   If an axis rect is clicked and dragged, it processes this by moving certain axis ranges. The
16426   behaviour can be controlled with \ref setRangeDrag and \ref setRangeDragAxes. If the mouse wheel
16427   is scrolled while the cursor is on the axis rect, certain axes are scaled. This is controllable
16428   via \ref setRangeZoom, \ref setRangeZoomAxes and \ref setRangeZoomFactor. These interactions are
16429   only enabled if \ref QCustomPlot::setInteractions contains \ref QCP::iRangeDrag and \ref
16430   QCP::iRangeZoom.
16431 
16432   \image html AxisRectSpacingOverview.png
16433   <center>Overview of the spacings and paddings that define the geometry of an axis. The dashed
16434   line on the far left indicates the viewport/widget border.</center>
16435 */
16436 
16437 /* start documentation of inline functions */
16438 
16439 /*! \fn QCPLayoutInset *QCPAxisRect::insetLayout() const
16440 
16441   Returns the inset layout of this axis rect. It can be used to place other layout elements (or
16442   even layouts with multiple other elements) inside/on top of an axis rect.
16443 
16444   \see QCPLayoutInset
16445 */
16446 
16447 /*! \fn int QCPAxisRect::left() const
16448 
16449   Returns the pixel position of the left border of this axis rect. Margins are not taken into
16450   account here, so the returned value is with respect to the inner \ref rect.
16451 */
16452 
16453 /*! \fn int QCPAxisRect::right() const
16454 
16455   Returns the pixel position of the right border of this axis rect. Margins are not taken into
16456   account here, so the returned value is with respect to the inner \ref rect.
16457 */
16458 
16459 /*! \fn int QCPAxisRect::top() const
16460 
16461   Returns the pixel position of the top border of this axis rect. Margins are not taken into
16462   account here, so the returned value is with respect to the inner \ref rect.
16463 */
16464 
16465 /*! \fn int QCPAxisRect::bottom() const
16466 
16467   Returns the pixel position of the bottom border of this axis rect. Margins are not taken into
16468   account here, so the returned value is with respect to the inner \ref rect.
16469 */
16470 
16471 /*! \fn int QCPAxisRect::width() const
16472 
16473   Returns the pixel width of this axis rect. Margins are not taken into account here, so the
16474   returned value is with respect to the inner \ref rect.
16475 */
16476 
16477 /*! \fn int QCPAxisRect::height() const
16478 
16479   Returns the pixel height of this axis rect. Margins are not taken into account here, so the
16480   returned value is with respect to the inner \ref rect.
16481 */
16482 
16483 /*! \fn QSize QCPAxisRect::size() const
16484 
16485   Returns the pixel size of this axis rect. Margins are not taken into account here, so the
16486   returned value is with respect to the inner \ref rect.
16487 */
16488 
16489 /*! \fn QPoint QCPAxisRect::topLeft() const
16490 
16491   Returns the top left corner of this axis rect in pixels. Margins are not taken into account here,
16492   so the returned value is with respect to the inner \ref rect.
16493 */
16494 
16495 /*! \fn QPoint QCPAxisRect::topRight() const
16496 
16497   Returns the top right corner of this axis rect in pixels. Margins are not taken into account
16498   here, so the returned value is with respect to the inner \ref rect.
16499 */
16500 
16501 /*! \fn QPoint QCPAxisRect::bottomLeft() const
16502 
16503   Returns the bottom left corner of this axis rect in pixels. Margins are not taken into account
16504   here, so the returned value is with respect to the inner \ref rect.
16505 */
16506 
16507 /*! \fn QPoint QCPAxisRect::bottomRight() const
16508 
16509   Returns the bottom right corner of this axis rect in pixels. Margins are not taken into account
16510   here, so the returned value is with respect to the inner \ref rect.
16511 */
16512 
16513 /*! \fn QPoint QCPAxisRect::center() const
16514 
16515   Returns the center of this axis rect in pixels. Margins are not taken into account here, so the
16516   returned value is with respect to the inner \ref rect.
16517 */
16518 
16519 /* end documentation of inline functions */
16520 
16521 /*!
16522   Creates a QCPAxisRect instance and sets default values. An axis is added for each of the four
16523   sides, the top and right axes are set invisible initially.
16524 */
QCPAxisRect(QCustomPlot * parentPlot,bool setupDefaultAxes)16525 QCPAxisRect::QCPAxisRect(QCustomPlot *parentPlot, bool setupDefaultAxes) :
16526   QCPLayoutElement(parentPlot),
16527   mBackgroundBrush(Qt::NoBrush),
16528   mBackgroundScaled(true),
16529   mBackgroundScaledMode(Qt::KeepAspectRatioByExpanding),
16530   mInsetLayout(new QCPLayoutInset),
16531   mRangeDrag(Qt::Horizontal|Qt::Vertical),
16532   mRangeZoom(Qt::Horizontal|Qt::Vertical),
16533   mRangeZoomFactorHorz(0.85),
16534   mRangeZoomFactorVert(0.85),
16535   mDragging(false)
16536 {
16537   mInsetLayout->initializeParentPlot(mParentPlot);
16538   mInsetLayout->setParentLayerable(this);
16539   mInsetLayout->setParent(this);
16540 
16541   setMinimumSize(50, 50);
16542   setMinimumMargins(QMargins(15, 15, 15, 15));
16543   mAxes.insert(QCPAxis::atLeft, QList<QCPAxis*>());
16544   mAxes.insert(QCPAxis::atRight, QList<QCPAxis*>());
16545   mAxes.insert(QCPAxis::atTop, QList<QCPAxis*>());
16546   mAxes.insert(QCPAxis::atBottom, QList<QCPAxis*>());
16547 
16548   if (setupDefaultAxes)
16549   {
16550     QCPAxis *xAxis = addAxis(QCPAxis::atBottom);
16551     QCPAxis *yAxis = addAxis(QCPAxis::atLeft);
16552     QCPAxis *xAxis2 = addAxis(QCPAxis::atTop);
16553     QCPAxis *yAxis2 = addAxis(QCPAxis::atRight);
16554     setRangeDragAxes(xAxis, yAxis);
16555     setRangeZoomAxes(xAxis, yAxis);
16556     xAxis2->setVisible(false);
16557     yAxis2->setVisible(false);
16558     xAxis->grid()->setVisible(true);
16559     yAxis->grid()->setVisible(true);
16560     xAxis2->grid()->setVisible(false);
16561     yAxis2->grid()->setVisible(false);
16562     xAxis2->grid()->setZeroLinePen(Qt::NoPen);
16563     yAxis2->grid()->setZeroLinePen(Qt::NoPen);
16564     xAxis2->grid()->setVisible(false);
16565     yAxis2->grid()->setVisible(false);
16566   }
16567 }
16568 
~QCPAxisRect()16569 QCPAxisRect::~QCPAxisRect()
16570 {
16571   delete mInsetLayout;
16572   mInsetLayout = 0;
16573 
16574   QList<QCPAxis*> axesList = axes();
16575   for (int i=0; i<axesList.size(); ++i)
16576     removeAxis(axesList.at(i));
16577 }
16578 
16579 /*!
16580   Returns the number of axes on the axis rect side specified with \a type.
16581 
16582   \see axis
16583 */
axisCount(QCPAxis::AxisType type) const16584 int QCPAxisRect::axisCount(QCPAxis::AxisType type) const
16585 {
16586   return mAxes.value(type).size();
16587 }
16588 
16589 /*!
16590   Returns the axis with the given \a index on the axis rect side specified with \a type.
16591 
16592   \see axisCount, axes
16593 */
axis(QCPAxis::AxisType type,int index) const16594 QCPAxis *QCPAxisRect::axis(QCPAxis::AxisType type, int index) const
16595 {
16596   QList<QCPAxis*> ax(mAxes.value(type));
16597   if (index >= 0 && index < ax.size())
16598   {
16599     return ax.at(index);
16600   } else
16601   {
16602     qDebug() << Q_FUNC_INFO << "Axis index out of bounds:" << index;
16603     return 0;
16604   }
16605 }
16606 
16607 /*!
16608   Returns all axes on the axis rect sides specified with \a types.
16609 
16610   \a types may be a single \ref QCPAxis::AxisType or an <tt>or</tt>-combination, to get the axes of
16611   multiple sides.
16612 
16613   \see axis
16614 */
axes(QCPAxis::AxisTypes types) const16615 QList<QCPAxis*> QCPAxisRect::axes(QCPAxis::AxisTypes types) const
16616 {
16617   QList<QCPAxis*> result;
16618   if (types.testFlag(QCPAxis::atLeft))
16619     result << mAxes.value(QCPAxis::atLeft);
16620   if (types.testFlag(QCPAxis::atRight))
16621     result << mAxes.value(QCPAxis::atRight);
16622   if (types.testFlag(QCPAxis::atTop))
16623     result << mAxes.value(QCPAxis::atTop);
16624   if (types.testFlag(QCPAxis::atBottom))
16625     result << mAxes.value(QCPAxis::atBottom);
16626   return result;
16627 }
16628 
16629 /*! \overload
16630 
16631   Returns all axes of this axis rect.
16632 */
axes() const16633 QList<QCPAxis*> QCPAxisRect::axes() const
16634 {
16635   QList<QCPAxis*> result;
16636   QHashIterator<QCPAxis::AxisType, QList<QCPAxis*> > it(mAxes);
16637   while (it.hasNext())
16638   {
16639     it.next();
16640     result << it.value();
16641   }
16642   return result;
16643 }
16644 
16645 /*!
16646   Adds a new axis to the axis rect side specified with \a type, and returns it. If \a axis is 0, a
16647   new QCPAxis instance is created internally. QCustomPlot owns the returned axis, so if you want to
16648   remove an axis, use \ref removeAxis instead of deleting it manually.
16649 
16650   You may inject QCPAxis instances (or sublasses of QCPAxis) by setting \a axis to an axis that was
16651   previously created outside QCustomPlot. It is important to note that QCustomPlot takes ownership
16652   of the axis, so you may not delete it afterwards. Further, the \a axis must have been created
16653   with this axis rect as parent and with the same axis type as specified in \a type. If this is not
16654   the case, a debug output is generated, the axis is not added, and the method returns 0.
16655 
16656   This method can not be used to move \a axis between axis rects. The same \a axis instance must
16657   not be added multiple times to the same or different axis rects.
16658 
16659   If an axis rect side already contains one or more axes, the lower and upper endings of the new
16660   axis (\ref QCPAxis::setLowerEnding, \ref QCPAxis::setUpperEnding) are set to \ref
16661   QCPLineEnding::esHalfBar.
16662 
16663   \see addAxes, setupFullAxesBox
16664 */
addAxis(QCPAxis::AxisType type,QCPAxis * axis)16665 QCPAxis *QCPAxisRect::addAxis(QCPAxis::AxisType type, QCPAxis *axis)
16666 {
16667   QCPAxis *newAxis = axis;
16668   if (!newAxis)
16669   {
16670     newAxis = new QCPAxis(this, type);
16671   } else // user provided existing axis instance, do some sanity checks
16672   {
16673     if (newAxis->axisType() != type)
16674     {
16675       qDebug() << Q_FUNC_INFO << "passed axis has different axis type than specified in type parameter";
16676       return 0;
16677     }
16678     if (newAxis->axisRect() != this)
16679     {
16680       qDebug() << Q_FUNC_INFO << "passed axis doesn't have this axis rect as parent axis rect";
16681       return 0;
16682     }
16683     if (axes().contains(newAxis))
16684     {
16685       qDebug() << Q_FUNC_INFO << "passed axis is already owned by this axis rect";
16686       return 0;
16687     }
16688   }
16689   if (mAxes[type].size() > 0) // multiple axes on one side, add half-bar axis ending to additional axes with offset
16690   {
16691     bool invert = (type == QCPAxis::atRight) || (type == QCPAxis::atBottom);
16692     newAxis->setLowerEnding(QCPLineEnding(QCPLineEnding::esHalfBar, 6, 10, !invert));
16693     newAxis->setUpperEnding(QCPLineEnding(QCPLineEnding::esHalfBar, 6, 10, invert));
16694   }
16695   mAxes[type].append(newAxis);
16696 
16697   // reset convenience axis pointers on parent QCustomPlot if they are unset:
16698   if (mParentPlot && mParentPlot->axisRectCount() > 0 && mParentPlot->axisRect(0) == this)
16699   {
16700     switch (type)
16701     {
16702       case QCPAxis::atBottom: { if (!mParentPlot->xAxis) mParentPlot->xAxis = newAxis; break; }
16703       case QCPAxis::atLeft: { if (!mParentPlot->yAxis) mParentPlot->yAxis = newAxis; break; }
16704       case QCPAxis::atTop: { if (!mParentPlot->xAxis2) mParentPlot->xAxis2 = newAxis; break; }
16705       case QCPAxis::atRight: { if (!mParentPlot->yAxis2) mParentPlot->yAxis2 = newAxis; break; }
16706     }
16707   }
16708 
16709   return newAxis;
16710 }
16711 
16712 /*!
16713   Adds a new axis with \ref addAxis to each axis rect side specified in \a types. This may be an
16714   <tt>or</tt>-combination of QCPAxis::AxisType, so axes can be added to multiple sides at once.
16715 
16716   Returns a list of the added axes.
16717 
16718   \see addAxis, setupFullAxesBox
16719 */
addAxes(QCPAxis::AxisTypes types)16720 QList<QCPAxis*> QCPAxisRect::addAxes(QCPAxis::AxisTypes types)
16721 {
16722   QList<QCPAxis*> result;
16723   if (types.testFlag(QCPAxis::atLeft))
16724     result << addAxis(QCPAxis::atLeft);
16725   if (types.testFlag(QCPAxis::atRight))
16726     result << addAxis(QCPAxis::atRight);
16727   if (types.testFlag(QCPAxis::atTop))
16728     result << addAxis(QCPAxis::atTop);
16729   if (types.testFlag(QCPAxis::atBottom))
16730     result << addAxis(QCPAxis::atBottom);
16731   return result;
16732 }
16733 
16734 /*!
16735   Removes the specified \a axis from the axis rect and deletes it.
16736 
16737   Returns true on success, i.e. if \a axis was a valid axis in this axis rect.
16738 
16739   \see addAxis
16740 */
removeAxis(QCPAxis * axis)16741 bool QCPAxisRect::removeAxis(QCPAxis *axis)
16742 {
16743   // don't access axis->axisType() to provide safety when axis is an invalid pointer, rather go through all axis containers:
16744   QHashIterator<QCPAxis::AxisType, QList<QCPAxis*> > it(mAxes);
16745   while (it.hasNext())
16746   {
16747     it.next();
16748     if (it.value().contains(axis))
16749     {
16750       mAxes[it.key()].removeOne(axis);
16751       if (qobject_cast<QCustomPlot*>(parentPlot())) // make sure this isn't called from QObject dtor when QCustomPlot is already destructed (happens when the axis rect is not in any layout and thus QObject-child of QCustomPlot)
16752         parentPlot()->axisRemoved(axis);
16753       delete axis;
16754       return true;
16755     }
16756   }
16757   qDebug() << Q_FUNC_INFO << "Axis isn't in axis rect:" << reinterpret_cast<quintptr>(axis);
16758   return false;
16759 }
16760 
16761 /*!
16762   Zooms in (or out) to the passed rectangular region \a pixelRect, given in pixel coordinates.
16763 
16764   All axes of this axis rect will have their range zoomed accordingly. If you only wish to zoom
16765   specific axes, use the overloaded version of this method.
16766 
16767   \see QCustomPlot::setSelectionRectMode
16768 */
zoom(const QRectF & pixelRect)16769 void QCPAxisRect::zoom(const QRectF &pixelRect)
16770 {
16771   zoom(pixelRect, axes());
16772 }
16773 
16774 /*! \overload
16775 
16776   Zooms in (or out) to the passed rectangular region \a pixelRect, given in pixel coordinates.
16777 
16778   Only the axes passed in \a affectedAxes will have their ranges zoomed accordingly.
16779 
16780   \see QCustomPlot::setSelectionRectMode
16781 */
zoom(const QRectF & pixelRect,const QList<QCPAxis * > & affectedAxes)16782 void QCPAxisRect::zoom(const QRectF &pixelRect, const QList<QCPAxis*> &affectedAxes)
16783 {
16784   foreach (QCPAxis *axis, affectedAxes)
16785   {
16786     if (!axis)
16787     {
16788       qDebug() << Q_FUNC_INFO << "a passed axis was zero";
16789       continue;
16790     }
16791     QCPRange pixelRange;
16792     if (axis->orientation() == Qt::Horizontal)
16793       pixelRange = QCPRange(pixelRect.left(), pixelRect.right());
16794     else
16795       pixelRange = QCPRange(pixelRect.top(), pixelRect.bottom());
16796     axis->setRange(axis->pixelToCoord(pixelRange.lower), axis->pixelToCoord(pixelRange.upper));
16797   }
16798 }
16799 
16800 /*!
16801   Convenience function to create an axis on each side that doesn't have any axes yet and set their
16802   visibility to true. Further, the top/right axes are assigned the following properties of the
16803   bottom/left axes:
16804 
16805   \li range (\ref QCPAxis::setRange)
16806   \li range reversed (\ref QCPAxis::setRangeReversed)
16807   \li scale type (\ref QCPAxis::setScaleType)
16808   \li tick visibility (\ref QCPAxis::setTicks)
16809   \li number format (\ref QCPAxis::setNumberFormat)
16810   \li number precision (\ref QCPAxis::setNumberPrecision)
16811   \li tick count of ticker (\ref QCPAxisTicker::setTickCount)
16812   \li tick origin of ticker (\ref QCPAxisTicker::setTickOrigin)
16813 
16814   Tick label visibility (\ref QCPAxis::setTickLabels) of the right and top axes are set to false.
16815 
16816   If \a connectRanges is true, the \ref QCPAxis::rangeChanged "rangeChanged" signals of the bottom
16817   and left axes are connected to the \ref QCPAxis::setRange slots of the top and right axes.
16818 */
setupFullAxesBox(bool connectRanges)16819 void QCPAxisRect::setupFullAxesBox(bool connectRanges)
16820 {
16821   QCPAxis *xAxis, *yAxis, *xAxis2, *yAxis2;
16822   if (axisCount(QCPAxis::atBottom) == 0)
16823     xAxis = addAxis(QCPAxis::atBottom);
16824   else
16825     xAxis = axis(QCPAxis::atBottom);
16826 
16827   if (axisCount(QCPAxis::atLeft) == 0)
16828     yAxis = addAxis(QCPAxis::atLeft);
16829   else
16830     yAxis = axis(QCPAxis::atLeft);
16831 
16832   if (axisCount(QCPAxis::atTop) == 0)
16833     xAxis2 = addAxis(QCPAxis::atTop);
16834   else
16835     xAxis2 = axis(QCPAxis::atTop);
16836 
16837   if (axisCount(QCPAxis::atRight) == 0)
16838     yAxis2 = addAxis(QCPAxis::atRight);
16839   else
16840     yAxis2 = axis(QCPAxis::atRight);
16841 
16842   xAxis->setVisible(true);
16843   yAxis->setVisible(true);
16844   xAxis2->setVisible(true);
16845   yAxis2->setVisible(true);
16846   xAxis2->setTickLabels(false);
16847   yAxis2->setTickLabels(false);
16848 
16849   xAxis2->setRange(xAxis->range());
16850   xAxis2->setRangeReversed(xAxis->rangeReversed());
16851   xAxis2->setScaleType(xAxis->scaleType());
16852   xAxis2->setTicks(xAxis->ticks());
16853   xAxis2->setNumberFormat(xAxis->numberFormat());
16854   xAxis2->setNumberPrecision(xAxis->numberPrecision());
16855   xAxis2->ticker()->setTickCount(xAxis->ticker()->tickCount());
16856   xAxis2->ticker()->setTickOrigin(xAxis->ticker()->tickOrigin());
16857 
16858   yAxis2->setRange(yAxis->range());
16859   yAxis2->setRangeReversed(yAxis->rangeReversed());
16860   yAxis2->setScaleType(yAxis->scaleType());
16861   yAxis2->setTicks(yAxis->ticks());
16862   yAxis2->setNumberFormat(yAxis->numberFormat());
16863   yAxis2->setNumberPrecision(yAxis->numberPrecision());
16864   yAxis2->ticker()->setTickCount(yAxis->ticker()->tickCount());
16865   yAxis2->ticker()->setTickOrigin(yAxis->ticker()->tickOrigin());
16866 
16867   if (connectRanges)
16868   {
16869     connect(xAxis, SIGNAL(rangeChanged(QCPRange)), xAxis2, SLOT(setRange(QCPRange)));
16870     connect(yAxis, SIGNAL(rangeChanged(QCPRange)), yAxis2, SLOT(setRange(QCPRange)));
16871   }
16872 }
16873 
16874 /*!
16875   Returns a list of all the plottables that are associated with this axis rect.
16876 
16877   A plottable is considered associated with an axis rect if its key or value axis (or both) is in
16878   this axis rect.
16879 
16880   \see graphs, items
16881 */
plottables() const16882 QList<QCPAbstractPlottable*> QCPAxisRect::plottables() const
16883 {
16884   // Note: don't append all QCPAxis::plottables() into a list, because we might get duplicate entries
16885   QList<QCPAbstractPlottable*> result;
16886   for (int i=0; i<mParentPlot->mPlottables.size(); ++i)
16887   {
16888     if (mParentPlot->mPlottables.at(i)->keyAxis()->axisRect() == this || mParentPlot->mPlottables.at(i)->valueAxis()->axisRect() == this)
16889       result.append(mParentPlot->mPlottables.at(i));
16890   }
16891   return result;
16892 }
16893 
16894 /*!
16895   Returns a list of all the graphs that are associated with this axis rect.
16896 
16897   A graph is considered associated with an axis rect if its key or value axis (or both) is in
16898   this axis rect.
16899 
16900   \see plottables, items
16901 */
graphs() const16902 QList<QCPGraph*> QCPAxisRect::graphs() const
16903 {
16904   // Note: don't append all QCPAxis::graphs() into a list, because we might get duplicate entries
16905   QList<QCPGraph*> result;
16906   for (int i=0; i<mParentPlot->mGraphs.size(); ++i)
16907   {
16908     if (mParentPlot->mGraphs.at(i)->keyAxis()->axisRect() == this || mParentPlot->mGraphs.at(i)->valueAxis()->axisRect() == this)
16909       result.append(mParentPlot->mGraphs.at(i));
16910   }
16911   return result;
16912 }
16913 
16914 /*!
16915   Returns a list of all the items that are associated with this axis rect.
16916 
16917   An item is considered associated with an axis rect if any of its positions has key or value axis
16918   set to an axis that is in this axis rect, or if any of its positions has \ref
16919   QCPItemPosition::setAxisRect set to the axis rect, or if the clip axis rect (\ref
16920   QCPAbstractItem::setClipAxisRect) is set to this axis rect.
16921 
16922   \see plottables, graphs
16923 */
items() const16924 QList<QCPAbstractItem *> QCPAxisRect::items() const
16925 {
16926   // Note: don't just append all QCPAxis::items() into a list, because we might get duplicate entries
16927   //       and miss those items that have this axis rect as clipAxisRect.
16928   QList<QCPAbstractItem*> result;
16929   for (int itemId=0; itemId<mParentPlot->mItems.size(); ++itemId)
16930   {
16931     if (mParentPlot->mItems.at(itemId)->clipAxisRect() == this)
16932     {
16933       result.append(mParentPlot->mItems.at(itemId));
16934       continue;
16935     }
16936     QList<QCPItemPosition*> positions = mParentPlot->mItems.at(itemId)->positions();
16937     for (int posId=0; posId<positions.size(); ++posId)
16938     {
16939       if (positions.at(posId)->axisRect() == this ||
16940           positions.at(posId)->keyAxis()->axisRect() == this ||
16941           positions.at(posId)->valueAxis()->axisRect() == this)
16942       {
16943         result.append(mParentPlot->mItems.at(itemId));
16944         break;
16945       }
16946     }
16947   }
16948   return result;
16949 }
16950 
16951 /*!
16952   This method is called automatically upon replot and doesn't need to be called by users of
16953   QCPAxisRect.
16954 
16955   Calls the base class implementation to update the margins (see \ref QCPLayoutElement::update),
16956   and finally passes the \ref rect to the inset layout (\ref insetLayout) and calls its
16957   QCPInsetLayout::update function.
16958 
16959   \seebaseclassmethod
16960 */
update(UpdatePhase phase)16961 void QCPAxisRect::update(UpdatePhase phase)
16962 {
16963   QCPLayoutElement::update(phase);
16964 
16965   switch (phase)
16966   {
16967     case upPreparation:
16968     {
16969       QList<QCPAxis*> allAxes = axes();
16970       for (int i=0; i<allAxes.size(); ++i)
16971         allAxes.at(i)->setupTickVectors();
16972       break;
16973     }
16974     case upLayout:
16975     {
16976       mInsetLayout->setOuterRect(rect());
16977       break;
16978     }
16979     default: break;
16980   }
16981 
16982   // pass update call on to inset layout (doesn't happen automatically, because QCPAxisRect doesn't derive from QCPLayout):
16983   mInsetLayout->update(phase);
16984 }
16985 
16986 /* inherits documentation from base class */
elements(bool recursive) const16987 QList<QCPLayoutElement*> QCPAxisRect::elements(bool recursive) const
16988 {
16989   QList<QCPLayoutElement*> result;
16990   if (mInsetLayout)
16991   {
16992     result << mInsetLayout;
16993     if (recursive)
16994       result << mInsetLayout->elements(recursive);
16995   }
16996   return result;
16997 }
16998 
16999 /* inherits documentation from base class */
applyDefaultAntialiasingHint(QCPPainter * painter) const17000 void QCPAxisRect::applyDefaultAntialiasingHint(QCPPainter *painter) const
17001 {
17002   painter->setAntialiasing(false);
17003 }
17004 
17005 /* inherits documentation from base class */
draw(QCPPainter * painter)17006 void QCPAxisRect::draw(QCPPainter *painter)
17007 {
17008   drawBackground(painter);
17009 }
17010 
17011 /*!
17012   Sets \a pm as the axis background pixmap. The axis background pixmap will be drawn inside the
17013   axis rect. Since axis rects place themselves on the "background" layer by default, the axis rect
17014   backgrounds are usually drawn below everything else.
17015 
17016   For cases where the provided pixmap doesn't have the same size as the axis rect, scaling can be
17017   enabled with \ref setBackgroundScaled and the scaling mode (i.e. whether and how the aspect ratio
17018   is preserved) can be set with \ref setBackgroundScaledMode. To set all these options in one call,
17019   consider using the overloaded version of this function.
17020 
17021   Below the pixmap, the axis rect may be optionally filled with a brush, if specified with \ref
17022   setBackground(const QBrush &brush).
17023 
17024   \see setBackgroundScaled, setBackgroundScaledMode, setBackground(const QBrush &brush)
17025 */
setBackground(const QPixmap & pm)17026 void QCPAxisRect::setBackground(const QPixmap &pm)
17027 {
17028   mBackgroundPixmap = pm;
17029   mScaledBackgroundPixmap = QPixmap();
17030 }
17031 
17032 /*! \overload
17033 
17034   Sets \a brush as the background brush. The axis rect background will be filled with this brush.
17035   Since axis rects place themselves on the "background" layer by default, the axis rect backgrounds
17036   are usually drawn below everything else.
17037 
17038   The brush will be drawn before (under) any background pixmap, which may be specified with \ref
17039   setBackground(const QPixmap &pm).
17040 
17041   To disable drawing of a background brush, set \a brush to Qt::NoBrush.
17042 
17043   \see setBackground(const QPixmap &pm)
17044 */
setBackground(const QBrush & brush)17045 void QCPAxisRect::setBackground(const QBrush &brush)
17046 {
17047   mBackgroundBrush = brush;
17048 }
17049 
17050 /*! \overload
17051 
17052   Allows setting the background pixmap of the axis rect, whether it shall be scaled and how it
17053   shall be scaled in one call.
17054 
17055   \see setBackground(const QPixmap &pm), setBackgroundScaled, setBackgroundScaledMode
17056 */
setBackground(const QPixmap & pm,bool scaled,Qt::AspectRatioMode mode)17057 void QCPAxisRect::setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode)
17058 {
17059   mBackgroundPixmap = pm;
17060   mScaledBackgroundPixmap = QPixmap();
17061   mBackgroundScaled = scaled;
17062   mBackgroundScaledMode = mode;
17063 }
17064 
17065 /*!
17066   Sets whether the axis background pixmap shall be scaled to fit the axis rect or not. If \a scaled
17067   is set to true, you may control whether and how the aspect ratio of the original pixmap is
17068   preserved with \ref setBackgroundScaledMode.
17069 
17070   Note that the scaled version of the original pixmap is buffered, so there is no performance
17071   penalty on replots. (Except when the axis rect dimensions are changed continuously.)
17072 
17073   \see setBackground, setBackgroundScaledMode
17074 */
setBackgroundScaled(bool scaled)17075 void QCPAxisRect::setBackgroundScaled(bool scaled)
17076 {
17077   mBackgroundScaled = scaled;
17078 }
17079 
17080 /*!
17081   If scaling of the axis background pixmap is enabled (\ref setBackgroundScaled), use this function to
17082   define whether and how the aspect ratio of the original pixmap passed to \ref setBackground is preserved.
17083   \see setBackground, setBackgroundScaled
17084 */
setBackgroundScaledMode(Qt::AspectRatioMode mode)17085 void QCPAxisRect::setBackgroundScaledMode(Qt::AspectRatioMode mode)
17086 {
17087   mBackgroundScaledMode = mode;
17088 }
17089 
17090 /*!
17091   Returns the range drag axis of the \a orientation provided. If multiple axes were set, returns
17092   the first one (use \ref rangeDragAxes to retrieve a list with all set axes).
17093 
17094   \see setRangeDragAxes
17095 */
rangeDragAxis(Qt::Orientation orientation)17096 QCPAxis *QCPAxisRect::rangeDragAxis(Qt::Orientation orientation)
17097 {
17098   if (orientation == Qt::Horizontal)
17099     return mRangeDragHorzAxis.isEmpty() ? 0 : mRangeDragHorzAxis.first().data();
17100   else
17101     return mRangeDragVertAxis.isEmpty() ? 0 : mRangeDragVertAxis.first().data();
17102 }
17103 
17104 /*!
17105   Returns the range zoom axis of the \a orientation provided. If multiple axes were set, returns
17106   the first one (use \ref rangeZoomAxes to retrieve a list with all set axes).
17107 
17108   \see setRangeZoomAxes
17109 */
rangeZoomAxis(Qt::Orientation orientation)17110 QCPAxis *QCPAxisRect::rangeZoomAxis(Qt::Orientation orientation)
17111 {
17112   if (orientation == Qt::Horizontal)
17113     return mRangeZoomHorzAxis.isEmpty() ? 0 : mRangeZoomHorzAxis.first().data();
17114   else
17115     return mRangeZoomVertAxis.isEmpty() ? 0 : mRangeZoomVertAxis.first().data();
17116 }
17117 
17118 /*!
17119   Returns all range drag axes of the \a orientation provided.
17120 
17121   \see rangeZoomAxis, setRangeZoomAxes
17122 */
rangeDragAxes(Qt::Orientation orientation)17123 QList<QCPAxis*> QCPAxisRect::rangeDragAxes(Qt::Orientation orientation)
17124 {
17125   QList<QCPAxis*> result;
17126   if (orientation == Qt::Horizontal)
17127   {
17128     for (int i=0; i<mRangeDragHorzAxis.size(); ++i)
17129     {
17130       if (!mRangeDragHorzAxis.at(i).isNull())
17131         result.append(mRangeDragHorzAxis.at(i).data());
17132     }
17133   } else
17134   {
17135     for (int i=0; i<mRangeDragVertAxis.size(); ++i)
17136     {
17137       if (!mRangeDragVertAxis.at(i).isNull())
17138         result.append(mRangeDragVertAxis.at(i).data());
17139     }
17140   }
17141   return result;
17142 }
17143 
17144 /*!
17145   Returns all range zoom axes of the \a orientation provided.
17146 
17147   \see rangeDragAxis, setRangeDragAxes
17148 */
rangeZoomAxes(Qt::Orientation orientation)17149 QList<QCPAxis*> QCPAxisRect::rangeZoomAxes(Qt::Orientation orientation)
17150 {
17151   QList<QCPAxis*> result;
17152   if (orientation == Qt::Horizontal)
17153   {
17154     for (int i=0; i<mRangeZoomHorzAxis.size(); ++i)
17155     {
17156       if (!mRangeZoomHorzAxis.at(i).isNull())
17157         result.append(mRangeZoomHorzAxis.at(i).data());
17158     }
17159   } else
17160   {
17161     for (int i=0; i<mRangeZoomVertAxis.size(); ++i)
17162     {
17163       if (!mRangeZoomVertAxis.at(i).isNull())
17164         result.append(mRangeZoomVertAxis.at(i).data());
17165     }
17166   }
17167   return result;
17168 }
17169 
17170 /*!
17171   Returns the range zoom factor of the \a orientation provided.
17172 
17173   \see setRangeZoomFactor
17174 */
rangeZoomFactor(Qt::Orientation orientation)17175 double QCPAxisRect::rangeZoomFactor(Qt::Orientation orientation)
17176 {
17177   return (orientation == Qt::Horizontal ? mRangeZoomFactorHorz : mRangeZoomFactorVert);
17178 }
17179 
17180 /*!
17181   Sets which axis orientation may be range dragged by the user with mouse interaction.
17182   What orientation corresponds to which specific axis can be set with
17183   \ref setRangeDragAxes(QCPAxis *horizontal, QCPAxis *vertical). By
17184   default, the horizontal axis is the bottom axis (xAxis) and the vertical axis
17185   is the left axis (yAxis).
17186 
17187   To disable range dragging entirely, pass 0 as \a orientations or remove \ref QCP::iRangeDrag from \ref
17188   QCustomPlot::setInteractions. To enable range dragging for both directions, pass <tt>Qt::Horizontal |
17189   Qt::Vertical</tt> as \a orientations.
17190 
17191   In addition to setting \a orientations to a non-zero value, make sure \ref QCustomPlot::setInteractions
17192   contains \ref QCP::iRangeDrag to enable the range dragging interaction.
17193 
17194   \see setRangeZoom, setRangeDragAxes, QCustomPlot::setNoAntialiasingOnDrag
17195 */
setRangeDrag(Qt::Orientations orientations)17196 void QCPAxisRect::setRangeDrag(Qt::Orientations orientations)
17197 {
17198   mRangeDrag = orientations;
17199 }
17200 
17201 /*!
17202   Sets which axis orientation may be zoomed by the user with the mouse wheel. What orientation
17203   corresponds to which specific axis can be set with \ref setRangeZoomAxes(QCPAxis *horizontal,
17204   QCPAxis *vertical). By default, the horizontal axis is the bottom axis (xAxis) and the vertical
17205   axis is the left axis (yAxis).
17206 
17207   To disable range zooming entirely, pass 0 as \a orientations or remove \ref QCP::iRangeZoom from \ref
17208   QCustomPlot::setInteractions. To enable range zooming for both directions, pass <tt>Qt::Horizontal |
17209   Qt::Vertical</tt> as \a orientations.
17210 
17211   In addition to setting \a orientations to a non-zero value, make sure \ref QCustomPlot::setInteractions
17212   contains \ref QCP::iRangeZoom to enable the range zooming interaction.
17213 
17214   \see setRangeZoomFactor, setRangeZoomAxes, setRangeDrag
17215 */
setRangeZoom(Qt::Orientations orientations)17216 void QCPAxisRect::setRangeZoom(Qt::Orientations orientations)
17217 {
17218   mRangeZoom = orientations;
17219 }
17220 
17221 /*! \overload
17222 
17223   Sets the axes whose range will be dragged when \ref setRangeDrag enables mouse range dragging on
17224   the QCustomPlot widget. Pass 0 if no axis shall be dragged in the respective orientation.
17225 
17226   Use the overload taking a list of axes, if multiple axes (more than one per orientation) shall
17227   react to dragging interactions.
17228 
17229   \see setRangeZoomAxes
17230 */
setRangeDragAxes(QCPAxis * horizontal,QCPAxis * vertical)17231 void QCPAxisRect::setRangeDragAxes(QCPAxis *horizontal, QCPAxis *vertical)
17232 {
17233   QList<QCPAxis*> horz, vert;
17234   if (horizontal)
17235     horz.append(horizontal);
17236   if (vertical)
17237     vert.append(vertical);
17238   setRangeDragAxes(horz, vert);
17239 }
17240 
17241 /*! \overload
17242 
17243   This method allows to set up multiple axes to react to horizontal and vertical dragging. The drag
17244   orientation that the respective axis will react to is deduced from its orientation (\ref
17245   QCPAxis::orientation).
17246 
17247   In the unusual case that you wish to e.g. drag a vertically oriented axis with a horizontal drag
17248   motion, use the overload taking two separate lists for horizontal and vertical dragging.
17249 */
setRangeDragAxes(QList<QCPAxis * > axes)17250 void QCPAxisRect::setRangeDragAxes(QList<QCPAxis*> axes)
17251 {
17252   QList<QCPAxis*> horz, vert;
17253   foreach (QCPAxis *ax, axes)
17254   {
17255     if (ax->orientation() == Qt::Horizontal)
17256       horz.append(ax);
17257     else
17258       vert.append(ax);
17259   }
17260   setRangeDragAxes(horz, vert);
17261 }
17262 
17263 /*! \overload
17264 
17265   This method allows to set multiple axes up to react to horizontal and vertical dragging, and
17266   define specifically which axis reacts to which drag orientation (irrespective of the axis
17267   orientation).
17268 */
setRangeDragAxes(QList<QCPAxis * > horizontal,QList<QCPAxis * > vertical)17269 void QCPAxisRect::setRangeDragAxes(QList<QCPAxis*> horizontal, QList<QCPAxis*> vertical)
17270 {
17271   mRangeDragHorzAxis.clear();
17272   foreach (QCPAxis *ax, horizontal)
17273   {
17274     QPointer<QCPAxis> axPointer(ax);
17275     if (!axPointer.isNull())
17276       mRangeDragHorzAxis.append(axPointer);
17277     else
17278       qDebug() << Q_FUNC_INFO << "invalid axis passed in horizontal list:" << reinterpret_cast<quintptr>(ax);
17279   }
17280   mRangeDragVertAxis.clear();
17281   foreach (QCPAxis *ax, vertical)
17282   {
17283     QPointer<QCPAxis> axPointer(ax);
17284     if (!axPointer.isNull())
17285       mRangeDragVertAxis.append(axPointer);
17286     else
17287       qDebug() << Q_FUNC_INFO << "invalid axis passed in vertical list:" << reinterpret_cast<quintptr>(ax);
17288   }
17289 }
17290 
17291 /*!
17292   Sets the axes whose range will be zoomed when \ref setRangeZoom enables mouse wheel zooming on
17293   the QCustomPlot widget. Pass 0 if no axis shall be zoomed in the respective orientation.
17294 
17295   The two axes can be zoomed with different strengths, when different factors are passed to \ref
17296   setRangeZoomFactor(double horizontalFactor, double verticalFactor).
17297 
17298   Use the overload taking a list of axes, if multiple axes (more than one per orientation) shall
17299   react to zooming interactions.
17300 
17301   \see setRangeDragAxes
17302 */
setRangeZoomAxes(QCPAxis * horizontal,QCPAxis * vertical)17303 void QCPAxisRect::setRangeZoomAxes(QCPAxis *horizontal, QCPAxis *vertical)
17304 {
17305   QList<QCPAxis*> horz, vert;
17306   if (horizontal)
17307     horz.append(horizontal);
17308   if (vertical)
17309     vert.append(vertical);
17310   setRangeZoomAxes(horz, vert);
17311 }
17312 
17313 /*! \overload
17314 
17315   This method allows to set up multiple axes to react to horizontal and vertical range zooming. The
17316   zoom orientation that the respective axis will react to is deduced from its orientation (\ref
17317   QCPAxis::orientation).
17318 
17319   In the unusual case that you wish to e.g. zoom a vertically oriented axis with a horizontal zoom
17320   interaction, use the overload taking two separate lists for horizontal and vertical zooming.
17321 */
setRangeZoomAxes(QList<QCPAxis * > axes)17322 void QCPAxisRect::setRangeZoomAxes(QList<QCPAxis*> axes)
17323 {
17324   QList<QCPAxis*> horz, vert;
17325   foreach (QCPAxis *ax, axes)
17326   {
17327     if (ax->orientation() == Qt::Horizontal)
17328       horz.append(ax);
17329     else
17330       vert.append(ax);
17331   }
17332   setRangeZoomAxes(horz, vert);
17333 }
17334 
17335 /*! \overload
17336 
17337   This method allows to set multiple axes up to react to horizontal and vertical zooming, and
17338   define specifically which axis reacts to which zoom orientation (irrespective of the axis
17339   orientation).
17340 */
setRangeZoomAxes(QList<QCPAxis * > horizontal,QList<QCPAxis * > vertical)17341 void QCPAxisRect::setRangeZoomAxes(QList<QCPAxis*> horizontal, QList<QCPAxis*> vertical)
17342 {
17343   mRangeZoomHorzAxis.clear();
17344   foreach (QCPAxis *ax, horizontal)
17345   {
17346     QPointer<QCPAxis> axPointer(ax);
17347     if (!axPointer.isNull())
17348       mRangeZoomHorzAxis.append(axPointer);
17349     else
17350       qDebug() << Q_FUNC_INFO << "invalid axis passed in horizontal list:" << reinterpret_cast<quintptr>(ax);
17351   }
17352   mRangeZoomVertAxis.clear();
17353   foreach (QCPAxis *ax, vertical)
17354   {
17355     QPointer<QCPAxis> axPointer(ax);
17356     if (!axPointer.isNull())
17357       mRangeZoomVertAxis.append(axPointer);
17358     else
17359       qDebug() << Q_FUNC_INFO << "invalid axis passed in vertical list:" << reinterpret_cast<quintptr>(ax);
17360   }
17361 }
17362 
17363 /*!
17364   Sets how strong one rotation step of the mouse wheel zooms, when range zoom was activated with
17365   \ref setRangeZoom. The two parameters \a horizontalFactor and \a verticalFactor provide a way to
17366   let the horizontal axis zoom at different rates than the vertical axis. Which axis is horizontal
17367   and which is vertical, can be set with \ref setRangeZoomAxes.
17368 
17369   When the zoom factor is greater than one, scrolling the mouse wheel backwards (towards the user)
17370   will zoom in (make the currently visible range smaller). For zoom factors smaller than one, the
17371   same scrolling direction will zoom out.
17372 */
setRangeZoomFactor(double horizontalFactor,double verticalFactor)17373 void QCPAxisRect::setRangeZoomFactor(double horizontalFactor, double verticalFactor)
17374 {
17375   mRangeZoomFactorHorz = horizontalFactor;
17376   mRangeZoomFactorVert = verticalFactor;
17377 }
17378 
17379 /*! \overload
17380 
17381   Sets both the horizontal and vertical zoom \a factor.
17382 */
setRangeZoomFactor(double factor)17383 void QCPAxisRect::setRangeZoomFactor(double factor)
17384 {
17385   mRangeZoomFactorHorz = factor;
17386   mRangeZoomFactorVert = factor;
17387 }
17388 
17389 /*! \internal
17390 
17391   Draws the background of this axis rect. It may consist of a background fill (a QBrush) and a
17392   pixmap.
17393 
17394   If a brush was given via \ref setBackground(const QBrush &brush), this function first draws an
17395   according filling inside the axis rect with the provided \a painter.
17396 
17397   Then, if a pixmap was provided via \ref setBackground, this function buffers the scaled version
17398   depending on \ref setBackgroundScaled and \ref setBackgroundScaledMode and then draws it inside
17399   the axis rect with the provided \a painter. The scaled version is buffered in
17400   mScaledBackgroundPixmap to prevent expensive rescaling at every redraw. It is only updated, when
17401   the axis rect has changed in a way that requires a rescale of the background pixmap (this is
17402   dependent on the \ref setBackgroundScaledMode), or when a differend axis background pixmap was
17403   set.
17404 
17405   \see setBackground, setBackgroundScaled, setBackgroundScaledMode
17406 */
drawBackground(QCPPainter * painter)17407 void QCPAxisRect::drawBackground(QCPPainter *painter)
17408 {
17409   // draw background fill:
17410   if (mBackgroundBrush != Qt::NoBrush)
17411     painter->fillRect(mRect, mBackgroundBrush);
17412 
17413   // draw background pixmap (on top of fill, if brush specified):
17414   if (!mBackgroundPixmap.isNull())
17415   {
17416     if (mBackgroundScaled)
17417     {
17418       // check whether mScaledBackground needs to be updated:
17419       QSize scaledSize(mBackgroundPixmap.size());
17420       scaledSize.scale(mRect.size(), mBackgroundScaledMode);
17421       if (mScaledBackgroundPixmap.size() != scaledSize)
17422         mScaledBackgroundPixmap = mBackgroundPixmap.scaled(mRect.size(), mBackgroundScaledMode, Qt::SmoothTransformation);
17423       painter->drawPixmap(mRect.topLeft()+QPoint(0, -1), mScaledBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height()) & mScaledBackgroundPixmap.rect());
17424     } else
17425     {
17426       painter->drawPixmap(mRect.topLeft()+QPoint(0, -1), mBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height()));
17427     }
17428   }
17429 }
17430 
17431 /*! \internal
17432 
17433   This function makes sure multiple axes on the side specified with \a type don't collide, but are
17434   distributed according to their respective space requirement (QCPAxis::calculateMargin).
17435 
17436   It does this by setting an appropriate offset (\ref QCPAxis::setOffset) on all axes except the
17437   one with index zero.
17438 
17439   This function is called by \ref calculateAutoMargin.
17440 */
updateAxesOffset(QCPAxis::AxisType type)17441 void QCPAxisRect::updateAxesOffset(QCPAxis::AxisType type)
17442 {
17443   const QList<QCPAxis*> axesList = mAxes.value(type);
17444   if (axesList.isEmpty())
17445     return;
17446 
17447   bool isFirstVisible = !axesList.first()->visible(); // if the first axis is visible, the second axis (which is where the loop starts) isn't the first visible axis, so initialize with false
17448   for (int i=1; i<axesList.size(); ++i)
17449   {
17450     int offset = axesList.at(i-1)->offset() + axesList.at(i-1)->calculateMargin();
17451     if (axesList.at(i)->visible()) // only add inner tick length to offset if this axis is visible and it's not the first visible one (might happen if true first axis is invisible)
17452     {
17453       if (!isFirstVisible)
17454         offset += axesList.at(i)->tickLengthIn();
17455       isFirstVisible = false;
17456     }
17457     axesList.at(i)->setOffset(offset);
17458   }
17459 }
17460 
17461 /* inherits documentation from base class */
calculateAutoMargin(QCP::MarginSide side)17462 int QCPAxisRect::calculateAutoMargin(QCP::MarginSide side)
17463 {
17464   if (!mAutoMargins.testFlag(side))
17465     qDebug() << Q_FUNC_INFO << "Called with side that isn't specified as auto margin";
17466 
17467   updateAxesOffset(QCPAxis::marginSideToAxisType(side));
17468 
17469   // note: only need to look at the last (outer most) axis to determine the total margin, due to updateAxisOffset call
17470   const QList<QCPAxis*> axesList = mAxes.value(QCPAxis::marginSideToAxisType(side));
17471   if (axesList.size() > 0)
17472     return axesList.last()->offset() + axesList.last()->calculateMargin();
17473   else
17474     return 0;
17475 }
17476 
17477 /*! \internal
17478 
17479   Reacts to a change in layout to potentially set the convenience axis pointers \ref
17480   QCustomPlot::xAxis, \ref QCustomPlot::yAxis, etc. of the parent QCustomPlot to the respective
17481   axes of this axis rect. This is only done if the respective convenience pointer is currently zero
17482   and if there is no QCPAxisRect at position (0, 0) of the plot layout.
17483 
17484   This automation makes it simpler to replace the main axis rect with a newly created one, without
17485   the need to manually reset the convenience pointers.
17486 */
layoutChanged()17487 void QCPAxisRect::layoutChanged()
17488 {
17489   if (mParentPlot && mParentPlot->axisRectCount() > 0 && mParentPlot->axisRect(0) == this)
17490   {
17491     if (axisCount(QCPAxis::atBottom) > 0 && !mParentPlot->xAxis)
17492       mParentPlot->xAxis = axis(QCPAxis::atBottom);
17493     if (axisCount(QCPAxis::atLeft) > 0 && !mParentPlot->yAxis)
17494       mParentPlot->yAxis = axis(QCPAxis::atLeft);
17495     if (axisCount(QCPAxis::atTop) > 0 && !mParentPlot->xAxis2)
17496       mParentPlot->xAxis2 = axis(QCPAxis::atTop);
17497     if (axisCount(QCPAxis::atRight) > 0 && !mParentPlot->yAxis2)
17498       mParentPlot->yAxis2 = axis(QCPAxis::atRight);
17499   }
17500 }
17501 
17502 /*! \internal
17503 
17504   Event handler for when a mouse button is pressed on the axis rect. If the left mouse button is
17505   pressed, the range dragging interaction is initialized (the actual range manipulation happens in
17506   the \ref mouseMoveEvent).
17507 
17508   The mDragging flag is set to true and some anchor points are set that are needed to determine the
17509   distance the mouse was dragged in the mouse move/release events later.
17510 
17511   \see mouseMoveEvent, mouseReleaseEvent
17512 */
mousePressEvent(QMouseEvent * event,const QVariant & details)17513 void QCPAxisRect::mousePressEvent(QMouseEvent *event, const QVariant &details)
17514 {
17515   Q_UNUSED(details)
17516   mDragStart = event->pos(); // need this even when not LeftButton is pressed, to determine in releaseEvent whether it was a full click (no position change between press and release)
17517   if (event->buttons() & Qt::LeftButton)
17518   {
17519     mDragging = true;
17520     // initialize antialiasing backup in case we start dragging:
17521     if (mParentPlot->noAntialiasingOnDrag())
17522     {
17523       mAADragBackup = mParentPlot->antialiasedElements();
17524       mNotAADragBackup = mParentPlot->notAntialiasedElements();
17525     }
17526     // Mouse range dragging interaction:
17527     if (mParentPlot->interactions().testFlag(QCP::iRangeDrag))
17528     {
17529       mDragStartHorzRange.clear();
17530       for (int i=0; i<mRangeDragHorzAxis.size(); ++i)
17531         mDragStartHorzRange.append(mRangeDragHorzAxis.at(i).isNull() ? QCPRange() : mRangeDragHorzAxis.at(i)->range());
17532       mDragStartVertRange.clear();
17533       for (int i=0; i<mRangeDragVertAxis.size(); ++i)
17534         mDragStartVertRange.append(mRangeDragVertAxis.at(i).isNull() ? QCPRange() : mRangeDragVertAxis.at(i)->range());
17535     }
17536   }
17537 }
17538 
17539 /*! \internal
17540 
17541   Event handler for when the mouse is moved on the axis rect. If range dragging was activated in a
17542   preceding \ref mousePressEvent, the range is moved accordingly.
17543 
17544   \see mousePressEvent, mouseReleaseEvent
17545 */
mouseMoveEvent(QMouseEvent * event,const QPointF & startPos)17546 void QCPAxisRect::mouseMoveEvent(QMouseEvent *event, const QPointF &startPos)
17547 {
17548   Q_UNUSED(startPos)
17549   // Mouse range dragging interaction:
17550   if (mDragging && mParentPlot->interactions().testFlag(QCP::iRangeDrag))
17551   {
17552 
17553     if (mRangeDrag.testFlag(Qt::Horizontal))
17554     {
17555       for (int i=0; i<mRangeDragHorzAxis.size(); ++i)
17556       {
17557         QCPAxis *ax = mRangeDragHorzAxis.at(i).data();
17558         if (!ax)
17559           continue;
17560         if (i >= mDragStartHorzRange.size())
17561           break;
17562         if (ax->mScaleType == QCPAxis::stLinear)
17563         {
17564           double diff = ax->pixelToCoord(mDragStart.x()) - ax->pixelToCoord(event->pos().x());
17565           ax->setRange(mDragStartHorzRange.at(i).lower+diff, mDragStartHorzRange.at(i).upper+diff);
17566         } else if (ax->mScaleType == QCPAxis::stLogarithmic)
17567         {
17568           double diff = ax->pixelToCoord(mDragStart.x()) / ax->pixelToCoord(event->pos().x());
17569           ax->setRange(mDragStartHorzRange.at(i).lower*diff, mDragStartHorzRange.at(i).upper*diff);
17570         }
17571       }
17572     }
17573 
17574     if (mRangeDrag.testFlag(Qt::Vertical))
17575     {
17576       for (int i=0; i<mRangeDragVertAxis.size(); ++i)
17577       {
17578         QCPAxis *ax = mRangeDragVertAxis.at(i).data();
17579         if (!ax)
17580           continue;
17581         if (i >= mDragStartVertRange.size())
17582           break;
17583         if (ax->mScaleType == QCPAxis::stLinear)
17584         {
17585           double diff = ax->pixelToCoord(mDragStart.y()) - ax->pixelToCoord(event->pos().y());
17586           ax->setRange(mDragStartVertRange.at(i).lower+diff, mDragStartVertRange.at(i).upper+diff);
17587         } else if (ax->mScaleType == QCPAxis::stLogarithmic)
17588         {
17589           double diff = ax->pixelToCoord(mDragStart.y()) / ax->pixelToCoord(event->pos().y());
17590           ax->setRange(mDragStartVertRange.at(i).lower*diff, mDragStartVertRange.at(i).upper*diff);
17591         }
17592       }
17593     }
17594 
17595     if (mRangeDrag != 0) // if either vertical or horizontal drag was enabled, do a replot
17596     {
17597       if (mParentPlot->noAntialiasingOnDrag())
17598         mParentPlot->setNotAntialiasedElements(QCP::aeAll);
17599       mParentPlot->replot();
17600     }
17601 
17602   }
17603 }
17604 
17605 /* inherits documentation from base class */
mouseReleaseEvent(QMouseEvent * event,const QPointF & startPos)17606 void QCPAxisRect::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos)
17607 {
17608   Q_UNUSED(event)
17609   Q_UNUSED(startPos)
17610   mDragging = false;
17611   if (mParentPlot->noAntialiasingOnDrag())
17612   {
17613     mParentPlot->setAntialiasedElements(mAADragBackup);
17614     mParentPlot->setNotAntialiasedElements(mNotAADragBackup);
17615   }
17616 }
17617 
17618 /*! \internal
17619 
17620   Event handler for mouse wheel events. If rangeZoom is Qt::Horizontal, Qt::Vertical or both, the
17621   ranges of the axes defined as rangeZoomHorzAxis and rangeZoomVertAxis are scaled. The center of
17622   the scaling operation is the current cursor position inside the axis rect. The scaling factor is
17623   dependent on the mouse wheel delta (which direction the wheel was rotated) to provide a natural
17624   zooming feel. The Strength of the zoom can be controlled via \ref setRangeZoomFactor.
17625 
17626   Note, that event->delta() is usually +/-120 for single rotation steps. However, if the mouse
17627   wheel is turned rapidly, many steps may bunch up to one event, so the event->delta() may then be
17628   multiples of 120. This is taken into account here, by calculating \a wheelSteps and using it as
17629   exponent of the range zoom factor. This takes care of the wheel direction automatically, by
17630   inverting the factor, when the wheel step is negative (f^-1 = 1/f).
17631 */
wheelEvent(QWheelEvent * event)17632 void QCPAxisRect::wheelEvent(QWheelEvent *event)
17633 {
17634   // Mouse range zooming interaction:
17635   if (mParentPlot->interactions().testFlag(QCP::iRangeZoom))
17636   {
17637     if (mRangeZoom != 0)
17638     {
17639       double factor;
17640 #if QT_VERSION < QT_VERSION_CHECK(5, 15, 0)
17641       double wheelSteps = event->delta()/120.0; // a single step delta is +/-120 usually
17642 #else
17643       double wheelSteps = event->angleDelta().y()/120.0; // a single step delta is +/-120 usually
17644 #endif
17645       if (mRangeZoom.testFlag(Qt::Horizontal))
17646       {
17647         factor = qPow(mRangeZoomFactorHorz, wheelSteps);
17648         for (int i=0; i<mRangeZoomHorzAxis.size(); ++i)
17649         {
17650           if (!mRangeZoomHorzAxis.at(i).isNull())
17651             mRangeZoomHorzAxis.at(i)->scaleRange(factor, mRangeZoomHorzAxis.at(i)->pixelToCoord(
17652 #if QT_VERSION < QT_VERSION_CHECK(5, 15, 0)
17653                                                                                                 event->posF().x()
17654 #else
17655                                                                                                 event->position().x()
17656 #endif
17657                                                                                                 ));
17658         }
17659       }
17660       if (mRangeZoom.testFlag(Qt::Vertical))
17661       {
17662         factor = qPow(mRangeZoomFactorVert, wheelSteps);
17663         for (int i=0; i<mRangeZoomVertAxis.size(); ++i)
17664         {
17665           if (!mRangeZoomVertAxis.at(i).isNull())
17666             mRangeZoomVertAxis.at(i)->scaleRange(factor, mRangeZoomVertAxis.at(i)->pixelToCoord(
17667 #if QT_VERSION < QT_VERSION_CHECK(5, 15, 0)
17668                                                                                                 event->posF().y()
17669 #else
17670                                                                                                 event->position().y()
17671 #endif
17672                                                                                                 ));
17673         }
17674       }
17675       mParentPlot->replot();
17676     }
17677   }
17678 }
17679 /* end of 'src/layoutelements/layoutelement-axisrect.cpp' */
17680 
17681 
17682 /* including file 'src/layoutelements/layoutelement-legend.cpp', size 30933  */
17683 /* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
17684 
17685 ////////////////////////////////////////////////////////////////////////////////////////////////////
17686 //////////////////// QCPAbstractLegendItem
17687 ////////////////////////////////////////////////////////////////////////////////////////////////////
17688 
17689 /*! \class QCPAbstractLegendItem
17690   \brief The abstract base class for all entries in a QCPLegend.
17691 
17692   It defines a very basic interface for entries in a QCPLegend. For representing plottables in the
17693   legend, the subclass \ref QCPPlottableLegendItem is more suitable.
17694 
17695   Only derive directly from this class when you need absolute freedom (e.g. a custom legend entry
17696   that's not even associated with a plottable).
17697 
17698   You must implement the following pure virtual functions:
17699   \li \ref draw (from QCPLayerable)
17700 
17701   You inherit the following members you may use:
17702   <table>
17703     <tr>
17704       <td>QCPLegend *\b mParentLegend</td>
17705       <td>A pointer to the parent QCPLegend.</td>
17706     </tr><tr>
17707       <td>QFont \b mFont</td>
17708       <td>The generic font of the item. You should use this font for all or at least the most prominent text of the item.</td>
17709     </tr>
17710   </table>
17711 */
17712 
17713 /* start of documentation of signals */
17714 
17715 /*! \fn void QCPAbstractLegendItem::selectionChanged(bool selected)
17716 
17717   This signal is emitted when the selection state of this legend item has changed, either by user
17718   interaction or by a direct call to \ref setSelected.
17719 */
17720 
17721 /* end of documentation of signals */
17722 
17723 /*!
17724   Constructs a QCPAbstractLegendItem and associates it with the QCPLegend \a parent. This does not
17725   cause the item to be added to \a parent, so \ref QCPLegend::addItem must be called separately.
17726 */
QCPAbstractLegendItem(QCPLegend * parent)17727 QCPAbstractLegendItem::QCPAbstractLegendItem(QCPLegend *parent) :
17728   QCPLayoutElement(parent->parentPlot()),
17729   mParentLegend(parent),
17730   mFont(parent->font()),
17731   mTextColor(parent->textColor()),
17732   mSelectedFont(parent->selectedFont()),
17733   mSelectedTextColor(parent->selectedTextColor()),
17734   mSelectable(true),
17735   mSelected(false)
17736 {
17737   setLayer(QLatin1String("legend"));
17738   setMargins(QMargins(0, 0, 0, 0));
17739 }
17740 
17741 /*!
17742   Sets the default font of this specific legend item to \a font.
17743 
17744   \see setTextColor, QCPLegend::setFont
17745 */
setFont(const QFont & font)17746 void QCPAbstractLegendItem::setFont(const QFont &font)
17747 {
17748   mFont = font;
17749 }
17750 
17751 /*!
17752   Sets the default text color of this specific legend item to \a color.
17753 
17754   \see setFont, QCPLegend::setTextColor
17755 */
setTextColor(const QColor & color)17756 void QCPAbstractLegendItem::setTextColor(const QColor &color)
17757 {
17758   mTextColor = color;
17759 }
17760 
17761 /*!
17762   When this legend item is selected, \a font is used to draw generic text, instead of the normal
17763   font set with \ref setFont.
17764 
17765   \see setFont, QCPLegend::setSelectedFont
17766 */
setSelectedFont(const QFont & font)17767 void QCPAbstractLegendItem::setSelectedFont(const QFont &font)
17768 {
17769   mSelectedFont = font;
17770 }
17771 
17772 /*!
17773   When this legend item is selected, \a color is used to draw generic text, instead of the normal
17774   color set with \ref setTextColor.
17775 
17776   \see setTextColor, QCPLegend::setSelectedTextColor
17777 */
setSelectedTextColor(const QColor & color)17778 void QCPAbstractLegendItem::setSelectedTextColor(const QColor &color)
17779 {
17780   mSelectedTextColor = color;
17781 }
17782 
17783 /*!
17784   Sets whether this specific legend item is selectable.
17785 
17786   \see setSelectedParts, QCustomPlot::setInteractions
17787 */
setSelectable(bool selectable)17788 void QCPAbstractLegendItem::setSelectable(bool selectable)
17789 {
17790   if (mSelectable != selectable)
17791   {
17792     mSelectable = selectable;
17793     emit selectableChanged(mSelectable);
17794   }
17795 }
17796 
17797 /*!
17798   Sets whether this specific legend item is selected.
17799 
17800   It is possible to set the selection state of this item by calling this function directly, even if
17801   setSelectable is set to false.
17802 
17803   \see setSelectableParts, QCustomPlot::setInteractions
17804 */
setSelected(bool selected)17805 void QCPAbstractLegendItem::setSelected(bool selected)
17806 {
17807   if (mSelected != selected)
17808   {
17809     mSelected = selected;
17810     emit selectionChanged(mSelected);
17811   }
17812 }
17813 
17814 /* inherits documentation from base class */
selectTest(const QPointF & pos,bool onlySelectable,QVariant * details) const17815 double QCPAbstractLegendItem::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
17816 {
17817   Q_UNUSED(details)
17818   if (!mParentPlot) return -1;
17819   if (onlySelectable && (!mSelectable || !mParentLegend->selectableParts().testFlag(QCPLegend::spItems)))
17820     return -1;
17821 
17822   if (mRect.contains(pos.toPoint()))
17823     return mParentPlot->selectionTolerance()*0.99;
17824   else
17825     return -1;
17826 }
17827 
17828 /* inherits documentation from base class */
applyDefaultAntialiasingHint(QCPPainter * painter) const17829 void QCPAbstractLegendItem::applyDefaultAntialiasingHint(QCPPainter *painter) const
17830 {
17831   applyAntialiasingHint(painter, mAntialiased, QCP::aeLegendItems);
17832 }
17833 
17834 /* inherits documentation from base class */
clipRect() const17835 QRect QCPAbstractLegendItem::clipRect() const
17836 {
17837   return mOuterRect;
17838 }
17839 
17840 /* inherits documentation from base class */
selectEvent(QMouseEvent * event,bool additive,const QVariant & details,bool * selectionStateChanged)17841 void QCPAbstractLegendItem::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
17842 {
17843   Q_UNUSED(event)
17844   Q_UNUSED(details)
17845   if (mSelectable && mParentLegend->selectableParts().testFlag(QCPLegend::spItems))
17846   {
17847     bool selBefore = mSelected;
17848     setSelected(additive ? !mSelected : true);
17849     if (selectionStateChanged)
17850       *selectionStateChanged = mSelected != selBefore;
17851   }
17852 }
17853 
17854 /* inherits documentation from base class */
deselectEvent(bool * selectionStateChanged)17855 void QCPAbstractLegendItem::deselectEvent(bool *selectionStateChanged)
17856 {
17857   if (mSelectable && mParentLegend->selectableParts().testFlag(QCPLegend::spItems))
17858   {
17859     bool selBefore = mSelected;
17860     setSelected(false);
17861     if (selectionStateChanged)
17862       *selectionStateChanged = mSelected != selBefore;
17863   }
17864 }
17865 
17866 ////////////////////////////////////////////////////////////////////////////////////////////////////
17867 //////////////////// QCPPlottableLegendItem
17868 ////////////////////////////////////////////////////////////////////////////////////////////////////
17869 
17870 /*! \class QCPPlottableLegendItem
17871   \brief A legend item representing a plottable with an icon and the plottable name.
17872 
17873   This is the standard legend item for plottables. It displays an icon of the plottable next to the
17874   plottable name. The icon is drawn by the respective plottable itself (\ref
17875   QCPAbstractPlottable::drawLegendIcon), and tries to give an intuitive symbol for the plottable.
17876   For example, the QCPGraph draws a centered horizontal line and/or a single scatter point in the
17877   middle.
17878 
17879   Legend items of this type are always associated with one plottable (retrievable via the
17880   plottable() function and settable with the constructor). You may change the font of the plottable
17881   name with \ref setFont. Icon padding and border pen is taken from the parent QCPLegend, see \ref
17882   QCPLegend::setIconBorderPen and \ref QCPLegend::setIconTextPadding.
17883 
17884   The function \ref QCPAbstractPlottable::addToLegend/\ref QCPAbstractPlottable::removeFromLegend
17885   creates/removes legend items of this type in the default implementation. However, these functions
17886   may be reimplemented such that a different kind of legend item (e.g a direct subclass of
17887   QCPAbstractLegendItem) is used for that plottable.
17888 
17889   Since QCPLegend is based on QCPLayoutGrid, a legend item itself is just a subclass of
17890   QCPLayoutElement. While it could be added to a legend (or any other layout) via the normal layout
17891   interface, QCPLegend has specialized functions for handling legend items conveniently, see the
17892   documentation of \ref QCPLegend.
17893 */
17894 
17895 /*!
17896   Creates a new legend item associated with \a plottable.
17897 
17898   Once it's created, it can be added to the legend via \ref QCPLegend::addItem.
17899 
17900   A more convenient way of adding/removing a plottable to/from the legend is via the functions \ref
17901   QCPAbstractPlottable::addToLegend and \ref QCPAbstractPlottable::removeFromLegend.
17902 */
QCPPlottableLegendItem(QCPLegend * parent,QCPAbstractPlottable * plottable)17903 QCPPlottableLegendItem::QCPPlottableLegendItem(QCPLegend *parent, QCPAbstractPlottable *plottable) :
17904   QCPAbstractLegendItem(parent),
17905   mPlottable(plottable)
17906 {
17907   setAntialiased(false);
17908 }
17909 
17910 /*! \internal
17911 
17912   Returns the pen that shall be used to draw the icon border, taking into account the selection
17913   state of this item.
17914 */
getIconBorderPen() const17915 QPen QCPPlottableLegendItem::getIconBorderPen() const
17916 {
17917   return mSelected ? mParentLegend->selectedIconBorderPen() : mParentLegend->iconBorderPen();
17918 }
17919 
17920 /*! \internal
17921 
17922   Returns the text color that shall be used to draw text, taking into account the selection state
17923   of this item.
17924 */
getTextColor() const17925 QColor QCPPlottableLegendItem::getTextColor() const
17926 {
17927   return mSelected ? mSelectedTextColor : mTextColor;
17928 }
17929 
17930 /*! \internal
17931 
17932   Returns the font that shall be used to draw text, taking into account the selection state of this
17933   item.
17934 */
getFont() const17935 QFont QCPPlottableLegendItem::getFont() const
17936 {
17937   return mSelected ? mSelectedFont : mFont;
17938 }
17939 
17940 /*! \internal
17941 
17942   Draws the item with \a painter. The size and position of the drawn legend item is defined by the
17943   parent layout (typically a \ref QCPLegend) and the \ref minimumSizeHint and \ref maximumSizeHint
17944   of this legend item.
17945 */
draw(QCPPainter * painter)17946 void QCPPlottableLegendItem::draw(QCPPainter *painter)
17947 {
17948   if (!mPlottable) return;
17949   painter->setFont(getFont());
17950   painter->setPen(QPen(getTextColor()));
17951   QSizeF iconSize = mParentLegend->iconSize();
17952   QRectF textRect = painter->fontMetrics().boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPlottable->name());
17953   QRectF iconRect(mRect.topLeft(), iconSize);
17954   int textHeight = qMax(textRect.height(), iconSize.height());  // if text has smaller height than icon, center text vertically in icon height, else align tops
17955   painter->drawText(mRect.x()+iconSize.width()+mParentLegend->iconTextPadding(), mRect.y(), textRect.width(), textHeight, Qt::TextDontClip, mPlottable->name());
17956   // draw icon:
17957   painter->save();
17958   painter->setClipRect(iconRect, Qt::IntersectClip);
17959   mPlottable->drawLegendIcon(painter, iconRect);
17960   painter->restore();
17961   // draw icon border:
17962   if (getIconBorderPen().style() != Qt::NoPen)
17963   {
17964     painter->setPen(getIconBorderPen());
17965     painter->setBrush(Qt::NoBrush);
17966     int halfPen = qCeil(painter->pen().widthF()*0.5)+1;
17967     painter->setClipRect(mOuterRect.adjusted(-halfPen, -halfPen, halfPen, halfPen)); // extend default clip rect so thicker pens (especially during selection) are not clipped
17968     painter->drawRect(iconRect);
17969   }
17970 }
17971 
17972 /*! \internal
17973 
17974   Calculates and returns the size of this item. This includes the icon, the text and the padding in
17975   between.
17976 
17977   \seebaseclassmethod
17978 */
minimumSizeHint() const17979 QSize QCPPlottableLegendItem::minimumSizeHint() const
17980 {
17981   if (!mPlottable) return QSize();
17982   QSize result(0, 0);
17983   QRect textRect;
17984   QFontMetrics fontMetrics(getFont());
17985   QSize iconSize = mParentLegend->iconSize();
17986   textRect = fontMetrics.boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPlottable->name());
17987   result.setWidth(iconSize.width() + mParentLegend->iconTextPadding() + textRect.width() + mMargins.left() + mMargins.right());
17988   result.setHeight(qMax(textRect.height(), iconSize.height()) + mMargins.top() + mMargins.bottom());
17989   return result;
17990 }
17991 
17992 
17993 ////////////////////////////////////////////////////////////////////////////////////////////////////
17994 //////////////////// QCPLegend
17995 ////////////////////////////////////////////////////////////////////////////////////////////////////
17996 
17997 /*! \class QCPLegend
17998   \brief Manages a legend inside a QCustomPlot.
17999 
18000   A legend is a small box somewhere in the plot which lists plottables with their name and icon.
18001 
18002   Normally, the legend is populated by calling \ref QCPAbstractPlottable::addToLegend. The
18003   respective legend item can be removed with \ref QCPAbstractPlottable::removeFromLegend. However,
18004   QCPLegend also offers an interface to add and manipulate legend items directly: \ref item, \ref
18005   itemWithPlottable, \ref itemCount, \ref addItem, \ref removeItem, etc.
18006 
18007   Since \ref QCPLegend derives from \ref QCPLayoutGrid, it can be placed in any position a \ref
18008   QCPLayoutElement may be positioned. The legend items are themselves \ref QCPLayoutElement
18009   "QCPLayoutElements" which are placed in the grid layout of the legend. \ref QCPLegend only adds
18010   an interface specialized for handling child elements of type \ref QCPAbstractLegendItem, as
18011   mentioned above. In principle, any other layout elements may also be added to a legend via the
18012   normal \ref QCPLayoutGrid interface. See the special page about \link thelayoutsystem The Layout
18013   System\endlink for examples on how to add other elements to the legend and move it outside the axis
18014   rect.
18015 
18016   Use the methods \ref setFillOrder and \ref setWrap inherited from \ref QCPLayoutGrid to control
18017   in which order (column first or row first) the legend is filled up when calling \ref addItem, and
18018   at which column or row wrapping occurs.
18019 
18020   By default, every QCustomPlot has one legend (\ref QCustomPlot::legend) which is placed in the
18021   inset layout of the main axis rect (\ref QCPAxisRect::insetLayout). To move the legend to another
18022   position inside the axis rect, use the methods of the \ref QCPLayoutInset. To move the legend
18023   outside of the axis rect, place it anywhere else with the \ref QCPLayout/\ref QCPLayoutElement
18024   interface.
18025 */
18026 
18027 /* start of documentation of signals */
18028 
18029 /*! \fn void QCPLegend::selectionChanged(QCPLegend::SelectableParts selection);
18030 
18031   This signal is emitted when the selection state of this legend has changed.
18032 
18033   \see setSelectedParts, setSelectableParts
18034 */
18035 
18036 /* end of documentation of signals */
18037 
18038 /*!
18039   Constructs a new QCPLegend instance with default values.
18040 
18041   Note that by default, QCustomPlot already contains a legend ready to be used as \ref
18042   QCustomPlot::legend
18043 */
QCPLegend()18044 QCPLegend::QCPLegend()
18045 {
18046   setFillOrder(QCPLayoutGrid::foRowsFirst);
18047   setWrap(0);
18048 
18049   setRowSpacing(3);
18050   setColumnSpacing(8);
18051   setMargins(QMargins(7, 5, 7, 4));
18052   setAntialiased(false);
18053   setIconSize(32, 18);
18054 
18055   setIconTextPadding(7);
18056 
18057   setSelectableParts(spLegendBox | spItems);
18058   setSelectedParts(spNone);
18059 
18060   setBorderPen(QPen(Qt::black, 0));
18061   setSelectedBorderPen(QPen(Qt::blue, 2));
18062   setIconBorderPen(Qt::NoPen);
18063   setSelectedIconBorderPen(QPen(Qt::blue, 2));
18064   setBrush(Qt::white);
18065   setSelectedBrush(Qt::white);
18066   setTextColor(Qt::black);
18067   setSelectedTextColor(Qt::blue);
18068 }
18069 
~QCPLegend()18070 QCPLegend::~QCPLegend()
18071 {
18072   clearItems();
18073   if (qobject_cast<QCustomPlot*>(mParentPlot)) // make sure this isn't called from QObject dtor when QCustomPlot is already destructed (happens when the legend is not in any layout and thus QObject-child of QCustomPlot)
18074     mParentPlot->legendRemoved(this);
18075 }
18076 
18077 /* no doc for getter, see setSelectedParts */
selectedParts() const18078 QCPLegend::SelectableParts QCPLegend::selectedParts() const
18079 {
18080   // check whether any legend elements selected, if yes, add spItems to return value
18081   bool hasSelectedItems = false;
18082   for (int i=0; i<itemCount(); ++i)
18083   {
18084     if (item(i) && item(i)->selected())
18085     {
18086       hasSelectedItems = true;
18087       break;
18088     }
18089   }
18090   if (hasSelectedItems)
18091     return mSelectedParts | spItems;
18092   else
18093     return mSelectedParts & ~spItems;
18094 }
18095 
18096 /*!
18097   Sets the pen, the border of the entire legend is drawn with.
18098 */
setBorderPen(const QPen & pen)18099 void QCPLegend::setBorderPen(const QPen &pen)
18100 {
18101   mBorderPen = pen;
18102 }
18103 
18104 /*!
18105   Sets the brush of the legend background.
18106 */
setBrush(const QBrush & brush)18107 void QCPLegend::setBrush(const QBrush &brush)
18108 {
18109   mBrush = brush;
18110 }
18111 
18112 /*!
18113   Sets the default font of legend text. Legend items that draw text (e.g. the name of a graph) will
18114   use this font by default. However, a different font can be specified on a per-item-basis by
18115   accessing the specific legend item.
18116 
18117   This function will also set \a font on all already existing legend items.
18118 
18119   \see QCPAbstractLegendItem::setFont
18120 */
setFont(const QFont & font)18121 void QCPLegend::setFont(const QFont &font)
18122 {
18123   mFont = font;
18124   for (int i=0; i<itemCount(); ++i)
18125   {
18126     if (item(i))
18127       item(i)->setFont(mFont);
18128   }
18129 }
18130 
18131 /*!
18132   Sets the default color of legend text. Legend items that draw text (e.g. the name of a graph)
18133   will use this color by default. However, a different colors can be specified on a per-item-basis
18134   by accessing the specific legend item.
18135 
18136   This function will also set \a color on all already existing legend items.
18137 
18138   \see QCPAbstractLegendItem::setTextColor
18139 */
setTextColor(const QColor & color)18140 void QCPLegend::setTextColor(const QColor &color)
18141 {
18142   mTextColor = color;
18143   for (int i=0; i<itemCount(); ++i)
18144   {
18145     if (item(i))
18146       item(i)->setTextColor(color);
18147   }
18148 }
18149 
18150 /*!
18151   Sets the size of legend icons. Legend items that draw an icon (e.g. a visual
18152   representation of the graph) will use this size by default.
18153 */
setIconSize(const QSize & size)18154 void QCPLegend::setIconSize(const QSize &size)
18155 {
18156   mIconSize = size;
18157 }
18158 
18159 /*! \overload
18160 */
setIconSize(int width,int height)18161 void QCPLegend::setIconSize(int width, int height)
18162 {
18163   mIconSize.setWidth(width);
18164   mIconSize.setHeight(height);
18165 }
18166 
18167 /*!
18168   Sets the horizontal space in pixels between the legend icon and the text next to it.
18169   Legend items that draw an icon (e.g. a visual representation of the graph) and text (e.g. the
18170   name of the graph) will use this space by default.
18171 */
setIconTextPadding(int padding)18172 void QCPLegend::setIconTextPadding(int padding)
18173 {
18174   mIconTextPadding = padding;
18175 }
18176 
18177 /*!
18178   Sets the pen used to draw a border around each legend icon. Legend items that draw an
18179   icon (e.g. a visual representation of the graph) will use this pen by default.
18180 
18181   If no border is wanted, set this to \a Qt::NoPen.
18182 */
setIconBorderPen(const QPen & pen)18183 void QCPLegend::setIconBorderPen(const QPen &pen)
18184 {
18185   mIconBorderPen = pen;
18186 }
18187 
18188 /*!
18189   Sets whether the user can (de-)select the parts in \a selectable by clicking on the QCustomPlot surface.
18190   (When \ref QCustomPlot::setInteractions contains \ref QCP::iSelectLegend.)
18191 
18192   However, even when \a selectable is set to a value not allowing the selection of a specific part,
18193   it is still possible to set the selection of this part manually, by calling \ref setSelectedParts
18194   directly.
18195 
18196   \see SelectablePart, setSelectedParts
18197 */
setSelectableParts(const SelectableParts & selectable)18198 void QCPLegend::setSelectableParts(const SelectableParts &selectable)
18199 {
18200   if (mSelectableParts != selectable)
18201   {
18202     mSelectableParts = selectable;
18203     emit selectableChanged(mSelectableParts);
18204   }
18205 }
18206 
18207 /*!
18208   Sets the selected state of the respective legend parts described by \ref SelectablePart. When a part
18209   is selected, it uses a different pen/font and brush. If some legend items are selected and \a selected
18210   doesn't contain \ref spItems, those items become deselected.
18211 
18212   The entire selection mechanism is handled automatically when \ref QCustomPlot::setInteractions
18213   contains iSelectLegend. You only need to call this function when you wish to change the selection
18214   state manually.
18215 
18216   This function can change the selection state of a part even when \ref setSelectableParts was set to a
18217   value that actually excludes the part.
18218 
18219   emits the \ref selectionChanged signal when \a selected is different from the previous selection state.
18220 
18221   Note that it doesn't make sense to set the selected state \ref spItems here when it wasn't set
18222   before, because there's no way to specify which exact items to newly select. Do this by calling
18223   \ref QCPAbstractLegendItem::setSelected directly on the legend item you wish to select.
18224 
18225   \see SelectablePart, setSelectableParts, selectTest, setSelectedBorderPen, setSelectedIconBorderPen, setSelectedBrush,
18226   setSelectedFont
18227 */
setSelectedParts(const SelectableParts & selected)18228 void QCPLegend::setSelectedParts(const SelectableParts &selected)
18229 {
18230   SelectableParts newSelected = selected;
18231   mSelectedParts = this->selectedParts(); // update mSelectedParts in case item selection changed
18232 
18233   if (mSelectedParts != newSelected)
18234   {
18235     if (!mSelectedParts.testFlag(spItems) && newSelected.testFlag(spItems)) // attempt to set spItems flag (can't do that)
18236     {
18237       qDebug() << Q_FUNC_INFO << "spItems flag can not be set, it can only be unset with this function";
18238       newSelected &= ~spItems;
18239     }
18240     if (mSelectedParts.testFlag(spItems) && !newSelected.testFlag(spItems)) // spItems flag was unset, so clear item selection
18241     {
18242       for (int i=0; i<itemCount(); ++i)
18243       {
18244         if (item(i))
18245           item(i)->setSelected(false);
18246       }
18247     }
18248     mSelectedParts = newSelected;
18249     emit selectionChanged(mSelectedParts);
18250   }
18251 }
18252 
18253 /*!
18254   When the legend box is selected, this pen is used to draw the border instead of the normal pen
18255   set via \ref setBorderPen.
18256 
18257   \see setSelectedParts, setSelectableParts, setSelectedBrush
18258 */
setSelectedBorderPen(const QPen & pen)18259 void QCPLegend::setSelectedBorderPen(const QPen &pen)
18260 {
18261   mSelectedBorderPen = pen;
18262 }
18263 
18264 /*!
18265   Sets the pen legend items will use to draw their icon borders, when they are selected.
18266 
18267   \see setSelectedParts, setSelectableParts, setSelectedFont
18268 */
setSelectedIconBorderPen(const QPen & pen)18269 void QCPLegend::setSelectedIconBorderPen(const QPen &pen)
18270 {
18271   mSelectedIconBorderPen = pen;
18272 }
18273 
18274 /*!
18275   When the legend box is selected, this brush is used to draw the legend background instead of the normal brush
18276   set via \ref setBrush.
18277 
18278   \see setSelectedParts, setSelectableParts, setSelectedBorderPen
18279 */
setSelectedBrush(const QBrush & brush)18280 void QCPLegend::setSelectedBrush(const QBrush &brush)
18281 {
18282   mSelectedBrush = brush;
18283 }
18284 
18285 /*!
18286   Sets the default font that is used by legend items when they are selected.
18287 
18288   This function will also set \a font on all already existing legend items.
18289 
18290   \see setFont, QCPAbstractLegendItem::setSelectedFont
18291 */
setSelectedFont(const QFont & font)18292 void QCPLegend::setSelectedFont(const QFont &font)
18293 {
18294   mSelectedFont = font;
18295   for (int i=0; i<itemCount(); ++i)
18296   {
18297     if (item(i))
18298       item(i)->setSelectedFont(font);
18299   }
18300 }
18301 
18302 /*!
18303   Sets the default text color that is used by legend items when they are selected.
18304 
18305   This function will also set \a color on all already existing legend items.
18306 
18307   \see setTextColor, QCPAbstractLegendItem::setSelectedTextColor
18308 */
setSelectedTextColor(const QColor & color)18309 void QCPLegend::setSelectedTextColor(const QColor &color)
18310 {
18311   mSelectedTextColor = color;
18312   for (int i=0; i<itemCount(); ++i)
18313   {
18314     if (item(i))
18315       item(i)->setSelectedTextColor(color);
18316   }
18317 }
18318 
18319 /*!
18320   Returns the item with index \a i.
18321 
18322   Note that the linear index depends on the current fill order (\ref setFillOrder).
18323 
18324   \see itemCount, addItem, itemWithPlottable
18325 */
item(int index) const18326 QCPAbstractLegendItem *QCPLegend::item(int index) const
18327 {
18328   return qobject_cast<QCPAbstractLegendItem*>(elementAt(index));
18329 }
18330 
18331 /*!
18332   Returns the QCPPlottableLegendItem which is associated with \a plottable (e.g. a \ref QCPGraph*).
18333   If such an item isn't in the legend, returns 0.
18334 
18335   \see hasItemWithPlottable
18336 */
itemWithPlottable(const QCPAbstractPlottable * plottable) const18337 QCPPlottableLegendItem *QCPLegend::itemWithPlottable(const QCPAbstractPlottable *plottable) const
18338 {
18339   for (int i=0; i<itemCount(); ++i)
18340   {
18341     if (QCPPlottableLegendItem *pli = qobject_cast<QCPPlottableLegendItem*>(item(i)))
18342     {
18343       if (pli->plottable() == plottable)
18344         return pli;
18345     }
18346   }
18347   return 0;
18348 }
18349 
18350 /*!
18351   Returns the number of items currently in the legend.
18352 
18353   Note that if empty cells are in the legend (e.g. by calling methods of the \ref QCPLayoutGrid
18354   base class which allows creating empty cells), they are included in the returned count.
18355 
18356   \see item
18357 */
itemCount() const18358 int QCPLegend::itemCount() const
18359 {
18360   return elementCount();
18361 }
18362 
18363 /*!
18364   Returns whether the legend contains \a item.
18365 
18366   \see hasItemWithPlottable
18367 */
hasItem(QCPAbstractLegendItem * item) const18368 bool QCPLegend::hasItem(QCPAbstractLegendItem *item) const
18369 {
18370   for (int i=0; i<itemCount(); ++i)
18371   {
18372     if (item == this->item(i))
18373         return true;
18374   }
18375   return false;
18376 }
18377 
18378 /*!
18379   Returns whether the legend contains a QCPPlottableLegendItem which is associated with \a plottable (e.g. a \ref QCPGraph*).
18380   If such an item isn't in the legend, returns false.
18381 
18382   \see itemWithPlottable
18383 */
hasItemWithPlottable(const QCPAbstractPlottable * plottable) const18384 bool QCPLegend::hasItemWithPlottable(const QCPAbstractPlottable *plottable) const
18385 {
18386   return itemWithPlottable(plottable);
18387 }
18388 
18389 /*!
18390   Adds \a item to the legend, if it's not present already. The element is arranged according to the
18391   current fill order (\ref setFillOrder) and wrapping (\ref setWrap).
18392 
18393   Returns true on sucess, i.e. if the item wasn't in the list already and has been successfuly added.
18394 
18395   The legend takes ownership of the item.
18396 
18397   \see removeItem, item, hasItem
18398 */
addItem(QCPAbstractLegendItem * item)18399 bool QCPLegend::addItem(QCPAbstractLegendItem *item)
18400 {
18401   return addElement(item);
18402 }
18403 
18404 /*! \overload
18405 
18406   Removes the item with the specified \a index from the legend and deletes it.
18407 
18408   After successful removal, the legend is reordered according to the current fill order (\ref
18409   setFillOrder) and wrapping (\ref setWrap), so no empty cell remains where the removed \a item
18410   was. If you don't want this, rather use the raw element interface of \ref QCPLayoutGrid.
18411 
18412   Returns true, if successful. Unlike \ref QCPLayoutGrid::removeAt, this method only removes
18413   elements derived from \ref QCPAbstractLegendItem.
18414 
18415   \see itemCount, clearItems
18416 */
removeItem(int index)18417 bool QCPLegend::removeItem(int index)
18418 {
18419   if (QCPAbstractLegendItem *ali = item(index))
18420   {
18421     bool success = remove(ali);
18422     if (success)
18423       setFillOrder(fillOrder(), true); // gets rid of empty cell by reordering
18424     return success;
18425   } else
18426     return false;
18427 }
18428 
18429 /*! \overload
18430 
18431   Removes \a item from the legend and deletes it.
18432 
18433   After successful removal, the legend is reordered according to the current fill order (\ref
18434   setFillOrder) and wrapping (\ref setWrap), so no empty cell remains where the removed \a item
18435   was. If you don't want this, rather use the raw element interface of \ref QCPLayoutGrid.
18436 
18437   Returns true, if successful.
18438 
18439   \see clearItems
18440 */
removeItem(QCPAbstractLegendItem * item)18441 bool QCPLegend::removeItem(QCPAbstractLegendItem *item)
18442 {
18443   bool success = remove(item);
18444   if (success)
18445     setFillOrder(fillOrder(), true); // gets rid of empty cell by reordering
18446   return success;
18447 }
18448 
18449 /*!
18450   Removes all items from the legend.
18451 */
clearItems()18452 void QCPLegend::clearItems()
18453 {
18454   for (int i=itemCount()-1; i>=0; --i)
18455     removeItem(i);
18456 }
18457 
18458 /*!
18459   Returns the legend items that are currently selected. If no items are selected,
18460   the list is empty.
18461 
18462   \see QCPAbstractLegendItem::setSelected, setSelectable
18463 */
selectedItems() const18464 QList<QCPAbstractLegendItem *> QCPLegend::selectedItems() const
18465 {
18466   QList<QCPAbstractLegendItem*> result;
18467   for (int i=0; i<itemCount(); ++i)
18468   {
18469     if (QCPAbstractLegendItem *ali = item(i))
18470     {
18471       if (ali->selected())
18472         result.append(ali);
18473     }
18474   }
18475   return result;
18476 }
18477 
18478 /*! \internal
18479 
18480   A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
18481   before drawing main legend elements.
18482 
18483   This is the antialiasing state the painter passed to the \ref draw method is in by default.
18484 
18485   This function takes into account the local setting of the antialiasing flag as well as the
18486   overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
18487   QCustomPlot::setNotAntialiasedElements.
18488 
18489   \seebaseclassmethod
18490 
18491   \see setAntialiased
18492 */
applyDefaultAntialiasingHint(QCPPainter * painter) const18493 void QCPLegend::applyDefaultAntialiasingHint(QCPPainter *painter) const
18494 {
18495   applyAntialiasingHint(painter, mAntialiased, QCP::aeLegend);
18496 }
18497 
18498 /*! \internal
18499 
18500   Returns the pen used to paint the border of the legend, taking into account the selection state
18501   of the legend box.
18502 */
getBorderPen() const18503 QPen QCPLegend::getBorderPen() const
18504 {
18505   return mSelectedParts.testFlag(spLegendBox) ? mSelectedBorderPen : mBorderPen;
18506 }
18507 
18508 /*! \internal
18509 
18510   Returns the brush used to paint the background of the legend, taking into account the selection
18511   state of the legend box.
18512 */
getBrush() const18513 QBrush QCPLegend::getBrush() const
18514 {
18515   return mSelectedParts.testFlag(spLegendBox) ? mSelectedBrush : mBrush;
18516 }
18517 
18518 /*! \internal
18519 
18520   Draws the legend box with the provided \a painter. The individual legend items are layerables
18521   themselves, thus are drawn independently.
18522 */
draw(QCPPainter * painter)18523 void QCPLegend::draw(QCPPainter *painter)
18524 {
18525   // draw background rect:
18526   painter->setBrush(getBrush());
18527   painter->setPen(getBorderPen());
18528   painter->drawRect(mOuterRect);
18529 }
18530 
18531 /* inherits documentation from base class */
selectTest(const QPointF & pos,bool onlySelectable,QVariant * details) const18532 double QCPLegend::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
18533 {
18534   if (!mParentPlot) return -1;
18535   if (onlySelectable && !mSelectableParts.testFlag(spLegendBox))
18536     return -1;
18537 
18538   if (mOuterRect.contains(pos.toPoint()))
18539   {
18540     if (details) details->setValue(spLegendBox);
18541     return mParentPlot->selectionTolerance()*0.99;
18542   }
18543   return -1;
18544 }
18545 
18546 /* inherits documentation from base class */
selectEvent(QMouseEvent * event,bool additive,const QVariant & details,bool * selectionStateChanged)18547 void QCPLegend::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
18548 {
18549   Q_UNUSED(event)
18550   mSelectedParts = selectedParts(); // in case item selection has changed
18551   if (details.value<SelectablePart>() == spLegendBox && mSelectableParts.testFlag(spLegendBox))
18552   {
18553     SelectableParts selBefore = mSelectedParts;
18554     setSelectedParts(additive ? mSelectedParts^spLegendBox : mSelectedParts|spLegendBox); // no need to unset spItems in !additive case, because they will be deselected by QCustomPlot (they're normal QCPLayerables with own deselectEvent)
18555     if (selectionStateChanged)
18556       *selectionStateChanged = mSelectedParts != selBefore;
18557   }
18558 }
18559 
18560 /* inherits documentation from base class */
deselectEvent(bool * selectionStateChanged)18561 void QCPLegend::deselectEvent(bool *selectionStateChanged)
18562 {
18563   mSelectedParts = selectedParts(); // in case item selection has changed
18564   if (mSelectableParts.testFlag(spLegendBox))
18565   {
18566     SelectableParts selBefore = mSelectedParts;
18567     setSelectedParts(selectedParts() & ~spLegendBox);
18568     if (selectionStateChanged)
18569       *selectionStateChanged = mSelectedParts != selBefore;
18570   }
18571 }
18572 
18573 /* inherits documentation from base class */
selectionCategory() const18574 QCP::Interaction QCPLegend::selectionCategory() const
18575 {
18576   return QCP::iSelectLegend;
18577 }
18578 
18579 /* inherits documentation from base class */
selectionCategory() const18580 QCP::Interaction QCPAbstractLegendItem::selectionCategory() const
18581 {
18582   return QCP::iSelectLegend;
18583 }
18584 
18585 /* inherits documentation from base class */
parentPlotInitialized(QCustomPlot * parentPlot)18586 void QCPLegend::parentPlotInitialized(QCustomPlot *parentPlot)
18587 {
18588   if (parentPlot && !parentPlot->legend)
18589     parentPlot->legend = this;
18590 }
18591 /* end of 'src/layoutelements/layoutelement-legend.cpp' */
18592 
18593 
18594 /* including file 'src/layoutelements/layoutelement-textelement.cpp', size 12759 */
18595 /* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200     */
18596 
18597 ////////////////////////////////////////////////////////////////////////////////////////////////////
18598 //////////////////// QCPTextElement
18599 ////////////////////////////////////////////////////////////////////////////////////////////////////
18600 
18601 /*! \class QCPTextElement
18602   \brief A layout element displaying a text
18603 
18604   The text may be specified with \ref setText, the formatting can be controlled with \ref setFont,
18605   \ref setTextColor, and \ref setTextFlags.
18606 
18607   A text element can be added as follows:
18608   \snippet documentation/doc-code-snippets/mainwindow.cpp qcptextelement-creation
18609 */
18610 
18611 /* start documentation of signals */
18612 
18613 /*! \fn void QCPTextElement::selectionChanged(bool selected)
18614 
18615   This signal is emitted when the selection state has changed to \a selected, either by user
18616   interaction or by a direct call to \ref setSelected.
18617 
18618   \see setSelected, setSelectable
18619 */
18620 
18621 /*! \fn void QCPTextElement::clicked(QMouseEvent *event)
18622 
18623   This signal is emitted when the text element is clicked.
18624 
18625   \see doubleClicked, selectTest
18626 */
18627 
18628 /*! \fn void QCPTextElement::doubleClicked(QMouseEvent *event)
18629 
18630   This signal is emitted when the text element is double clicked.
18631 
18632   \see clicked, selectTest
18633 */
18634 
18635 /* end documentation of signals */
18636 
18637 /*! \overload
18638 
18639   Creates a new QCPTextElement instance and sets default values. The initial text is empty (\ref
18640   setText).
18641 */
QCPTextElement(QCustomPlot * parentPlot)18642 QCPTextElement::QCPTextElement(QCustomPlot *parentPlot) :
18643   QCPLayoutElement(parentPlot),
18644   mText(),
18645   mTextFlags(Qt::AlignCenter|Qt::TextWordWrap),
18646   mFont(QFont(QLatin1String("sans serif"), 12)), // will be taken from parentPlot if available, see below
18647   mTextColor(Qt::black),
18648   mSelectedFont(QFont(QLatin1String("sans serif"), 12)), // will be taken from parentPlot if available, see below
18649   mSelectedTextColor(Qt::blue),
18650   mSelectable(false),
18651   mSelected(false)
18652 {
18653   if (parentPlot)
18654   {
18655     mFont = parentPlot->font();
18656     mSelectedFont = parentPlot->font();
18657   }
18658   setMargins(QMargins(2, 2, 2, 2));
18659 }
18660 
18661 /*! \overload
18662 
18663   Creates a new QCPTextElement instance and sets default values.
18664 
18665   The initial text is set to \a text.
18666 */
QCPTextElement(QCustomPlot * parentPlot,const QString & text)18667 QCPTextElement::QCPTextElement(QCustomPlot *parentPlot, const QString &text) :
18668   QCPLayoutElement(parentPlot),
18669   mText(text),
18670   mTextFlags(Qt::AlignCenter|Qt::TextWordWrap),
18671   mFont(QFont(QLatin1String("sans serif"), 12)), // will be taken from parentPlot if available, see below
18672   mTextColor(Qt::black),
18673   mSelectedFont(QFont(QLatin1String("sans serif"), 12)), // will be taken from parentPlot if available, see below
18674   mSelectedTextColor(Qt::blue),
18675   mSelectable(false),
18676   mSelected(false)
18677 {
18678   if (parentPlot)
18679   {
18680     mFont = parentPlot->font();
18681     mSelectedFont = parentPlot->font();
18682   }
18683   setMargins(QMargins(2, 2, 2, 2));
18684 }
18685 
18686 /*! \overload
18687 
18688   Creates a new QCPTextElement instance and sets default values.
18689 
18690   The initial text is set to \a text with \a pointSize.
18691 */
QCPTextElement(QCustomPlot * parentPlot,const QString & text,double pointSize)18692 QCPTextElement::QCPTextElement(QCustomPlot *parentPlot, const QString &text, double pointSize) :
18693   QCPLayoutElement(parentPlot),
18694   mText(text),
18695   mTextFlags(Qt::AlignCenter|Qt::TextWordWrap),
18696   mFont(QFont(QLatin1String("sans serif"), pointSize)), // will be taken from parentPlot if available, see below
18697   mTextColor(Qt::black),
18698   mSelectedFont(QFont(QLatin1String("sans serif"), pointSize)), // will be taken from parentPlot if available, see below
18699   mSelectedTextColor(Qt::blue),
18700   mSelectable(false),
18701   mSelected(false)
18702 {
18703   if (parentPlot)
18704   {
18705     mFont = parentPlot->font();
18706     mFont.setPointSizeF(pointSize);
18707     mSelectedFont = parentPlot->font();
18708     mSelectedFont.setPointSizeF(pointSize);
18709   }
18710   setMargins(QMargins(2, 2, 2, 2));
18711 }
18712 
18713 /*! \overload
18714 
18715   Creates a new QCPTextElement instance and sets default values.
18716 
18717   The initial text is set to \a text with \a pointSize and the specified \a fontFamily.
18718 */
QCPTextElement(QCustomPlot * parentPlot,const QString & text,const QString & fontFamily,double pointSize)18719 QCPTextElement::QCPTextElement(QCustomPlot *parentPlot, const QString &text, const QString &fontFamily, double pointSize) :
18720   QCPLayoutElement(parentPlot),
18721   mText(text),
18722   mTextFlags(Qt::AlignCenter|Qt::TextWordWrap),
18723   mFont(QFont(fontFamily, pointSize)),
18724   mTextColor(Qt::black),
18725   mSelectedFont(QFont(fontFamily, pointSize)),
18726   mSelectedTextColor(Qt::blue),
18727   mSelectable(false),
18728   mSelected(false)
18729 {
18730   setMargins(QMargins(2, 2, 2, 2));
18731 }
18732 
18733 /*! \overload
18734 
18735   Creates a new QCPTextElement instance and sets default values.
18736 
18737   The initial text is set to \a text with the specified \a font.
18738 */
QCPTextElement(QCustomPlot * parentPlot,const QString & text,const QFont & font)18739 QCPTextElement::QCPTextElement(QCustomPlot *parentPlot, const QString &text, const QFont &font) :
18740   QCPLayoutElement(parentPlot),
18741   mText(text),
18742   mTextFlags(Qt::AlignCenter|Qt::TextWordWrap),
18743   mFont(font),
18744   mTextColor(Qt::black),
18745   mSelectedFont(font),
18746   mSelectedTextColor(Qt::blue),
18747   mSelectable(false),
18748   mSelected(false)
18749 {
18750   setMargins(QMargins(2, 2, 2, 2));
18751 }
18752 
18753 /*!
18754   Sets the text that will be displayed to \a text. Multiple lines can be created by insertion of "\n".
18755 
18756   \see setFont, setTextColor, setTextFlags
18757 */
setText(const QString & text)18758 void QCPTextElement::setText(const QString &text)
18759 {
18760   mText = text;
18761 }
18762 
18763 /*!
18764   Sets options for text alignment and wrapping behaviour. \a flags is a bitwise OR-combination of
18765   \c Qt::AlignmentFlag and \c Qt::TextFlag enums.
18766 
18767   Possible enums are:
18768   - Qt::AlignLeft
18769   - Qt::AlignRight
18770   - Qt::AlignHCenter
18771   - Qt::AlignJustify
18772   - Qt::AlignTop
18773   - Qt::AlignBottom
18774   - Qt::AlignVCenter
18775   - Qt::AlignCenter
18776   - Qt::TextDontClip
18777   - Qt::TextSingleLine
18778   - Qt::TextExpandTabs
18779   - Qt::TextShowMnemonic
18780   - Qt::TextWordWrap
18781   - Qt::TextIncludeTrailingSpaces
18782 */
setTextFlags(int flags)18783 void QCPTextElement::setTextFlags(int flags)
18784 {
18785   mTextFlags = flags;
18786 }
18787 
18788 /*!
18789   Sets the \a font of the text.
18790 
18791   \see setTextColor, setSelectedFont
18792 */
setFont(const QFont & font)18793 void QCPTextElement::setFont(const QFont &font)
18794 {
18795   mFont = font;
18796 }
18797 
18798 /*!
18799   Sets the \a color of the text.
18800 
18801   \see setFont, setSelectedTextColor
18802 */
setTextColor(const QColor & color)18803 void QCPTextElement::setTextColor(const QColor &color)
18804 {
18805   mTextColor = color;
18806 }
18807 
18808 /*!
18809   Sets the \a font of the text that will be used if the text element is selected (\ref setSelected).
18810 
18811   \see setFont
18812 */
setSelectedFont(const QFont & font)18813 void QCPTextElement::setSelectedFont(const QFont &font)
18814 {
18815   mSelectedFont = font;
18816 }
18817 
18818 /*!
18819   Sets the \a color of the text that will be used if the text element is selected (\ref setSelected).
18820 
18821   \see setTextColor
18822 */
setSelectedTextColor(const QColor & color)18823 void QCPTextElement::setSelectedTextColor(const QColor &color)
18824 {
18825   mSelectedTextColor = color;
18826 }
18827 
18828 /*!
18829   Sets whether the user may select this text element.
18830 
18831   Note that even when \a selectable is set to <tt>false</tt>, the selection state may be changed
18832   programmatically via \ref setSelected.
18833 */
setSelectable(bool selectable)18834 void QCPTextElement::setSelectable(bool selectable)
18835 {
18836   if (mSelectable != selectable)
18837   {
18838     mSelectable = selectable;
18839     emit selectableChanged(mSelectable);
18840   }
18841 }
18842 
18843 /*!
18844   Sets the selection state of this text element to \a selected. If the selection has changed, \ref
18845   selectionChanged is emitted.
18846 
18847   Note that this function can change the selection state independently of the current \ref
18848   setSelectable state.
18849 */
setSelected(bool selected)18850 void QCPTextElement::setSelected(bool selected)
18851 {
18852   if (mSelected != selected)
18853   {
18854     mSelected = selected;
18855     emit selectionChanged(mSelected);
18856   }
18857 }
18858 
18859 /* inherits documentation from base class */
applyDefaultAntialiasingHint(QCPPainter * painter) const18860 void QCPTextElement::applyDefaultAntialiasingHint(QCPPainter *painter) const
18861 {
18862   applyAntialiasingHint(painter, mAntialiased, QCP::aeOther);
18863 }
18864 
18865 /* inherits documentation from base class */
draw(QCPPainter * painter)18866 void QCPTextElement::draw(QCPPainter *painter)
18867 {
18868   painter->setFont(mainFont());
18869   painter->setPen(QPen(mainTextColor()));
18870   painter->drawText(mRect, Qt::AlignCenter, mText, &mTextBoundingRect);
18871 }
18872 
18873 /* inherits documentation from base class */
minimumSizeHint() const18874 QSize QCPTextElement::minimumSizeHint() const
18875 {
18876   QFontMetrics metrics(mFont);
18877   QSize result = metrics.boundingRect(0, 0, 0, 0, Qt::AlignCenter, mText).size();
18878   result.rwidth() += mMargins.left() + mMargins.right();
18879   result.rheight() += mMargins.top() + mMargins.bottom();
18880   return result;
18881 }
18882 
18883 /* inherits documentation from base class */
maximumSizeHint() const18884 QSize QCPTextElement::maximumSizeHint() const
18885 {
18886   QFontMetrics metrics(mFont);
18887   QSize result = metrics.boundingRect(0, 0, 0, 0, Qt::AlignCenter, mText).size();
18888   result.rheight() += mMargins.top() + mMargins.bottom();
18889   result.setWidth(QWIDGETSIZE_MAX);
18890   return result;
18891 }
18892 
18893 /* inherits documentation from base class */
selectEvent(QMouseEvent * event,bool additive,const QVariant & details,bool * selectionStateChanged)18894 void QCPTextElement::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
18895 {
18896   Q_UNUSED(event)
18897   Q_UNUSED(details)
18898   if (mSelectable)
18899   {
18900     bool selBefore = mSelected;
18901     setSelected(additive ? !mSelected : true);
18902     if (selectionStateChanged)
18903       *selectionStateChanged = mSelected != selBefore;
18904   }
18905 }
18906 
18907 /* inherits documentation from base class */
deselectEvent(bool * selectionStateChanged)18908 void QCPTextElement::deselectEvent(bool *selectionStateChanged)
18909 {
18910   if (mSelectable)
18911   {
18912     bool selBefore = mSelected;
18913     setSelected(false);
18914     if (selectionStateChanged)
18915       *selectionStateChanged = mSelected != selBefore;
18916   }
18917 }
18918 
18919 /*!
18920   Returns 0.99*selectionTolerance (see \ref QCustomPlot::setSelectionTolerance) when \a pos is
18921   within the bounding box of the text element's text. Note that this bounding box is updated in the
18922   draw call.
18923 
18924   If \a pos is outside the text's bounding box or if \a onlySelectable is true and this text
18925   element is not selectable (\ref setSelectable), returns -1.
18926 
18927   \seebaseclassmethod
18928 */
selectTest(const QPointF & pos,bool onlySelectable,QVariant * details) const18929 double QCPTextElement::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
18930 {
18931   Q_UNUSED(details)
18932   if (onlySelectable && !mSelectable)
18933     return -1;
18934 
18935   if (mTextBoundingRect.contains(pos.toPoint()))
18936     return mParentPlot->selectionTolerance()*0.99;
18937   else
18938     return -1;
18939 }
18940 
18941 /*!
18942   Accepts the mouse event in order to emit the according click signal in the \ref
18943   mouseReleaseEvent.
18944 
18945   \seebaseclassmethod
18946 */
mousePressEvent(QMouseEvent * event,const QVariant & details)18947 void QCPTextElement::mousePressEvent(QMouseEvent *event, const QVariant &details)
18948 {
18949   Q_UNUSED(details)
18950   event->accept();
18951 }
18952 
18953 /*!
18954   Emits the \ref clicked signal if the cursor hasn't moved by more than a few pixels since the \ref
18955   mousePressEvent.
18956 
18957   \seebaseclassmethod
18958 */
mouseReleaseEvent(QMouseEvent * event,const QPointF & startPos)18959 void QCPTextElement::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos)
18960 {
18961   if ((QPointF(event->pos())-startPos).manhattanLength() <= 3)
18962     emit clicked(event);
18963 }
18964 
18965 /*!
18966   Emits the \ref doubleClicked signal.
18967 
18968   \seebaseclassmethod
18969 */
mouseDoubleClickEvent(QMouseEvent * event,const QVariant & details)18970 void QCPTextElement::mouseDoubleClickEvent(QMouseEvent *event, const QVariant &details)
18971 {
18972   Q_UNUSED(details)
18973   emit doubleClicked(event);
18974 }
18975 
18976 /*! \internal
18977 
18978   Returns the main font to be used. This is mSelectedFont if \ref setSelected is set to
18979   <tt>true</tt>, else mFont is returned.
18980 */
mainFont() const18981 QFont QCPTextElement::mainFont() const
18982 {
18983   return mSelected ? mSelectedFont : mFont;
18984 }
18985 
18986 /*! \internal
18987 
18988   Returns the main color to be used. This is mSelectedTextColor if \ref setSelected is set to
18989   <tt>true</tt>, else mTextColor is returned.
18990 */
mainTextColor() const18991 QColor QCPTextElement::mainTextColor() const
18992 {
18993   return mSelected ? mSelectedTextColor : mTextColor;
18994 }
18995 /* end of 'src/layoutelements/layoutelement-textelement.cpp' */
18996 
18997 
18998 /* including file 'src/layoutelements/layoutelement-colorscale.cpp', size 25910 */
18999 /* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200    */
19000 
19001 
19002 ////////////////////////////////////////////////////////////////////////////////////////////////////
19003 //////////////////// QCPColorScale
19004 ////////////////////////////////////////////////////////////////////////////////////////////////////
19005 
19006 /*! \class QCPColorScale
19007   \brief A color scale for use with color coding data such as QCPColorMap
19008 
19009   This layout element can be placed on the plot to correlate a color gradient with data values. It
19010   is usually used in combination with one or multiple \ref QCPColorMap "QCPColorMaps".
19011 
19012   \image html QCPColorScale.png
19013 
19014   The color scale can be either horizontal or vertical, as shown in the image above. The
19015   orientation and the side where the numbers appear is controlled with \ref setType.
19016 
19017   Use \ref QCPColorMap::setColorScale to connect a color map with a color scale. Once they are
19018   connected, they share their gradient, data range and data scale type (\ref setGradient, \ref
19019   setDataRange, \ref setDataScaleType). Multiple color maps may be associated with a single color
19020   scale, to make them all synchronize these properties.
19021 
19022   To have finer control over the number display and axis behaviour, you can directly access the
19023   \ref axis. See the documentation of QCPAxis for details about configuring axes. For example, if
19024   you want to change the number of automatically generated ticks, call
19025   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolorscale-tickcount
19026 
19027   Placing a color scale next to the main axis rect works like with any other layout element:
19028   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolorscale-creation
19029   In this case we have placed it to the right of the default axis rect, so it wasn't necessary to
19030   call \ref setType, since \ref QCPAxis::atRight is already the default. The text next to the color
19031   scale can be set with \ref setLabel.
19032 
19033   For optimum appearance (like in the image above), it may be desirable to line up the axis rect and
19034   the borders of the color scale. Use a \ref QCPMarginGroup to achieve this:
19035   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolorscale-margingroup
19036 
19037   Color scales are initialized with a non-zero minimum top and bottom margin (\ref
19038   setMinimumMargins), because vertical color scales are most common and the minimum top/bottom
19039   margin makes sure it keeps some distance to the top/bottom widget border. So if you change to a
19040   horizontal color scale by setting \ref setType to \ref QCPAxis::atBottom or \ref QCPAxis::atTop, you
19041   might want to also change the minimum margins accordingly, e.g. <tt>setMinimumMargins(QMargins(6, 0, 6, 0))</tt>.
19042 */
19043 
19044 /* start documentation of inline functions */
19045 
19046 /*! \fn QCPAxis *QCPColorScale::axis() const
19047 
19048   Returns the internal \ref QCPAxis instance of this color scale. You can access it to alter the
19049   appearance and behaviour of the axis. \ref QCPColorScale duplicates some properties in its
19050   interface for convenience. Those are \ref setDataRange (\ref QCPAxis::setRange), \ref
19051   setDataScaleType (\ref QCPAxis::setScaleType), and the method \ref setLabel (\ref
19052   QCPAxis::setLabel). As they each are connected, it does not matter whether you use the method on
19053   the QCPColorScale or on its QCPAxis.
19054 
19055   If the type of the color scale is changed with \ref setType, the axis returned by this method
19056   will change, too, to either the left, right, bottom or top axis, depending on which type was set.
19057 */
19058 
19059 /* end documentation of signals */
19060 /* start documentation of signals */
19061 
19062 /*! \fn void QCPColorScale::dataRangeChanged(const QCPRange &newRange);
19063 
19064   This signal is emitted when the data range changes.
19065 
19066   \see setDataRange
19067 */
19068 
19069 /*! \fn void QCPColorScale::dataScaleTypeChanged(QCPAxis::ScaleType scaleType);
19070 
19071   This signal is emitted when the data scale type changes.
19072 
19073   \see setDataScaleType
19074 */
19075 
19076 /*! \fn void QCPColorScale::gradientChanged(const QCPColorGradient &newGradient);
19077 
19078   This signal is emitted when the gradient changes.
19079 
19080   \see setGradient
19081 */
19082 
19083 /* end documentation of signals */
19084 
19085 /*!
19086   Constructs a new QCPColorScale.
19087 */
QCPColorScale(QCustomPlot * parentPlot)19088 QCPColorScale::QCPColorScale(QCustomPlot *parentPlot) :
19089   QCPLayoutElement(parentPlot),
19090   mType(QCPAxis::atTop), // set to atTop such that setType(QCPAxis::atRight) below doesn't skip work because it thinks it's already atRight
19091   mDataScaleType(QCPAxis::stLinear),
19092   mBarWidth(20),
19093   mAxisRect(new QCPColorScaleAxisRectPrivate(this))
19094 {
19095   setMinimumMargins(QMargins(0, 6, 0, 6)); // for default right color scale types, keep some room at bottom and top (important if no margin group is used)
19096   setType(QCPAxis::atRight);
19097   setDataRange(QCPRange(0, 6));
19098 }
19099 
~QCPColorScale()19100 QCPColorScale::~QCPColorScale()
19101 {
19102   delete mAxisRect;
19103 }
19104 
19105 /* undocumented getter */
label() const19106 QString QCPColorScale::label() const
19107 {
19108   if (!mColorAxis)
19109   {
19110     qDebug() << Q_FUNC_INFO << "internal color axis undefined";
19111     return QString();
19112   }
19113 
19114   return mColorAxis.data()->label();
19115 }
19116 
19117 /* undocumented getter */
rangeDrag() const19118 bool QCPColorScale::rangeDrag() const
19119 {
19120   if (!mAxisRect)
19121   {
19122     qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
19123     return false;
19124   }
19125 
19126   return mAxisRect.data()->rangeDrag().testFlag(QCPAxis::orientation(mType)) &&
19127       mAxisRect.data()->rangeDragAxis(QCPAxis::orientation(mType)) &&
19128       mAxisRect.data()->rangeDragAxis(QCPAxis::orientation(mType))->orientation() == QCPAxis::orientation(mType);
19129 }
19130 
19131 /* undocumented getter */
rangeZoom() const19132 bool QCPColorScale::rangeZoom() const
19133 {
19134   if (!mAxisRect)
19135   {
19136     qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
19137     return false;
19138   }
19139 
19140   return mAxisRect.data()->rangeZoom().testFlag(QCPAxis::orientation(mType)) &&
19141       mAxisRect.data()->rangeZoomAxis(QCPAxis::orientation(mType)) &&
19142       mAxisRect.data()->rangeZoomAxis(QCPAxis::orientation(mType))->orientation() == QCPAxis::orientation(mType);
19143 }
19144 
19145 /*!
19146   Sets at which side of the color scale the axis is placed, and thus also its orientation.
19147 
19148   Note that after setting \a type to a different value, the axis returned by \ref axis() will
19149   be a different one. The new axis will adopt the following properties from the previous axis: The
19150   range, scale type, label and ticker (the latter will be shared and not copied).
19151 */
setType(QCPAxis::AxisType type)19152 void QCPColorScale::setType(QCPAxis::AxisType type)
19153 {
19154   if (!mAxisRect)
19155   {
19156     qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
19157     return;
19158   }
19159   if (mType != type)
19160   {
19161     mType = type;
19162     QCPRange rangeTransfer(0, 6);
19163     QString labelTransfer;
19164     QSharedPointer<QCPAxisTicker> tickerTransfer;
19165     // transfer/revert some settings on old axis if it exists:
19166     bool doTransfer = (bool)mColorAxis;
19167     if (doTransfer)
19168     {
19169       rangeTransfer = mColorAxis.data()->range();
19170       labelTransfer = mColorAxis.data()->label();
19171       tickerTransfer = mColorAxis.data()->ticker();
19172       mColorAxis.data()->setLabel(QString());
19173       disconnect(mColorAxis.data(), SIGNAL(rangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange)));
19174       disconnect(mColorAxis.data(), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType)));
19175     }
19176     QList<QCPAxis::AxisType> allAxisTypes = QList<QCPAxis::AxisType>() << QCPAxis::atLeft << QCPAxis::atRight << QCPAxis::atBottom << QCPAxis::atTop;
19177     foreach (QCPAxis::AxisType atype, allAxisTypes)
19178     {
19179       mAxisRect.data()->axis(atype)->setTicks(atype == mType);
19180       mAxisRect.data()->axis(atype)->setTickLabels(atype== mType);
19181     }
19182     // set new mColorAxis pointer:
19183     mColorAxis = mAxisRect.data()->axis(mType);
19184     // transfer settings to new axis:
19185     if (doTransfer)
19186     {
19187       mColorAxis.data()->setRange(rangeTransfer); // range transfer necessary if axis changes from vertical to horizontal or vice versa (axes with same orientation are synchronized via signals)
19188       mColorAxis.data()->setLabel(labelTransfer);
19189       mColorAxis.data()->setTicker(tickerTransfer);
19190     }
19191     connect(mColorAxis.data(), SIGNAL(rangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange)));
19192     connect(mColorAxis.data(), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType)));
19193     mAxisRect.data()->setRangeDragAxes(QList<QCPAxis*>() << mColorAxis.data());
19194   }
19195 }
19196 
19197 /*!
19198   Sets the range spanned by the color gradient and that is shown by the axis in the color scale.
19199 
19200   It is equivalent to calling QCPColorMap::setDataRange on any of the connected color maps. It is
19201   also equivalent to directly accessing the \ref axis and setting its range with \ref
19202   QCPAxis::setRange.
19203 
19204   \see setDataScaleType, setGradient, rescaleDataRange
19205 */
setDataRange(const QCPRange & dataRange)19206 void QCPColorScale::setDataRange(const QCPRange &dataRange)
19207 {
19208   if (mDataRange.lower != dataRange.lower || mDataRange.upper != dataRange.upper)
19209   {
19210     mDataRange = dataRange;
19211     if (mColorAxis)
19212       mColorAxis.data()->setRange(mDataRange);
19213     emit dataRangeChanged(mDataRange);
19214   }
19215 }
19216 
19217 /*!
19218   Sets the scale type of the color scale, i.e. whether values are linearly associated with colors
19219   or logarithmically.
19220 
19221   It is equivalent to calling QCPColorMap::setDataScaleType on any of the connected color maps. It is
19222   also equivalent to directly accessing the \ref axis and setting its scale type with \ref
19223   QCPAxis::setScaleType.
19224 
19225   \see setDataRange, setGradient
19226 */
setDataScaleType(QCPAxis::ScaleType scaleType)19227 void QCPColorScale::setDataScaleType(QCPAxis::ScaleType scaleType)
19228 {
19229   if (mDataScaleType != scaleType)
19230   {
19231     mDataScaleType = scaleType;
19232     if (mColorAxis)
19233       mColorAxis.data()->setScaleType(mDataScaleType);
19234     if (mDataScaleType == QCPAxis::stLogarithmic)
19235       setDataRange(mDataRange.sanitizedForLogScale());
19236     emit dataScaleTypeChanged(mDataScaleType);
19237   }
19238 }
19239 
19240 /*!
19241   Sets the color gradient that will be used to represent data values.
19242 
19243   It is equivalent to calling QCPColorMap::setGradient on any of the connected color maps.
19244 
19245   \see setDataRange, setDataScaleType
19246 */
setGradient(const QCPColorGradient & gradient)19247 void QCPColorScale::setGradient(const QCPColorGradient &gradient)
19248 {
19249   if (mGradient != gradient)
19250   {
19251     mGradient = gradient;
19252     if (mAxisRect)
19253       mAxisRect.data()->mGradientImageInvalidated = true;
19254     emit gradientChanged(mGradient);
19255   }
19256 }
19257 
19258 /*!
19259   Sets the axis label of the color scale. This is equivalent to calling \ref QCPAxis::setLabel on
19260   the internal \ref axis.
19261 */
setLabel(const QString & str)19262 void QCPColorScale::setLabel(const QString &str)
19263 {
19264   if (!mColorAxis)
19265   {
19266     qDebug() << Q_FUNC_INFO << "internal color axis undefined";
19267     return;
19268   }
19269 
19270   mColorAxis.data()->setLabel(str);
19271 }
19272 
19273 /*!
19274   Sets the width (or height, for horizontal color scales) the bar where the gradient is displayed
19275   will have.
19276 */
setBarWidth(int width)19277 void QCPColorScale::setBarWidth(int width)
19278 {
19279   mBarWidth = width;
19280 }
19281 
19282 /*!
19283   Sets whether the user can drag the data range (\ref setDataRange).
19284 
19285   Note that \ref QCP::iRangeDrag must be in the QCustomPlot's interactions (\ref
19286   QCustomPlot::setInteractions) to allow range dragging.
19287 */
setRangeDrag(bool enabled)19288 void QCPColorScale::setRangeDrag(bool enabled)
19289 {
19290   if (!mAxisRect)
19291   {
19292     qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
19293     return;
19294   }
19295 
19296   if (enabled)
19297     mAxisRect.data()->setRangeDrag(QCPAxis::orientation(mType));
19298   else
19299     mAxisRect.data()->setRangeDrag(Qt::Orientations());
19300 }
19301 
19302 /*!
19303   Sets whether the user can zoom the data range (\ref setDataRange) by scrolling the mouse wheel.
19304 
19305   Note that \ref QCP::iRangeZoom must be in the QCustomPlot's interactions (\ref
19306   QCustomPlot::setInteractions) to allow range dragging.
19307 */
setRangeZoom(bool enabled)19308 void QCPColorScale::setRangeZoom(bool enabled)
19309 {
19310   if (!mAxisRect)
19311   {
19312     qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
19313     return;
19314   }
19315 
19316   if (enabled)
19317     mAxisRect.data()->setRangeZoom(QCPAxis::orientation(mType));
19318   else
19319     mAxisRect.data()->setRangeZoom(Qt::Orientations());
19320 }
19321 
19322 /*!
19323   Returns a list of all the color maps associated with this color scale.
19324 */
colorMaps() const19325 QList<QCPColorMap*> QCPColorScale::colorMaps() const
19326 {
19327   QList<QCPColorMap*> result;
19328   for (int i=0; i<mParentPlot->plottableCount(); ++i)
19329   {
19330     if (QCPColorMap *cm = qobject_cast<QCPColorMap*>(mParentPlot->plottable(i)))
19331       if (cm->colorScale() == this)
19332         result.append(cm);
19333   }
19334   return result;
19335 }
19336 
19337 /*!
19338   Changes the data range such that all color maps associated with this color scale are fully mapped
19339   to the gradient in the data dimension.
19340 
19341   \see setDataRange
19342 */
rescaleDataRange(bool onlyVisibleMaps)19343 void QCPColorScale::rescaleDataRange(bool onlyVisibleMaps)
19344 {
19345   QList<QCPColorMap*> maps = colorMaps();
19346   QCPRange newRange;
19347   bool haveRange = false;
19348   QCP::SignDomain sign = QCP::sdBoth;
19349   if (mDataScaleType == QCPAxis::stLogarithmic)
19350     sign = (mDataRange.upper < 0 ? QCP::sdNegative : QCP::sdPositive);
19351   for (int i=0; i<maps.size(); ++i)
19352   {
19353     if (!maps.at(i)->realVisibility() && onlyVisibleMaps)
19354       continue;
19355     QCPRange mapRange;
19356     if (maps.at(i)->colorScale() == this)
19357     {
19358       bool currentFoundRange = true;
19359       mapRange = maps.at(i)->data()->dataBounds();
19360       if (sign == QCP::sdPositive)
19361       {
19362         if (mapRange.lower <= 0 && mapRange.upper > 0)
19363           mapRange.lower = mapRange.upper*1e-3;
19364         else if (mapRange.lower <= 0 && mapRange.upper <= 0)
19365           currentFoundRange = false;
19366       } else if (sign == QCP::sdNegative)
19367       {
19368         if (mapRange.upper >= 0 && mapRange.lower < 0)
19369           mapRange.upper = mapRange.lower*1e-3;
19370         else if (mapRange.upper >= 0 && mapRange.lower >= 0)
19371           currentFoundRange = false;
19372       }
19373       if (currentFoundRange)
19374       {
19375         if (!haveRange)
19376           newRange = mapRange;
19377         else
19378           newRange.expand(mapRange);
19379         haveRange = true;
19380       }
19381     }
19382   }
19383   if (haveRange)
19384   {
19385     if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this dimension), shift current range to at least center the data
19386     {
19387       double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason
19388       if (mDataScaleType == QCPAxis::stLinear)
19389       {
19390         newRange.lower = center-mDataRange.size()/2.0;
19391         newRange.upper = center+mDataRange.size()/2.0;
19392       } else // mScaleType == stLogarithmic
19393       {
19394         newRange.lower = center/qSqrt(mDataRange.upper/mDataRange.lower);
19395         newRange.upper = center*qSqrt(mDataRange.upper/mDataRange.lower);
19396       }
19397     }
19398     setDataRange(newRange);
19399   }
19400 }
19401 
19402 /* inherits documentation from base class */
update(UpdatePhase phase)19403 void QCPColorScale::update(UpdatePhase phase)
19404 {
19405   QCPLayoutElement::update(phase);
19406   if (!mAxisRect)
19407   {
19408     qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
19409     return;
19410   }
19411 
19412   mAxisRect.data()->update(phase);
19413 
19414   switch (phase)
19415   {
19416     case upMargins:
19417     {
19418       if (mType == QCPAxis::atBottom || mType == QCPAxis::atTop)
19419       {
19420         setMaximumSize(QWIDGETSIZE_MAX, mBarWidth+mAxisRect.data()->margins().top()+mAxisRect.data()->margins().bottom()+margins().top()+margins().bottom());
19421         setMinimumSize(0,               mBarWidth+mAxisRect.data()->margins().top()+mAxisRect.data()->margins().bottom()+margins().top()+margins().bottom());
19422       } else
19423       {
19424         setMaximumSize(mBarWidth+mAxisRect.data()->margins().left()+mAxisRect.data()->margins().right()+margins().left()+margins().right(), QWIDGETSIZE_MAX);
19425         setMinimumSize(mBarWidth+mAxisRect.data()->margins().left()+mAxisRect.data()->margins().right()+margins().left()+margins().right(), 0);
19426       }
19427       break;
19428     }
19429     case upLayout:
19430     {
19431       mAxisRect.data()->setOuterRect(rect());
19432       break;
19433     }
19434     default: break;
19435   }
19436 }
19437 
19438 /* inherits documentation from base class */
applyDefaultAntialiasingHint(QCPPainter * painter) const19439 void QCPColorScale::applyDefaultAntialiasingHint(QCPPainter *painter) const
19440 {
19441   painter->setAntialiasing(false);
19442 }
19443 
19444 /* inherits documentation from base class */
mousePressEvent(QMouseEvent * event,const QVariant & details)19445 void QCPColorScale::mousePressEvent(QMouseEvent *event, const QVariant &details)
19446 {
19447   if (!mAxisRect)
19448   {
19449     qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
19450     return;
19451   }
19452   mAxisRect.data()->mousePressEvent(event, details);
19453 }
19454 
19455 /* inherits documentation from base class */
mouseMoveEvent(QMouseEvent * event,const QPointF & startPos)19456 void QCPColorScale::mouseMoveEvent(QMouseEvent *event, const QPointF &startPos)
19457 {
19458   if (!mAxisRect)
19459   {
19460     qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
19461     return;
19462   }
19463   mAxisRect.data()->mouseMoveEvent(event, startPos);
19464 }
19465 
19466 /* inherits documentation from base class */
mouseReleaseEvent(QMouseEvent * event,const QPointF & startPos)19467 void QCPColorScale::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos)
19468 {
19469   if (!mAxisRect)
19470   {
19471     qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
19472     return;
19473   }
19474   mAxisRect.data()->mouseReleaseEvent(event, startPos);
19475 }
19476 
19477 /* inherits documentation from base class */
wheelEvent(QWheelEvent * event)19478 void QCPColorScale::wheelEvent(QWheelEvent *event)
19479 {
19480   if (!mAxisRect)
19481   {
19482     qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
19483     return;
19484   }
19485   mAxisRect.data()->wheelEvent(event);
19486 }
19487 
19488 ////////////////////////////////////////////////////////////////////////////////////////////////////
19489 //////////////////// QCPColorScaleAxisRectPrivate
19490 ////////////////////////////////////////////////////////////////////////////////////////////////////
19491 
19492 /*! \class QCPColorScaleAxisRectPrivate
19493 
19494   \internal
19495   \brief An axis rect subclass for use in a QCPColorScale
19496 
19497   This is a private class and not part of the public QCustomPlot interface.
19498 
19499   It provides the axis rect functionality for the QCPColorScale class.
19500 */
19501 
19502 
19503 /*!
19504   Creates a new instance, as a child of \a parentColorScale.
19505 */
QCPColorScaleAxisRectPrivate(QCPColorScale * parentColorScale)19506 QCPColorScaleAxisRectPrivate::QCPColorScaleAxisRectPrivate(QCPColorScale *parentColorScale) :
19507   QCPAxisRect(parentColorScale->parentPlot(), true),
19508   mParentColorScale(parentColorScale),
19509   mGradientImageInvalidated(true)
19510 {
19511   setParentLayerable(parentColorScale);
19512   setMinimumMargins(QMargins(0, 0, 0, 0));
19513   QList<QCPAxis::AxisType> allAxisTypes = QList<QCPAxis::AxisType>() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight;
19514   foreach (QCPAxis::AxisType type, allAxisTypes)
19515   {
19516     axis(type)->setVisible(true);
19517     axis(type)->grid()->setVisible(false);
19518     axis(type)->setPadding(0);
19519     connect(axis(type), SIGNAL(selectionChanged(QCPAxis::SelectableParts)), this, SLOT(axisSelectionChanged(QCPAxis::SelectableParts)));
19520     connect(axis(type), SIGNAL(selectableChanged(QCPAxis::SelectableParts)), this, SLOT(axisSelectableChanged(QCPAxis::SelectableParts)));
19521   }
19522 
19523   connect(axis(QCPAxis::atLeft), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atRight), SLOT(setRange(QCPRange)));
19524   connect(axis(QCPAxis::atRight), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atLeft), SLOT(setRange(QCPRange)));
19525   connect(axis(QCPAxis::atBottom), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atTop), SLOT(setRange(QCPRange)));
19526   connect(axis(QCPAxis::atTop), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atBottom), SLOT(setRange(QCPRange)));
19527   connect(axis(QCPAxis::atLeft), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atRight), SLOT(setScaleType(QCPAxis::ScaleType)));
19528   connect(axis(QCPAxis::atRight), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atLeft), SLOT(setScaleType(QCPAxis::ScaleType)));
19529   connect(axis(QCPAxis::atBottom), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atTop), SLOT(setScaleType(QCPAxis::ScaleType)));
19530   connect(axis(QCPAxis::atTop), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atBottom), SLOT(setScaleType(QCPAxis::ScaleType)));
19531 
19532   // make layer transfers of color scale transfer to axis rect and axes
19533   // the axes must be set after axis rect, such that they appear above color gradient drawn by axis rect:
19534   connect(parentColorScale, SIGNAL(layerChanged(QCPLayer*)), this, SLOT(setLayer(QCPLayer*)));
19535   foreach (QCPAxis::AxisType type, allAxisTypes)
19536     connect(parentColorScale, SIGNAL(layerChanged(QCPLayer*)), axis(type), SLOT(setLayer(QCPLayer*)));
19537 }
19538 
19539 /*! \internal
19540 
19541   Updates the color gradient image if necessary, by calling \ref updateGradientImage, then draws
19542   it. Then the axes are drawn by calling the \ref QCPAxisRect::draw base class implementation.
19543 
19544   \seebaseclassmethod
19545 */
draw(QCPPainter * painter)19546 void QCPColorScaleAxisRectPrivate::draw(QCPPainter *painter)
19547 {
19548   if (mGradientImageInvalidated)
19549     updateGradientImage();
19550 
19551   bool mirrorHorz = false;
19552   bool mirrorVert = false;
19553   if (mParentColorScale->mColorAxis)
19554   {
19555     mirrorHorz = mParentColorScale->mColorAxis.data()->rangeReversed() && (mParentColorScale->type() == QCPAxis::atBottom || mParentColorScale->type() == QCPAxis::atTop);
19556     mirrorVert = mParentColorScale->mColorAxis.data()->rangeReversed() && (mParentColorScale->type() == QCPAxis::atLeft || mParentColorScale->type() == QCPAxis::atRight);
19557   }
19558 
19559   painter->drawImage(rect().adjusted(0, -1, 0, -1), mGradientImage.mirrored(mirrorHorz, mirrorVert));
19560   QCPAxisRect::draw(painter);
19561 }
19562 
19563 /*! \internal
19564 
19565   Uses the current gradient of the parent \ref QCPColorScale (specified in the constructor) to
19566   generate a gradient image. This gradient image will be used in the \ref draw method.
19567 */
updateGradientImage()19568 void QCPColorScaleAxisRectPrivate::updateGradientImage()
19569 {
19570   if (rect().isEmpty())
19571     return;
19572 
19573   const QImage::Format format = QImage::Format_ARGB32_Premultiplied;
19574   int n = mParentColorScale->mGradient.levelCount();
19575   int w, h;
19576   QVector<double> data(n);
19577   for (int i=0; i<n; ++i)
19578     data[i] = i;
19579   if (mParentColorScale->mType == QCPAxis::atBottom || mParentColorScale->mType == QCPAxis::atTop)
19580   {
19581     w = n;
19582     h = rect().height();
19583     mGradientImage = QImage(w, h, format);
19584     QVector<QRgb*> pixels;
19585     for (int y=0; y<h; ++y)
19586       pixels.append(reinterpret_cast<QRgb*>(mGradientImage.scanLine(y)));
19587     mParentColorScale->mGradient.colorize(data.constData(), QCPRange(0, n-1), pixels.first(), n);
19588     for (int y=1; y<h; ++y)
19589       memcpy(pixels.at(y), pixels.first(), n*sizeof(QRgb));
19590   } else
19591   {
19592     w = rect().width();
19593     h = n;
19594     mGradientImage = QImage(w, h, format);
19595     for (int y=0; y<h; ++y)
19596     {
19597       QRgb *pixels = reinterpret_cast<QRgb*>(mGradientImage.scanLine(y));
19598       const QRgb lineColor = mParentColorScale->mGradient.color(data[h-1-y], QCPRange(0, n-1));
19599       for (int x=0; x<w; ++x)
19600         pixels[x] = lineColor;
19601     }
19602   }
19603   mGradientImageInvalidated = false;
19604 }
19605 
19606 /*! \internal
19607 
19608   This slot is connected to the selectionChanged signals of the four axes in the constructor. It
19609   synchronizes the selection state of the axes.
19610 */
axisSelectionChanged(QCPAxis::SelectableParts selectedParts)19611 void QCPColorScaleAxisRectPrivate::axisSelectionChanged(QCPAxis::SelectableParts selectedParts)
19612 {
19613   // axis bases of four axes shall always (de-)selected synchronously:
19614   QList<QCPAxis::AxisType> allAxisTypes = QList<QCPAxis::AxisType>() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight;
19615   foreach (QCPAxis::AxisType type, allAxisTypes)
19616   {
19617     if (QCPAxis *senderAxis = qobject_cast<QCPAxis*>(sender()))
19618       if (senderAxis->axisType() == type)
19619         continue;
19620 
19621     if (axis(type)->selectableParts().testFlag(QCPAxis::spAxis))
19622     {
19623       if (selectedParts.testFlag(QCPAxis::spAxis))
19624         axis(type)->setSelectedParts(axis(type)->selectedParts() | QCPAxis::spAxis);
19625       else
19626         axis(type)->setSelectedParts(axis(type)->selectedParts() & ~QCPAxis::spAxis);
19627     }
19628   }
19629 }
19630 
19631 /*! \internal
19632 
19633   This slot is connected to the selectableChanged signals of the four axes in the constructor. It
19634   synchronizes the selectability of the axes.
19635 */
axisSelectableChanged(QCPAxis::SelectableParts selectableParts)19636 void QCPColorScaleAxisRectPrivate::axisSelectableChanged(QCPAxis::SelectableParts selectableParts)
19637 {
19638   // synchronize axis base selectability:
19639   QList<QCPAxis::AxisType> allAxisTypes = QList<QCPAxis::AxisType>() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight;
19640   foreach (QCPAxis::AxisType type, allAxisTypes)
19641   {
19642     if (QCPAxis *senderAxis = qobject_cast<QCPAxis*>(sender()))
19643       if (senderAxis->axisType() == type)
19644         continue;
19645 
19646     if (axis(type)->selectableParts().testFlag(QCPAxis::spAxis))
19647     {
19648       if (selectableParts.testFlag(QCPAxis::spAxis))
19649         axis(type)->setSelectableParts(axis(type)->selectableParts() | QCPAxis::spAxis);
19650       else
19651         axis(type)->setSelectableParts(axis(type)->selectableParts() & ~QCPAxis::spAxis);
19652     }
19653   }
19654 }
19655 /* end of 'src/layoutelements/layoutelement-colorscale.cpp' */
19656 
19657 
19658 /* including file 'src/plottables/plottable-graph.cpp', size 72363           */
19659 /* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
19660 
19661 ////////////////////////////////////////////////////////////////////////////////////////////////////
19662 //////////////////// QCPGraphData
19663 ////////////////////////////////////////////////////////////////////////////////////////////////////
19664 
19665 /*! \class QCPGraphData
19666   \brief Holds the data of one single data point for QCPGraph.
19667 
19668   The stored data is:
19669   \li \a key: coordinate on the key axis of this data point (this is the \a mainKey and the \a sortKey)
19670   \li \a value: coordinate on the value axis of this data point (this is the \a mainValue)
19671 
19672   The container for storing multiple data points is \ref QCPGraphDataContainer. It is a typedef for
19673   \ref QCPDataContainer with \ref QCPGraphData as the DataType template parameter. See the
19674   documentation there for an explanation regarding the data type's generic methods.
19675 
19676   \see QCPGraphDataContainer
19677 */
19678 
19679 /* start documentation of inline functions */
19680 
19681 /*! \fn double QCPGraphData::sortKey() const
19682 
19683   Returns the \a key member of this data point.
19684 
19685   For a general explanation of what this method is good for in the context of the data container,
19686   see the documentation of \ref QCPDataContainer.
19687 */
19688 
19689 /*! \fn static QCPGraphData QCPGraphData::fromSortKey(double sortKey)
19690 
19691   Returns a data point with the specified \a sortKey. All other members are set to zero.
19692 
19693   For a general explanation of what this method is good for in the context of the data container,
19694   see the documentation of \ref QCPDataContainer.
19695 */
19696 
19697 /*! \fn static static bool QCPGraphData::sortKeyIsMainKey()
19698 
19699   Since the member \a key is both the data point key coordinate and the data ordering parameter,
19700   this method returns true.
19701 
19702   For a general explanation of what this method is good for in the context of the data container,
19703   see the documentation of \ref QCPDataContainer.
19704 */
19705 
19706 /*! \fn double QCPGraphData::mainKey() const
19707 
19708   Returns the \a key member of this data point.
19709 
19710   For a general explanation of what this method is good for in the context of the data container,
19711   see the documentation of \ref QCPDataContainer.
19712 */
19713 
19714 /*! \fn double QCPGraphData::mainValue() const
19715 
19716   Returns the \a value member of this data point.
19717 
19718   For a general explanation of what this method is good for in the context of the data container,
19719   see the documentation of \ref QCPDataContainer.
19720 */
19721 
19722 /*! \fn QCPRange QCPGraphData::valueRange() const
19723 
19724   Returns a QCPRange with both lower and upper boundary set to \a value of this data point.
19725 
19726   For a general explanation of what this method is good for in the context of the data container,
19727   see the documentation of \ref QCPDataContainer.
19728 */
19729 
19730 /* end documentation of inline functions */
19731 
19732 /*!
19733   Constructs a data point with key and value set to zero.
19734 */
QCPGraphData()19735 QCPGraphData::QCPGraphData() :
19736   key(0),
19737   value(0)
19738 {
19739 }
19740 
19741 /*!
19742   Constructs a data point with the specified \a key and \a value.
19743 */
QCPGraphData(double key,double value)19744 QCPGraphData::QCPGraphData(double key, double value) :
19745   key(key),
19746   value(value)
19747 {
19748 }
19749 
19750 
19751 ////////////////////////////////////////////////////////////////////////////////////////////////////
19752 //////////////////// QCPGraph
19753 ////////////////////////////////////////////////////////////////////////////////////////////////////
19754 
19755 /*! \class QCPGraph
19756   \brief A plottable representing a graph in a plot.
19757 
19758   \image html QCPGraph.png
19759 
19760   Usually you create new graphs by calling QCustomPlot::addGraph. The resulting instance can be
19761   accessed via QCustomPlot::graph.
19762 
19763   To plot data, assign it with the \ref setData or \ref addData functions. Alternatively, you can
19764   also access and modify the data via the \ref data method, which returns a pointer to the internal
19765   \ref QCPGraphDataContainer.
19766 
19767   Graphs are used to display single-valued data. Single-valued means that there should only be one
19768   data point per unique key coordinate. In other words, the graph can't have \a loops. If you do
19769   want to plot non-single-valued curves, rather use the QCPCurve plottable.
19770 
19771   Gaps in the graph line can be created by adding data points with NaN as value
19772   (<tt>qQNaN()</tt> or <tt>std::numeric_limits<double>::quiet_NaN()</tt>) in between the two data points that shall be
19773   separated.
19774 
19775   \section qcpgraph-appearance Changing the appearance
19776 
19777   The appearance of the graph is mainly determined by the line style, scatter style, brush and pen
19778   of the graph (\ref setLineStyle, \ref setScatterStyle, \ref setBrush, \ref setPen).
19779 
19780   \subsection filling Filling under or between graphs
19781 
19782   QCPGraph knows two types of fills: Normal graph fills towards the zero-value-line parallel to
19783   the key axis of the graph, and fills between two graphs, called channel fills. To enable a fill,
19784   just set a brush with \ref setBrush which is neither Qt::NoBrush nor fully transparent.
19785 
19786   By default, a normal fill towards the zero-value-line will be drawn. To set up a channel fill
19787   between this graph and another one, call \ref setChannelFillGraph with the other graph as
19788   parameter.
19789 
19790   \see QCustomPlot::addGraph, QCustomPlot::graph
19791 */
19792 
19793 /* start of documentation of inline functions */
19794 
19795 /*! \fn QSharedPointer<QCPGraphDataContainer> QCPGraph::data() const
19796 
19797   Returns a shared pointer to the internal data storage of type \ref QCPGraphDataContainer. You may
19798   use it to directly manipulate the data, which may be more convenient and faster than using the
19799   regular \ref setData or \ref addData methods.
19800 */
19801 
19802 /* end of documentation of inline functions */
19803 
19804 /*!
19805   Constructs a graph which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value
19806   axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have
19807   the same orientation. If either of these restrictions is violated, a corresponding message is
19808   printed to the debug output (qDebug), the construction is not aborted, though.
19809 
19810   The created QCPGraph is automatically registered with the QCustomPlot instance inferred from \a
19811   keyAxis. This QCustomPlot instance takes ownership of the QCPGraph, so do not delete it manually
19812   but use QCustomPlot::removePlottable() instead.
19813 
19814   To directly create a graph inside a plot, you can also use the simpler QCustomPlot::addGraph function.
19815 */
QCPGraph(QCPAxis * keyAxis,QCPAxis * valueAxis)19816 QCPGraph::QCPGraph(QCPAxis *keyAxis, QCPAxis *valueAxis) :
19817   QCPAbstractPlottable1D<QCPGraphData>(keyAxis, valueAxis)
19818 {
19819   // special handling for QCPGraphs to maintain the simple graph interface:
19820   mParentPlot->registerGraph(this);
19821 
19822   setPen(QPen(Qt::blue, 0));
19823   setBrush(Qt::NoBrush);
19824 
19825   setLineStyle(lsLine);
19826   setScatterSkip(0);
19827   setChannelFillGraph(0);
19828   setAdaptiveSampling(true);
19829 }
19830 
~QCPGraph()19831 QCPGraph::~QCPGraph()
19832 {
19833 }
19834 
19835 /*! \overload
19836 
19837   Replaces the current data container with the provided \a data container.
19838 
19839   Since a QSharedPointer is used, multiple QCPGraphs may share the same data container safely.
19840   Modifying the data in the container will then affect all graphs that share the container. Sharing
19841   can be achieved by simply exchanging the data containers wrapped in shared pointers:
19842   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpgraph-datasharing-1
19843 
19844   If you do not wish to share containers, but create a copy from an existing container, rather use
19845   the \ref QCPDataContainer<DataType>::set method on the graph's data container directly:
19846   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpgraph-datasharing-2
19847 
19848   \see addData
19849 */
setData(QSharedPointer<QCPGraphDataContainer> data)19850 void QCPGraph::setData(QSharedPointer<QCPGraphDataContainer> data)
19851 {
19852   mDataContainer = data;
19853 }
19854 
19855 /*! \overload
19856 
19857   Replaces the current data with the provided points in \a keys and \a values. The provided
19858   vectors should have equal length. Else, the number of added points will be the size of the
19859   smallest vector.
19860 
19861   If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
19862   can set \a alreadySorted to true, to improve performance by saving a sorting run.
19863 
19864   \see addData
19865 */
setData(const QVector<double> & keys,const QVector<double> & values,bool alreadySorted)19866 void QCPGraph::setData(const QVector<double> &keys, const QVector<double> &values, bool alreadySorted)
19867 {
19868   mDataContainer->clear();
19869   addData(keys, values, alreadySorted);
19870 }
19871 
19872 /*!
19873   Sets how the single data points are connected in the plot. For scatter-only plots, set \a ls to
19874   \ref lsNone and \ref setScatterStyle to the desired scatter style.
19875 
19876   \see setScatterStyle
19877 */
setLineStyle(LineStyle ls)19878 void QCPGraph::setLineStyle(LineStyle ls)
19879 {
19880   mLineStyle = ls;
19881 }
19882 
19883 /*!
19884   Sets the visual appearance of single data points in the plot. If set to \ref QCPScatterStyle::ssNone, no scatter points
19885   are drawn (e.g. for line-only-plots with appropriate line style).
19886 
19887   \see QCPScatterStyle, setLineStyle
19888 */
setScatterStyle(const QCPScatterStyle & style)19889 void QCPGraph::setScatterStyle(const QCPScatterStyle &style)
19890 {
19891   mScatterStyle = style;
19892 }
19893 
19894 /*!
19895   If scatters are displayed (scatter style not \ref QCPScatterStyle::ssNone), \a skip number of
19896   scatter points are skipped/not drawn after every drawn scatter point.
19897 
19898   This can be used to make the data appear sparser while for example still having a smooth line,
19899   and to improve performance for very high density plots.
19900 
19901   If \a skip is set to 0 (default), all scatter points are drawn.
19902 
19903   \see setScatterStyle
19904 */
setScatterSkip(int skip)19905 void QCPGraph::setScatterSkip(int skip)
19906 {
19907   mScatterSkip = qMax(0, skip);
19908 }
19909 
19910 /*!
19911   Sets the target graph for filling the area between this graph and \a targetGraph with the current
19912   brush (\ref setBrush).
19913 
19914   When \a targetGraph is set to 0, a normal graph fill to the zero-value-line will be shown. To
19915   disable any filling, set the brush to Qt::NoBrush.
19916 
19917   \see setBrush
19918 */
setChannelFillGraph(QCPGraph * targetGraph)19919 void QCPGraph::setChannelFillGraph(QCPGraph *targetGraph)
19920 {
19921   // prevent setting channel target to this graph itself:
19922   if (targetGraph == this)
19923   {
19924     qDebug() << Q_FUNC_INFO << "targetGraph is this graph itself";
19925     mChannelFillGraph = 0;
19926     return;
19927   }
19928   // prevent setting channel target to a graph not in the plot:
19929   if (targetGraph && targetGraph->mParentPlot != mParentPlot)
19930   {
19931     qDebug() << Q_FUNC_INFO << "targetGraph not in same plot";
19932     mChannelFillGraph = 0;
19933     return;
19934   }
19935 
19936   mChannelFillGraph = targetGraph;
19937 }
19938 
19939 /*!
19940   Sets whether adaptive sampling shall be used when plotting this graph. QCustomPlot's adaptive
19941   sampling technique can drastically improve the replot performance for graphs with a larger number
19942   of points (e.g. above 10,000), without notably changing the appearance of the graph.
19943 
19944   By default, adaptive sampling is enabled. Even if enabled, QCustomPlot decides whether adaptive
19945   sampling shall actually be used on a per-graph basis. So leaving adaptive sampling enabled has no
19946   disadvantage in almost all cases.
19947 
19948   \image html adaptive-sampling-line.png "A line plot of 500,000 points without and with adaptive sampling"
19949 
19950   As can be seen, line plots experience no visual degradation from adaptive sampling. Outliers are
19951   reproduced reliably, as well as the overall shape of the data set. The replot time reduces
19952   dramatically though. This allows QCustomPlot to display large amounts of data in realtime.
19953 
19954   \image html adaptive-sampling-scatter.png "A scatter plot of 100,000 points without and with adaptive sampling"
19955 
19956   Care must be taken when using high-density scatter plots in combination with adaptive sampling.
19957   The adaptive sampling algorithm treats scatter plots more carefully than line plots which still
19958   gives a significant reduction of replot times, but not quite as much as for line plots. This is
19959   because scatter plots inherently need more data points to be preserved in order to still resemble
19960   the original, non-adaptive-sampling plot. As shown above, the results still aren't quite
19961   identical, as banding occurs for the outer data points. This is in fact intentional, such that
19962   the boundaries of the data cloud stay visible to the viewer. How strong the banding appears,
19963   depends on the point density, i.e. the number of points in the plot.
19964 
19965   For some situations with scatter plots it might thus be desirable to manually turn adaptive
19966   sampling off. For example, when saving the plot to disk. This can be achieved by setting \a
19967   enabled to false before issuing a command like \ref QCustomPlot::savePng, and setting \a enabled
19968   back to true afterwards.
19969 */
setAdaptiveSampling(bool enabled)19970 void QCPGraph::setAdaptiveSampling(bool enabled)
19971 {
19972   mAdaptiveSampling = enabled;
19973 }
19974 
19975 /*! \overload
19976 
19977   Adds the provided points in \a keys and \a values to the current data. The provided vectors
19978   should have equal length. Else, the number of added points will be the size of the smallest
19979   vector.
19980 
19981   If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
19982   can set \a alreadySorted to true, to improve performance by saving a sorting run.
19983 
19984   Alternatively, you can also access and modify the data directly via the \ref data method, which
19985   returns a pointer to the internal data container.
19986 */
addData(const QVector<double> & keys,const QVector<double> & values,bool alreadySorted)19987 void QCPGraph::addData(const QVector<double> &keys, const QVector<double> &values, bool alreadySorted)
19988 {
19989   if (keys.size() != values.size())
19990     qDebug() << Q_FUNC_INFO << "keys and values have different sizes:" << keys.size() << values.size();
19991   const int n = qMin(keys.size(), values.size());
19992   QVector<QCPGraphData> tempData(n);
19993   QVector<QCPGraphData>::iterator it = tempData.begin();
19994   const QVector<QCPGraphData>::iterator itEnd = tempData.end();
19995   int i = 0;
19996   while (it != itEnd)
19997   {
19998     it->key = keys[i];
19999     it->value = values[i];
20000     ++it;
20001     ++i;
20002   }
20003   mDataContainer->add(tempData, alreadySorted); // don't modify tempData beyond this to prevent copy on write
20004 }
20005 
20006 /*! \overload
20007 
20008   Adds the provided data point as \a key and \a value to the current data.
20009 
20010   Alternatively, you can also access and modify the data directly via the \ref data method, which
20011   returns a pointer to the internal data container.
20012 */
addData(double key,double value)20013 void QCPGraph::addData(double key, double value)
20014 {
20015   mDataContainer->add(QCPGraphData(key, value));
20016 }
20017 
20018 /* inherits documentation from base class */
selectTest(const QPointF & pos,bool onlySelectable,QVariant * details) const20019 double QCPGraph::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
20020 {
20021   if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
20022     return -1;
20023   if (!mKeyAxis || !mValueAxis)
20024     return -1;
20025 
20026   if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()))
20027   {
20028     QCPGraphDataContainer::const_iterator closestDataPoint = mDataContainer->constEnd();
20029     double result = pointDistance(pos, closestDataPoint);
20030     if (details)
20031     {
20032       int pointIndex = closestDataPoint-mDataContainer->constBegin();
20033       details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1)));
20034     }
20035     return result;
20036   } else
20037     return -1;
20038 }
20039 
20040 /* inherits documentation from base class */
getKeyRange(bool & foundRange,QCP::SignDomain inSignDomain) const20041 QCPRange QCPGraph::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const
20042 {
20043   return mDataContainer->keyRange(foundRange, inSignDomain);
20044 }
20045 
20046 /* inherits documentation from base class */
getValueRange(bool & foundRange,QCP::SignDomain inSignDomain,const QCPRange & inKeyRange) const20047 QCPRange QCPGraph::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const
20048 {
20049   return mDataContainer->valueRange(foundRange, inSignDomain, inKeyRange);
20050 }
20051 
20052 /* inherits documentation from base class */
draw(QCPPainter * painter)20053 void QCPGraph::draw(QCPPainter *painter)
20054 {
20055   if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
20056   if (mKeyAxis.data()->range().size() <= 0 || mDataContainer->isEmpty()) return;
20057   if (mLineStyle == lsNone && mScatterStyle.isNone()) return;
20058 
20059   QVector<QPointF> lines, scatters; // line and (if necessary) scatter pixel coordinates will be stored here while iterating over segments
20060 
20061   // loop over and draw segments of unselected/selected data:
20062   QList<QCPDataRange> selectedSegments, unselectedSegments, allSegments;
20063   getDataSegments(selectedSegments, unselectedSegments);
20064   allSegments << unselectedSegments << selectedSegments;
20065   for (int i=0; i<allSegments.size(); ++i)
20066   {
20067     bool isSelectedSegment = i >= unselectedSegments.size();
20068     // get line pixel points appropriate to line style:
20069     QCPDataRange lineDataRange = isSelectedSegment ? allSegments.at(i) : allSegments.at(i).adjusted(-1, 1); // unselected segments extend lines to bordering selected data point (safe to exceed total data bounds in first/last segment, getLines takes care)
20070     getLines(&lines, lineDataRange);
20071 
20072     // check data validity if flag set:
20073 #ifdef QCUSTOMPLOT_CHECK_DATA
20074     QCPGraphDataContainer::const_iterator it;
20075     for (it = mDataContainer->constBegin(); it != mDataContainer->constEnd(); ++it)
20076     {
20077       if (QCP::isInvalidData(it->key, it->value))
20078         qDebug() << Q_FUNC_INFO << "Data point at" << it->key << "invalid." << "Plottable name:" << name();
20079     }
20080 #endif
20081 
20082     // draw fill of graph:
20083     if (isSelectedSegment && mSelectionDecorator)
20084       mSelectionDecorator->applyBrush(painter);
20085     else
20086       painter->setBrush(mBrush);
20087     painter->setPen(Qt::NoPen);
20088     drawFill(painter, &lines);
20089 
20090     // draw line:
20091     if (mLineStyle != lsNone)
20092     {
20093       if (isSelectedSegment && mSelectionDecorator)
20094         mSelectionDecorator->applyPen(painter);
20095       else
20096         painter->setPen(mPen);
20097       painter->setBrush(Qt::NoBrush);
20098       if (mLineStyle == lsImpulse)
20099         drawImpulsePlot(painter, lines);
20100       else
20101         drawLinePlot(painter, lines); // also step plots can be drawn as a line plot
20102     }
20103 
20104     // draw scatters:
20105     QCPScatterStyle finalScatterStyle = mScatterStyle;
20106     if (isSelectedSegment && mSelectionDecorator)
20107       finalScatterStyle = mSelectionDecorator->getFinalScatterStyle(mScatterStyle);
20108     if (!finalScatterStyle.isNone())
20109     {
20110       getScatters(&scatters, allSegments.at(i));
20111       drawScatterPlot(painter, scatters, finalScatterStyle);
20112     }
20113   }
20114 
20115   // draw other selection decoration that isn't just line/scatter pens and brushes:
20116   if (mSelectionDecorator)
20117     mSelectionDecorator->drawDecoration(painter, selection());
20118 }
20119 
20120 /* inherits documentation from base class */
drawLegendIcon(QCPPainter * painter,const QRectF & rect) const20121 void QCPGraph::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
20122 {
20123   // draw fill:
20124   if (mBrush.style() != Qt::NoBrush)
20125   {
20126     applyFillAntialiasingHint(painter);
20127     painter->fillRect(QRectF(rect.left(), rect.top()+rect.height()/2.0, rect.width(), rect.height()/3.0), mBrush);
20128   }
20129   // draw line vertically centered:
20130   if (mLineStyle != lsNone)
20131   {
20132     applyDefaultAntialiasingHint(painter);
20133     painter->setPen(mPen);
20134     painter->drawLine(QLineF(rect.left(), rect.top()+rect.height()/2.0, rect.right()+5, rect.top()+rect.height()/2.0)); // +5 on x2 else last segment is missing from dashed/dotted pens
20135   }
20136   // draw scatter symbol:
20137   if (!mScatterStyle.isNone())
20138   {
20139     applyScattersAntialiasingHint(painter);
20140     // scale scatter pixmap if it's too large to fit in legend icon rect:
20141     if (mScatterStyle.shape() == QCPScatterStyle::ssPixmap && (mScatterStyle.pixmap().size().width() > rect.width() || mScatterStyle.pixmap().size().height() > rect.height()))
20142     {
20143       QCPScatterStyle scaledStyle(mScatterStyle);
20144       scaledStyle.setPixmap(scaledStyle.pixmap().scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
20145       scaledStyle.applyTo(painter, mPen);
20146       scaledStyle.drawShape(painter, QRectF(rect).center());
20147     } else
20148     {
20149       mScatterStyle.applyTo(painter, mPen);
20150       mScatterStyle.drawShape(painter, QRectF(rect).center());
20151     }
20152   }
20153 }
20154 
20155 /*! \internal
20156 
20157   This method retrieves an optimized set of data points via \ref getOptimizedLineData, an branches
20158   out to the line style specific functions such as \ref dataToLines, \ref dataToStepLeftLines, etc.
20159   according to the line style of the graph.
20160 
20161   \a lines will be filled with points in pixel coordinates, that can be drawn with the according
20162   draw functions like \ref drawLinePlot and \ref drawImpulsePlot. The points returned in \a lines
20163   aren't necessarily the original data points. For example, step line styles require additional
20164   points to form the steps when drawn. If the line style of the graph is \ref lsNone, the \a
20165   lines vector will be empty.
20166 
20167   \a dataRange specifies the beginning and ending data indices that will be taken into account for
20168   conversion. In this function, the specified range may exceed the total data bounds without harm:
20169   a correspondingly trimmed data range will be used. This takes the burden off the user of this
20170   function to check for valid indices in \a dataRange, e.g. when extending ranges coming from \ref
20171   getDataSegments.
20172 
20173   \see getScatters
20174 */
getLines(QVector<QPointF> * lines,const QCPDataRange & dataRange) const20175 void QCPGraph::getLines(QVector<QPointF> *lines, const QCPDataRange &dataRange) const
20176 {
20177   if (!lines) return;
20178   QCPGraphDataContainer::const_iterator begin, end;
20179   getVisibleDataBounds(begin, end, dataRange);
20180   if (begin == end)
20181   {
20182     lines->clear();
20183     return;
20184   }
20185 
20186   QVector<QCPGraphData> lineData;
20187   if (mLineStyle != lsNone)
20188     getOptimizedLineData(&lineData, begin, end);
20189 
20190   switch (mLineStyle)
20191   {
20192     case lsNone: lines->clear(); break;
20193     case lsLine: *lines = dataToLines(lineData); break;
20194     case lsStepLeft: *lines = dataToStepLeftLines(lineData); break;
20195     case lsStepRight: *lines = dataToStepRightLines(lineData); break;
20196     case lsStepCenter: *lines = dataToStepCenterLines(lineData); break;
20197     case lsImpulse: *lines = dataToImpulseLines(lineData); break;
20198   }
20199 }
20200 
20201 /*! \internal
20202 
20203   This method retrieves an optimized set of data points via \ref getOptimizedScatterData and then
20204   converts them to pixel coordinates. The resulting points are returned in \a scatters, and can be
20205   passed to \ref drawScatterPlot.
20206 
20207   \a dataRange specifies the beginning and ending data indices that will be taken into account for
20208   conversion. In this function, the specified range may exceed the total data bounds without harm:
20209   a correspondingly trimmed data range will be used. This takes the burden off the user of this
20210   function to check for valid indices in \a dataRange, e.g. when extending ranges coming from \ref
20211   getDataSegments.
20212 */
getScatters(QVector<QPointF> * scatters,const QCPDataRange & dataRange) const20213 void QCPGraph::getScatters(QVector<QPointF> *scatters, const QCPDataRange &dataRange) const
20214 {
20215   if (!scatters) return;
20216   QCPAxis *keyAxis = mKeyAxis.data();
20217   QCPAxis *valueAxis = mValueAxis.data();
20218   if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; scatters->clear(); return; }
20219 
20220   QCPGraphDataContainer::const_iterator begin, end;
20221   getVisibleDataBounds(begin, end, dataRange);
20222   if (begin == end)
20223   {
20224     scatters->clear();
20225     return;
20226   }
20227 
20228   QVector<QCPGraphData> data;
20229   getOptimizedScatterData(&data, begin, end);
20230   scatters->resize(data.size());
20231   if (keyAxis->orientation() == Qt::Vertical)
20232   {
20233     for (int i=0; i<data.size(); ++i)
20234     {
20235       if (!qIsNaN(data.at(i).value))
20236       {
20237         (*scatters)[i].setX(valueAxis->coordToPixel(data.at(i).value));
20238         (*scatters)[i].setY(keyAxis->coordToPixel(data.at(i).key));
20239       }
20240     }
20241   } else
20242   {
20243     for (int i=0; i<data.size(); ++i)
20244     {
20245       if (!qIsNaN(data.at(i).value))
20246       {
20247         (*scatters)[i].setX(keyAxis->coordToPixel(data.at(i).key));
20248         (*scatters)[i].setY(valueAxis->coordToPixel(data.at(i).value));
20249       }
20250     }
20251   }
20252 }
20253 
20254 /*! \internal
20255 
20256   Takes raw data points in plot coordinates as \a data, and returns a vector containing pixel
20257   coordinate points which are suitable for drawing the line style \ref lsLine.
20258 
20259   The source of \a data is usually \ref getOptimizedLineData, and this method is called in \a
20260   getLines if the line style is set accordingly.
20261 
20262   \see dataToStepLeftLines, dataToStepRightLines, dataToStepCenterLines, dataToImpulseLines, getLines, drawLinePlot
20263 */
dataToLines(const QVector<QCPGraphData> & data) const20264 QVector<QPointF> QCPGraph::dataToLines(const QVector<QCPGraphData> &data) const
20265 {
20266   QVector<QPointF> result;
20267   QCPAxis *keyAxis = mKeyAxis.data();
20268   QCPAxis *valueAxis = mValueAxis.data();
20269   if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return result; }
20270 
20271   result.reserve(data.size()+2); // added 2 to reserve memory for lower/upper fill base points that might be needed for fill
20272   result.resize(data.size());
20273 
20274   // transform data points to pixels:
20275   if (keyAxis->orientation() == Qt::Vertical)
20276   {
20277     for (int i=0; i<data.size(); ++i)
20278     {
20279       result[i].setX(valueAxis->coordToPixel(data.at(i).value));
20280       result[i].setY(keyAxis->coordToPixel(data.at(i).key));
20281     }
20282   } else // key axis is horizontal
20283   {
20284     for (int i=0; i<data.size(); ++i)
20285     {
20286       result[i].setX(keyAxis->coordToPixel(data.at(i).key));
20287       result[i].setY(valueAxis->coordToPixel(data.at(i).value));
20288     }
20289   }
20290   return result;
20291 }
20292 
20293 /*! \internal
20294 
20295   Takes raw data points in plot coordinates as \a data, and returns a vector containing pixel
20296   coordinate points which are suitable for drawing the line style \ref lsStepLeft.
20297 
20298   The source of \a data is usually \ref getOptimizedLineData, and this method is called in \a
20299   getLines if the line style is set accordingly.
20300 
20301   \see dataToLines, dataToStepRightLines, dataToStepCenterLines, dataToImpulseLines, getLines, drawLinePlot
20302 */
dataToStepLeftLines(const QVector<QCPGraphData> & data) const20303 QVector<QPointF> QCPGraph::dataToStepLeftLines(const QVector<QCPGraphData> &data) const
20304 {
20305   QVector<QPointF> result;
20306   QCPAxis *keyAxis = mKeyAxis.data();
20307   QCPAxis *valueAxis = mValueAxis.data();
20308   if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return result; }
20309 
20310   result.reserve(data.size()*2+2); // added 2 to reserve memory for lower/upper fill base points that might be needed for fill
20311   result.resize(data.size()*2);
20312 
20313   // calculate steps from data and transform to pixel coordinates:
20314   if (keyAxis->orientation() == Qt::Vertical)
20315   {
20316     double lastValue = valueAxis->coordToPixel(data.first().value);
20317     for (int i=0; i<data.size(); ++i)
20318     {
20319       const double key = keyAxis->coordToPixel(data.at(i).key);
20320       result[i*2+0].setX(lastValue);
20321       result[i*2+0].setY(key);
20322       lastValue = valueAxis->coordToPixel(data.at(i).value);
20323       result[i*2+1].setX(lastValue);
20324       result[i*2+1].setY(key);
20325     }
20326   } else // key axis is horizontal
20327   {
20328     double lastValue = valueAxis->coordToPixel(data.first().value);
20329     for (int i=0; i<data.size(); ++i)
20330     {
20331       const double key = keyAxis->coordToPixel(data.at(i).key);
20332       result[i*2+0].setX(key);
20333       result[i*2+0].setY(lastValue);
20334       lastValue = valueAxis->coordToPixel(data.at(i).value);
20335       result[i*2+1].setX(key);
20336       result[i*2+1].setY(lastValue);
20337     }
20338   }
20339   return result;
20340 }
20341 
20342 /*! \internal
20343 
20344   Takes raw data points in plot coordinates as \a data, and returns a vector containing pixel
20345   coordinate points which are suitable for drawing the line style \ref lsStepRight.
20346 
20347   The source of \a data is usually \ref getOptimizedLineData, and this method is called in \a
20348   getLines if the line style is set accordingly.
20349 
20350   \see dataToLines, dataToStepLeftLines, dataToStepCenterLines, dataToImpulseLines, getLines, drawLinePlot
20351 */
dataToStepRightLines(const QVector<QCPGraphData> & data) const20352 QVector<QPointF> QCPGraph::dataToStepRightLines(const QVector<QCPGraphData> &data) const
20353 {
20354   QVector<QPointF> result;
20355   QCPAxis *keyAxis = mKeyAxis.data();
20356   QCPAxis *valueAxis = mValueAxis.data();
20357   if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return result; }
20358 
20359   result.reserve(data.size()*2+2); // added 2 to reserve memory for lower/upper fill base points that might be needed for fill
20360   result.resize(data.size()*2);
20361 
20362   // calculate steps from data and transform to pixel coordinates:
20363   if (keyAxis->orientation() == Qt::Vertical)
20364   {
20365     double lastKey = keyAxis->coordToPixel(data.first().key);
20366     for (int i=0; i<data.size(); ++i)
20367     {
20368       const double value = valueAxis->coordToPixel(data.at(i).value);
20369       result[i*2+0].setX(value);
20370       result[i*2+0].setY(lastKey);
20371       lastKey = keyAxis->coordToPixel(data.at(i).key);
20372       result[i*2+1].setX(value);
20373       result[i*2+1].setY(lastKey);
20374     }
20375   } else // key axis is horizontal
20376   {
20377     double lastKey = keyAxis->coordToPixel(data.first().key);
20378     for (int i=0; i<data.size(); ++i)
20379     {
20380       const double value = valueAxis->coordToPixel(data.at(i).value);
20381       result[i*2+0].setX(lastKey);
20382       result[i*2+0].setY(value);
20383       lastKey = keyAxis->coordToPixel(data.at(i).key);
20384       result[i*2+1].setX(lastKey);
20385       result[i*2+1].setY(value);
20386     }
20387   }
20388   return result;
20389 }
20390 
20391 /*! \internal
20392 
20393   Takes raw data points in plot coordinates as \a data, and returns a vector containing pixel
20394   coordinate points which are suitable for drawing the line style \ref lsStepCenter.
20395 
20396   The source of \a data is usually \ref getOptimizedLineData, and this method is called in \a
20397   getLines if the line style is set accordingly.
20398 
20399   \see dataToLines, dataToStepLeftLines, dataToStepRightLines, dataToImpulseLines, getLines, drawLinePlot
20400 */
dataToStepCenterLines(const QVector<QCPGraphData> & data) const20401 QVector<QPointF> QCPGraph::dataToStepCenterLines(const QVector<QCPGraphData> &data) const
20402 {
20403   QVector<QPointF> result;
20404   QCPAxis *keyAxis = mKeyAxis.data();
20405   QCPAxis *valueAxis = mValueAxis.data();
20406   if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return result; }
20407 
20408   result.reserve(data.size()*2+2); // added 2 to reserve memory for lower/upper fill base points that might be needed for fill
20409   result.resize(data.size()*2);
20410 
20411   // calculate steps from data and transform to pixel coordinates:
20412   if (keyAxis->orientation() == Qt::Vertical)
20413   {
20414     double lastKey = keyAxis->coordToPixel(data.first().key);
20415     double lastValue = valueAxis->coordToPixel(data.first().value);
20416     result[0].setX(lastValue);
20417     result[0].setY(lastKey);
20418     for (int i=1; i<data.size(); ++i)
20419     {
20420       const double key = (keyAxis->coordToPixel(data.at(i).key)+lastKey)*0.5;
20421       result[i*2-1].setX(lastValue);
20422       result[i*2-1].setY(key);
20423       lastValue = valueAxis->coordToPixel(data.at(i).value);
20424       lastKey = keyAxis->coordToPixel(data.at(i).key);
20425       result[i*2+0].setX(lastValue);
20426       result[i*2+0].setY(key);
20427     }
20428     result[data.size()*2-1].setX(lastValue);
20429     result[data.size()*2-1].setY(lastKey);
20430   } else // key axis is horizontal
20431   {
20432     double lastKey = keyAxis->coordToPixel(data.first().key);
20433     double lastValue = valueAxis->coordToPixel(data.first().value);
20434     result[0].setX(lastKey);
20435     result[0].setY(lastValue);
20436     for (int i=1; i<data.size(); ++i)
20437     {
20438       const double key = (keyAxis->coordToPixel(data.at(i).key)+lastKey)*0.5;
20439       result[i*2-1].setX(key);
20440       result[i*2-1].setY(lastValue);
20441       lastValue = valueAxis->coordToPixel(data.at(i).value);
20442       lastKey = keyAxis->coordToPixel(data.at(i).key);
20443       result[i*2+0].setX(key);
20444       result[i*2+0].setY(lastValue);
20445     }
20446     result[data.size()*2-1].setX(lastKey);
20447     result[data.size()*2-1].setY(lastValue);
20448   }
20449   return result;
20450 }
20451 
20452 /*! \internal
20453 
20454   Takes raw data points in plot coordinates as \a data, and returns a vector containing pixel
20455   coordinate points which are suitable for drawing the line style \ref lsImpulse.
20456 
20457   The source of \a data is usually \ref getOptimizedLineData, and this method is called in \a
20458   getLines if the line style is set accordingly.
20459 
20460   \see dataToLines, dataToStepLeftLines, dataToStepRightLines, dataToStepCenterLines, getLines, drawImpulsePlot
20461 */
dataToImpulseLines(const QVector<QCPGraphData> & data) const20462 QVector<QPointF> QCPGraph::dataToImpulseLines(const QVector<QCPGraphData> &data) const
20463 {
20464   QVector<QPointF> result;
20465   QCPAxis *keyAxis = mKeyAxis.data();
20466   QCPAxis *valueAxis = mValueAxis.data();
20467   if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return result; }
20468 
20469   result.resize(data.size()*2); // no need to reserve 2 extra points because impulse plot has no fill
20470 
20471   // transform data points to pixels:
20472   if (keyAxis->orientation() == Qt::Vertical)
20473   {
20474     for (int i=0; i<data.size(); ++i)
20475     {
20476       const double key = keyAxis->coordToPixel(data.at(i).key);
20477       result[i*2+0].setX(valueAxis->coordToPixel(0));
20478       result[i*2+0].setY(key);
20479       result[i*2+1].setX(valueAxis->coordToPixel(data.at(i).value));
20480       result[i*2+1].setY(key);
20481     }
20482   } else // key axis is horizontal
20483   {
20484     for (int i=0; i<data.size(); ++i)
20485     {
20486       const double key = keyAxis->coordToPixel(data.at(i).key);
20487       result[i*2+0].setX(key);
20488       result[i*2+0].setY(valueAxis->coordToPixel(0));
20489       result[i*2+1].setX(key);
20490       result[i*2+1].setY(valueAxis->coordToPixel(data.at(i).value));
20491     }
20492   }
20493   return result;
20494 }
20495 
20496 /*! \internal
20497 
20498   Draws the fill of the graph using the specified \a painter, with the currently set brush.
20499 
20500   \a lines contains the points of the graph line, in pixel coordinates.
20501 
20502   If the fill is a normal fill towards the zero-value-line, only the points in \a lines are
20503   required and two extra points at the zero-value-line, which are added by \ref addFillBasePoints
20504   and removed by \ref removeFillBasePoints after the fill drawing is done.
20505 
20506   On the other hand if the fill is a channel fill between this QCPGraph and another QCPGraph (\a
20507   mChannelFillGraph), the more complex polygon is calculated with the \ref getChannelFillPolygon
20508   function, and then drawn.
20509 
20510   \see drawLinePlot, drawImpulsePlot, drawScatterPlot
20511 */
drawFill(QCPPainter * painter,QVector<QPointF> * lines) const20512 void QCPGraph::drawFill(QCPPainter *painter, QVector<QPointF> *lines) const
20513 {
20514   if (mLineStyle == lsImpulse) return; // fill doesn't make sense for impulse plot
20515   if (painter->brush().style() == Qt::NoBrush || painter->brush().color().alpha() == 0) return;
20516 
20517   applyFillAntialiasingHint(painter);
20518   if (!mChannelFillGraph)
20519   {
20520     // draw base fill under graph, fill goes all the way to the zero-value-line:
20521     addFillBasePoints(lines);
20522     painter->drawPolygon(QPolygonF(*lines));
20523     removeFillBasePoints(lines);
20524   } else
20525   {
20526     // draw channel fill between this graph and mChannelFillGraph:
20527     painter->drawPolygon(getChannelFillPolygon(lines));
20528   }
20529 }
20530 
20531 /*! \internal
20532 
20533   Draws scatter symbols at every point passed in \a scatters, given in pixel coordinates. The
20534   scatters will be drawn with \a painter and have the appearance as specified in \a style.
20535 
20536   \see drawLinePlot, drawImpulsePlot
20537 */
drawScatterPlot(QCPPainter * painter,const QVector<QPointF> & scatters,const QCPScatterStyle & style) const20538 void QCPGraph::drawScatterPlot(QCPPainter *painter, const QVector<QPointF> &scatters, const QCPScatterStyle &style) const
20539 {
20540   applyScattersAntialiasingHint(painter);
20541   style.applyTo(painter, mPen);
20542   for (int i=0; i<scatters.size(); ++i)
20543     style.drawShape(painter, scatters.at(i).x(), scatters.at(i).y());
20544 }
20545 
20546 /*!  \internal
20547 
20548   Draws lines between the points in \a lines, given in pixel coordinates.
20549 
20550   \see drawScatterPlot, drawImpulsePlot, QCPAbstractPlottable1D::drawPolyline
20551 */
drawLinePlot(QCPPainter * painter,const QVector<QPointF> & lines) const20552 void QCPGraph::drawLinePlot(QCPPainter *painter, const QVector<QPointF> &lines) const
20553 {
20554   if (painter->pen().style() != Qt::NoPen && painter->pen().color().alpha() != 0)
20555   {
20556     applyDefaultAntialiasingHint(painter);
20557     drawPolyline(painter, lines);
20558   }
20559 }
20560 
20561 /*! \internal
20562 
20563   Draws impulses from the provided data, i.e. it connects all line pairs in \a lines, given in
20564   pixel coordinates. The \a lines necessary for impulses are generated by \ref dataToImpulseLines
20565   from the regular graph data points.
20566 
20567   \see drawLinePlot, drawScatterPlot
20568 */
drawImpulsePlot(QCPPainter * painter,const QVector<QPointF> & lines) const20569 void QCPGraph::drawImpulsePlot(QCPPainter *painter, const QVector<QPointF> &lines) const
20570 {
20571   if (painter->pen().style() != Qt::NoPen && painter->pen().color().alpha() != 0)
20572   {
20573     applyDefaultAntialiasingHint(painter);
20574     QPen oldPen = painter->pen();
20575     QPen newPen = painter->pen();
20576     newPen.setCapStyle(Qt::FlatCap); // so impulse line doesn't reach beyond zero-line
20577     painter->setPen(newPen);
20578     painter->drawLines(lines);
20579     painter->setPen(oldPen);
20580   }
20581 }
20582 
20583 /*! \internal
20584 
20585   Returns via \a lineData the data points that need to be visualized for this graph when plotting
20586   graph lines, taking into consideration the currently visible axis ranges and, if \ref
20587   setAdaptiveSampling is enabled, local point densities. The considered data can be restricted
20588   further by \a begin and \a end, e.g. to only plot a certain segment of the data (see \ref
20589   getDataSegments).
20590 
20591   This method is used by \ref getLines to retrieve the basic working set of data.
20592 
20593   \see getOptimizedScatterData
20594 */
getOptimizedLineData(QVector<QCPGraphData> * lineData,const QCPGraphDataContainer::const_iterator & begin,const QCPGraphDataContainer::const_iterator & end) const20595 void QCPGraph::getOptimizedLineData(QVector<QCPGraphData> *lineData, const QCPGraphDataContainer::const_iterator &begin, const QCPGraphDataContainer::const_iterator &end) const
20596 {
20597   if (!lineData) return;
20598   QCPAxis *keyAxis = mKeyAxis.data();
20599   QCPAxis *valueAxis = mValueAxis.data();
20600   if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
20601   if (begin == end) return;
20602 
20603   int dataCount = end-begin;
20604   int maxCount = std::numeric_limits<int>::max();
20605   if (mAdaptiveSampling)
20606   {
20607     double keyPixelSpan = qAbs(keyAxis->coordToPixel(begin->key)-keyAxis->coordToPixel((end-1)->key));
20608     if (2*keyPixelSpan+2 < (double)std::numeric_limits<int>::max())
20609       maxCount = 2*keyPixelSpan+2;
20610   }
20611 
20612   if (mAdaptiveSampling && dataCount >= maxCount) // use adaptive sampling only if there are at least two points per pixel on average
20613   {
20614     QCPGraphDataContainer::const_iterator it = begin;
20615     double minValue = it->value;
20616     double maxValue = it->value;
20617     QCPGraphDataContainer::const_iterator currentIntervalFirstPoint = it;
20618     int reversedFactor = keyAxis->pixelOrientation(); // is used to calculate keyEpsilon pixel into the correct direction
20619     int reversedRound = reversedFactor==-1 ? 1 : 0; // is used to switch between floor (normal) and ceil (reversed) rounding of currentIntervalStartKey
20620     double currentIntervalStartKey = keyAxis->pixelToCoord((int)(keyAxis->coordToPixel(begin->key)+reversedRound));
20621     double lastIntervalEndKey = currentIntervalStartKey;
20622     double keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor)); // interval of one pixel on screen when mapped to plot key coordinates
20623     bool keyEpsilonVariable = keyAxis->scaleType() == QCPAxis::stLogarithmic; // indicates whether keyEpsilon needs to be updated after every interval (for log axes)
20624     int intervalDataCount = 1;
20625     ++it; // advance iterator to second data point because adaptive sampling works in 1 point retrospect
20626     while (it != end)
20627     {
20628       if (it->key < currentIntervalStartKey+keyEpsilon) // data point is still within same pixel, so skip it and expand value span of this cluster if necessary
20629       {
20630         if (it->value < minValue)
20631           minValue = it->value;
20632         else if (it->value > maxValue)
20633           maxValue = it->value;
20634         ++intervalDataCount;
20635       } else // new pixel interval started
20636       {
20637         if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them to a cluster
20638         {
20639           if (lastIntervalEndKey < currentIntervalStartKey-keyEpsilon) // last point is further away, so first point of this cluster must be at a real data point
20640             lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.2, currentIntervalFirstPoint->value));
20641           lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.25, minValue));
20642           lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.75, maxValue));
20643           if (it->key > currentIntervalStartKey+keyEpsilon*2) // new pixel started further away from previous cluster, so make sure the last point of the cluster is at a real data point
20644             lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.8, (it-1)->value));
20645         } else
20646           lineData->append(QCPGraphData(currentIntervalFirstPoint->key, currentIntervalFirstPoint->value));
20647         lastIntervalEndKey = (it-1)->key;
20648         minValue = it->value;
20649         maxValue = it->value;
20650         currentIntervalFirstPoint = it;
20651         currentIntervalStartKey = keyAxis->pixelToCoord((int)(keyAxis->coordToPixel(it->key)+reversedRound));
20652         if (keyEpsilonVariable)
20653           keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor));
20654         intervalDataCount = 1;
20655       }
20656       ++it;
20657     }
20658     // handle last interval:
20659     if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them to a cluster
20660     {
20661       if (lastIntervalEndKey < currentIntervalStartKey-keyEpsilon) // last point wasn't a cluster, so first point of this cluster must be at a real data point
20662         lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.2, currentIntervalFirstPoint->value));
20663       lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.25, minValue));
20664       lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.75, maxValue));
20665     } else
20666       lineData->append(QCPGraphData(currentIntervalFirstPoint->key, currentIntervalFirstPoint->value));
20667 
20668   } else // don't use adaptive sampling algorithm, transfer points one-to-one from the data container into the output
20669   {
20670     QCPGraphDataContainer::const_iterator it = begin;
20671     lineData->reserve(dataCount+2); // +2 for possible fill end points
20672     while (it != end)
20673     {
20674       lineData->append(*it);
20675       ++it;
20676     }
20677   }
20678 }
20679 
20680 /*! \internal
20681 
20682   Returns via \a scatterData the data points that need to be visualized for this graph when
20683   plotting scatter points, taking into consideration the currently visible axis ranges and, if \ref
20684   setAdaptiveSampling is enabled, local point densities. The considered data can be restricted
20685   further by \a begin and \a end, e.g. to only plot a certain segment of the data (see \ref
20686   getDataSegments).
20687 
20688   This method is used by \ref getScatters to retrieve the basic working set of data.
20689 
20690   \see getOptimizedLineData
20691 */
getOptimizedScatterData(QVector<QCPGraphData> * scatterData,QCPGraphDataContainer::const_iterator begin,QCPGraphDataContainer::const_iterator end) const20692 void QCPGraph::getOptimizedScatterData(QVector<QCPGraphData> *scatterData, QCPGraphDataContainer::const_iterator begin, QCPGraphDataContainer::const_iterator end) const
20693 {
20694   if (!scatterData) return;
20695   QCPAxis *keyAxis = mKeyAxis.data();
20696   QCPAxis *valueAxis = mValueAxis.data();
20697   if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
20698 
20699   const int scatterModulo = mScatterSkip+1;
20700   const bool doScatterSkip = mScatterSkip > 0;
20701   int beginIndex = begin-mDataContainer->constBegin();
20702   int endIndex = end-mDataContainer->constBegin();
20703   while (doScatterSkip && begin != end && beginIndex % scatterModulo != 0) // advance begin iterator to first non-skipped scatter
20704   {
20705     ++beginIndex;
20706     ++begin;
20707   }
20708   if (begin == end) return;
20709   int dataCount = end-begin;
20710   int maxCount = std::numeric_limits<int>::max();
20711   if (mAdaptiveSampling)
20712   {
20713     int keyPixelSpan = qAbs(keyAxis->coordToPixel(begin->key)-keyAxis->coordToPixel((end-1)->key));
20714     maxCount = 2*keyPixelSpan+2;
20715   }
20716 
20717   if (mAdaptiveSampling && dataCount >= maxCount) // use adaptive sampling only if there are at least two points per pixel on average
20718   {
20719     double valueMaxRange = valueAxis->range().upper;
20720     double valueMinRange = valueAxis->range().lower;
20721     QCPGraphDataContainer::const_iterator it = begin;
20722     int itIndex = beginIndex;
20723     double minValue = it->value;
20724     double maxValue = it->value;
20725     QCPGraphDataContainer::const_iterator minValueIt = it;
20726     QCPGraphDataContainer::const_iterator maxValueIt = it;
20727     QCPGraphDataContainer::const_iterator currentIntervalStart = it;
20728     int reversedFactor = keyAxis->pixelOrientation(); // is used to calculate keyEpsilon pixel into the correct direction
20729     int reversedRound = reversedFactor==-1 ? 1 : 0; // is used to switch between floor (normal) and ceil (reversed) rounding of currentIntervalStartKey
20730     double currentIntervalStartKey = keyAxis->pixelToCoord((int)(keyAxis->coordToPixel(begin->key)+reversedRound));
20731     double keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor)); // interval of one pixel on screen when mapped to plot key coordinates
20732     bool keyEpsilonVariable = keyAxis->scaleType() == QCPAxis::stLogarithmic; // indicates whether keyEpsilon needs to be updated after every interval (for log axes)
20733     int intervalDataCount = 1;
20734     // advance iterator to second (non-skipped) data point because adaptive sampling works in 1 point retrospect:
20735     if (!doScatterSkip)
20736       ++it;
20737     else
20738     {
20739       itIndex += scatterModulo;
20740       if (itIndex < endIndex) // make sure we didn't jump over end
20741         it += scatterModulo;
20742       else
20743       {
20744         it = end;
20745         itIndex = endIndex;
20746       }
20747     }
20748     // main loop over data points:
20749     while (it != end)
20750     {
20751       if (it->key < currentIntervalStartKey+keyEpsilon) // data point is still within same pixel, so skip it and expand value span of this pixel if necessary
20752       {
20753         if (it->value < minValue && it->value > valueMinRange && it->value < valueMaxRange)
20754         {
20755           minValue = it->value;
20756           minValueIt = it;
20757         } else if (it->value > maxValue && it->value > valueMinRange && it->value < valueMaxRange)
20758         {
20759           maxValue = it->value;
20760           maxValueIt = it;
20761         }
20762         ++intervalDataCount;
20763       } else // new pixel started
20764       {
20765         if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them
20766         {
20767           // determine value pixel span and add as many points in interval to maintain certain vertical data density (this is specific to scatter plot):
20768           double valuePixelSpan = qAbs(valueAxis->coordToPixel(minValue)-valueAxis->coordToPixel(maxValue));
20769           int dataModulo = qMax(1, qRound(intervalDataCount/(valuePixelSpan/4.0))); // approximately every 4 value pixels one data point on average
20770           QCPGraphDataContainer::const_iterator intervalIt = currentIntervalStart;
20771           int c = 0;
20772           while (intervalIt != it)
20773           {
20774             if ((c % dataModulo == 0 || intervalIt == minValueIt || intervalIt == maxValueIt) && intervalIt->value > valueMinRange && intervalIt->value < valueMaxRange)
20775               scatterData->append(*intervalIt);
20776             ++c;
20777             if (!doScatterSkip)
20778               ++intervalIt;
20779             else
20780               intervalIt += scatterModulo; // since we know indices of "currentIntervalStart", "intervalIt" and "it" are multiples of scatterModulo, we can't accidentally jump over "it" here
20781           }
20782         } else if (currentIntervalStart->value > valueMinRange && currentIntervalStart->value < valueMaxRange)
20783           scatterData->append(*currentIntervalStart);
20784         minValue = it->value;
20785         maxValue = it->value;
20786         currentIntervalStart = it;
20787         currentIntervalStartKey = keyAxis->pixelToCoord((int)(keyAxis->coordToPixel(it->key)+reversedRound));
20788         if (keyEpsilonVariable)
20789           keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor));
20790         intervalDataCount = 1;
20791       }
20792       // advance to next data point:
20793       if (!doScatterSkip)
20794         ++it;
20795       else
20796       {
20797         itIndex += scatterModulo;
20798         if (itIndex < endIndex) // make sure we didn't jump over end
20799           it += scatterModulo;
20800         else
20801         {
20802           it = end;
20803           itIndex = endIndex;
20804         }
20805       }
20806     }
20807     // handle last interval:
20808     if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them
20809     {
20810       // determine value pixel span and add as many points in interval to maintain certain vertical data density (this is specific to scatter plot):
20811       double valuePixelSpan = qAbs(valueAxis->coordToPixel(minValue)-valueAxis->coordToPixel(maxValue));
20812       int dataModulo = qMax(1, qRound(intervalDataCount/(valuePixelSpan/4.0))); // approximately every 4 value pixels one data point on average
20813       QCPGraphDataContainer::const_iterator intervalIt = currentIntervalStart;
20814       int intervalItIndex = intervalIt-mDataContainer->constBegin();
20815       int c = 0;
20816       while (intervalIt != it)
20817       {
20818         if ((c % dataModulo == 0 || intervalIt == minValueIt || intervalIt == maxValueIt) && intervalIt->value > valueMinRange && intervalIt->value < valueMaxRange)
20819           scatterData->append(*intervalIt);
20820         ++c;
20821         if (!doScatterSkip)
20822           ++intervalIt;
20823         else // here we can't guarantee that adding scatterModulo doesn't exceed "it" (because "it" is equal to "end" here, and "end" isn't scatterModulo-aligned), so check via index comparison:
20824         {
20825           intervalItIndex += scatterModulo;
20826           if (intervalItIndex < itIndex)
20827             intervalIt += scatterModulo;
20828           else
20829           {
20830             intervalIt = it;
20831             intervalItIndex = itIndex;
20832           }
20833         }
20834       }
20835     } else if (currentIntervalStart->value > valueMinRange && currentIntervalStart->value < valueMaxRange)
20836       scatterData->append(*currentIntervalStart);
20837 
20838   } else // don't use adaptive sampling algorithm, transfer points one-to-one from the data container into the output
20839   {
20840     QCPGraphDataContainer::const_iterator it = begin;
20841     int itIndex = beginIndex;
20842     scatterData->reserve(dataCount);
20843     while (it != end)
20844     {
20845       scatterData->append(*it);
20846       // advance to next data point:
20847       if (!doScatterSkip)
20848         ++it;
20849       else
20850       {
20851         itIndex += scatterModulo;
20852         if (itIndex < endIndex)
20853           it += scatterModulo;
20854         else
20855         {
20856           it = end;
20857           itIndex = endIndex;
20858         }
20859       }
20860     }
20861   }
20862 }
20863 
20864 /*!
20865   This method outputs the currently visible data range via \a begin and \a end. The returned range
20866   will also never exceed \a rangeRestriction.
20867 
20868   This method takes into account that the drawing of data lines at the axis rect border always
20869   requires the points just outside the visible axis range. So \a begin and \a end may actually
20870   indicate a range that contains one additional data point to the left and right of the visible
20871   axis range.
20872 */
getVisibleDataBounds(QCPGraphDataContainer::const_iterator & begin,QCPGraphDataContainer::const_iterator & end,const QCPDataRange & rangeRestriction) const20873 void QCPGraph::getVisibleDataBounds(QCPGraphDataContainer::const_iterator &begin, QCPGraphDataContainer::const_iterator &end, const QCPDataRange &rangeRestriction) const
20874 {
20875   if (rangeRestriction.isEmpty())
20876   {
20877     end = mDataContainer->constEnd();
20878     begin = end;
20879   } else
20880   {
20881     QCPAxis *keyAxis = mKeyAxis.data();
20882     QCPAxis *valueAxis = mValueAxis.data();
20883     if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
20884     // get visible data range:
20885     begin = mDataContainer->findBegin(keyAxis->range().lower);
20886     end = mDataContainer->findEnd(keyAxis->range().upper);
20887     // limit lower/upperEnd to rangeRestriction:
20888     mDataContainer->limitIteratorsToDataRange(begin, end, rangeRestriction); // this also ensures rangeRestriction outside data bounds doesn't break anything
20889   }
20890 }
20891 
20892 /*! \internal
20893 
20894   The line vector generated by e.g. \ref getLines describes only the line that connects the data
20895   points. If the graph needs to be filled, two additional points need to be added at the
20896   value-zero-line in the lower and upper key positions of the graph. This function calculates these
20897   points and adds them to the end of \a lineData. Since the fill is typically drawn before the line
20898   stroke, these added points need to be removed again after the fill is done, with the
20899   removeFillBasePoints function.
20900 
20901   The expanding of \a lines by two points will not cause unnecessary memory reallocations, because
20902   the data vector generation functions (e.g. \ref getLines) reserve two extra points when they
20903   allocate memory for \a lines.
20904 
20905   \see removeFillBasePoints, lowerFillBasePoint, upperFillBasePoint
20906 */
addFillBasePoints(QVector<QPointF> * lines) const20907 void QCPGraph::addFillBasePoints(QVector<QPointF> *lines) const
20908 {
20909   if (!mKeyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; }
20910   if (!lines) { qDebug() << Q_FUNC_INFO << "passed null as lineData"; return; }
20911   if (lines->isEmpty()) return;
20912 
20913   // append points that close the polygon fill at the key axis:
20914   if (mKeyAxis.data()->orientation() == Qt::Vertical)
20915   {
20916     *lines << upperFillBasePoint(lines->last().y());
20917     *lines << lowerFillBasePoint(lines->first().y());
20918   } else
20919   {
20920     *lines << upperFillBasePoint(lines->last().x());
20921     *lines << lowerFillBasePoint(lines->first().x());
20922   }
20923 }
20924 
20925 /*! \internal
20926 
20927   removes the two points from \a lines that were added by \ref addFillBasePoints.
20928 
20929   \see addFillBasePoints, lowerFillBasePoint, upperFillBasePoint
20930 */
removeFillBasePoints(QVector<QPointF> * lines) const20931 void QCPGraph::removeFillBasePoints(QVector<QPointF> *lines) const
20932 {
20933   if (!lines) { qDebug() << Q_FUNC_INFO << "passed null as lineData"; return; }
20934   if (lines->isEmpty()) return;
20935 
20936   lines->remove(lines->size()-2, 2);
20937 }
20938 
20939 /*! \internal
20940 
20941   called by \ref addFillBasePoints to conveniently assign the point which closes the fill polygon
20942   on the lower side of the zero-value-line parallel to the key axis. The logarithmic axis scale
20943   case is a bit special, since the zero-value-line in pixel coordinates is in positive or negative
20944   infinity. So this case is handled separately by just closing the fill polygon on the axis which
20945   lies in the direction towards the zero value.
20946 
20947   \a lowerKey will be the the key (in pixels) of the returned point. Depending on whether the key
20948   axis is horizontal or vertical, \a lowerKey will end up as the x or y value of the returned
20949   point, respectively.
20950 
20951   \see upperFillBasePoint, addFillBasePoints
20952 */
lowerFillBasePoint(double lowerKey) const20953 QPointF QCPGraph::lowerFillBasePoint(double lowerKey) const
20954 {
20955   QCPAxis *keyAxis = mKeyAxis.data();
20956   QCPAxis *valueAxis = mValueAxis.data();
20957   if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPointF(); }
20958 
20959   QPointF point;
20960   if (valueAxis->scaleType() == QCPAxis::stLinear)
20961   {
20962     if (keyAxis->axisType() == QCPAxis::atLeft)
20963     {
20964       point.setX(valueAxis->coordToPixel(0));
20965       point.setY(lowerKey);
20966     } else if (keyAxis->axisType() == QCPAxis::atRight)
20967     {
20968       point.setX(valueAxis->coordToPixel(0));
20969       point.setY(lowerKey);
20970     } else if (keyAxis->axisType() == QCPAxis::atTop)
20971     {
20972       point.setX(lowerKey);
20973       point.setY(valueAxis->coordToPixel(0));
20974     } else if (keyAxis->axisType() == QCPAxis::atBottom)
20975     {
20976       point.setX(lowerKey);
20977       point.setY(valueAxis->coordToPixel(0));
20978     }
20979   } else // valueAxis->mScaleType == QCPAxis::stLogarithmic
20980   {
20981     // In logarithmic scaling we can't just draw to value zero so we just fill all the way
20982     // to the axis which is in the direction towards zero
20983     if (keyAxis->orientation() == Qt::Vertical)
20984     {
20985       if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) ||
20986           (valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis
20987         point.setX(keyAxis->axisRect()->right());
20988       else
20989         point.setX(keyAxis->axisRect()->left());
20990       point.setY(lowerKey);
20991     } else if (keyAxis->axisType() == QCPAxis::atTop || keyAxis->axisType() == QCPAxis::atBottom)
20992     {
20993       point.setX(lowerKey);
20994       if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) ||
20995           (valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis
20996         point.setY(keyAxis->axisRect()->top());
20997       else
20998         point.setY(keyAxis->axisRect()->bottom());
20999     }
21000   }
21001   return point;
21002 }
21003 
21004 /*! \internal
21005 
21006   called by \ref addFillBasePoints to conveniently assign the point which closes the fill
21007   polygon on the upper side of the zero-value-line parallel to the key axis. The logarithmic axis
21008   scale case is a bit special, since the zero-value-line in pixel coordinates is in positive or
21009   negative infinity. So this case is handled separately by just closing the fill polygon on the
21010   axis which lies in the direction towards the zero value.
21011 
21012   \a upperKey will be the the key (in pixels) of the returned point. Depending on whether the key
21013   axis is horizontal or vertical, \a upperKey will end up as the x or y value of the returned
21014   point, respectively.
21015 
21016   \see lowerFillBasePoint, addFillBasePoints
21017 */
upperFillBasePoint(double upperKey) const21018 QPointF QCPGraph::upperFillBasePoint(double upperKey) const
21019 {
21020   QCPAxis *keyAxis = mKeyAxis.data();
21021   QCPAxis *valueAxis = mValueAxis.data();
21022   if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPointF(); }
21023 
21024   QPointF point;
21025   if (valueAxis->scaleType() == QCPAxis::stLinear)
21026   {
21027     if (keyAxis->axisType() == QCPAxis::atLeft)
21028     {
21029       point.setX(valueAxis->coordToPixel(0));
21030       point.setY(upperKey);
21031     } else if (keyAxis->axisType() == QCPAxis::atRight)
21032     {
21033       point.setX(valueAxis->coordToPixel(0));
21034       point.setY(upperKey);
21035     } else if (keyAxis->axisType() == QCPAxis::atTop)
21036     {
21037       point.setX(upperKey);
21038       point.setY(valueAxis->coordToPixel(0));
21039     } else if (keyAxis->axisType() == QCPAxis::atBottom)
21040     {
21041       point.setX(upperKey);
21042       point.setY(valueAxis->coordToPixel(0));
21043     }
21044   } else // valueAxis->mScaleType == QCPAxis::stLogarithmic
21045   {
21046     // In logarithmic scaling we can't just draw to value 0 so we just fill all the way
21047     // to the axis which is in the direction towards 0
21048     if (keyAxis->orientation() == Qt::Vertical)
21049     {
21050       if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) ||
21051           (valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis
21052         point.setX(keyAxis->axisRect()->right());
21053       else
21054         point.setX(keyAxis->axisRect()->left());
21055       point.setY(upperKey);
21056     } else if (keyAxis->axisType() == QCPAxis::atTop || keyAxis->axisType() == QCPAxis::atBottom)
21057     {
21058       point.setX(upperKey);
21059       if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) ||
21060           (valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis
21061         point.setY(keyAxis->axisRect()->top());
21062       else
21063         point.setY(keyAxis->axisRect()->bottom());
21064     }
21065   }
21066   return point;
21067 }
21068 
21069 /*! \internal
21070 
21071   Generates the polygon needed for drawing channel fills between this graph and the graph specified
21072   in \a mChannelFillGraph (see \ref setChannelFillGraph). The data points representing the line of
21073   this graph in pixel coordinates must be passed in \a lines, the corresponding points of the other
21074   graph are generated by calling its \ref getLines method.
21075 
21076   This method may return an empty polygon if the key ranges of the two graphs have no overlap of if
21077   they don't have the same orientation (e.g. one key axis vertical, the other horizontal). For
21078   increased performance (due to implicit sharing), it is recommended to keep the returned QPolygonF
21079   const.
21080 */
getChannelFillPolygon(const QVector<QPointF> * lines) const21081 const QPolygonF QCPGraph::getChannelFillPolygon(const QVector<QPointF> *lines) const
21082 {
21083   if (!mChannelFillGraph)
21084     return QPolygonF();
21085 
21086   QCPAxis *keyAxis = mKeyAxis.data();
21087   QCPAxis *valueAxis = mValueAxis.data();
21088   if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPolygonF(); }
21089   if (!mChannelFillGraph.data()->mKeyAxis) { qDebug() << Q_FUNC_INFO << "channel fill target key axis invalid"; return QPolygonF(); }
21090 
21091   if (mChannelFillGraph.data()->mKeyAxis.data()->orientation() != keyAxis->orientation())
21092     return QPolygonF(); // don't have same axis orientation, can't fill that (Note: if keyAxis fits, valueAxis will fit too, because it's always orthogonal to keyAxis)
21093 
21094   if (lines->isEmpty()) return QPolygonF();
21095   QVector<QPointF> otherData;
21096   mChannelFillGraph.data()->getLines(&otherData, QCPDataRange(0, mChannelFillGraph.data()->dataCount()));
21097   if (otherData.isEmpty()) return QPolygonF();
21098   QVector<QPointF> thisData;
21099   thisData.reserve(lines->size()+otherData.size()); // because we will join both vectors at end of this function
21100   for (int i=0; i<lines->size(); ++i) // don't use the vector<<(vector),  it squeezes internally, which ruins the performance tuning with reserve()
21101     thisData << lines->at(i);
21102 
21103   // pointers to be able to swap them, depending which data range needs cropping:
21104   QVector<QPointF> *staticData = &thisData;
21105   QVector<QPointF> *croppedData = &otherData;
21106 
21107   // crop both vectors to ranges in which the keys overlap (which coord is key, depends on axisType):
21108   if (keyAxis->orientation() == Qt::Horizontal)
21109   {
21110     // x is key
21111     // if an axis range is reversed, the data point keys will be descending. Reverse them, since following algorithm assumes ascending keys:
21112     if (staticData->first().x() > staticData->last().x())
21113     {
21114       int size = staticData->size();
21115       for (int i=0; i<size/2; ++i)
21116         qSwap((*staticData)[i], (*staticData)[size-1-i]);
21117     }
21118     if (croppedData->first().x() > croppedData->last().x())
21119     {
21120       int size = croppedData->size();
21121       for (int i=0; i<size/2; ++i)
21122         qSwap((*croppedData)[i], (*croppedData)[size-1-i]);
21123     }
21124     // crop lower bound:
21125     if (staticData->first().x() < croppedData->first().x()) // other one must be cropped
21126       qSwap(staticData, croppedData);
21127     int lowBound = findIndexBelowX(croppedData, staticData->first().x());
21128     if (lowBound == -1) return QPolygonF(); // key ranges have no overlap
21129     croppedData->remove(0, lowBound);
21130     // set lowest point of cropped data to fit exactly key position of first static data
21131     // point via linear interpolation:
21132     if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation
21133     double slope;
21134     if (croppedData->at(1).x()-croppedData->at(0).x() != 0)
21135       slope = (croppedData->at(1).y()-croppedData->at(0).y())/(croppedData->at(1).x()-croppedData->at(0).x());
21136     else
21137       slope = 0;
21138     (*croppedData)[0].setY(croppedData->at(0).y()+slope*(staticData->first().x()-croppedData->at(0).x()));
21139     (*croppedData)[0].setX(staticData->first().x());
21140 
21141     // crop upper bound:
21142     if (staticData->last().x() > croppedData->last().x()) // other one must be cropped
21143       qSwap(staticData, croppedData);
21144     int highBound = findIndexAboveX(croppedData, staticData->last().x());
21145     if (highBound == -1) return QPolygonF(); // key ranges have no overlap
21146     croppedData->remove(highBound+1, croppedData->size()-(highBound+1));
21147     // set highest point of cropped data to fit exactly key position of last static data
21148     // point via linear interpolation:
21149     if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation
21150     int li = croppedData->size()-1; // last index
21151     if (croppedData->at(li).x()-croppedData->at(li-1).x() != 0)
21152       slope = (croppedData->at(li).y()-croppedData->at(li-1).y())/(croppedData->at(li).x()-croppedData->at(li-1).x());
21153     else
21154       slope = 0;
21155     (*croppedData)[li].setY(croppedData->at(li-1).y()+slope*(staticData->last().x()-croppedData->at(li-1).x()));
21156     (*croppedData)[li].setX(staticData->last().x());
21157   } else // mKeyAxis->orientation() == Qt::Vertical
21158   {
21159     // y is key
21160     // similar to "x is key" but switched x,y. Further, lower/upper meaning is inverted compared to x,
21161     // because in pixel coordinates, y increases from top to bottom, not bottom to top like data coordinate.
21162     // if an axis range is reversed, the data point keys will be descending. Reverse them, since following algorithm assumes ascending keys:
21163     if (staticData->first().y() < staticData->last().y())
21164     {
21165       int size = staticData->size();
21166       for (int i=0; i<size/2; ++i)
21167         qSwap((*staticData)[i], (*staticData)[size-1-i]);
21168     }
21169     if (croppedData->first().y() < croppedData->last().y())
21170     {
21171       int size = croppedData->size();
21172       for (int i=0; i<size/2; ++i)
21173         qSwap((*croppedData)[i], (*croppedData)[size-1-i]);
21174     }
21175     // crop lower bound:
21176     if (staticData->first().y() > croppedData->first().y()) // other one must be cropped
21177       qSwap(staticData, croppedData);
21178     int lowBound = findIndexAboveY(croppedData, staticData->first().y());
21179     if (lowBound == -1) return QPolygonF(); // key ranges have no overlap
21180     croppedData->remove(0, lowBound);
21181     // set lowest point of cropped data to fit exactly key position of first static data
21182     // point via linear interpolation:
21183     if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation
21184     double slope;
21185     if (croppedData->at(1).y()-croppedData->at(0).y() != 0) // avoid division by zero in step plots
21186       slope = (croppedData->at(1).x()-croppedData->at(0).x())/(croppedData->at(1).y()-croppedData->at(0).y());
21187     else
21188       slope = 0;
21189     (*croppedData)[0].setX(croppedData->at(0).x()+slope*(staticData->first().y()-croppedData->at(0).y()));
21190     (*croppedData)[0].setY(staticData->first().y());
21191 
21192     // crop upper bound:
21193     if (staticData->last().y() < croppedData->last().y()) // other one must be cropped
21194       qSwap(staticData, croppedData);
21195     int highBound = findIndexBelowY(croppedData, staticData->last().y());
21196     if (highBound == -1) return QPolygonF(); // key ranges have no overlap
21197     croppedData->remove(highBound+1, croppedData->size()-(highBound+1));
21198     // set highest point of cropped data to fit exactly key position of last static data
21199     // point via linear interpolation:
21200     if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation
21201     int li = croppedData->size()-1; // last index
21202     if (croppedData->at(li).y()-croppedData->at(li-1).y() != 0) // avoid division by zero in step plots
21203       slope = (croppedData->at(li).x()-croppedData->at(li-1).x())/(croppedData->at(li).y()-croppedData->at(li-1).y());
21204     else
21205       slope = 0;
21206     (*croppedData)[li].setX(croppedData->at(li-1).x()+slope*(staticData->last().y()-croppedData->at(li-1).y()));
21207     (*croppedData)[li].setY(staticData->last().y());
21208   }
21209 
21210   // return joined:
21211   for (int i=otherData.size()-1; i>=0; --i) // insert reversed, otherwise the polygon will be twisted
21212     thisData << otherData.at(i);
21213   return QPolygonF(thisData);
21214 }
21215 
21216 /*! \internal
21217 
21218   Finds the smallest index of \a data, whose points x value is just above \a x. Assumes x values in
21219   \a data points are ordered ascending, as is the case when plotting with horizontal key axis.
21220 
21221   Used to calculate the channel fill polygon, see \ref getChannelFillPolygon.
21222 */
findIndexAboveX(const QVector<QPointF> * data,double x) const21223 int QCPGraph::findIndexAboveX(const QVector<QPointF> *data, double x) const
21224 {
21225   for (int i=data->size()-1; i>=0; --i)
21226   {
21227     if (data->at(i).x() < x)
21228     {
21229       if (i<data->size()-1)
21230         return i+1;
21231       else
21232         return data->size()-1;
21233     }
21234   }
21235   return -1;
21236 }
21237 
21238 /*! \internal
21239 
21240   Finds the highest index of \a data, whose points x value is just below \a x. Assumes x values in
21241   \a data points are ordered ascending, as is the case when plotting with horizontal key axis.
21242 
21243   Used to calculate the channel fill polygon, see \ref getChannelFillPolygon.
21244 */
findIndexBelowX(const QVector<QPointF> * data,double x) const21245 int QCPGraph::findIndexBelowX(const QVector<QPointF> *data, double x) const
21246 {
21247   for (int i=0; i<data->size(); ++i)
21248   {
21249     if (data->at(i).x() > x)
21250     {
21251       if (i>0)
21252         return i-1;
21253       else
21254         return 0;
21255     }
21256   }
21257   return -1;
21258 }
21259 
21260 /*! \internal
21261 
21262   Finds the smallest index of \a data, whose points y value is just above \a y. Assumes y values in
21263   \a data points are ordered descending, as is the case when plotting with vertical key axis.
21264 
21265   Used to calculate the channel fill polygon, see \ref getChannelFillPolygon.
21266 */
findIndexAboveY(const QVector<QPointF> * data,double y) const21267 int QCPGraph::findIndexAboveY(const QVector<QPointF> *data, double y) const
21268 {
21269   for (int i=0; i<data->size(); ++i)
21270   {
21271     if (data->at(i).y() < y)
21272     {
21273       if (i>0)
21274         return i-1;
21275       else
21276         return 0;
21277     }
21278   }
21279   return -1;
21280 }
21281 
21282 /*! \internal
21283 
21284   Calculates the minimum distance in pixels the graph's representation has from the given \a
21285   pixelPoint. This is used to determine whether the graph was clicked or not, e.g. in \ref
21286   selectTest. The closest data point to \a pixelPoint is returned in \a closestData. Note that if
21287   the graph has a line representation, the returned distance may be smaller than the distance to
21288   the \a closestData point, since the distance to the graph line is also taken into account.
21289 
21290   If either the graph has no data or if the line style is \ref lsNone and the scatter style's shape
21291   is \ref QCPScatterStyle::ssNone (i.e. there is no visual representation of the graph), returns -1.0.
21292 */
pointDistance(const QPointF & pixelPoint,QCPGraphDataContainer::const_iterator & closestData) const21293 double QCPGraph::pointDistance(const QPointF &pixelPoint, QCPGraphDataContainer::const_iterator &closestData) const
21294 {
21295   closestData = mDataContainer->constEnd();
21296   if (mDataContainer->isEmpty())
21297     return -1.0;
21298   if (mLineStyle == lsNone && mScatterStyle.isNone())
21299     return -1.0;
21300 
21301   // calculate minimum distances to graph data points and find closestData iterator:
21302   double minDistSqr = std::numeric_limits<double>::max();
21303   // determine which key range comes into question, taking selection tolerance around pos into account:
21304   double posKeyMin, posKeyMax, dummy;
21305   pixelsToCoords(pixelPoint-QPointF(mParentPlot->selectionTolerance(), mParentPlot->selectionTolerance()), posKeyMin, dummy);
21306   pixelsToCoords(pixelPoint+QPointF(mParentPlot->selectionTolerance(), mParentPlot->selectionTolerance()), posKeyMax, dummy);
21307   if (posKeyMin > posKeyMax)
21308     qSwap(posKeyMin, posKeyMax);
21309   // iterate over found data points and then choose the one with the shortest distance to pos:
21310   QCPGraphDataContainer::const_iterator begin = mDataContainer->findBegin(posKeyMin, true);
21311   QCPGraphDataContainer::const_iterator end = mDataContainer->findEnd(posKeyMax, true);
21312   for (QCPGraphDataContainer::const_iterator it=begin; it!=end; ++it)
21313   {
21314     const double currentDistSqr = QCPVector2D(coordsToPixels(it->key, it->value)-pixelPoint).lengthSquared();
21315     if (currentDistSqr < minDistSqr)
21316     {
21317       minDistSqr = currentDistSqr;
21318       closestData = it;
21319     }
21320   }
21321 
21322   // calculate distance to graph line if there is one (if so, will probably be smaller than distance to closest data point):
21323   if (mLineStyle != lsNone)
21324   {
21325     // line displayed, calculate distance to line segments:
21326     QVector<QPointF> lineData;
21327     getLines(&lineData, QCPDataRange(0, dataCount()));
21328     QCPVector2D p(pixelPoint);
21329     const int step = mLineStyle==lsImpulse ? 2 : 1; // impulse plot differs from other line styles in that the lineData points are only pairwise connected
21330     for (int i=0; i<lineData.size()-1; i+=step)
21331     {
21332       const double currentDistSqr = p.distanceSquaredToLine(lineData.at(i), lineData.at(i+1));
21333       if (currentDistSqr < minDistSqr)
21334         minDistSqr = currentDistSqr;
21335     }
21336   }
21337 
21338   return qSqrt(minDistSqr);
21339 }
21340 
21341 /*! \internal
21342 
21343   Finds the highest index of \a data, whose points y value is just below \a y. Assumes y values in
21344   \a data points are ordered descending, as is the case when plotting with vertical key axis (since
21345   keys are ordered ascending).
21346 
21347   Used to calculate the channel fill polygon, see \ref getChannelFillPolygon.
21348 */
findIndexBelowY(const QVector<QPointF> * data,double y) const21349 int QCPGraph::findIndexBelowY(const QVector<QPointF> *data, double y) const
21350 {
21351   for (int i=data->size()-1; i>=0; --i)
21352   {
21353     if (data->at(i).y() > y)
21354     {
21355       if (i<data->size()-1)
21356         return i+1;
21357       else
21358         return data->size()-1;
21359     }
21360   }
21361   return -1;
21362 }
21363 /* end of 'src/plottables/plottable-graph.cpp' */
21364 
21365 
21366 /* including file 'src/plottables/plottable-curve.cpp', size 60009           */
21367 /* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
21368 
21369 ////////////////////////////////////////////////////////////////////////////////////////////////////
21370 //////////////////// QCPCurveData
21371 ////////////////////////////////////////////////////////////////////////////////////////////////////
21372 
21373 /*! \class QCPCurveData
21374   \brief Holds the data of one single data point for QCPCurve.
21375 
21376   The stored data is:
21377   \li \a t: the free ordering parameter of this curve point, like in the mathematical vector <em>(x(t), y(t))</em>. (This is the \a sortKey)
21378   \li \a key: coordinate on the key axis of this curve point (this is the \a mainKey)
21379   \li \a value: coordinate on the value axis of this curve point (this is the \a mainValue)
21380 
21381   The container for storing multiple data points is \ref QCPCurveDataContainer. It is a typedef for
21382   \ref QCPDataContainer with \ref QCPCurveData as the DataType template parameter. See the
21383   documentation there for an explanation regarding the data type's generic methods.
21384 
21385   \see QCPCurveDataContainer
21386 */
21387 
21388 /* start documentation of inline functions */
21389 
21390 /*! \fn double QCPCurveData::sortKey() const
21391 
21392   Returns the \a t member of this data point.
21393 
21394   For a general explanation of what this method is good for in the context of the data container,
21395   see the documentation of \ref QCPDataContainer.
21396 */
21397 
21398 /*! \fn static QCPCurveData QCPCurveData::fromSortKey(double sortKey)
21399 
21400   Returns a data point with the specified \a sortKey (assigned to the data point's \a t member).
21401   All other members are set to zero.
21402 
21403   For a general explanation of what this method is good for in the context of the data container,
21404   see the documentation of \ref QCPDataContainer.
21405 */
21406 
21407 /*! \fn static static bool QCPCurveData::sortKeyIsMainKey()
21408 
21409   Since the member \a key is the data point key coordinate and the member \a t is the data ordering
21410   parameter, this method returns false.
21411 
21412   For a general explanation of what this method is good for in the context of the data container,
21413   see the documentation of \ref QCPDataContainer.
21414 */
21415 
21416 /*! \fn double QCPCurveData::mainKey() const
21417 
21418   Returns the \a key member of this data point.
21419 
21420   For a general explanation of what this method is good for in the context of the data container,
21421   see the documentation of \ref QCPDataContainer.
21422 */
21423 
21424 /*! \fn double QCPCurveData::mainValue() const
21425 
21426   Returns the \a value member of this data point.
21427 
21428   For a general explanation of what this method is good for in the context of the data container,
21429   see the documentation of \ref QCPDataContainer.
21430 */
21431 
21432 /*! \fn QCPRange QCPCurveData::valueRange() const
21433 
21434   Returns a QCPRange with both lower and upper boundary set to \a value of this data point.
21435 
21436   For a general explanation of what this method is good for in the context of the data container,
21437   see the documentation of \ref QCPDataContainer.
21438 */
21439 
21440 /* end documentation of inline functions */
21441 
21442 /*!
21443   Constructs a curve data point with t, key and value set to zero.
21444 */
QCPCurveData()21445 QCPCurveData::QCPCurveData() :
21446   t(0),
21447   key(0),
21448   value(0)
21449 {
21450 }
21451 
21452 /*!
21453   Constructs a curve data point with the specified \a t, \a key and \a value.
21454 */
QCPCurveData(double t,double key,double value)21455 QCPCurveData::QCPCurveData(double t, double key, double value) :
21456   t(t),
21457   key(key),
21458   value(value)
21459 {
21460 }
21461 
21462 
21463 ////////////////////////////////////////////////////////////////////////////////////////////////////
21464 //////////////////// QCPCurve
21465 ////////////////////////////////////////////////////////////////////////////////////////////////////
21466 
21467 /*! \class QCPCurve
21468   \brief A plottable representing a parametric curve in a plot.
21469 
21470   \image html QCPCurve.png
21471 
21472   Unlike QCPGraph, plottables of this type may have multiple points with the same key coordinate,
21473   so their visual representation can have \a loops. This is realized by introducing a third
21474   coordinate \a t, which defines the order of the points described by the other two coordinates \a
21475   x and \a y.
21476 
21477   To plot data, assign it with the \ref setData or \ref addData functions. Alternatively, you can
21478   also access and modify the curve's data via the \ref data method, which returns a pointer to the
21479   internal \ref QCPCurveDataContainer.
21480 
21481   Gaps in the curve can be created by adding data points with NaN as key and value
21482   (<tt>qQNaN()</tt> or <tt>std::numeric_limits<double>::quiet_NaN()</tt>) in between the two data points that shall be
21483   separated.
21484 
21485   \section qcpcurve-appearance Changing the appearance
21486 
21487   The appearance of the curve is determined by the pen and the brush (\ref setPen, \ref setBrush).
21488 
21489   \section qcpcurve-usage Usage
21490 
21491   Like all data representing objects in QCustomPlot, the QCPCurve is a plottable
21492   (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies
21493   (QCustomPlot::plottable, QCustomPlot::removePlottable, etc.)
21494 
21495   Usually, you first create an instance:
21496   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcurve-creation-1
21497   which registers it with the QCustomPlot instance of the passed axes. Note that this QCustomPlot instance takes
21498   ownership of the plottable, so do not delete it manually but use QCustomPlot::removePlottable() instead.
21499   The newly created plottable can be modified, e.g.:
21500   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcurve-creation-2
21501 */
21502 
21503 /* start of documentation of inline functions */
21504 
21505 /*! \fn QSharedPointer<QCPCurveDataContainer> QCPCurve::data() const
21506 
21507   Returns a shared pointer to the internal data storage of type \ref QCPCurveDataContainer. You may
21508   use it to directly manipulate the data, which may be more convenient and faster than using the
21509   regular \ref setData or \ref addData methods.
21510 */
21511 
21512 /* end of documentation of inline functions */
21513 
21514 /*!
21515   Constructs a curve which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value
21516   axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have
21517   the same orientation. If either of these restrictions is violated, a corresponding message is
21518   printed to the debug output (qDebug), the construction is not aborted, though.
21519 
21520   The created QCPCurve is automatically registered with the QCustomPlot instance inferred from \a
21521   keyAxis. This QCustomPlot instance takes ownership of the QCPCurve, so do not delete it manually
21522   but use QCustomPlot::removePlottable() instead.
21523 */
QCPCurve(QCPAxis * keyAxis,QCPAxis * valueAxis)21524 QCPCurve::QCPCurve(QCPAxis *keyAxis, QCPAxis *valueAxis) :
21525   QCPAbstractPlottable1D<QCPCurveData>(keyAxis, valueAxis)
21526 {
21527   // modify inherited properties from abstract plottable:
21528   setPen(QPen(Qt::blue, 0));
21529   setBrush(Qt::NoBrush);
21530 
21531   setScatterStyle(QCPScatterStyle());
21532   setLineStyle(lsLine);
21533 }
21534 
~QCPCurve()21535 QCPCurve::~QCPCurve()
21536 {
21537 }
21538 
21539 /*! \overload
21540 
21541   Replaces the current data container with the provided \a data container.
21542 
21543   Since a QSharedPointer is used, multiple QCPCurves may share the same data container safely.
21544   Modifying the data in the container will then affect all curves that share the container. Sharing
21545   can be achieved by simply exchanging the data containers wrapped in shared pointers:
21546   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcurve-datasharing-1
21547 
21548   If you do not wish to share containers, but create a copy from an existing container, rather use
21549   the \ref QCPDataContainer<DataType>::set method on the curve's data container directly:
21550   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcurve-datasharing-2
21551 
21552   \see addData
21553 */
setData(QSharedPointer<QCPCurveDataContainer> data)21554 void QCPCurve::setData(QSharedPointer<QCPCurveDataContainer> data)
21555 {
21556   mDataContainer = data;
21557 }
21558 
21559 /*! \overload
21560 
21561   Replaces the current data with the provided points in \a t, \a keys and \a values. The provided
21562   vectors should have equal length. Else, the number of added points will be the size of the
21563   smallest vector.
21564 
21565   If you can guarantee that the passed data points are sorted by \a t in ascending order, you can
21566   set \a alreadySorted to true, to improve performance by saving a sorting run.
21567 
21568   \see addData
21569 */
setData(const QVector<double> & t,const QVector<double> & keys,const QVector<double> & values,bool alreadySorted)21570 void QCPCurve::setData(const QVector<double> &t, const QVector<double> &keys, const QVector<double> &values, bool alreadySorted)
21571 {
21572   mDataContainer->clear();
21573   addData(t, keys, values, alreadySorted);
21574 }
21575 
21576 
21577 /*! \overload
21578 
21579   Replaces the current data with the provided points in \a keys and \a values. The provided vectors
21580   should have equal length. Else, the number of added points will be the size of the smallest
21581   vector.
21582 
21583   The t parameter of each data point will be set to the integer index of the respective key/value
21584   pair.
21585 
21586   \see addData
21587 */
setData(const QVector<double> & keys,const QVector<double> & values)21588 void QCPCurve::setData(const QVector<double> &keys, const QVector<double> &values)
21589 {
21590   mDataContainer->clear();
21591   addData(keys, values);
21592 }
21593 
21594 /*!
21595   Sets the visual appearance of single data points in the plot. If set to \ref
21596   QCPScatterStyle::ssNone, no scatter points are drawn (e.g. for line-only plots with appropriate
21597   line style).
21598 
21599   \see QCPScatterStyle, setLineStyle
21600 */
setScatterStyle(const QCPScatterStyle & style)21601 void QCPCurve::setScatterStyle(const QCPScatterStyle &style)
21602 {
21603   mScatterStyle = style;
21604 }
21605 
21606 /*!
21607   If scatters are displayed (scatter style not \ref QCPScatterStyle::ssNone), \a skip number of
21608   scatter points are skipped/not drawn after every drawn scatter point.
21609 
21610   This can be used to make the data appear sparser while for example still having a smooth line,
21611   and to improve performance for very high density plots.
21612 
21613   If \a skip is set to 0 (default), all scatter points are drawn.
21614 
21615   \see setScatterStyle
21616 */
setScatterSkip(int skip)21617 void QCPCurve::setScatterSkip(int skip)
21618 {
21619   mScatterSkip = qMax(0, skip);
21620 }
21621 
21622 /*!
21623   Sets how the single data points are connected in the plot or how they are represented visually
21624   apart from the scatter symbol. For scatter-only plots, set \a style to \ref lsNone and \ref
21625   setScatterStyle to the desired scatter style.
21626 
21627   \see setScatterStyle
21628 */
setLineStyle(QCPCurve::LineStyle style)21629 void QCPCurve::setLineStyle(QCPCurve::LineStyle style)
21630 {
21631   mLineStyle = style;
21632 }
21633 
21634 /*! \overload
21635 
21636   Adds the provided points in \a t, \a keys and \a values to the current data. The provided vectors
21637   should have equal length. Else, the number of added points will be the size of the smallest
21638   vector.
21639 
21640   If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
21641   can set \a alreadySorted to true, to improve performance by saving a sorting run.
21642 
21643   Alternatively, you can also access and modify the data directly via the \ref data method, which
21644   returns a pointer to the internal data container.
21645 */
addData(const QVector<double> & t,const QVector<double> & keys,const QVector<double> & values,bool alreadySorted)21646 void QCPCurve::addData(const QVector<double> &t, const QVector<double> &keys, const QVector<double> &values, bool alreadySorted)
21647 {
21648   if (t.size() != keys.size() || t.size() != values.size())
21649     qDebug() << Q_FUNC_INFO << "ts, keys and values have different sizes:" << t.size() << keys.size() << values.size();
21650   const int n = qMin(qMin(t.size(), keys.size()), values.size());
21651   QVector<QCPCurveData> tempData(n);
21652   QVector<QCPCurveData>::iterator it = tempData.begin();
21653   const QVector<QCPCurveData>::iterator itEnd = tempData.end();
21654   int i = 0;
21655   while (it != itEnd)
21656   {
21657     it->t = t[i];
21658     it->key = keys[i];
21659     it->value = values[i];
21660     ++it;
21661     ++i;
21662   }
21663   mDataContainer->add(tempData, alreadySorted); // don't modify tempData beyond this to prevent copy on write
21664 }
21665 
21666 /*! \overload
21667 
21668   Adds the provided points in \a keys and \a values to the current data. The provided vectors
21669   should have equal length. Else, the number of added points will be the size of the smallest
21670   vector.
21671 
21672   The t parameter of each data point will be set to the integer index of the respective key/value
21673   pair.
21674 
21675   Alternatively, you can also access and modify the data directly via the \ref data method, which
21676   returns a pointer to the internal data container.
21677 */
addData(const QVector<double> & keys,const QVector<double> & values)21678 void QCPCurve::addData(const QVector<double> &keys, const QVector<double> &values)
21679 {
21680   if (keys.size() != values.size())
21681     qDebug() << Q_FUNC_INFO << "keys and values have different sizes:" << keys.size() << values.size();
21682   const int n = qMin(keys.size(), values.size());
21683   double tStart;
21684   if (!mDataContainer->isEmpty())
21685     tStart = (mDataContainer->constEnd()-1)->t + 1.0;
21686   else
21687     tStart = 0;
21688   QVector<QCPCurveData> tempData(n);
21689   QVector<QCPCurveData>::iterator it = tempData.begin();
21690   const QVector<QCPCurveData>::iterator itEnd = tempData.end();
21691   int i = 0;
21692   while (it != itEnd)
21693   {
21694     it->t = tStart + i;
21695     it->key = keys[i];
21696     it->value = values[i];
21697     ++it;
21698     ++i;
21699   }
21700   mDataContainer->add(tempData, true); // don't modify tempData beyond this to prevent copy on write
21701 }
21702 
21703 /*! \overload
21704   Adds the provided data point as \a t, \a key and \a value to the current data.
21705 
21706   Alternatively, you can also access and modify the data directly via the \ref data method, which
21707   returns a pointer to the internal data container.
21708 */
addData(double t,double key,double value)21709 void QCPCurve::addData(double t, double key, double value)
21710 {
21711   mDataContainer->add(QCPCurveData(t, key, value));
21712 }
21713 
21714 /*! \overload
21715 
21716   Adds the provided data point as \a key and \a value to the current data.
21717 
21718   The t parameter is generated automatically by increments of 1 for each point, starting at the
21719   highest t of previously existing data or 0, if the curve data is empty.
21720 
21721   Alternatively, you can also access and modify the data directly via the \ref data method, which
21722   returns a pointer to the internal data container.
21723 */
addData(double key,double value)21724 void QCPCurve::addData(double key, double value)
21725 {
21726   if (!mDataContainer->isEmpty())
21727     mDataContainer->add(QCPCurveData((mDataContainer->constEnd()-1)->t + 1.0, key, value));
21728   else
21729     mDataContainer->add(QCPCurveData(0.0, key, value));
21730 }
21731 
21732 /* inherits documentation from base class */
selectTest(const QPointF & pos,bool onlySelectable,QVariant * details) const21733 double QCPCurve::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
21734 {
21735   if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
21736     return -1;
21737   if (!mKeyAxis || !mValueAxis)
21738     return -1;
21739 
21740   if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()))
21741   {
21742     QCPCurveDataContainer::const_iterator closestDataPoint = mDataContainer->constEnd();
21743     double result = pointDistance(pos, closestDataPoint);
21744     if (details)
21745     {
21746       int pointIndex = closestDataPoint-mDataContainer->constBegin();
21747       details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1)));
21748     }
21749     return result;
21750   } else
21751     return -1;
21752 }
21753 
21754 /* inherits documentation from base class */
getKeyRange(bool & foundRange,QCP::SignDomain inSignDomain) const21755 QCPRange QCPCurve::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const
21756 {
21757   return mDataContainer->keyRange(foundRange, inSignDomain);
21758 }
21759 
21760 /* inherits documentation from base class */
getValueRange(bool & foundRange,QCP::SignDomain inSignDomain,const QCPRange & inKeyRange) const21761 QCPRange QCPCurve::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const
21762 {
21763   return mDataContainer->valueRange(foundRange, inSignDomain, inKeyRange);
21764 }
21765 
21766 /* inherits documentation from base class */
draw(QCPPainter * painter)21767 void QCPCurve::draw(QCPPainter *painter)
21768 {
21769   if (mDataContainer->isEmpty()) return;
21770 
21771   // allocate line vector:
21772   QVector<QPointF> lines, scatters;
21773 
21774   // loop over and draw segments of unselected/selected data:
21775   QList<QCPDataRange> selectedSegments, unselectedSegments, allSegments;
21776   getDataSegments(selectedSegments, unselectedSegments);
21777   allSegments << unselectedSegments << selectedSegments;
21778   for (int i=0; i<allSegments.size(); ++i)
21779   {
21780     bool isSelectedSegment = i >= unselectedSegments.size();
21781 
21782     // fill with curve data:
21783     QPen finalCurvePen = mPen; // determine the final pen already here, because the line optimization depends on its stroke width
21784     if (isSelectedSegment && mSelectionDecorator)
21785       finalCurvePen = mSelectionDecorator->pen();
21786 
21787     QCPDataRange lineDataRange = isSelectedSegment ? allSegments.at(i) : allSegments.at(i).adjusted(-1, 1); // unselected segments extend lines to bordering selected data point (safe to exceed total data bounds in first/last segment, getCurveLines takes care)
21788     getCurveLines(&lines, lineDataRange, finalCurvePen.widthF());
21789 
21790     // check data validity if flag set:
21791   #ifdef QCUSTOMPLOT_CHECK_DATA
21792     for (QCPCurveDataContainer::const_iterator it = mDataContainer->constBegin(); it != mDataContainer->constEnd(); ++it)
21793     {
21794       if (QCP::isInvalidData(it->t) ||
21795           QCP::isInvalidData(it->key, it->value))
21796         qDebug() << Q_FUNC_INFO << "Data point at" << it->key << "invalid." << "Plottable name:" << name();
21797     }
21798   #endif
21799 
21800     // draw curve fill:
21801     applyFillAntialiasingHint(painter);
21802     if (isSelectedSegment && mSelectionDecorator)
21803       mSelectionDecorator->applyBrush(painter);
21804     else
21805       painter->setBrush(mBrush);
21806     painter->setPen(Qt::NoPen);
21807     if (painter->brush().style() != Qt::NoBrush && painter->brush().color().alpha() != 0)
21808       painter->drawPolygon(QPolygonF(lines));
21809 
21810     // draw curve line:
21811     if (mLineStyle != lsNone)
21812     {
21813       painter->setPen(finalCurvePen);
21814       painter->setBrush(Qt::NoBrush);
21815       drawCurveLine(painter, lines);
21816     }
21817 
21818     // draw scatters:
21819     QCPScatterStyle finalScatterStyle = mScatterStyle;
21820     if (isSelectedSegment && mSelectionDecorator)
21821       finalScatterStyle = mSelectionDecorator->getFinalScatterStyle(mScatterStyle);
21822     if (!finalScatterStyle.isNone())
21823     {
21824       getScatters(&scatters, allSegments.at(i), finalScatterStyle.size());
21825       drawScatterPlot(painter, scatters, finalScatterStyle);
21826     }
21827   }
21828 
21829   // draw other selection decoration that isn't just line/scatter pens and brushes:
21830   if (mSelectionDecorator)
21831     mSelectionDecorator->drawDecoration(painter, selection());
21832 }
21833 
21834 /* inherits documentation from base class */
drawLegendIcon(QCPPainter * painter,const QRectF & rect) const21835 void QCPCurve::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
21836 {
21837   // draw fill:
21838   if (mBrush.style() != Qt::NoBrush)
21839   {
21840     applyFillAntialiasingHint(painter);
21841     painter->fillRect(QRectF(rect.left(), rect.top()+rect.height()/2.0, rect.width(), rect.height()/3.0), mBrush);
21842   }
21843   // draw line vertically centered:
21844   if (mLineStyle != lsNone)
21845   {
21846     applyDefaultAntialiasingHint(painter);
21847     painter->setPen(mPen);
21848     painter->drawLine(QLineF(rect.left(), rect.top()+rect.height()/2.0, rect.right()+5, rect.top()+rect.height()/2.0)); // +5 on x2 else last segment is missing from dashed/dotted pens
21849   }
21850   // draw scatter symbol:
21851   if (!mScatterStyle.isNone())
21852   {
21853     applyScattersAntialiasingHint(painter);
21854     // scale scatter pixmap if it's too large to fit in legend icon rect:
21855     if (mScatterStyle.shape() == QCPScatterStyle::ssPixmap && (mScatterStyle.pixmap().size().width() > rect.width() || mScatterStyle.pixmap().size().height() > rect.height()))
21856     {
21857       QCPScatterStyle scaledStyle(mScatterStyle);
21858       scaledStyle.setPixmap(scaledStyle.pixmap().scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
21859       scaledStyle.applyTo(painter, mPen);
21860       scaledStyle.drawShape(painter, QRectF(rect).center());
21861     } else
21862     {
21863       mScatterStyle.applyTo(painter, mPen);
21864       mScatterStyle.drawShape(painter, QRectF(rect).center());
21865     }
21866   }
21867 }
21868 
21869 /*!  \internal
21870 
21871   Draws lines between the points in \a lines, given in pixel coordinates.
21872 
21873   \see drawScatterPlot, getCurveLines
21874 */
drawCurveLine(QCPPainter * painter,const QVector<QPointF> & lines) const21875 void QCPCurve::drawCurveLine(QCPPainter *painter, const QVector<QPointF> &lines) const
21876 {
21877   if (painter->pen().style() != Qt::NoPen && painter->pen().color().alpha() != 0)
21878   {
21879     applyDefaultAntialiasingHint(painter);
21880     drawPolyline(painter, lines);
21881   }
21882 }
21883 
21884 /*! \internal
21885 
21886   Draws scatter symbols at every point passed in \a points, given in pixel coordinates. The
21887   scatters will be drawn with \a painter and have the appearance as specified in \a style.
21888 
21889   \see drawCurveLine, getCurveLines
21890 */
drawScatterPlot(QCPPainter * painter,const QVector<QPointF> & points,const QCPScatterStyle & style) const21891 void QCPCurve::drawScatterPlot(QCPPainter *painter, const QVector<QPointF> &points, const QCPScatterStyle &style) const
21892 {
21893   // draw scatter point symbols:
21894   applyScattersAntialiasingHint(painter);
21895   style.applyTo(painter, mPen);
21896   for (int i=0; i<points.size(); ++i)
21897     if (!qIsNaN(points.at(i).x()) && !qIsNaN(points.at(i).y()))
21898       style.drawShape(painter,  points.at(i));
21899 }
21900 
21901 /*! \internal
21902 
21903   Called by \ref draw to generate points in pixel coordinates which represent the line of the
21904   curve.
21905 
21906   Line segments that aren't visible in the current axis rect are handled in an optimized way. They
21907   are projected onto a rectangle slightly larger than the visible axis rect and simplified
21908   regarding point count. The algorithm makes sure to preserve appearance of lines and fills inside
21909   the visible axis rect by generating new temporary points on the outer rect if necessary.
21910 
21911   \a lines will be filled with points in pixel coordinates, that can be drawn with \ref
21912   drawCurveLine.
21913 
21914   \a dataRange specifies the beginning and ending data indices that will be taken into account for
21915   conversion. In this function, the specified range may exceed the total data bounds without harm:
21916   a correspondingly trimmed data range will be used. This takes the burden off the user of this
21917   function to check for valid indices in \a dataRange, e.g. when extending ranges coming from \ref
21918   getDataSegments.
21919 
21920   \a penWidth specifies the pen width that will be used to later draw the lines generated by this
21921   function. This is needed here to calculate an accordingly wider margin around the axis rect when
21922   performing the line optimization.
21923 
21924   Methods that are also involved in the algorithm are: \ref getRegion, \ref getOptimizedPoint, \ref
21925   getOptimizedCornerPoints \ref mayTraverse, \ref getTraverse, \ref getTraverseCornerPoints.
21926 
21927   \see drawCurveLine, drawScatterPlot
21928 */
getCurveLines(QVector<QPointF> * lines,const QCPDataRange & dataRange,double penWidth) const21929 void QCPCurve::getCurveLines(QVector<QPointF> *lines, const QCPDataRange &dataRange, double penWidth) const
21930 {
21931   if (!lines) return;
21932   lines->clear();
21933   QCPAxis *keyAxis = mKeyAxis.data();
21934   QCPAxis *valueAxis = mValueAxis.data();
21935   if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
21936 
21937   // add margins to rect to compensate for stroke width
21938   const double strokeMargin = qMax(qreal(1.0), qreal(penWidth*0.75)); // stroke radius + 50% safety
21939   const double keyMin = keyAxis->pixelToCoord(keyAxis->coordToPixel(keyAxis->range().lower)-strokeMargin*keyAxis->pixelOrientation());
21940   const double keyMax = keyAxis->pixelToCoord(keyAxis->coordToPixel(keyAxis->range().upper)+strokeMargin*keyAxis->pixelOrientation());
21941   const double valueMin = valueAxis->pixelToCoord(valueAxis->coordToPixel(valueAxis->range().lower)-strokeMargin*valueAxis->pixelOrientation());
21942   const double valueMax = valueAxis->pixelToCoord(valueAxis->coordToPixel(valueAxis->range().upper)+strokeMargin*valueAxis->pixelOrientation());
21943   QCPCurveDataContainer::const_iterator itBegin = mDataContainer->constBegin();
21944   QCPCurveDataContainer::const_iterator itEnd = mDataContainer->constEnd();
21945   mDataContainer->limitIteratorsToDataRange(itBegin, itEnd, dataRange);
21946   if (itBegin == itEnd)
21947     return;
21948   QCPCurveDataContainer::const_iterator it = itBegin;
21949   QCPCurveDataContainer::const_iterator prevIt = itEnd-1;
21950   int prevRegion = getRegion(prevIt->key, prevIt->value, keyMin, valueMax, keyMax, valueMin);
21951   QVector<QPointF> trailingPoints; // points that must be applied after all other points (are generated only when handling first point to get virtual segment between last and first point right)
21952   while (it != itEnd)
21953   {
21954     const int currentRegion = getRegion(it->key, it->value, keyMin, valueMax, keyMax, valueMin);
21955     if (currentRegion != prevRegion) // changed region, possibly need to add some optimized edge points or original points if entering R
21956     {
21957       if (currentRegion != 5) // segment doesn't end in R, so it's a candidate for removal
21958       {
21959         QPointF crossA, crossB;
21960         if (prevRegion == 5) // we're coming from R, so add this point optimized
21961         {
21962           lines->append(getOptimizedPoint(currentRegion, it->key, it->value, prevIt->key, prevIt->value, keyMin, valueMax, keyMax, valueMin));
21963           // in the situations 5->1/7/9/3 the segment may leave R and directly cross through two outer regions. In these cases we need to add an additional corner point
21964           *lines << getOptimizedCornerPoints(prevRegion, currentRegion, prevIt->key, prevIt->value, it->key, it->value, keyMin, valueMax, keyMax, valueMin);
21965         } else if (mayTraverse(prevRegion, currentRegion) &&
21966                    getTraverse(prevIt->key, prevIt->value, it->key, it->value, keyMin, valueMax, keyMax, valueMin, crossA, crossB))
21967         {
21968           // add the two cross points optimized if segment crosses R and if segment isn't virtual zeroth segment between last and first curve point:
21969           QVector<QPointF> beforeTraverseCornerPoints, afterTraverseCornerPoints;
21970           getTraverseCornerPoints(prevRegion, currentRegion, keyMin, valueMax, keyMax, valueMin, beforeTraverseCornerPoints, afterTraverseCornerPoints);
21971           if (it != itBegin)
21972           {
21973             *lines << beforeTraverseCornerPoints;
21974             lines->append(crossA);
21975             lines->append(crossB);
21976             *lines << afterTraverseCornerPoints;
21977           } else
21978           {
21979             lines->append(crossB);
21980             *lines << afterTraverseCornerPoints;
21981             trailingPoints << beforeTraverseCornerPoints << crossA ;
21982           }
21983         } else // doesn't cross R, line is just moving around in outside regions, so only need to add optimized point(s) at the boundary corner(s)
21984         {
21985           *lines << getOptimizedCornerPoints(prevRegion, currentRegion, prevIt->key, prevIt->value, it->key, it->value, keyMin, valueMax, keyMax, valueMin);
21986         }
21987       } else // segment does end in R, so we add previous point optimized and this point at original position
21988       {
21989         if (it == itBegin) // it is first point in curve and prevIt is last one. So save optimized point for adding it to the lineData in the end
21990           trailingPoints << getOptimizedPoint(prevRegion, prevIt->key, prevIt->value, it->key, it->value, keyMin, valueMax, keyMax, valueMin);
21991         else
21992           lines->append(getOptimizedPoint(prevRegion, prevIt->key, prevIt->value, it->key, it->value, keyMin, valueMax, keyMax, valueMin));
21993         lines->append(coordsToPixels(it->key, it->value));
21994       }
21995     } else // region didn't change
21996     {
21997       if (currentRegion == 5) // still in R, keep adding original points
21998       {
21999         lines->append(coordsToPixels(it->key, it->value));
22000       } else // still outside R, no need to add anything
22001       {
22002         // see how this is not doing anything? That's the main optimization...
22003       }
22004     }
22005     prevIt = it;
22006     prevRegion = currentRegion;
22007     ++it;
22008   }
22009   *lines << trailingPoints;
22010 }
22011 
22012 /*! \internal
22013 
22014   Called by \ref draw to generate points in pixel coordinates which represent the scatters of the
22015   curve. If a scatter skip is configured (\ref setScatterSkip), the returned points are accordingly
22016   sparser.
22017 
22018   Scatters that aren't visible in the current axis rect are optimized away.
22019 
22020   \a scatters will be filled with points in pixel coordinates, that can be drawn with \ref
22021   drawScatterPlot.
22022 
22023   \a dataRange specifies the beginning and ending data indices that will be taken into account for
22024   conversion.
22025 
22026   \a scatterWidth specifies the scatter width that will be used to later draw the scatters at pixel
22027   coordinates generated by this function. This is needed here to calculate an accordingly wider
22028   margin around the axis rect when performing the data point reduction.
22029 
22030   \see draw, drawScatterPlot
22031 */
getScatters(QVector<QPointF> * scatters,const QCPDataRange & dataRange,double scatterWidth) const22032 void QCPCurve::getScatters(QVector<QPointF> *scatters, const QCPDataRange &dataRange, double scatterWidth) const
22033 {
22034   if (!scatters) return;
22035   scatters->clear();
22036   QCPAxis *keyAxis = mKeyAxis.data();
22037   QCPAxis *valueAxis = mValueAxis.data();
22038   if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
22039 
22040   QCPCurveDataContainer::const_iterator begin = mDataContainer->constBegin();
22041   QCPCurveDataContainer::const_iterator end = mDataContainer->constEnd();
22042   mDataContainer->limitIteratorsToDataRange(begin, end, dataRange);
22043   if (begin == end)
22044     return;
22045   const int scatterModulo = mScatterSkip+1;
22046   const bool doScatterSkip = mScatterSkip > 0;
22047   int endIndex = end-mDataContainer->constBegin();
22048 
22049   QCPRange keyRange = keyAxis->range();
22050   QCPRange valueRange = valueAxis->range();
22051   // extend range to include width of scatter symbols:
22052   keyRange.lower = keyAxis->pixelToCoord(keyAxis->coordToPixel(keyRange.lower)-scatterWidth*keyAxis->pixelOrientation());
22053   keyRange.upper = keyAxis->pixelToCoord(keyAxis->coordToPixel(keyRange.upper)+scatterWidth*keyAxis->pixelOrientation());
22054   valueRange.lower = valueAxis->pixelToCoord(valueAxis->coordToPixel(valueRange.lower)-scatterWidth*valueAxis->pixelOrientation());
22055   valueRange.upper = valueAxis->pixelToCoord(valueAxis->coordToPixel(valueRange.upper)+scatterWidth*valueAxis->pixelOrientation());
22056 
22057   QCPCurveDataContainer::const_iterator it = begin;
22058   int itIndex = begin-mDataContainer->constBegin();
22059   while (doScatterSkip && it != end && itIndex % scatterModulo != 0) // advance begin iterator to first non-skipped scatter
22060   {
22061     ++itIndex;
22062     ++it;
22063   }
22064   if (keyAxis->orientation() == Qt::Vertical)
22065   {
22066     while (it != end)
22067     {
22068       if (!qIsNaN(it->value) && keyRange.contains(it->key) && valueRange.contains(it->value))
22069         scatters->append(QPointF(valueAxis->coordToPixel(it->value), keyAxis->coordToPixel(it->key)));
22070 
22071       // advance iterator to next (non-skipped) data point:
22072       if (!doScatterSkip)
22073         ++it;
22074       else
22075       {
22076         itIndex += scatterModulo;
22077         if (itIndex < endIndex) // make sure we didn't jump over end
22078           it += scatterModulo;
22079         else
22080         {
22081           it = end;
22082           itIndex = endIndex;
22083         }
22084       }
22085     }
22086   } else
22087   {
22088     while (it != end)
22089     {
22090       if (!qIsNaN(it->value) && keyRange.contains(it->key) && valueRange.contains(it->value))
22091         scatters->append(QPointF(keyAxis->coordToPixel(it->key), valueAxis->coordToPixel(it->value)));
22092 
22093       // advance iterator to next (non-skipped) data point:
22094       if (!doScatterSkip)
22095         ++it;
22096       else
22097       {
22098         itIndex += scatterModulo;
22099         if (itIndex < endIndex) // make sure we didn't jump over end
22100           it += scatterModulo;
22101         else
22102         {
22103           it = end;
22104           itIndex = endIndex;
22105         }
22106       }
22107     }
22108   }
22109 }
22110 
22111 /*! \internal
22112 
22113   This function is part of the curve optimization algorithm of \ref getCurveLines.
22114 
22115   It returns the region of the given point (\a key, \a value) with respect to a rectangle defined
22116   by \a keyMin, \a keyMax, \a valueMin, and \a valueMax.
22117 
22118   The regions are enumerated from top to bottom (\a valueMin to \a valueMax) and left to right (\a
22119   keyMin to \a keyMax):
22120 
22121   <table style="width:10em; text-align:center">
22122     <tr><td>1</td><td>4</td><td>7</td></tr>
22123     <tr><td>2</td><td style="border:1px solid black">5</td><td>8</td></tr>
22124     <tr><td>3</td><td>6</td><td>9</td></tr>
22125   </table>
22126 
22127   With the rectangle being region 5, and the outer regions extending infinitely outwards. In the
22128   curve optimization algorithm, region 5 is considered to be the visible portion of the plot.
22129 */
getRegion(double key,double value,double keyMin,double valueMax,double keyMax,double valueMin) const22130 int QCPCurve::getRegion(double key, double value, double keyMin, double valueMax, double keyMax, double valueMin) const
22131 {
22132   if (key < keyMin) // region 123
22133   {
22134     if (value > valueMax)
22135       return 1;
22136     else if (value < valueMin)
22137       return 3;
22138     else
22139       return 2;
22140   } else if (key > keyMax) // region 789
22141   {
22142     if (value > valueMax)
22143       return 7;
22144     else if (value < valueMin)
22145       return 9;
22146     else
22147       return 8;
22148   } else // region 456
22149   {
22150     if (value > valueMax)
22151       return 4;
22152     else if (value < valueMin)
22153       return 6;
22154     else
22155       return 5;
22156   }
22157 }
22158 
22159 /*! \internal
22160 
22161   This function is part of the curve optimization algorithm of \ref getCurveLines.
22162 
22163   This method is used in case the current segment passes from inside the visible rect (region 5,
22164   see \ref getRegion) to any of the outer regions (\a otherRegion). The current segment is given by
22165   the line connecting (\a key, \a value) with (\a otherKey, \a otherValue).
22166 
22167   It returns the intersection point of the segment with the border of region 5.
22168 
22169   For this function it doesn't matter whether (\a key, \a value) is the point inside region 5 or
22170   whether it's (\a otherKey, \a otherValue), i.e. whether the segment is coming from region 5 or
22171   leaving it. It is important though that \a otherRegion correctly identifies the other region not
22172   equal to 5.
22173 */
getOptimizedPoint(int otherRegion,double otherKey,double otherValue,double key,double value,double keyMin,double valueMax,double keyMax,double valueMin) const22174 QPointF QCPCurve::getOptimizedPoint(int otherRegion, double otherKey, double otherValue, double key, double value, double keyMin, double valueMax, double keyMax, double valueMin) const
22175 {
22176   double intersectKey = keyMin; // initial value is just fail-safe
22177   double intersectValue = valueMax; // initial value is just fail-safe
22178   switch (otherRegion)
22179   {
22180     case 1: // top and left edge
22181     {
22182       intersectValue = valueMax;
22183       intersectKey = otherKey + (key-otherKey)/(value-otherValue)*(intersectValue-otherValue);
22184       if (intersectKey < keyMin || intersectKey > keyMax) // doesn't intersect, so must intersect other:
22185       {
22186         intersectKey = keyMin;
22187         intersectValue = otherValue + (value-otherValue)/(key-otherKey)*(intersectKey-otherKey);
22188       }
22189       break;
22190     }
22191     case 2: // left edge
22192     {
22193       intersectKey = keyMin;
22194       intersectValue = otherValue + (value-otherValue)/(key-otherKey)*(intersectKey-otherKey);
22195       break;
22196     }
22197     case 3: // bottom and left edge
22198     {
22199       intersectValue = valueMin;
22200       intersectKey = otherKey + (key-otherKey)/(value-otherValue)*(intersectValue-otherValue);
22201       if (intersectKey < keyMin || intersectKey > keyMax) // doesn't intersect, so must intersect other:
22202       {
22203         intersectKey = keyMin;
22204         intersectValue = otherValue + (value-otherValue)/(key-otherKey)*(intersectKey-otherKey);
22205       }
22206       break;
22207     }
22208     case 4: // top edge
22209     {
22210       intersectValue = valueMax;
22211       intersectKey = otherKey + (key-otherKey)/(value-otherValue)*(intersectValue-otherValue);
22212       break;
22213     }
22214     case 5:
22215     {
22216       break; // case 5 shouldn't happen for this function but we add it anyway to prevent potential discontinuity in branch table
22217     }
22218     case 6: // bottom edge
22219     {
22220       intersectValue = valueMin;
22221       intersectKey = otherKey + (key-otherKey)/(value-otherValue)*(intersectValue-otherValue);
22222       break;
22223     }
22224     case 7: // top and right edge
22225     {
22226       intersectValue = valueMax;
22227       intersectKey = otherKey + (key-otherKey)/(value-otherValue)*(intersectValue-otherValue);
22228       if (intersectKey < keyMin || intersectKey > keyMax) // doesn't intersect, so must intersect other:
22229       {
22230         intersectKey = keyMax;
22231         intersectValue = otherValue + (value-otherValue)/(key-otherKey)*(intersectKey-otherKey);
22232       }
22233       break;
22234     }
22235     case 8: // right edge
22236     {
22237       intersectKey = keyMax;
22238       intersectValue = otherValue + (value-otherValue)/(key-otherKey)*(intersectKey-otherKey);
22239       break;
22240     }
22241     case 9: // bottom and right edge
22242     {
22243       intersectValue = valueMin;
22244       intersectKey = otherKey + (key-otherKey)/(value-otherValue)*(intersectValue-otherValue);
22245       if (intersectKey < keyMin || intersectKey > keyMax) // doesn't intersect, so must intersect other:
22246       {
22247         intersectKey = keyMax;
22248         intersectValue = otherValue + (value-otherValue)/(key-otherKey)*(intersectKey-otherKey);
22249       }
22250       break;
22251     }
22252   }
22253   return coordsToPixels(intersectKey, intersectValue);
22254 }
22255 
22256 /*! \internal
22257 
22258   This function is part of the curve optimization algorithm of \ref getCurveLines.
22259 
22260   In situations where a single segment skips over multiple regions it might become necessary to add
22261   extra points at the corners of region 5 (see \ref getRegion) such that the optimized segment
22262   doesn't unintentionally cut through the visible area of the axis rect and create plot artifacts.
22263   This method provides these points that must be added, assuming the original segment doesn't
22264   start, end, or traverse region 5. (Corner points where region 5 is traversed are calculated by
22265   \ref getTraverseCornerPoints.)
22266 
22267   For example, consider a segment which directly goes from region 4 to 2 but originally is far out
22268   to the top left such that it doesn't cross region 5. Naively optimizing these points by
22269   projecting them on the top and left borders of region 5 will create a segment that surely crosses
22270   5, creating a visual artifact in the plot. This method prevents this by providing extra points at
22271   the top left corner, making the optimized curve correctly pass from region 4 to 1 to 2 without
22272   traversing 5.
22273 */
getOptimizedCornerPoints(int prevRegion,int currentRegion,double prevKey,double prevValue,double key,double value,double keyMin,double valueMax,double keyMax,double valueMin) const22274 QVector<QPointF> QCPCurve::getOptimizedCornerPoints(int prevRegion, int currentRegion, double prevKey, double prevValue, double key, double value, double keyMin, double valueMax, double keyMax, double valueMin) const
22275 {
22276   QVector<QPointF> result;
22277   switch (prevRegion)
22278   {
22279     case 1:
22280     {
22281       switch (currentRegion)
22282       {
22283         case 2: { result << coordsToPixels(keyMin, valueMax); break; }
22284         case 4: { result << coordsToPixels(keyMin, valueMax); break; }
22285         case 3: { result << coordsToPixels(keyMin, valueMax) << coordsToPixels(keyMin, valueMin); break; }
22286         case 7: { result << coordsToPixels(keyMin, valueMax) << coordsToPixels(keyMax, valueMax); break; }
22287         case 6: { result << coordsToPixels(keyMin, valueMax) << coordsToPixels(keyMin, valueMin); result.append(result.last()); break; }
22288         case 8: { result << coordsToPixels(keyMin, valueMax) << coordsToPixels(keyMax, valueMax); result.append(result.last()); break; }
22289         case 9: { // in this case we need another distinction of cases: segment may pass below or above rect, requiring either bottom right or top left corner points
22290           if ((value-prevValue)/(key-prevKey)*(keyMin-key)+value < valueMin) // segment passes below R
22291           { result << coordsToPixels(keyMin, valueMax) << coordsToPixels(keyMin, valueMin); result.append(result.last()); result << coordsToPixels(keyMax, valueMin); }
22292           else
22293           { result << coordsToPixels(keyMin, valueMax) << coordsToPixels(keyMax, valueMax); result.append(result.last()); result << coordsToPixels(keyMax, valueMin); }
22294           break;
22295         }
22296       }
22297       break;
22298     }
22299     case 2:
22300     {
22301       switch (currentRegion)
22302       {
22303         case 1: { result << coordsToPixels(keyMin, valueMax); break; }
22304         case 3: { result << coordsToPixels(keyMin, valueMin); break; }
22305         case 4: { result << coordsToPixels(keyMin, valueMax); result.append(result.last()); break; }
22306         case 6: { result << coordsToPixels(keyMin, valueMin); result.append(result.last()); break; }
22307         case 7: { result << coordsToPixels(keyMin, valueMax); result.append(result.last()); result << coordsToPixels(keyMax, valueMax); break; }
22308         case 9: { result << coordsToPixels(keyMin, valueMin); result.append(result.last()); result << coordsToPixels(keyMax, valueMin); break; }
22309       }
22310       break;
22311     }
22312     case 3:
22313     {
22314       switch (currentRegion)
22315       {
22316         case 2: { result << coordsToPixels(keyMin, valueMin); break; }
22317         case 6: { result << coordsToPixels(keyMin, valueMin); break; }
22318         case 1: { result << coordsToPixels(keyMin, valueMin) << coordsToPixels(keyMin, valueMax); break; }
22319         case 9: { result << coordsToPixels(keyMin, valueMin) << coordsToPixels(keyMax, valueMin); break; }
22320         case 4: { result << coordsToPixels(keyMin, valueMin) << coordsToPixels(keyMin, valueMax); result.append(result.last()); break; }
22321         case 8: { result << coordsToPixels(keyMin, valueMin) << coordsToPixels(keyMax, valueMin); result.append(result.last()); break; }
22322         case 7: { // in this case we need another distinction of cases: segment may pass below or above rect, requiring either bottom right or top left corner points
22323           if ((value-prevValue)/(key-prevKey)*(keyMax-key)+value < valueMin) // segment passes below R
22324           { result << coordsToPixels(keyMin, valueMin) << coordsToPixels(keyMax, valueMin); result.append(result.last()); result << coordsToPixels(keyMax, valueMax); }
22325           else
22326           { result << coordsToPixels(keyMin, valueMin) << coordsToPixels(keyMin, valueMax); result.append(result.last()); result << coordsToPixels(keyMax, valueMax); }
22327           break;
22328         }
22329       }
22330       break;
22331     }
22332     case 4:
22333     {
22334       switch (currentRegion)
22335       {
22336         case 1: { result << coordsToPixels(keyMin, valueMax); break; }
22337         case 7: { result << coordsToPixels(keyMax, valueMax); break; }
22338         case 2: { result << coordsToPixels(keyMin, valueMax); result.append(result.last()); break; }
22339         case 8: { result << coordsToPixels(keyMax, valueMax); result.append(result.last()); break; }
22340         case 3: { result << coordsToPixels(keyMin, valueMax); result.append(result.last()); result << coordsToPixels(keyMin, valueMin); break; }
22341         case 9: { result << coordsToPixels(keyMax, valueMax); result.append(result.last()); result << coordsToPixels(keyMax, valueMin); break; }
22342       }
22343       break;
22344     }
22345     case 5:
22346     {
22347       switch (currentRegion)
22348       {
22349         case 1: { result << coordsToPixels(keyMin, valueMax); break; }
22350         case 7: { result << coordsToPixels(keyMax, valueMax); break; }
22351         case 9: { result << coordsToPixels(keyMax, valueMin); break; }
22352         case 3: { result << coordsToPixels(keyMin, valueMin); break; }
22353       }
22354       break;
22355     }
22356     case 6:
22357     {
22358       switch (currentRegion)
22359       {
22360         case 3: { result << coordsToPixels(keyMin, valueMin); break; }
22361         case 9: { result << coordsToPixels(keyMax, valueMin); break; }
22362         case 2: { result << coordsToPixels(keyMin, valueMin); result.append(result.last()); break; }
22363         case 8: { result << coordsToPixels(keyMax, valueMin); result.append(result.last()); break; }
22364         case 1: { result << coordsToPixels(keyMin, valueMin); result.append(result.last()); result << coordsToPixels(keyMin, valueMax); break; }
22365         case 7: { result << coordsToPixels(keyMax, valueMin); result.append(result.last()); result << coordsToPixels(keyMax, valueMax); break; }
22366       }
22367       break;
22368     }
22369     case 7:
22370     {
22371       switch (currentRegion)
22372       {
22373         case 4: { result << coordsToPixels(keyMax, valueMax); break; }
22374         case 8: { result << coordsToPixels(keyMax, valueMax); break; }
22375         case 1: { result << coordsToPixels(keyMax, valueMax) << coordsToPixels(keyMin, valueMax); break; }
22376         case 9: { result << coordsToPixels(keyMax, valueMax) << coordsToPixels(keyMax, valueMin); break; }
22377         case 2: { result << coordsToPixels(keyMax, valueMax) << coordsToPixels(keyMin, valueMax); result.append(result.last()); break; }
22378         case 6: { result << coordsToPixels(keyMax, valueMax) << coordsToPixels(keyMax, valueMin); result.append(result.last()); break; }
22379         case 3: { // in this case we need another distinction of cases: segment may pass below or above rect, requiring either bottom right or top left corner points
22380           if ((value-prevValue)/(key-prevKey)*(keyMax-key)+value < valueMin) // segment passes below R
22381           { result << coordsToPixels(keyMax, valueMax) << coordsToPixels(keyMax, valueMin); result.append(result.last()); result << coordsToPixels(keyMin, valueMin); }
22382           else
22383           { result << coordsToPixels(keyMax, valueMax) << coordsToPixels(keyMin, valueMax); result.append(result.last()); result << coordsToPixels(keyMin, valueMin); }
22384           break;
22385         }
22386       }
22387       break;
22388     }
22389     case 8:
22390     {
22391       switch (currentRegion)
22392       {
22393         case 7: { result << coordsToPixels(keyMax, valueMax); break; }
22394         case 9: { result << coordsToPixels(keyMax, valueMin); break; }
22395         case 4: { result << coordsToPixels(keyMax, valueMax); result.append(result.last()); break; }
22396         case 6: { result << coordsToPixels(keyMax, valueMin); result.append(result.last()); break; }
22397         case 1: { result << coordsToPixels(keyMax, valueMax); result.append(result.last()); result << coordsToPixels(keyMin, valueMax); break; }
22398         case 3: { result << coordsToPixels(keyMax, valueMin); result.append(result.last()); result << coordsToPixels(keyMin, valueMin); break; }
22399       }
22400       break;
22401     }
22402     case 9:
22403     {
22404       switch (currentRegion)
22405       {
22406         case 6: { result << coordsToPixels(keyMax, valueMin); break; }
22407         case 8: { result << coordsToPixels(keyMax, valueMin); break; }
22408         case 3: { result << coordsToPixels(keyMax, valueMin) << coordsToPixels(keyMin, valueMin); break; }
22409         case 7: { result << coordsToPixels(keyMax, valueMin) << coordsToPixels(keyMax, valueMax); break; }
22410         case 2: { result << coordsToPixels(keyMax, valueMin) << coordsToPixels(keyMin, valueMin); result.append(result.last()); break; }
22411         case 4: { result << coordsToPixels(keyMax, valueMin) << coordsToPixels(keyMax, valueMax); result.append(result.last()); break; }
22412         case 1: { // in this case we need another distinction of cases: segment may pass below or above rect, requiring either bottom right or top left corner points
22413           if ((value-prevValue)/(key-prevKey)*(keyMin-key)+value < valueMin) // segment passes below R
22414           { result << coordsToPixels(keyMax, valueMin) << coordsToPixels(keyMin, valueMin); result.append(result.last()); result << coordsToPixels(keyMin, valueMax); }
22415           else
22416           { result << coordsToPixels(keyMax, valueMin) << coordsToPixels(keyMax, valueMax); result.append(result.last()); result << coordsToPixels(keyMin, valueMax); }
22417           break;
22418         }
22419       }
22420       break;
22421     }
22422   }
22423   return result;
22424 }
22425 
22426 /*! \internal
22427 
22428   This function is part of the curve optimization algorithm of \ref getCurveLines.
22429 
22430   This method returns whether a segment going from \a prevRegion to \a currentRegion (see \ref
22431   getRegion) may traverse the visible region 5. This function assumes that neither \a prevRegion
22432   nor \a currentRegion is 5 itself.
22433 
22434   If this method returns false, the segment for sure doesn't pass region 5. If it returns true, the
22435   segment may or may not pass region 5 and a more fine-grained calculation must be used (\ref
22436   getTraverse).
22437 */
mayTraverse(int prevRegion,int currentRegion) const22438 bool QCPCurve::mayTraverse(int prevRegion, int currentRegion) const
22439 {
22440   switch (prevRegion)
22441   {
22442     case 1:
22443     {
22444       switch (currentRegion)
22445       {
22446         case 4:
22447         case 7:
22448         case 2:
22449         case 3: return false;
22450         default: return true;
22451       }
22452     }
22453     case 2:
22454     {
22455       switch (currentRegion)
22456       {
22457         case 1:
22458         case 3: return false;
22459         default: return true;
22460       }
22461     }
22462     case 3:
22463     {
22464       switch (currentRegion)
22465       {
22466         case 1:
22467         case 2:
22468         case 6:
22469         case 9: return false;
22470         default: return true;
22471       }
22472     }
22473     case 4:
22474     {
22475       switch (currentRegion)
22476       {
22477         case 1:
22478         case 7: return false;
22479         default: return true;
22480       }
22481     }
22482     case 5: return false; // should never occur
22483     case 6:
22484     {
22485       switch (currentRegion)
22486       {
22487         case 3:
22488         case 9: return false;
22489         default: return true;
22490       }
22491     }
22492     case 7:
22493     {
22494       switch (currentRegion)
22495       {
22496         case 1:
22497         case 4:
22498         case 8:
22499         case 9: return false;
22500         default: return true;
22501       }
22502     }
22503     case 8:
22504     {
22505       switch (currentRegion)
22506       {
22507         case 7:
22508         case 9: return false;
22509         default: return true;
22510       }
22511     }
22512     case 9:
22513     {
22514       switch (currentRegion)
22515       {
22516         case 3:
22517         case 6:
22518         case 8:
22519         case 7: return false;
22520         default: return true;
22521       }
22522     }
22523     default: return true;
22524   }
22525 }
22526 
22527 
22528 /*! \internal
22529 
22530   This function is part of the curve optimization algorithm of \ref getCurveLines.
22531 
22532   This method assumes that the \ref mayTraverse test has returned true, so there is a chance the
22533   segment defined by (\a prevKey, \a prevValue) and (\a key, \a value) goes through the visible
22534   region 5.
22535 
22536   The return value of this method indicates whether the segment actually traverses region 5 or not.
22537 
22538   If the segment traverses 5, the output parameters \a crossA and \a crossB indicate the entry and
22539   exit points of region 5. They will become the optimized points for that segment.
22540 */
getTraverse(double prevKey,double prevValue,double key,double value,double keyMin,double valueMax,double keyMax,double valueMin,QPointF & crossA,QPointF & crossB) const22541 bool QCPCurve::getTraverse(double prevKey, double prevValue, double key, double value, double keyMin, double valueMax, double keyMax, double valueMin, QPointF &crossA, QPointF &crossB) const
22542 {
22543   QList<QPointF> intersections; // x of QPointF corresponds to key and y to value
22544   if (qFuzzyIsNull(key-prevKey)) // line is parallel to value axis
22545   {
22546     // due to region filter in mayTraverseR(), if line is parallel to value or key axis, R is traversed here
22547     intersections.append(QPointF(key, valueMin)); // direction will be taken care of at end of method
22548     intersections.append(QPointF(key, valueMax));
22549   } else if (qFuzzyIsNull(value-prevValue)) // line is parallel to key axis
22550   {
22551     // due to region filter in mayTraverseR(), if line is parallel to value or key axis, R is traversed here
22552     intersections.append(QPointF(keyMin, value)); // direction will be taken care of at end of method
22553     intersections.append(QPointF(keyMax, value));
22554   } else // line is skewed
22555   {
22556     double gamma;
22557     double keyPerValue = (key-prevKey)/(value-prevValue);
22558     // check top of rect:
22559     gamma = prevKey + (valueMax-prevValue)*keyPerValue;
22560     if (gamma >= keyMin && gamma <= keyMax)
22561       intersections.append(QPointF(gamma, valueMax));
22562     // check bottom of rect:
22563     gamma = prevKey + (valueMin-prevValue)*keyPerValue;
22564     if (gamma >= keyMin && gamma <= keyMax)
22565       intersections.append(QPointF(gamma, valueMin));
22566     double valuePerKey = 1.0/keyPerValue;
22567     // check left of rect:
22568     gamma = prevValue + (keyMin-prevKey)*valuePerKey;
22569     if (gamma >= valueMin && gamma <= valueMax)
22570       intersections.append(QPointF(keyMin, gamma));
22571     // check right of rect:
22572     gamma = prevValue + (keyMax-prevKey)*valuePerKey;
22573     if (gamma >= valueMin && gamma <= valueMax)
22574       intersections.append(QPointF(keyMax, gamma));
22575   }
22576 
22577   // handle cases where found points isn't exactly 2:
22578   if (intersections.size() > 2)
22579   {
22580     // line probably goes through corner of rect, and we got duplicate points there. single out the point pair with greatest distance in between:
22581     double distSqrMax = 0;
22582     QPointF pv1, pv2;
22583     for (int i=0; i<intersections.size()-1; ++i)
22584     {
22585       for (int k=i+1; k<intersections.size(); ++k)
22586       {
22587         QPointF distPoint = intersections.at(i)-intersections.at(k);
22588         double distSqr = distPoint.x()*distPoint.x()+distPoint.y()+distPoint.y();
22589         if (distSqr > distSqrMax)
22590         {
22591           pv1 = intersections.at(i);
22592           pv2 = intersections.at(k);
22593           distSqrMax = distSqr;
22594         }
22595       }
22596     }
22597     intersections = QList<QPointF>() << pv1 << pv2;
22598   } else if (intersections.size() != 2)
22599   {
22600     // one or even zero points found (shouldn't happen unless line perfectly tangent to corner), no need to draw segment
22601     return false;
22602   }
22603 
22604   // possibly re-sort points so optimized point segment has same direction as original segment:
22605   if ((key-prevKey)*(intersections.at(1).x()-intersections.at(0).x()) + (value-prevValue)*(intersections.at(1).y()-intersections.at(0).y()) < 0) // scalar product of both segments < 0 -> opposite direction
22606     intersections.move(0, 1);
22607   crossA = coordsToPixels(intersections.at(0).x(), intersections.at(0).y());
22608   crossB = coordsToPixels(intersections.at(1).x(), intersections.at(1).y());
22609   return true;
22610 }
22611 
22612 /*! \internal
22613 
22614   This function is part of the curve optimization algorithm of \ref getCurveLines.
22615 
22616   This method assumes that the \ref getTraverse test has returned true, so the segment definitely
22617   traverses the visible region 5 when going from \a prevRegion to \a currentRegion.
22618 
22619   In certain situations it is not sufficient to merely generate the entry and exit points of the
22620   segment into/out of region 5, as \ref getTraverse provides. It may happen that a single segment, in
22621   addition to traversing region 5, skips another region outside of region 5, which makes it
22622   necessary to add an optimized corner point there (very similar to the job \ref
22623   getOptimizedCornerPoints does for segments that are completely in outside regions and don't
22624   traverse 5).
22625 
22626   As an example, consider a segment going from region 1 to region 6, traversing the lower left
22627   corner of region 5. In this configuration, the segment additionally crosses the border between
22628   region 1 and 2 before entering region 5. This makes it necessary to add an additional point in
22629   the top left corner, before adding the optimized traverse points. So in this case, the output
22630   parameter \a beforeTraverse will contain the top left corner point, and \a afterTraverse will be
22631   empty.
22632 
22633   In some cases, such as when going from region 1 to 9, it may even be necessary to add additional
22634   corner points before and after the traverse. Then both \a beforeTraverse and \a afterTraverse
22635   return the respective corner points.
22636 */
getTraverseCornerPoints(int prevRegion,int currentRegion,double keyMin,double valueMax,double keyMax,double valueMin,QVector<QPointF> & beforeTraverse,QVector<QPointF> & afterTraverse) const22637 void QCPCurve::getTraverseCornerPoints(int prevRegion, int currentRegion, double keyMin, double valueMax, double keyMax, double valueMin, QVector<QPointF> &beforeTraverse, QVector<QPointF> &afterTraverse) const
22638 {
22639   switch (prevRegion)
22640   {
22641     case 1:
22642     {
22643       switch (currentRegion)
22644       {
22645         case 6: { beforeTraverse << coordsToPixels(keyMin, valueMax); break; }
22646         case 9: { beforeTraverse << coordsToPixels(keyMin, valueMax); afterTraverse << coordsToPixels(keyMax, valueMin); break; }
22647         case 8: { beforeTraverse << coordsToPixels(keyMin, valueMax); break; }
22648       }
22649       break;
22650     }
22651     case 2:
22652     {
22653       switch (currentRegion)
22654       {
22655         case 7: { afterTraverse << coordsToPixels(keyMax, valueMax); break; }
22656         case 9: { afterTraverse << coordsToPixels(keyMax, valueMin); break; }
22657       }
22658       break;
22659     }
22660     case 3:
22661     {
22662       switch (currentRegion)
22663       {
22664         case 4: { beforeTraverse << coordsToPixels(keyMin, valueMin); break; }
22665         case 7: { beforeTraverse << coordsToPixels(keyMin, valueMin); afterTraverse << coordsToPixels(keyMax, valueMax); break; }
22666         case 8: { beforeTraverse << coordsToPixels(keyMin, valueMin); break; }
22667       }
22668       break;
22669     }
22670     case 4:
22671     {
22672       switch (currentRegion)
22673       {
22674         case 3: { afterTraverse << coordsToPixels(keyMin, valueMin); break; }
22675         case 9: { afterTraverse << coordsToPixels(keyMax, valueMin); break; }
22676       }
22677       break;
22678     }
22679     case 5: { break; } // shouldn't happen because this method only handles full traverses
22680     case 6:
22681     {
22682       switch (currentRegion)
22683       {
22684         case 1: { afterTraverse << coordsToPixels(keyMin, valueMax); break; }
22685         case 7: { afterTraverse << coordsToPixels(keyMax, valueMax); break; }
22686       }
22687       break;
22688     }
22689     case 7:
22690     {
22691       switch (currentRegion)
22692       {
22693         case 2: { beforeTraverse << coordsToPixels(keyMax, valueMax); break; }
22694         case 3: { beforeTraverse << coordsToPixels(keyMax, valueMax); afterTraverse << coordsToPixels(keyMin, valueMin); break; }
22695         case 6: { beforeTraverse << coordsToPixels(keyMax, valueMax); break; }
22696       }
22697       break;
22698     }
22699     case 8:
22700     {
22701       switch (currentRegion)
22702       {
22703         case 1: { afterTraverse << coordsToPixels(keyMin, valueMax); break; }
22704         case 3: { afterTraverse << coordsToPixels(keyMin, valueMin); break; }
22705       }
22706       break;
22707     }
22708     case 9:
22709     {
22710       switch (currentRegion)
22711       {
22712         case 2: { beforeTraverse << coordsToPixels(keyMax, valueMin); break; }
22713         case 1: { beforeTraverse << coordsToPixels(keyMax, valueMin); afterTraverse << coordsToPixels(keyMin, valueMax); break; }
22714         case 4: { beforeTraverse << coordsToPixels(keyMax, valueMin); break; }
22715       }
22716       break;
22717     }
22718   }
22719 }
22720 
22721 /*! \internal
22722 
22723   Calculates the (minimum) distance (in pixels) the curve's representation has from the given \a
22724   pixelPoint in pixels. This is used to determine whether the curve was clicked or not, e.g. in
22725   \ref selectTest. The closest data point to \a pixelPoint is returned in \a closestData. Note that
22726   if the curve has a line representation, the returned distance may be smaller than the distance to
22727   the \a closestData point, since the distance to the curve line is also taken into account.
22728 
22729   If either the curve has no data or if the line style is \ref lsNone and the scatter style's shape
22730   is \ref QCPScatterStyle::ssNone (i.e. there is no visual representation of the curve), returns
22731   -1.0.
22732 */
pointDistance(const QPointF & pixelPoint,QCPCurveDataContainer::const_iterator & closestData) const22733 double QCPCurve::pointDistance(const QPointF &pixelPoint, QCPCurveDataContainer::const_iterator &closestData) const
22734 {
22735   closestData = mDataContainer->constEnd();
22736   if (mDataContainer->isEmpty())
22737     return -1.0;
22738   if (mLineStyle == lsNone && mScatterStyle.isNone())
22739     return -1.0;
22740 
22741   if (mDataContainer->size() == 1)
22742   {
22743     QPointF dataPoint = coordsToPixels(mDataContainer->constBegin()->key, mDataContainer->constBegin()->value);
22744     closestData = mDataContainer->constBegin();
22745     return QCPVector2D(dataPoint-pixelPoint).length();
22746   }
22747 
22748   // calculate minimum distances to curve data points and find closestData iterator:
22749   double minDistSqr = std::numeric_limits<double>::max();
22750   // iterate over found data points and then choose the one with the shortest distance to pos:
22751   QCPCurveDataContainer::const_iterator begin = mDataContainer->constBegin();
22752   QCPCurveDataContainer::const_iterator end = mDataContainer->constEnd();
22753   for (QCPCurveDataContainer::const_iterator it=begin; it!=end; ++it)
22754   {
22755     const double currentDistSqr = QCPVector2D(coordsToPixels(it->key, it->value)-pixelPoint).lengthSquared();
22756     if (currentDistSqr < minDistSqr)
22757     {
22758       minDistSqr = currentDistSqr;
22759       closestData = it;
22760     }
22761   }
22762 
22763   // calculate distance to line if there is one (if so, will probably be smaller than distance to closest data point):
22764   if (mLineStyle != lsNone)
22765   {
22766     QVector<QPointF> lines;
22767     getCurveLines(&lines, QCPDataRange(0, dataCount()), mParentPlot->selectionTolerance()*1.2); // optimized lines outside axis rect shouldn't respond to clicks at the edge, so use 1.2*tolerance as pen width
22768     for (int i=0; i<lines.size()-1; ++i)
22769     {
22770       double currentDistSqr = QCPVector2D(pixelPoint).distanceSquaredToLine(lines.at(i), lines.at(i+1));
22771       if (currentDistSqr < minDistSqr)
22772         minDistSqr = currentDistSqr;
22773     }
22774   }
22775 
22776   return qSqrt(minDistSqr);
22777 }
22778 /* end of 'src/plottables/plottable-curve.cpp' */
22779 
22780 
22781 /* including file 'src/plottables/plottable-bars.cpp', size 43512            */
22782 /* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
22783 
22784 
22785 ////////////////////////////////////////////////////////////////////////////////////////////////////
22786 //////////////////// QCPBarsGroup
22787 ////////////////////////////////////////////////////////////////////////////////////////////////////
22788 
22789 /*! \class QCPBarsGroup
22790   \brief Groups multiple QCPBars together so they appear side by side
22791 
22792   \image html QCPBarsGroup.png
22793 
22794   When showing multiple QCPBars in one plot which have bars at identical keys, it may be desirable
22795   to have them appearing next to each other at each key. This is what adding the respective QCPBars
22796   plottables to a QCPBarsGroup achieves. (An alternative approach is to stack them on top of each
22797   other, see \ref QCPBars::moveAbove.)
22798 
22799   \section qcpbarsgroup-usage Usage
22800 
22801   To add a QCPBars plottable to the group, create a new group and then add the respective bars
22802   intances:
22803   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpbarsgroup-creation
22804   Alternatively to appending to the group like shown above, you can also set the group on the
22805   QCPBars plottable via \ref QCPBars::setBarsGroup.
22806 
22807   The spacing between the bars can be configured via \ref setSpacingType and \ref setSpacing. The
22808   bars in this group appear in the plot in the order they were appended. To insert a bars plottable
22809   at a certain index position, or to reposition a bars plottable which is already in the group, use
22810   \ref insert.
22811 
22812   To remove specific bars from the group, use either \ref remove or call \ref
22813   QCPBars::setBarsGroup "QCPBars::setBarsGroup(0)" on the respective bars plottable.
22814 
22815   To clear the entire group, call \ref clear, or simply delete the group.
22816 
22817   \section qcpbarsgroup-example Example
22818 
22819   The image above is generated with the following code:
22820   \snippet documentation/doc-image-generator/mainwindow.cpp qcpbarsgroup-example
22821 */
22822 
22823 /* start of documentation of inline functions */
22824 
22825 /*! \fn QList<QCPBars*> QCPBarsGroup::bars() const
22826 
22827   Returns all bars currently in this group.
22828 
22829   \see bars(int index)
22830 */
22831 
22832 /*! \fn int QCPBarsGroup::size() const
22833 
22834   Returns the number of QCPBars plottables that are part of this group.
22835 
22836 */
22837 
22838 /*! \fn bool QCPBarsGroup::isEmpty() const
22839 
22840   Returns whether this bars group is empty.
22841 
22842   \see size
22843 */
22844 
22845 /*! \fn bool QCPBarsGroup::contains(QCPBars *bars)
22846 
22847   Returns whether the specified \a bars plottable is part of this group.
22848 
22849 */
22850 
22851 /* end of documentation of inline functions */
22852 
22853 /*!
22854   Constructs a new bars group for the specified QCustomPlot instance.
22855 */
QCPBarsGroup(QCustomPlot * parentPlot)22856 QCPBarsGroup::QCPBarsGroup(QCustomPlot *parentPlot) :
22857   QObject(parentPlot),
22858   mParentPlot(parentPlot),
22859   mSpacingType(stAbsolute),
22860   mSpacing(4)
22861 {
22862 }
22863 
~QCPBarsGroup()22864 QCPBarsGroup::~QCPBarsGroup()
22865 {
22866   clear();
22867 }
22868 
22869 /*!
22870   Sets how the spacing between adjacent bars is interpreted. See \ref SpacingType.
22871 
22872   The actual spacing can then be specified with \ref setSpacing.
22873 
22874   \see setSpacing
22875 */
setSpacingType(SpacingType spacingType)22876 void QCPBarsGroup::setSpacingType(SpacingType spacingType)
22877 {
22878   mSpacingType = spacingType;
22879 }
22880 
22881 /*!
22882   Sets the spacing between adjacent bars. What the number passed as \a spacing actually means, is
22883   defined by the current \ref SpacingType, which can be set with \ref setSpacingType.
22884 
22885   \see setSpacingType
22886 */
setSpacing(double spacing)22887 void QCPBarsGroup::setSpacing(double spacing)
22888 {
22889   mSpacing = spacing;
22890 }
22891 
22892 /*!
22893   Returns the QCPBars instance with the specified \a index in this group. If no such QCPBars
22894   exists, returns 0.
22895 
22896   \see bars(), size
22897 */
bars(int index) const22898 QCPBars *QCPBarsGroup::bars(int index) const
22899 {
22900   if (index >= 0 && index < mBars.size())
22901   {
22902     return mBars.at(index);
22903   } else
22904   {
22905     qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
22906     return 0;
22907   }
22908 }
22909 
22910 /*!
22911   Removes all QCPBars plottables from this group.
22912 
22913   \see isEmpty
22914 */
clear()22915 void QCPBarsGroup::clear()
22916 {
22917   foreach (QCPBars *bars, mBars) // since foreach takes a copy, removing bars in the loop is okay
22918     bars->setBarsGroup(0); // removes itself via removeBars
22919 }
22920 
22921 /*!
22922   Adds the specified \a bars plottable to this group. Alternatively, you can also use \ref
22923   QCPBars::setBarsGroup on the \a bars instance.
22924 
22925   \see insert, remove
22926 */
append(QCPBars * bars)22927 void QCPBarsGroup::append(QCPBars *bars)
22928 {
22929   if (!bars)
22930   {
22931     qDebug() << Q_FUNC_INFO << "bars is 0";
22932     return;
22933   }
22934 
22935   if (!mBars.contains(bars))
22936     bars->setBarsGroup(this);
22937   else
22938     qDebug() << Q_FUNC_INFO << "bars plottable is already in this bars group:" << reinterpret_cast<quintptr>(bars);
22939 }
22940 
22941 /*!
22942   Inserts the specified \a bars plottable into this group at the specified index position \a i.
22943   This gives you full control over the ordering of the bars.
22944 
22945   \a bars may already be part of this group. In that case, \a bars is just moved to the new index
22946   position.
22947 
22948   \see append, remove
22949 */
insert(int i,QCPBars * bars)22950 void QCPBarsGroup::insert(int i, QCPBars *bars)
22951 {
22952   if (!bars)
22953   {
22954     qDebug() << Q_FUNC_INFO << "bars is 0";
22955     return;
22956   }
22957 
22958   // first append to bars list normally:
22959   if (!mBars.contains(bars))
22960     bars->setBarsGroup(this);
22961   // then move to according position:
22962   mBars.move(mBars.indexOf(bars), qBound(0, i, mBars.size()-1));
22963 }
22964 
22965 /*!
22966   Removes the specified \a bars plottable from this group.
22967 
22968   \see contains, clear
22969 */
remove(QCPBars * bars)22970 void QCPBarsGroup::remove(QCPBars *bars)
22971 {
22972   if (!bars)
22973   {
22974     qDebug() << Q_FUNC_INFO << "bars is 0";
22975     return;
22976   }
22977 
22978   if (mBars.contains(bars))
22979     bars->setBarsGroup(0);
22980   else
22981     qDebug() << Q_FUNC_INFO << "bars plottable is not in this bars group:" << reinterpret_cast<quintptr>(bars);
22982 }
22983 
22984 /*! \internal
22985 
22986   Adds the specified \a bars to the internal mBars list of bars. This method does not change the
22987   barsGroup property on \a bars.
22988 
22989   \see unregisterBars
22990 */
registerBars(QCPBars * bars)22991 void QCPBarsGroup::registerBars(QCPBars *bars)
22992 {
22993   if (!mBars.contains(bars))
22994     mBars.append(bars);
22995 }
22996 
22997 /*! \internal
22998 
22999   Removes the specified \a bars from the internal mBars list of bars. This method does not change
23000   the barsGroup property on \a bars.
23001 
23002   \see registerBars
23003 */
unregisterBars(QCPBars * bars)23004 void QCPBarsGroup::unregisterBars(QCPBars *bars)
23005 {
23006   mBars.removeOne(bars);
23007 }
23008 
23009 /*! \internal
23010 
23011   Returns the pixel offset in the key dimension the specified \a bars plottable should have at the
23012   given key coordinate \a keyCoord. The offset is relative to the pixel position of the key
23013   coordinate \a keyCoord.
23014 */
keyPixelOffset(const QCPBars * bars,double keyCoord)23015 double QCPBarsGroup::keyPixelOffset(const QCPBars *bars, double keyCoord)
23016 {
23017   // find list of all base bars in case some mBars are stacked:
23018   QList<const QCPBars*> baseBars;
23019   foreach (const QCPBars *b, mBars)
23020   {
23021     while (b->barBelow())
23022       b = b->barBelow();
23023     if (!baseBars.contains(b))
23024       baseBars.append(b);
23025   }
23026   // find base bar this "bars" is stacked on:
23027   const QCPBars *thisBase = bars;
23028   while (thisBase->barBelow())
23029     thisBase = thisBase->barBelow();
23030 
23031   // determine key pixel offset of this base bars considering all other base bars in this barsgroup:
23032   double result = 0;
23033   int index = baseBars.indexOf(thisBase);
23034   if (index >= 0)
23035   {
23036     if (baseBars.size() % 2 == 1 && index == (baseBars.size()-1)/2) // is center bar (int division on purpose)
23037     {
23038       return result;
23039     } else
23040     {
23041       double lowerPixelWidth, upperPixelWidth;
23042       int startIndex;
23043       int dir = (index <= (baseBars.size()-1)/2) ? -1 : 1; // if bar is to lower keys of center, dir is negative
23044       if (baseBars.size() % 2 == 0) // even number of bars
23045       {
23046         startIndex = baseBars.size()/2 + (dir < 0 ? -1 : 0);
23047         result += getPixelSpacing(baseBars.at(startIndex), keyCoord)*0.5; // half of middle spacing
23048       } else // uneven number of bars
23049       {
23050         startIndex = (baseBars.size()-1)/2+dir;
23051         baseBars.at((baseBars.size()-1)/2)->getPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth);
23052         result += qAbs(upperPixelWidth-lowerPixelWidth)*0.5; // half of center bar
23053         result += getPixelSpacing(baseBars.at((baseBars.size()-1)/2), keyCoord); // center bar spacing
23054       }
23055       for (int i = startIndex; i != index; i += dir) // add widths and spacings of bars in between center and our bars
23056       {
23057         baseBars.at(i)->getPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth);
23058         result += qAbs(upperPixelWidth-lowerPixelWidth);
23059         result += getPixelSpacing(baseBars.at(i), keyCoord);
23060       }
23061       // finally half of our bars width:
23062       baseBars.at(index)->getPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth);
23063       result += qAbs(upperPixelWidth-lowerPixelWidth)*0.5;
23064       // correct sign of result depending on orientation and direction of key axis:
23065       result *= dir*thisBase->keyAxis()->pixelOrientation();
23066     }
23067   }
23068   return result;
23069 }
23070 
23071 /*! \internal
23072 
23073   Returns the spacing in pixels which is between this \a bars and the following one, both at the
23074   key coordinate \a keyCoord.
23075 
23076   \note Typically the returned value doesn't depend on \a bars or \a keyCoord. \a bars is only
23077   needed to get access to the key axis transformation and axis rect for the modes \ref
23078   stAxisRectRatio and \ref stPlotCoords. The \a keyCoord is only relevant for spacings given in
23079   \ref stPlotCoords on a logarithmic axis.
23080 */
getPixelSpacing(const QCPBars * bars,double keyCoord)23081 double QCPBarsGroup::getPixelSpacing(const QCPBars *bars, double keyCoord)
23082 {
23083   switch (mSpacingType)
23084   {
23085     case stAbsolute:
23086     {
23087       return mSpacing;
23088     }
23089     case stAxisRectRatio:
23090     {
23091       if (bars->keyAxis()->orientation() == Qt::Horizontal)
23092         return bars->keyAxis()->axisRect()->width()*mSpacing;
23093       else
23094         return bars->keyAxis()->axisRect()->height()*mSpacing;
23095     }
23096     case stPlotCoords:
23097     {
23098       double keyPixel = bars->keyAxis()->coordToPixel(keyCoord);
23099       return qAbs(bars->keyAxis()->coordToPixel(keyCoord+mSpacing)-keyPixel);
23100     }
23101   }
23102   return 0;
23103 }
23104 
23105 
23106 ////////////////////////////////////////////////////////////////////////////////////////////////////
23107 //////////////////// QCPBarsData
23108 ////////////////////////////////////////////////////////////////////////////////////////////////////
23109 
23110 /*! \class QCPBarsData
23111   \brief Holds the data of one single data point (one bar) for QCPBars.
23112 
23113   The stored data is:
23114   \li \a key: coordinate on the key axis of this bar (this is the \a mainKey and the \a sortKey)
23115   \li \a value: height coordinate on the value axis of this bar (this is the \a mainValue)
23116 
23117   The container for storing multiple data points is \ref QCPBarsDataContainer. It is a typedef for
23118   \ref QCPDataContainer with \ref QCPBarsData as the DataType template parameter. See the
23119   documentation there for an explanation regarding the data type's generic methods.
23120 
23121   \see QCPBarsDataContainer
23122 */
23123 
23124 /* start documentation of inline functions */
23125 
23126 /*! \fn double QCPBarsData::sortKey() const
23127 
23128   Returns the \a key member of this data point.
23129 
23130   For a general explanation of what this method is good for in the context of the data container,
23131   see the documentation of \ref QCPDataContainer.
23132 */
23133 
23134 /*! \fn static QCPBarsData QCPBarsData::fromSortKey(double sortKey)
23135 
23136   Returns a data point with the specified \a sortKey. All other members are set to zero.
23137 
23138   For a general explanation of what this method is good for in the context of the data container,
23139   see the documentation of \ref QCPDataContainer.
23140 */
23141 
23142 /*! \fn static static bool QCPBarsData::sortKeyIsMainKey()
23143 
23144   Since the member \a key is both the data point key coordinate and the data ordering parameter,
23145   this method returns true.
23146 
23147   For a general explanation of what this method is good for in the context of the data container,
23148   see the documentation of \ref QCPDataContainer.
23149 */
23150 
23151 /*! \fn double QCPBarsData::mainKey() const
23152 
23153   Returns the \a key member of this data point.
23154 
23155   For a general explanation of what this method is good for in the context of the data container,
23156   see the documentation of \ref QCPDataContainer.
23157 */
23158 
23159 /*! \fn double QCPBarsData::mainValue() const
23160 
23161   Returns the \a value member of this data point.
23162 
23163   For a general explanation of what this method is good for in the context of the data container,
23164   see the documentation of \ref QCPDataContainer.
23165 */
23166 
23167 /*! \fn QCPRange QCPBarsData::valueRange() const
23168 
23169   Returns a QCPRange with both lower and upper boundary set to \a value of this data point.
23170 
23171   For a general explanation of what this method is good for in the context of the data container,
23172   see the documentation of \ref QCPDataContainer.
23173 */
23174 
23175 /* end documentation of inline functions */
23176 
23177 /*!
23178   Constructs a bar data point with key and value set to zero.
23179 */
QCPBarsData()23180 QCPBarsData::QCPBarsData() :
23181   key(0),
23182   value(0)
23183 {
23184 }
23185 
23186 /*!
23187   Constructs a bar data point with the specified \a key and \a value.
23188 */
QCPBarsData(double key,double value)23189 QCPBarsData::QCPBarsData(double key, double value) :
23190   key(key),
23191   value(value)
23192 {
23193 }
23194 
23195 
23196 ////////////////////////////////////////////////////////////////////////////////////////////////////
23197 //////////////////// QCPBars
23198 ////////////////////////////////////////////////////////////////////////////////////////////////////
23199 
23200 /*! \class QCPBars
23201   \brief A plottable representing a bar chart in a plot.
23202 
23203   \image html QCPBars.png
23204 
23205   To plot data, assign it with the \ref setData or \ref addData functions.
23206 
23207   \section qcpbars-appearance Changing the appearance
23208 
23209   The appearance of the bars is determined by the pen and the brush (\ref setPen, \ref setBrush).
23210   The width of the individual bars can be controlled with \ref setWidthType and \ref setWidth.
23211 
23212   Bar charts are stackable. This means, two QCPBars plottables can be placed on top of each other
23213   (see \ref QCPBars::moveAbove). So when two bars are at the same key position, they will appear
23214   stacked.
23215 
23216   If you would like to group multiple QCPBars plottables together so they appear side by side as
23217   shown below, use QCPBarsGroup.
23218 
23219   \image html QCPBarsGroup.png
23220 
23221   \section qcpbars-usage Usage
23222 
23223   Like all data representing objects in QCustomPlot, the QCPBars is a plottable
23224   (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies
23225   (QCustomPlot::plottable, QCustomPlot::removePlottable, etc.)
23226 
23227   Usually, you first create an instance:
23228   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpbars-creation-1
23229   which registers it with the QCustomPlot instance of the passed axes. Note that this QCustomPlot instance takes
23230   ownership of the plottable, so do not delete it manually but use QCustomPlot::removePlottable() instead.
23231   The newly created plottable can be modified, e.g.:
23232   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpbars-creation-2
23233 */
23234 
23235 /* start of documentation of inline functions */
23236 
23237 /*! \fn QSharedPointer<QCPBarsDataContainer> QCPBars::data() const
23238 
23239   Returns a shared pointer to the internal data storage of type \ref QCPBarsDataContainer. You may
23240   use it to directly manipulate the data, which may be more convenient and faster than using the
23241   regular \ref setData or \ref addData methods.
23242 */
23243 
23244 /*! \fn QCPBars *QCPBars::barBelow() const
23245   Returns the bars plottable that is directly below this bars plottable.
23246   If there is no such plottable, returns 0.
23247 
23248   \see barAbove, moveBelow, moveAbove
23249 */
23250 
23251 /*! \fn QCPBars *QCPBars::barAbove() const
23252   Returns the bars plottable that is directly above this bars plottable.
23253   If there is no such plottable, returns 0.
23254 
23255   \see barBelow, moveBelow, moveAbove
23256 */
23257 
23258 /* end of documentation of inline functions */
23259 
23260 /*!
23261   Constructs a bar chart which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value
23262   axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have
23263   the same orientation. If either of these restrictions is violated, a corresponding message is
23264   printed to the debug output (qDebug), the construction is not aborted, though.
23265 
23266   The created QCPBars is automatically registered with the QCustomPlot instance inferred from \a
23267   keyAxis. This QCustomPlot instance takes ownership of the QCPBars, so do not delete it manually
23268   but use QCustomPlot::removePlottable() instead.
23269 */
QCPBars(QCPAxis * keyAxis,QCPAxis * valueAxis)23270 QCPBars::QCPBars(QCPAxis *keyAxis, QCPAxis *valueAxis) :
23271   QCPAbstractPlottable1D<QCPBarsData>(keyAxis, valueAxis),
23272   mWidth(0.75),
23273   mWidthType(wtPlotCoords),
23274   mBarsGroup(0),
23275   mBaseValue(0),
23276   mStackingGap(0)
23277 {
23278   // modify inherited properties from abstract plottable:
23279   mPen.setColor(Qt::blue);
23280   mPen.setStyle(Qt::SolidLine);
23281   mBrush.setColor(QColor(40, 50, 255, 30));
23282   mBrush.setStyle(Qt::SolidPattern);
23283   mSelectionDecorator->setBrush(QBrush(QColor(160, 160, 255)));
23284 }
23285 
~QCPBars()23286 QCPBars::~QCPBars()
23287 {
23288   setBarsGroup(0);
23289   if (mBarBelow || mBarAbove)
23290     connectBars(mBarBelow.data(), mBarAbove.data()); // take this bar out of any stacking
23291 }
23292 
23293 /*! \overload
23294 
23295   Replaces the current data container with the provided \a data container.
23296 
23297   Since a QSharedPointer is used, multiple QCPBars may share the same data container safely.
23298   Modifying the data in the container will then affect all bars that share the container. Sharing
23299   can be achieved by simply exchanging the data containers wrapped in shared pointers:
23300   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpbars-datasharing-1
23301 
23302   If you do not wish to share containers, but create a copy from an existing container, rather use
23303   the \ref QCPDataContainer<DataType>::set method on the bar's data container directly:
23304   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpbars-datasharing-2
23305 
23306   \see addData
23307 */
setData(QSharedPointer<QCPBarsDataContainer> data)23308 void QCPBars::setData(QSharedPointer<QCPBarsDataContainer> data)
23309 {
23310   mDataContainer = data;
23311 }
23312 
23313 /*! \overload
23314 
23315   Replaces the current data with the provided points in \a keys and \a values. The provided
23316   vectors should have equal length. Else, the number of added points will be the size of the
23317   smallest vector.
23318 
23319   If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
23320   can set \a alreadySorted to true, to improve performance by saving a sorting run.
23321 
23322   \see addData
23323 */
setData(const QVector<double> & keys,const QVector<double> & values,bool alreadySorted)23324 void QCPBars::setData(const QVector<double> &keys, const QVector<double> &values, bool alreadySorted)
23325 {
23326   mDataContainer->clear();
23327   addData(keys, values, alreadySorted);
23328 }
23329 
23330 /*!
23331   Sets the width of the bars.
23332 
23333   How the number passed as \a width is interpreted (e.g. screen pixels, plot coordinates,...),
23334   depends on the currently set width type, see \ref setWidthType and \ref WidthType.
23335 */
setWidth(double width)23336 void QCPBars::setWidth(double width)
23337 {
23338   mWidth = width;
23339 }
23340 
23341 /*!
23342   Sets how the width of the bars is defined. See the documentation of \ref WidthType for an
23343   explanation of the possible values for \a widthType.
23344 
23345   The default value is \ref wtPlotCoords.
23346 
23347   \see setWidth
23348 */
setWidthType(QCPBars::WidthType widthType)23349 void QCPBars::setWidthType(QCPBars::WidthType widthType)
23350 {
23351   mWidthType = widthType;
23352 }
23353 
23354 /*!
23355   Sets to which QCPBarsGroup this QCPBars instance belongs to. Alternatively, you can also use \ref
23356   QCPBarsGroup::append.
23357 
23358   To remove this QCPBars from any group, set \a barsGroup to 0.
23359 */
setBarsGroup(QCPBarsGroup * barsGroup)23360 void QCPBars::setBarsGroup(QCPBarsGroup *barsGroup)
23361 {
23362   // deregister at old group:
23363   if (mBarsGroup)
23364     mBarsGroup->unregisterBars(this);
23365   mBarsGroup = barsGroup;
23366   // register at new group:
23367   if (mBarsGroup)
23368     mBarsGroup->registerBars(this);
23369 }
23370 
23371 /*!
23372   Sets the base value of this bars plottable.
23373 
23374   The base value defines where on the value coordinate the bars start. How far the bars extend from
23375   the base value is given by their individual value data. For example, if the base value is set to
23376   1, a bar with data value 2 will have its lowest point at value coordinate 1 and highest point at
23377   3.
23378 
23379   For stacked bars, only the base value of the bottom-most QCPBars has meaning.
23380 
23381   The default base value is 0.
23382 */
setBaseValue(double baseValue)23383 void QCPBars::setBaseValue(double baseValue)
23384 {
23385   mBaseValue = baseValue;
23386 }
23387 
23388 /*!
23389   If this bars plottable is stacked on top of another bars plottable (\ref moveAbove), this method
23390   allows specifying a distance in \a pixels, by which the drawn bar rectangles will be separated by
23391   the bars below it.
23392 */
setStackingGap(double pixels)23393 void QCPBars::setStackingGap(double pixels)
23394 {
23395   mStackingGap = pixels;
23396 }
23397 
23398 /*! \overload
23399 
23400   Adds the provided points in \a keys and \a values to the current data. The provided vectors
23401   should have equal length. Else, the number of added points will be the size of the smallest
23402   vector.
23403 
23404   If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
23405   can set \a alreadySorted to true, to improve performance by saving a sorting run.
23406 
23407   Alternatively, you can also access and modify the data directly via the \ref data method, which
23408   returns a pointer to the internal data container.
23409 */
addData(const QVector<double> & keys,const QVector<double> & values,bool alreadySorted)23410 void QCPBars::addData(const QVector<double> &keys, const QVector<double> &values, bool alreadySorted)
23411 {
23412   if (keys.size() != values.size())
23413     qDebug() << Q_FUNC_INFO << "keys and values have different sizes:" << keys.size() << values.size();
23414   const int n = qMin(keys.size(), values.size());
23415   QVector<QCPBarsData> tempData(n);
23416   QVector<QCPBarsData>::iterator it = tempData.begin();
23417   const QVector<QCPBarsData>::iterator itEnd = tempData.end();
23418   int i = 0;
23419   while (it != itEnd)
23420   {
23421     it->key = keys[i];
23422     it->value = values[i];
23423     ++it;
23424     ++i;
23425   }
23426   mDataContainer->add(tempData, alreadySorted); // don't modify tempData beyond this to prevent copy on write
23427 }
23428 
23429 /*! \overload
23430   Adds the provided data point as \a key and \a value to the current data.
23431 
23432   Alternatively, you can also access and modify the data directly via the \ref data method, which
23433   returns a pointer to the internal data container.
23434 */
addData(double key,double value)23435 void QCPBars::addData(double key, double value)
23436 {
23437   mDataContainer->add(QCPBarsData(key, value));
23438 }
23439 
23440 /*!
23441   Moves this bars plottable below \a bars. In other words, the bars of this plottable will appear
23442   below the bars of \a bars. The move target \a bars must use the same key and value axis as this
23443   plottable.
23444 
23445   Inserting into and removing from existing bar stacking is handled gracefully. If \a bars already
23446   has a bars object below itself, this bars object is inserted between the two. If this bars object
23447   is already between two other bars, the two other bars will be stacked on top of each other after
23448   the operation.
23449 
23450   To remove this bars plottable from any stacking, set \a bars to 0.
23451 
23452   \see moveBelow, barAbove, barBelow
23453 */
moveBelow(QCPBars * bars)23454 void QCPBars::moveBelow(QCPBars *bars)
23455 {
23456   if (bars == this) return;
23457   if (bars && (bars->keyAxis() != mKeyAxis.data() || bars->valueAxis() != mValueAxis.data()))
23458   {
23459     qDebug() << Q_FUNC_INFO << "passed QCPBars* doesn't have same key and value axis as this QCPBars";
23460     return;
23461   }
23462   // remove from stacking:
23463   connectBars(mBarBelow.data(), mBarAbove.data()); // Note: also works if one (or both) of them is 0
23464   // if new bar given, insert this bar below it:
23465   if (bars)
23466   {
23467     if (bars->mBarBelow)
23468       connectBars(bars->mBarBelow.data(), this);
23469     connectBars(this, bars);
23470   }
23471 }
23472 
23473 /*!
23474   Moves this bars plottable above \a bars. In other words, the bars of this plottable will appear
23475   above the bars of \a bars. The move target \a bars must use the same key and value axis as this
23476   plottable.
23477 
23478   Inserting into and removing from existing bar stacking is handled gracefully. If \a bars already
23479   has a bars object above itself, this bars object is inserted between the two. If this bars object
23480   is already between two other bars, the two other bars will be stacked on top of each other after
23481   the operation.
23482 
23483   To remove this bars plottable from any stacking, set \a bars to 0.
23484 
23485   \see moveBelow, barBelow, barAbove
23486 */
moveAbove(QCPBars * bars)23487 void QCPBars::moveAbove(QCPBars *bars)
23488 {
23489   if (bars == this) return;
23490   if (bars && (bars->keyAxis() != mKeyAxis.data() || bars->valueAxis() != mValueAxis.data()))
23491   {
23492     qDebug() << Q_FUNC_INFO << "passed QCPBars* doesn't have same key and value axis as this QCPBars";
23493     return;
23494   }
23495   // remove from stacking:
23496   connectBars(mBarBelow.data(), mBarAbove.data()); // Note: also works if one (or both) of them is 0
23497   // if new bar given, insert this bar above it:
23498   if (bars)
23499   {
23500     if (bars->mBarAbove)
23501       connectBars(this, bars->mBarAbove.data());
23502     connectBars(bars, this);
23503   }
23504 }
23505 
23506 /*!
23507   \copydoc QCPPlottableInterface1D::selectTestRect
23508 */
selectTestRect(const QRectF & rect,bool onlySelectable) const23509 QCPDataSelection QCPBars::selectTestRect(const QRectF &rect, bool onlySelectable) const
23510 {
23511   QCPDataSelection result;
23512   if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
23513     return result;
23514   if (!mKeyAxis || !mValueAxis)
23515     return result;
23516 
23517   QCPBarsDataContainer::const_iterator visibleBegin, visibleEnd;
23518   getVisibleDataBounds(visibleBegin, visibleEnd);
23519 
23520   for (QCPBarsDataContainer::const_iterator it=visibleBegin; it!=visibleEnd; ++it)
23521   {
23522     if (rect.intersects(getBarRect(it->key, it->value)))
23523       result.addDataRange(QCPDataRange(it-mDataContainer->constBegin(), it-mDataContainer->constBegin()+1), false);
23524   }
23525   result.simplify();
23526   return result;
23527 }
23528 
23529 /* inherits documentation from base class */
selectTest(const QPointF & pos,bool onlySelectable,QVariant * details) const23530 double QCPBars::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
23531 {
23532   Q_UNUSED(details)
23533   if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
23534     return -1;
23535   if (!mKeyAxis || !mValueAxis)
23536     return -1;
23537 
23538   if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()))
23539   {
23540     // get visible data range:
23541     QCPBarsDataContainer::const_iterator visibleBegin, visibleEnd;
23542     getVisibleDataBounds(visibleBegin, visibleEnd);
23543     for (QCPBarsDataContainer::const_iterator it=visibleBegin; it!=visibleEnd; ++it)
23544     {
23545       if (getBarRect(it->key, it->value).contains(pos))
23546       {
23547         if (details)
23548         {
23549           int pointIndex = it-mDataContainer->constBegin();
23550           details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1)));
23551         }
23552         return mParentPlot->selectionTolerance()*0.99;
23553       }
23554     }
23555   }
23556   return -1;
23557 }
23558 
23559 /* inherits documentation from base class */
getKeyRange(bool & foundRange,QCP::SignDomain inSignDomain) const23560 QCPRange QCPBars::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const
23561 {
23562   /* Note: If this QCPBars uses absolute pixels as width (or is in a QCPBarsGroup with spacing in
23563   absolute pixels), using this method to adapt the key axis range to fit the bars into the
23564   currently visible axis range will not work perfectly. Because in the moment the axis range is
23565   changed to the new range, the fixed pixel widths/spacings will represent different coordinate
23566   spans than before, which in turn would require a different key range to perfectly fit, and so on.
23567   The only solution would be to iteratively approach the perfect fitting axis range, but the
23568   mismatch isn't large enough in most applications, to warrant this here. If a user does need a
23569   better fit, he should call the corresponding axis rescale multiple times in a row.
23570   */
23571   QCPRange range;
23572   range = mDataContainer->keyRange(foundRange, inSignDomain);
23573 
23574   // determine exact range of bars by including bar width and barsgroup offset:
23575   if (foundRange && mKeyAxis)
23576   {
23577     double lowerPixelWidth, upperPixelWidth, keyPixel;
23578     // lower range bound:
23579     getPixelWidth(range.lower, lowerPixelWidth, upperPixelWidth);
23580     keyPixel = mKeyAxis.data()->coordToPixel(range.lower) + lowerPixelWidth;
23581     if (mBarsGroup)
23582       keyPixel += mBarsGroup->keyPixelOffset(this, range.lower);
23583     const double lowerCorrected = mKeyAxis.data()->pixelToCoord(keyPixel);
23584     if (!qIsNaN(lowerCorrected) && qIsFinite(lowerCorrected) && range.lower > lowerCorrected)
23585       range.lower = lowerCorrected;
23586     // upper range bound:
23587     getPixelWidth(range.upper, lowerPixelWidth, upperPixelWidth);
23588     keyPixel = mKeyAxis.data()->coordToPixel(range.upper) + upperPixelWidth;
23589     if (mBarsGroup)
23590       keyPixel += mBarsGroup->keyPixelOffset(this, range.upper);
23591     const double upperCorrected = mKeyAxis.data()->pixelToCoord(keyPixel);
23592     if (!qIsNaN(upperCorrected) && qIsFinite(upperCorrected) && range.upper < upperCorrected)
23593       range.upper = upperCorrected;
23594   }
23595   return range;
23596 }
23597 
23598 /* inherits documentation from base class */
getValueRange(bool & foundRange,QCP::SignDomain inSignDomain,const QCPRange & inKeyRange) const23599 QCPRange QCPBars::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const
23600 {
23601   // Note: can't simply use mDataContainer->valueRange here because we need to
23602   // take into account bar base value and possible stacking of multiple bars
23603   QCPRange range;
23604   range.lower = mBaseValue;
23605   range.upper = mBaseValue;
23606   bool haveLower = true; // set to true, because baseValue should always be visible in bar charts
23607   bool haveUpper = true; // set to true, because baseValue should always be visible in bar charts
23608   QCPBarsDataContainer::const_iterator itBegin = mDataContainer->constBegin();
23609   QCPBarsDataContainer::const_iterator itEnd = mDataContainer->constEnd();
23610   if (inKeyRange != QCPRange())
23611   {
23612     itBegin = mDataContainer->findBegin(inKeyRange.lower);
23613     itEnd = mDataContainer->findEnd(inKeyRange.upper);
23614   }
23615   for (QCPBarsDataContainer::const_iterator it = itBegin; it != itEnd; ++it)
23616   {
23617     const double current = it->value + getStackedBaseValue(it->key, it->value >= 0);
23618     if (qIsNaN(current)) continue;
23619     if (inSignDomain == QCP::sdBoth || (inSignDomain == QCP::sdNegative && current < 0) || (inSignDomain == QCP::sdPositive && current > 0))
23620     {
23621       if (current < range.lower || !haveLower)
23622       {
23623         range.lower = current;
23624         haveLower = true;
23625       }
23626       if (current > range.upper || !haveUpper)
23627       {
23628         range.upper = current;
23629         haveUpper = true;
23630       }
23631     }
23632   }
23633 
23634   foundRange = true; // return true because bar charts always have the 0-line visible
23635   return range;
23636 }
23637 
23638 /* inherits documentation from base class */
dataPixelPosition(int index) const23639 QPointF QCPBars::dataPixelPosition(int index) const
23640 {
23641   if (index >= 0 && index < mDataContainer->size())
23642   {
23643     QCPAxis *keyAxis = mKeyAxis.data();
23644     QCPAxis *valueAxis = mValueAxis.data();
23645     if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPointF(); }
23646 
23647     const QCPDataContainer<QCPBarsData>::const_iterator it = mDataContainer->constBegin()+index;
23648     const double valuePixel = valueAxis->coordToPixel(getStackedBaseValue(it->key, it->value >= 0) + it->value);
23649     const double keyPixel = keyAxis->coordToPixel(it->key) + (mBarsGroup ? mBarsGroup->keyPixelOffset(this, it->key) : 0);
23650     if (keyAxis->orientation() == Qt::Horizontal)
23651       return QPointF(keyPixel, valuePixel);
23652     else
23653       return QPointF(valuePixel, keyPixel);
23654   } else
23655   {
23656     qDebug() << Q_FUNC_INFO << "Index out of bounds" << index;
23657     return QPointF();
23658   }
23659 }
23660 
23661 /* inherits documentation from base class */
draw(QCPPainter * painter)23662 void QCPBars::draw(QCPPainter *painter)
23663 {
23664   if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
23665   if (mDataContainer->isEmpty()) return;
23666 
23667   QCPBarsDataContainer::const_iterator visibleBegin, visibleEnd;
23668   getVisibleDataBounds(visibleBegin, visibleEnd);
23669 
23670   // loop over and draw segments of unselected/selected data:
23671   QList<QCPDataRange> selectedSegments, unselectedSegments, allSegments;
23672   getDataSegments(selectedSegments, unselectedSegments);
23673   allSegments << unselectedSegments << selectedSegments;
23674   for (int i=0; i<allSegments.size(); ++i)
23675   {
23676     bool isSelectedSegment = i >= unselectedSegments.size();
23677     QCPBarsDataContainer::const_iterator begin = visibleBegin;
23678     QCPBarsDataContainer::const_iterator end = visibleEnd;
23679     mDataContainer->limitIteratorsToDataRange(begin, end, allSegments.at(i));
23680     if (begin == end)
23681       continue;
23682 
23683     for (QCPBarsDataContainer::const_iterator it=begin; it!=end; ++it)
23684     {
23685       // check data validity if flag set:
23686 #ifdef QCUSTOMPLOT_CHECK_DATA
23687       if (QCP::isInvalidData(it->key, it->value))
23688         qDebug() << Q_FUNC_INFO << "Data point at" << it->key << "of drawn range invalid." << "Plottable name:" << name();
23689 #endif
23690       // draw bar:
23691       if (isSelectedSegment && mSelectionDecorator)
23692       {
23693         mSelectionDecorator->applyBrush(painter);
23694         mSelectionDecorator->applyPen(painter);
23695       } else
23696       {
23697         painter->setBrush(mBrush);
23698         painter->setPen(mPen);
23699       }
23700       applyDefaultAntialiasingHint(painter);
23701       painter->drawPolygon(getBarRect(it->key, it->value));
23702     }
23703   }
23704 
23705   // draw other selection decoration that isn't just line/scatter pens and brushes:
23706   if (mSelectionDecorator)
23707     mSelectionDecorator->drawDecoration(painter, selection());
23708 }
23709 
23710 /* inherits documentation from base class */
drawLegendIcon(QCPPainter * painter,const QRectF & rect) const23711 void QCPBars::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
23712 {
23713   // draw filled rect:
23714   applyDefaultAntialiasingHint(painter);
23715   painter->setBrush(mBrush);
23716   painter->setPen(mPen);
23717   QRectF r = QRectF(0, 0, rect.width()*0.67, rect.height()*0.67);
23718   r.moveCenter(rect.center());
23719   painter->drawRect(r);
23720 }
23721 
23722 /*!  \internal
23723 
23724   called by \ref draw to determine which data (key) range is visible at the current key axis range
23725   setting, so only that needs to be processed. It also takes into account the bar width.
23726 
23727   \a begin returns an iterator to the lowest data point that needs to be taken into account when
23728   plotting. Note that in order to get a clean plot all the way to the edge of the axis rect, \a
23729   lower may still be just outside the visible range.
23730 
23731   \a end returns an iterator one higher than the highest visible data point. Same as before, \a end
23732   may also lie just outside of the visible range.
23733 
23734   if the plottable contains no data, both \a begin and \a end point to constEnd.
23735 */
getVisibleDataBounds(QCPBarsDataContainer::const_iterator & begin,QCPBarsDataContainer::const_iterator & end) const23736 void QCPBars::getVisibleDataBounds(QCPBarsDataContainer::const_iterator &begin, QCPBarsDataContainer::const_iterator &end) const
23737 {
23738   if (!mKeyAxis)
23739   {
23740     qDebug() << Q_FUNC_INFO << "invalid key axis";
23741     begin = mDataContainer->constEnd();
23742     end = mDataContainer->constEnd();
23743     return;
23744   }
23745   if (mDataContainer->isEmpty())
23746   {
23747     begin = mDataContainer->constEnd();
23748     end = mDataContainer->constEnd();
23749     return;
23750   }
23751 
23752   // get visible data range as QMap iterators
23753   begin = mDataContainer->findBegin(mKeyAxis.data()->range().lower);
23754   end = mDataContainer->findEnd(mKeyAxis.data()->range().upper);
23755   double lowerPixelBound = mKeyAxis.data()->coordToPixel(mKeyAxis.data()->range().lower);
23756   double upperPixelBound = mKeyAxis.data()->coordToPixel(mKeyAxis.data()->range().upper);
23757   bool isVisible = false;
23758   // walk left from begin to find lower bar that actually is completely outside visible pixel range:
23759   QCPBarsDataContainer::const_iterator it = begin;
23760   while (it != mDataContainer->constBegin())
23761   {
23762     --it;
23763     const QRectF barRect = getBarRect(it->key, it->value);
23764     if (mKeyAxis.data()->orientation() == Qt::Horizontal)
23765       isVisible = ((!mKeyAxis.data()->rangeReversed() && barRect.right() >= lowerPixelBound) || (mKeyAxis.data()->rangeReversed() && barRect.left() <= lowerPixelBound));
23766     else // keyaxis is vertical
23767       isVisible = ((!mKeyAxis.data()->rangeReversed() && barRect.top() <= lowerPixelBound) || (mKeyAxis.data()->rangeReversed() && barRect.bottom() >= lowerPixelBound));
23768     if (isVisible)
23769       begin = it;
23770     else
23771       break;
23772   }
23773   // walk right from ubound to find upper bar that actually is completely outside visible pixel range:
23774   it = end;
23775   while (it != mDataContainer->constEnd())
23776   {
23777     const QRectF barRect = getBarRect(it->key, it->value);
23778     if (mKeyAxis.data()->orientation() == Qt::Horizontal)
23779       isVisible = ((!mKeyAxis.data()->rangeReversed() && barRect.left() <= upperPixelBound) || (mKeyAxis.data()->rangeReversed() && barRect.right() >= upperPixelBound));
23780     else // keyaxis is vertical
23781       isVisible = ((!mKeyAxis.data()->rangeReversed() && barRect.bottom() >= upperPixelBound) || (mKeyAxis.data()->rangeReversed() && barRect.top() <= upperPixelBound));
23782     if (isVisible)
23783       end = it+1;
23784     else
23785       break;
23786     ++it;
23787   }
23788 }
23789 
23790 /*! \internal
23791 
23792   Returns the rect in pixel coordinates of a single bar with the specified \a key and \a value. The
23793   rect is shifted according to the bar stacking (see \ref moveAbove) and base value (see \ref
23794   setBaseValue), and to have non-overlapping border lines with the bars stacked below.
23795 */
getBarRect(double key,double value) const23796 QRectF QCPBars::getBarRect(double key, double value) const
23797 {
23798   QCPAxis *keyAxis = mKeyAxis.data();
23799   QCPAxis *valueAxis = mValueAxis.data();
23800   if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QRectF(); }
23801 
23802   double lowerPixelWidth, upperPixelWidth;
23803   getPixelWidth(key, lowerPixelWidth, upperPixelWidth);
23804   double base = getStackedBaseValue(key, value >= 0);
23805   double basePixel = valueAxis->coordToPixel(base);
23806   double valuePixel = valueAxis->coordToPixel(base+value);
23807   double keyPixel = keyAxis->coordToPixel(key);
23808   if (mBarsGroup)
23809     keyPixel += mBarsGroup->keyPixelOffset(this, key);
23810   double bottomOffset = (mBarBelow && mPen != Qt::NoPen ? 1 : 0)*(mPen.isCosmetic() ? 1 : mPen.widthF());
23811   bottomOffset += mBarBelow ? mStackingGap : 0;
23812   bottomOffset *= (value<0 ? -1 : 1)*valueAxis->pixelOrientation();
23813   if (qAbs(valuePixel-basePixel) <= qAbs(bottomOffset))
23814     bottomOffset = valuePixel-basePixel;
23815   if (keyAxis->orientation() == Qt::Horizontal)
23816   {
23817     return QRectF(QPointF(keyPixel+lowerPixelWidth, valuePixel), QPointF(keyPixel+upperPixelWidth, basePixel+bottomOffset)).normalized();
23818   } else
23819   {
23820     return QRectF(QPointF(basePixel+bottomOffset, keyPixel+lowerPixelWidth), QPointF(valuePixel, keyPixel+upperPixelWidth)).normalized();
23821   }
23822 }
23823 
23824 /*! \internal
23825 
23826   This function is used to determine the width of the bar at coordinate \a key, according to the
23827   specified width (\ref setWidth) and width type (\ref setWidthType).
23828 
23829   The output parameters \a lower and \a upper return the number of pixels the bar extends to lower
23830   and higher keys, relative to the \a key coordinate (so with a non-reversed horizontal axis, \a
23831   lower is negative and \a upper positive).
23832 */
getPixelWidth(double key,double & lower,double & upper) const23833 void QCPBars::getPixelWidth(double key, double &lower, double &upper) const
23834 {
23835   lower = 0;
23836   upper = 0;
23837   switch (mWidthType)
23838   {
23839     case wtAbsolute:
23840     {
23841       upper = mWidth*0.5*mKeyAxis.data()->pixelOrientation();
23842       lower = -upper;
23843       break;
23844     }
23845     case wtAxisRectRatio:
23846     {
23847       if (mKeyAxis && mKeyAxis.data()->axisRect())
23848       {
23849         if (mKeyAxis.data()->orientation() == Qt::Horizontal)
23850           upper = mKeyAxis.data()->axisRect()->width()*mWidth*0.5*mKeyAxis.data()->pixelOrientation();
23851         else
23852           upper = mKeyAxis.data()->axisRect()->height()*mWidth*0.5*mKeyAxis.data()->pixelOrientation();
23853         lower = -upper;
23854       } else
23855         qDebug() << Q_FUNC_INFO << "No key axis or axis rect defined";
23856       break;
23857     }
23858     case wtPlotCoords:
23859     {
23860       if (mKeyAxis)
23861       {
23862         double keyPixel = mKeyAxis.data()->coordToPixel(key);
23863         upper = mKeyAxis.data()->coordToPixel(key+mWidth*0.5)-keyPixel;
23864         lower = mKeyAxis.data()->coordToPixel(key-mWidth*0.5)-keyPixel;
23865         // no need to qSwap(lower, higher) when range reversed, because higher/lower are gained by
23866         // coordinate transform which includes range direction
23867       } else
23868         qDebug() << Q_FUNC_INFO << "No key axis defined";
23869       break;
23870     }
23871   }
23872 }
23873 
23874 /*! \internal
23875 
23876   This function is called to find at which value to start drawing the base of a bar at \a key, when
23877   it is stacked on top of another QCPBars (e.g. with \ref moveAbove).
23878 
23879   positive and negative bars are separated per stack (positive are stacked above baseValue upwards,
23880   negative are stacked below baseValue downwards). This can be indicated with \a positive. So if the
23881   bar for which we need the base value is negative, set \a positive to false.
23882 */
getStackedBaseValue(double key,bool positive) const23883 double QCPBars::getStackedBaseValue(double key, bool positive) const
23884 {
23885   if (mBarBelow)
23886   {
23887     double max = 0; // don't initialize with mBaseValue here because only base value of bottom-most bar has meaning in a bar stack
23888     // find bars of mBarBelow that are approximately at key and find largest one:
23889     double epsilon = qAbs(key)*(sizeof(key)==4 ? 1e-6 : 1e-14); // should be safe even when changed to use float at some point
23890     if (key == 0)
23891       epsilon = (sizeof(key)==4 ? 1e-6 : 1e-14);
23892     QCPBarsDataContainer::const_iterator it = mBarBelow.data()->mDataContainer->findBegin(key-epsilon);
23893     QCPBarsDataContainer::const_iterator itEnd = mBarBelow.data()->mDataContainer->findEnd(key+epsilon);
23894     while (it != itEnd)
23895     {
23896       if (it->key > key-epsilon && it->key < key+epsilon)
23897       {
23898         if ((positive && it->value > max) ||
23899             (!positive && it->value < max))
23900           max = it->value;
23901       }
23902       ++it;
23903     }
23904     // recurse down the bar-stack to find the total height:
23905     return max + mBarBelow.data()->getStackedBaseValue(key, positive);
23906   } else
23907     return mBaseValue;
23908 }
23909 
23910 /*! \internal
23911 
23912   Connects \a below and \a above to each other via their mBarAbove/mBarBelow properties. The bar(s)
23913   currently above lower and below upper will become disconnected to lower/upper.
23914 
23915   If lower is zero, upper will be disconnected at the bottom.
23916   If upper is zero, lower will be disconnected at the top.
23917 */
connectBars(QCPBars * lower,QCPBars * upper)23918 void QCPBars::connectBars(QCPBars *lower, QCPBars *upper)
23919 {
23920   if (!lower && !upper) return;
23921 
23922   if (!lower) // disconnect upper at bottom
23923   {
23924     // disconnect old bar below upper:
23925     if (upper->mBarBelow && upper->mBarBelow.data()->mBarAbove.data() == upper)
23926       upper->mBarBelow.data()->mBarAbove = 0;
23927     upper->mBarBelow = 0;
23928   } else if (!upper) // disconnect lower at top
23929   {
23930     // disconnect old bar above lower:
23931     if (lower->mBarAbove && lower->mBarAbove.data()->mBarBelow.data() == lower)
23932       lower->mBarAbove.data()->mBarBelow = 0;
23933     lower->mBarAbove = 0;
23934   } else // connect lower and upper
23935   {
23936     // disconnect old bar above lower:
23937     if (lower->mBarAbove && lower->mBarAbove.data()->mBarBelow.data() == lower)
23938       lower->mBarAbove.data()->mBarBelow = 0;
23939     // disconnect old bar below upper:
23940     if (upper->mBarBelow && upper->mBarBelow.data()->mBarAbove.data() == upper)
23941       upper->mBarBelow.data()->mBarAbove = 0;
23942     lower->mBarAbove = upper;
23943     upper->mBarBelow = lower;
23944   }
23945 }
23946 /* end of 'src/plottables/plottable-bars.cpp' */
23947 
23948 
23949 /* including file 'src/plottables/plottable-statisticalbox.cpp', size 28622  */
23950 /* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
23951 
23952 ////////////////////////////////////////////////////////////////////////////////////////////////////
23953 //////////////////// QCPStatisticalBoxData
23954 ////////////////////////////////////////////////////////////////////////////////////////////////////
23955 
23956 /*! \class QCPStatisticalBoxData
23957   \brief Holds the data of one single data point for QCPStatisticalBox.
23958 
23959   The stored data is:
23960 
23961   \li \a key: coordinate on the key axis of this data point (this is the \a mainKey and the \a sortKey)
23962 
23963   \li \a minimum: the position of the lower whisker, typically the minimum measurement of the
23964   sample that's not considered an outlier.
23965 
23966   \li \a lowerQuartile: the lower end of the box. The lower and the upper quartiles are the two
23967   statistical quartiles around the median of the sample, they should contain 50% of the sample
23968   data.
23969 
23970   \li \a median: the value of the median mark inside the quartile box. The median separates the
23971   sample data in half (50% of the sample data is below/above the median). (This is the \a mainValue)
23972 
23973   \li \a upperQuartile: the upper end of the box. The lower and the upper quartiles are the two
23974   statistical quartiles around the median of the sample, they should contain 50% of the sample
23975   data.
23976 
23977   \li \a maximum: the position of the upper whisker, typically the maximum measurement of the
23978   sample that's not considered an outlier.
23979 
23980   \li \a outliers: a QVector of outlier values that will be drawn as scatter points at the \a key
23981   coordinate of this data point (see \ref QCPStatisticalBox::setOutlierStyle)
23982 
23983   The container for storing multiple data points is \ref QCPStatisticalBoxDataContainer. It is a
23984   typedef for \ref QCPDataContainer with \ref QCPStatisticalBoxData as the DataType template
23985   parameter. See the documentation there for an explanation regarding the data type's generic
23986   methods.
23987 
23988   \see QCPStatisticalBoxDataContainer
23989 */
23990 
23991 /* start documentation of inline functions */
23992 
23993 /*! \fn double QCPStatisticalBoxData::sortKey() const
23994 
23995   Returns the \a key member of this data point.
23996 
23997   For a general explanation of what this method is good for in the context of the data container,
23998   see the documentation of \ref QCPDataContainer.
23999 */
24000 
24001 /*! \fn static QCPStatisticalBoxData QCPStatisticalBoxData::fromSortKey(double sortKey)
24002 
24003   Returns a data point with the specified \a sortKey. All other members are set to zero.
24004 
24005   For a general explanation of what this method is good for in the context of the data container,
24006   see the documentation of \ref QCPDataContainer.
24007 */
24008 
24009 /*! \fn static static bool QCPStatisticalBoxData::sortKeyIsMainKey()
24010 
24011   Since the member \a key is both the data point key coordinate and the data ordering parameter,
24012   this method returns true.
24013 
24014   For a general explanation of what this method is good for in the context of the data container,
24015   see the documentation of \ref QCPDataContainer.
24016 */
24017 
24018 /*! \fn double QCPStatisticalBoxData::mainKey() const
24019 
24020   Returns the \a key member of this data point.
24021 
24022   For a general explanation of what this method is good for in the context of the data container,
24023   see the documentation of \ref QCPDataContainer.
24024 */
24025 
24026 /*! \fn double QCPStatisticalBoxData::mainValue() const
24027 
24028   Returns the \a median member of this data point.
24029 
24030   For a general explanation of what this method is good for in the context of the data container,
24031   see the documentation of \ref QCPDataContainer.
24032 */
24033 
24034 /*! \fn QCPRange QCPStatisticalBoxData::valueRange() const
24035 
24036   Returns a QCPRange spanning from the \a minimum to the \a maximum member of this statistical box
24037   data point, possibly further expanded by outliers.
24038 
24039   For a general explanation of what this method is good for in the context of the data container,
24040   see the documentation of \ref QCPDataContainer.
24041 */
24042 
24043 /* end documentation of inline functions */
24044 
24045 /*!
24046   Constructs a data point with key and all values set to zero.
24047 */
QCPStatisticalBoxData()24048 QCPStatisticalBoxData::QCPStatisticalBoxData() :
24049   key(0),
24050   minimum(0),
24051   lowerQuartile(0),
24052   median(0),
24053   upperQuartile(0),
24054   maximum(0)
24055 {
24056 }
24057 
24058 /*!
24059   Constructs a data point with the specified \a key, \a minimum, \a lowerQuartile, \a median, \a
24060   upperQuartile, \a maximum and optionally a number of \a outliers.
24061 */
QCPStatisticalBoxData(double key,double minimum,double lowerQuartile,double median,double upperQuartile,double maximum,const QVector<double> & outliers)24062 QCPStatisticalBoxData::QCPStatisticalBoxData(double key, double minimum, double lowerQuartile, double median, double upperQuartile, double maximum, const QVector<double> &outliers) :
24063   key(key),
24064   minimum(minimum),
24065   lowerQuartile(lowerQuartile),
24066   median(median),
24067   upperQuartile(upperQuartile),
24068   maximum(maximum),
24069   outliers(outliers)
24070 {
24071 }
24072 
24073 
24074 ////////////////////////////////////////////////////////////////////////////////////////////////////
24075 //////////////////// QCPStatisticalBox
24076 ////////////////////////////////////////////////////////////////////////////////////////////////////
24077 
24078 /*! \class QCPStatisticalBox
24079   \brief A plottable representing a single statistical box in a plot.
24080 
24081   \image html QCPStatisticalBox.png
24082 
24083   To plot data, assign it with the \ref setData or \ref addData functions. Alternatively, you can
24084   also access and modify the data via the \ref data method, which returns a pointer to the internal
24085   \ref QCPStatisticalBoxDataContainer.
24086 
24087   Additionally each data point can itself have a list of outliers, drawn as scatter points at the
24088   key coordinate of the respective statistical box data point. They can either be set by using the
24089   respective \ref addData(double,double,double,double,double,double,const QVector<double>&)
24090   "addData" method or accessing the individual data points through \ref data, and setting the
24091   <tt>QVector<double> outliers</tt> of the data points directly.
24092 
24093   \section qcpstatisticalbox-appearance Changing the appearance
24094 
24095   The appearance of each data point box, ranging from the lower to the upper quartile, is
24096   controlled via \ref setPen and \ref setBrush. You may change the width of the boxes with \ref
24097   setWidth in plot coordinates.
24098 
24099   Each data point's visual representation also consists of two whiskers. Whiskers are the lines
24100   which reach from the upper quartile to the maximum, and from the lower quartile to the minimum.
24101   The appearance of the whiskers can be modified with: \ref setWhiskerPen, \ref setWhiskerBarPen,
24102   \ref setWhiskerWidth. The whisker width is the width of the bar perpendicular to the whisker at
24103   the top (for maximum) and bottom (for minimum). If the whisker pen is changed, make sure to set
24104   the \c capStyle to \c Qt::FlatCap. Otherwise the backbone line might exceed the whisker bars by a
24105   few pixels due to the pen cap being not perfectly flat.
24106 
24107   The median indicator line inside the box has its own pen, \ref setMedianPen.
24108 
24109   The outlier data points are drawn as normal scatter points. Their look can be controlled with
24110   \ref setOutlierStyle
24111 
24112   \section qcpstatisticalbox-usage Usage
24113 
24114   Like all data representing objects in QCustomPlot, the QCPStatisticalBox is a plottable
24115   (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies
24116   (QCustomPlot::plottable, QCustomPlot::removePlottable, etc.)
24117 
24118   Usually, you first create an instance:
24119   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpstatisticalbox-creation-1
24120   which registers it with the QCustomPlot instance of the passed axes. Note that this QCustomPlot instance takes
24121   ownership of the plottable, so do not delete it manually but use QCustomPlot::removePlottable() instead.
24122   The newly created plottable can be modified, e.g.:
24123   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpstatisticalbox-creation-2
24124 */
24125 
24126 /* start documentation of inline functions */
24127 
24128 /*! \fn QSharedPointer<QCPStatisticalBoxDataContainer> QCPStatisticalBox::data() const
24129 
24130   Returns a shared pointer to the internal data storage of type \ref
24131   QCPStatisticalBoxDataContainer. You may use it to directly manipulate the data, which may be more
24132   convenient and faster than using the regular \ref setData or \ref addData methods.
24133 */
24134 
24135 /* end documentation of inline functions */
24136 
24137 /*!
24138   Constructs a statistical box which uses \a keyAxis as its key axis ("x") and \a valueAxis as its
24139   value axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and
24140   not have the same orientation. If either of these restrictions is violated, a corresponding
24141   message is printed to the debug output (qDebug), the construction is not aborted, though.
24142 
24143   The created QCPStatisticalBox is automatically registered with the QCustomPlot instance inferred
24144   from \a keyAxis. This QCustomPlot instance takes ownership of the QCPStatisticalBox, so do not
24145   delete it manually but use QCustomPlot::removePlottable() instead.
24146 */
QCPStatisticalBox(QCPAxis * keyAxis,QCPAxis * valueAxis)24147 QCPStatisticalBox::QCPStatisticalBox(QCPAxis *keyAxis, QCPAxis *valueAxis) :
24148   QCPAbstractPlottable1D<QCPStatisticalBoxData>(keyAxis, valueAxis),
24149   mWidth(0.5),
24150   mWhiskerWidth(0.2),
24151   mWhiskerPen(Qt::black, 0, Qt::DashLine, Qt::FlatCap),
24152   mWhiskerBarPen(Qt::black),
24153   mWhiskerAntialiased(false),
24154   mMedianPen(Qt::black, 3, Qt::SolidLine, Qt::FlatCap),
24155   mOutlierStyle(QCPScatterStyle::ssCircle, Qt::blue, 6)
24156 {
24157   setPen(QPen(Qt::black));
24158   setBrush(Qt::NoBrush);
24159 }
24160 
24161 /*! \overload
24162 
24163   Replaces the current data container with the provided \a data container.
24164 
24165   Since a QSharedPointer is used, multiple QCPStatisticalBoxes may share the same data container
24166   safely. Modifying the data in the container will then affect all statistical boxes that share the
24167   container. Sharing can be achieved by simply exchanging the data containers wrapped in shared
24168   pointers:
24169   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpstatisticalbox-datasharing-1
24170 
24171   If you do not wish to share containers, but create a copy from an existing container, rather use
24172   the \ref QCPDataContainer<DataType>::set method on the statistical box data container directly:
24173   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpstatisticalbox-datasharing-2
24174 
24175   \see addData
24176 */
setData(QSharedPointer<QCPStatisticalBoxDataContainer> data)24177 void QCPStatisticalBox::setData(QSharedPointer<QCPStatisticalBoxDataContainer> data)
24178 {
24179   mDataContainer = data;
24180 }
24181 /*! \overload
24182 
24183   Replaces the current data with the provided points in \a keys, \a minimum, \a lowerQuartile, \a
24184   median, \a upperQuartile and \a maximum. The provided vectors should have equal length. Else, the
24185   number of added points will be the size of the smallest vector.
24186 
24187   If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
24188   can set \a alreadySorted to true, to improve performance by saving a sorting run.
24189 
24190   \see addData
24191 */
setData(const QVector<double> & keys,const QVector<double> & minimum,const QVector<double> & lowerQuartile,const QVector<double> & median,const QVector<double> & upperQuartile,const QVector<double> & maximum,bool alreadySorted)24192 void QCPStatisticalBox::setData(const QVector<double> &keys, const QVector<double> &minimum, const QVector<double> &lowerQuartile, const QVector<double> &median, const QVector<double> &upperQuartile, const QVector<double> &maximum, bool alreadySorted)
24193 {
24194   mDataContainer->clear();
24195   addData(keys, minimum, lowerQuartile, median, upperQuartile, maximum, alreadySorted);
24196 }
24197 
24198 /*!
24199   Sets the width of the boxes in key coordinates.
24200 
24201   \see setWhiskerWidth
24202 */
setWidth(double width)24203 void QCPStatisticalBox::setWidth(double width)
24204 {
24205   mWidth = width;
24206 }
24207 
24208 /*!
24209   Sets the width of the whiskers in key coordinates.
24210 
24211   Whiskers are the lines which reach from the upper quartile to the maximum, and from the lower
24212   quartile to the minimum.
24213 
24214   \see setWidth
24215 */
setWhiskerWidth(double width)24216 void QCPStatisticalBox::setWhiskerWidth(double width)
24217 {
24218   mWhiskerWidth = width;
24219 }
24220 
24221 /*!
24222   Sets the pen used for drawing the whisker backbone.
24223 
24224   Whiskers are the lines which reach from the upper quartile to the maximum, and from the lower
24225   quartile to the minimum.
24226 
24227   Make sure to set the \c capStyle of the passed \a pen to \c Qt::FlatCap. Otherwise the backbone
24228   line might exceed the whisker bars by a few pixels due to the pen cap being not perfectly flat.
24229 
24230   \see setWhiskerBarPen
24231 */
setWhiskerPen(const QPen & pen)24232 void QCPStatisticalBox::setWhiskerPen(const QPen &pen)
24233 {
24234   mWhiskerPen = pen;
24235 }
24236 
24237 /*!
24238   Sets the pen used for drawing the whisker bars. Those are the lines parallel to the key axis at
24239   each end of the whisker backbone.
24240 
24241   Whiskers are the lines which reach from the upper quartile to the maximum, and from the lower
24242   quartile to the minimum.
24243 
24244   \see setWhiskerPen
24245 */
setWhiskerBarPen(const QPen & pen)24246 void QCPStatisticalBox::setWhiskerBarPen(const QPen &pen)
24247 {
24248   mWhiskerBarPen = pen;
24249 }
24250 
24251 /*!
24252   Sets whether the statistical boxes whiskers are drawn with antialiasing or not.
24253 
24254   Note that antialiasing settings may be overridden by QCustomPlot::setAntialiasedElements and
24255   QCustomPlot::setNotAntialiasedElements.
24256 */
setWhiskerAntialiased(bool enabled)24257 void QCPStatisticalBox::setWhiskerAntialiased(bool enabled)
24258 {
24259   mWhiskerAntialiased = enabled;
24260 }
24261 
24262 /*!
24263   Sets the pen used for drawing the median indicator line inside the statistical boxes.
24264 */
setMedianPen(const QPen & pen)24265 void QCPStatisticalBox::setMedianPen(const QPen &pen)
24266 {
24267   mMedianPen = pen;
24268 }
24269 
24270 /*!
24271   Sets the appearance of the outlier data points.
24272 
24273   Outliers can be specified with the method
24274   \ref addData(double key, double minimum, double lowerQuartile, double median, double upperQuartile, double maximum, const QVector<double> &outliers)
24275 */
setOutlierStyle(const QCPScatterStyle & style)24276 void QCPStatisticalBox::setOutlierStyle(const QCPScatterStyle &style)
24277 {
24278   mOutlierStyle = style;
24279 }
24280 
24281 /*! \overload
24282 
24283   Adds the provided points in \a keys, \a minimum, \a lowerQuartile, \a median, \a upperQuartile and
24284   \a maximum to the current data. The provided vectors should have equal length. Else, the number
24285   of added points will be the size of the smallest vector.
24286 
24287   If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
24288   can set \a alreadySorted to true, to improve performance by saving a sorting run.
24289 
24290   Alternatively, you can also access and modify the data directly via the \ref data method, which
24291   returns a pointer to the internal data container.
24292 */
addData(const QVector<double> & keys,const QVector<double> & minimum,const QVector<double> & lowerQuartile,const QVector<double> & median,const QVector<double> & upperQuartile,const QVector<double> & maximum,bool alreadySorted)24293 void QCPStatisticalBox::addData(const QVector<double> &keys, const QVector<double> &minimum, const QVector<double> &lowerQuartile, const QVector<double> &median, const QVector<double> &upperQuartile, const QVector<double> &maximum, bool alreadySorted)
24294 {
24295   if (keys.size() != minimum.size() || minimum.size() != lowerQuartile.size() || lowerQuartile.size() != median.size() ||
24296       median.size() != upperQuartile.size() || upperQuartile.size() != maximum.size() || maximum.size() != keys.size())
24297     qDebug() << Q_FUNC_INFO << "keys, minimum, lowerQuartile, median, upperQuartile, maximum have different sizes:"
24298              << keys.size() << minimum.size() << lowerQuartile.size() << median.size() << upperQuartile.size() << maximum.size();
24299   const int n = qMin(keys.size(), qMin(minimum.size(), qMin(lowerQuartile.size(), qMin(median.size(), qMin(upperQuartile.size(), maximum.size())))));
24300   QVector<QCPStatisticalBoxData> tempData(n);
24301   QVector<QCPStatisticalBoxData>::iterator it = tempData.begin();
24302   const QVector<QCPStatisticalBoxData>::iterator itEnd = tempData.end();
24303   int i = 0;
24304   while (it != itEnd)
24305   {
24306     it->key = keys[i];
24307     it->minimum = minimum[i];
24308     it->lowerQuartile = lowerQuartile[i];
24309     it->median = median[i];
24310     it->upperQuartile = upperQuartile[i];
24311     it->maximum = maximum[i];
24312     ++it;
24313     ++i;
24314   }
24315   mDataContainer->add(tempData, alreadySorted); // don't modify tempData beyond this to prevent copy on write
24316 }
24317 
24318 /*! \overload
24319 
24320   Adds the provided data point as \a key, \a minimum, \a lowerQuartile, \a median, \a upperQuartile
24321   and \a maximum to the current data.
24322 
24323   Alternatively, you can also access and modify the data directly via the \ref data method, which
24324   returns a pointer to the internal data container.
24325 */
addData(double key,double minimum,double lowerQuartile,double median,double upperQuartile,double maximum,const QVector<double> & outliers)24326 void QCPStatisticalBox::addData(double key, double minimum, double lowerQuartile, double median, double upperQuartile, double maximum, const QVector<double> &outliers)
24327 {
24328   mDataContainer->add(QCPStatisticalBoxData(key, minimum, lowerQuartile, median, upperQuartile, maximum, outliers));
24329 }
24330 
24331 /*!
24332   \copydoc QCPPlottableInterface1D::selectTestRect
24333 */
selectTestRect(const QRectF & rect,bool onlySelectable) const24334 QCPDataSelection QCPStatisticalBox::selectTestRect(const QRectF &rect, bool onlySelectable) const
24335 {
24336   QCPDataSelection result;
24337   if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
24338     return result;
24339   if (!mKeyAxis || !mValueAxis)
24340     return result;
24341 
24342   QCPStatisticalBoxDataContainer::const_iterator visibleBegin, visibleEnd;
24343   getVisibleDataBounds(visibleBegin, visibleEnd);
24344 
24345   for (QCPStatisticalBoxDataContainer::const_iterator it=visibleBegin; it!=visibleEnd; ++it)
24346   {
24347     if (rect.intersects(getQuartileBox(it)))
24348       result.addDataRange(QCPDataRange(it-mDataContainer->constBegin(), it-mDataContainer->constBegin()+1), false);
24349   }
24350   result.simplify();
24351   return result;
24352 }
24353 
24354 /* inherits documentation from base class */
selectTest(const QPointF & pos,bool onlySelectable,QVariant * details) const24355 double QCPStatisticalBox::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
24356 {
24357   Q_UNUSED(details)
24358   if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
24359     return -1;
24360   if (!mKeyAxis || !mValueAxis)
24361     return -1;
24362 
24363   if (mKeyAxis->axisRect()->rect().contains(pos.toPoint()))
24364   {
24365     // get visible data range:
24366     QCPStatisticalBoxDataContainer::const_iterator visibleBegin, visibleEnd;
24367     QCPStatisticalBoxDataContainer::const_iterator closestDataPoint = mDataContainer->constEnd();
24368     getVisibleDataBounds(visibleBegin, visibleEnd);
24369     double minDistSqr = std::numeric_limits<double>::max();
24370     for (QCPStatisticalBoxDataContainer::const_iterator it=visibleBegin; it!=visibleEnd; ++it)
24371     {
24372       if (getQuartileBox(it).contains(pos)) // quartile box
24373       {
24374         double currentDistSqr = mParentPlot->selectionTolerance()*0.99 * mParentPlot->selectionTolerance()*0.99;
24375         if (currentDistSqr < minDistSqr)
24376         {
24377           minDistSqr = currentDistSqr;
24378           closestDataPoint = it;
24379         }
24380       } else // whiskers
24381       {
24382         const QVector<QLineF> whiskerBackbones(getWhiskerBackboneLines(it));
24383         for (int i=0; i<whiskerBackbones.size(); ++i)
24384         {
24385           double currentDistSqr = QCPVector2D(pos).distanceSquaredToLine(whiskerBackbones.at(i));
24386           if (currentDistSqr < minDistSqr)
24387           {
24388             minDistSqr = currentDistSqr;
24389             closestDataPoint = it;
24390           }
24391         }
24392       }
24393     }
24394     if (details)
24395     {
24396       int pointIndex = closestDataPoint-mDataContainer->constBegin();
24397       details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1)));
24398     }
24399     return qSqrt(minDistSqr);
24400   }
24401   return -1;
24402 }
24403 
24404 /* inherits documentation from base class */
getKeyRange(bool & foundRange,QCP::SignDomain inSignDomain) const24405 QCPRange QCPStatisticalBox::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const
24406 {
24407   QCPRange range = mDataContainer->keyRange(foundRange, inSignDomain);
24408   // determine exact range by including width of bars/flags:
24409   if (foundRange)
24410   {
24411     if (inSignDomain != QCP::sdPositive || range.lower-mWidth*0.5 > 0)
24412       range.lower -= mWidth*0.5;
24413     if (inSignDomain != QCP::sdNegative || range.upper+mWidth*0.5 < 0)
24414       range.upper += mWidth*0.5;
24415   }
24416   return range;
24417 }
24418 
24419 /* inherits documentation from base class */
getValueRange(bool & foundRange,QCP::SignDomain inSignDomain,const QCPRange & inKeyRange) const24420 QCPRange QCPStatisticalBox::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const
24421 {
24422   return mDataContainer->valueRange(foundRange, inSignDomain, inKeyRange);
24423 }
24424 
24425 /* inherits documentation from base class */
draw(QCPPainter * painter)24426 void QCPStatisticalBox::draw(QCPPainter *painter)
24427 {
24428   if (mDataContainer->isEmpty()) return;
24429   QCPAxis *keyAxis = mKeyAxis.data();
24430   QCPAxis *valueAxis = mValueAxis.data();
24431   if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
24432 
24433   QCPStatisticalBoxDataContainer::const_iterator visibleBegin, visibleEnd;
24434   getVisibleDataBounds(visibleBegin, visibleEnd);
24435 
24436   // loop over and draw segments of unselected/selected data:
24437   QList<QCPDataRange> selectedSegments, unselectedSegments, allSegments;
24438   getDataSegments(selectedSegments, unselectedSegments);
24439   allSegments << unselectedSegments << selectedSegments;
24440   for (int i=0; i<allSegments.size(); ++i)
24441   {
24442     bool isSelectedSegment = i >= unselectedSegments.size();
24443     QCPStatisticalBoxDataContainer::const_iterator begin = visibleBegin;
24444     QCPStatisticalBoxDataContainer::const_iterator end = visibleEnd;
24445     mDataContainer->limitIteratorsToDataRange(begin, end, allSegments.at(i));
24446     if (begin == end)
24447       continue;
24448 
24449     for (QCPStatisticalBoxDataContainer::const_iterator it=begin; it!=end; ++it)
24450     {
24451       // check data validity if flag set:
24452 # ifdef QCUSTOMPLOT_CHECK_DATA
24453       if (QCP::isInvalidData(it->key, it->minimum) ||
24454           QCP::isInvalidData(it->lowerQuartile, it->median) ||
24455           QCP::isInvalidData(it->upperQuartile, it->maximum))
24456         qDebug() << Q_FUNC_INFO << "Data point at" << it->key << "of drawn range has invalid data." << "Plottable name:" << name();
24457       for (int i=0; i<it->outliers.size(); ++i)
24458         if (QCP::isInvalidData(it->outliers.at(i)))
24459           qDebug() << Q_FUNC_INFO << "Data point outlier at" << it->key << "of drawn range invalid." << "Plottable name:" << name();
24460 # endif
24461 
24462       if (isSelectedSegment && mSelectionDecorator)
24463       {
24464         mSelectionDecorator->applyPen(painter);
24465         mSelectionDecorator->applyBrush(painter);
24466       } else
24467       {
24468         painter->setPen(mPen);
24469         painter->setBrush(mBrush);
24470       }
24471       QCPScatterStyle finalOutlierStyle = mOutlierStyle;
24472       if (isSelectedSegment && mSelectionDecorator)
24473         finalOutlierStyle = mSelectionDecorator->getFinalScatterStyle(mOutlierStyle);
24474       drawStatisticalBox(painter, it, finalOutlierStyle);
24475     }
24476   }
24477 
24478   // draw other selection decoration that isn't just line/scatter pens and brushes:
24479   if (mSelectionDecorator)
24480     mSelectionDecorator->drawDecoration(painter, selection());
24481 }
24482 
24483 /* inherits documentation from base class */
drawLegendIcon(QCPPainter * painter,const QRectF & rect) const24484 void QCPStatisticalBox::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
24485 {
24486   // draw filled rect:
24487   applyDefaultAntialiasingHint(painter);
24488   painter->setPen(mPen);
24489   painter->setBrush(mBrush);
24490   QRectF r = QRectF(0, 0, rect.width()*0.67, rect.height()*0.67);
24491   r.moveCenter(rect.center());
24492   painter->drawRect(r);
24493 }
24494 
24495 /*!
24496   Draws the graphical representation of a single statistical box with the data given by the
24497   iterator \a it with the provided \a painter.
24498 
24499   If the statistical box has a set of outlier data points, they are drawn with \a outlierStyle.
24500 
24501   \see getQuartileBox, getWhiskerBackboneLines, getWhiskerBarLines
24502 */
drawStatisticalBox(QCPPainter * painter,QCPStatisticalBoxDataContainer::const_iterator it,const QCPScatterStyle & outlierStyle) const24503 void QCPStatisticalBox::drawStatisticalBox(QCPPainter *painter, QCPStatisticalBoxDataContainer::const_iterator it, const QCPScatterStyle &outlierStyle) const
24504 {
24505   // draw quartile box:
24506   applyDefaultAntialiasingHint(painter);
24507   const QRectF quartileBox = getQuartileBox(it);
24508   painter->drawRect(quartileBox);
24509   // draw median line with cliprect set to quartile box:
24510   painter->save();
24511   painter->setClipRect(quartileBox, Qt::IntersectClip);
24512   painter->setPen(mMedianPen);
24513   painter->drawLine(QLineF(coordsToPixels(it->key-mWidth*0.5, it->median), coordsToPixels(it->key+mWidth*0.5, it->median)));
24514   painter->restore();
24515   // draw whisker lines:
24516   applyAntialiasingHint(painter, mWhiskerAntialiased, QCP::aePlottables);
24517   painter->setPen(mWhiskerPen);
24518   painter->drawLines(getWhiskerBackboneLines(it));
24519   painter->setPen(mWhiskerBarPen);
24520   painter->drawLines(getWhiskerBarLines(it));
24521   // draw outliers:
24522   applyScattersAntialiasingHint(painter);
24523   outlierStyle.applyTo(painter, mPen);
24524   for (int i=0; i<it->outliers.size(); ++i)
24525     outlierStyle.drawShape(painter, coordsToPixels(it->key, it->outliers.at(i)));
24526 }
24527 
24528 /*!  \internal
24529 
24530   called by \ref draw to determine which data (key) range is visible at the current key axis range
24531   setting, so only that needs to be processed. It also takes into account the bar width.
24532 
24533   \a begin returns an iterator to the lowest data point that needs to be taken into account when
24534   plotting. Note that in order to get a clean plot all the way to the edge of the axis rect, \a
24535   lower may still be just outside the visible range.
24536 
24537   \a end returns an iterator one higher than the highest visible data point. Same as before, \a end
24538   may also lie just outside of the visible range.
24539 
24540   if the plottable contains no data, both \a begin and \a end point to constEnd.
24541 */
getVisibleDataBounds(QCPStatisticalBoxDataContainer::const_iterator & begin,QCPStatisticalBoxDataContainer::const_iterator & end) const24542 void QCPStatisticalBox::getVisibleDataBounds(QCPStatisticalBoxDataContainer::const_iterator &begin, QCPStatisticalBoxDataContainer::const_iterator &end) const
24543 {
24544   if (!mKeyAxis)
24545   {
24546     qDebug() << Q_FUNC_INFO << "invalid key axis";
24547     begin = mDataContainer->constEnd();
24548     end = mDataContainer->constEnd();
24549     return;
24550   }
24551   begin = mDataContainer->findBegin(mKeyAxis.data()->range().lower-mWidth*0.5); // subtract half width of box to include partially visible data points
24552   end = mDataContainer->findEnd(mKeyAxis.data()->range().upper+mWidth*0.5); // add half width of box to include partially visible data points
24553 }
24554 
24555 /*!  \internal
24556 
24557   Returns the box in plot coordinates (keys in x, values in y of the returned rect) that covers the
24558   value range from the lower to the upper quartile, of the data given by \a it.
24559 
24560   \see drawStatisticalBox, getWhiskerBackboneLines, getWhiskerBarLines
24561 */
getQuartileBox(QCPStatisticalBoxDataContainer::const_iterator it) const24562 QRectF QCPStatisticalBox::getQuartileBox(QCPStatisticalBoxDataContainer::const_iterator it) const
24563 {
24564   QRectF result;
24565   result.setTopLeft(coordsToPixels(it->key-mWidth*0.5, it->upperQuartile));
24566   result.setBottomRight(coordsToPixels(it->key+mWidth*0.5, it->lowerQuartile));
24567   return result;
24568 }
24569 
24570 /*!  \internal
24571 
24572   Returns the whisker backbones (keys in x, values in y of the returned lines) that cover the value
24573   range from the minimum to the lower quartile, and from the upper quartile to the maximum of the
24574   data given by \a it.
24575 
24576   \see drawStatisticalBox, getQuartileBox, getWhiskerBarLines
24577 */
getWhiskerBackboneLines(QCPStatisticalBoxDataContainer::const_iterator it) const24578 QVector<QLineF> QCPStatisticalBox::getWhiskerBackboneLines(QCPStatisticalBoxDataContainer::const_iterator it) const
24579 {
24580   QVector<QLineF> result(2);
24581   result[0].setPoints(coordsToPixels(it->key, it->lowerQuartile), coordsToPixels(it->key, it->minimum)); // min backbone
24582   result[1].setPoints(coordsToPixels(it->key, it->upperQuartile), coordsToPixels(it->key, it->maximum)); // max backbone
24583   return result;
24584 }
24585 
24586 /*!  \internal
24587 
24588   Returns the whisker bars (keys in x, values in y of the returned lines) that are placed at the
24589   end of the whisker backbones, at the minimum and maximum of the data given by \a it.
24590 
24591   \see drawStatisticalBox, getQuartileBox, getWhiskerBackboneLines
24592 */
getWhiskerBarLines(QCPStatisticalBoxDataContainer::const_iterator it) const24593 QVector<QLineF> QCPStatisticalBox::getWhiskerBarLines(QCPStatisticalBoxDataContainer::const_iterator it) const
24594 {
24595   QVector<QLineF> result(2);
24596   result[0].setPoints(coordsToPixels(it->key-mWhiskerWidth*0.5, it->minimum), coordsToPixels(it->key+mWhiskerWidth*0.5, it->minimum)); // min bar
24597   result[1].setPoints(coordsToPixels(it->key-mWhiskerWidth*0.5, it->maximum), coordsToPixels(it->key+mWhiskerWidth*0.5, it->maximum)); // max bar
24598   return result;
24599 }
24600 /* end of 'src/plottables/plottable-statisticalbox.cpp' */
24601 
24602 
24603 /* including file 'src/plottables/plottable-colormap.cpp', size 47531        */
24604 /* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
24605 
24606 ////////////////////////////////////////////////////////////////////////////////////////////////////
24607 //////////////////// QCPColorMapData
24608 ////////////////////////////////////////////////////////////////////////////////////////////////////
24609 
24610 /*! \class QCPColorMapData
24611   \brief Holds the two-dimensional data of a QCPColorMap plottable.
24612 
24613   This class is a data storage for \ref QCPColorMap. It holds a two-dimensional array, which \ref
24614   QCPColorMap then displays as a 2D image in the plot, where the array values are represented by a
24615   color, depending on the value.
24616 
24617   The size of the array can be controlled via \ref setSize (or \ref setKeySize, \ref setValueSize).
24618   Which plot coordinates these cells correspond to can be configured with \ref setRange (or \ref
24619   setKeyRange, \ref setValueRange).
24620 
24621   The data cells can be accessed in two ways: They can be directly addressed by an integer index
24622   with \ref setCell. This is the fastest method. Alternatively, they can be addressed by their plot
24623   coordinate with \ref setData. plot coordinate to cell index transformations and vice versa are
24624   provided by the functions \ref coordToCell and \ref cellToCoord.
24625 
24626   A \ref QCPColorMapData also holds an on-demand two-dimensional array of alpha values which (if
24627   allocated) has the same size as the data map. It can be accessed via \ref setAlpha, \ref
24628   fillAlpha and \ref clearAlpha. The memory for the alpha map is only allocated if needed, i.e. on
24629   the first call of \ref setAlpha. \ref clearAlpha restores full opacity and frees the alpha map.
24630 
24631   This class also buffers the minimum and maximum values that are in the data set, to provide
24632   QCPColorMap::rescaleDataRange with the necessary information quickly. Setting a cell to a value
24633   that is greater than the current maximum increases this maximum to the new value. However,
24634   setting the cell that currently holds the maximum value to a smaller value doesn't decrease the
24635   maximum again, because finding the true new maximum would require going through the entire data
24636   array, which might be time consuming. The same holds for the data minimum. This functionality is
24637   given by \ref recalculateDataBounds, such that you can decide when it is sensible to find the
24638   true current minimum and maximum. The method QCPColorMap::rescaleDataRange offers a convenience
24639   parameter \a recalculateDataBounds which may be set to true to automatically call \ref
24640   recalculateDataBounds internally.
24641 */
24642 
24643 /* start of documentation of inline functions */
24644 
24645 /*! \fn bool QCPColorMapData::isEmpty() const
24646 
24647   Returns whether this instance carries no data. This is equivalent to having a size where at least
24648   one of the dimensions is 0 (see \ref setSize).
24649 */
24650 
24651 /* end of documentation of inline functions */
24652 
24653 /*!
24654   Constructs a new QCPColorMapData instance. The instance has \a keySize cells in the key direction
24655   and \a valueSize cells in the value direction. These cells will be displayed by the \ref QCPColorMap
24656   at the coordinates \a keyRange and \a valueRange.
24657 
24658   \see setSize, setKeySize, setValueSize, setRange, setKeyRange, setValueRange
24659 */
QCPColorMapData(int keySize,int valueSize,const QCPRange & keyRange,const QCPRange & valueRange)24660 QCPColorMapData::QCPColorMapData(int keySize, int valueSize, const QCPRange &keyRange, const QCPRange &valueRange) :
24661   mKeySize(0),
24662   mValueSize(0),
24663   mKeyRange(keyRange),
24664   mValueRange(valueRange),
24665   mIsEmpty(true),
24666   mData(0),
24667   mAlpha(0),
24668   mDataModified(true)
24669 {
24670   setSize(keySize, valueSize);
24671   fill(0);
24672 }
24673 
~QCPColorMapData()24674 QCPColorMapData::~QCPColorMapData()
24675 {
24676   if (mData)
24677     delete[] mData;
24678   if (mAlpha)
24679     delete[] mAlpha;
24680 }
24681 
24682 /*!
24683   Constructs a new QCPColorMapData instance copying the data and range of \a other.
24684 */
QCPColorMapData(const QCPColorMapData & other)24685 QCPColorMapData::QCPColorMapData(const QCPColorMapData &other) :
24686   mKeySize(0),
24687   mValueSize(0),
24688   mIsEmpty(true),
24689   mData(0),
24690   mAlpha(0),
24691   mDataModified(true)
24692 {
24693   *this = other;
24694 }
24695 
24696 /*!
24697   Overwrites this color map data instance with the data stored in \a other. The alpha map state is
24698   transferred, too.
24699 */
operator =(const QCPColorMapData & other)24700 QCPColorMapData &QCPColorMapData::operator=(const QCPColorMapData &other)
24701 {
24702   if (&other != this)
24703   {
24704     const int keySize = other.keySize();
24705     const int valueSize = other.valueSize();
24706     if (!other.mAlpha && mAlpha)
24707       clearAlpha();
24708     setSize(keySize, valueSize);
24709     if (other.mAlpha && !mAlpha)
24710       createAlpha(false);
24711     setRange(other.keyRange(), other.valueRange());
24712     if (!isEmpty())
24713     {
24714       memcpy(mData, other.mData, sizeof(mData[0])*keySize*valueSize);
24715       if (mAlpha)
24716         memcpy(mAlpha, other.mAlpha, sizeof(mAlpha[0])*keySize*valueSize);
24717     }
24718     mDataBounds = other.mDataBounds;
24719     mDataModified = true;
24720   }
24721   return *this;
24722 }
24723 
24724 /* undocumented getter */
data(double key,double value)24725 double QCPColorMapData::data(double key, double value)
24726 {
24727   int keyCell = (key-mKeyRange.lower)/(mKeyRange.upper-mKeyRange.lower)*(mKeySize-1)+0.5;
24728   int valueCell = (value-mValueRange.lower)/(mValueRange.upper-mValueRange.lower)*(mValueSize-1)+0.5;
24729   if (keyCell >= 0 && keyCell < mKeySize && valueCell >= 0 && valueCell < mValueSize)
24730     return mData[valueCell*mKeySize + keyCell];
24731   else
24732     return 0;
24733 }
24734 
24735 /* undocumented getter */
cell(int keyIndex,int valueIndex)24736 double QCPColorMapData::cell(int keyIndex, int valueIndex)
24737 {
24738   if (keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize)
24739     return mData[valueIndex*mKeySize + keyIndex];
24740   else
24741     return 0;
24742 }
24743 
24744 /*!
24745   Returns the alpha map value of the cell with the indices \a keyIndex and \a valueIndex.
24746 
24747   If this color map data doesn't have an alpha map (because \ref setAlpha was never called after
24748   creation or after a call to \ref clearAlpha), returns 255, which corresponds to full opacity.
24749 
24750   \see setAlpha
24751 */
alpha(int keyIndex,int valueIndex)24752 unsigned char QCPColorMapData::alpha(int keyIndex, int valueIndex)
24753 {
24754   if (mAlpha && keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize)
24755     return mAlpha[valueIndex*mKeySize + keyIndex];
24756   else
24757     return 255;
24758 }
24759 
24760 /*!
24761   Resizes the data array to have \a keySize cells in the key dimension and \a valueSize cells in
24762   the value dimension.
24763 
24764   The current data is discarded and the map cells are set to 0, unless the map had already the
24765   requested size.
24766 
24767   Setting at least one of \a keySize or \a valueSize to zero frees the internal data array and \ref
24768   isEmpty returns true.
24769 
24770   \see setRange, setKeySize, setValueSize
24771 */
setSize(int keySize,int valueSize)24772 void QCPColorMapData::setSize(int keySize, int valueSize)
24773 {
24774   if (keySize != mKeySize || valueSize != mValueSize)
24775   {
24776     mKeySize = keySize;
24777     mValueSize = valueSize;
24778     if (mData)
24779       delete[] mData;
24780     mIsEmpty = mKeySize == 0 || mValueSize == 0;
24781     if (!mIsEmpty)
24782     {
24783 #ifdef __EXCEPTIONS
24784       try { // 2D arrays get memory intensive fast. So if the allocation fails, at least output debug message
24785 #endif
24786       mData = new double[mKeySize*mValueSize];
24787 #ifdef __EXCEPTIONS
24788       } catch (...) { mData = 0; }
24789 #endif
24790       if (mData)
24791         fill(0);
24792       else
24793         qDebug() << Q_FUNC_INFO << "out of memory for data dimensions "<< mKeySize << "*" << mValueSize;
24794     } else
24795       mData = 0;
24796 
24797     if (mAlpha) // if we had an alpha map, recreate it with new size
24798       createAlpha();
24799 
24800     mDataModified = true;
24801   }
24802 }
24803 
24804 /*!
24805   Resizes the data array to have \a keySize cells in the key dimension.
24806 
24807   The current data is discarded and the map cells are set to 0, unless the map had already the
24808   requested size.
24809 
24810   Setting \a keySize to zero frees the internal data array and \ref isEmpty returns true.
24811 
24812   \see setKeyRange, setSize, setValueSize
24813 */
setKeySize(int keySize)24814 void QCPColorMapData::setKeySize(int keySize)
24815 {
24816   setSize(keySize, mValueSize);
24817 }
24818 
24819 /*!
24820   Resizes the data array to have \a valueSize cells in the value dimension.
24821 
24822   The current data is discarded and the map cells are set to 0, unless the map had already the
24823   requested size.
24824 
24825   Setting \a valueSize to zero frees the internal data array and \ref isEmpty returns true.
24826 
24827   \see setValueRange, setSize, setKeySize
24828 */
setValueSize(int valueSize)24829 void QCPColorMapData::setValueSize(int valueSize)
24830 {
24831   setSize(mKeySize, valueSize);
24832 }
24833 
24834 /*!
24835   Sets the coordinate ranges the data shall be distributed over. This defines the rectangular area
24836   covered by the color map in plot coordinates.
24837 
24838   The outer cells will be centered on the range boundaries given to this function. For example, if
24839   the key size (\ref setKeySize) is 3 and \a keyRange is set to <tt>QCPRange(2, 3)</tt> there will
24840   be cells centered on the key coordinates 2, 2.5 and 3.
24841 
24842   \see setSize
24843 */
setRange(const QCPRange & keyRange,const QCPRange & valueRange)24844 void QCPColorMapData::setRange(const QCPRange &keyRange, const QCPRange &valueRange)
24845 {
24846   setKeyRange(keyRange);
24847   setValueRange(valueRange);
24848 }
24849 
24850 /*!
24851   Sets the coordinate range the data shall be distributed over in the key dimension. Together with
24852   the value range, This defines the rectangular area covered by the color map in plot coordinates.
24853 
24854   The outer cells will be centered on the range boundaries given to this function. For example, if
24855   the key size (\ref setKeySize) is 3 and \a keyRange is set to <tt>QCPRange(2, 3)</tt> there will
24856   be cells centered on the key coordinates 2, 2.5 and 3.
24857 
24858   \see setRange, setValueRange, setSize
24859 */
setKeyRange(const QCPRange & keyRange)24860 void QCPColorMapData::setKeyRange(const QCPRange &keyRange)
24861 {
24862   mKeyRange = keyRange;
24863 }
24864 
24865 /*!
24866   Sets the coordinate range the data shall be distributed over in the value dimension. Together with
24867   the key range, This defines the rectangular area covered by the color map in plot coordinates.
24868 
24869   The outer cells will be centered on the range boundaries given to this function. For example, if
24870   the value size (\ref setValueSize) is 3 and \a valueRange is set to <tt>QCPRange(2, 3)</tt> there
24871   will be cells centered on the value coordinates 2, 2.5 and 3.
24872 
24873   \see setRange, setKeyRange, setSize
24874 */
setValueRange(const QCPRange & valueRange)24875 void QCPColorMapData::setValueRange(const QCPRange &valueRange)
24876 {
24877   mValueRange = valueRange;
24878 }
24879 
24880 /*!
24881   Sets the data of the cell, which lies at the plot coordinates given by \a key and \a value, to \a
24882   z.
24883 
24884   \note The QCPColorMap always displays the data at equal key/value intervals, even if the key or
24885   value axis is set to a logarithmic scaling. If you want to use QCPColorMap with logarithmic axes,
24886   you shouldn't use the \ref QCPColorMapData::setData method as it uses a linear transformation to
24887   determine the cell index. Rather directly access the cell index with \ref
24888   QCPColorMapData::setCell.
24889 
24890   \see setCell, setRange
24891 */
setData(double key,double value,double z)24892 void QCPColorMapData::setData(double key, double value, double z)
24893 {
24894   int keyCell = (key-mKeyRange.lower)/(mKeyRange.upper-mKeyRange.lower)*(mKeySize-1)+0.5;
24895   int valueCell = (value-mValueRange.lower)/(mValueRange.upper-mValueRange.lower)*(mValueSize-1)+0.5;
24896   if (keyCell >= 0 && keyCell < mKeySize && valueCell >= 0 && valueCell < mValueSize)
24897   {
24898     mData[valueCell*mKeySize + keyCell] = z;
24899     if (z < mDataBounds.lower)
24900       mDataBounds.lower = z;
24901     if (z > mDataBounds.upper)
24902       mDataBounds.upper = z;
24903      mDataModified = true;
24904   }
24905 }
24906 
24907 /*!
24908   Sets the data of the cell with indices \a keyIndex and \a valueIndex to \a z. The indices
24909   enumerate the cells starting from zero, up to the map's size-1 in the respective dimension (see
24910   \ref setSize).
24911 
24912   In the standard plot configuration (horizontal key axis and vertical value axis, both not
24913   range-reversed), the cell with indices (0, 0) is in the bottom left corner and the cell with
24914   indices (keySize-1, valueSize-1) is in the top right corner of the color map.
24915 
24916   \see setData, setSize
24917 */
setCell(int keyIndex,int valueIndex,double z)24918 void QCPColorMapData::setCell(int keyIndex, int valueIndex, double z)
24919 {
24920   if (keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize)
24921   {
24922     mData[valueIndex*mKeySize + keyIndex] = z;
24923     if (z < mDataBounds.lower)
24924       mDataBounds.lower = z;
24925     if (z > mDataBounds.upper)
24926       mDataBounds.upper = z;
24927      mDataModified = true;
24928   } else
24929     qDebug() << Q_FUNC_INFO << "index out of bounds:" << keyIndex << valueIndex;
24930 }
24931 
24932 /*!
24933   Sets the alpha of the color map cell given by \a keyIndex and \a valueIndex to \a alpha. A value
24934   of 0 for \a alpha results in a fully transparent cell, and a value of 255 results in a fully
24935   opaque cell.
24936 
24937   If an alpha map doesn't exist yet for this color map data, it will be created here. If you wish
24938   to restore full opacity and free any allocated memory of the alpha map, call \ref clearAlpha.
24939 
24940   Note that the cell-wise alpha which can be configured here is independent of any alpha configured
24941   in the color map's gradient (\ref QCPColorGradient). If a cell is affected both by the cell-wise
24942   and gradient alpha, the alpha values will be blended accordingly during rendering of the color
24943   map.
24944 
24945   \see fillAlpha, clearAlpha
24946 */
setAlpha(int keyIndex,int valueIndex,unsigned char alpha)24947 void QCPColorMapData::setAlpha(int keyIndex, int valueIndex, unsigned char alpha)
24948 {
24949   if (keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize)
24950   {
24951     if (mAlpha || createAlpha())
24952     {
24953       mAlpha[valueIndex*mKeySize + keyIndex] = alpha;
24954       mDataModified = true;
24955     }
24956   } else
24957     qDebug() << Q_FUNC_INFO << "index out of bounds:" << keyIndex << valueIndex;
24958 }
24959 
24960 /*!
24961   Goes through the data and updates the buffered minimum and maximum data values.
24962 
24963   Calling this method is only advised if you are about to call \ref QCPColorMap::rescaleDataRange
24964   and can not guarantee that the cells holding the maximum or minimum data haven't been overwritten
24965   with a smaller or larger value respectively, since the buffered maximum/minimum values have been
24966   updated the last time. Why this is the case is explained in the class description (\ref
24967   QCPColorMapData).
24968 
24969   Note that the method \ref QCPColorMap::rescaleDataRange provides a parameter \a
24970   recalculateDataBounds for convenience. Setting this to true will call this method for you, before
24971   doing the rescale.
24972 */
recalculateDataBounds()24973 void QCPColorMapData::recalculateDataBounds()
24974 {
24975   if (mKeySize > 0 && mValueSize > 0)
24976   {
24977     double minHeight = mData[0];
24978     double maxHeight = mData[0];
24979     const int dataCount = mValueSize*mKeySize;
24980     for (int i=0; i<dataCount; ++i)
24981     {
24982       if (mData[i] > maxHeight)
24983         maxHeight = mData[i];
24984       if (mData[i] < minHeight)
24985         minHeight = mData[i];
24986     }
24987     mDataBounds.lower = minHeight;
24988     mDataBounds.upper = maxHeight;
24989   }
24990 }
24991 
24992 /*!
24993   Frees the internal data memory.
24994 
24995   This is equivalent to calling \ref setSize "setSize(0, 0)".
24996 */
clear()24997 void QCPColorMapData::clear()
24998 {
24999   setSize(0, 0);
25000 }
25001 
25002 /*!
25003   Frees the internal alpha map. The color map will have full opacity again.
25004 */
clearAlpha()25005 void QCPColorMapData::clearAlpha()
25006 {
25007   if (mAlpha)
25008   {
25009     delete[] mAlpha;
25010     mAlpha = 0;
25011     mDataModified = true;
25012   }
25013 }
25014 
25015 /*!
25016   Sets all cells to the value \a z.
25017 */
fill(double z)25018 void QCPColorMapData::fill(double z)
25019 {
25020   const int dataCount = mValueSize*mKeySize;
25021   for (int i=0; i<dataCount; ++i)
25022     mData[i] = z;
25023   mDataBounds = QCPRange(z, z);
25024   mDataModified = true;
25025 }
25026 
25027 /*!
25028   Sets the opacity of all color map cells to \a alpha. A value of 0 for \a alpha results in a fully
25029   transparent color map, and a value of 255 results in a fully opaque color map.
25030 
25031   If you wish to restore opacity to 100% and free any used memory for the alpha map, rather use
25032   \ref clearAlpha.
25033 
25034   \see setAlpha
25035 */
fillAlpha(unsigned char alpha)25036 void QCPColorMapData::fillAlpha(unsigned char alpha)
25037 {
25038   if (mAlpha || createAlpha(false))
25039   {
25040     const int dataCount = mValueSize*mKeySize;
25041     for (int i=0; i<dataCount; ++i)
25042       mAlpha[i] = alpha;
25043     mDataModified = true;
25044   }
25045 }
25046 
25047 /*!
25048   Transforms plot coordinates given by \a key and \a value to cell indices of this QCPColorMapData
25049   instance. The resulting cell indices are returned via the output parameters \a keyIndex and \a
25050   valueIndex.
25051 
25052   The retrieved key/value cell indices can then be used for example with \ref setCell.
25053 
25054   If you are only interested in a key or value index, you may pass 0 as \a valueIndex or \a
25055   keyIndex.
25056 
25057   \note The QCPColorMap always displays the data at equal key/value intervals, even if the key or
25058   value axis is set to a logarithmic scaling. If you want to use QCPColorMap with logarithmic axes,
25059   you shouldn't use the \ref QCPColorMapData::coordToCell method as it uses a linear transformation to
25060   determine the cell index.
25061 
25062   \see cellToCoord, QCPAxis::coordToPixel
25063 */
coordToCell(double key,double value,int * keyIndex,int * valueIndex) const25064 void QCPColorMapData::coordToCell(double key, double value, int *keyIndex, int *valueIndex) const
25065 {
25066   if (keyIndex)
25067     *keyIndex = (key-mKeyRange.lower)/(mKeyRange.upper-mKeyRange.lower)*(mKeySize-1)+0.5;
25068   if (valueIndex)
25069     *valueIndex = (value-mValueRange.lower)/(mValueRange.upper-mValueRange.lower)*(mValueSize-1)+0.5;
25070 }
25071 
25072 /*!
25073   Transforms cell indices given by \a keyIndex and \a valueIndex to cell indices of this QCPColorMapData
25074   instance. The resulting coordinates are returned via the output parameters \a key and \a
25075   value.
25076 
25077   If you are only interested in a key or value coordinate, you may pass 0 as \a key or \a
25078   value.
25079 
25080   \note The QCPColorMap always displays the data at equal key/value intervals, even if the key or
25081   value axis is set to a logarithmic scaling. If you want to use QCPColorMap with logarithmic axes,
25082   you shouldn't use the \ref QCPColorMapData::cellToCoord method as it uses a linear transformation to
25083   determine the cell index.
25084 
25085   \see coordToCell, QCPAxis::pixelToCoord
25086 */
cellToCoord(int keyIndex,int valueIndex,double * key,double * value) const25087 void QCPColorMapData::cellToCoord(int keyIndex, int valueIndex, double *key, double *value) const
25088 {
25089   if (key)
25090     *key = keyIndex/(double)(mKeySize-1)*(mKeyRange.upper-mKeyRange.lower)+mKeyRange.lower;
25091   if (value)
25092     *value = valueIndex/(double)(mValueSize-1)*(mValueRange.upper-mValueRange.lower)+mValueRange.lower;
25093 }
25094 
25095 /*! \internal
25096 
25097   Allocates the internal alpha map with the current data map key/value size and, if \a
25098   initializeOpaque is true, initializes all values to 255. If \a initializeOpaque is false, the
25099   values are not initialized at all. In this case, the alpha map should be initialized manually,
25100   e.g. with \ref fillAlpha.
25101 
25102   If an alpha map exists already, it is deleted first. If this color map is empty (has either key
25103   or value size zero, see \ref isEmpty), the alpha map is cleared.
25104 
25105   The return value indicates the existence of the alpha map after the call. So this method returns
25106   true if the data map isn't empty and an alpha map was successfully allocated.
25107 */
createAlpha(bool initializeOpaque)25108 bool QCPColorMapData::createAlpha(bool initializeOpaque)
25109 {
25110   clearAlpha();
25111   if (isEmpty())
25112     return false;
25113 
25114 #ifdef __EXCEPTIONS
25115   try { // 2D arrays get memory intensive fast. So if the allocation fails, at least output debug message
25116 #endif
25117     mAlpha = new unsigned char[mKeySize*mValueSize];
25118 #ifdef __EXCEPTIONS
25119   } catch (...) { mAlpha = 0; }
25120 #endif
25121   if (mAlpha)
25122   {
25123     if (initializeOpaque)
25124       fillAlpha(255);
25125     return true;
25126   } else
25127   {
25128     qDebug() << Q_FUNC_INFO << "out of memory for data dimensions "<< mKeySize << "*" << mValueSize;
25129     return false;
25130   }
25131 }
25132 
25133 
25134 ////////////////////////////////////////////////////////////////////////////////////////////////////
25135 //////////////////// QCPColorMap
25136 ////////////////////////////////////////////////////////////////////////////////////////////////////
25137 
25138 /*! \class QCPColorMap
25139   \brief A plottable representing a two-dimensional color map in a plot.
25140 
25141   \image html QCPColorMap.png
25142 
25143   The data is stored in the class \ref QCPColorMapData, which can be accessed via the data()
25144   method.
25145 
25146   A color map has three dimensions to represent a data point: The \a key dimension, the \a value
25147   dimension and the \a data dimension. As with other plottables such as graphs, \a key and \a value
25148   correspond to two orthogonal axes on the QCustomPlot surface that you specify in the QCPColorMap
25149   constructor. The \a data dimension however is encoded as the color of the point at (\a key, \a
25150   value).
25151 
25152   Set the number of points (or \a cells) in the key/value dimension via \ref
25153   QCPColorMapData::setSize. The plot coordinate range over which these points will be displayed is
25154   specified via \ref QCPColorMapData::setRange. The first cell will be centered on the lower range
25155   boundary and the last cell will be centered on the upper range boundary. The data can be set by
25156   either accessing the cells directly with QCPColorMapData::setCell or by addressing the cells via
25157   their plot coordinates with \ref QCPColorMapData::setData. If possible, you should prefer
25158   setCell, since it doesn't need to do any coordinate transformation and thus performs a bit
25159   better.
25160 
25161   The cell with index (0, 0) is at the bottom left, if the color map uses normal (i.e. not reversed)
25162   key and value axes.
25163 
25164   To show the user which colors correspond to which \a data values, a \ref QCPColorScale is
25165   typically placed to the right of the axis rect. See the documentation there for details on how to
25166   add and use a color scale.
25167 
25168   \section qcpcolormap-appearance Changing the appearance
25169 
25170   The central part of the appearance is the color gradient, which can be specified via \ref
25171   setGradient. See the documentation of \ref QCPColorGradient for details on configuring a color
25172   gradient.
25173 
25174   The \a data range that is mapped to the colors of the gradient can be specified with \ref
25175   setDataRange. To make the data range encompass the whole data set minimum to maximum, call \ref
25176   rescaleDataRange.
25177 
25178   \section qcpcolormap-transparency Transparency
25179 
25180   Transparency in color maps can be achieved by two mechanisms. On one hand, you can specify alpha
25181   values for color stops of the \ref QCPColorGradient, via the regular QColor interface. This will
25182   cause the color map data which gets mapped to colors around those color stops to appear with the
25183   accordingly interpolated transparency.
25184 
25185   On the other hand you can also directly apply an alpha value to each cell independent of its
25186   data, by using the alpha map feature of \ref QCPColorMapData. The relevant methods are \ref
25187   QCPColorMapData::setAlpha, QCPColorMapData::fillAlpha and \ref QCPColorMapData::clearAlpha().
25188 
25189   The two transparencies will be joined together in the plot and otherwise not interfere with each
25190   other. They are mixed in a multiplicative matter, so an alpha of e.g. 50% (128/255) in both modes
25191   simultaneously, will result in a total transparency of 25% (64/255).
25192 
25193   \section qcpcolormap-usage Usage
25194 
25195   Like all data representing objects in QCustomPlot, the QCPColorMap is a plottable
25196   (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies
25197   (QCustomPlot::plottable, QCustomPlot::removePlottable, etc.)
25198 
25199   Usually, you first create an instance:
25200   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolormap-creation-1
25201   which registers it with the QCustomPlot instance of the passed axes. Note that this QCustomPlot instance takes
25202   ownership of the plottable, so do not delete it manually but use QCustomPlot::removePlottable() instead.
25203   The newly created plottable can be modified, e.g.:
25204   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolormap-creation-2
25205 
25206   \note The QCPColorMap always displays the data at equal key/value intervals, even if the key or
25207   value axis is set to a logarithmic scaling. If you want to use QCPColorMap with logarithmic axes,
25208   you shouldn't use the \ref QCPColorMapData::setData method as it uses a linear transformation to
25209   determine the cell index. Rather directly access the cell index with \ref
25210   QCPColorMapData::setCell.
25211 */
25212 
25213 /* start documentation of inline functions */
25214 
25215 /*! \fn QCPColorMapData *QCPColorMap::data() const
25216 
25217   Returns a pointer to the internal data storage of type \ref QCPColorMapData. Access this to
25218   modify data points (cells) and the color map key/value range.
25219 
25220   \see setData
25221 */
25222 
25223 /* end documentation of inline functions */
25224 
25225 /* start documentation of signals */
25226 
25227 /*! \fn void QCPColorMap::dataRangeChanged(const QCPRange &newRange);
25228 
25229   This signal is emitted when the data range changes.
25230 
25231   \see setDataRange
25232 */
25233 
25234 /*! \fn void QCPColorMap::dataScaleTypeChanged(QCPAxis::ScaleType scaleType);
25235 
25236   This signal is emitted when the data scale type changes.
25237 
25238   \see setDataScaleType
25239 */
25240 
25241 /*! \fn void QCPColorMap::gradientChanged(const QCPColorGradient &newGradient);
25242 
25243   This signal is emitted when the gradient changes.
25244 
25245   \see setGradient
25246 */
25247 
25248 /* end documentation of signals */
25249 
25250 /*!
25251   Constructs a color map with the specified \a keyAxis and \a valueAxis.
25252 
25253   The created QCPColorMap is automatically registered with the QCustomPlot instance inferred from
25254   \a keyAxis. This QCustomPlot instance takes ownership of the QCPColorMap, so do not delete it
25255   manually but use QCustomPlot::removePlottable() instead.
25256 */
QCPColorMap(QCPAxis * keyAxis,QCPAxis * valueAxis)25257 QCPColorMap::QCPColorMap(QCPAxis *keyAxis, QCPAxis *valueAxis) :
25258   QCPAbstractPlottable(keyAxis, valueAxis),
25259   mDataScaleType(QCPAxis::stLinear),
25260   mMapData(new QCPColorMapData(10, 10, QCPRange(0, 5), QCPRange(0, 5))),
25261   mInterpolate(true),
25262   mTightBoundary(false),
25263   mMapImageInvalidated(true)
25264 {
25265 }
25266 
~QCPColorMap()25267 QCPColorMap::~QCPColorMap()
25268 {
25269   delete mMapData;
25270 }
25271 
25272 /*!
25273   Replaces the current \ref data with the provided \a data.
25274 
25275   If \a copy is set to true, the \a data object will only be copied. if false, the color map
25276   takes ownership of the passed data and replaces the internal data pointer with it. This is
25277   significantly faster than copying for large datasets.
25278 */
setData(QCPColorMapData * data,bool copy)25279 void QCPColorMap::setData(QCPColorMapData *data, bool copy)
25280 {
25281   if (mMapData == data)
25282   {
25283     qDebug() << Q_FUNC_INFO << "The data pointer is already in (and owned by) this plottable" << reinterpret_cast<quintptr>(data);
25284     return;
25285   }
25286   if (copy)
25287   {
25288     *mMapData = *data;
25289   } else
25290   {
25291     delete mMapData;
25292     mMapData = data;
25293   }
25294   mMapImageInvalidated = true;
25295 }
25296 
25297 /*!
25298   Sets the data range of this color map to \a dataRange. The data range defines which data values
25299   are mapped to the color gradient.
25300 
25301   To make the data range span the full range of the data set, use \ref rescaleDataRange.
25302 
25303   \see QCPColorScale::setDataRange
25304 */
setDataRange(const QCPRange & dataRange)25305 void QCPColorMap::setDataRange(const QCPRange &dataRange)
25306 {
25307   if (!QCPRange::validRange(dataRange)) return;
25308   if (mDataRange.lower != dataRange.lower || mDataRange.upper != dataRange.upper)
25309   {
25310     if (mDataScaleType == QCPAxis::stLogarithmic)
25311       mDataRange = dataRange.sanitizedForLogScale();
25312     else
25313       mDataRange = dataRange.sanitizedForLinScale();
25314     mMapImageInvalidated = true;
25315     emit dataRangeChanged(mDataRange);
25316   }
25317 }
25318 
25319 /*!
25320   Sets whether the data is correlated with the color gradient linearly or logarithmically.
25321 
25322   \see QCPColorScale::setDataScaleType
25323 */
setDataScaleType(QCPAxis::ScaleType scaleType)25324 void QCPColorMap::setDataScaleType(QCPAxis::ScaleType scaleType)
25325 {
25326   if (mDataScaleType != scaleType)
25327   {
25328     mDataScaleType = scaleType;
25329     mMapImageInvalidated = true;
25330     emit dataScaleTypeChanged(mDataScaleType);
25331     if (mDataScaleType == QCPAxis::stLogarithmic)
25332       setDataRange(mDataRange.sanitizedForLogScale());
25333   }
25334 }
25335 
25336 /*!
25337   Sets the color gradient that is used to represent the data. For more details on how to create an
25338   own gradient or use one of the preset gradients, see \ref QCPColorGradient.
25339 
25340   The colors defined by the gradient will be used to represent data values in the currently set
25341   data range, see \ref setDataRange. Data points that are outside this data range will either be
25342   colored uniformly with the respective gradient boundary color, or the gradient will repeat,
25343   depending on \ref QCPColorGradient::setPeriodic.
25344 
25345   \see QCPColorScale::setGradient
25346 */
setGradient(const QCPColorGradient & gradient)25347 void QCPColorMap::setGradient(const QCPColorGradient &gradient)
25348 {
25349   if (mGradient != gradient)
25350   {
25351     mGradient = gradient;
25352     mMapImageInvalidated = true;
25353     emit gradientChanged(mGradient);
25354   }
25355 }
25356 
25357 /*!
25358   Sets whether the color map image shall use bicubic interpolation when displaying the color map
25359   shrinked or expanded, and not at a 1:1 pixel-to-data scale.
25360 
25361   \image html QCPColorMap-interpolate.png "A 10*10 color map, with interpolation and without interpolation enabled"
25362 */
setInterpolate(bool enabled)25363 void QCPColorMap::setInterpolate(bool enabled)
25364 {
25365   mInterpolate = enabled;
25366   mMapImageInvalidated = true; // because oversampling factors might need to change
25367 }
25368 
25369 /*!
25370   Sets whether the outer most data rows and columns are clipped to the specified key and value
25371   range (see \ref QCPColorMapData::setKeyRange, \ref QCPColorMapData::setValueRange).
25372 
25373   if \a enabled is set to false, the data points at the border of the color map are drawn with the
25374   same width and height as all other data points. Since the data points are represented by
25375   rectangles of one color centered on the data coordinate, this means that the shown color map
25376   extends by half a data point over the specified key/value range in each direction.
25377 
25378   \image html QCPColorMap-tightboundary.png "A color map, with tight boundary enabled and disabled"
25379 */
setTightBoundary(bool enabled)25380 void QCPColorMap::setTightBoundary(bool enabled)
25381 {
25382   mTightBoundary = enabled;
25383 }
25384 
25385 /*!
25386   Associates the color scale \a colorScale with this color map.
25387 
25388   This means that both the color scale and the color map synchronize their gradient, data range and
25389   data scale type (\ref setGradient, \ref setDataRange, \ref setDataScaleType). Multiple color maps
25390   can be associated with one single color scale. This causes the color maps to also synchronize
25391   those properties, via the mutual color scale.
25392 
25393   This function causes the color map to adopt the current color gradient, data range and data scale
25394   type of \a colorScale. After this call, you may change these properties at either the color map
25395   or the color scale, and the setting will be applied to both.
25396 
25397   Pass 0 as \a colorScale to disconnect the color scale from this color map again.
25398 */
setColorScale(QCPColorScale * colorScale)25399 void QCPColorMap::setColorScale(QCPColorScale *colorScale)
25400 {
25401   if (mColorScale) // unconnect signals from old color scale
25402   {
25403     disconnect(this, SIGNAL(dataRangeChanged(QCPRange)), mColorScale.data(), SLOT(setDataRange(QCPRange)));
25404     disconnect(this, SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), mColorScale.data(), SLOT(setDataScaleType(QCPAxis::ScaleType)));
25405     disconnect(this, SIGNAL(gradientChanged(QCPColorGradient)), mColorScale.data(), SLOT(setGradient(QCPColorGradient)));
25406     disconnect(mColorScale.data(), SIGNAL(dataRangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange)));
25407     disconnect(mColorScale.data(), SIGNAL(gradientChanged(QCPColorGradient)), this, SLOT(setGradient(QCPColorGradient)));
25408     disconnect(mColorScale.data(), SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType)));
25409   }
25410   mColorScale = colorScale;
25411   if (mColorScale) // connect signals to new color scale
25412   {
25413     setGradient(mColorScale.data()->gradient());
25414     setDataRange(mColorScale.data()->dataRange());
25415     setDataScaleType(mColorScale.data()->dataScaleType());
25416     connect(this, SIGNAL(dataRangeChanged(QCPRange)), mColorScale.data(), SLOT(setDataRange(QCPRange)));
25417     connect(this, SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), mColorScale.data(), SLOT(setDataScaleType(QCPAxis::ScaleType)));
25418     connect(this, SIGNAL(gradientChanged(QCPColorGradient)), mColorScale.data(), SLOT(setGradient(QCPColorGradient)));
25419     connect(mColorScale.data(), SIGNAL(dataRangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange)));
25420     connect(mColorScale.data(), SIGNAL(gradientChanged(QCPColorGradient)), this, SLOT(setGradient(QCPColorGradient)));
25421     connect(mColorScale.data(), SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType)));
25422   }
25423 }
25424 
25425 /*!
25426   Sets the data range (\ref setDataRange) to span the minimum and maximum values that occur in the
25427   current data set. This corresponds to the \ref rescaleKeyAxis or \ref rescaleValueAxis methods,
25428   only for the third data dimension of the color map.
25429 
25430   The minimum and maximum values of the data set are buffered in the internal QCPColorMapData
25431   instance (\ref data). As data is updated via its \ref QCPColorMapData::setCell or \ref
25432   QCPColorMapData::setData, the buffered minimum and maximum values are updated, too. For
25433   performance reasons, however, they are only updated in an expanding fashion. So the buffered
25434   maximum can only increase and the buffered minimum can only decrease. In consequence, changes to
25435   the data that actually lower the maximum of the data set (by overwriting the cell holding the
25436   current maximum with a smaller value), aren't recognized and the buffered maximum overestimates
25437   the true maximum of the data set. The same happens for the buffered minimum. To recalculate the
25438   true minimum and maximum by explicitly looking at each cell, the method
25439   QCPColorMapData::recalculateDataBounds can be used. For convenience, setting the parameter \a
25440   recalculateDataBounds calls this method before setting the data range to the buffered minimum and
25441   maximum.
25442 
25443   \see setDataRange
25444 */
rescaleDataRange(bool recalculateDataBounds)25445 void QCPColorMap::rescaleDataRange(bool recalculateDataBounds)
25446 {
25447   if (recalculateDataBounds)
25448     mMapData->recalculateDataBounds();
25449   setDataRange(mMapData->dataBounds());
25450 }
25451 
25452 /*!
25453   Takes the current appearance of the color map and updates the legend icon, which is used to
25454   represent this color map in the legend (see \ref QCPLegend).
25455 
25456   The \a transformMode specifies whether the rescaling is done by a faster, low quality image
25457   scaling algorithm (Qt::FastTransformation) or by a slower, higher quality algorithm
25458   (Qt::SmoothTransformation).
25459 
25460   The current color map appearance is scaled down to \a thumbSize. Ideally, this should be equal to
25461   the size of the legend icon (see \ref QCPLegend::setIconSize). If it isn't exactly the configured
25462   legend icon size, the thumb will be rescaled during drawing of the legend item.
25463 
25464   \see setDataRange
25465 */
updateLegendIcon(Qt::TransformationMode transformMode,const QSize & thumbSize)25466 void QCPColorMap::updateLegendIcon(Qt::TransformationMode transformMode, const QSize &thumbSize)
25467 {
25468   if (mMapImage.isNull() && !data()->isEmpty())
25469     updateMapImage(); // try to update map image if it's null (happens if no draw has happened yet)
25470 
25471   if (!mMapImage.isNull()) // might still be null, e.g. if data is empty, so check here again
25472   {
25473     bool mirrorX = (keyAxis()->orientation() == Qt::Horizontal ? keyAxis() : valueAxis())->rangeReversed();
25474     bool mirrorY = (valueAxis()->orientation() == Qt::Vertical ? valueAxis() : keyAxis())->rangeReversed();
25475     mLegendIcon = QPixmap::fromImage(mMapImage.mirrored(mirrorX, mirrorY)).scaled(thumbSize, Qt::KeepAspectRatio, transformMode);
25476   }
25477 }
25478 
25479 /* inherits documentation from base class */
selectTest(const QPointF & pos,bool onlySelectable,QVariant * details) const25480 double QCPColorMap::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
25481 {
25482   Q_UNUSED(details)
25483   if ((onlySelectable && mSelectable == QCP::stNone) || mMapData->isEmpty())
25484     return -1;
25485   if (!mKeyAxis || !mValueAxis)
25486     return -1;
25487 
25488   if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()))
25489   {
25490     double posKey, posValue;
25491     pixelsToCoords(pos, posKey, posValue);
25492     if (mMapData->keyRange().contains(posKey) && mMapData->valueRange().contains(posValue))
25493     {
25494       if (details)
25495         details->setValue(QCPDataSelection(QCPDataRange(0, 1))); // temporary solution, to facilitate whole-plottable selection. Replace in future version with segmented 2D selection.
25496       return mParentPlot->selectionTolerance()*0.99;
25497     }
25498   }
25499   return -1;
25500 }
25501 
25502 /* inherits documentation from base class */
getKeyRange(bool & foundRange,QCP::SignDomain inSignDomain) const25503 QCPRange QCPColorMap::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const
25504 {
25505   foundRange = true;
25506   QCPRange result = mMapData->keyRange();
25507   result.normalize();
25508   if (inSignDomain == QCP::sdPositive)
25509   {
25510     if (result.lower <= 0 && result.upper > 0)
25511       result.lower = result.upper*1e-3;
25512     else if (result.lower <= 0 && result.upper <= 0)
25513       foundRange = false;
25514   } else if (inSignDomain == QCP::sdNegative)
25515   {
25516     if (result.upper >= 0 && result.lower < 0)
25517       result.upper = result.lower*1e-3;
25518     else if (result.upper >= 0 && result.lower >= 0)
25519       foundRange = false;
25520   }
25521   return result;
25522 }
25523 
25524 /* inherits documentation from base class */
getValueRange(bool & foundRange,QCP::SignDomain inSignDomain,const QCPRange & inKeyRange) const25525 QCPRange QCPColorMap::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const
25526 {
25527   if (inKeyRange != QCPRange())
25528   {
25529     if (mMapData->keyRange().upper < inKeyRange.lower || mMapData->keyRange().lower > inKeyRange.upper)
25530     {
25531       foundRange = false;
25532       return QCPRange();
25533     }
25534   }
25535 
25536   foundRange = true;
25537   QCPRange result = mMapData->valueRange();
25538   result.normalize();
25539   if (inSignDomain == QCP::sdPositive)
25540   {
25541     if (result.lower <= 0 && result.upper > 0)
25542       result.lower = result.upper*1e-3;
25543     else if (result.lower <= 0 && result.upper <= 0)
25544       foundRange = false;
25545   } else if (inSignDomain == QCP::sdNegative)
25546   {
25547     if (result.upper >= 0 && result.lower < 0)
25548       result.upper = result.lower*1e-3;
25549     else if (result.upper >= 0 && result.lower >= 0)
25550       foundRange = false;
25551   }
25552   return result;
25553 }
25554 
25555 /*! \internal
25556 
25557   Updates the internal map image buffer by going through the internal \ref QCPColorMapData and
25558   turning the data values into color pixels with \ref QCPColorGradient::colorize.
25559 
25560   This method is called by \ref QCPColorMap::draw if either the data has been modified or the map image
25561   has been invalidated for a different reason (e.g. a change of the data range with \ref
25562   setDataRange).
25563 
25564   If the map cell count is low, the image created will be oversampled in order to avoid a
25565   QPainter::drawImage bug which makes inner pixel boundaries jitter when stretch-drawing images
25566   without smooth transform enabled. Accordingly, oversampling isn't performed if \ref
25567   setInterpolate is true.
25568 */
updateMapImage()25569 void QCPColorMap::updateMapImage()
25570 {
25571   QCPAxis *keyAxis = mKeyAxis.data();
25572   if (!keyAxis) return;
25573   if (mMapData->isEmpty()) return;
25574 
25575   const QImage::Format format = QImage::Format_ARGB32_Premultiplied;
25576   const int keySize = mMapData->keySize();
25577   const int valueSize = mMapData->valueSize();
25578   int keyOversamplingFactor = mInterpolate ? 1 : (int)(1.0+100.0/(double)keySize); // make mMapImage have at least size 100, factor becomes 1 if size > 200 or interpolation is on
25579   int valueOversamplingFactor = mInterpolate ? 1 : (int)(1.0+100.0/(double)valueSize); // make mMapImage have at least size 100, factor becomes 1 if size > 200 or interpolation is on
25580 
25581   // resize mMapImage to correct dimensions including possible oversampling factors, according to key/value axes orientation:
25582   if (keyAxis->orientation() == Qt::Horizontal && (mMapImage.width() != keySize*keyOversamplingFactor || mMapImage.height() != valueSize*valueOversamplingFactor))
25583     mMapImage = QImage(QSize(keySize*keyOversamplingFactor, valueSize*valueOversamplingFactor), format);
25584   else if (keyAxis->orientation() == Qt::Vertical && (mMapImage.width() != valueSize*valueOversamplingFactor || mMapImage.height() != keySize*keyOversamplingFactor))
25585     mMapImage = QImage(QSize(valueSize*valueOversamplingFactor, keySize*keyOversamplingFactor), format);
25586 
25587   QImage *localMapImage = &mMapImage; // this is the image on which the colorization operates. Either the final mMapImage, or if we need oversampling, mUndersampledMapImage
25588   if (keyOversamplingFactor > 1 || valueOversamplingFactor > 1)
25589   {
25590     // resize undersampled map image to actual key/value cell sizes:
25591     if (keyAxis->orientation() == Qt::Horizontal && (mUndersampledMapImage.width() != keySize || mUndersampledMapImage.height() != valueSize))
25592       mUndersampledMapImage = QImage(QSize(keySize, valueSize), format);
25593     else if (keyAxis->orientation() == Qt::Vertical && (mUndersampledMapImage.width() != valueSize || mUndersampledMapImage.height() != keySize))
25594       mUndersampledMapImage = QImage(QSize(valueSize, keySize), format);
25595     localMapImage = &mUndersampledMapImage; // make the colorization run on the undersampled image
25596   } else if (!mUndersampledMapImage.isNull())
25597     mUndersampledMapImage = QImage(); // don't need oversampling mechanism anymore (map size has changed) but mUndersampledMapImage still has nonzero size, free it
25598 
25599   const double *rawData = mMapData->mData;
25600   const unsigned char *rawAlpha = mMapData->mAlpha;
25601   if (keyAxis->orientation() == Qt::Horizontal)
25602   {
25603     const int lineCount = valueSize;
25604     const int rowCount = keySize;
25605     for (int line=0; line<lineCount; ++line)
25606     {
25607       QRgb* pixels = reinterpret_cast<QRgb*>(localMapImage->scanLine(lineCount-1-line)); // invert scanline index because QImage counts scanlines from top, but our vertical index counts from bottom (mathematical coordinate system)
25608       if (rawAlpha)
25609         mGradient.colorize(rawData+line*rowCount, rawAlpha+line*rowCount, mDataRange, pixels, rowCount, 1, mDataScaleType==QCPAxis::stLogarithmic);
25610       else
25611         mGradient.colorize(rawData+line*rowCount, mDataRange, pixels, rowCount, 1, mDataScaleType==QCPAxis::stLogarithmic);
25612     }
25613   } else // keyAxis->orientation() == Qt::Vertical
25614   {
25615     const int lineCount = keySize;
25616     const int rowCount = valueSize;
25617     for (int line=0; line<lineCount; ++line)
25618     {
25619       QRgb* pixels = reinterpret_cast<QRgb*>(localMapImage->scanLine(lineCount-1-line)); // invert scanline index because QImage counts scanlines from top, but our vertical index counts from bottom (mathematical coordinate system)
25620       if (rawAlpha)
25621         mGradient.colorize(rawData+line, rawAlpha+line, mDataRange, pixels, rowCount, lineCount, mDataScaleType==QCPAxis::stLogarithmic);
25622       else
25623         mGradient.colorize(rawData+line, mDataRange, pixels, rowCount, lineCount, mDataScaleType==QCPAxis::stLogarithmic);
25624     }
25625   }
25626 
25627   if (keyOversamplingFactor > 1 || valueOversamplingFactor > 1)
25628   {
25629     if (keyAxis->orientation() == Qt::Horizontal)
25630       mMapImage = mUndersampledMapImage.scaled(keySize*keyOversamplingFactor, valueSize*valueOversamplingFactor, Qt::IgnoreAspectRatio, Qt::FastTransformation);
25631     else
25632       mMapImage = mUndersampledMapImage.scaled(valueSize*valueOversamplingFactor, keySize*keyOversamplingFactor, Qt::IgnoreAspectRatio, Qt::FastTransformation);
25633   }
25634   mMapData->mDataModified = false;
25635   mMapImageInvalidated = false;
25636 }
25637 
25638 /* inherits documentation from base class */
draw(QCPPainter * painter)25639 void QCPColorMap::draw(QCPPainter *painter)
25640 {
25641   if (mMapData->isEmpty()) return;
25642   if (!mKeyAxis || !mValueAxis) return;
25643   applyDefaultAntialiasingHint(painter);
25644 
25645   if (mMapData->mDataModified || mMapImageInvalidated)
25646     updateMapImage();
25647 
25648   // use buffer if painting vectorized (PDF):
25649   const bool useBuffer = painter->modes().testFlag(QCPPainter::pmVectorized);
25650   QCPPainter *localPainter = painter; // will be redirected to paint on mapBuffer if painting vectorized
25651   QRectF mapBufferTarget; // the rect in absolute widget coordinates where the visible map portion/buffer will end up in
25652   QPixmap mapBuffer;
25653   if (useBuffer)
25654   {
25655     const double mapBufferPixelRatio = 3; // factor by which DPI is increased in embedded bitmaps
25656     mapBufferTarget = painter->clipRegion().boundingRect();
25657     mapBuffer = QPixmap((mapBufferTarget.size()*mapBufferPixelRatio).toSize());
25658     mapBuffer.fill(Qt::transparent);
25659     localPainter = new QCPPainter(&mapBuffer);
25660     localPainter->scale(mapBufferPixelRatio, mapBufferPixelRatio);
25661     localPainter->translate(-mapBufferTarget.topLeft());
25662   }
25663 
25664   QRectF imageRect = QRectF(coordsToPixels(mMapData->keyRange().lower, mMapData->valueRange().lower),
25665                             coordsToPixels(mMapData->keyRange().upper, mMapData->valueRange().upper)).normalized();
25666   // extend imageRect to contain outer halves/quarters of bordering/cornering pixels (cells are centered on map range boundary):
25667   double halfCellWidth = 0; // in pixels
25668   double halfCellHeight = 0; // in pixels
25669   if (keyAxis()->orientation() == Qt::Horizontal)
25670   {
25671     if (mMapData->keySize() > 1)
25672       halfCellWidth = 0.5*imageRect.width()/(double)(mMapData->keySize()-1);
25673     if (mMapData->valueSize() > 1)
25674       halfCellHeight = 0.5*imageRect.height()/(double)(mMapData->valueSize()-1);
25675   } else // keyAxis orientation is Qt::Vertical
25676   {
25677     if (mMapData->keySize() > 1)
25678       halfCellHeight = 0.5*imageRect.height()/(double)(mMapData->keySize()-1);
25679     if (mMapData->valueSize() > 1)
25680       halfCellWidth = 0.5*imageRect.width()/(double)(mMapData->valueSize()-1);
25681   }
25682   imageRect.adjust(-halfCellWidth, -halfCellHeight, halfCellWidth, halfCellHeight);
25683   const bool mirrorX = (keyAxis()->orientation() == Qt::Horizontal ? keyAxis() : valueAxis())->rangeReversed();
25684   const bool mirrorY = (valueAxis()->orientation() == Qt::Vertical ? valueAxis() : keyAxis())->rangeReversed();
25685   const bool smoothBackup = localPainter->renderHints().testFlag(QPainter::SmoothPixmapTransform);
25686   localPainter->setRenderHint(QPainter::SmoothPixmapTransform, mInterpolate);
25687   QRegion clipBackup;
25688   if (mTightBoundary)
25689   {
25690     clipBackup = localPainter->clipRegion();
25691     QRectF tightClipRect = QRectF(coordsToPixels(mMapData->keyRange().lower, mMapData->valueRange().lower),
25692                                   coordsToPixels(mMapData->keyRange().upper, mMapData->valueRange().upper)).normalized();
25693     localPainter->setClipRect(tightClipRect, Qt::IntersectClip);
25694   }
25695   localPainter->drawImage(imageRect, mMapImage.mirrored(mirrorX, mirrorY));
25696   if (mTightBoundary)
25697     localPainter->setClipRegion(clipBackup);
25698   localPainter->setRenderHint(QPainter::SmoothPixmapTransform, smoothBackup);
25699 
25700   if (useBuffer) // localPainter painted to mapBuffer, so now draw buffer with original painter
25701   {
25702     delete localPainter;
25703     painter->drawPixmap(mapBufferTarget.toRect(), mapBuffer);
25704   }
25705 }
25706 
25707 /* inherits documentation from base class */
drawLegendIcon(QCPPainter * painter,const QRectF & rect) const25708 void QCPColorMap::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
25709 {
25710   applyDefaultAntialiasingHint(painter);
25711   // draw map thumbnail:
25712   if (!mLegendIcon.isNull())
25713   {
25714     QPixmap scaledIcon = mLegendIcon.scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::FastTransformation);
25715     QRectF iconRect = QRectF(0, 0, scaledIcon.width(), scaledIcon.height());
25716     iconRect.moveCenter(rect.center());
25717     painter->drawPixmap(iconRect.topLeft(), scaledIcon);
25718   }
25719   /*
25720   // draw frame:
25721   painter->setBrush(Qt::NoBrush);
25722   painter->setPen(Qt::black);
25723   painter->drawRect(rect.adjusted(1, 1, 0, 0));
25724   */
25725 }
25726 /* end of 'src/plottables/plottable-colormap.cpp' */
25727 
25728 
25729 /* including file 'src/plottables/plottable-financial.cpp', size 42610       */
25730 /* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
25731 
25732 ////////////////////////////////////////////////////////////////////////////////////////////////////
25733 //////////////////// QCPFinancialData
25734 ////////////////////////////////////////////////////////////////////////////////////////////////////
25735 
25736 /*! \class QCPFinancialData
25737   \brief Holds the data of one single data point for QCPFinancial.
25738 
25739   The stored data is:
25740   \li \a key: coordinate on the key axis of this data point (this is the \a mainKey and the \a sortKey)
25741   \li \a open: The opening value at the data point (this is the \a mainValue)
25742   \li \a high: The high/maximum value at the data point
25743   \li \a low: The low/minimum value at the data point
25744   \li \a close: The closing value at the data point
25745 
25746   The container for storing multiple data points is \ref QCPFinancialDataContainer. It is a typedef
25747   for \ref QCPDataContainer with \ref QCPFinancialData as the DataType template parameter. See the
25748   documentation there for an explanation regarding the data type's generic methods.
25749 
25750   \see QCPFinancialDataContainer
25751 */
25752 
25753 /* start documentation of inline functions */
25754 
25755 /*! \fn double QCPFinancialData::sortKey() const
25756 
25757   Returns the \a key member of this data point.
25758 
25759   For a general explanation of what this method is good for in the context of the data container,
25760   see the documentation of \ref QCPDataContainer.
25761 */
25762 
25763 /*! \fn static QCPFinancialData QCPFinancialData::fromSortKey(double sortKey)
25764 
25765   Returns a data point with the specified \a sortKey. All other members are set to zero.
25766 
25767   For a general explanation of what this method is good for in the context of the data container,
25768   see the documentation of \ref QCPDataContainer.
25769 */
25770 
25771 /*! \fn static static bool QCPFinancialData::sortKeyIsMainKey()
25772 
25773   Since the member \a key is both the data point key coordinate and the data ordering parameter,
25774   this method returns true.
25775 
25776   For a general explanation of what this method is good for in the context of the data container,
25777   see the documentation of \ref QCPDataContainer.
25778 */
25779 
25780 /*! \fn double QCPFinancialData::mainKey() const
25781 
25782   Returns the \a key member of this data point.
25783 
25784   For a general explanation of what this method is good for in the context of the data container,
25785   see the documentation of \ref QCPDataContainer.
25786 */
25787 
25788 /*! \fn double QCPFinancialData::mainValue() const
25789 
25790   Returns the \a open member of this data point.
25791 
25792   For a general explanation of what this method is good for in the context of the data container,
25793   see the documentation of \ref QCPDataContainer.
25794 */
25795 
25796 /*! \fn QCPRange QCPFinancialData::valueRange() const
25797 
25798   Returns a QCPRange spanning from the \a low to the \a high value of this data point.
25799 
25800   For a general explanation of what this method is good for in the context of the data container,
25801   see the documentation of \ref QCPDataContainer.
25802 */
25803 
25804 /* end documentation of inline functions */
25805 
25806 /*!
25807   Constructs a data point with key and all values set to zero.
25808 */
QCPFinancialData()25809 QCPFinancialData::QCPFinancialData() :
25810   key(0),
25811   open(0),
25812   high(0),
25813   low(0),
25814   close(0)
25815 {
25816 }
25817 
25818 /*!
25819   Constructs a data point with the specified \a key and OHLC values.
25820 */
QCPFinancialData(double key,double open,double high,double low,double close)25821 QCPFinancialData::QCPFinancialData(double key, double open, double high, double low, double close) :
25822   key(key),
25823   open(open),
25824   high(high),
25825   low(low),
25826   close(close)
25827 {
25828 }
25829 
25830 
25831 ////////////////////////////////////////////////////////////////////////////////////////////////////
25832 //////////////////// QCPFinancial
25833 ////////////////////////////////////////////////////////////////////////////////////////////////////
25834 
25835 /*! \class QCPFinancial
25836   \brief A plottable representing a financial stock chart
25837 
25838   \image html QCPFinancial.png
25839 
25840   This plottable represents time series data binned to certain intervals, mainly used for stock
25841   charts. The two common representations OHLC (Open-High-Low-Close) bars and Candlesticks can be
25842   set via \ref setChartStyle.
25843 
25844   The data is passed via \ref setData as a set of open/high/low/close values at certain keys
25845   (typically times). This means the data must be already binned appropriately. If data is only
25846   available as a series of values (e.g. \a price against \a time), you can use the static
25847   convenience function \ref timeSeriesToOhlc to generate binned OHLC-data which can then be passed
25848   to \ref setData.
25849 
25850   The width of the OHLC bars/candlesticks can be controlled with \ref setWidth and \ref
25851   setWidthType. A typical choice is to set the width type to \ref wtPlotCoords (the default) and
25852   the width to (or slightly less than) one time bin interval width.
25853 
25854   \section qcpfinancial-appearance Changing the appearance
25855 
25856   Charts can be either single- or two-colored (\ref setTwoColored). If set to be single-colored,
25857   lines are drawn with the plottable's pen (\ref setPen) and fills with the brush (\ref setBrush).
25858 
25859   If set to two-colored, positive changes of the value during an interval (\a close >= \a open) are
25860   represented with a different pen and brush than negative changes (\a close < \a open). These can
25861   be configured with \ref setPenPositive, \ref setPenNegative, \ref setBrushPositive, and \ref
25862   setBrushNegative. In two-colored mode, the normal plottable pen/brush is ignored. Upon selection
25863   however, the normal selected pen/brush (provided by the \ref selectionDecorator) is used,
25864   irrespective of whether the chart is single- or two-colored.
25865 
25866   \section qcpfinancial-usage Usage
25867 
25868   Like all data representing objects in QCustomPlot, the QCPFinancial is a plottable
25869   (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies
25870   (QCustomPlot::plottable, QCustomPlot::removePlottable, etc.)
25871 
25872   Usually, you first create an instance:
25873 
25874   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpfinancial-creation-1
25875   which registers it with the QCustomPlot instance of the passed axes. Note that this QCustomPlot
25876   instance takes ownership of the plottable, so do not delete it manually but use
25877   QCustomPlot::removePlottable() instead. The newly created plottable can be modified, e.g.:
25878 
25879   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpfinancial-creation-2
25880   Here we have used the static helper method \ref timeSeriesToOhlc, to turn a time-price data
25881   series into a 24-hour binned open-high-low-close data series as QCPFinancial uses.
25882 */
25883 
25884 /* start of documentation of inline functions */
25885 
25886 /*! \fn QCPFinancialDataContainer *QCPFinancial::data() const
25887 
25888   Returns a pointer to the internal data storage of type \ref QCPFinancialDataContainer. You may
25889   use it to directly manipulate the data, which may be more convenient and faster than using the
25890   regular \ref setData or \ref addData methods, in certain situations.
25891 */
25892 
25893 /* end of documentation of inline functions */
25894 
25895 /*!
25896   Constructs a financial chart which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value
25897   axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have
25898   the same orientation. If either of these restrictions is violated, a corresponding message is
25899   printed to the debug output (qDebug), the construction is not aborted, though.
25900 
25901   The created QCPFinancial is automatically registered with the QCustomPlot instance inferred from \a
25902   keyAxis. This QCustomPlot instance takes ownership of the QCPFinancial, so do not delete it manually
25903   but use QCustomPlot::removePlottable() instead.
25904 */
QCPFinancial(QCPAxis * keyAxis,QCPAxis * valueAxis)25905 QCPFinancial::QCPFinancial(QCPAxis *keyAxis, QCPAxis *valueAxis) :
25906   QCPAbstractPlottable1D<QCPFinancialData>(keyAxis, valueAxis),
25907   mChartStyle(csCandlestick),
25908   mWidth(0.5),
25909   mWidthType(wtPlotCoords),
25910   mTwoColored(true),
25911   mBrushPositive(QBrush(QColor(50, 160, 0))),
25912   mBrushNegative(QBrush(QColor(180, 0, 15))),
25913   mPenPositive(QPen(QColor(40, 150, 0))),
25914   mPenNegative(QPen(QColor(170, 5, 5)))
25915 {
25916   mSelectionDecorator->setBrush(QBrush(QColor(160, 160, 255)));
25917 }
25918 
~QCPFinancial()25919 QCPFinancial::~QCPFinancial()
25920 {
25921 }
25922 
25923 /*! \overload
25924 
25925   Replaces the current data container with the provided \a data container.
25926 
25927   Since a QSharedPointer is used, multiple QCPFinancials may share the same data container safely.
25928   Modifying the data in the container will then affect all financials that share the container.
25929   Sharing can be achieved by simply exchanging the data containers wrapped in shared pointers:
25930   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpfinancial-datasharing-1
25931 
25932   If you do not wish to share containers, but create a copy from an existing container, rather use
25933   the \ref QCPDataContainer<DataType>::set method on the financial's data container directly:
25934   \snippet documentation/doc-code-snippets/mainwindow.cpp qcpfinancial-datasharing-2
25935 
25936   \see addData, timeSeriesToOhlc
25937 */
setData(QSharedPointer<QCPFinancialDataContainer> data)25938 void QCPFinancial::setData(QSharedPointer<QCPFinancialDataContainer> data)
25939 {
25940   mDataContainer = data;
25941 }
25942 
25943 /*! \overload
25944 
25945   Replaces the current data with the provided points in \a keys, \a open, \a high, \a low and \a
25946   close. The provided vectors should have equal length. Else, the number of added points will be
25947   the size of the smallest vector.
25948 
25949   If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
25950   can set \a alreadySorted to true, to improve performance by saving a sorting run.
25951 
25952   \see addData, timeSeriesToOhlc
25953 */
setData(const QVector<double> & keys,const QVector<double> & open,const QVector<double> & high,const QVector<double> & low,const QVector<double> & close,bool alreadySorted)25954 void QCPFinancial::setData(const QVector<double> &keys, const QVector<double> &open, const QVector<double> &high, const QVector<double> &low, const QVector<double> &close, bool alreadySorted)
25955 {
25956   mDataContainer->clear();
25957   addData(keys, open, high, low, close, alreadySorted);
25958 }
25959 
25960 /*!
25961   Sets which representation style shall be used to display the OHLC data.
25962 */
setChartStyle(QCPFinancial::ChartStyle style)25963 void QCPFinancial::setChartStyle(QCPFinancial::ChartStyle style)
25964 {
25965   mChartStyle = style;
25966 }
25967 
25968 /*!
25969   Sets the width of the individual bars/candlesticks to \a width in plot key coordinates.
25970 
25971   A typical choice is to set it to (or slightly less than) one bin interval width.
25972 */
setWidth(double width)25973 void QCPFinancial::setWidth(double width)
25974 {
25975   mWidth = width;
25976 }
25977 
25978 /*!
25979   Sets how the width of the financial bars is defined. See the documentation of \ref WidthType for
25980   an explanation of the possible values for \a widthType.
25981 
25982   The default value is \ref wtPlotCoords.
25983 
25984   \see setWidth
25985 */
setWidthType(QCPFinancial::WidthType widthType)25986 void QCPFinancial::setWidthType(QCPFinancial::WidthType widthType)
25987 {
25988   mWidthType = widthType;
25989 }
25990 
25991 /*!
25992   Sets whether this chart shall contrast positive from negative trends per data point by using two
25993   separate colors to draw the respective bars/candlesticks.
25994 
25995   If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref
25996   setBrush).
25997 
25998   \see setPenPositive, setPenNegative, setBrushPositive, setBrushNegative
25999 */
setTwoColored(bool twoColored)26000 void QCPFinancial::setTwoColored(bool twoColored)
26001 {
26002   mTwoColored = twoColored;
26003 }
26004 
26005 /*!
26006   If \ref setTwoColored is set to true, this function controls the brush that is used to draw fills
26007   of data points with a positive trend (i.e. bars/candlesticks with close >= open).
26008 
26009   If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref
26010   setBrush).
26011 
26012   \see setBrushNegative, setPenPositive, setPenNegative
26013 */
setBrushPositive(const QBrush & brush)26014 void QCPFinancial::setBrushPositive(const QBrush &brush)
26015 {
26016   mBrushPositive = brush;
26017 }
26018 
26019 /*!
26020   If \ref setTwoColored is set to true, this function controls the brush that is used to draw fills
26021   of data points with a negative trend (i.e. bars/candlesticks with close < open).
26022 
26023   If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref
26024   setBrush).
26025 
26026   \see setBrushPositive, setPenNegative, setPenPositive
26027 */
setBrushNegative(const QBrush & brush)26028 void QCPFinancial::setBrushNegative(const QBrush &brush)
26029 {
26030   mBrushNegative = brush;
26031 }
26032 
26033 /*!
26034   If \ref setTwoColored is set to true, this function controls the pen that is used to draw
26035   outlines of data points with a positive trend (i.e. bars/candlesticks with close >= open).
26036 
26037   If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref
26038   setBrush).
26039 
26040   \see setPenNegative, setBrushPositive, setBrushNegative
26041 */
setPenPositive(const QPen & pen)26042 void QCPFinancial::setPenPositive(const QPen &pen)
26043 {
26044   mPenPositive = pen;
26045 }
26046 
26047 /*!
26048   If \ref setTwoColored is set to true, this function controls the pen that is used to draw
26049   outlines of data points with a negative trend (i.e. bars/candlesticks with close < open).
26050 
26051   If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref
26052   setBrush).
26053 
26054   \see setPenPositive, setBrushNegative, setBrushPositive
26055 */
setPenNegative(const QPen & pen)26056 void QCPFinancial::setPenNegative(const QPen &pen)
26057 {
26058   mPenNegative = pen;
26059 }
26060 
26061 /*! \overload
26062 
26063   Adds the provided points in \a keys, \a open, \a high, \a low and \a close to the current data.
26064   The provided vectors should have equal length. Else, the number of added points will be the size
26065   of the smallest vector.
26066 
26067   If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
26068   can set \a alreadySorted to true, to improve performance by saving a sorting run.
26069 
26070   Alternatively, you can also access and modify the data directly via the \ref data method, which
26071   returns a pointer to the internal data container.
26072 
26073   \see timeSeriesToOhlc
26074 */
addData(const QVector<double> & keys,const QVector<double> & open,const QVector<double> & high,const QVector<double> & low,const QVector<double> & close,bool alreadySorted)26075 void QCPFinancial::addData(const QVector<double> &keys, const QVector<double> &open, const QVector<double> &high, const QVector<double> &low, const QVector<double> &close, bool alreadySorted)
26076 {
26077   if (keys.size() != open.size() || open.size() != high.size() || high.size() != low.size() || low.size() != close.size() || close.size() != keys.size())
26078     qDebug() << Q_FUNC_INFO << "keys, open, high, low, close have different sizes:" << keys.size() << open.size() << high.size() << low.size() << close.size();
26079   const int n = qMin(keys.size(), qMin(open.size(), qMin(high.size(), qMin(low.size(), close.size()))));
26080   QVector<QCPFinancialData> tempData(n);
26081   QVector<QCPFinancialData>::iterator it = tempData.begin();
26082   const QVector<QCPFinancialData>::iterator itEnd = tempData.end();
26083   int i = 0;
26084   while (it != itEnd)
26085   {
26086     it->key = keys[i];
26087     it->open = open[i];
26088     it->high = high[i];
26089     it->low = low[i];
26090     it->close = close[i];
26091     ++it;
26092     ++i;
26093   }
26094   mDataContainer->add(tempData, alreadySorted); // don't modify tempData beyond this to prevent copy on write
26095 }
26096 
26097 /*! \overload
26098 
26099   Adds the provided data point as \a key, \a open, \a high, \a low and \a close to the current
26100   data.
26101 
26102   Alternatively, you can also access and modify the data directly via the \ref data method, which
26103   returns a pointer to the internal data container.
26104 
26105   \see timeSeriesToOhlc
26106 */
addData(double key,double open,double high,double low,double close)26107 void QCPFinancial::addData(double key, double open, double high, double low, double close)
26108 {
26109   mDataContainer->add(QCPFinancialData(key, open, high, low, close));
26110 }
26111 
26112 /*!
26113   \copydoc QCPPlottableInterface1D::selectTestRect
26114 */
selectTestRect(const QRectF & rect,bool onlySelectable) const26115 QCPDataSelection QCPFinancial::selectTestRect(const QRectF &rect, bool onlySelectable) const
26116 {
26117   QCPDataSelection result;
26118   if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
26119     return result;
26120   if (!mKeyAxis || !mValueAxis)
26121     return result;
26122 
26123   QCPFinancialDataContainer::const_iterator visibleBegin, visibleEnd;
26124   getVisibleDataBounds(visibleBegin, visibleEnd);
26125 
26126   for (QCPFinancialDataContainer::const_iterator it=visibleBegin; it!=visibleEnd; ++it)
26127   {
26128     if (rect.intersects(selectionHitBox(it)))
26129       result.addDataRange(QCPDataRange(it-mDataContainer->constBegin(), it-mDataContainer->constBegin()+1), false);
26130   }
26131   result.simplify();
26132   return result;
26133 }
26134 
26135 /* inherits documentation from base class */
selectTest(const QPointF & pos,bool onlySelectable,QVariant * details) const26136 double QCPFinancial::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
26137 {
26138   Q_UNUSED(details)
26139   if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
26140     return -1;
26141   if (!mKeyAxis || !mValueAxis)
26142     return -1;
26143 
26144   if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()))
26145   {
26146     // get visible data range:
26147     QCPFinancialDataContainer::const_iterator visibleBegin, visibleEnd;
26148     QCPFinancialDataContainer::const_iterator closestDataPoint = mDataContainer->constEnd();
26149     getVisibleDataBounds(visibleBegin, visibleEnd);
26150     // perform select test according to configured style:
26151     double result = -1;
26152     switch (mChartStyle)
26153     {
26154       case QCPFinancial::csOhlc:
26155         result = ohlcSelectTest(pos, visibleBegin, visibleEnd, closestDataPoint); break;
26156       case QCPFinancial::csCandlestick:
26157         result = candlestickSelectTest(pos, visibleBegin, visibleEnd, closestDataPoint); break;
26158     }
26159     if (details)
26160     {
26161       int pointIndex = closestDataPoint-mDataContainer->constBegin();
26162       details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1)));
26163     }
26164     return result;
26165   }
26166 
26167   return -1;
26168 }
26169 
26170 /* inherits documentation from base class */
getKeyRange(bool & foundRange,QCP::SignDomain inSignDomain) const26171 QCPRange QCPFinancial::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const
26172 {
26173   QCPRange range = mDataContainer->keyRange(foundRange, inSignDomain);
26174   // determine exact range by including width of bars/flags:
26175   if (foundRange)
26176   {
26177     if (inSignDomain != QCP::sdPositive || range.lower-mWidth*0.5 > 0)
26178       range.lower -= mWidth*0.5;
26179     if (inSignDomain != QCP::sdNegative || range.upper+mWidth*0.5 < 0)
26180       range.upper += mWidth*0.5;
26181   }
26182   return range;
26183 }
26184 
26185 /* inherits documentation from base class */
getValueRange(bool & foundRange,QCP::SignDomain inSignDomain,const QCPRange & inKeyRange) const26186 QCPRange QCPFinancial::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const
26187 {
26188   return mDataContainer->valueRange(foundRange, inSignDomain, inKeyRange);
26189 }
26190 
26191 /*!
26192   A convenience function that converts time series data (\a value against \a time) to OHLC binned
26193   data points. The return value can then be passed on to \ref QCPFinancialDataContainer::set(const
26194   QCPFinancialDataContainer&).
26195 
26196   The size of the bins can be controlled with \a timeBinSize in the same units as \a time is given.
26197   For example, if the unit of \a time is seconds and single OHLC/Candlesticks should span an hour
26198   each, set \a timeBinSize to 3600.
26199 
26200   \a timeBinOffset allows to control precisely at what \a time coordinate a bin should start. The
26201   value passed as \a timeBinOffset doesn't need to be in the range encompassed by the \a time keys.
26202   It merely defines the mathematical offset/phase of the bins that will be used to process the
26203   data.
26204 */
timeSeriesToOhlc(const QVector<double> & time,const QVector<double> & value,double timeBinSize,double timeBinOffset)26205 QCPFinancialDataContainer QCPFinancial::timeSeriesToOhlc(const QVector<double> &time, const QVector<double> &value, double timeBinSize, double timeBinOffset)
26206 {
26207   QCPFinancialDataContainer data;
26208   int count = qMin(time.size(), value.size());
26209   if (count == 0)
26210     return QCPFinancialDataContainer();
26211 
26212   QCPFinancialData currentBinData(0, value.first(), value.first(), value.first(), value.first());
26213   int currentBinIndex = qFloor((time.first()-timeBinOffset)/timeBinSize+0.5);
26214   for (int i=0; i<count; ++i)
26215   {
26216     int index = qFloor((time.at(i)-timeBinOffset)/timeBinSize+0.5);
26217     if (currentBinIndex == index) // data point still in current bin, extend high/low:
26218     {
26219       if (value.at(i) < currentBinData.low) currentBinData.low = value.at(i);
26220       if (value.at(i) > currentBinData.high) currentBinData.high = value.at(i);
26221       if (i == count-1) // last data point is in current bin, finalize bin:
26222       {
26223         currentBinData.close = value.at(i);
26224         currentBinData.key = timeBinOffset+(index)*timeBinSize;
26225         data.add(currentBinData);
26226       }
26227     } else // data point not anymore in current bin, set close of old and open of new bin, and add old to map:
26228     {
26229       // finalize current bin:
26230       currentBinData.close = value.at(i-1);
26231       currentBinData.key = timeBinOffset+(index-1)*timeBinSize;
26232       data.add(currentBinData);
26233       // start next bin:
26234       currentBinIndex = index;
26235       currentBinData.open = value.at(i);
26236       currentBinData.high = value.at(i);
26237       currentBinData.low = value.at(i);
26238     }
26239   }
26240 
26241   return data;
26242 }
26243 
26244 /* inherits documentation from base class */
draw(QCPPainter * painter)26245 void QCPFinancial::draw(QCPPainter *painter)
26246 {
26247   // get visible data range:
26248   QCPFinancialDataContainer::const_iterator visibleBegin, visibleEnd;
26249   getVisibleDataBounds(visibleBegin, visibleEnd);
26250 
26251   // loop over and draw segments of unselected/selected data:
26252   QList<QCPDataRange> selectedSegments, unselectedSegments, allSegments;
26253   getDataSegments(selectedSegments, unselectedSegments);
26254   allSegments << unselectedSegments << selectedSegments;
26255   for (int i=0; i<allSegments.size(); ++i)
26256   {
26257     bool isSelectedSegment = i >= unselectedSegments.size();
26258     QCPFinancialDataContainer::const_iterator begin = visibleBegin;
26259     QCPFinancialDataContainer::const_iterator end = visibleEnd;
26260     mDataContainer->limitIteratorsToDataRange(begin, end, allSegments.at(i));
26261     if (begin == end)
26262       continue;
26263 
26264     // draw data segment according to configured style:
26265     switch (mChartStyle)
26266     {
26267       case QCPFinancial::csOhlc:
26268         drawOhlcPlot(painter, begin, end, isSelectedSegment); break;
26269       case QCPFinancial::csCandlestick:
26270         drawCandlestickPlot(painter, begin, end, isSelectedSegment); break;
26271     }
26272   }
26273 
26274   // draw other selection decoration that isn't just line/scatter pens and brushes:
26275   if (mSelectionDecorator)
26276     mSelectionDecorator->drawDecoration(painter, selection());
26277 }
26278 
26279 /* inherits documentation from base class */
drawLegendIcon(QCPPainter * painter,const QRectF & rect) const26280 void QCPFinancial::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
26281 {
26282   painter->setAntialiasing(false); // legend icon especially of csCandlestick looks better without antialiasing
26283   if (mChartStyle == csOhlc)
26284   {
26285     if (mTwoColored)
26286     {
26287       // draw upper left half icon with positive color:
26288       painter->setBrush(mBrushPositive);
26289       painter->setPen(mPenPositive);
26290       painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.topLeft().toPoint()));
26291       painter->drawLine(QLineF(0, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft()));
26292       painter->drawLine(QLineF(rect.width()*0.2, rect.height()*0.3, rect.width()*0.2, rect.height()*0.5).translated(rect.topLeft()));
26293       painter->drawLine(QLineF(rect.width()*0.8, rect.height()*0.5, rect.width()*0.8, rect.height()*0.7).translated(rect.topLeft()));
26294       // draw bottom right half icon with negative color:
26295       painter->setBrush(mBrushNegative);
26296       painter->setPen(mPenNegative);
26297       painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.bottomRight().toPoint()));
26298       painter->drawLine(QLineF(0, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft()));
26299       painter->drawLine(QLineF(rect.width()*0.2, rect.height()*0.3, rect.width()*0.2, rect.height()*0.5).translated(rect.topLeft()));
26300       painter->drawLine(QLineF(rect.width()*0.8, rect.height()*0.5, rect.width()*0.8, rect.height()*0.7).translated(rect.topLeft()));
26301     } else
26302     {
26303       painter->setBrush(mBrush);
26304       painter->setPen(mPen);
26305       painter->drawLine(QLineF(0, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft()));
26306       painter->drawLine(QLineF(rect.width()*0.2, rect.height()*0.3, rect.width()*0.2, rect.height()*0.5).translated(rect.topLeft()));
26307       painter->drawLine(QLineF(rect.width()*0.8, rect.height()*0.5, rect.width()*0.8, rect.height()*0.7).translated(rect.topLeft()));
26308     }
26309   } else if (mChartStyle == csCandlestick)
26310   {
26311     if (mTwoColored)
26312     {
26313       // draw upper left half icon with positive color:
26314       painter->setBrush(mBrushPositive);
26315       painter->setPen(mPenPositive);
26316       painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.topLeft().toPoint()));
26317       painter->drawLine(QLineF(0, rect.height()*0.5, rect.width()*0.25, rect.height()*0.5).translated(rect.topLeft()));
26318       painter->drawLine(QLineF(rect.width()*0.75, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft()));
26319       painter->drawRect(QRectF(rect.width()*0.25, rect.height()*0.25, rect.width()*0.5, rect.height()*0.5).translated(rect.topLeft()));
26320       // draw bottom right half icon with negative color:
26321       painter->setBrush(mBrushNegative);
26322       painter->setPen(mPenNegative);
26323       painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.bottomRight().toPoint()));
26324       painter->drawLine(QLineF(0, rect.height()*0.5, rect.width()*0.25, rect.height()*0.5).translated(rect.topLeft()));
26325       painter->drawLine(QLineF(rect.width()*0.75, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft()));
26326       painter->drawRect(QRectF(rect.width()*0.25, rect.height()*0.25, rect.width()*0.5, rect.height()*0.5).translated(rect.topLeft()));
26327     } else
26328     {
26329       painter->setBrush(mBrush);
26330       painter->setPen(mPen);
26331       painter->drawLine(QLineF(0, rect.height()*0.5, rect.width()*0.25, rect.height()*0.5).translated(rect.topLeft()));
26332       painter->drawLine(QLineF(rect.width()*0.75, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft()));
26333       painter->drawRect(QRectF(rect.width()*0.25, rect.height()*0.25, rect.width()*0.5, rect.height()*0.5).translated(rect.topLeft()));
26334     }
26335   }
26336 }
26337 
26338 /*! \internal
26339 
26340   Draws the data from \a begin to \a end-1 as OHLC bars with the provided \a painter.
26341 
26342   This method is a helper function for \ref draw. It is used when the chart style is \ref csOhlc.
26343 */
drawOhlcPlot(QCPPainter * painter,const QCPFinancialDataContainer::const_iterator & begin,const QCPFinancialDataContainer::const_iterator & end,bool isSelected)26344 void QCPFinancial::drawOhlcPlot(QCPPainter *painter, const QCPFinancialDataContainer::const_iterator &begin, const QCPFinancialDataContainer::const_iterator &end, bool isSelected)
26345 {
26346   QCPAxis *keyAxis = mKeyAxis.data();
26347   QCPAxis *valueAxis = mValueAxis.data();
26348   if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
26349 
26350   if (keyAxis->orientation() == Qt::Horizontal)
26351   {
26352     for (QCPFinancialDataContainer::const_iterator it = begin; it != end; ++it)
26353     {
26354       if (isSelected && mSelectionDecorator)
26355         mSelectionDecorator->applyPen(painter);
26356       else if (mTwoColored)
26357         painter->setPen(it->close >= it->open ? mPenPositive : mPenNegative);
26358       else
26359         painter->setPen(mPen);
26360       double keyPixel = keyAxis->coordToPixel(it->key);
26361       double openPixel = valueAxis->coordToPixel(it->open);
26362       double closePixel = valueAxis->coordToPixel(it->close);
26363       // draw backbone:
26364       painter->drawLine(QPointF(keyPixel, valueAxis->coordToPixel(it->high)), QPointF(keyPixel, valueAxis->coordToPixel(it->low)));
26365       // draw open:
26366       double pixelWidth = getPixelWidth(it->key, keyPixel); // sign of this makes sure open/close are on correct sides
26367       painter->drawLine(QPointF(keyPixel-pixelWidth, openPixel), QPointF(keyPixel, openPixel));
26368       // draw close:
26369       painter->drawLine(QPointF(keyPixel, closePixel), QPointF(keyPixel+pixelWidth, closePixel));
26370     }
26371   } else
26372   {
26373     for (QCPFinancialDataContainer::const_iterator it = begin; it != end; ++it)
26374     {
26375       if (isSelected && mSelectionDecorator)
26376         mSelectionDecorator->applyPen(painter);
26377       else if (mTwoColored)
26378         painter->setPen(it->close >= it->open ? mPenPositive : mPenNegative);
26379       else
26380         painter->setPen(mPen);
26381       double keyPixel = keyAxis->coordToPixel(it->key);
26382       double openPixel = valueAxis->coordToPixel(it->open);
26383       double closePixel = valueAxis->coordToPixel(it->close);
26384       // draw backbone:
26385       painter->drawLine(QPointF(valueAxis->coordToPixel(it->high), keyPixel), QPointF(valueAxis->coordToPixel(it->low), keyPixel));
26386       // draw open:
26387       double pixelWidth = getPixelWidth(it->key, keyPixel); // sign of this makes sure open/close are on correct sides
26388       painter->drawLine(QPointF(openPixel, keyPixel-pixelWidth), QPointF(openPixel, keyPixel));
26389       // draw close:
26390       painter->drawLine(QPointF(closePixel, keyPixel), QPointF(closePixel, keyPixel+pixelWidth));
26391     }
26392   }
26393 }
26394 
26395 /*! \internal
26396 
26397   Draws the data from \a begin to \a end-1 as Candlesticks with the provided \a painter.
26398 
26399   This method is a helper function for \ref draw. It is used when the chart style is \ref csCandlestick.
26400 */
drawCandlestickPlot(QCPPainter * painter,const QCPFinancialDataContainer::const_iterator & begin,const QCPFinancialDataContainer::const_iterator & end,bool isSelected)26401 void QCPFinancial::drawCandlestickPlot(QCPPainter *painter, const QCPFinancialDataContainer::const_iterator &begin, const QCPFinancialDataContainer::const_iterator &end, bool isSelected)
26402 {
26403   QCPAxis *keyAxis = mKeyAxis.data();
26404   QCPAxis *valueAxis = mValueAxis.data();
26405   if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
26406 
26407   if (keyAxis->orientation() == Qt::Horizontal)
26408   {
26409     for (QCPFinancialDataContainer::const_iterator it = begin; it != end; ++it)
26410     {
26411       if (isSelected && mSelectionDecorator)
26412       {
26413         mSelectionDecorator->applyPen(painter);
26414         mSelectionDecorator->applyBrush(painter);
26415       } else if (mTwoColored)
26416       {
26417         painter->setPen(it->close >= it->open ? mPenPositive : mPenNegative);
26418         painter->setBrush(it->close >= it->open ? mBrushPositive : mBrushNegative);
26419       } else
26420       {
26421         painter->setPen(mPen);
26422         painter->setBrush(mBrush);
26423       }
26424       double keyPixel = keyAxis->coordToPixel(it->key);
26425       double openPixel = valueAxis->coordToPixel(it->open);
26426       double closePixel = valueAxis->coordToPixel(it->close);
26427       // draw high:
26428       painter->drawLine(QPointF(keyPixel, valueAxis->coordToPixel(it->high)), QPointF(keyPixel, valueAxis->coordToPixel(qMax(it->open, it->close))));
26429       // draw low:
26430       painter->drawLine(QPointF(keyPixel, valueAxis->coordToPixel(it->low)), QPointF(keyPixel, valueAxis->coordToPixel(qMin(it->open, it->close))));
26431       // draw open-close box:
26432       double pixelWidth = getPixelWidth(it->key, keyPixel);
26433       painter->drawRect(QRectF(QPointF(keyPixel-pixelWidth, closePixel), QPointF(keyPixel+pixelWidth, openPixel)));
26434     }
26435   } else // keyAxis->orientation() == Qt::Vertical
26436   {
26437     for (QCPFinancialDataContainer::const_iterator it = begin; it != end; ++it)
26438     {
26439       if (isSelected && mSelectionDecorator)
26440       {
26441         mSelectionDecorator->applyPen(painter);
26442         mSelectionDecorator->applyBrush(painter);
26443       } else if (mTwoColored)
26444       {
26445         painter->setPen(it->close >= it->open ? mPenPositive : mPenNegative);
26446         painter->setBrush(it->close >= it->open ? mBrushPositive : mBrushNegative);
26447       } else
26448       {
26449         painter->setPen(mPen);
26450         painter->setBrush(mBrush);
26451       }
26452       double keyPixel = keyAxis->coordToPixel(it->key);
26453       double openPixel = valueAxis->coordToPixel(it->open);
26454       double closePixel = valueAxis->coordToPixel(it->close);
26455       // draw high:
26456       painter->drawLine(QPointF(valueAxis->coordToPixel(it->high), keyPixel), QPointF(valueAxis->coordToPixel(qMax(it->open, it->close)), keyPixel));
26457       // draw low:
26458       painter->drawLine(QPointF(valueAxis->coordToPixel(it->low), keyPixel), QPointF(valueAxis->coordToPixel(qMin(it->open, it->close)), keyPixel));
26459       // draw open-close box:
26460       double pixelWidth = getPixelWidth(it->key, keyPixel);
26461       painter->drawRect(QRectF(QPointF(closePixel, keyPixel-pixelWidth), QPointF(openPixel, keyPixel+pixelWidth)));
26462     }
26463   }
26464 }
26465 
26466 /*! \internal
26467 
26468   This function is used to determine the width of the bar at coordinate \a key, according to the
26469   specified width (\ref setWidth) and width type (\ref setWidthType). Provide the pixel position of
26470   \a key in \a keyPixel (because usually this was already calculated via \ref QCPAxis::coordToPixel
26471   when this function is called).
26472 
26473   It returns the number of pixels the bar extends to higher keys, relative to the \a key
26474   coordinate. So with a non-reversed horizontal axis, the return value is positive. With a reversed
26475   horizontal axis, the return value is negative. This is important so the open/close flags on the
26476   \ref csOhlc bar are drawn to the correct side.
26477 */
getPixelWidth(double key,double keyPixel) const26478 double QCPFinancial::getPixelWidth(double key, double keyPixel) const
26479 {
26480   double result = 0;
26481   switch (mWidthType)
26482   {
26483     case wtAbsolute:
26484     {
26485       if (mKeyAxis)
26486         result = mWidth*0.5*mKeyAxis.data()->pixelOrientation();
26487       break;
26488     }
26489     case wtAxisRectRatio:
26490     {
26491       if (mKeyAxis && mKeyAxis.data()->axisRect())
26492       {
26493         if (mKeyAxis.data()->orientation() == Qt::Horizontal)
26494           result = mKeyAxis.data()->axisRect()->width()*mWidth*0.5*mKeyAxis.data()->pixelOrientation();
26495         else
26496           result = mKeyAxis.data()->axisRect()->height()*mWidth*0.5*mKeyAxis.data()->pixelOrientation();
26497       } else
26498         qDebug() << Q_FUNC_INFO << "No key axis or axis rect defined";
26499       break;
26500     }
26501     case wtPlotCoords:
26502     {
26503       if (mKeyAxis)
26504         result = mKeyAxis.data()->coordToPixel(key+mWidth*0.5)-keyPixel;
26505       else
26506         qDebug() << Q_FUNC_INFO << "No key axis defined";
26507       break;
26508     }
26509   }
26510   return result;
26511 }
26512 
26513 /*! \internal
26514 
26515   This method is a helper function for \ref selectTest. It is used to test for selection when the
26516   chart style is \ref csOhlc. It only tests against the data points between \a begin and \a end.
26517 
26518   Like \ref selectTest, this method returns the shortest distance of \a pos to the graphical
26519   representation of the plottable, and \a closestDataPoint will point to the respective data point.
26520 */
ohlcSelectTest(const QPointF & pos,const QCPFinancialDataContainer::const_iterator & begin,const QCPFinancialDataContainer::const_iterator & end,QCPFinancialDataContainer::const_iterator & closestDataPoint) const26521 double QCPFinancial::ohlcSelectTest(const QPointF &pos, const QCPFinancialDataContainer::const_iterator &begin, const QCPFinancialDataContainer::const_iterator &end, QCPFinancialDataContainer::const_iterator &closestDataPoint) const
26522 {
26523   closestDataPoint = mDataContainer->constEnd();
26524   QCPAxis *keyAxis = mKeyAxis.data();
26525   QCPAxis *valueAxis = mValueAxis.data();
26526   if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; }
26527 
26528   double minDistSqr = std::numeric_limits<double>::max();
26529   if (keyAxis->orientation() == Qt::Horizontal)
26530   {
26531     for (QCPFinancialDataContainer::const_iterator it=begin; it!=end; ++it)
26532     {
26533       double keyPixel = keyAxis->coordToPixel(it->key);
26534       // calculate distance to backbone:
26535       double currentDistSqr = QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(keyPixel, valueAxis->coordToPixel(it->high)), QCPVector2D(keyPixel, valueAxis->coordToPixel(it->low)));
26536       if (currentDistSqr < minDistSqr)
26537       {
26538         minDistSqr = currentDistSqr;
26539         closestDataPoint = it;
26540       }
26541     }
26542   } else // keyAxis->orientation() == Qt::Vertical
26543   {
26544     for (QCPFinancialDataContainer::const_iterator it=begin; it!=end; ++it)
26545     {
26546       double keyPixel = keyAxis->coordToPixel(it->key);
26547       // calculate distance to backbone:
26548       double currentDistSqr = QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(valueAxis->coordToPixel(it->high), keyPixel), QCPVector2D(valueAxis->coordToPixel(it->low), keyPixel));
26549       if (currentDistSqr < minDistSqr)
26550       {
26551         minDistSqr = currentDistSqr;
26552         closestDataPoint = it;
26553       }
26554     }
26555   }
26556   return qSqrt(minDistSqr);
26557 }
26558 
26559 /*! \internal
26560 
26561   This method is a helper function for \ref selectTest. It is used to test for selection when the
26562   chart style is \ref csCandlestick. It only tests against the data points between \a begin and \a
26563   end.
26564 
26565   Like \ref selectTest, this method returns the shortest distance of \a pos to the graphical
26566   representation of the plottable, and \a closestDataPoint will point to the respective data point.
26567 */
candlestickSelectTest(const QPointF & pos,const QCPFinancialDataContainer::const_iterator & begin,const QCPFinancialDataContainer::const_iterator & end,QCPFinancialDataContainer::const_iterator & closestDataPoint) const26568 double QCPFinancial::candlestickSelectTest(const QPointF &pos, const QCPFinancialDataContainer::const_iterator &begin, const QCPFinancialDataContainer::const_iterator &end, QCPFinancialDataContainer::const_iterator &closestDataPoint) const
26569 {
26570   closestDataPoint = mDataContainer->constEnd();
26571   QCPAxis *keyAxis = mKeyAxis.data();
26572   QCPAxis *valueAxis = mValueAxis.data();
26573   if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; }
26574 
26575   double minDistSqr = std::numeric_limits<double>::max();
26576   if (keyAxis->orientation() == Qt::Horizontal)
26577   {
26578     for (QCPFinancialDataContainer::const_iterator it=begin; it!=end; ++it)
26579     {
26580       double currentDistSqr;
26581       // determine whether pos is in open-close-box:
26582       QCPRange boxKeyRange(it->key-mWidth*0.5, it->key+mWidth*0.5);
26583       QCPRange boxValueRange(it->close, it->open);
26584       double posKey, posValue;
26585       pixelsToCoords(pos, posKey, posValue);
26586       if (boxKeyRange.contains(posKey) && boxValueRange.contains(posValue)) // is in open-close-box
26587       {
26588         currentDistSqr = mParentPlot->selectionTolerance()*0.99 * mParentPlot->selectionTolerance()*0.99;
26589       } else
26590       {
26591         // calculate distance to high/low lines:
26592         double keyPixel = keyAxis->coordToPixel(it->key);
26593         double highLineDistSqr = QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(keyPixel, valueAxis->coordToPixel(it->high)), QCPVector2D(keyPixel, valueAxis->coordToPixel(qMax(it->open, it->close))));
26594         double lowLineDistSqr = QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(keyPixel, valueAxis->coordToPixel(it->low)), QCPVector2D(keyPixel, valueAxis->coordToPixel(qMin(it->open, it->close))));
26595         currentDistSqr = qMin(highLineDistSqr, lowLineDistSqr);
26596       }
26597       if (currentDistSqr < minDistSqr)
26598       {
26599         minDistSqr = currentDistSqr;
26600         closestDataPoint = it;
26601       }
26602     }
26603   } else // keyAxis->orientation() == Qt::Vertical
26604   {
26605     for (QCPFinancialDataContainer::const_iterator it=begin; it!=end; ++it)
26606     {
26607       double currentDistSqr;
26608       // determine whether pos is in open-close-box:
26609       QCPRange boxKeyRange(it->key-mWidth*0.5, it->key+mWidth*0.5);
26610       QCPRange boxValueRange(it->close, it->open);
26611       double posKey, posValue;
26612       pixelsToCoords(pos, posKey, posValue);
26613       if (boxKeyRange.contains(posKey) && boxValueRange.contains(posValue)) // is in open-close-box
26614       {
26615         currentDistSqr = mParentPlot->selectionTolerance()*0.99 * mParentPlot->selectionTolerance()*0.99;
26616       } else
26617       {
26618         // calculate distance to high/low lines:
26619         double keyPixel = keyAxis->coordToPixel(it->key);
26620         double highLineDistSqr = QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(valueAxis->coordToPixel(it->high), keyPixel), QCPVector2D(valueAxis->coordToPixel(qMax(it->open, it->close)), keyPixel));
26621         double lowLineDistSqr = QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(valueAxis->coordToPixel(it->low), keyPixel), QCPVector2D(valueAxis->coordToPixel(qMin(it->open, it->close)), keyPixel));
26622         currentDistSqr = qMin(highLineDistSqr, lowLineDistSqr);
26623       }
26624       if (currentDistSqr < minDistSqr)
26625       {
26626         minDistSqr = currentDistSqr;
26627         closestDataPoint = it;
26628       }
26629     }
26630   }
26631   return qSqrt(minDistSqr);
26632 }
26633 
26634 /*! \internal
26635 
26636   called by the drawing methods to determine which data (key) range is visible at the current key
26637   axis range setting, so only that needs to be processed.
26638 
26639   \a begin returns an iterator to the lowest data point that needs to be taken into account when
26640   plotting. Note that in order to get a clean plot all the way to the edge of the axis rect, \a
26641   begin may still be just outside the visible range.
26642 
26643   \a end returns the iterator just above the highest data point that needs to be taken into
26644   account. Same as before, \a end may also lie just outside of the visible range
26645 
26646   if the plottable contains no data, both \a begin and \a end point to \c constEnd.
26647 */
getVisibleDataBounds(QCPFinancialDataContainer::const_iterator & begin,QCPFinancialDataContainer::const_iterator & end) const26648 void QCPFinancial::getVisibleDataBounds(QCPFinancialDataContainer::const_iterator &begin, QCPFinancialDataContainer::const_iterator &end) const
26649 {
26650   if (!mKeyAxis)
26651   {
26652     qDebug() << Q_FUNC_INFO << "invalid key axis";
26653     begin = mDataContainer->constEnd();
26654     end = mDataContainer->constEnd();
26655     return;
26656   }
26657   begin = mDataContainer->findBegin(mKeyAxis.data()->range().lower-mWidth*0.5); // subtract half width of ohlc/candlestick to include partially visible data points
26658   end = mDataContainer->findEnd(mKeyAxis.data()->range().upper+mWidth*0.5); // add half width of ohlc/candlestick to include partially visible data points
26659 }
26660 
26661 /*!  \internal
26662 
26663   Returns the hit box in pixel coordinates that will be used for data selection with the selection
26664   rect (\ref selectTestRect), of the data point given by \a it.
26665 */
selectionHitBox(QCPFinancialDataContainer::const_iterator it) const26666 QRectF QCPFinancial::selectionHitBox(QCPFinancialDataContainer::const_iterator it) const
26667 {
26668   QCPAxis *keyAxis = mKeyAxis.data();
26669   QCPAxis *valueAxis = mValueAxis.data();
26670   if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QRectF(); }
26671 
26672   double keyPixel = keyAxis->coordToPixel(it->key);
26673   double highPixel = valueAxis->coordToPixel(it->high);
26674   double lowPixel = valueAxis->coordToPixel(it->low);
26675   double keyWidthPixels = keyPixel-keyAxis->coordToPixel(it->key-mWidth*0.5);
26676   if (keyAxis->orientation() == Qt::Horizontal)
26677     return QRectF(keyPixel-keyWidthPixels, highPixel, keyWidthPixels*2, lowPixel-highPixel).normalized();
26678   else
26679     return QRectF(highPixel, keyPixel-keyWidthPixels, lowPixel-highPixel, keyWidthPixels*2).normalized();
26680 }
26681 /* end of 'src/plottables/plottable-financial.cpp' */
26682 
26683 
26684 /* including file 'src/plottables/plottable-errorbar.cpp', size 37210        */
26685 /* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
26686 
26687 ////////////////////////////////////////////////////////////////////////////////////////////////////
26688 //////////////////// QCPErrorBarsData
26689 ////////////////////////////////////////////////////////////////////////////////////////////////////
26690 
26691 /*! \class QCPErrorBarsData
26692   \brief Holds the data of one single error bar for QCPErrorBars.
26693 
26694   The stored data is:
26695   \li \a errorMinus: how much the error bar extends towards negative coordinates from the data
26696   point position
26697   \li \a errorPlus: how much the error bar extends towards positive coordinates from the data point
26698   position
26699 
26700   The container for storing the error bar information is \ref QCPErrorBarsDataContainer. It is a
26701   typedef for <tt>QVector<\ref QCPErrorBarsData></tt>.
26702 
26703   \see QCPErrorBarsDataContainer
26704 */
26705 
26706 /*!
26707   Constructs an error bar with errors set to zero.
26708 */
QCPErrorBarsData()26709 QCPErrorBarsData::QCPErrorBarsData() :
26710   errorMinus(0),
26711   errorPlus(0)
26712 {
26713 }
26714 
26715 /*!
26716   Constructs an error bar with equal \a error in both negative and positive direction.
26717 */
QCPErrorBarsData(double error)26718 QCPErrorBarsData::QCPErrorBarsData(double error) :
26719   errorMinus(error),
26720   errorPlus(error)
26721 {
26722 }
26723 
26724 /*!
26725   Constructs an error bar with negative and positive errors set to \a errorMinus and \a errorPlus,
26726   respectively.
26727 */
QCPErrorBarsData(double errorMinus,double errorPlus)26728 QCPErrorBarsData::QCPErrorBarsData(double errorMinus, double errorPlus) :
26729   errorMinus(errorMinus),
26730   errorPlus(errorPlus)
26731 {
26732 }
26733 
26734 
26735 ////////////////////////////////////////////////////////////////////////////////////////////////////
26736 //////////////////// QCPErrorBars
26737 ////////////////////////////////////////////////////////////////////////////////////////////////////
26738 
26739 /*! \class QCPErrorBars
26740   \brief A plottable that adds a set of error bars to other plottables.
26741 
26742   \image html QCPErrorBars.png
26743 
26744   The \ref QCPErrorBars plottable can be attached to other one-dimensional plottables (e.g. \ref
26745   QCPGraph, \ref QCPCurve, \ref QCPBars, etc.) and equips them with error bars.
26746 
26747   Use \ref setDataPlottable to define for which plottable the \ref QCPErrorBars shall display the
26748   error bars. The orientation of the error bars can be controlled with \ref setErrorType.
26749 
26750   By using \ref setData, you can supply the actual error data, either as symmetric error or
26751   plus/minus asymmetric errors. \ref QCPErrorBars only stores the error data. The absolute
26752   key/value position of each error bar will be adopted from the configured data plottable. The
26753   error data of the \ref QCPErrorBars are associated one-to-one via their index to the data points
26754   of the data plottable. You can directly access and manipulate the error bar data via \ref data.
26755 
26756   Set either of the plus/minus errors to NaN (<tt>qQNaN()</tt> or
26757   <tt>std::numeric_limits<double>::quiet_NaN()</tt>) to not show the respective error bar on the data point at
26758   that index.
26759 
26760   \section qcperrorbars-appearance Changing the appearance
26761 
26762   The appearance of the error bars is defined by the pen (\ref setPen), and the width of the
26763   whiskers (\ref setWhiskerWidth). Further, the error bar backbones may leave a gap around the data
26764   point center to prevent that error bars are drawn too close to or even through scatter points.
26765   This gap size can be controlled via \ref setSymbolGap.
26766 */
26767 
26768 /* start of documentation of inline functions */
26769 
26770 /*! \fn QSharedPointer<QCPErrorBarsDataContainer> QCPErrorBars::data() const
26771 
26772   Returns a shared pointer to the internal data storage of type \ref QCPErrorBarsDataContainer. You
26773   may use it to directly manipulate the error values, which may be more convenient and faster than
26774   using the regular \ref setData methods.
26775 */
26776 
26777 /* end of documentation of inline functions */
26778 
26779 /*!
26780   Constructs an error bars plottable which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value
26781   axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have
26782   the same orientation. If either of these restrictions is violated, a corresponding message is
26783   printed to the debug output (qDebug), the construction is not aborted, though.
26784 
26785   It is also important that the \a keyAxis and \a valueAxis are the same for the error bars
26786   plottable and the data plottable that the error bars shall be drawn on (\ref setDataPlottable).
26787 
26788   The created \ref QCPErrorBars is automatically registered with the QCustomPlot instance inferred
26789   from \a keyAxis. This QCustomPlot instance takes ownership of the \ref QCPErrorBars, so do not
26790   delete it manually but use \ref QCustomPlot::removePlottable() instead.
26791 */
QCPErrorBars(QCPAxis * keyAxis,QCPAxis * valueAxis)26792 QCPErrorBars::QCPErrorBars(QCPAxis *keyAxis, QCPAxis *valueAxis) :
26793   QCPAbstractPlottable(keyAxis, valueAxis),
26794   mDataContainer(new QVector<QCPErrorBarsData>),
26795   mErrorType(etValueError),
26796   mWhiskerWidth(9),
26797   mSymbolGap(10)
26798 {
26799   setPen(QPen(Qt::black, 0));
26800   setBrush(Qt::NoBrush);
26801 }
26802 
~QCPErrorBars()26803 QCPErrorBars::~QCPErrorBars()
26804 {
26805 }
26806 
26807 /*! \overload
26808 
26809   Replaces the current data container with the provided \a data container.
26810 
26811   Since a QSharedPointer is used, multiple \ref QCPErrorBars instances may share the same data
26812   container safely. Modifying the data in the container will then affect all \ref QCPErrorBars
26813   instances that share the container. Sharing can be achieved by simply exchanging the data
26814   containers wrapped in shared pointers:
26815   \snippet documentation/doc-code-snippets/mainwindow.cpp qcperrorbars-datasharing-1
26816 
26817   If you do not wish to share containers, but create a copy from an existing container, assign the
26818   data containers directly:
26819   \snippet documentation/doc-code-snippets/mainwindow.cpp qcperrorbars-datasharing-2
26820   (This uses different notation compared with other plottables, because the \ref QCPErrorBars
26821   uses a \c QVector<QCPErrorBarsData> as its data container, instead of a \ref QCPDataContainer.)
26822 
26823   \see addData
26824 */
setData(QSharedPointer<QCPErrorBarsDataContainer> data)26825 void QCPErrorBars::setData(QSharedPointer<QCPErrorBarsDataContainer> data)
26826 {
26827   mDataContainer = data;
26828 }
26829 
26830 /*! \overload
26831 
26832   Sets symmetrical error values as specified in \a error. The errors will be associated one-to-one
26833   by the data point index to the associated data plottable (\ref setDataPlottable).
26834 
26835   You can directly access and manipulate the error bar data via \ref data.
26836 
26837   \see addData
26838 */
setData(const QVector<double> & error)26839 void QCPErrorBars::setData(const QVector<double> &error)
26840 {
26841   mDataContainer->clear();
26842   addData(error);
26843 }
26844 
26845 /*! \overload
26846 
26847   Sets asymmetrical errors as specified in \a errorMinus and \a errorPlus. The errors will be
26848   associated one-to-one by the data point index to the associated data plottable (\ref
26849   setDataPlottable).
26850 
26851   You can directly access and manipulate the error bar data via \ref data.
26852 
26853   \see addData
26854 */
setData(const QVector<double> & errorMinus,const QVector<double> & errorPlus)26855 void QCPErrorBars::setData(const QVector<double> &errorMinus, const QVector<double> &errorPlus)
26856 {
26857   mDataContainer->clear();
26858   addData(errorMinus, errorPlus);
26859 }
26860 
26861 /*!
26862   Sets the data plottable to which the error bars will be applied. The error values specified e.g.
26863   via \ref setData will be associated one-to-one by the data point index to the data points of \a
26864   plottable. This means that the error bars will adopt the key/value coordinates of the data point
26865   with the same index.
26866 
26867   The passed \a plottable must be a one-dimensional plottable, i.e. it must implement the \ref
26868   QCPPlottableInterface1D. Further, it must not be a \ref QCPErrorBars instance itself. If either
26869   of these restrictions is violated, a corresponding qDebug output is generated, and the data
26870   plottable of this \ref QCPErrorBars instance is set to zero.
26871 
26872   For proper display, care must also be taken that the key and value axes of the \a plottable match
26873   those configured for this \ref QCPErrorBars instance.
26874 */
setDataPlottable(QCPAbstractPlottable * plottable)26875 void QCPErrorBars::setDataPlottable(QCPAbstractPlottable *plottable)
26876 {
26877   if (plottable && qobject_cast<QCPErrorBars*>(plottable))
26878   {
26879     mDataPlottable = 0;
26880     qDebug() << Q_FUNC_INFO << "can't set another QCPErrorBars instance as data plottable";
26881     return;
26882   }
26883   if (plottable && !plottable->interface1D())
26884   {
26885     mDataPlottable = 0;
26886     qDebug() << Q_FUNC_INFO << "passed plottable doesn't implement 1d interface, can't associate with QCPErrorBars";
26887     return;
26888   }
26889 
26890   mDataPlottable = plottable;
26891 }
26892 
26893 /*!
26894   Sets in which orientation the error bars shall appear on the data points. If your data needs both
26895   error dimensions, create two \ref QCPErrorBars with different \a type.
26896 */
setErrorType(ErrorType type)26897 void QCPErrorBars::setErrorType(ErrorType type)
26898 {
26899   mErrorType = type;
26900 }
26901 
26902 /*!
26903   Sets the width of the whiskers (the short bars at the end of the actual error bar backbones) to
26904   \a pixels.
26905 */
setWhiskerWidth(double pixels)26906 void QCPErrorBars::setWhiskerWidth(double pixels)
26907 {
26908   mWhiskerWidth = pixels;
26909 }
26910 
26911 /*!
26912   Sets the gap diameter around the data points that will be left out when drawing the error bar
26913   backbones. This gap prevents that error bars are drawn too close to or even through scatter
26914   points.
26915 */
setSymbolGap(double pixels)26916 void QCPErrorBars::setSymbolGap(double pixels)
26917 {
26918   mSymbolGap = pixels;
26919 }
26920 
26921 /*! \overload
26922 
26923   Adds symmetrical error values as specified in \a error. The errors will be associated one-to-one
26924   by the data point index to the associated data plottable (\ref setDataPlottable).
26925 
26926   You can directly access and manipulate the error bar data via \ref data.
26927 
26928   \see setData
26929 */
addData(const QVector<double> & error)26930 void QCPErrorBars::addData(const QVector<double> &error)
26931 {
26932   addData(error, error);
26933 }
26934 
26935 /*! \overload
26936 
26937   Adds asymmetrical errors as specified in \a errorMinus and \a errorPlus. The errors will be
26938   associated one-to-one by the data point index to the associated data plottable (\ref
26939   setDataPlottable).
26940 
26941   You can directly access and manipulate the error bar data via \ref data.
26942 
26943   \see setData
26944 */
addData(const QVector<double> & errorMinus,const QVector<double> & errorPlus)26945 void QCPErrorBars::addData(const QVector<double> &errorMinus, const QVector<double> &errorPlus)
26946 {
26947   if (errorMinus.size() != errorPlus.size())
26948     qDebug() << Q_FUNC_INFO << "minus and plus error vectors have different sizes:" << errorMinus.size() << errorPlus.size();
26949   const int n = qMin(errorMinus.size(), errorPlus.size());
26950   mDataContainer->reserve(n);
26951   for (int i=0; i<n; ++i)
26952     mDataContainer->append(QCPErrorBarsData(errorMinus.at(i), errorPlus.at(i)));
26953 }
26954 
26955 /*! \overload
26956 
26957   Adds a single symmetrical error bar as specified in \a error. The errors will be associated
26958   one-to-one by the data point index to the associated data plottable (\ref setDataPlottable).
26959 
26960   You can directly access and manipulate the error bar data via \ref data.
26961 
26962   \see setData
26963 */
addData(double error)26964 void QCPErrorBars::addData(double error)
26965 {
26966   mDataContainer->append(QCPErrorBarsData(error));
26967 }
26968 
26969 /*! \overload
26970 
26971   Adds a single asymmetrical error bar as specified in \a errorMinus and \a errorPlus. The errors
26972   will be associated one-to-one by the data point index to the associated data plottable (\ref
26973   setDataPlottable).
26974 
26975   You can directly access and manipulate the error bar data via \ref data.
26976 
26977   \see setData
26978 */
addData(double errorMinus,double errorPlus)26979 void QCPErrorBars::addData(double errorMinus, double errorPlus)
26980 {
26981   mDataContainer->append(QCPErrorBarsData(errorMinus, errorPlus));
26982 }
26983 
26984 /* inherits documentation from base class */
dataCount() const26985 int QCPErrorBars::dataCount() const
26986 {
26987   return mDataContainer->size();
26988 }
26989 
26990 /* inherits documentation from base class */
dataMainKey(int index) const26991 double QCPErrorBars::dataMainKey(int index) const
26992 {
26993   if (mDataPlottable)
26994     return mDataPlottable->interface1D()->dataMainKey(index);
26995   else
26996     qDebug() << Q_FUNC_INFO << "no data plottable set";
26997   return 0;
26998 }
26999 
27000 /* inherits documentation from base class */
dataSortKey(int index) const27001 double QCPErrorBars::dataSortKey(int index) const
27002 {
27003   if (mDataPlottable)
27004     return mDataPlottable->interface1D()->dataSortKey(index);
27005   else
27006     qDebug() << Q_FUNC_INFO << "no data plottable set";
27007   return 0;
27008 }
27009 
27010 /* inherits documentation from base class */
dataMainValue(int index) const27011 double QCPErrorBars::dataMainValue(int index) const
27012 {
27013   if (mDataPlottable)
27014     return mDataPlottable->interface1D()->dataMainValue(index);
27015   else
27016     qDebug() << Q_FUNC_INFO << "no data plottable set";
27017   return 0;
27018 }
27019 
27020 /* inherits documentation from base class */
dataValueRange(int index) const27021 QCPRange QCPErrorBars::dataValueRange(int index) const
27022 {
27023   if (mDataPlottable)
27024   {
27025     const double value = mDataPlottable->interface1D()->dataMainValue(index);
27026     if (index >= 0 && index < mDataContainer->size() && mErrorType == etValueError)
27027       return QCPRange(value-mDataContainer->at(index).errorMinus, value+mDataContainer->at(index).errorPlus);
27028     else
27029       return QCPRange(value, value);
27030   } else
27031   {
27032     qDebug() << Q_FUNC_INFO << "no data plottable set";
27033     return QCPRange();
27034   }
27035 }
27036 
27037 /* inherits documentation from base class */
dataPixelPosition(int index) const27038 QPointF QCPErrorBars::dataPixelPosition(int index) const
27039 {
27040   if (mDataPlottable)
27041     return mDataPlottable->interface1D()->dataPixelPosition(index);
27042   else
27043     qDebug() << Q_FUNC_INFO << "no data plottable set";
27044   return QPointF();
27045 }
27046 
27047 /* inherits documentation from base class */
sortKeyIsMainKey() const27048 bool QCPErrorBars::sortKeyIsMainKey() const
27049 {
27050   if (mDataPlottable)
27051   {
27052     return mDataPlottable->interface1D()->sortKeyIsMainKey();
27053   } else
27054   {
27055     qDebug() << Q_FUNC_INFO << "no data plottable set";
27056     return true;
27057   }
27058 }
27059 
27060 /*!
27061   \copydoc QCPPlottableInterface1D::selectTestRect
27062 */
selectTestRect(const QRectF & rect,bool onlySelectable) const27063 QCPDataSelection QCPErrorBars::selectTestRect(const QRectF &rect, bool onlySelectable) const
27064 {
27065   QCPDataSelection result;
27066   if (!mDataPlottable)
27067     return result;
27068   if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
27069     return result;
27070   if (!mKeyAxis || !mValueAxis)
27071     return result;
27072 
27073   QCPErrorBarsDataContainer::const_iterator visibleBegin, visibleEnd;
27074   getVisibleDataBounds(visibleBegin, visibleEnd, QCPDataRange(0, dataCount()));
27075 
27076   QVector<QLineF> backbones, whiskers;
27077   for (QCPErrorBarsDataContainer::const_iterator it=visibleBegin; it!=visibleEnd; ++it)
27078   {
27079     backbones.clear();
27080     whiskers.clear();
27081     getErrorBarLines(it, backbones, whiskers);
27082     for (int i=0; i<backbones.size(); ++i)
27083     {
27084       if (rectIntersectsLine(rect, backbones.at(i)))
27085       {
27086         result.addDataRange(QCPDataRange(it-mDataContainer->constBegin(), it-mDataContainer->constBegin()+1), false);
27087         break;
27088       }
27089     }
27090   }
27091   result.simplify();
27092   return result;
27093 }
27094 
27095 /* inherits documentation from base class */
findBegin(double sortKey,bool expandedRange) const27096 int QCPErrorBars::findBegin(double sortKey, bool expandedRange) const
27097 {
27098   if (mDataPlottable)
27099   {
27100     if (mDataContainer->isEmpty())
27101       return 0;
27102     int beginIndex = mDataPlottable->interface1D()->findBegin(sortKey, expandedRange);
27103     if (beginIndex >= mDataContainer->size())
27104       beginIndex = mDataContainer->size()-1;
27105     return beginIndex;
27106   } else
27107     qDebug() << Q_FUNC_INFO << "no data plottable set";
27108   return 0;
27109 }
27110 
27111 /* inherits documentation from base class */
findEnd(double sortKey,bool expandedRange) const27112 int QCPErrorBars::findEnd(double sortKey, bool expandedRange) const
27113 {
27114   if (mDataPlottable)
27115   {
27116     if (mDataContainer->isEmpty())
27117       return 0;
27118     int endIndex = mDataPlottable->interface1D()->findEnd(sortKey, expandedRange);
27119     if (endIndex > mDataContainer->size())
27120       endIndex = mDataContainer->size();
27121     return endIndex;
27122   } else
27123     qDebug() << Q_FUNC_INFO << "no data plottable set";
27124   return 0;
27125 }
27126 
27127 /* inherits documentation from base class */
selectTest(const QPointF & pos,bool onlySelectable,QVariant * details) const27128 double QCPErrorBars::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
27129 {
27130   if (!mDataPlottable) return -1;
27131 
27132   if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
27133     return -1;
27134   if (!mKeyAxis || !mValueAxis)
27135     return -1;
27136 
27137   if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()))
27138   {
27139     QCPErrorBarsDataContainer::const_iterator closestDataPoint = mDataContainer->constEnd();
27140     double result = pointDistance(pos, closestDataPoint);
27141     if (details)
27142     {
27143       int pointIndex = closestDataPoint-mDataContainer->constBegin();
27144       details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1)));
27145     }
27146     return result;
27147   } else
27148     return -1;
27149 }
27150 
27151 /* inherits documentation from base class */
draw(QCPPainter * painter)27152 void QCPErrorBars::draw(QCPPainter *painter)
27153 {
27154   if (!mDataPlottable) return;
27155   if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
27156   if (mKeyAxis.data()->range().size() <= 0 || mDataContainer->isEmpty()) return;
27157 
27158   // if the sort key isn't the main key, we must check the visibility for each data point/error bar individually
27159   // (getVisibleDataBounds applies range restriction, but otherwise can only return full data range):
27160   bool checkPointVisibility = !mDataPlottable->interface1D()->sortKeyIsMainKey();
27161 
27162     // check data validity if flag set:
27163 #ifdef QCUSTOMPLOT_CHECK_DATA
27164   QCPErrorBarsDataContainer::const_iterator it;
27165   for (it = mDataContainer->constBegin(); it != mDataContainer->constEnd(); ++it)
27166   {
27167     if (QCP::isInvalidData(it->errorMinus, it->errorPlus))
27168       qDebug() << Q_FUNC_INFO << "Data point at index" << it-mDataContainer->constBegin() << "invalid." << "Plottable name:" << name();
27169   }
27170 #endif
27171 
27172   applyDefaultAntialiasingHint(painter);
27173   painter->setBrush(Qt::NoBrush);
27174   // loop over and draw segments of unselected/selected data:
27175   QList<QCPDataRange> selectedSegments, unselectedSegments, allSegments;
27176   getDataSegments(selectedSegments, unselectedSegments);
27177   allSegments << unselectedSegments << selectedSegments;
27178   QVector<QLineF> backbones, whiskers;
27179   for (int i=0; i<allSegments.size(); ++i)
27180   {
27181     QCPErrorBarsDataContainer::const_iterator begin, end;
27182     getVisibleDataBounds(begin, end, allSegments.at(i));
27183     if (begin == end)
27184       continue;
27185 
27186     bool isSelectedSegment = i >= unselectedSegments.size();
27187     if (isSelectedSegment && mSelectionDecorator)
27188       mSelectionDecorator->applyPen(painter);
27189     else
27190       painter->setPen(mPen);
27191     if (painter->pen().capStyle() == Qt::SquareCap)
27192     {
27193       QPen capFixPen(painter->pen());
27194       capFixPen.setCapStyle(Qt::FlatCap);
27195       painter->setPen(capFixPen);
27196     }
27197     backbones.clear();
27198     whiskers.clear();
27199     for (QCPErrorBarsDataContainer::const_iterator it=begin; it!=end; ++it)
27200     {
27201       if (!checkPointVisibility || errorBarVisible(it-mDataContainer->constBegin()))
27202         getErrorBarLines(it, backbones, whiskers);
27203     }
27204     painter->drawLines(backbones);
27205     painter->drawLines(whiskers);
27206   }
27207 
27208   // draw other selection decoration that isn't just line/scatter pens and brushes:
27209   if (mSelectionDecorator)
27210     mSelectionDecorator->drawDecoration(painter, selection());
27211 }
27212 
27213 /* inherits documentation from base class */
drawLegendIcon(QCPPainter * painter,const QRectF & rect) const27214 void QCPErrorBars::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
27215 {
27216   applyDefaultAntialiasingHint(painter);
27217   painter->setPen(mPen);
27218   if (mErrorType == etValueError && mValueAxis && mValueAxis->orientation() == Qt::Vertical)
27219   {
27220     painter->drawLine(QLineF(rect.center().x(), rect.top()+2, rect.center().x(), rect.bottom()-1));
27221     painter->drawLine(QLineF(rect.center().x()-4, rect.top()+2, rect.center().x()+4, rect.top()+2));
27222     painter->drawLine(QLineF(rect.center().x()-4, rect.bottom()-1, rect.center().x()+4, rect.bottom()-1));
27223   } else
27224   {
27225     painter->drawLine(QLineF(rect.left()+2, rect.center().y(), rect.right()-2, rect.center().y()));
27226     painter->drawLine(QLineF(rect.left()+2, rect.center().y()-4, rect.left()+2, rect.center().y()+4));
27227     painter->drawLine(QLineF(rect.right()-2, rect.center().y()-4, rect.right()-2, rect.center().y()+4));
27228   }
27229 }
27230 
27231 /* inherits documentation from base class */
getKeyRange(bool & foundRange,QCP::SignDomain inSignDomain) const27232 QCPRange QCPErrorBars::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const
27233 {
27234   if (!mDataPlottable)
27235   {
27236     foundRange = false;
27237     return QCPRange();
27238   }
27239 
27240   QCPRange range;
27241   bool haveLower = false;
27242   bool haveUpper = false;
27243   QCPErrorBarsDataContainer::const_iterator it;
27244   for (it = mDataContainer->constBegin(); it != mDataContainer->constEnd(); ++it)
27245   {
27246     if (mErrorType == etValueError)
27247     {
27248       // error bar doesn't extend in key dimension (except whisker but we ignore that here), so only use data point center
27249       const double current = mDataPlottable->interface1D()->dataMainKey(it-mDataContainer->constBegin());
27250       if (qIsNaN(current)) continue;
27251       if (inSignDomain == QCP::sdBoth || (inSignDomain == QCP::sdNegative && current < 0) || (inSignDomain == QCP::sdPositive && current > 0))
27252       {
27253         if (current < range.lower || !haveLower)
27254         {
27255           range.lower = current;
27256           haveLower = true;
27257         }
27258         if (current > range.upper || !haveUpper)
27259         {
27260           range.upper = current;
27261           haveUpper = true;
27262         }
27263       }
27264     } else // mErrorType == etKeyError
27265     {
27266       const double dataKey = mDataPlottable->interface1D()->dataMainKey(it-mDataContainer->constBegin());
27267       if (qIsNaN(dataKey)) continue;
27268       // plus error:
27269       double current = dataKey + (qIsNaN(it->errorPlus) ? 0 : it->errorPlus);
27270       if (inSignDomain == QCP::sdBoth || (inSignDomain == QCP::sdNegative && current < 0) || (inSignDomain == QCP::sdPositive && current > 0))
27271       {
27272         if (current > range.upper || !haveUpper)
27273         {
27274           range.upper = current;
27275           haveUpper = true;
27276         }
27277       }
27278       // minus error:
27279       current = dataKey - (qIsNaN(it->errorMinus) ? 0 : it->errorMinus);
27280       if (inSignDomain == QCP::sdBoth || (inSignDomain == QCP::sdNegative && current < 0) || (inSignDomain == QCP::sdPositive && current > 0))
27281       {
27282         if (current < range.lower || !haveLower)
27283         {
27284           range.lower = current;
27285           haveLower = true;
27286         }
27287       }
27288     }
27289   }
27290 
27291   if (haveUpper && !haveLower)
27292   {
27293     range.lower = range.upper;
27294     haveLower = true;
27295   } else if (haveLower && !haveUpper)
27296   {
27297     range.upper = range.lower;
27298     haveUpper = true;
27299   }
27300 
27301   foundRange = haveLower && haveUpper;
27302   return range;
27303 }
27304 
27305 /* inherits documentation from base class */
getValueRange(bool & foundRange,QCP::SignDomain inSignDomain,const QCPRange & inKeyRange) const27306 QCPRange QCPErrorBars::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const
27307 {
27308   if (!mDataPlottable)
27309   {
27310     foundRange = false;
27311     return QCPRange();
27312   }
27313 
27314   QCPRange range;
27315   const bool restrictKeyRange = inKeyRange != QCPRange();
27316   bool haveLower = false;
27317   bool haveUpper = false;
27318   QCPErrorBarsDataContainer::const_iterator itBegin = mDataContainer->constBegin();
27319   QCPErrorBarsDataContainer::const_iterator itEnd = mDataContainer->constEnd();
27320   if (mDataPlottable->interface1D()->sortKeyIsMainKey() && restrictKeyRange)
27321   {
27322     itBegin = mDataContainer->constBegin()+findBegin(inKeyRange.lower);
27323     itEnd = mDataContainer->constBegin()+findEnd(inKeyRange.upper);
27324   }
27325   for (QCPErrorBarsDataContainer::const_iterator it = itBegin; it != itEnd; ++it)
27326   {
27327     if (restrictKeyRange)
27328     {
27329       const double dataKey = mDataPlottable->interface1D()->dataMainKey(it-mDataContainer->constBegin());
27330       if (dataKey < inKeyRange.lower || dataKey > inKeyRange.upper)
27331         continue;
27332     }
27333     if (mErrorType == etValueError)
27334     {
27335       const double dataValue = mDataPlottable->interface1D()->dataMainValue(it-mDataContainer->constBegin());
27336       if (qIsNaN(dataValue)) continue;
27337       // plus error:
27338       double current = dataValue + (qIsNaN(it->errorPlus) ? 0 : it->errorPlus);
27339       if (inSignDomain == QCP::sdBoth || (inSignDomain == QCP::sdNegative && current < 0) || (inSignDomain == QCP::sdPositive && current > 0))
27340       {
27341         if (current > range.upper || !haveUpper)
27342         {
27343           range.upper = current;
27344           haveUpper = true;
27345         }
27346       }
27347       // minus error:
27348       current = dataValue - (qIsNaN(it->errorMinus) ? 0 : it->errorMinus);
27349       if (inSignDomain == QCP::sdBoth || (inSignDomain == QCP::sdNegative && current < 0) || (inSignDomain == QCP::sdPositive && current > 0))
27350       {
27351         if (current < range.lower || !haveLower)
27352         {
27353           range.lower = current;
27354           haveLower = true;
27355         }
27356       }
27357     } else // mErrorType == etKeyError
27358     {
27359       // error bar doesn't extend in value dimension (except whisker but we ignore that here), so only use data point center
27360       const double current = mDataPlottable->interface1D()->dataMainValue(it-mDataContainer->constBegin());
27361       if (qIsNaN(current)) continue;
27362       if (inSignDomain == QCP::sdBoth || (inSignDomain == QCP::sdNegative && current < 0) || (inSignDomain == QCP::sdPositive && current > 0))
27363       {
27364         if (current < range.lower || !haveLower)
27365         {
27366           range.lower = current;
27367           haveLower = true;
27368         }
27369         if (current > range.upper || !haveUpper)
27370         {
27371           range.upper = current;
27372           haveUpper = true;
27373         }
27374       }
27375     }
27376   }
27377 
27378   if (haveUpper && !haveLower)
27379   {
27380     range.lower = range.upper;
27381     haveLower = true;
27382   } else if (haveLower && !haveUpper)
27383   {
27384     range.upper = range.lower;
27385     haveUpper = true;
27386   }
27387 
27388   foundRange = haveLower && haveUpper;
27389   return range;
27390 }
27391 
27392 /*! \internal
27393 
27394   Calculates the lines that make up the error bar belonging to the data point \a it.
27395 
27396   The resulting lines are added to \a backbones and \a whiskers. The vectors are not cleared, so
27397   calling this method with different \a it but the same \a backbones and \a whiskers allows to
27398   accumulate lines for multiple data points.
27399 
27400   This method assumes that \a it is a valid iterator within the bounds of this \ref QCPErrorBars
27401   instance and within the bounds of the associated data plottable.
27402 */
getErrorBarLines(QCPErrorBarsDataContainer::const_iterator it,QVector<QLineF> & backbones,QVector<QLineF> & whiskers) const27403 void QCPErrorBars::getErrorBarLines(QCPErrorBarsDataContainer::const_iterator it, QVector<QLineF> &backbones, QVector<QLineF> &whiskers) const
27404 {
27405   if (!mDataPlottable) return;
27406 
27407   int index = it-mDataContainer->constBegin();
27408   QPointF centerPixel = mDataPlottable->interface1D()->dataPixelPosition(index);
27409   if (qIsNaN(centerPixel.x()) || qIsNaN(centerPixel.y()))
27410     return;
27411   QCPAxis *errorAxis = mErrorType == etValueError ? mValueAxis : mKeyAxis;
27412   QCPAxis *orthoAxis = mErrorType == etValueError ? mKeyAxis : mValueAxis;
27413   const double centerErrorAxisPixel = errorAxis->orientation() == Qt::Horizontal ? centerPixel.x() : centerPixel.y();
27414   const double centerOrthoAxisPixel = orthoAxis->orientation() == Qt::Horizontal ? centerPixel.x() : centerPixel.y();
27415   const double centerErrorAxisCoord = errorAxis->pixelToCoord(centerErrorAxisPixel); // depending on plottable, this might be different from just mDataPlottable->interface1D()->dataMainKey/Value
27416   const double symbolGap = mSymbolGap*0.5*errorAxis->pixelOrientation();
27417   // plus error:
27418   double errorStart, errorEnd;
27419   if (!qIsNaN(it->errorPlus))
27420   {
27421     errorStart = centerErrorAxisPixel+symbolGap;
27422     errorEnd = errorAxis->coordToPixel(centerErrorAxisCoord+it->errorPlus);
27423     if (errorAxis->orientation() == Qt::Vertical)
27424     {
27425       if ((errorStart > errorEnd) != errorAxis->rangeReversed())
27426         backbones.append(QLineF(centerOrthoAxisPixel, errorStart, centerOrthoAxisPixel, errorEnd));
27427       whiskers.append(QLineF(centerOrthoAxisPixel-mWhiskerWidth*0.5, errorEnd, centerOrthoAxisPixel+mWhiskerWidth*0.5, errorEnd));
27428     } else
27429     {
27430       if ((errorStart < errorEnd) != errorAxis->rangeReversed())
27431         backbones.append(QLineF(errorStart, centerOrthoAxisPixel, errorEnd, centerOrthoAxisPixel));
27432       whiskers.append(QLineF(errorEnd, centerOrthoAxisPixel-mWhiskerWidth*0.5, errorEnd, centerOrthoAxisPixel+mWhiskerWidth*0.5));
27433     }
27434   }
27435   // minus error:
27436   if (!qIsNaN(it->errorMinus))
27437   {
27438     errorStart = centerErrorAxisPixel-symbolGap;
27439     errorEnd = errorAxis->coordToPixel(centerErrorAxisCoord-it->errorMinus);
27440     if (errorAxis->orientation() == Qt::Vertical)
27441     {
27442       if ((errorStart < errorEnd) != errorAxis->rangeReversed())
27443         backbones.append(QLineF(centerOrthoAxisPixel, errorStart, centerOrthoAxisPixel, errorEnd));
27444       whiskers.append(QLineF(centerOrthoAxisPixel-mWhiskerWidth*0.5, errorEnd, centerOrthoAxisPixel+mWhiskerWidth*0.5, errorEnd));
27445     } else
27446     {
27447       if ((errorStart > errorEnd) != errorAxis->rangeReversed())
27448         backbones.append(QLineF(errorStart, centerOrthoAxisPixel, errorEnd, centerOrthoAxisPixel));
27449       whiskers.append(QLineF(errorEnd, centerOrthoAxisPixel-mWhiskerWidth*0.5, errorEnd, centerOrthoAxisPixel+mWhiskerWidth*0.5));
27450     }
27451   }
27452 }
27453 
27454 /*! \internal
27455 
27456   This method outputs the currently visible data range via \a begin and \a end. The returned range
27457   will also never exceed \a rangeRestriction.
27458 
27459   Since error bars with type \ref etKeyError may extend to arbitrarily positive and negative key
27460   coordinates relative to their data point key, this method checks all outer error bars whether
27461   they truly don't reach into the visible portion of the axis rect, by calling \ref
27462   errorBarVisible. On the other hand error bars with type \ref etValueError that are associated
27463   with data plottables whose sort key is equal to the main key (see \ref qcpdatacontainer-datatype
27464   "QCPDataContainer DataType") can be handled very efficiently by finding the visible range of
27465   error bars through binary search (\ref QCPPlottableInterface1D::findBegin and \ref
27466   QCPPlottableInterface1D::findEnd).
27467 
27468   If the plottable's sort key is not equal to the main key, this method returns the full data
27469   range, only restricted by \a rangeRestriction. Drawing optimization then has to be done on a
27470   point-by-point basis in the \ref draw method.
27471 */
getVisibleDataBounds(QCPErrorBarsDataContainer::const_iterator & begin,QCPErrorBarsDataContainer::const_iterator & end,const QCPDataRange & rangeRestriction) const27472 void QCPErrorBars::getVisibleDataBounds(QCPErrorBarsDataContainer::const_iterator &begin, QCPErrorBarsDataContainer::const_iterator &end, const QCPDataRange &rangeRestriction) const
27473 {
27474   QCPAxis *keyAxis = mKeyAxis.data();
27475   QCPAxis *valueAxis = mValueAxis.data();
27476   if (!keyAxis || !valueAxis)
27477   {
27478     qDebug() << Q_FUNC_INFO << "invalid key or value axis";
27479     end = mDataContainer->constEnd();
27480     begin = end;
27481     return;
27482   }
27483   if (!mDataPlottable || rangeRestriction.isEmpty())
27484   {
27485     end = mDataContainer->constEnd();
27486     begin = end;
27487     return;
27488   }
27489   if (!mDataPlottable->interface1D()->sortKeyIsMainKey())
27490   {
27491     // if the sort key isn't the main key, it's not possible to find a contiguous range of visible
27492     // data points, so this method then only applies the range restriction and otherwise returns
27493     // the full data range. Visibility checks must be done on a per-datapoin-basis during drawing
27494     QCPDataRange dataRange(0, mDataContainer->size());
27495     dataRange = dataRange.bounded(rangeRestriction);
27496     begin = mDataContainer->constBegin()+dataRange.begin();
27497     end = mDataContainer->constBegin()+dataRange.end();
27498     return;
27499   }
27500 
27501   // get visible data range via interface from data plottable, and then restrict to available error data points:
27502   const int n = qMin(mDataContainer->size(), mDataPlottable->interface1D()->dataCount());
27503   int beginIndex = mDataPlottable->interface1D()->findBegin(keyAxis->range().lower);
27504   int endIndex = mDataPlottable->interface1D()->findEnd(keyAxis->range().upper);
27505   int i = beginIndex;
27506   while (i > 0 && i < n && i > rangeRestriction.begin())
27507   {
27508     if (errorBarVisible(i))
27509       beginIndex = i;
27510     --i;
27511   }
27512   i = endIndex;
27513   while (i >= 0 && i < n && i < rangeRestriction.end())
27514   {
27515     if (errorBarVisible(i))
27516       endIndex = i+1;
27517     ++i;
27518   }
27519   QCPDataRange dataRange(beginIndex, endIndex);
27520   dataRange = dataRange.bounded(rangeRestriction.bounded(QCPDataRange(0, mDataContainer->size())));
27521   begin = mDataContainer->constBegin()+dataRange.begin();
27522   end = mDataContainer->constBegin()+dataRange.end();
27523 }
27524 
27525 /*! \internal
27526 
27527   Calculates the minimum distance in pixels the error bars' representation has from the given \a
27528   pixelPoint. This is used to determine whether the error bar was clicked or not, e.g. in \ref
27529   selectTest. The closest data point to \a pixelPoint is returned in \a closestData.
27530 */
pointDistance(const QPointF & pixelPoint,QCPErrorBarsDataContainer::const_iterator & closestData) const27531 double QCPErrorBars::pointDistance(const QPointF &pixelPoint, QCPErrorBarsDataContainer::const_iterator &closestData) const
27532 {
27533   closestData = mDataContainer->constEnd();
27534   if (!mDataPlottable || mDataContainer->isEmpty())
27535     return -1.0;
27536 
27537   QCPErrorBarsDataContainer::const_iterator begin, end;
27538   getVisibleDataBounds(begin, end, QCPDataRange(0, dataCount()));
27539 
27540   // calculate minimum distances to error backbones (whiskers are ignored for speed) and find closestData iterator:
27541   double minDistSqr = std::numeric_limits<double>::max();
27542   QVector<QLineF> backbones, whiskers;
27543   for (QCPErrorBarsDataContainer::const_iterator it=begin; it!=end; ++it)
27544   {
27545     getErrorBarLines(it, backbones, whiskers);
27546     for (int i=0; i<backbones.size(); ++i)
27547     {
27548       const double currentDistSqr = QCPVector2D(pixelPoint).distanceSquaredToLine(backbones.at(i));
27549       if (currentDistSqr < minDistSqr)
27550       {
27551         minDistSqr = currentDistSqr;
27552         closestData = it;
27553       }
27554     }
27555   }
27556   return qSqrt(minDistSqr);
27557 }
27558 
27559 /*! \internal
27560 
27561   \note This method is identical to \ref QCPAbstractPlottable1D::getDataSegments but needs to be
27562   reproduced here since the \ref QCPErrorBars plottable, as a special case that doesn't have its
27563   own key/value data coordinates, doesn't derive from \ref QCPAbstractPlottable1D. See the
27564   documentation there for details.
27565 */
getDataSegments(QList<QCPDataRange> & selectedSegments,QList<QCPDataRange> & unselectedSegments) const27566 void QCPErrorBars::getDataSegments(QList<QCPDataRange> &selectedSegments, QList<QCPDataRange> &unselectedSegments) const
27567 {
27568   selectedSegments.clear();
27569   unselectedSegments.clear();
27570   if (mSelectable == QCP::stWhole) // stWhole selection type draws the entire plottable with selected style if mSelection isn't empty
27571   {
27572     if (selected())
27573       selectedSegments << QCPDataRange(0, dataCount());
27574     else
27575       unselectedSegments << QCPDataRange(0, dataCount());
27576   } else
27577   {
27578     QCPDataSelection sel(selection());
27579     sel.simplify();
27580     selectedSegments = sel.dataRanges();
27581     unselectedSegments = sel.inverse(QCPDataRange(0, dataCount())).dataRanges();
27582   }
27583 }
27584 
27585 /*! \internal
27586 
27587   Returns whether the error bar at the specified \a index is visible within the current key axis
27588   range.
27589 
27590   This method assumes for performance reasons without checking that the key axis, the value axis,
27591   and the data plottable (\ref setDataPlottable) are not zero and that \a index is within valid
27592   bounds of this \ref QCPErrorBars instance and the bounds of the data plottable.
27593 */
errorBarVisible(int index) const27594 bool QCPErrorBars::errorBarVisible(int index) const
27595 {
27596   QPointF centerPixel = mDataPlottable->interface1D()->dataPixelPosition(index);
27597   const double centerKeyPixel = mKeyAxis->orientation() == Qt::Horizontal ? centerPixel.x() : centerPixel.y();
27598   if (qIsNaN(centerKeyPixel))
27599     return false;
27600 
27601   double keyMin, keyMax;
27602   if (mErrorType == etKeyError)
27603   {
27604     const double centerKey = mKeyAxis->pixelToCoord(centerKeyPixel);
27605     const double errorPlus = mDataContainer->at(index).errorPlus;
27606     const double errorMinus = mDataContainer->at(index).errorMinus;
27607     keyMax = centerKey+(qIsNaN(errorPlus) ? 0 : errorPlus);
27608     keyMin = centerKey-(qIsNaN(errorMinus) ? 0 : errorMinus);
27609   } else // mErrorType == etValueError
27610   {
27611     keyMax = mKeyAxis->pixelToCoord(centerKeyPixel+mWhiskerWidth*0.5*mKeyAxis->pixelOrientation());
27612     keyMin = mKeyAxis->pixelToCoord(centerKeyPixel-mWhiskerWidth*0.5*mKeyAxis->pixelOrientation());
27613   }
27614   return ((keyMax > mKeyAxis->range().lower) && (keyMin < mKeyAxis->range().upper));
27615 }
27616 
27617 /*! \internal
27618 
27619   Returns whether \a line intersects (or is contained in) \a pixelRect.
27620 
27621   \a line is assumed to be either perfectly horizontal or perfectly vertical, as is the case for
27622   error bar lines.
27623 */
rectIntersectsLine(const QRectF & pixelRect,const QLineF & line) const27624 bool QCPErrorBars::rectIntersectsLine(const QRectF &pixelRect, const QLineF &line) const
27625 {
27626   if (pixelRect.left() > line.x1() && pixelRect.left() > line.x2())
27627     return false;
27628   else if (pixelRect.right() < line.x1() && pixelRect.right() < line.x2())
27629     return false;
27630   else if (pixelRect.top() > line.y1() && pixelRect.top() > line.y2())
27631     return false;
27632   else if (pixelRect.bottom() < line.y1() && pixelRect.bottom() < line.y2())
27633     return false;
27634   else
27635     return true;
27636 }
27637 /* end of 'src/plottables/plottable-errorbar.cpp' */
27638 
27639 
27640 /* including file 'src/items/item-straightline.cpp', size 7592               */
27641 /* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
27642 
27643 ////////////////////////////////////////////////////////////////////////////////////////////////////
27644 //////////////////// QCPItemStraightLine
27645 ////////////////////////////////////////////////////////////////////////////////////////////////////
27646 
27647 /*! \class QCPItemStraightLine
27648   \brief A straight line that spans infinitely in both directions
27649 
27650   \image html QCPItemStraightLine.png "Straight line example. Blue dotted circles are anchors, solid blue discs are positions."
27651 
27652   It has two positions, \a point1 and \a point2, which define the straight line.
27653 */
27654 
27655 /*!
27656   Creates a straight line item and sets default values.
27657 
27658   The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
27659   ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
27660 */
QCPItemStraightLine(QCustomPlot * parentPlot)27661 QCPItemStraightLine::QCPItemStraightLine(QCustomPlot *parentPlot) :
27662   QCPAbstractItem(parentPlot),
27663   point1(createPosition(QLatin1String("point1"))),
27664   point2(createPosition(QLatin1String("point2")))
27665 {
27666   point1->setCoords(0, 0);
27667   point2->setCoords(1, 1);
27668 
27669   setPen(QPen(Qt::black));
27670   setSelectedPen(QPen(Qt::blue,2));
27671 }
27672 
~QCPItemStraightLine()27673 QCPItemStraightLine::~QCPItemStraightLine()
27674 {
27675 }
27676 
27677 /*!
27678   Sets the pen that will be used to draw the line
27679 
27680   \see setSelectedPen
27681 */
setPen(const QPen & pen)27682 void QCPItemStraightLine::setPen(const QPen &pen)
27683 {
27684   mPen = pen;
27685 }
27686 
27687 /*!
27688   Sets the pen that will be used to draw the line when selected
27689 
27690   \see setPen, setSelected
27691 */
setSelectedPen(const QPen & pen)27692 void QCPItemStraightLine::setSelectedPen(const QPen &pen)
27693 {
27694   mSelectedPen = pen;
27695 }
27696 
27697 /* inherits documentation from base class */
selectTest(const QPointF & pos,bool onlySelectable,QVariant * details) const27698 double QCPItemStraightLine::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
27699 {
27700   Q_UNUSED(details)
27701   if (onlySelectable && !mSelectable)
27702     return -1;
27703 
27704   return QCPVector2D(pos).distanceToStraightLine(point1->pixelPosition(), point2->pixelPosition()-point1->pixelPosition());
27705 }
27706 
27707 /* inherits documentation from base class */
draw(QCPPainter * painter)27708 void QCPItemStraightLine::draw(QCPPainter *painter)
27709 {
27710   QCPVector2D start(point1->pixelPosition());
27711   QCPVector2D end(point2->pixelPosition());
27712   // get visible segment of straight line inside clipRect:
27713   double clipPad = mainPen().widthF();
27714   QLineF line = getRectClippedStraightLine(start, end-start, clipRect().adjusted(-clipPad, -clipPad, clipPad, clipPad));
27715   // paint visible segment, if existent:
27716   if (!line.isNull())
27717   {
27718     painter->setPen(mainPen());
27719     painter->drawLine(line);
27720   }
27721 }
27722 
27723 /*! \internal
27724 
27725   Returns the section of the straight line defined by \a base and direction vector \a
27726   vec, that is visible in the specified \a rect.
27727 
27728   This is a helper function for \ref draw.
27729 */
getRectClippedStraightLine(const QCPVector2D & base,const QCPVector2D & vec,const QRect & rect) const27730 QLineF QCPItemStraightLine::getRectClippedStraightLine(const QCPVector2D &base, const QCPVector2D &vec, const QRect &rect) const
27731 {
27732   double bx, by;
27733   double gamma;
27734   QLineF result;
27735   if (vec.x() == 0 && vec.y() == 0)
27736     return result;
27737   if (qFuzzyIsNull(vec.x())) // line is vertical
27738   {
27739     // check top of rect:
27740     bx = rect.left();
27741     by = rect.top();
27742     gamma = base.x()-bx + (by-base.y())*vec.x()/vec.y();
27743     if (gamma >= 0 && gamma <= rect.width())
27744       result.setLine(bx+gamma, rect.top(), bx+gamma, rect.bottom()); // no need to check bottom because we know line is vertical
27745   } else if (qFuzzyIsNull(vec.y())) // line is horizontal
27746   {
27747     // check left of rect:
27748     bx = rect.left();
27749     by = rect.top();
27750     gamma = base.y()-by + (bx-base.x())*vec.y()/vec.x();
27751     if (gamma >= 0 && gamma <= rect.height())
27752       result.setLine(rect.left(), by+gamma, rect.right(), by+gamma); // no need to check right because we know line is horizontal
27753   } else // line is skewed
27754   {
27755     QList<QCPVector2D> pointVectors;
27756     // check top of rect:
27757     bx = rect.left();
27758     by = rect.top();
27759     gamma = base.x()-bx + (by-base.y())*vec.x()/vec.y();
27760     if (gamma >= 0 && gamma <= rect.width())
27761       pointVectors.append(QCPVector2D(bx+gamma, by));
27762     // check bottom of rect:
27763     bx = rect.left();
27764     by = rect.bottom();
27765     gamma = base.x()-bx + (by-base.y())*vec.x()/vec.y();
27766     if (gamma >= 0 && gamma <= rect.width())
27767       pointVectors.append(QCPVector2D(bx+gamma, by));
27768     // check left of rect:
27769     bx = rect.left();
27770     by = rect.top();
27771     gamma = base.y()-by + (bx-base.x())*vec.y()/vec.x();
27772     if (gamma >= 0 && gamma <= rect.height())
27773       pointVectors.append(QCPVector2D(bx, by+gamma));
27774     // check right of rect:
27775     bx = rect.right();
27776     by = rect.top();
27777     gamma = base.y()-by + (bx-base.x())*vec.y()/vec.x();
27778     if (gamma >= 0 && gamma <= rect.height())
27779       pointVectors.append(QCPVector2D(bx, by+gamma));
27780 
27781     // evaluate points:
27782     if (pointVectors.size() == 2)
27783     {
27784       result.setPoints(pointVectors.at(0).toPointF(), pointVectors.at(1).toPointF());
27785     } else if (pointVectors.size() > 2)
27786     {
27787       // line probably goes through corner of rect, and we got two points there. single out the point pair with greatest distance:
27788       double distSqrMax = 0;
27789       QCPVector2D pv1, pv2;
27790       for (int i=0; i<pointVectors.size()-1; ++i)
27791       {
27792         for (int k=i+1; k<pointVectors.size(); ++k)
27793         {
27794           double distSqr = (pointVectors.at(i)-pointVectors.at(k)).lengthSquared();
27795           if (distSqr > distSqrMax)
27796           {
27797             pv1 = pointVectors.at(i);
27798             pv2 = pointVectors.at(k);
27799             distSqrMax = distSqr;
27800           }
27801         }
27802       }
27803       result.setPoints(pv1.toPointF(), pv2.toPointF());
27804     }
27805   }
27806   return result;
27807 }
27808 
27809 /*! \internal
27810 
27811   Returns the pen that should be used for drawing lines. Returns mPen when the
27812   item is not selected and mSelectedPen when it is.
27813 */
mainPen() const27814 QPen QCPItemStraightLine::mainPen() const
27815 {
27816   return mSelected ? mSelectedPen : mPen;
27817 }
27818 /* end of 'src/items/item-straightline.cpp' */
27819 
27820 
27821 /* including file 'src/items/item-line.cpp', size 8498                       */
27822 /* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
27823 
27824 ////////////////////////////////////////////////////////////////////////////////////////////////////
27825 //////////////////// QCPItemLine
27826 ////////////////////////////////////////////////////////////////////////////////////////////////////
27827 
27828 /*! \class QCPItemLine
27829   \brief A line from one point to another
27830 
27831   \image html QCPItemLine.png "Line example. Blue dotted circles are anchors, solid blue discs are positions."
27832 
27833   It has two positions, \a start and \a end, which define the end points of the line.
27834 
27835   With \ref setHead and \ref setTail you may set different line ending styles, e.g. to create an arrow.
27836 */
27837 
27838 /*!
27839   Creates a line item and sets default values.
27840 
27841   The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
27842   ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
27843 */
QCPItemLine(QCustomPlot * parentPlot)27844 QCPItemLine::QCPItemLine(QCustomPlot *parentPlot) :
27845   QCPAbstractItem(parentPlot),
27846   start(createPosition(QLatin1String("start"))),
27847   end(createPosition(QLatin1String("end")))
27848 {
27849   start->setCoords(0, 0);
27850   end->setCoords(1, 1);
27851 
27852   setPen(QPen(Qt::black));
27853   setSelectedPen(QPen(Qt::blue,2));
27854 }
27855 
~QCPItemLine()27856 QCPItemLine::~QCPItemLine()
27857 {
27858 }
27859 
27860 /*!
27861   Sets the pen that will be used to draw the line
27862 
27863   \see setSelectedPen
27864 */
setPen(const QPen & pen)27865 void QCPItemLine::setPen(const QPen &pen)
27866 {
27867   mPen = pen;
27868 }
27869 
27870 /*!
27871   Sets the pen that will be used to draw the line when selected
27872 
27873   \see setPen, setSelected
27874 */
setSelectedPen(const QPen & pen)27875 void QCPItemLine::setSelectedPen(const QPen &pen)
27876 {
27877   mSelectedPen = pen;
27878 }
27879 
27880 /*!
27881   Sets the line ending style of the head. The head corresponds to the \a end position.
27882 
27883   Note that due to the overloaded QCPLineEnding constructor, you may directly specify
27884   a QCPLineEnding::EndingStyle here, e.g. \code setHead(QCPLineEnding::esSpikeArrow) \endcode
27885 
27886   \see setTail
27887 */
setHead(const QCPLineEnding & head)27888 void QCPItemLine::setHead(const QCPLineEnding &head)
27889 {
27890   mHead = head;
27891 }
27892 
27893 /*!
27894   Sets the line ending style of the tail. The tail corresponds to the \a start position.
27895 
27896   Note that due to the overloaded QCPLineEnding constructor, you may directly specify
27897   a QCPLineEnding::EndingStyle here, e.g. \code setTail(QCPLineEnding::esSpikeArrow) \endcode
27898 
27899   \see setHead
27900 */
setTail(const QCPLineEnding & tail)27901 void QCPItemLine::setTail(const QCPLineEnding &tail)
27902 {
27903   mTail = tail;
27904 }
27905 
27906 /* inherits documentation from base class */
selectTest(const QPointF & pos,bool onlySelectable,QVariant * details) const27907 double QCPItemLine::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
27908 {
27909   Q_UNUSED(details)
27910   if (onlySelectable && !mSelectable)
27911     return -1;
27912 
27913   return qSqrt(QCPVector2D(pos).distanceSquaredToLine(start->pixelPosition(), end->pixelPosition()));
27914 }
27915 
27916 /* inherits documentation from base class */
draw(QCPPainter * painter)27917 void QCPItemLine::draw(QCPPainter *painter)
27918 {
27919   QCPVector2D startVec(start->pixelPosition());
27920   QCPVector2D endVec(end->pixelPosition());
27921   if (qFuzzyIsNull((startVec-endVec).lengthSquared()))
27922     return;
27923   // get visible segment of straight line inside clipRect:
27924   double clipPad = qMax(mHead.boundingDistance(), mTail.boundingDistance());
27925   clipPad = qMax(clipPad, (double)mainPen().widthF());
27926   QLineF line = getRectClippedLine(startVec, endVec, clipRect().adjusted(-clipPad, -clipPad, clipPad, clipPad));
27927   // paint visible segment, if existent:
27928   if (!line.isNull())
27929   {
27930     painter->setPen(mainPen());
27931     painter->drawLine(line);
27932     painter->setBrush(Qt::SolidPattern);
27933     if (mTail.style() != QCPLineEnding::esNone)
27934       mTail.draw(painter, startVec, startVec-endVec);
27935     if (mHead.style() != QCPLineEnding::esNone)
27936       mHead.draw(painter, endVec, endVec-startVec);
27937   }
27938 }
27939 
27940 /*! \internal
27941 
27942   Returns the section of the line defined by \a start and \a end, that is visible in the specified
27943   \a rect.
27944 
27945   This is a helper function for \ref draw.
27946 */
getRectClippedLine(const QCPVector2D & start,const QCPVector2D & end,const QRect & rect) const27947 QLineF QCPItemLine::getRectClippedLine(const QCPVector2D &start, const QCPVector2D &end, const QRect &rect) const
27948 {
27949   bool containsStart = rect.contains(start.x(), start.y());
27950   bool containsEnd = rect.contains(end.x(), end.y());
27951   if (containsStart && containsEnd)
27952     return QLineF(start.toPointF(), end.toPointF());
27953 
27954   QCPVector2D base = start;
27955   QCPVector2D vec = end-start;
27956   double bx, by;
27957   double gamma, mu;
27958   QLineF result;
27959   QList<QCPVector2D> pointVectors;
27960 
27961   if (!qFuzzyIsNull(vec.y())) // line is not horizontal
27962   {
27963     // check top of rect:
27964     bx = rect.left();
27965     by = rect.top();
27966     mu = (by-base.y())/vec.y();
27967     if (mu >= 0 && mu <= 1)
27968     {
27969       gamma = base.x()-bx + mu*vec.x();
27970       if (gamma >= 0 && gamma <= rect.width())
27971         pointVectors.append(QCPVector2D(bx+gamma, by));
27972     }
27973     // check bottom of rect:
27974     bx = rect.left();
27975     by = rect.bottom();
27976     mu = (by-base.y())/vec.y();
27977     if (mu >= 0 && mu <= 1)
27978     {
27979       gamma = base.x()-bx + mu*vec.x();
27980       if (gamma >= 0 && gamma <= rect.width())
27981         pointVectors.append(QCPVector2D(bx+gamma, by));
27982     }
27983   }
27984   if (!qFuzzyIsNull(vec.x())) // line is not vertical
27985   {
27986     // check left of rect:
27987     bx = rect.left();
27988     by = rect.top();
27989     mu = (bx-base.x())/vec.x();
27990     if (mu >= 0 && mu <= 1)
27991     {
27992       gamma = base.y()-by + mu*vec.y();
27993       if (gamma >= 0 && gamma <= rect.height())
27994         pointVectors.append(QCPVector2D(bx, by+gamma));
27995     }
27996     // check right of rect:
27997     bx = rect.right();
27998     by = rect.top();
27999     mu = (bx-base.x())/vec.x();
28000     if (mu >= 0 && mu <= 1)
28001     {
28002       gamma = base.y()-by + mu*vec.y();
28003       if (gamma >= 0 && gamma <= rect.height())
28004         pointVectors.append(QCPVector2D(bx, by+gamma));
28005     }
28006   }
28007 
28008   if (containsStart)
28009     pointVectors.append(start);
28010   if (containsEnd)
28011     pointVectors.append(end);
28012 
28013   // evaluate points:
28014   if (pointVectors.size() == 2)
28015   {
28016     result.setPoints(pointVectors.at(0).toPointF(), pointVectors.at(1).toPointF());
28017   } else if (pointVectors.size() > 2)
28018   {
28019     // line probably goes through corner of rect, and we got two points there. single out the point pair with greatest distance:
28020     double distSqrMax = 0;
28021     QCPVector2D pv1, pv2;
28022     for (int i=0; i<pointVectors.size()-1; ++i)
28023     {
28024       for (int k=i+1; k<pointVectors.size(); ++k)
28025       {
28026         double distSqr = (pointVectors.at(i)-pointVectors.at(k)).lengthSquared();
28027         if (distSqr > distSqrMax)
28028         {
28029           pv1 = pointVectors.at(i);
28030           pv2 = pointVectors.at(k);
28031           distSqrMax = distSqr;
28032         }
28033       }
28034     }
28035     result.setPoints(pv1.toPointF(), pv2.toPointF());
28036   }
28037   return result;
28038 }
28039 
28040 /*! \internal
28041 
28042   Returns the pen that should be used for drawing lines. Returns mPen when the
28043   item is not selected and mSelectedPen when it is.
28044 */
mainPen() const28045 QPen QCPItemLine::mainPen() const
28046 {
28047   return mSelected ? mSelectedPen : mPen;
28048 }
28049 /* end of 'src/items/item-line.cpp' */
28050 
28051 
28052 /* including file 'src/items/item-curve.cpp', size 7159                      */
28053 /* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
28054 
28055 ////////////////////////////////////////////////////////////////////////////////////////////////////
28056 //////////////////// QCPItemCurve
28057 ////////////////////////////////////////////////////////////////////////////////////////////////////
28058 
28059 /*! \class QCPItemCurve
28060   \brief A curved line from one point to another
28061 
28062   \image html QCPItemCurve.png "Curve example. Blue dotted circles are anchors, solid blue discs are positions."
28063 
28064   It has four positions, \a start and \a end, which define the end points of the line, and two
28065   control points which define the direction the line exits from the start and the direction from
28066   which it approaches the end: \a startDir and \a endDir.
28067 
28068   With \ref setHead and \ref setTail you may set different line ending styles, e.g. to create an
28069   arrow.
28070 
28071   Often it is desirable for the control points to stay at fixed relative positions to the start/end
28072   point. This can be achieved by setting the parent anchor e.g. of \a startDir simply to \a start,
28073   and then specify the desired pixel offset with QCPItemPosition::setCoords on \a startDir.
28074 */
28075 
28076 /*!
28077   Creates a curve item and sets default values.
28078 
28079   The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
28080   ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
28081 */
QCPItemCurve(QCustomPlot * parentPlot)28082 QCPItemCurve::QCPItemCurve(QCustomPlot *parentPlot) :
28083   QCPAbstractItem(parentPlot),
28084   start(createPosition(QLatin1String("start"))),
28085   startDir(createPosition(QLatin1String("startDir"))),
28086   endDir(createPosition(QLatin1String("endDir"))),
28087   end(createPosition(QLatin1String("end")))
28088 {
28089   start->setCoords(0, 0);
28090   startDir->setCoords(0.5, 0);
28091   endDir->setCoords(0, 0.5);
28092   end->setCoords(1, 1);
28093 
28094   setPen(QPen(Qt::black));
28095   setSelectedPen(QPen(Qt::blue,2));
28096 }
28097 
~QCPItemCurve()28098 QCPItemCurve::~QCPItemCurve()
28099 {
28100 }
28101 
28102 /*!
28103   Sets the pen that will be used to draw the line
28104 
28105   \see setSelectedPen
28106 */
setPen(const QPen & pen)28107 void QCPItemCurve::setPen(const QPen &pen)
28108 {
28109   mPen = pen;
28110 }
28111 
28112 /*!
28113   Sets the pen that will be used to draw the line when selected
28114 
28115   \see setPen, setSelected
28116 */
setSelectedPen(const QPen & pen)28117 void QCPItemCurve::setSelectedPen(const QPen &pen)
28118 {
28119   mSelectedPen = pen;
28120 }
28121 
28122 /*!
28123   Sets the line ending style of the head. The head corresponds to the \a end position.
28124 
28125   Note that due to the overloaded QCPLineEnding constructor, you may directly specify
28126   a QCPLineEnding::EndingStyle here, e.g. \code setHead(QCPLineEnding::esSpikeArrow) \endcode
28127 
28128   \see setTail
28129 */
setHead(const QCPLineEnding & head)28130 void QCPItemCurve::setHead(const QCPLineEnding &head)
28131 {
28132   mHead = head;
28133 }
28134 
28135 /*!
28136   Sets the line ending style of the tail. The tail corresponds to the \a start position.
28137 
28138   Note that due to the overloaded QCPLineEnding constructor, you may directly specify
28139   a QCPLineEnding::EndingStyle here, e.g. \code setTail(QCPLineEnding::esSpikeArrow) \endcode
28140 
28141   \see setHead
28142 */
setTail(const QCPLineEnding & tail)28143 void QCPItemCurve::setTail(const QCPLineEnding &tail)
28144 {
28145   mTail = tail;
28146 }
28147 
28148 /* inherits documentation from base class */
selectTest(const QPointF & pos,bool onlySelectable,QVariant * details) const28149 double QCPItemCurve::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
28150 {
28151   Q_UNUSED(details)
28152   if (onlySelectable && !mSelectable)
28153     return -1;
28154 
28155   QPointF startVec(start->pixelPosition());
28156   QPointF startDirVec(startDir->pixelPosition());
28157   QPointF endDirVec(endDir->pixelPosition());
28158   QPointF endVec(end->pixelPosition());
28159 
28160   QPainterPath cubicPath(startVec);
28161   cubicPath.cubicTo(startDirVec, endDirVec, endVec);
28162 
28163   QPolygonF polygon = cubicPath.toSubpathPolygons().first();
28164   QCPVector2D p(pos);
28165   double minDistSqr = std::numeric_limits<double>::max();
28166   for (int i=1; i<polygon.size(); ++i)
28167   {
28168     double distSqr = p.distanceSquaredToLine(polygon.at(i-1), polygon.at(i));
28169     if (distSqr < minDistSqr)
28170       minDistSqr = distSqr;
28171   }
28172   return qSqrt(minDistSqr);
28173 }
28174 
28175 /* inherits documentation from base class */
draw(QCPPainter * painter)28176 void QCPItemCurve::draw(QCPPainter *painter)
28177 {
28178   QCPVector2D startVec(start->pixelPosition());
28179   QCPVector2D startDirVec(startDir->pixelPosition());
28180   QCPVector2D endDirVec(endDir->pixelPosition());
28181   QCPVector2D endVec(end->pixelPosition());
28182   if ((endVec-startVec).length() > 1e10) // too large curves cause crash
28183     return;
28184 
28185   QPainterPath cubicPath(startVec.toPointF());
28186   cubicPath.cubicTo(startDirVec.toPointF(), endDirVec.toPointF(), endVec.toPointF());
28187 
28188   // paint visible segment, if existent:
28189   QRect clip = clipRect().adjusted(-mainPen().widthF(), -mainPen().widthF(), mainPen().widthF(), mainPen().widthF());
28190   QRect cubicRect = cubicPath.controlPointRect().toRect();
28191   if (cubicRect.isEmpty()) // may happen when start and end exactly on same x or y position
28192     cubicRect.adjust(0, 0, 1, 1);
28193   if (clip.intersects(cubicRect))
28194   {
28195     painter->setPen(mainPen());
28196     painter->drawPath(cubicPath);
28197     painter->setBrush(Qt::SolidPattern);
28198     if (mTail.style() != QCPLineEnding::esNone)
28199       mTail.draw(painter, startVec, M_PI-cubicPath.angleAtPercent(0)/180.0*M_PI);
28200     if (mHead.style() != QCPLineEnding::esNone)
28201       mHead.draw(painter, endVec, -cubicPath.angleAtPercent(1)/180.0*M_PI);
28202   }
28203 }
28204 
28205 /*! \internal
28206 
28207   Returns the pen that should be used for drawing lines. Returns mPen when the
28208   item is not selected and mSelectedPen when it is.
28209 */
mainPen() const28210 QPen QCPItemCurve::mainPen() const
28211 {
28212   return mSelected ? mSelectedPen : mPen;
28213 }
28214 /* end of 'src/items/item-curve.cpp' */
28215 
28216 
28217 /* including file 'src/items/item-rect.cpp', size 6479                       */
28218 /* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
28219 
28220 ////////////////////////////////////////////////////////////////////////////////////////////////////
28221 //////////////////// QCPItemRect
28222 ////////////////////////////////////////////////////////////////////////////////////////////////////
28223 
28224 /*! \class QCPItemRect
28225   \brief A rectangle
28226 
28227   \image html QCPItemRect.png "Rectangle example. Blue dotted circles are anchors, solid blue discs are positions."
28228 
28229   It has two positions, \a topLeft and \a bottomRight, which define the rectangle.
28230 */
28231 
28232 /*!
28233   Creates a rectangle item and sets default values.
28234 
28235   The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
28236   ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
28237 */
QCPItemRect(QCustomPlot * parentPlot)28238 QCPItemRect::QCPItemRect(QCustomPlot *parentPlot) :
28239   QCPAbstractItem(parentPlot),
28240   topLeft(createPosition(QLatin1String("topLeft"))),
28241   bottomRight(createPosition(QLatin1String("bottomRight"))),
28242   top(createAnchor(QLatin1String("top"), aiTop)),
28243   topRight(createAnchor(QLatin1String("topRight"), aiTopRight)),
28244   right(createAnchor(QLatin1String("right"), aiRight)),
28245   bottom(createAnchor(QLatin1String("bottom"), aiBottom)),
28246   bottomLeft(createAnchor(QLatin1String("bottomLeft"), aiBottomLeft)),
28247   left(createAnchor(QLatin1String("left"), aiLeft))
28248 {
28249   topLeft->setCoords(0, 1);
28250   bottomRight->setCoords(1, 0);
28251 
28252   setPen(QPen(Qt::black));
28253   setSelectedPen(QPen(Qt::blue,2));
28254   setBrush(Qt::NoBrush);
28255   setSelectedBrush(Qt::NoBrush);
28256 }
28257 
~QCPItemRect()28258 QCPItemRect::~QCPItemRect()
28259 {
28260 }
28261 
28262 /*!
28263   Sets the pen that will be used to draw the line of the rectangle
28264 
28265   \see setSelectedPen, setBrush
28266 */
setPen(const QPen & pen)28267 void QCPItemRect::setPen(const QPen &pen)
28268 {
28269   mPen = pen;
28270 }
28271 
28272 /*!
28273   Sets the pen that will be used to draw the line of the rectangle when selected
28274 
28275   \see setPen, setSelected
28276 */
setSelectedPen(const QPen & pen)28277 void QCPItemRect::setSelectedPen(const QPen &pen)
28278 {
28279   mSelectedPen = pen;
28280 }
28281 
28282 /*!
28283   Sets the brush that will be used to fill the rectangle. To disable filling, set \a brush to
28284   Qt::NoBrush.
28285 
28286   \see setSelectedBrush, setPen
28287 */
setBrush(const QBrush & brush)28288 void QCPItemRect::setBrush(const QBrush &brush)
28289 {
28290   mBrush = brush;
28291 }
28292 
28293 /*!
28294   Sets the brush that will be used to fill the rectangle when selected. To disable filling, set \a
28295   brush to Qt::NoBrush.
28296 
28297   \see setBrush
28298 */
setSelectedBrush(const QBrush & brush)28299 void QCPItemRect::setSelectedBrush(const QBrush &brush)
28300 {
28301   mSelectedBrush = brush;
28302 }
28303 
28304 /* inherits documentation from base class */
selectTest(const QPointF & pos,bool onlySelectable,QVariant * details) const28305 double QCPItemRect::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
28306 {
28307   Q_UNUSED(details)
28308   if (onlySelectable && !mSelectable)
28309     return -1;
28310 
28311   QRectF rect = QRectF(topLeft->pixelPosition(), bottomRight->pixelPosition()).normalized();
28312   bool filledRect = mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0;
28313   return rectDistance(rect, pos, filledRect);
28314 }
28315 
28316 /* inherits documentation from base class */
draw(QCPPainter * painter)28317 void QCPItemRect::draw(QCPPainter *painter)
28318 {
28319   QPointF p1 = topLeft->pixelPosition();
28320   QPointF p2 = bottomRight->pixelPosition();
28321   if (p1.toPoint() == p2.toPoint())
28322     return;
28323   QRectF rect = QRectF(p1, p2).normalized();
28324   double clipPad = mainPen().widthF();
28325   QRectF boundingRect = rect.adjusted(-clipPad, -clipPad, clipPad, clipPad);
28326   if (boundingRect.intersects(clipRect())) // only draw if bounding rect of rect item is visible in cliprect
28327   {
28328     painter->setPen(mainPen());
28329     painter->setBrush(mainBrush());
28330     painter->drawRect(rect);
28331   }
28332 }
28333 
28334 /* inherits documentation from base class */
anchorPixelPosition(int anchorId) const28335 QPointF QCPItemRect::anchorPixelPosition(int anchorId) const
28336 {
28337   QRectF rect = QRectF(topLeft->pixelPosition(), bottomRight->pixelPosition());
28338   switch (anchorId)
28339   {
28340     case aiTop:         return (rect.topLeft()+rect.topRight())*0.5;
28341     case aiTopRight:    return rect.topRight();
28342     case aiRight:       return (rect.topRight()+rect.bottomRight())*0.5;
28343     case aiBottom:      return (rect.bottomLeft()+rect.bottomRight())*0.5;
28344     case aiBottomLeft:  return rect.bottomLeft();
28345     case aiLeft:        return (rect.topLeft()+rect.bottomLeft())*0.5;
28346   }
28347 
28348   qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId;
28349   return QPointF();
28350 }
28351 
28352 /*! \internal
28353 
28354   Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected
28355   and mSelectedPen when it is.
28356 */
mainPen() const28357 QPen QCPItemRect::mainPen() const
28358 {
28359   return mSelected ? mSelectedPen : mPen;
28360 }
28361 
28362 /*! \internal
28363 
28364   Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item
28365   is not selected and mSelectedBrush when it is.
28366 */
mainBrush() const28367 QBrush QCPItemRect::mainBrush() const
28368 {
28369   return mSelected ? mSelectedBrush : mBrush;
28370 }
28371 /* end of 'src/items/item-rect.cpp' */
28372 
28373 
28374 /* including file 'src/items/item-text.cpp', size 13338                      */
28375 /* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
28376 
28377 ////////////////////////////////////////////////////////////////////////////////////////////////////
28378 //////////////////// QCPItemText
28379 ////////////////////////////////////////////////////////////////////////////////////////////////////
28380 
28381 /*! \class QCPItemText
28382   \brief A text label
28383 
28384   \image html QCPItemText.png "Text example. Blue dotted circles are anchors, solid blue discs are positions."
28385 
28386   Its position is defined by the member \a position and the setting of \ref setPositionAlignment.
28387   The latter controls which part of the text rect shall be aligned with \a position.
28388 
28389   The text alignment itself (i.e. left, center, right) can be controlled with \ref
28390   setTextAlignment.
28391 
28392   The text may be rotated around the \a position point with \ref setRotation.
28393 */
28394 
28395 /*!
28396   Creates a text item and sets default values.
28397 
28398   The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
28399   ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
28400 */
QCPItemText(QCustomPlot * parentPlot)28401 QCPItemText::QCPItemText(QCustomPlot *parentPlot) :
28402   QCPAbstractItem(parentPlot),
28403   position(createPosition(QLatin1String("position"))),
28404   topLeft(createAnchor(QLatin1String("topLeft"), aiTopLeft)),
28405   top(createAnchor(QLatin1String("top"), aiTop)),
28406   topRight(createAnchor(QLatin1String("topRight"), aiTopRight)),
28407   right(createAnchor(QLatin1String("right"), aiRight)),
28408   bottomRight(createAnchor(QLatin1String("bottomRight"), aiBottomRight)),
28409   bottom(createAnchor(QLatin1String("bottom"), aiBottom)),
28410   bottomLeft(createAnchor(QLatin1String("bottomLeft"), aiBottomLeft)),
28411   left(createAnchor(QLatin1String("left"), aiLeft)),
28412   mText(QLatin1String("text")),
28413   mPositionAlignment(Qt::AlignCenter),
28414   mTextAlignment(Qt::AlignTop|Qt::AlignHCenter),
28415   mRotation(0)
28416 {
28417   position->setCoords(0, 0);
28418 
28419   setPen(Qt::NoPen);
28420   setSelectedPen(Qt::NoPen);
28421   setBrush(Qt::NoBrush);
28422   setSelectedBrush(Qt::NoBrush);
28423   setColor(Qt::black);
28424   setSelectedColor(Qt::blue);
28425 }
28426 
~QCPItemText()28427 QCPItemText::~QCPItemText()
28428 {
28429 }
28430 
28431 /*!
28432   Sets the color of the text.
28433 */
setColor(const QColor & color)28434 void QCPItemText::setColor(const QColor &color)
28435 {
28436   mColor = color;
28437 }
28438 
28439 /*!
28440   Sets the color of the text that will be used when the item is selected.
28441 */
setSelectedColor(const QColor & color)28442 void QCPItemText::setSelectedColor(const QColor &color)
28443 {
28444   mSelectedColor = color;
28445 }
28446 
28447 /*!
28448   Sets the pen that will be used do draw a rectangular border around the text. To disable the
28449   border, set \a pen to Qt::NoPen.
28450 
28451   \see setSelectedPen, setBrush, setPadding
28452 */
setPen(const QPen & pen)28453 void QCPItemText::setPen(const QPen &pen)
28454 {
28455   mPen = pen;
28456 }
28457 
28458 /*!
28459   Sets the pen that will be used do draw a rectangular border around the text, when the item is
28460   selected. To disable the border, set \a pen to Qt::NoPen.
28461 
28462   \see setPen
28463 */
setSelectedPen(const QPen & pen)28464 void QCPItemText::setSelectedPen(const QPen &pen)
28465 {
28466   mSelectedPen = pen;
28467 }
28468 
28469 /*!
28470   Sets the brush that will be used do fill the background of the text. To disable the
28471   background, set \a brush to Qt::NoBrush.
28472 
28473   \see setSelectedBrush, setPen, setPadding
28474 */
setBrush(const QBrush & brush)28475 void QCPItemText::setBrush(const QBrush &brush)
28476 {
28477   mBrush = brush;
28478 }
28479 
28480 /*!
28481   Sets the brush that will be used do fill the background of the text, when the item is selected. To disable the
28482   background, set \a brush to Qt::NoBrush.
28483 
28484   \see setBrush
28485 */
setSelectedBrush(const QBrush & brush)28486 void QCPItemText::setSelectedBrush(const QBrush &brush)
28487 {
28488   mSelectedBrush = brush;
28489 }
28490 
28491 /*!
28492   Sets the font of the text.
28493 
28494   \see setSelectedFont, setColor
28495 */
setFont(const QFont & font)28496 void QCPItemText::setFont(const QFont &font)
28497 {
28498   mFont = font;
28499 }
28500 
28501 /*!
28502   Sets the font of the text that will be used when the item is selected.
28503 
28504   \see setFont
28505 */
setSelectedFont(const QFont & font)28506 void QCPItemText::setSelectedFont(const QFont &font)
28507 {
28508   mSelectedFont = font;
28509 }
28510 
28511 /*!
28512   Sets the text that will be displayed. Multi-line texts are supported by inserting a line break
28513   character, e.g. '\n'.
28514 
28515   \see setFont, setColor, setTextAlignment
28516 */
setText(const QString & text)28517 void QCPItemText::setText(const QString &text)
28518 {
28519   mText = text;
28520 }
28521 
28522 /*!
28523   Sets which point of the text rect shall be aligned with \a position.
28524 
28525   Examples:
28526   \li If \a alignment is <tt>Qt::AlignHCenter | Qt::AlignTop</tt>, the text will be positioned such
28527   that the top of the text rect will be horizontally centered on \a position.
28528   \li If \a alignment is <tt>Qt::AlignLeft | Qt::AlignBottom</tt>, \a position will indicate the
28529   bottom left corner of the text rect.
28530 
28531   If you want to control the alignment of (multi-lined) text within the text rect, use \ref
28532   setTextAlignment.
28533 */
setPositionAlignment(Qt::Alignment alignment)28534 void QCPItemText::setPositionAlignment(Qt::Alignment alignment)
28535 {
28536   mPositionAlignment = alignment;
28537 }
28538 
28539 /*!
28540   Controls how (multi-lined) text is aligned inside the text rect (typically Qt::AlignLeft, Qt::AlignCenter or Qt::AlignRight).
28541 */
setTextAlignment(Qt::Alignment alignment)28542 void QCPItemText::setTextAlignment(Qt::Alignment alignment)
28543 {
28544   mTextAlignment = alignment;
28545 }
28546 
28547 /*!
28548   Sets the angle in degrees by which the text (and the text rectangle, if visible) will be rotated
28549   around \a position.
28550 */
setRotation(double degrees)28551 void QCPItemText::setRotation(double degrees)
28552 {
28553   mRotation = degrees;
28554 }
28555 
28556 /*!
28557   Sets the distance between the border of the text rectangle and the text. The appearance (and
28558   visibility) of the text rectangle can be controlled with \ref setPen and \ref setBrush.
28559 */
setPadding(const QMargins & padding)28560 void QCPItemText::setPadding(const QMargins &padding)
28561 {
28562   mPadding = padding;
28563 }
28564 
28565 /* inherits documentation from base class */
selectTest(const QPointF & pos,bool onlySelectable,QVariant * details) const28566 double QCPItemText::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
28567 {
28568   Q_UNUSED(details)
28569   if (onlySelectable && !mSelectable)
28570     return -1;
28571 
28572   // The rect may be rotated, so we transform the actual clicked pos to the rotated
28573   // coordinate system, so we can use the normal rectDistance function for non-rotated rects:
28574   QPointF positionPixels(position->pixelPosition());
28575   QTransform inputTransform;
28576   inputTransform.translate(positionPixels.x(), positionPixels.y());
28577   inputTransform.rotate(-mRotation);
28578   inputTransform.translate(-positionPixels.x(), -positionPixels.y());
28579   QPointF rotatedPos = inputTransform.map(pos);
28580   QFontMetrics fontMetrics(mFont);
28581   QRect textRect = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip|mTextAlignment, mText);
28582   QRect textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom());
28583   QPointF textPos = getTextDrawPoint(positionPixels, textBoxRect, mPositionAlignment);
28584   textBoxRect.moveTopLeft(textPos.toPoint());
28585 
28586   return rectDistance(textBoxRect, rotatedPos, true);
28587 }
28588 
28589 /* inherits documentation from base class */
draw(QCPPainter * painter)28590 void QCPItemText::draw(QCPPainter *painter)
28591 {
28592   QPointF pos(position->pixelPosition());
28593   QTransform transform = painter->transform();
28594   transform.translate(pos.x(), pos.y());
28595   if (!qFuzzyIsNull(mRotation))
28596     transform.rotate(mRotation);
28597   painter->setFont(mainFont());
28598   QRect textRect = painter->fontMetrics().boundingRect(0, 0, 0, 0, Qt::TextDontClip|mTextAlignment, mText);
28599   QRect textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom());
28600   QPointF textPos = getTextDrawPoint(QPointF(0, 0), textBoxRect, mPositionAlignment); // 0, 0 because the transform does the translation
28601   textRect.moveTopLeft(textPos.toPoint()+QPoint(mPadding.left(), mPadding.top()));
28602   textBoxRect.moveTopLeft(textPos.toPoint());
28603   double clipPad = mainPen().widthF();
28604   QRect boundingRect = textBoxRect.adjusted(-clipPad, -clipPad, clipPad, clipPad);
28605   if (transform.mapRect(boundingRect).intersects(painter->transform().mapRect(clipRect())))
28606   {
28607     painter->setTransform(transform);
28608     if ((mainBrush().style() != Qt::NoBrush && mainBrush().color().alpha() != 0) ||
28609         (mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0))
28610     {
28611       painter->setPen(mainPen());
28612       painter->setBrush(mainBrush());
28613       painter->drawRect(textBoxRect);
28614     }
28615     painter->setBrush(Qt::NoBrush);
28616     painter->setPen(QPen(mainColor()));
28617     painter->drawText(textRect, Qt::TextDontClip|mTextAlignment, mText);
28618   }
28619 }
28620 
28621 /* inherits documentation from base class */
anchorPixelPosition(int anchorId) const28622 QPointF QCPItemText::anchorPixelPosition(int anchorId) const
28623 {
28624   // get actual rect points (pretty much copied from draw function):
28625   QPointF pos(position->pixelPosition());
28626   QTransform transform;
28627   transform.translate(pos.x(), pos.y());
28628   if (!qFuzzyIsNull(mRotation))
28629     transform.rotate(mRotation);
28630   QFontMetrics fontMetrics(mainFont());
28631   QRect textRect = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip|mTextAlignment, mText);
28632   QRectF textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom());
28633   QPointF textPos = getTextDrawPoint(QPointF(0, 0), textBoxRect, mPositionAlignment); // 0, 0 because the transform does the translation
28634   textBoxRect.moveTopLeft(textPos.toPoint());
28635   QPolygonF rectPoly = transform.map(QPolygonF(textBoxRect));
28636 
28637   switch (anchorId)
28638   {
28639     case aiTopLeft:     return rectPoly.at(0);
28640     case aiTop:         return (rectPoly.at(0)+rectPoly.at(1))*0.5;
28641     case aiTopRight:    return rectPoly.at(1);
28642     case aiRight:       return (rectPoly.at(1)+rectPoly.at(2))*0.5;
28643     case aiBottomRight: return rectPoly.at(2);
28644     case aiBottom:      return (rectPoly.at(2)+rectPoly.at(3))*0.5;
28645     case aiBottomLeft:  return rectPoly.at(3);
28646     case aiLeft:        return (rectPoly.at(3)+rectPoly.at(0))*0.5;
28647   }
28648 
28649   qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId;
28650   return QPointF();
28651 }
28652 
28653 /*! \internal
28654 
28655   Returns the point that must be given to the QPainter::drawText function (which expects the top
28656   left point of the text rect), according to the position \a pos, the text bounding box \a rect and
28657   the requested \a positionAlignment.
28658 
28659   For example, if \a positionAlignment is <tt>Qt::AlignLeft | Qt::AlignBottom</tt> the returned point
28660   will be shifted upward by the height of \a rect, starting from \a pos. So if the text is finally
28661   drawn at that point, the lower left corner of the resulting text rect is at \a pos.
28662 */
getTextDrawPoint(const QPointF & pos,const QRectF & rect,Qt::Alignment positionAlignment) const28663 QPointF QCPItemText::getTextDrawPoint(const QPointF &pos, const QRectF &rect, Qt::Alignment positionAlignment) const
28664 {
28665   if (positionAlignment == 0 || positionAlignment == (Qt::AlignLeft|Qt::AlignTop))
28666     return pos;
28667 
28668   QPointF result = pos; // start at top left
28669   if (positionAlignment.testFlag(Qt::AlignHCenter))
28670     result.rx() -= rect.width()/2.0;
28671   else if (positionAlignment.testFlag(Qt::AlignRight))
28672     result.rx() -= rect.width();
28673   if (positionAlignment.testFlag(Qt::AlignVCenter))
28674     result.ry() -= rect.height()/2.0;
28675   else if (positionAlignment.testFlag(Qt::AlignBottom))
28676     result.ry() -= rect.height();
28677   return result;
28678 }
28679 
28680 /*! \internal
28681 
28682   Returns the font that should be used for drawing text. Returns mFont when the item is not selected
28683   and mSelectedFont when it is.
28684 */
mainFont() const28685 QFont QCPItemText::mainFont() const
28686 {
28687   return mSelected ? mSelectedFont : mFont;
28688 }
28689 
28690 /*! \internal
28691 
28692   Returns the color that should be used for drawing text. Returns mColor when the item is not
28693   selected and mSelectedColor when it is.
28694 */
mainColor() const28695 QColor QCPItemText::mainColor() const
28696 {
28697   return mSelected ? mSelectedColor : mColor;
28698 }
28699 
28700 /*! \internal
28701 
28702   Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected
28703   and mSelectedPen when it is.
28704 */
mainPen() const28705 QPen QCPItemText::mainPen() const
28706 {
28707   return mSelected ? mSelectedPen : mPen;
28708 }
28709 
28710 /*! \internal
28711 
28712   Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item
28713   is not selected and mSelectedBrush when it is.
28714 */
mainBrush() const28715 QBrush QCPItemText::mainBrush() const
28716 {
28717   return mSelected ? mSelectedBrush : mBrush;
28718 }
28719 /* end of 'src/items/item-text.cpp' */
28720 
28721 
28722 /* including file 'src/items/item-ellipse.cpp', size 7863                    */
28723 /* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
28724 
28725 ////////////////////////////////////////////////////////////////////////////////////////////////////
28726 //////////////////// QCPItemEllipse
28727 ////////////////////////////////////////////////////////////////////////////////////////////////////
28728 
28729 /*! \class QCPItemEllipse
28730   \brief An ellipse
28731 
28732   \image html QCPItemEllipse.png "Ellipse example. Blue dotted circles are anchors, solid blue discs are positions."
28733 
28734   It has two positions, \a topLeft and \a bottomRight, which define the rect the ellipse will be drawn in.
28735 */
28736 
28737 /*!
28738   Creates an ellipse item and sets default values.
28739 
28740   The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
28741   ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
28742 */
QCPItemEllipse(QCustomPlot * parentPlot)28743 QCPItemEllipse::QCPItemEllipse(QCustomPlot *parentPlot) :
28744   QCPAbstractItem(parentPlot),
28745   topLeft(createPosition(QLatin1String("topLeft"))),
28746   bottomRight(createPosition(QLatin1String("bottomRight"))),
28747   topLeftRim(createAnchor(QLatin1String("topLeftRim"), aiTopLeftRim)),
28748   top(createAnchor(QLatin1String("top"), aiTop)),
28749   topRightRim(createAnchor(QLatin1String("topRightRim"), aiTopRightRim)),
28750   right(createAnchor(QLatin1String("right"), aiRight)),
28751   bottomRightRim(createAnchor(QLatin1String("bottomRightRim"), aiBottomRightRim)),
28752   bottom(createAnchor(QLatin1String("bottom"), aiBottom)),
28753   bottomLeftRim(createAnchor(QLatin1String("bottomLeftRim"), aiBottomLeftRim)),
28754   left(createAnchor(QLatin1String("left"), aiLeft)),
28755   center(createAnchor(QLatin1String("center"), aiCenter))
28756 {
28757   topLeft->setCoords(0, 1);
28758   bottomRight->setCoords(1, 0);
28759 
28760   setPen(QPen(Qt::black));
28761   setSelectedPen(QPen(Qt::blue, 2));
28762   setBrush(Qt::NoBrush);
28763   setSelectedBrush(Qt::NoBrush);
28764 }
28765 
~QCPItemEllipse()28766 QCPItemEllipse::~QCPItemEllipse()
28767 {
28768 }
28769 
28770 /*!
28771   Sets the pen that will be used to draw the line of the ellipse
28772 
28773   \see setSelectedPen, setBrush
28774 */
setPen(const QPen & pen)28775 void QCPItemEllipse::setPen(const QPen &pen)
28776 {
28777   mPen = pen;
28778 }
28779 
28780 /*!
28781   Sets the pen that will be used to draw the line of the ellipse when selected
28782 
28783   \see setPen, setSelected
28784 */
setSelectedPen(const QPen & pen)28785 void QCPItemEllipse::setSelectedPen(const QPen &pen)
28786 {
28787   mSelectedPen = pen;
28788 }
28789 
28790 /*!
28791   Sets the brush that will be used to fill the ellipse. To disable filling, set \a brush to
28792   Qt::NoBrush.
28793 
28794   \see setSelectedBrush, setPen
28795 */
setBrush(const QBrush & brush)28796 void QCPItemEllipse::setBrush(const QBrush &brush)
28797 {
28798   mBrush = brush;
28799 }
28800 
28801 /*!
28802   Sets the brush that will be used to fill the ellipse when selected. To disable filling, set \a
28803   brush to Qt::NoBrush.
28804 
28805   \see setBrush
28806 */
setSelectedBrush(const QBrush & brush)28807 void QCPItemEllipse::setSelectedBrush(const QBrush &brush)
28808 {
28809   mSelectedBrush = brush;
28810 }
28811 
28812 /* inherits documentation from base class */
selectTest(const QPointF & pos,bool onlySelectable,QVariant * details) const28813 double QCPItemEllipse::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
28814 {
28815   Q_UNUSED(details)
28816   if (onlySelectable && !mSelectable)
28817     return -1;
28818 
28819   QPointF p1 = topLeft->pixelPosition();
28820   QPointF p2 = bottomRight->pixelPosition();
28821   QPointF center((p1+p2)/2.0);
28822   double a = qAbs(p1.x()-p2.x())/2.0;
28823   double b = qAbs(p1.y()-p2.y())/2.0;
28824   double x = pos.x()-center.x();
28825   double y = pos.y()-center.y();
28826 
28827   // distance to border:
28828   double c = 1.0/qSqrt(x*x/(a*a)+y*y/(b*b));
28829   double result = qAbs(c-1)*qSqrt(x*x+y*y);
28830   // filled ellipse, allow click inside to count as hit:
28831   if (result > mParentPlot->selectionTolerance()*0.99 && mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0)
28832   {
28833     if (x*x/(a*a) + y*y/(b*b) <= 1)
28834       result = mParentPlot->selectionTolerance()*0.99;
28835   }
28836   return result;
28837 }
28838 
28839 /* inherits documentation from base class */
draw(QCPPainter * painter)28840 void QCPItemEllipse::draw(QCPPainter *painter)
28841 {
28842   QPointF p1 = topLeft->pixelPosition();
28843   QPointF p2 = bottomRight->pixelPosition();
28844   if (p1.toPoint() == p2.toPoint())
28845     return;
28846   QRectF ellipseRect = QRectF(p1, p2).normalized();
28847   QRect clip = clipRect().adjusted(-mainPen().widthF(), -mainPen().widthF(), mainPen().widthF(), mainPen().widthF());
28848   if (ellipseRect.intersects(clip)) // only draw if bounding rect of ellipse is visible in cliprect
28849   {
28850     painter->setPen(mainPen());
28851     painter->setBrush(mainBrush());
28852 #ifdef __EXCEPTIONS
28853     try // drawEllipse sometimes throws exceptions if ellipse is too big
28854     {
28855 #endif
28856       painter->drawEllipse(ellipseRect);
28857 #ifdef __EXCEPTIONS
28858     } catch (...)
28859     {
28860       qDebug() << Q_FUNC_INFO << "Item too large for memory, setting invisible";
28861       setVisible(false);
28862     }
28863 #endif
28864   }
28865 }
28866 
28867 /* inherits documentation from base class */
anchorPixelPosition(int anchorId) const28868 QPointF QCPItemEllipse::anchorPixelPosition(int anchorId) const
28869 {
28870   QRectF rect = QRectF(topLeft->pixelPosition(), bottomRight->pixelPosition());
28871   switch (anchorId)
28872   {
28873     case aiTopLeftRim:     return rect.center()+(rect.topLeft()-rect.center())*1/qSqrt(2);
28874     case aiTop:            return (rect.topLeft()+rect.topRight())*0.5;
28875     case aiTopRightRim:    return rect.center()+(rect.topRight()-rect.center())*1/qSqrt(2);
28876     case aiRight:          return (rect.topRight()+rect.bottomRight())*0.5;
28877     case aiBottomRightRim: return rect.center()+(rect.bottomRight()-rect.center())*1/qSqrt(2);
28878     case aiBottom:         return (rect.bottomLeft()+rect.bottomRight())*0.5;
28879     case aiBottomLeftRim:  return rect.center()+(rect.bottomLeft()-rect.center())*1/qSqrt(2);
28880     case aiLeft:           return (rect.topLeft()+rect.bottomLeft())*0.5;
28881     case aiCenter:         return (rect.topLeft()+rect.bottomRight())*0.5;
28882   }
28883 
28884   qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId;
28885   return QPointF();
28886 }
28887 
28888 /*! \internal
28889 
28890   Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected
28891   and mSelectedPen when it is.
28892 */
mainPen() const28893 QPen QCPItemEllipse::mainPen() const
28894 {
28895   return mSelected ? mSelectedPen : mPen;
28896 }
28897 
28898 /*! \internal
28899 
28900   Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item
28901   is not selected and mSelectedBrush when it is.
28902 */
mainBrush() const28903 QBrush QCPItemEllipse::mainBrush() const
28904 {
28905   return mSelected ? mSelectedBrush : mBrush;
28906 }
28907 /* end of 'src/items/item-ellipse.cpp' */
28908 
28909 
28910 /* including file 'src/items/item-pixmap.cpp', size 10615                    */
28911 /* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
28912 
28913 ////////////////////////////////////////////////////////////////////////////////////////////////////
28914 //////////////////// QCPItemPixmap
28915 ////////////////////////////////////////////////////////////////////////////////////////////////////
28916 
28917 /*! \class QCPItemPixmap
28918   \brief An arbitrary pixmap
28919 
28920   \image html QCPItemPixmap.png "Pixmap example. Blue dotted circles are anchors, solid blue discs are positions."
28921 
28922   It has two positions, \a topLeft and \a bottomRight, which define the rectangle the pixmap will
28923   be drawn in. Depending on the scale setting (\ref setScaled), the pixmap will be either scaled to
28924   fit the rectangle or be drawn aligned to the topLeft position.
28925 
28926   If scaling is enabled and \a topLeft is further to the bottom/right than \a bottomRight (as shown
28927   on the right side of the example image), the pixmap will be flipped in the respective
28928   orientations.
28929 */
28930 
28931 /*!
28932   Creates a rectangle item and sets default values.
28933 
28934   The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
28935   ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
28936 */
QCPItemPixmap(QCustomPlot * parentPlot)28937 QCPItemPixmap::QCPItemPixmap(QCustomPlot *parentPlot) :
28938   QCPAbstractItem(parentPlot),
28939   topLeft(createPosition(QLatin1String("topLeft"))),
28940   bottomRight(createPosition(QLatin1String("bottomRight"))),
28941   top(createAnchor(QLatin1String("top"), aiTop)),
28942   topRight(createAnchor(QLatin1String("topRight"), aiTopRight)),
28943   right(createAnchor(QLatin1String("right"), aiRight)),
28944   bottom(createAnchor(QLatin1String("bottom"), aiBottom)),
28945   bottomLeft(createAnchor(QLatin1String("bottomLeft"), aiBottomLeft)),
28946   left(createAnchor(QLatin1String("left"), aiLeft)),
28947   mScaled(false),
28948   mScaledPixmapInvalidated(true),
28949   mAspectRatioMode(Qt::KeepAspectRatio),
28950   mTransformationMode(Qt::SmoothTransformation)
28951 {
28952   topLeft->setCoords(0, 1);
28953   bottomRight->setCoords(1, 0);
28954 
28955   setPen(Qt::NoPen);
28956   setSelectedPen(QPen(Qt::blue));
28957 }
28958 
~QCPItemPixmap()28959 QCPItemPixmap::~QCPItemPixmap()
28960 {
28961 }
28962 
28963 /*!
28964   Sets the pixmap that will be displayed.
28965 */
setPixmap(const QPixmap & pixmap)28966 void QCPItemPixmap::setPixmap(const QPixmap &pixmap)
28967 {
28968   mPixmap = pixmap;
28969   mScaledPixmapInvalidated = true;
28970   if (mPixmap.isNull())
28971     qDebug() << Q_FUNC_INFO << "pixmap is null";
28972 }
28973 
28974 /*!
28975   Sets whether the pixmap will be scaled to fit the rectangle defined by the \a topLeft and \a
28976   bottomRight positions.
28977 */
setScaled(bool scaled,Qt::AspectRatioMode aspectRatioMode,Qt::TransformationMode transformationMode)28978 void QCPItemPixmap::setScaled(bool scaled, Qt::AspectRatioMode aspectRatioMode, Qt::TransformationMode transformationMode)
28979 {
28980   mScaled = scaled;
28981   mAspectRatioMode = aspectRatioMode;
28982   mTransformationMode = transformationMode;
28983   mScaledPixmapInvalidated = true;
28984 }
28985 
28986 /*!
28987   Sets the pen that will be used to draw a border around the pixmap.
28988 
28989   \see setSelectedPen, setBrush
28990 */
setPen(const QPen & pen)28991 void QCPItemPixmap::setPen(const QPen &pen)
28992 {
28993   mPen = pen;
28994 }
28995 
28996 /*!
28997   Sets the pen that will be used to draw a border around the pixmap when selected
28998 
28999   \see setPen, setSelected
29000 */
setSelectedPen(const QPen & pen)29001 void QCPItemPixmap::setSelectedPen(const QPen &pen)
29002 {
29003   mSelectedPen = pen;
29004 }
29005 
29006 /* inherits documentation from base class */
selectTest(const QPointF & pos,bool onlySelectable,QVariant * details) const29007 double QCPItemPixmap::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
29008 {
29009   Q_UNUSED(details)
29010   if (onlySelectable && !mSelectable)
29011     return -1;
29012 
29013   return rectDistance(getFinalRect(), pos, true);
29014 }
29015 
29016 /* inherits documentation from base class */
draw(QCPPainter * painter)29017 void QCPItemPixmap::draw(QCPPainter *painter)
29018 {
29019   bool flipHorz = false;
29020   bool flipVert = false;
29021   QRect rect = getFinalRect(&flipHorz, &flipVert);
29022   double clipPad = mainPen().style() == Qt::NoPen ? 0 : mainPen().widthF();
29023   QRect boundingRect = rect.adjusted(-clipPad, -clipPad, clipPad, clipPad);
29024   if (boundingRect.intersects(clipRect()))
29025   {
29026     updateScaledPixmap(rect, flipHorz, flipVert);
29027     painter->drawPixmap(rect.topLeft(), mScaled ? mScaledPixmap : mPixmap);
29028     QPen pen = mainPen();
29029     if (pen.style() != Qt::NoPen)
29030     {
29031       painter->setPen(pen);
29032       painter->setBrush(Qt::NoBrush);
29033       painter->drawRect(rect);
29034     }
29035   }
29036 }
29037 
29038 /* inherits documentation from base class */
anchorPixelPosition(int anchorId) const29039 QPointF QCPItemPixmap::anchorPixelPosition(int anchorId) const
29040 {
29041   bool flipHorz;
29042   bool flipVert;
29043   QRect rect = getFinalRect(&flipHorz, &flipVert);
29044   // we actually want denormal rects (negative width/height) here, so restore
29045   // the flipped state:
29046   if (flipHorz)
29047     rect.adjust(rect.width(), 0, -rect.width(), 0);
29048   if (flipVert)
29049     rect.adjust(0, rect.height(), 0, -rect.height());
29050 
29051   switch (anchorId)
29052   {
29053     case aiTop:         return (rect.topLeft()+rect.topRight())*0.5;
29054     case aiTopRight:    return rect.topRight();
29055     case aiRight:       return (rect.topRight()+rect.bottomRight())*0.5;
29056     case aiBottom:      return (rect.bottomLeft()+rect.bottomRight())*0.5;
29057     case aiBottomLeft:  return rect.bottomLeft();
29058     case aiLeft:        return (rect.topLeft()+rect.bottomLeft())*0.5;;
29059   }
29060 
29061   qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId;
29062   return QPointF();
29063 }
29064 
29065 /*! \internal
29066 
29067   Creates the buffered scaled image (\a mScaledPixmap) to fit the specified \a finalRect. The
29068   parameters \a flipHorz and \a flipVert control whether the resulting image shall be flipped
29069   horizontally or vertically. (This is used when \a topLeft is further to the bottom/right than \a
29070   bottomRight.)
29071 
29072   This function only creates the scaled pixmap when the buffered pixmap has a different size than
29073   the expected result, so calling this function repeatedly, e.g. in the \ref draw function, does
29074   not cause expensive rescaling every time.
29075 
29076   If scaling is disabled, sets mScaledPixmap to a null QPixmap.
29077 */
updateScaledPixmap(QRect finalRect,bool flipHorz,bool flipVert)29078 void QCPItemPixmap::updateScaledPixmap(QRect finalRect, bool flipHorz, bool flipVert)
29079 {
29080   if (mPixmap.isNull())
29081     return;
29082 
29083   if (mScaled)
29084   {
29085 #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
29086     double devicePixelRatio = mPixmap.devicePixelRatio();
29087 #else
29088     double devicePixelRatio = 1.0;
29089 #endif
29090     if (finalRect.isNull())
29091       finalRect = getFinalRect(&flipHorz, &flipVert);
29092     if (mScaledPixmapInvalidated || finalRect.size() != mScaledPixmap.size()/devicePixelRatio)
29093     {
29094       mScaledPixmap = mPixmap.scaled(finalRect.size()*devicePixelRatio, mAspectRatioMode, mTransformationMode);
29095       if (flipHorz || flipVert)
29096         mScaledPixmap = QPixmap::fromImage(mScaledPixmap.toImage().mirrored(flipHorz, flipVert));
29097 #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
29098       mScaledPixmap.setDevicePixelRatio(devicePixelRatio);
29099 #endif
29100     }
29101   } else if (!mScaledPixmap.isNull())
29102     mScaledPixmap = QPixmap();
29103   mScaledPixmapInvalidated = false;
29104 }
29105 
29106 /*! \internal
29107 
29108   Returns the final (tight) rect the pixmap is drawn in, depending on the current item positions
29109   and scaling settings.
29110 
29111   The output parameters \a flippedHorz and \a flippedVert return whether the pixmap should be drawn
29112   flipped horizontally or vertically in the returned rect. (The returned rect itself is always
29113   normalized, i.e. the top left corner of the rect is actually further to the top/left than the
29114   bottom right corner). This is the case when the item position \a topLeft is further to the
29115   bottom/right than \a bottomRight.
29116 
29117   If scaling is disabled, returns a rect with size of the original pixmap and the top left corner
29118   aligned with the item position \a topLeft. The position \a bottomRight is ignored.
29119 */
getFinalRect(bool * flippedHorz,bool * flippedVert) const29120 QRect QCPItemPixmap::getFinalRect(bool *flippedHorz, bool *flippedVert) const
29121 {
29122   QRect result;
29123   bool flipHorz = false;
29124   bool flipVert = false;
29125   QPoint p1 = topLeft->pixelPosition().toPoint();
29126   QPoint p2 = bottomRight->pixelPosition().toPoint();
29127   if (p1 == p2)
29128     return QRect(p1, QSize(0, 0));
29129   if (mScaled)
29130   {
29131     QSize newSize = QSize(p2.x()-p1.x(), p2.y()-p1.y());
29132     QPoint topLeft = p1;
29133     if (newSize.width() < 0)
29134     {
29135       flipHorz = true;
29136       newSize.rwidth() *= -1;
29137       topLeft.setX(p2.x());
29138     }
29139     if (newSize.height() < 0)
29140     {
29141       flipVert = true;
29142       newSize.rheight() *= -1;
29143       topLeft.setY(p2.y());
29144     }
29145     QSize scaledSize = mPixmap.size();
29146 #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
29147     scaledSize /= mPixmap.devicePixelRatio();
29148     scaledSize.scale(newSize*mPixmap.devicePixelRatio(), mAspectRatioMode);
29149 #else
29150     scaledSize.scale(newSize, mAspectRatioMode);
29151 #endif
29152     result = QRect(topLeft, scaledSize);
29153   } else
29154   {
29155 #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
29156     result = QRect(p1, mPixmap.size()/mPixmap.devicePixelRatio());
29157 #else
29158     result = QRect(p1, mPixmap.size());
29159 #endif
29160   }
29161   if (flippedHorz)
29162     *flippedHorz = flipHorz;
29163   if (flippedVert)
29164     *flippedVert = flipVert;
29165   return result;
29166 }
29167 
29168 /*! \internal
29169 
29170   Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected
29171   and mSelectedPen when it is.
29172 */
mainPen() const29173 QPen QCPItemPixmap::mainPen() const
29174 {
29175   return mSelected ? mSelectedPen : mPen;
29176 }
29177 /* end of 'src/items/item-pixmap.cpp' */
29178 
29179 
29180 /* including file 'src/items/item-tracer.cpp', size 14624                    */
29181 /* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
29182 
29183 ////////////////////////////////////////////////////////////////////////////////////////////////////
29184 //////////////////// QCPItemTracer
29185 ////////////////////////////////////////////////////////////////////////////////////////////////////
29186 
29187 /*! \class QCPItemTracer
29188   \brief Item that sticks to QCPGraph data points
29189 
29190   \image html QCPItemTracer.png "Tracer example. Blue dotted circles are anchors, solid blue discs are positions."
29191 
29192   The tracer can be connected with a QCPGraph via \ref setGraph. Then it will automatically adopt
29193   the coordinate axes of the graph and update its \a position to be on the graph's data. This means
29194   the key stays controllable via \ref setGraphKey, but the value will follow the graph data. If a
29195   QCPGraph is connected, note that setting the coordinates of the tracer item directly via \a
29196   position will have no effect because they will be overriden in the next redraw (this is when the
29197   coordinate update happens).
29198 
29199   If the specified key in \ref setGraphKey is outside the key bounds of the graph, the tracer will
29200   stay at the corresponding end of the graph.
29201 
29202   With \ref setInterpolating you may specify whether the tracer may only stay exactly on data
29203   points or whether it interpolates data points linearly, if given a key that lies between two data
29204   points of the graph.
29205 
29206   The tracer has different visual styles, see \ref setStyle. It is also possible to make the tracer
29207   have no own visual appearance (set the style to \ref tsNone), and just connect other item
29208   positions to the tracer \a position (used as an anchor) via \ref
29209   QCPItemPosition::setParentAnchor.
29210 
29211   \note The tracer position is only automatically updated upon redraws. So when the data of the
29212   graph changes and immediately afterwards (without a redraw) the position coordinates of the
29213   tracer are retrieved, they will not reflect the updated data of the graph. In this case \ref
29214   updatePosition must be called manually, prior to reading the tracer coordinates.
29215 */
29216 
29217 /*!
29218   Creates a tracer item and sets default values.
29219 
29220   The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
29221   ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
29222 */
QCPItemTracer(QCustomPlot * parentPlot)29223 QCPItemTracer::QCPItemTracer(QCustomPlot *parentPlot) :
29224   QCPAbstractItem(parentPlot),
29225   position(createPosition(QLatin1String("position"))),
29226   mSize(6),
29227   mStyle(tsCrosshair),
29228   mGraph(0),
29229   mGraphKey(0),
29230   mInterpolating(false)
29231 {
29232   position->setCoords(0, 0);
29233 
29234   setBrush(Qt::NoBrush);
29235   setSelectedBrush(Qt::NoBrush);
29236   setPen(QPen(Qt::black));
29237   setSelectedPen(QPen(Qt::blue, 2));
29238 }
29239 
~QCPItemTracer()29240 QCPItemTracer::~QCPItemTracer()
29241 {
29242 }
29243 
29244 /*!
29245   Sets the pen that will be used to draw the line of the tracer
29246 
29247   \see setSelectedPen, setBrush
29248 */
setPen(const QPen & pen)29249 void QCPItemTracer::setPen(const QPen &pen)
29250 {
29251   mPen = pen;
29252 }
29253 
29254 /*!
29255   Sets the pen that will be used to draw the line of the tracer when selected
29256 
29257   \see setPen, setSelected
29258 */
setSelectedPen(const QPen & pen)29259 void QCPItemTracer::setSelectedPen(const QPen &pen)
29260 {
29261   mSelectedPen = pen;
29262 }
29263 
29264 /*!
29265   Sets the brush that will be used to draw any fills of the tracer
29266 
29267   \see setSelectedBrush, setPen
29268 */
setBrush(const QBrush & brush)29269 void QCPItemTracer::setBrush(const QBrush &brush)
29270 {
29271   mBrush = brush;
29272 }
29273 
29274 /*!
29275   Sets the brush that will be used to draw any fills of the tracer, when selected.
29276 
29277   \see setBrush, setSelected
29278 */
setSelectedBrush(const QBrush & brush)29279 void QCPItemTracer::setSelectedBrush(const QBrush &brush)
29280 {
29281   mSelectedBrush = brush;
29282 }
29283 
29284 /*!
29285   Sets the size of the tracer in pixels, if the style supports setting a size (e.g. \ref tsSquare
29286   does, \ref tsCrosshair does not).
29287 */
setSize(double size)29288 void QCPItemTracer::setSize(double size)
29289 {
29290   mSize = size;
29291 }
29292 
29293 /*!
29294   Sets the style/visual appearance of the tracer.
29295 
29296   If you only want to use the tracer \a position as an anchor for other items, set \a style to
29297   \ref tsNone.
29298 */
setStyle(QCPItemTracer::TracerStyle style)29299 void QCPItemTracer::setStyle(QCPItemTracer::TracerStyle style)
29300 {
29301   mStyle = style;
29302 }
29303 
29304 /*!
29305   Sets the QCPGraph this tracer sticks to. The tracer \a position will be set to type
29306   QCPItemPosition::ptPlotCoords and the axes will be set to the axes of \a graph.
29307 
29308   To free the tracer from any graph, set \a graph to 0. The tracer \a position can then be placed
29309   freely like any other item position. This is the state the tracer will assume when its graph gets
29310   deleted while still attached to it.
29311 
29312   \see setGraphKey
29313 */
setGraph(QCPGraph * graph)29314 void QCPItemTracer::setGraph(QCPGraph *graph)
29315 {
29316   if (graph)
29317   {
29318     if (graph->parentPlot() == mParentPlot)
29319     {
29320       position->setType(QCPItemPosition::ptPlotCoords);
29321       position->setAxes(graph->keyAxis(), graph->valueAxis());
29322       mGraph = graph;
29323       updatePosition();
29324     } else
29325       qDebug() << Q_FUNC_INFO << "graph isn't in same QCustomPlot instance as this item";
29326   } else
29327   {
29328     mGraph = 0;
29329   }
29330 }
29331 
29332 /*!
29333   Sets the key of the graph's data point the tracer will be positioned at. This is the only free
29334   coordinate of a tracer when attached to a graph.
29335 
29336   Depending on \ref setInterpolating, the tracer will be either positioned on the data point
29337   closest to \a key, or will stay exactly at \a key and interpolate the value linearly.
29338 
29339   \see setGraph, setInterpolating
29340 */
setGraphKey(double key)29341 void QCPItemTracer::setGraphKey(double key)
29342 {
29343   mGraphKey = key;
29344 }
29345 
29346 /*!
29347   Sets whether the value of the graph's data points shall be interpolated, when positioning the
29348   tracer.
29349 
29350   If \a enabled is set to false and a key is given with \ref setGraphKey, the tracer is placed on
29351   the data point of the graph which is closest to the key, but which is not necessarily exactly
29352   there. If \a enabled is true, the tracer will be positioned exactly at the specified key, and
29353   the appropriate value will be interpolated from the graph's data points linearly.
29354 
29355   \see setGraph, setGraphKey
29356 */
setInterpolating(bool enabled)29357 void QCPItemTracer::setInterpolating(bool enabled)
29358 {
29359   mInterpolating = enabled;
29360 }
29361 
29362 /* inherits documentation from base class */
selectTest(const QPointF & pos,bool onlySelectable,QVariant * details) const29363 double QCPItemTracer::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
29364 {
29365   Q_UNUSED(details)
29366   if (onlySelectable && !mSelectable)
29367     return -1;
29368 
29369   QPointF center(position->pixelPosition());
29370   double w = mSize/2.0;
29371   QRect clip = clipRect();
29372   switch (mStyle)
29373   {
29374     case tsNone: return -1;
29375     case tsPlus:
29376     {
29377       if (clipRect().intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
29378         return qSqrt(qMin(QCPVector2D(pos).distanceSquaredToLine(center+QPointF(-w, 0), center+QPointF(w, 0)),
29379                           QCPVector2D(pos).distanceSquaredToLine(center+QPointF(0, -w), center+QPointF(0, w))));
29380       break;
29381     }
29382     case tsCrosshair:
29383     {
29384       return qSqrt(qMin(QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(clip.left(), center.y()), QCPVector2D(clip.right(), center.y())),
29385                         QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(center.x(), clip.top()), QCPVector2D(center.x(), clip.bottom()))));
29386     }
29387     case tsCircle:
29388     {
29389       if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
29390       {
29391         // distance to border:
29392         double centerDist = QCPVector2D(center-pos).length();
29393         double circleLine = w;
29394         double result = qAbs(centerDist-circleLine);
29395         // filled ellipse, allow click inside to count as hit:
29396         if (result > mParentPlot->selectionTolerance()*0.99 && mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0)
29397         {
29398           if (centerDist <= circleLine)
29399             result = mParentPlot->selectionTolerance()*0.99;
29400         }
29401         return result;
29402       }
29403       break;
29404     }
29405     case tsSquare:
29406     {
29407       if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
29408       {
29409         QRectF rect = QRectF(center-QPointF(w, w), center+QPointF(w, w));
29410         bool filledRect = mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0;
29411         return rectDistance(rect, pos, filledRect);
29412       }
29413       break;
29414     }
29415   }
29416   return -1;
29417 }
29418 
29419 /* inherits documentation from base class */
draw(QCPPainter * painter)29420 void QCPItemTracer::draw(QCPPainter *painter)
29421 {
29422   updatePosition();
29423   if (mStyle == tsNone)
29424     return;
29425 
29426   painter->setPen(mainPen());
29427   painter->setBrush(mainBrush());
29428   QPointF center(position->pixelPosition());
29429   double w = mSize/2.0;
29430   QRect clip = clipRect();
29431   switch (mStyle)
29432   {
29433     case tsNone: return;
29434     case tsPlus:
29435     {
29436       if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
29437       {
29438         painter->drawLine(QLineF(center+QPointF(-w, 0), center+QPointF(w, 0)));
29439         painter->drawLine(QLineF(center+QPointF(0, -w), center+QPointF(0, w)));
29440       }
29441       break;
29442     }
29443     case tsCrosshair:
29444     {
29445       if (center.y() > clip.top() && center.y() < clip.bottom())
29446         painter->drawLine(QLineF(clip.left(), center.y(), clip.right(), center.y()));
29447       if (center.x() > clip.left() && center.x() < clip.right())
29448         painter->drawLine(QLineF(center.x(), clip.top(), center.x(), clip.bottom()));
29449       break;
29450     }
29451     case tsCircle:
29452     {
29453       if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
29454         painter->drawEllipse(center, w, w);
29455       break;
29456     }
29457     case tsSquare:
29458     {
29459       if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
29460         painter->drawRect(QRectF(center-QPointF(w, w), center+QPointF(w, w)));
29461       break;
29462     }
29463   }
29464 }
29465 
29466 /*!
29467   If the tracer is connected with a graph (\ref setGraph), this function updates the tracer's \a
29468   position to reside on the graph data, depending on the configured key (\ref setGraphKey).
29469 
29470   It is called automatically on every redraw and normally doesn't need to be called manually. One
29471   exception is when you want to read the tracer coordinates via \a position and are not sure that
29472   the graph's data (or the tracer key with \ref setGraphKey) hasn't changed since the last redraw.
29473   In that situation, call this function before accessing \a position, to make sure you don't get
29474   out-of-date coordinates.
29475 
29476   If there is no graph set on this tracer, this function does nothing.
29477 */
updatePosition()29478 void QCPItemTracer::updatePosition()
29479 {
29480   if (mGraph)
29481   {
29482     if (mParentPlot->hasPlottable(mGraph))
29483     {
29484       if (mGraph->data()->size() > 1)
29485       {
29486         QCPGraphDataContainer::const_iterator first = mGraph->data()->constBegin();
29487         QCPGraphDataContainer::const_iterator last = mGraph->data()->constEnd()-1;
29488         if (mGraphKey <= first->key)
29489           position->setCoords(first->key, first->value);
29490         else if (mGraphKey >= last->key)
29491           position->setCoords(last->key, last->value);
29492         else
29493         {
29494           QCPGraphDataContainer::const_iterator it = mGraph->data()->findBegin(mGraphKey);
29495           if (it != mGraph->data()->constEnd()) // mGraphKey is not exactly on last iterator, but somewhere between iterators
29496           {
29497             QCPGraphDataContainer::const_iterator prevIt = it;
29498             ++it; // won't advance to constEnd because we handled that case (mGraphKey >= last->key) before
29499             if (mInterpolating)
29500             {
29501               // interpolate between iterators around mGraphKey:
29502               double slope = 0;
29503               if (!qFuzzyCompare((double)it->key, (double)prevIt->key))
29504                 slope = (it->value-prevIt->value)/(it->key-prevIt->key);
29505               position->setCoords(mGraphKey, (mGraphKey-prevIt->key)*slope+prevIt->value);
29506             } else
29507             {
29508               // find iterator with key closest to mGraphKey:
29509               if (mGraphKey < (prevIt->key+it->key)*0.5)
29510                 position->setCoords(prevIt->key, prevIt->value);
29511               else
29512                 position->setCoords(it->key, it->value);
29513             }
29514           } else // mGraphKey is exactly on last iterator (should actually be caught when comparing first/last keys, but this is a failsafe for fp uncertainty)
29515             position->setCoords(it->key, it->value);
29516         }
29517       } else if (mGraph->data()->size() == 1)
29518       {
29519         QCPGraphDataContainer::const_iterator it = mGraph->data()->constBegin();
29520         position->setCoords(it->key, it->value);
29521       } else
29522         qDebug() << Q_FUNC_INFO << "graph has no data";
29523     } else
29524       qDebug() << Q_FUNC_INFO << "graph not contained in QCustomPlot instance (anymore)";
29525   }
29526 }
29527 
29528 /*! \internal
29529 
29530   Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected
29531   and mSelectedPen when it is.
29532 */
mainPen() const29533 QPen QCPItemTracer::mainPen() const
29534 {
29535   return mSelected ? mSelectedPen : mPen;
29536 }
29537 
29538 /*! \internal
29539 
29540   Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item
29541   is not selected and mSelectedBrush when it is.
29542 */
mainBrush() const29543 QBrush QCPItemTracer::mainBrush() const
29544 {
29545   return mSelected ? mSelectedBrush : mBrush;
29546 }
29547 /* end of 'src/items/item-tracer.cpp' */
29548 
29549 
29550 /* including file 'src/items/item-bracket.cpp', size 10687                   */
29551 /* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
29552 
29553 ////////////////////////////////////////////////////////////////////////////////////////////////////
29554 //////////////////// QCPItemBracket
29555 ////////////////////////////////////////////////////////////////////////////////////////////////////
29556 
29557 /*! \class QCPItemBracket
29558   \brief A bracket for referencing/highlighting certain parts in the plot.
29559 
29560   \image html QCPItemBracket.png "Bracket example. Blue dotted circles are anchors, solid blue discs are positions."
29561 
29562   It has two positions, \a left and \a right, which define the span of the bracket. If \a left is
29563   actually farther to the left than \a right, the bracket is opened to the bottom, as shown in the
29564   example image.
29565 
29566   The bracket supports multiple styles via \ref setStyle. The length, i.e. how far the bracket
29567   stretches away from the embraced span, can be controlled with \ref setLength.
29568 
29569   \image html QCPItemBracket-length.png
29570   <center>Demonstrating the effect of different values for \ref setLength, for styles \ref
29571   bsCalligraphic and \ref bsSquare. Anchors and positions are displayed for reference.</center>
29572 
29573   It provides an anchor \a center, to allow connection of other items, e.g. an arrow (QCPItemLine
29574   or QCPItemCurve) or a text label (QCPItemText), to the bracket.
29575 */
29576 
29577 /*!
29578   Creates a bracket item and sets default values.
29579 
29580   The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
29581   ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
29582 */
QCPItemBracket(QCustomPlot * parentPlot)29583 QCPItemBracket::QCPItemBracket(QCustomPlot *parentPlot) :
29584   QCPAbstractItem(parentPlot),
29585   left(createPosition(QLatin1String("left"))),
29586   right(createPosition(QLatin1String("right"))),
29587   center(createAnchor(QLatin1String("center"), aiCenter)),
29588   mLength(8),
29589   mStyle(bsCalligraphic)
29590 {
29591   left->setCoords(0, 0);
29592   right->setCoords(1, 1);
29593 
29594   setPen(QPen(Qt::black));
29595   setSelectedPen(QPen(Qt::blue, 2));
29596 }
29597 
~QCPItemBracket()29598 QCPItemBracket::~QCPItemBracket()
29599 {
29600 }
29601 
29602 /*!
29603   Sets the pen that will be used to draw the bracket.
29604 
29605   Note that when the style is \ref bsCalligraphic, only the color will be taken from the pen, the
29606   stroke and width are ignored. To change the apparent stroke width of a calligraphic bracket, use
29607   \ref setLength, which has a similar effect.
29608 
29609   \see setSelectedPen
29610 */
setPen(const QPen & pen)29611 void QCPItemBracket::setPen(const QPen &pen)
29612 {
29613   mPen = pen;
29614 }
29615 
29616 /*!
29617   Sets the pen that will be used to draw the bracket when selected
29618 
29619   \see setPen, setSelected
29620 */
setSelectedPen(const QPen & pen)29621 void QCPItemBracket::setSelectedPen(const QPen &pen)
29622 {
29623   mSelectedPen = pen;
29624 }
29625 
29626 /*!
29627   Sets the \a length in pixels how far the bracket extends in the direction towards the embraced
29628   span of the bracket (i.e. perpendicular to the <i>left</i>-<i>right</i>-direction)
29629 
29630   \image html QCPItemBracket-length.png
29631   <center>Demonstrating the effect of different values for \ref setLength, for styles \ref
29632   bsCalligraphic and \ref bsSquare. Anchors and positions are displayed for reference.</center>
29633 */
setLength(double length)29634 void QCPItemBracket::setLength(double length)
29635 {
29636   mLength = length;
29637 }
29638 
29639 /*!
29640   Sets the style of the bracket, i.e. the shape/visual appearance.
29641 
29642   \see setPen
29643 */
setStyle(QCPItemBracket::BracketStyle style)29644 void QCPItemBracket::setStyle(QCPItemBracket::BracketStyle style)
29645 {
29646   mStyle = style;
29647 }
29648 
29649 /* inherits documentation from base class */
selectTest(const QPointF & pos,bool onlySelectable,QVariant * details) const29650 double QCPItemBracket::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
29651 {
29652   Q_UNUSED(details)
29653   if (onlySelectable && !mSelectable)
29654     return -1;
29655 
29656   QCPVector2D p(pos);
29657   QCPVector2D leftVec(left->pixelPosition());
29658   QCPVector2D rightVec(right->pixelPosition());
29659   if (leftVec.toPoint() == rightVec.toPoint())
29660     return -1;
29661 
29662   QCPVector2D widthVec = (rightVec-leftVec)*0.5;
29663   QCPVector2D lengthVec = widthVec.perpendicular().normalized()*mLength;
29664   QCPVector2D centerVec = (rightVec+leftVec)*0.5-lengthVec;
29665 
29666   switch (mStyle)
29667   {
29668     case QCPItemBracket::bsSquare:
29669     case QCPItemBracket::bsRound:
29670     {
29671       double a = p.distanceSquaredToLine(centerVec-widthVec, centerVec+widthVec);
29672       double b = p.distanceSquaredToLine(centerVec-widthVec+lengthVec, centerVec-widthVec);
29673       double c = p.distanceSquaredToLine(centerVec+widthVec+lengthVec, centerVec+widthVec);
29674       return qSqrt(qMin(qMin(a, b), c));
29675     }
29676     case QCPItemBracket::bsCurly:
29677     case QCPItemBracket::bsCalligraphic:
29678     {
29679       double a = p.distanceSquaredToLine(centerVec-widthVec*0.75+lengthVec*0.15, centerVec+lengthVec*0.3);
29680       double b = p.distanceSquaredToLine(centerVec-widthVec+lengthVec*0.7, centerVec-widthVec*0.75+lengthVec*0.15);
29681       double c = p.distanceSquaredToLine(centerVec+widthVec*0.75+lengthVec*0.15, centerVec+lengthVec*0.3);
29682       double d = p.distanceSquaredToLine(centerVec+widthVec+lengthVec*0.7, centerVec+widthVec*0.75+lengthVec*0.15);
29683       return qSqrt(qMin(qMin(a, b), qMin(c, d)));
29684     }
29685   }
29686   return -1;
29687 }
29688 
29689 /* inherits documentation from base class */
draw(QCPPainter * painter)29690 void QCPItemBracket::draw(QCPPainter *painter)
29691 {
29692   QCPVector2D leftVec(left->pixelPosition());
29693   QCPVector2D rightVec(right->pixelPosition());
29694   if (leftVec.toPoint() == rightVec.toPoint())
29695     return;
29696 
29697   QCPVector2D widthVec = (rightVec-leftVec)*0.5;
29698   QCPVector2D lengthVec = widthVec.perpendicular().normalized()*mLength;
29699   QCPVector2D centerVec = (rightVec+leftVec)*0.5-lengthVec;
29700 
29701   QPolygon boundingPoly;
29702   boundingPoly << leftVec.toPoint() << rightVec.toPoint()
29703                << (rightVec-lengthVec).toPoint() << (leftVec-lengthVec).toPoint();
29704   QRect clip = clipRect().adjusted(-mainPen().widthF(), -mainPen().widthF(), mainPen().widthF(), mainPen().widthF());
29705   if (clip.intersects(boundingPoly.boundingRect()))
29706   {
29707     painter->setPen(mainPen());
29708     switch (mStyle)
29709     {
29710       case bsSquare:
29711       {
29712         painter->drawLine((centerVec+widthVec).toPointF(), (centerVec-widthVec).toPointF());
29713         painter->drawLine((centerVec+widthVec).toPointF(), (centerVec+widthVec+lengthVec).toPointF());
29714         painter->drawLine((centerVec-widthVec).toPointF(), (centerVec-widthVec+lengthVec).toPointF());
29715         break;
29716       }
29717       case bsRound:
29718       {
29719         painter->setBrush(Qt::NoBrush);
29720         QPainterPath path;
29721         path.moveTo((centerVec+widthVec+lengthVec).toPointF());
29722         path.cubicTo((centerVec+widthVec).toPointF(), (centerVec+widthVec).toPointF(), centerVec.toPointF());
29723         path.cubicTo((centerVec-widthVec).toPointF(), (centerVec-widthVec).toPointF(), (centerVec-widthVec+lengthVec).toPointF());
29724         painter->drawPath(path);
29725         break;
29726       }
29727       case bsCurly:
29728       {
29729         painter->setBrush(Qt::NoBrush);
29730         QPainterPath path;
29731         path.moveTo((centerVec+widthVec+lengthVec).toPointF());
29732         path.cubicTo((centerVec+widthVec-lengthVec*0.8).toPointF(), (centerVec+0.4*widthVec+lengthVec).toPointF(), centerVec.toPointF());
29733         path.cubicTo((centerVec-0.4*widthVec+lengthVec).toPointF(), (centerVec-widthVec-lengthVec*0.8).toPointF(), (centerVec-widthVec+lengthVec).toPointF());
29734         painter->drawPath(path);
29735         break;
29736       }
29737       case bsCalligraphic:
29738       {
29739         painter->setPen(Qt::NoPen);
29740         painter->setBrush(QBrush(mainPen().color()));
29741         QPainterPath path;
29742         path.moveTo((centerVec+widthVec+lengthVec).toPointF());
29743 
29744         path.cubicTo((centerVec+widthVec-lengthVec*0.8).toPointF(), (centerVec+0.4*widthVec+0.8*lengthVec).toPointF(), centerVec.toPointF());
29745         path.cubicTo((centerVec-0.4*widthVec+0.8*lengthVec).toPointF(), (centerVec-widthVec-lengthVec*0.8).toPointF(), (centerVec-widthVec+lengthVec).toPointF());
29746 
29747         path.cubicTo((centerVec-widthVec-lengthVec*0.5).toPointF(), (centerVec-0.2*widthVec+1.2*lengthVec).toPointF(), (centerVec+lengthVec*0.2).toPointF());
29748         path.cubicTo((centerVec+0.2*widthVec+1.2*lengthVec).toPointF(), (centerVec+widthVec-lengthVec*0.5).toPointF(), (centerVec+widthVec+lengthVec).toPointF());
29749 
29750         painter->drawPath(path);
29751         break;
29752       }
29753     }
29754   }
29755 }
29756 
29757 /* inherits documentation from base class */
anchorPixelPosition(int anchorId) const29758 QPointF QCPItemBracket::anchorPixelPosition(int anchorId) const
29759 {
29760   QCPVector2D leftVec(left->pixelPosition());
29761   QCPVector2D rightVec(right->pixelPosition());
29762   if (leftVec.toPoint() == rightVec.toPoint())
29763     return leftVec.toPointF();
29764 
29765   QCPVector2D widthVec = (rightVec-leftVec)*0.5;
29766   QCPVector2D lengthVec = widthVec.perpendicular().normalized()*mLength;
29767   QCPVector2D centerVec = (rightVec+leftVec)*0.5-lengthVec;
29768 
29769   switch (anchorId)
29770   {
29771     case aiCenter:
29772       return centerVec.toPointF();
29773   }
29774   qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId;
29775   return QPointF();
29776 }
29777 
29778 /*! \internal
29779 
29780   Returns the pen that should be used for drawing lines. Returns mPen when the
29781   item is not selected and mSelectedPen when it is.
29782 */
mainPen() const29783 QPen QCPItemBracket::mainPen() const
29784 {
29785     return mSelected ? mSelectedPen : mPen;
29786 }
29787 /* end of 'src/items/item-bracket.cpp' */
29788 
29789 
29790