summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJasem Mutlaq <mutlaqja@ikarustech.com>2016-10-05 21:31:05 (GMT)
committerJasem Mutlaq <mutlaqja@ikarustech.com>2016-10-05 21:31:05 (GMT)
commit4e3fd8cb5a2187ab0c61e10ad99b2d0ffc927215 (patch)
tree1bfcb858188b4875f1c9b376e990d94ca14b9539
parentc738585e0d3dd0dbf6c30b81e09bbca0abbcb2b5 (diff)
Update to 2.0 beta of QCustomPlot
-rw-r--r--kstars/auxiliary/qcustomplot.cpp17275
-rw-r--r--kstars/auxiliary/qcustomplot.h4249
2 files changed, 15297 insertions, 6227 deletions
diff --git a/kstars/auxiliary/qcustomplot.cpp b/kstars/auxiliary/qcustomplot.cpp
index 05c3f46..e20ef35 100644
--- a/kstars/auxiliary/qcustomplot.cpp
+++ b/kstars/auxiliary/qcustomplot.cpp
@@ -1,11 +1,11 @@
/***************************************************************************
** **
** QCustomPlot, an easy to use, modern plotting widget for Qt **
-** Copyright (C) 2011-2015 Emanuel Eichhammer **
+** Copyright (C) 2011-2016 Emanuel Eichhammer **
** **
** This program is free software: you can redistribute it and/or modify **
** it under the terms of the GNU General Public License as published by **
-** the Free Software Foundation, either version 2 of the License, or **
+** the Free Software Foundation, either version 3 of the License, or **
** (at your option) any later version. **
** **
** This program is distributed in the hope that it will be useful, **
@@ -19,13 +19,248 @@
****************************************************************************
** Author: Emanuel Eichhammer **
** Website/Contact: http://www.qcustomplot.com/ **
-** Date: 25.04.15 **
-** Version: 1.3.1 **
+** Date: 13.09.16 **
+** Version: 2.0.0-beta **
****************************************************************************/
#include "qcustomplot.h"
+/* including file 'src/vector2d.cpp', size 7340 */
+/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
+
+////////////////////////////////////////////////////////////////////////////////////////////////////
+//////////////////// QCPVector2D
+////////////////////////////////////////////////////////////////////////////////////////////////////
+
+/*! \class QCPVector2D
+ \brief Represents two doubles as a mathematical 2D vector
+
+ This class acts as a replacement for QVector2D with the advantage of double precision instead of
+ single, and some convenience methods tailored for the QCustomPlot library.
+*/
+
+/* start documentation of inline functions */
+
+/*! \fn void QCPVector2D::setX(double x)
+
+ Sets the x coordinate of this vector to \a x.
+
+ \see setY
+*/
+
+/*! \fn void QCPVector2D::setY(double y)
+
+ Sets the y coordinate of this vector to \a y.
+
+ \see setX
+*/
+
+/*! \fn double QCPVector2D::length() const
+
+ Returns the length of this vector.
+
+ \see lengthSquared
+*/
+
+/*! \fn double QCPVector2D::lengthSquared() const
+
+ Returns the squared length of this vector. In some situations, e.g. when just trying to find the
+ shortest vector of a group, this is faster than calculating \ref length, because it avoids
+ calculation of a square root.
+
+ \see length
+*/
+
+/*! \fn QPoint QCPVector2D::toPoint() const
+
+ Returns a QPoint which has the x and y coordinates of this vector, truncating any floating point
+ information.
+
+ \see toPointF
+*/
+
+/*! \fn QPointF QCPVector2D::toPointF() const
+
+ Returns a QPointF which has the x and y coordinates of this vector.
+
+ \see toPoint
+*/
+
+/*! \fn bool QCPVector2D::isNull() const
+
+ Returns whether this vector is null. A vector is null if \c qIsNull returns true for both x and y
+ coordinates, i.e. if both are binary equal to 0.
+*/
+
+/*! \fn QCPVector2D QCPVector2D::perpendicular() const
+
+ Returns a vector perpendicular to this vector, with the same length.
+*/
+
+/*! \fn double QCPVector2D::dot() const
+
+ Returns the dot/scalar product of this vector with the specified vector \a vec.
+*/
+
+/* end documentation of inline functions */
+
+/*!
+ Creates a QCPVector2D object and initializes the x and y coordinates to 0.
+*/
+QCPVector2D::QCPVector2D() :
+ mX(0),
+ mY(0)
+{
+}
+
+/*!
+ Creates a QCPVector2D object and initializes the \a x and \a y coordinates with the specified
+ values.
+*/
+QCPVector2D::QCPVector2D(double x, double y) :
+ mX(x),
+ mY(y)
+{
+}
+
+/*!
+ Creates a QCPVector2D object and initializes the x and y coordinates respective coordinates of
+ the specified \a point.
+*/
+QCPVector2D::QCPVector2D(const QPoint &point) :
+ mX(point.x()),
+ mY(point.y())
+{
+}
+
+/*!
+ Creates a QCPVector2D object and initializes the x and y coordinates respective coordinates of
+ the specified \a point.
+*/
+QCPVector2D::QCPVector2D(const QPointF &point) :
+ mX(point.x()),
+ mY(point.y())
+{
+}
+
+/*!
+ Normalizes this vector. After this operation, the length of the vector is equal to 1.
+
+ \see normalized, length, lengthSquared
+*/
+void QCPVector2D::normalize()
+{
+ double len = length();
+ mX /= len;
+ mY /= len;
+}
+
+/*!
+ Returns a normalized version of this vector. The length of the returned vector is equal to 1.
+
+ \see normalize, length, lengthSquared
+*/
+QCPVector2D QCPVector2D::normalized() const
+{
+ QCPVector2D result(mX, mY);
+ result.normalize();
+ return result;
+}
+
+/*! \overload
+
+ Returns the squared shortest distance of this vector (interpreted as a point) to the finite line
+ segment given by \a start and \a end.
+
+ \see distanceToStraightLine
+*/
+double QCPVector2D::distanceSquaredToLine(const QCPVector2D &start, const QCPVector2D &end) const
+{
+ QCPVector2D v(end-start);
+ double vLengthSqr = v.lengthSquared();
+ if (!qFuzzyIsNull(vLengthSqr))
+ {
+ double mu = v.dot(*this-start)/vLengthSqr;
+ if (mu < 0)
+ return (*this-start).lengthSquared();
+ else if (mu > 1)
+ return (*this-end).lengthSquared();
+ else
+ return ((start + mu*v)-*this).lengthSquared();
+ } else
+ return (*this-start).lengthSquared();
+}
+
+/*! \overload
+
+ Returns the squared shortest distance of this vector (interpreted as a point) to the finite line
+ segment given by \a line.
+
+ \see distanceToStraightLine
+*/
+double QCPVector2D::distanceSquaredToLine(const QLineF &line) const
+{
+ return distanceSquaredToLine(QCPVector2D(line.p1()), QCPVector2D(line.p2()));
+}
+
+/*!
+ Returns the shortest distance of this vector (interpreted as a point) to the infinite straight
+ line given by a \a base point and a \a direction vector.
+
+ \see distanceSquaredToLine
+*/
+double QCPVector2D::distanceToStraightLine(const QCPVector2D &base, const QCPVector2D &direction) const
+{
+ return qAbs((*this-base).dot(direction.perpendicular()))/direction.length();
+}
+
+/*!
+ Scales this vector by the given \a factor, i.e. the x and y components are multiplied by \a
+ factor.
+*/
+QCPVector2D &QCPVector2D::operator*=(double factor)
+{
+ mX *= factor;
+ mY *= factor;
+ return *this;
+}
+
+/*!
+ Scales this vector by the given \a divisor, i.e. the x and y components are divided by \a
+ divisor.
+*/
+QCPVector2D &QCPVector2D::operator/=(double divisor)
+{
+ mX /= divisor;
+ mY /= divisor;
+ return *this;
+}
+
+/*!
+ Adds the given \a vector to this vector component-wise.
+*/
+QCPVector2D &QCPVector2D::operator+=(const QCPVector2D &vector)
+{
+ mX += vector.mX;
+ mY += vector.mY;
+ return *this;
+}
+
+/*!
+ subtracts the given \a vector from this vector component-wise.
+*/
+QCPVector2D &QCPVector2D::operator-=(const QCPVector2D &vector)
+{
+ mX -= vector.mX;
+ mY -= vector.mY;
+ return *this;
+}
+/* end of 'src/vector2d.cpp' */
+
+
+/* including file 'src/painter.cpp', size 8670 */
+/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPPainter
@@ -73,10 +308,6 @@ QCPPainter::QCPPainter(QPaintDevice *device) :
#endif
}
-QCPPainter::~QCPPainter()
-{
-}
-
/*!
Sets the pen of the painter and applies certain fixes to it, depending on the mode of this
QCPPainter.
@@ -243,471 +474,543 @@ void QCPPainter::makeNonCosmetic()
QPainter::setPen(p);
}
}
+/* end of 'src/painter.cpp' */
+/* including file 'src/paintbuffer.cpp', size 18502 */
+/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
+
////////////////////////////////////////////////////////////////////////////////////////////////////
-//////////////////// QCPScatterStyle
+//////////////////// QCPAbstractPaintBuffer
////////////////////////////////////////////////////////////////////////////////////////////////////
-/*! \class QCPScatterStyle
- \brief Represents the visual appearance of scatter points
-
- This class holds information about shape, color and size of scatter points. In plottables like
- QCPGraph it is used to store how scatter points shall be drawn. For example, \ref
- QCPGraph::setScatterStyle takes a QCPScatterStyle instance.
-
- A scatter style consists of a shape (\ref setShape), a line color (\ref setPen) and possibly a
- fill (\ref setBrush), if the shape provides a fillable area. Further, the size of the shape can
- be controlled with \ref setSize.
+/*! \class QCPAbstractPaintBuffer
+ \brief The abstract base class for paint buffers, which define the rendering backend
- \section QCPScatterStyle-defining Specifying a scatter style
-
- You can set all these configurations either by calling the respective functions on an instance:
- \snippet documentation/doc-code-snippets/mainwindow.cpp qcpscatterstyle-creation-1
-
- Or you can use one of the various constructors that take different parameter combinations, making
- it easy to specify a scatter style in a single call, like so:
- \snippet documentation/doc-code-snippets/mainwindow.cpp qcpscatterstyle-creation-2
-
- \section QCPScatterStyle-undefinedpen Leaving the color/pen up to the plottable
-
- There are two constructors which leave the pen undefined: \ref QCPScatterStyle() and \ref
- QCPScatterStyle(ScatterShape shape, double size). If those constructors are used, a call to \ref
- isPenDefined will return false. It leads to scatter points that inherit the pen from the
- plottable that uses the scatter style. Thus, if such a scatter style is passed to QCPGraph, the line
- color of the graph (\ref QCPGraph::setPen) will be used by the scatter points. This makes
- it very convenient to set up typical scatter settings:
-
- \snippet documentation/doc-code-snippets/mainwindow.cpp qcpscatterstyle-shortcreation
+ This abstract base class defines the basic interface that a paint buffer needs to provide in
+ order to be usable by QCustomPlot.
- Notice that it wasn't even necessary to explicitly call a QCPScatterStyle constructor. This works
- because QCPScatterStyle provides a constructor that can transform a \ref ScatterShape directly
- into a QCPScatterStyle instance (that's the \ref QCPScatterStyle(ScatterShape shape, double size)
- constructor with a default for \a size). In those cases, C++ allows directly supplying a \ref
- ScatterShape, where actually a QCPScatterStyle is expected.
-
- \section QCPScatterStyle-custompath-and-pixmap Custom shapes and pixmaps
-
- QCPScatterStyle supports drawing custom shapes and arbitrary pixmaps as scatter points.
+ A paint buffer manages both a surface to draw onto, and the matching paint device. The size of
+ the surface can be changed via \ref setSize. External classes (\ref QCustomPlot and \ref
+ QCPLayer) request a painter via \ref startPainting and then perform the draw calls. Once the
+ painting is complete, \ref donePainting is called, so the paint buffer implementation can do
+ clean up if necessary. Before rendering a frame, each paint buffer is usually filled with a color
+ using \ref clear (usually the color is \c Qt::transparent), to remove the contents of the
+ previous frame.
- For custom shapes, you can provide a QPainterPath with the desired shape to the \ref
- setCustomPath function or call the constructor that takes a painter path. The scatter shape will
- automatically be set to \ref ssCustom.
-
- For pixmaps, you call \ref setPixmap with the desired QPixmap. Alternatively you can use the
- constructor that takes a QPixmap. The scatter shape will automatically be set to \ref ssPixmap.
- Note that \ref setSize does not influence the appearance of the pixmap.
+ The simplest paint buffer implementation is \ref QCPPaintBufferPixmap which allows regular
+ software rendering via the raster engine. Hardware accelerated rendering via pixel buffers and
+ frame buffer objects is provided by \ref QCPPaintBufferGlPbuffer and \ref QCPPaintBufferGlFbo.
+ They are used automatically if \ref QCustomPlot::setOpenGl is enabled.
*/
-/* start documentation of inline functions */
+/* start documentation of pure virtual functions */
-/*! \fn bool QCPScatterStyle::isNone() const
-
- Returns whether the scatter shape is \ref ssNone.
-
- \see setShape
+/*! \fn virtual QCPPainter *QCPAbstractPaintBuffer::startPainting() = 0
+
+ Returns a \ref QCPPainter which is ready to draw to this buffer. The ownership and thus the
+ responsibility to delete the painter after the painting operations are complete is given to the
+ caller of this method.
+
+ Once you are done using the painter, delete the painter and call \ref donePainting.
+
+ While a painter generated with this method is active, you must not call \ref setSize, \ref
+ setDevicePixelRatio or \ref clear.
+
+ This method may return 0, if a painter couldn't be activated on the buffer. This usually
+ indicates a problem with the respective painting backend.
*/
-/*! \fn bool QCPScatterStyle::isPenDefined() const
-
- Returns whether a pen has been defined for this scatter style.
-
- The pen is undefined if a constructor is called that does not carry \a pen as parameter. Those are
- \ref QCPScatterStyle() and \ref QCPScatterStyle(ScatterShape shape, double size). If the pen is
- left undefined, the scatter color will be inherited from the plottable that uses this scatter
- style.
-
- \see setPen
+/*! \fn virtual void QCPAbstractPaintBuffer::draw(QCPPainter *painter) const = 0
+
+ Draws the contents of this buffer with the provided \a painter. This is the method that is used
+ to finally join all paint buffers and draw them onto the screen.
+*/
+
+/*! \fn virtual void QCPAbstractPaintBuffer::clear(const QColor &color) = 0
+
+ Fills the entire buffer with the provided \a color. To have an empty transparent buffer, use the
+ named color \c Qt::transparent.
+
+ This method must not be called if there is currently a painter (acquired with \ref startPainting)
+ active.
+*/
+
+/*! \fn virtual void QCPAbstractPaintBuffer::reallocateBuffer() = 0
+
+ Reallocates the internal buffer with the currently configured size (\ref setSize) and device
+ pixel ratio, if applicable (\ref setDevicePixelRatio). It is called as soon as any of those
+ properties are changed on this paint buffer.
+
+ \note Subclasses of \ref QCPAbstractPaintBuffer must call their reimplementation of this method
+ in their constructor, to perform the first allocation (this can not be done by the base class
+ because calling pure virtual methods in base class constructors is not possible).
+*/
+
+/* end documentation of pure virtual functions */
+/* start documentation of inline functions */
+
+/*! \fn virtual void QCPAbstractPaintBuffer::donePainting()
+
+ If you have acquired a \ref QCPPainter to paint onto this paint buffer via \ref startPainting,
+ call this method as soon as you are done with the painting operations and have deleted the
+ painter.
+
+ paint buffer subclasses may use this method to perform any type of cleanup that is necessary. The
+ default implementation does nothing.
*/
/* end documentation of inline functions */
/*!
- Creates a new QCPScatterStyle instance with size set to 6. No shape, pen or brush is defined.
-
- Since the pen is undefined (\ref isPenDefined returns false), the scatter color will be inherited
- from the plottable that uses this scatter style.
+ Creates a paint buffer and initializes it with the provided \a size and \a devicePixelRatio.
+
+ Subclasses must call their \ref reallocateBuffer implementation in their respective constructors.
*/
-QCPScatterStyle::QCPScatterStyle() :
- mSize(6),
- mShape(ssNone),
- mPen(Qt::NoPen),
- mBrush(Qt::NoBrush),
- mPenDefined(false)
+QCPAbstractPaintBuffer::QCPAbstractPaintBuffer(const QSize &size, double devicePixelRatio) :
+ mSize(size),
+ mDevicePixelRatio(devicePixelRatio),
+ mInvalidated(true)
{
}
-/*!
- Creates a new QCPScatterStyle instance with shape set to \a shape and size to \a size. No pen or
- brush is defined.
-
- Since the pen is undefined (\ref isPenDefined returns false), the scatter color will be inherited
- from the plottable that uses this scatter style.
-*/
-QCPScatterStyle::QCPScatterStyle(ScatterShape shape, double size) :
- mSize(size),
- mShape(shape),
- mPen(Qt::NoPen),
- mBrush(Qt::NoBrush),
- mPenDefined(false)
+QCPAbstractPaintBuffer::~QCPAbstractPaintBuffer()
{
}
/*!
- Creates a new QCPScatterStyle instance with shape set to \a shape, the pen color set to \a color,
- and size to \a size. No brush is defined, i.e. the scatter point will not be filled.
+ Sets the paint buffer size.
+
+ The buffer is reallocated (by calling \ref reallocateBuffer), so any painters that were obtained
+ by \ref startPainting are invalidated and must not be used after calling this method.
+
+ If \a size is already the current buffer size, this method does nothing.
*/
-QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QColor &color, double size) :
- mSize(size),
- mShape(shape),
- mPen(QPen(color)),
- mBrush(Qt::NoBrush),
- mPenDefined(true)
+void QCPAbstractPaintBuffer::setSize(const QSize &size)
{
+ if (mSize != size)
+ {
+ mSize = size;
+ reallocateBuffer();
+ }
}
/*!
- Creates a new QCPScatterStyle instance with shape set to \a shape, the pen color set to \a color,
- the brush color to \a fill (with a solid pattern), and size to \a size.
+ Sets the invalidated flag to \a invalidated.
+
+ This mechanism is used internally in conjunction with isolated replotting of \ref QCPLayer
+ instances (in \ref QCPLayer::lmBuffered mode). If \ref QCPLayer::replot is called on a buffered
+ layer, i.e. an isolated repaint of only that layer (and its dedicated paint buffer) is requested,
+ QCustomPlot will decide depending on the invalidated flags of other paint buffers whether it also
+ replots them, instead of only the layer on which the replot was called.
+
+ The invalidated flag is set to true when \ref QCPLayer association has changed, i.e. if layers
+ were added or removed from this buffer, or if they were reordered. It is set to false as soon as
+ all associated \ref QCPLayer instances are drawn onto the buffer.
+
+ Under normal circumstances, it is not necessary to manually call this method.
*/
-QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QColor &color, const QColor &fill, double size) :
- mSize(size),
- mShape(shape),
- mPen(QPen(color)),
- mBrush(QBrush(fill)),
- mPenDefined(true)
+void QCPAbstractPaintBuffer::setInvalidated(bool invalidated)
{
+ mInvalidated = invalidated;
}
/*!
- Creates a new QCPScatterStyle instance with shape set to \a shape, the pen set to \a pen, the
- brush to \a brush, and size to \a size.
-
- \warning In some cases it might be tempting to directly use a pen style like <tt>Qt::NoPen</tt> as \a pen
- and a color like <tt>Qt::blue</tt> as \a brush. Notice however, that the corresponding call\n
- <tt>QCPScatterStyle(QCPScatterShape::ssCircle, Qt::NoPen, Qt::blue, 5)</tt>\n
- doesn't necessarily lead C++ to use this constructor in some cases, but might mistake
- <tt>Qt::NoPen</tt> for a QColor and use the
- \ref QCPScatterStyle(ScatterShape shape, const QColor &color, const QColor &fill, double size)
- constructor instead (which will lead to an unexpected look of the scatter points). To prevent
- this, be more explicit with the parameter types. For example, use <tt>QBrush(Qt::blue)</tt>
- instead of just <tt>Qt::blue</tt>, to clearly point out to the compiler that this constructor is
- wanted.
+ Sets the the device pixel ratio to \a ratio. This is useful to render on high-DPI output devices.
+ The ratio is automatically set to the device pixel ratio used by the parent QCustomPlot instance.
+
+ The buffer is reallocated (by calling \ref reallocateBuffer), so any painters that were obtained
+ by \ref startPainting are invalidated and must not be used after calling this method.
+
+ \note This method is only available for Qt versions 5.4 and higher.
*/
-QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QPen &pen, const QBrush &brush, double size) :
- mSize(size),
- mShape(shape),
- mPen(pen),
- mBrush(brush),
- mPenDefined(pen.style() != Qt::NoPen)
+void QCPAbstractPaintBuffer::setDevicePixelRatio(double ratio)
{
+ if (!qFuzzyCompare(ratio, mDevicePixelRatio))
+ {
+#ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
+ mDevicePixelRatio = ratio;
+ reallocateBuffer();
+#else
+ qDebug() << Q_FUNC_INFO << "Device pixel ratios not supported for Qt versions before 5.4";
+ mDevicePixelRatio = 1.0;
+#endif
+ }
}
+////////////////////////////////////////////////////////////////////////////////////////////////////
+//////////////////// QCPPaintBufferPixmap
+////////////////////////////////////////////////////////////////////////////////////////////////////
+
+/*! \class QCPPaintBufferPixmap
+ \brief A paint buffer based on QPixmap, using software raster rendering
+
+ This paint buffer is the default and fall-back paint buffer which uses software rendering and
+ QPixmap as internal buffer. It is used if \ref QCustomPlot::setOpenGl is false.
+*/
+
/*!
- Creates a new QCPScatterStyle instance which will show the specified \a pixmap. The scatter shape
- is set to \ref ssPixmap.
+ Creates a pixmap paint buffer instancen with the specified \a size and \a devicePixelRatio, if
+ applicable.
*/
-QCPScatterStyle::QCPScatterStyle(const QPixmap &pixmap) :
- mSize(5),
- mShape(ssPixmap),
- mPen(Qt::NoPen),
- mBrush(Qt::NoBrush),
- mPixmap(pixmap),
- mPenDefined(false)
+QCPPaintBufferPixmap::QCPPaintBufferPixmap(const QSize &size, double devicePixelRatio) :
+ QCPAbstractPaintBuffer(size, devicePixelRatio)
{
+ QCPPaintBufferPixmap::reallocateBuffer();
}
-/*!
- Creates a new QCPScatterStyle instance with a custom shape that is defined via \a customPath. The
- scatter shape is set to \ref ssCustom.
-
- The custom shape line will be drawn with \a pen and filled with \a brush. The size has a slightly
- different meaning than for built-in scatter points: The custom path will be drawn scaled by a
- factor of \a size/6.0. Since the default \a size is 6, the custom path will appear at a its
- natural size by default. To double the size of the path for example, set \a size to 12.
-*/
-QCPScatterStyle::QCPScatterStyle(const QPainterPath &customPath, const QPen &pen, const QBrush &brush, double size) :
- mSize(size),
- mShape(ssCustom),
- mPen(pen),
- mBrush(brush),
- mCustomPath(customPath),
- mPenDefined(pen.style() != Qt::NoPen)
+QCPPaintBufferPixmap::~QCPPaintBufferPixmap()
{
}
-/*!
- Sets the size (pixel diameter) of the drawn scatter points to \a size.
-
- \see setShape
-*/
-void QCPScatterStyle::setSize(double size)
+/* inherits documentation from base class */
+QCPPainter *QCPPaintBufferPixmap::startPainting()
{
- mSize = size;
+ QCPPainter *result = new QCPPainter(&mBuffer);
+ result->setRenderHint(QPainter::HighQualityAntialiasing);
+ return result;
}
-/*!
- Sets the shape to \a shape.
-
- Note that the calls \ref setPixmap and \ref setCustomPath automatically set the shape to \ref
- ssPixmap and \ref ssCustom, respectively.
-
- \see setSize
-*/
-void QCPScatterStyle::setShape(QCPScatterStyle::ScatterShape shape)
+/* inherits documentation from base class */
+void QCPPaintBufferPixmap::draw(QCPPainter *painter) const
{
- mShape = shape;
+ if (painter && painter->isActive())
+ painter->drawPixmap(0, 0, mBuffer);
+ else
+ qDebug() << Q_FUNC_INFO << "invalid or inactive painter passed";
}
-/*!
- Sets the pen that will be used to draw scatter points to \a pen.
-
- If the pen was previously undefined (see \ref isPenDefined), the pen is considered defined after
- a call to this function, even if \a pen is <tt>Qt::NoPen</tt>.
-
- \see setBrush
-*/
-void QCPScatterStyle::setPen(const QPen &pen)
+/* inherits documentation from base class */
+void QCPPaintBufferPixmap::clear(const QColor &color)
{
- mPenDefined = true;
- mPen = pen;
+ mBuffer.fill(color);
}
-/*!
- Sets the brush that will be used to fill scatter points to \a brush. Note that not all scatter
- shapes have fillable areas. For example, \ref ssPlus does not while \ref ssCircle does.
-
- \see setPen
-*/
-void QCPScatterStyle::setBrush(const QBrush &brush)
+/* inherits documentation from base class */
+void QCPPaintBufferPixmap::reallocateBuffer()
{
- mBrush = brush;
+ setInvalidated();
+ if (!qFuzzyCompare(1.0, mDevicePixelRatio))
+ {
+#ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
+ mBuffer = QPixmap(mSize*mDevicePixelRatio);
+ mBuffer.setDevicePixelRatio(mDevicePixelRatio);
+#else
+ qDebug() << Q_FUNC_INFO << "Device pixel ratios not supported for Qt versions before 5.4";
+ mDevicePixelRatio = 1.0;
+ mBuffer = QPixmap(mSize);
+#endif
+ } else
+ {
+ mBuffer = QPixmap(mSize);
+ }
}
+
+#ifdef QCP_OPENGL_PBUFFER
+////////////////////////////////////////////////////////////////////////////////////////////////////
+//////////////////// QCPPaintBufferGlPbuffer
+////////////////////////////////////////////////////////////////////////////////////////////////////
+
+/*! \class QCPPaintBufferGlPbuffer
+ \brief A paint buffer based on OpenGL pixel buffers, using hardware accelerated rendering
+
+ This paint buffer is one of the OpenGL paint buffers which facilitate hardware accelerated plot
+ rendering. It is based on OpenGL pixel buffers (pbuffer) and is used in Qt versions before 5.0.
+ (See \ref QCPPaintBufferGlFbo used in newer Qt versions.)
+
+ The OpenGL paint buffers are used if \ref QCustomPlot::setOpenGl is set to true, and if they are
+ supported by the system.
+*/
+
/*!
- Sets the pixmap that will be drawn as scatter point to \a pixmap.
-
- Note that \ref setSize does not influence the appearance of the pixmap.
-
- The scatter shape is automatically set to \ref ssPixmap.
+ Creates a \ref QCPPaintBufferGlPbuffer instance with the specified \a size and \a
+ devicePixelRatio, if applicable.
+
+ The parameter \a multisamples defines how many samples are used per pixel. Higher values thus
+ result in higher quality antialiasing. If the specified \a multisamples value exceeds the
+ capability of the graphics hardware, the highest supported multisampling is used.
*/
-void QCPScatterStyle::setPixmap(const QPixmap &pixmap)
+QCPPaintBufferGlPbuffer::QCPPaintBufferGlPbuffer(const QSize &size, double devicePixelRatio, int multisamples) :
+ QCPAbstractPaintBuffer(size, devicePixelRatio),
+ mGlPBuffer(0),
+ mMultisamples(qMax(0, multisamples))
{
- setShape(ssPixmap);
- mPixmap = pixmap;
+ QCPPaintBufferGlPbuffer::reallocateBuffer();
}
-/*!
- Sets the custom shape that will be drawn as scatter point to \a customPath.
-
- The scatter shape is automatically set to \ref ssCustom.
-*/
-void QCPScatterStyle::setCustomPath(const QPainterPath &customPath)
+QCPPaintBufferGlPbuffer::~QCPPaintBufferGlPbuffer()
{
- setShape(ssCustom);
- mCustomPath = customPath;
+ if (mGlPBuffer)
+ delete mGlPBuffer;
}
-/*!
- Applies the pen and the brush of this scatter style to \a painter. If this scatter style has an
- undefined pen (\ref isPenDefined), sets the pen of \a painter to \a defaultPen instead.
+/* inherits documentation from base class */
+QCPPainter *QCPPaintBufferGlPbuffer::startPainting()
+{
+ if (!mGlPBuffer->isValid())
+ {
+ qDebug() << Q_FUNC_INFO << "OpenGL frame buffer object doesn't exist, reallocateBuffer was not called?";
+ return 0;
+ }
- This function is used by plottables (or any class that wants to draw scatters) just before a
- number of scatters with this style shall be drawn with the \a painter.
+ QCPPainter *result = new QCPPainter(mGlPBuffer);
+ result->setRenderHint(QPainter::HighQualityAntialiasing);
+ return result;
+}
+
+/* inherits documentation from base class */
+void QCPPaintBufferGlPbuffer::draw(QCPPainter *painter) const
+{
+ if (!painter || !painter->isActive())
+ {
+ qDebug() << Q_FUNC_INFO << "invalid or inactive painter passed";
+ return;
+ }
+ if (!mGlPBuffer->isValid())
+ {
+ qDebug() << Q_FUNC_INFO << "OpenGL pbuffer isn't valid, reallocateBuffer was not called?";
+ return;
+ }
+ painter->drawImage(0, 0, mGlPBuffer->toImage());
+}
+
+/* inherits documentation from base class */
+void QCPPaintBufferGlPbuffer::clear(const QColor &color)
+{
+ if (mGlPBuffer->isValid())
+ {
+ mGlPBuffer->makeCurrent();
+ glClearColor(color.redF(), color.greenF(), color.blueF(), color.alphaF());
+ glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
+ mGlPBuffer->doneCurrent();
+ } else
+ qDebug() << Q_FUNC_INFO << "OpenGL pbuffer invalid or context not current";
+}
+
+/* inherits documentation from base class */
+void QCPPaintBufferGlPbuffer::reallocateBuffer()
+{
+ if (mGlPBuffer)
+ delete mGlPBuffer;
- \see drawShape
+ QGLFormat format;
+ format.setAlpha(true);
+ format.setSamples(mMultisamples);
+ mGlPBuffer = new QGLPixelBuffer(mSize, format);
+}
+#endif // QCP_OPENGL_PBUFFER
+
+
+#ifdef QCP_OPENGL_FBO
+////////////////////////////////////////////////////////////////////////////////////////////////////
+//////////////////// QCPPaintBufferGlFbo
+////////////////////////////////////////////////////////////////////////////////////////////////////
+
+/*! \class QCPPaintBufferGlFbo
+ \brief A paint buffer based on OpenGL frame buffers objects, using hardware accelerated rendering
+
+ This paint buffer is one of the OpenGL paint buffers which facilitate hardware accelerated plot
+ rendering. It is based on OpenGL frame buffer objects (fbo) and is used in Qt versions 5.0 and
+ higher. (See \ref QCPPaintBufferGlPbuffer used in older Qt versions.)
+
+ The OpenGL paint buffers are used if \ref QCustomPlot::setOpenGl is set to true, and if they are
+ supported by the system.
*/
-void QCPScatterStyle::applyTo(QCPPainter *painter, const QPen &defaultPen) const
+
+/*!
+ Creates a \ref QCPPaintBufferGlFbo instance with the specified \a size and \a devicePixelRatio,
+ if applicable.
+
+ All frame buffer objects shall share one OpenGL context and paint device, which need to be set up
+ externally and passed via \a glContext and \a glPaintDevice. The set-up is done in \ref
+ QCustomPlot::setupOpenGl and the context and paint device are managed by the parent QCustomPlot
+ instance.
+*/
+QCPPaintBufferGlFbo::QCPPaintBufferGlFbo(const QSize &size, double devicePixelRatio, QWeakPointer<QOpenGLContext> glContext, QWeakPointer<QOpenGLPaintDevice> glPaintDevice) :
+ QCPAbstractPaintBuffer(size, devicePixelRatio),
+ mGlContext(glContext),
+ mGlPaintDevice(glPaintDevice),
+ mGlFrameBuffer(0)
{
- painter->setPen(mPenDefined ? mPen : defaultPen);
- painter->setBrush(mBrush);
+ QCPPaintBufferGlFbo::reallocateBuffer();
}
-/*!
- Draws the scatter shape with \a painter at position \a pos.
-
- This function does not modify the pen or the brush on the painter, as \ref applyTo is meant to be
- called before scatter points are drawn with \ref drawShape.
+QCPPaintBufferGlFbo::~QCPPaintBufferGlFbo()
+{
+ if (mGlFrameBuffer)
+ delete mGlFrameBuffer;
+}
+
+/* inherits documentation from base class */
+QCPPainter *QCPPaintBufferGlFbo::startPainting()
+{
+ if (mGlPaintDevice.isNull())
+ {
+ qDebug() << Q_FUNC_INFO << "OpenGL paint device doesn't exist";
+ return 0;
+ }
+ if (!mGlFrameBuffer)
+ {
+ qDebug() << Q_FUNC_INFO << "OpenGL frame buffer object doesn't exist, reallocateBuffer was not called?";
+ return 0;
+ }
- \see applyTo
-*/
-void QCPScatterStyle::drawShape(QCPPainter *painter, QPointF pos) const
+ if (QOpenGLContext::currentContext() != mGlContext.data())
+ mGlContext.data()->makeCurrent(mGlContext.data()->surface());
+ mGlFrameBuffer->bind();
+ QCPPainter *result = new QCPPainter(mGlPaintDevice.data());
+ result->setRenderHint(QPainter::HighQualityAntialiasing);
+ return result;
+}
+
+/* inherits documentation from base class */
+void QCPPaintBufferGlFbo::donePainting()
{
- drawShape(painter, pos.x(), pos.y());
+ if (mGlFrameBuffer && mGlFrameBuffer->isBound())
+ mGlFrameBuffer->release();
+ else
+ qDebug() << Q_FUNC_INFO << "Either OpenGL frame buffer not valid or was not bound";
}
-/*! \overload
- Draws the scatter shape with \a painter at position \a x and \a y.
-*/
-void QCPScatterStyle::drawShape(QCPPainter *painter, double x, double y) const
+/* inherits documentation from base class */
+void QCPPaintBufferGlFbo::draw(QCPPainter *painter) const
{
- double w = mSize/2.0;
- switch (mShape)
+ if (!painter || !painter->isActive())
{
- case ssNone: break;
- case ssDot:
- {
- painter->drawLine(QPointF(x, y), QPointF(x+0.0001, y));
- break;
- }
- case ssCross:
- {
- painter->drawLine(QLineF(x-w, y-w, x+w, y+w));
- painter->drawLine(QLineF(x-w, y+w, x+w, y-w));
- break;
- }
- case ssPlus:
- {
- painter->drawLine(QLineF(x-w, y, x+w, y));
- painter->drawLine(QLineF( x, y+w, x, y-w));
- break;
- }
- case ssCircle:
- {
- painter->drawEllipse(QPointF(x , y), w, w);
- break;
- }
- case ssDisc:
- {
- QBrush b = painter->brush();
- painter->setBrush(painter->pen().color());
- painter->drawEllipse(QPointF(x , y), w, w);
- painter->setBrush(b);
- break;
- }
- case ssSquare:
- {
- painter->drawRect(QRectF(x-w, y-w, mSize, mSize));
- break;
- }
- case ssDiamond:
- {
- painter->drawLine(QLineF(x-w, y, x, y-w));
- painter->drawLine(QLineF( x, y-w, x+w, y));
- painter->drawLine(QLineF(x+w, y, x, y+w));
- painter->drawLine(QLineF( x, y+w, x-w, y));
- break;
- }
- case ssStar:
- {
- painter->drawLine(QLineF(x-w, y, x+w, y));
- painter->drawLine(QLineF( x, y+w, x, y-w));
- painter->drawLine(QLineF(x-w*0.707, y-w*0.707, x+w*0.707, y+w*0.707));
- painter->drawLine(QLineF(x-w*0.707, y+w*0.707, x+w*0.707, y-w*0.707));
- break;
- }
- case ssTriangle:
- {
- painter->drawLine(QLineF(x-w, y+0.755*w, x+w, y+0.755*w));
- painter->drawLine(QLineF(x+w, y+0.755*w, x, y-0.977*w));
- painter->drawLine(QLineF( x, y-0.977*w, x-w, y+0.755*w));
- break;
- }
- case ssTriangleInverted:
- {
- painter->drawLine(QLineF(x-w, y-0.755*w, x+w, y-0.755*w));
- painter->drawLine(QLineF(x+w, y-0.755*w, x, y+0.977*w));
- painter->drawLine(QLineF( x, y+0.977*w, x-w, y-0.755*w));
- break;
- }
- case ssCrossSquare:
- {
- painter->drawLine(QLineF(x-w, y-w, x+w*0.95, y+w*0.95));
- painter->drawLine(QLineF(x-w, y+w*0.95, x+w*0.95, y-w));
- painter->drawRect(QRectF(x-w, y-w, mSize, mSize));
- break;
- }
- case ssPlusSquare:
- {
- painter->drawLine(QLineF(x-w, y, x+w*0.95, y));
- painter->drawLine(QLineF( x, y+w, x, y-w));
- painter->drawRect(QRectF(x-w, y-w, mSize, mSize));
- break;
- }
- case ssCrossCircle:
- {
- painter->drawLine(QLineF(x-w*0.707, y-w*0.707, x+w*0.670, y+w*0.670));
- painter->drawLine(QLineF(x-w*0.707, y+w*0.670, x+w*0.670, y-w*0.707));
- painter->drawEllipse(QPointF(x, y), w, w);
- break;
- }
- case ssPlusCircle:
- {
- painter->drawLine(QLineF(x-w, y, x+w, y));
- painter->drawLine(QLineF( x, y+w, x, y-w));
- painter->drawEllipse(QPointF(x, y), w, w);
- break;
- }
- case ssPeace:
- {
- painter->drawLine(QLineF(x, y-w, x, y+w));
- painter->drawLine(QLineF(x, y, x-w*0.707, y+w*0.707));
- painter->drawLine(QLineF(x, y, x+w*0.707, y+w*0.707));
- painter->drawEllipse(QPointF(x, y), w, w);
- break;
- }
- case ssPixmap:
- {
- painter->drawPixmap(x-mPixmap.width()*0.5, y-mPixmap.height()*0.5, mPixmap);
- break;
- }
- case ssCustom:
- {
- QTransform oldTransform = painter->transform();
- painter->translate(x, y);
- painter->scale(mSize/6.0, mSize/6.0);
- painter->drawPath(mCustomPath);
- painter->setTransform(oldTransform);
- break;
- }
+ qDebug() << Q_FUNC_INFO << "invalid or inactive painter passed";
+ return;
+ }
+ if (!mGlFrameBuffer)
+ {
+ qDebug() << Q_FUNC_INFO << "OpenGL frame buffer object doesn't exist, reallocateBuffer was not called?";
+ return;
+ }
+ painter->drawImage(0, 0, mGlFrameBuffer->toImage());
+}
+
+/* inherits documentation from base class */
+void QCPPaintBufferGlFbo::clear(const QColor &color)
+{
+ if (mGlContext.isNull())
+ {
+ qDebug() << Q_FUNC_INFO << "OpenGL context doesn't exist";
+ return;
+ }
+ if (!mGlFrameBuffer)
+ {
+ qDebug() << Q_FUNC_INFO << "OpenGL frame buffer object doesn't exist, reallocateBuffer was not called?";
+ return;
+ }
+
+ if (QOpenGLContext::currentContext() != mGlContext.data())
+ mGlContext.data()->makeCurrent(mGlContext.data()->surface());
+ mGlFrameBuffer->bind();
+ glClearColor(color.redF(), color.greenF(), color.blueF(), color.alphaF());
+ glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
+ mGlFrameBuffer->release();
+}
+
+/* inherits documentation from base class */
+void QCPPaintBufferGlFbo::reallocateBuffer()
+{
+ // release and delete possibly existing framebuffer:
+ if (mGlFrameBuffer)
+ {
+ if (mGlFrameBuffer->isBound())
+ mGlFrameBuffer->release();
+ delete mGlFrameBuffer;
+ mGlFrameBuffer = 0;
+ }
+
+ if (mGlContext.isNull())
+ {
+ qDebug() << Q_FUNC_INFO << "OpenGL context doesn't exist";
+ return;
+ }
+ if (mGlPaintDevice.isNull())
+ {
+ qDebug() << Q_FUNC_INFO << "OpenGL paint device doesn't exist";
+ return;
}
+
+ // create new fbo with appropriate size:
+ mGlContext.data()->makeCurrent(mGlContext.data()->surface());
+ QOpenGLFramebufferObjectFormat frameBufferFormat;
+ frameBufferFormat.setSamples(mGlContext.data()->format().samples());
+ frameBufferFormat.setAttachment(QOpenGLFramebufferObject::CombinedDepthStencil);
+ mGlFrameBuffer = new QOpenGLFramebufferObject(mSize*mDevicePixelRatio, frameBufferFormat);
+ if (mGlPaintDevice.data()->size() != mSize*mDevicePixelRatio)
+ mGlPaintDevice.data()->setSize(mSize*mDevicePixelRatio);
+#ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
+ mGlPaintDevice.data()->setDevicePixelRatio(mDevicePixelRatio);
+#endif
}
+#endif // QCP_OPENGL_FBO
+/* end of 'src/paintbuffer.cpp' */
+/* including file 'src/layer.cpp', size 37064 */
+/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
+
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPLayer
////////////////////////////////////////////////////////////////////////////////////////////////////
/*! \class QCPLayer
\brief A layer that may contain objects, to control the rendering order
-
+
The Layering system of QCustomPlot is the mechanism to control the rendering order of the
elements inside the plot.
-
+
It is based on the two classes QCPLayer and QCPLayerable. QCustomPlot holds an ordered list of
one or more instances of QCPLayer (see QCustomPlot::addLayer, QCustomPlot::layer,
QCustomPlot::moveLayer, etc.). When replotting, QCustomPlot goes through the list of layers
- bottom to top and successively draws the layerables of the layers.
-
+ bottom to top and successively draws the layerables of the layers into the paint buffer(s).
+
A QCPLayer contains an ordered list of QCPLayerable instances. QCPLayerable is an abstract base
class from which almost all visible objects derive, like axes, grids, graphs, items, etc.
-
- Initially, QCustomPlot has five layers: "background", "grid", "main", "axes" and "legend" (in
- that order). The top two layers "axes" and "legend" contain the default axes and legend, so they
- will be drawn on top. In the middle, there is the "main" layer. It is initially empty and set as
- the current layer (see QCustomPlot::setCurrentLayer). This means, all new plottables, items etc.
- are created on this layer by default. Then comes the "grid" layer which contains the QCPGrid
- instances (which belong tightly to QCPAxis, see \ref QCPAxis::grid). The Axis rect background
- shall be drawn behind everything else, thus the default QCPAxisRect instance is placed on the
- "background" layer. Of course, the layer affiliation of the individual objects can be changed as
- required (\ref QCPLayerable::setLayer).
-
- Controlling the ordering of objects is easy: Create a new layer in the position you want it to
- be, e.g. above "main", with QCustomPlot::addLayer. Then set the current layer with
- QCustomPlot::setCurrentLayer to that new layer and finally create the objects normally. They will
- be placed on the new layer automatically, due to the current layer setting. Alternatively you
- could have also ignored the current layer setting and just moved the objects with
- QCPLayerable::setLayer to the desired layer after creating them.
-
+
+ \section qcplayer-defaultlayers Default layers
+
+ Initially, QCustomPlot has six layers: "background", "grid", "main", "axes", "legend" and
+ "overlay" (in that order). On top is the "overlay" layer, which only contains the QCustomPlot's
+ selection rect (\ref QCustomPlot::selectionRect). The next two layers "axes" and "legend" contain
+ the default axes and legend, so they will be drawn above plottables. In the middle, there is the
+ "main" layer. It is initially empty and set as the current layer (see
+ QCustomPlot::setCurrentLayer). This means, all new plottables, items etc. are created on this
+ layer by default. Then comes the "grid" layer which contains the QCPGrid instances (which belong
+ tightly to QCPAxis, see \ref QCPAxis::grid). The Axis rect background shall be drawn behind
+ everything else, thus the default QCPAxisRect instance is placed on the "background" layer. Of
+ course, the layer affiliation of the individual objects can be changed as required (\ref
+ QCPLayerable::setLayer).
+
+ \section qcplayer-ordering Controlling the rendering order via layers
+
+ Controlling the ordering of layerables in the plot is easy: Create a new layer in the position
+ you want the layerable to be in, e.g. above "main", with \ref QCustomPlot::addLayer. Then set the
+ current layer with \ref QCustomPlot::setCurrentLayer to that new layer and finally create the
+ objects normally. They will be placed on the new layer automatically, due to the current layer
+ setting. Alternatively you could have also ignored the current layer setting and just moved the
+ objects with \ref QCPLayerable::setLayer to the desired layer after creating them.
+
It is also possible to move whole layers. For example, If you want the grid to be shown in front
of all plottables/items on the "main" layer, just move it above "main" with
QCustomPlot::moveLayer.
-
+
The rendering order within one layer is simply by order of creation or insertion. The item
created last (or added last to the layer), is drawn on top of all other objects on that layer.
-
+
When a layer is deleted, the objects on it are not deleted with it, but fall on the layer below
the deleted layer, see QCustomPlot::removeLayer.
+
+ \section qcplayer-buffering Replotting only a specific layer
+
+ If the layer mode (\ref setMode) is set to \ref lmBuffered, you can replot only this specific
+ layer by calling \ref replot. In certain situations this can provide better replot performance,
+ compared with a full replot of all layers. Upon creation of a new layer, the layer mode is
+ initialized to \ref lmLogical. The only layer that is set to \ref lmBuffered in a new \ref
+ QCustomPlot instance is the "overlay" layer, containing the selection rect.
*/
/* start documentation of inline functions */
@@ -741,7 +1044,8 @@ QCPLayer::QCPLayer(QCustomPlot *parentPlot, const QString &layerName) :
mParentPlot(parentPlot),
mName(layerName),
mIndex(-1), // will be set to a proper value by the QCustomPlot layer creation function
- mVisible(true)
+ mVisible(true),
+ mMode(lmLogical)
{
// Note: no need to make sure layerName is unique, because layer
// management is done with QCustomPlot functions.
@@ -774,6 +1078,113 @@ void QCPLayer::setVisible(bool visible)
mVisible = visible;
}
+/*!
+ Sets the rendering mode of this layer.
+
+ If \a mode is set to \ref lmBuffered for a layer, it will be given a dedicated paint buffer by
+ the parent QCustomPlot instance. This means it may be replotted individually by calling \ref
+ QCPLayer::replot, without needing to replot all other layers.
+
+ Layers which are set to \ref lmLogical (the default) are used only to define the rendering order
+ and can't be replotted individually.
+
+ Note that each layer which is set to \ref lmBuffered requires additional paint buffers for the
+ layers below, above and for the layer itself. This increases the memory consumption and
+ (slightly) decreases the repainting speed because multiple paint buffers need to be joined. So
+ you should carefully choose which layers benefit from having their own paint buffer. A typical
+ example would be a layer which contains certain layerables (e.g. items) that need to be changed
+ and thus replotted regularly, while all other layerables on other layers stay static. By default,
+ only the topmost layer called "overlay" is in mode \ref lmBuffered, and contains the selection
+ rect.
+
+ \see replot
+*/
+void QCPLayer::setMode(QCPLayer::LayerMode mode)
+{
+ if (mMode != mode)
+ {
+ mMode = mode;
+ if (!mPaintBuffer.isNull())
+ mPaintBuffer.data()->setInvalidated();
+ }
+}
+
+/*! \internal
+
+ Draws the contents of this layer with the provided \a painter.
+
+ \see replot, drawToPaintBuffer
+*/
+void QCPLayer::draw(QCPPainter *painter)
+{
+ foreach (QCPLayerable *child, mChildren)
+ {
+ if (child->realVisibility())
+ {
+ painter->save();
+ painter->setClipRect(child->clipRect().translated(0, -1));
+ child->applyDefaultAntialiasingHint(painter);
+ child->draw(painter);
+ painter->restore();
+ }
+ }
+}
+
+/*! \internal
+
+ Draws the contents of this layer into the paint buffer which is associated with this layer. The
+ association is established by the parent QCustomPlot, which manages all paint buffers (see \ref
+ QCustomPlot::setupPaintBuffers).
+
+ \see draw
+*/
+void QCPLayer::drawToPaintBuffer()
+{
+ if (!mPaintBuffer.isNull())
+ {
+ if (QCPPainter *painter = mPaintBuffer.data()->startPainting())
+ {
+ if (painter->isActive())
+ draw(painter);
+ else
+ qDebug() << Q_FUNC_INFO << "paint buffer returned inactive painter";
+ delete painter;
+ mPaintBuffer.data()->donePainting();
+ } else
+ qDebug() << Q_FUNC_INFO << "paint buffer returned zero painter";
+ } else
+ qDebug() << Q_FUNC_INFO << "no valid paint buffer associated with this layer";
+}
+
+/*!
+ If the layer mode (\ref setMode) is set to \ref lmBuffered, this method allows replotting only
+ the layerables on this specific layer, without the need to replot all other layers (as a call to
+ \ref QCustomPlot::replot would do).
+
+ If the layer mode is \ref lmLogical however, this method simply calls \ref QCustomPlot::replot on
+ the parent QCustomPlot instance.
+
+ QCustomPlot also makes sure to replot all layers instead of only this one, if the layer ordering
+ has changed since the last full replot and the other paint buffers were thus invalidated.
+
+ \see draw
+*/
+void QCPLayer::replot()
+{
+ if (mMode == lmBuffered && !mParentPlot->hasInvalidatedPaintBuffers())
+ {
+ if (!mPaintBuffer.isNull())
+ {
+ mPaintBuffer.data()->clear(Qt::transparent);
+ drawToPaintBuffer();
+ mPaintBuffer.data()->setInvalidated(false);
+ mParentPlot->update();
+ } else
+ qDebug() << Q_FUNC_INFO << "no valid paint buffer associated with this layer";
+ } else if (mMode == lmLogical)
+ mParentPlot->replot();
+}
+
/*! \internal
Adds the \a layerable to the list of this layer. If \a prepend is set to true, the layerable will
@@ -792,6 +1203,8 @@ void QCPLayer::addChild(QCPLayerable *layerable, bool prepend)
mChildren.prepend(layerable);
else
mChildren.append(layerable);
+ if (!mPaintBuffer.isNull())
+ mPaintBuffer.data()->setInvalidated();
} else
qDebug() << Q_FUNC_INFO << "layerable is already child of this layer" << reinterpret_cast<quintptr>(layerable);
}
@@ -807,7 +1220,11 @@ void QCPLayer::addChild(QCPLayerable *layerable, bool prepend)
*/
void QCPLayer::removeChild(QCPLayerable *layerable)
{
- if (!mChildren.removeOne(layerable))
+ if (mChildren.removeOne(layerable))
+ {
+ if (!mPaintBuffer.isNull())
+ mPaintBuffer.data()->setInvalidated();
+ } else
qDebug() << Q_FUNC_INFO << "layerable is not child of this layer" << reinterpret_cast<quintptr>(layerable);
}
@@ -839,7 +1256,7 @@ void QCPLayer::removeChild(QCPLayerable *layerable)
Note that a parent layerable is not necessarily also the QObject parent for memory management.
Further, a layerable doesn't always have a parent layerable, so this function may return 0.
- A parent layerable is set implicitly with when placed inside layout elements and doesn't need to be
+ A parent layerable is set implicitly when placed inside layout elements and doesn't need to be
set manually by the user.
*/
@@ -858,9 +1275,9 @@ void QCPLayer::removeChild(QCPLayerable *layerable)
default antialiasing hint.
<b>First example:</b> QCPGraph has multiple entities that have an antialiasing setting: The graph
- line, fills, scatters and error bars. Those can be configured via QCPGraph::setAntialiased,
- QCPGraph::setAntialiasedFill, QCPGraph::setAntialiasedScatters etc. Consequently, there isn't
- only the QCPGraph::applyDefaultAntialiasingHint function (which corresponds to the graph line's
+ line, fills and scatters. Those can be configured via QCPGraph::setAntialiased,
+ QCPGraph::setAntialiasedFill and QCPGraph::setAntialiasedScatters. Consequently, there isn't only
+ the QCPGraph::applyDefaultAntialiasingHint function (which corresponds to the graph line's
antialiasing), but specialized ones like QCPGraph::applyFillAntialiasingHint and
QCPGraph::applyScattersAntialiasingHint. So before drawing one of those entities, QCPGraph::draw
calls the respective specialized applyAntialiasingHint function.
@@ -912,10 +1329,12 @@ void QCPLayer::removeChild(QCPLayerable *layerable)
It is possible to provide 0 as \a plot. In that case, you should assign a parent plot at a later
time with \ref initializeParentPlot.
- The layerable's parent layerable is set to \a parentLayerable, if provided. Direct layerable parents
- are mainly used to control visibility in a hierarchy of layerables. This means a layerable is
- only drawn, if all its ancestor layerables are also visible. Note that \a parentLayerable does
- not become the QObject-parent (for memory management) of this layerable, \a plot does.
+ The layerable's parent layerable is set to \a parentLayerable, if provided. Direct layerable
+ parents are mainly used to control visibility in a hierarchy of layerables. This means a
+ layerable is only drawn, if all its ancestor layerables are also visible. Note that \a
+ parentLayerable does not become the QObject-parent (for memory management) of this layerable, \a
+ plot does. It is not uncommon to set the QObject-parent to something else in the constructors of
+ QCPLayerable subclasses, to guarantee a working destruction hierarchy.
*/
QCPLayerable::QCPLayerable(QCustomPlot *plot, QString targetLayer, QCPLayerable *parentLayerable) :
QObject(plot),
@@ -957,7 +1376,10 @@ void QCPLayerable::setVisible(bool on)
Sets the \a layer of this layerable object. The object will be placed on top of the other objects
already on \a layer.
- Returns true on success, i.e. if \a layer is a valid layer.
+ If \a layer is 0, this layerable will not be on any layer and thus not appear in the plot (or
+ interact/receive events).
+
+ Returns true if the layer of this layerable was successfully changed to \a layer.
*/
bool QCPLayerable::setLayer(QCPLayer *layer)
{
@@ -999,16 +1421,13 @@ void QCPLayerable::setAntialiased(bool enabled)
/*!
Returns whether this layerable is visible, taking the visibility of the layerable parent and the
- visibility of the layer this layerable is on into account. This is the method that is consulted
- to decide whether a layerable shall be drawn or not.
+ visibility of this layerable's layer into account. This is the method that is consulted to decide
+ whether a layerable shall be drawn or not.
If this layerable has a direct layerable parent (usually set via hierarchies implemented in
- subclasses, like in the case of QCPLayoutElement), this function returns true only if this
+ subclasses, like in the case of \ref QCPLayoutElement), this function returns true only if this
layerable has its visibility set to true and the parent layerable's \ref realVisibility returns
true.
-
- If this layerable doesn't have a direct layerable parent, returns the state of this layerable's
- visibility.
*/
bool QCPLayerable::realVisibility() const
{
@@ -1034,7 +1453,7 @@ bool QCPLayerable::realVisibility() const
The actual setting of the selection state is not done by this function. This is handled by the
parent QCustomPlot when the mouseReleaseEvent occurs, and the finally selected object is notified
- via the selectEvent/deselectEvent methods.
+ via the \ref selectEvent/\ref deselectEvent methods.
\a details is an optional output parameter. Every layerable subclass may place any information
in \a details. This information will be passed to \ref selectEvent when the parent QCustomPlot
@@ -1047,7 +1466,7 @@ bool QCPLayerable::realVisibility() const
You may pass 0 as \a details to indicate that you are not interested in those selection details.
- \see selectEvent, deselectEvent, QCustomPlot::setInteractions
+ \see selectEvent, deselectEvent, mousePressEvent, wheelEvent, QCustomPlot::setInteractions
*/
double QCPLayerable::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
@@ -1261,6 +1680,131 @@ void QCPLayerable::deselectEvent(bool *selectionStateChanged)
Q_UNUSED(selectionStateChanged)
}
+/*!
+ This event gets called when the user presses a mouse button while the cursor is over the
+ layerable. Whether a cursor is over the layerable is decided by a preceding call to \ref
+ selectTest.
+
+ The current pixel position of the cursor on the QCustomPlot widget is accessible via \c
+ event->pos(). The parameter \a details contains layerable-specific details about the hit, which
+ were generated in the previous call to \ref selectTest. For example, One-dimensional plottables
+ like \ref QCPGraph or \ref QCPBars convey the clicked data point in the \a details parameter, as
+ \ref QCPDataSelection packed as QVariant. Multi-part objects convey the specific \c
+ SelectablePart that was hit (e.g. \ref QCPAxis::SelectablePart in the case of axes).
+
+ QCustomPlot uses an event propagation system that works the same as Qt's system. If your
+ layerable doesn't reimplement the \ref mousePressEvent or explicitly calls \c event->ignore() in
+ its reimplementation, the event will be propagated to the next layerable in the stacking order.
+
+ Once a layerable has accepted the \ref mousePressEvent, it is considered the mouse grabber and
+ will receive all following calls to \ref mouseMoveEvent or \ref mouseReleaseEvent for this mouse
+ interaction (a "mouse interaction" in this context ends with the release).
+
+ The default implementation does nothing except explicitly ignoring the event with \c
+ event->ignore().
+
+ \see mouseMoveEvent, mouseReleaseEvent, mouseDoubleClickEvent, wheelEvent
+*/
+void QCPLayerable::mousePressEvent(QMouseEvent *event, const QVariant &details)
+{
+ Q_UNUSED(details)
+ event->ignore();
+}
+
+/*!
+ This event gets called when the user moves the mouse while holding a mouse button, after this
+ layerable has become the mouse grabber by accepting the preceding \ref mousePressEvent.
+
+ The current pixel position of the cursor on the QCustomPlot widget is accessible via \c
+ event->pos(). The parameter \a startPos indicates the position where the initial \ref
+ mousePressEvent occured, that started the mouse interaction.
+
+ The default implementation does nothing.
+
+ \see mousePressEvent, mouseReleaseEvent, mouseDoubleClickEvent, wheelEvent
+*/
+void QCPLayerable::mouseMoveEvent(QMouseEvent *event, const QPointF &startPos)
+{
+ Q_UNUSED(startPos)
+ event->ignore();
+}
+
+/*!
+ This event gets called when the user releases the mouse button, after this layerable has become
+ the mouse grabber by accepting the preceding \ref mousePressEvent.
+
+ The current pixel position of the cursor on the QCustomPlot widget is accessible via \c
+ event->pos(). The parameter \a startPos indicates the position where the initial \ref
+ mousePressEvent occured, that started the mouse interaction.
+
+ The default implementation does nothing.
+
+ \see mousePressEvent, mouseMoveEvent, mouseDoubleClickEvent, wheelEvent
+*/
+void QCPLayerable::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos)
+{
+ Q_UNUSED(startPos)
+ event->ignore();
+}
+
+/*!
+ This event gets called when the user presses the mouse button a second time in a double-click,
+ while the cursor is over the layerable. Whether a cursor is over the layerable is decided by a
+ preceding call to \ref selectTest.
+
+ The \ref mouseDoubleClickEvent is called instead of the second \ref mousePressEvent. So in the
+ case of a double-click, the event succession is
+ <i>pressEvent &ndash; releaseEvent &ndash; doubleClickEvent &ndash; releaseEvent</i>.
+
+ The current pixel position of the cursor on the QCustomPlot widget is accessible via \c
+ event->pos(). The parameter \a details contains layerable-specific details about the hit, which
+ were generated in the previous call to \ref selectTest. For example, One-dimensional plottables
+ like \ref QCPGraph or \ref QCPBars convey the clicked data point in the \a details parameter, as
+ \ref QCPDataSelection packed as QVariant. Multi-part objects convey the specific \c
+ SelectablePart that was hit (e.g. \ref QCPAxis::SelectablePart in the case of axes).
+
+ Similarly to \ref mousePressEvent, once a layerable has accepted the \ref mouseDoubleClickEvent,
+ it is considered the mouse grabber and will receive all following calls to \ref mouseMoveEvent
+ and \ref mouseReleaseEvent for this mouse interaction (a "mouse interaction" in this context ends
+ with the release).
+
+ The default implementation does nothing except explicitly ignoring the event with \c
+ event->ignore().
+
+ \see mousePressEvent, mouseMoveEvent, mouseReleaseEvent, wheelEvent
+*/
+void QCPLayerable::mouseDoubleClickEvent(QMouseEvent *event, const QVariant &details)
+{
+ Q_UNUSED(details)
+ event->ignore();
+}
+
+/*!
+ This event gets called when the user turns the mouse scroll wheel while the cursor is over the
+ layerable. Whether a cursor is over the layerable is decided by a preceding call to \ref
+ selectTest.
+
+ The current pixel position of the cursor on the QCustomPlot widget is accessible via \c
+ event->pos().
+
+ The \c event->delta() indicates how far the mouse wheel was turned, which is usually +/- 120 for
+ single rotation steps. However, if the mouse wheel is turned rapidly, multiple steps may
+ accumulate to one event, making \c event->delta() larger. On the other hand, if the wheel has
+ very smooth steps or none at all, the delta may be smaller.
+
+ The default implementation does nothing.
+
+ \see mousePressEvent, mouseMoveEvent, mouseReleaseEvent, mouseDoubleClickEvent
+*/
+void QCPLayerable::wheelEvent(QWheelEvent *event)
+{
+ event->ignore();
+}
+/* end of 'src/layer.cpp' */
+
+
+/* including file 'src/axis/range.cpp', size 12221 */
+/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPRange
@@ -1274,10 +1818,60 @@ void QCPLayerable::deselectEvent(bool *selectionStateChanged)
\see QCPAxis::setRange
*/
+/* start of documentation of inline functions */
+
+/*! \fn double QCPRange::size() const
+
+ Returns the size of the range, i.e. \a upper-\a lower
+*/
+
+/*! \fn double QCPRange::center() const
+
+ Returns the center of the range, i.e. (\a upper+\a lower)*0.5
+*/
+
+/*! \fn void QCPRange::normalize()
+
+ Makes sure \a lower is numerically smaller than \a upper. If this is not the case, the values are
+ swapped.
+*/
+
+/*! \fn bool QCPRange::contains(double value) const
+
+ Returns true when \a value lies within or exactly on the borders of the range.
+*/
+
+/*! \fn QCPRange &QCPRange::operator+=(const double& value)
+
+ Adds \a value to both boundaries of the range.
+*/
+
+/*! \fn QCPRange &QCPRange::operator-=(const double& value)
+
+ Subtracts \a value from both boundaries of the range.
+*/
+
+/*! \fn QCPRange &QCPRange::operator*=(const double& value)
+
+ Multiplies both boundaries of the range by \a value.
+*/
+
+/*! \fn QCPRange &QCPRange::operator/=(const double& value)
+
+ Divides both boundaries of the range by \a value.
+*/
+
+/* end of documentation of inline functions */
+
/*!
Minimum range size (\a upper - \a lower) the range changing functions will accept. Smaller
intervals would cause errors due to the 11-bit exponent of double precision numbers,
corresponding to a minimum magnitude of roughly 1e-308.
+
+ \warning Do not use this constant to indicate "arbitrarily small" values in plotting logic (as
+ values that will appear in the plot)! It is intended only as a bound to compare against, e.g. to
+ prevent axis ranges from obtaining underflowing ranges.
+
\see validRange, maxRange
*/
const double QCPRange::minRange = 1e-280;
@@ -1286,8 +1880,11 @@ const double QCPRange::minRange = 1e-280;
Maximum values (negative and positive) the range will accept in range-changing functions.
Larger absolute values would cause errors due to the 11-bit exponent of double precision numbers,
corresponding to a maximum magnitude of roughly 1e308.
- Since the number of planck-volumes in the entire visible universe is only ~1e183, this should
- be enough.
+
+ \warning Do not use this constant to indicate "arbitrarily large" values in plotting logic (as
+ values that will appear in the plot)! It is intended only as a bound to compare against, e.g. to
+ prevent axis ranges from obtaining overflowing ranges.
+
\see validRange, minRange
*/
const double QCPRange::maxRange = 1e250;
@@ -1302,7 +1899,11 @@ QCPRange::QCPRange() :
}
/*! \overload
+
Constructs a range with the specified \a lower and \a upper values.
+
+ The resulting range will be normalized (see \ref normalize), so if \a lower is not numerically
+ smaller than \a upper, they will be swapped.
*/
QCPRange::QCPRange(double lower, double upper) :
lower(lower),
@@ -1311,53 +1912,55 @@ QCPRange::QCPRange(double lower, double upper) :
normalize();
}
-/*!
- Returns the size of the range, i.e. \a upper-\a lower
-*/
-double QCPRange::size() const
-{
- return upper-lower;
-}
-
-/*!
- Returns the center of the range, i.e. (\a upper+\a lower)*0.5
-*/
-double QCPRange::center() const
-{
- return (upper+lower)*0.5;
-}
-
-/*!
- Makes sure \a lower is numerically smaller than \a upper. If this is not the case, the values
- are swapped.
-*/
-void QCPRange::normalize()
-{
- if (lower > upper)
- qSwap(lower, upper);
-}
+/*! \overload
-/*!
Expands this range such that \a otherRange is contained in the new range. It is assumed that both
this range and \a otherRange are normalized (see \ref normalize).
-
+
+ If this range contains NaN as lower or upper bound, it will be replaced by the respective bound
+ of \a otherRange.
+
If \a otherRange is already inside the current range, this function does nothing.
-
+
\see expanded
*/
void QCPRange::expand(const QCPRange &otherRange)
{
- if (lower > otherRange.lower)
+ if (lower > otherRange.lower || qIsNaN(lower))
lower = otherRange.lower;
- if (upper < otherRange.upper)
+ if (upper < otherRange.upper || qIsNaN(upper))
upper = otherRange.upper;
}
+/*! \overload
+
+ Expands this range such that \a includeCoord is contained in the new range. It is assumed that
+ this range is normalized (see \ref normalize).
+
+ If this range contains NaN as lower or upper bound, the respective bound will be set to \a
+ includeCoord.
+
+ If \a includeCoord is already inside the current range, this function does nothing.
+
+ \see expand
+*/
+void QCPRange::expand(double includeCoord)
+{
+ if (lower > includeCoord || qIsNaN(lower))
+ lower = includeCoord;
+ if (upper < includeCoord || qIsNaN(upper))
+ upper = includeCoord;
+}
+
+
+/*! \overload
-/*!
Returns an expanded range that contains this and \a otherRange. It is assumed that both this
range and \a otherRange are normalized (see \ref normalize).
-
+
+ If this range contains NaN as lower or upper bound, the returned range's bound will be taken from
+ \a otherRange.
+
\see expand
*/
QCPRange QCPRange::expanded(const QCPRange &otherRange) const
@@ -1367,6 +1970,54 @@ QCPRange QCPRange::expanded(const QCPRange &otherRange) const
return result;
}
+/*! \overload
+
+ Returns an expanded range that includes the specified \a includeCoord. It is assumed that this
+ range is normalized (see \ref normalize).
+
+ If this range contains NaN as lower or upper bound, the returned range's bound will be set to \a
+ includeCoord.
+
+ \see expand
+*/
+QCPRange QCPRange::expanded(double includeCoord) const
+{
+ QCPRange result = *this;
+ result.expand(includeCoord);
+ return result;
+}
+
+/*!
+ Returns this range, possibly modified to not exceed the bounds provided as \a lowerBound and \a
+ upperBound. If possible, the size of the current range is preserved in the process.
+
+ If the range shall only be bounded at the lower side, you can set \a upperBound to \ref
+ QCPRange::maxRange. If it shall only be bounded at the upper side, set \a lowerBound to -\ref
+ QCPRange::maxRange.
+*/
+QCPRange QCPRange::bounded(double lowerBound, double upperBound) const
+{
+ if (lowerBound > upperBound)
+ qSwap(lowerBound, upperBound);
+
+ QCPRange result(lower, upper);
+ if (result.lower < lowerBound)
+ {
+ result.lower = lowerBound;
+ result.upper = lowerBound + size();
+ if (result.upper > upperBound || qFuzzyCompare(size(), upperBound-lowerBound))
+ result.upper = upperBound;
+ } else if (result.upper > upperBound)
+ {
+ result.upper = upperBound;
+ result.lower = upperBound - size();
+ if (result.lower < lowerBound || qFuzzyCompare(size(), upperBound-lowerBound))
+ result.lower = lowerBound;
+ }
+
+ return result;
+}
+
/*!
Returns a sanitized version of the range. Sanitized means for logarithmic scales, that
the range won't span the positive and negative sign domain, i.e. contain zero. Further
@@ -1436,14 +2087,6 @@ QCPRange QCPRange::sanitizedForLinScale() const
}
/*!
- Returns true when \a value lies within or exactly on the borders of the range.
-*/
-bool QCPRange::contains(double value) const
-{
- return value >= lower && value <= upper;
-}
-
-/*!
Checks, whether the specified range is within valid bounds, which are defined
as QCPRange::maxRange and QCPRange::minRange.
A valid range means:
@@ -1453,17 +2096,12 @@ bool QCPRange::contains(double value) const
*/
bool QCPRange::validRange(double lower, double upper)
{
- /*
- return (lower > -maxRange &&
- upper < maxRange &&
- qAbs(lower-upper) > minRange &&
- (lower < -minRange || lower > minRange) &&
- (upper < -minRange || upper > minRange));
- */
return (lower > -maxRange &&
upper < maxRange &&
qAbs(lower-upper) > minRange &&
- qAbs(lower-upper) < maxRange);
+ qAbs(lower-upper) < maxRange &&
+ !(lower > 0 && qIsInf(upper/lower)) &&
+ !(upper < 0 && qIsInf(lower/upper)));
}
/*!
@@ -1477,20 +2115,847 @@ bool QCPRange::validRange(double lower, double upper)
*/
bool QCPRange::validRange(const QCPRange &range)
{
- /*
return (range.lower > -maxRange &&
range.upper < maxRange &&
qAbs(range.lower-range.upper) > minRange &&
qAbs(range.lower-range.upper) < maxRange &&
- (range.lower < -minRange || range.lower > minRange) &&
- (range.upper < -minRange || range.upper > minRange));
- */
- return (range.lower > -maxRange &&
- range.upper < maxRange &&
- qAbs(range.lower-range.upper) > minRange &&
- qAbs(range.lower-range.upper) < maxRange);
+ !(range.lower > 0 && qIsInf(range.upper/range.lower)) &&
+ !(range.upper < 0 && qIsInf(range.lower/range.upper)));
+}
+/* end of 'src/axis/range.cpp' */
+
+
+/* including file 'src/selection.cpp', size 21898 */
+/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
+
+////////////////////////////////////////////////////////////////////////////////////////////////////
+//////////////////// QCPDataRange
+////////////////////////////////////////////////////////////////////////////////////////////////////
+
+/*! \class QCPDataRange
+ \brief Describes a data range given by begin and end index
+
+ QCPDataRange holds two integers describing the begin (\ref setBegin) and end (\ref setEnd) index
+ of a contiguous set of data points. The end index points to the data point above the last data point that's part of
+ the data range, similarly to the nomenclature used in standard iterators.
+
+ Data Ranges are not bound to a certain plottable, thus they can be freely exchanged, created and
+ modified. If a non-contiguous data set shall be described, the class \ref QCPDataSelection is
+ used, which holds and manages multiple instances of \ref QCPDataRange. In most situations, \ref
+ QCPDataSelection is thus used.
+
+ Both \ref QCPDataRange and \ref QCPDataSelection offer convenience methods to work with them,
+ e.g. \ref bounded, \ref expanded, \ref intersects, \ref intersection, \ref adjusted, \ref
+ contains. Further, addition and subtraction operators (defined in \ref QCPDataSelection) can be
+ used to join/subtract data ranges and data selections (or mixtures), to retrieve a corresponding
+ \ref QCPDataSelection.
+
+ %QCustomPlot's \ref dataselection "data selection mechanism" is based on \ref QCPDataSelection and
+ QCPDataRange.
+
+ \note Do not confuse \ref QCPDataRange with \ref QCPRange. A \ref QCPRange describes an interval
+ in floating point plot coordinates, e.g. the current axis range.
+*/
+
+/* start documentation of inline functions */
+
+/*! \fn int QCPDataRange::size() const
+
+ Returns the number of data points described by this data range. This is equal to the end index
+ minus the begin index.
+
+ \see length
+*/
+
+/*! \fn int QCPDataRange::length() const
+
+ Returns the number of data points described by this data range. Equivalent to \ref size.
+*/
+
+/*! \fn void QCPDataRange::setBegin(int begin)
+
+ Sets the begin of this data range. The \a begin index points to the first data point that is part
+ of the data range.
+
+ No checks or corrections are made to ensure the resulting range is valid (\ref isValid).
+
+ \see setEnd
+*/
+
+/*! \fn void QCPDataRange::setEnd(int end)
+
+ Sets the end of this data range. The \a end index points to the data point just above the last
+ data point that is part of the data range.
+
+ No checks or corrections are made to ensure the resulting range is valid (\ref isValid).
+
+ \see setBegin
+*/
+
+/*! \fn bool QCPDataRange::isValid() const
+
+ Returns whether this range is valid. A valid range has a begin index greater or equal to 0, and
+ an end index greater or equal to the begin index.
+
+ \note Invalid ranges should be avoided and are never the result of any of QCustomPlot's methods
+ (unless they are themselves fed with invalid ranges). Do not pass invalid ranges to QCustomPlot's
+ methods. The invalid range is not inherently prevented in QCPDataRange, to allow temporary
+ invalid begin/end values while manipulating the range. An invalid range is not necessarily empty
+ (\ref isEmpty), since its \ref length can be negative and thus non-zero.
+*/
+
+/*! \fn bool QCPDataRange::isEmpty() const
+
+ Returns whether this range is empty, i.e. whether its begin index equals its end index.
+
+ \see size, length
+*/
+
+/*! \fn QCPDataRange QCPDataRange::adjusted(int changeBegin, int changeEnd) const
+
+ Returns a data range where \a changeBegin and \a changeEnd were added to the begin and end
+ indices, respectively.
+*/
+
+/* end documentation of inline functions */
+
+/*!
+ Creates an empty QCPDataRange, with begin and end set to 0.
+*/
+QCPDataRange::QCPDataRange() :
+ mBegin(0),
+ mEnd(0)
+{
}
+/*!
+ Creates a QCPDataRange, initialized with the specified \a begin and \a end.
+
+ No checks or corrections are made to ensure the resulting range is valid (\ref isValid).
+*/
+QCPDataRange::QCPDataRange(int begin, int end) :
+ mBegin(begin),
+ mEnd(end)
+{
+}
+
+/*!
+ Returns a data range that matches this data range, except that parts exceeding \a other are
+ excluded.
+
+ This method is very similar to \ref intersection, with one distinction: If this range and the \a
+ other range share no intersection, the returned data range will be empty with begin and end set
+ to the respective boundary side of \a other, at which this range is residing. (\ref intersection
+ would just return a range with begin and end set to 0.)
+*/
+QCPDataRange QCPDataRange::bounded(const QCPDataRange &other) const
+{
+ QCPDataRange result(intersection(other));
+ if (result.isEmpty()) // no intersection, preserve respective bounding side of otherRange as both begin and end of return value
+ {
+ if (mEnd <= other.mBegin)
+ result = QCPDataRange(other.mBegin, other.mBegin);
+ else
+ result = QCPDataRange(other.mEnd, other.mEnd);
+ }
+ return result;
+}
+
+/*!
+ Returns a data range that contains both this data range as well as \a other.
+*/
+QCPDataRange QCPDataRange::expanded(const QCPDataRange &other) const
+{
+ return QCPDataRange(qMin(mBegin, other.mBegin), qMax(mEnd, other.mEnd));
+}
+
+/*!
+ Returns the data range which is contained in both this data range and \a other.
+
+ This method is very similar to \ref bounded, with one distinction: If this range and the \a other
+ range share no intersection, the returned data range will be empty with begin and end set to 0.
+ (\ref bounded would return a range with begin and end set to one of the boundaries of \a other,
+ depending on which side this range is on.)
+
+ \see QCPDataSelection::intersection
+*/
+QCPDataRange QCPDataRange::intersection(const QCPDataRange &other) const
+{
+ QCPDataRange result(qMax(mBegin, other.mBegin), qMin(mEnd, other.mEnd));
+ if (result.isValid())
+ return result;
+ else
+ return QCPDataRange();
+}
+
+/*!
+ Returns whether this data range and \a other share common data points.
+
+ \see intersection, contains
+*/
+bool QCPDataRange::intersects(const QCPDataRange &other) const
+{
+ return !( (mBegin > other.mBegin && mBegin >= other.mEnd) ||
+ (mEnd <= other.mBegin && mEnd < other.mEnd) );
+}
+
+/*!
+ Returns whether all data points described by this data range are also in \a other.
+
+ \see intersects
+*/
+bool QCPDataRange::contains(const QCPDataRange &other) const
+{
+ return mBegin <= other.mBegin && mEnd >= other.mEnd;
+}
+
+
+
+////////////////////////////////////////////////////////////////////////////////////////////////////
+//////////////////// QCPDataSelection
+////////////////////////////////////////////////////////////////////////////////////////////////////
+
+/*! \class QCPDataSelection
+ \brief Describes a data set by holding multiple QCPDataRange instances
+
+ QCPDataSelection manages multiple instances of QCPDataRange in order to represent any (possibly
+ disjoint) set of data selection.
+
+ The data selection can be modified with addition and subtraction operators which take
+ QCPDataSelection and QCPDataRange instances, as well as methods such as \ref addDataRange and
+ \ref clear. Read access is provided by \ref dataRange, \ref dataRanges, \ref dataRangeCount, etc.
+
+ The method \ref simplify is used to join directly adjacent or even overlapping QCPDataRange
+ instances. QCPDataSelection automatically simplifies when using the addition/subtraction
+ operators. The only case when \ref simplify is left to the user, is when calling \ref
+ addDataRange, with the parameter \a simplify explicitly set to false. This is useful if many data
+ ranges will be added to the selection successively and the overhead for simplifying after each
+ iteration shall be avoided. In this case, you should make sure to call \ref simplify after
+ completing the operation.
+
+ Use \ref enforceType to bring the data selection into a state complying with the constraints for
+ selections defined in \ref QCP::SelectionType.
+
+ %QCustomPlot's \ref dataselection "data selection mechanism" is based on QCPDataSelection and
+ QCPDataRange.
+
+ \section qcpdataselection-iterating Iterating over a data selection
+
+ As an example, the following code snippet calculates the average value of a graph's data
+ \ref QCPAbstractPlottable::selection "selection":
+
+ \snippet documentation/doc-code-snippets/mainwindow.cpp qcpdataselection-iterating-1
+
+*/
+
+/* start documentation of inline functions */
+
+/*! \fn int QCPDataSelection::dataRangeCount() const
+
+ Returns the number of ranges that make up the data selection. The ranges can be accessed by \ref
+ dataRange via their index.
+
+ \see dataRange, dataPointCount
+*/
+
+/*! \fn QList<QCPDataRange> QCPDataSelection::dataRanges() const
+
+ Returns all data ranges that make up the data selection. If the data selection is simplified (the
+ usual state of the selection, see \ref simplify), the ranges are sorted by ascending data point
+ index.
+
+ \see dataRange
+*/
+
+/*! \fn bool QCPDataSelection::isEmpty() const
+
+ Returns true if there are no data ranges, and thus no data points, in this QCPDataSelection
+ instance.
+
+ \see dataRangeCount
+*/
+
+/* end documentation of inline functions */
+
+/*!
+ Creates an empty QCPDataSelection.
+*/
+QCPDataSelection::QCPDataSelection()
+{
+}
+
+/*!
+ Creates a QCPDataSelection containing the provided \a range.
+*/
+QCPDataSelection::QCPDataSelection(const QCPDataRange &range)
+{
+ mDataRanges.append(range);
+}
+
+/*!
+ Returns true if this selection is identical (contains the same data ranges with the same begin
+ and end indices) to \a other.
+
+ Note that both data selections must be in simplified state (the usual state of the selection, see
+ \ref simplify) for this operator to return correct results.
+*/
+bool QCPDataSelection::operator==(const QCPDataSelection &other) const
+{
+ if (mDataRanges.size() != other.mDataRanges.size())
+ return false;
+ for (int i=0; i<mDataRanges.size(); ++i)
+ {
+ if (mDataRanges.at(i) != other.mDataRanges.at(i))
+ return false;
+ }
+ return true;
+}
+
+/*!
+ Adds the data selection of \a other to this data selection, and then simplifies this data
+ selection (see \ref simplify).
+*/
+QCPDataSelection &QCPDataSelection::operator+=(const QCPDataSelection &other)
+{
+ mDataRanges << other.mDataRanges;
+ simplify();
+ return *this;
+}
+
+/*!
+ Adds the data range \a other to this data selection, and then simplifies this data selection (see
+ \ref simplify).
+*/
+QCPDataSelection &QCPDataSelection::operator+=(const QCPDataRange &other)
+{
+ addDataRange(other);
+ return *this;
+}
+
+/*!
+ Removes all data point indices that are described by \a other from this data range.
+*/
+QCPDataSelection &QCPDataSelection::operator-=(const QCPDataSelection &other)
+{
+ for (int i=0; i<other.dataRangeCount(); ++i)
+ *this -= other.dataRange(i);
+
+ return *this;
+}
+
+/*!
+ Removes all data point indices that are described by \a other from this data range.
+*/
+QCPDataSelection &QCPDataSelection::operator-=(const QCPDataRange &other)
+{
+ if (other.isEmpty() || isEmpty())
+ return *this;
+
+ simplify();
+ int i=0;
+ while (i < mDataRanges.size())
+ {
+ const int thisBegin = mDataRanges.at(i).begin();
+ const int thisEnd = mDataRanges.at(i).end();
+ if (thisBegin >= other.end())
+ break; // since data ranges are sorted after the simplify() call, no ranges which contain other will come after this
+
+ if (thisEnd > other.begin()) // ranges which don't fulfill this are entirely before other and can be ignored
+ {
+ if (thisBegin >= other.begin()) // range leading segment is encompassed
+ {
+ if (thisEnd <= other.end()) // range fully encompassed, remove completely
+ {
+ mDataRanges.removeAt(i);
+ continue;
+ } else // only leading segment is encompassed, trim accordingly
+ mDataRanges[i].setBegin(other.end());
+ } else // leading segment is not encompassed
+ {
+ if (thisEnd <= other.end()) // only trailing segment is encompassed, trim accordingly
+ {
+ mDataRanges[i].setEnd(other.begin());
+ } else // other lies inside this range, so split range
+ {
+ mDataRanges[i].setEnd(other.begin());
+ mDataRanges.insert(i+1, QCPDataRange(other.end(), thisEnd));
+ break; // since data ranges are sorted (and don't overlap) after simplify() call, we're done here
+ }
+ }
+ }
+ ++i;
+ }
+
+ return *this;
+}
+
+/*!
+ Returns the total number of data points contained in all data ranges that make up this data
+ selection.
+*/
+int QCPDataSelection::dataPointCount() const
+{
+ int result = 0;
+ for (int i=0; i<mDataRanges.size(); ++i)
+ result += mDataRanges.at(i).length();
+ return result;
+}
+
+/*!
+ Returns the data range with the specified \a index.
+
+ If the data selection is simplified (the usual state of the selection, see \ref simplify), the
+ ranges are sorted by ascending data point index.
+
+ \see dataRangeCount
+*/
+QCPDataRange QCPDataSelection::dataRange(int index) const
+{
+ if (index >= 0 && index < mDataRanges.size())
+ {
+ return mDataRanges.at(index);
+ } else
+ {
+ qDebug() << Q_FUNC_INFO << "index out of range:" << index;
+ return QCPDataRange();
+ }
+}
+
+/*!
+ Returns a \ref QCPDataRange which spans the entire data selection, including possible
+ intermediate segments which are not part of the original data selection.
+*/
+QCPDataRange QCPDataSelection::span() const
+{
+ if (isEmpty())
+ return QCPDataRange();
+ else
+ return QCPDataRange(mDataRanges.first().begin(), mDataRanges.last().end());
+}
+
+/*!
+ Adds the given \a dataRange to this data selection. This is equivalent to the += operator but
+ allows disabling immediate simplification by setting \a simplify to false. This can improve
+ performance if adding a very large amount of data ranges successively. In this case, make sure to
+ call \ref simplify manually, after the operation.
+*/
+void QCPDataSelection::addDataRange(const QCPDataRange &dataRange, bool simplify)
+{
+ mDataRanges.append(dataRange);
+ if (simplify)
+ this->simplify();
+}
+
+/*!
+ Removes all data ranges. The data selection then contains no data points.
+
+ \ref isEmpty
+*/
+void QCPDataSelection::clear()
+{
+ mDataRanges.clear();
+}
+
+/*!
+ Sorts all data ranges by range begin index in ascending order, and then joins directly adjacent
+ or overlapping ranges. This can reduce the number of individual data ranges in the selection, and
+ prevents possible double-counting when iterating over the data points held by the data ranges.
+
+ This method is automatically called when using the addition/subtraction operators. The only case
+ when \ref simplify is left to the user, is when calling \ref addDataRange, with the parameter \a
+ simplify explicitly set to false.
+*/
+void QCPDataSelection::simplify()
+{
+ // remove any empty ranges:
+ for (int i=mDataRanges.size()-1; i>=0; --i)
+ {
+ if (mDataRanges.at(i).isEmpty())
+ mDataRanges.removeAt(i);
+ }
+ if (mDataRanges.isEmpty())
+ return;
+
+ // sort ranges by starting value, ascending:
+ std::sort(mDataRanges.begin(), mDataRanges.end(), lessThanDataRangeBegin);
+
+ // join overlapping/contiguous ranges:
+ int i = 1;
+ while (i < mDataRanges.size())
+ {
+ 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
+ {
+ mDataRanges[i-1].setEnd(qMax(mDataRanges.at(i-1).end(), mDataRanges.at(i).end()));
+ mDataRanges.removeAt(i);
+ } else
+ ++i;
+ }
+}
+
+/*!
+ Makes sure this data selection conforms to the specified \a type selection type. Before the type
+ is enforced, \ref simplify is called.
+
+ Depending on \a type, enforcing means adding new data points that were previously not part of the
+ selection, or removing data points from the selection. If the current selection already conforms
+ to \a type, the data selection is not changed.
+
+ \see QCP::SelectionType
+*/
+void QCPDataSelection::enforceType(QCP::SelectionType type)
+{
+ simplify();
+ switch (type)
+ {
+ case QCP::stNone:
+ {
+ mDataRanges.clear();
+ break;
+ }
+ case QCP::stWhole:
+ {
+ // whole selection isn't defined by data range, so don't change anything (is handled in plottable methods)
+ break;
+ }
+ case QCP::stSingleData:
+ {
+ // reduce all data ranges to the single first data point:
+ if (!mDataRanges.isEmpty())
+ {
+ if (mDataRanges.size() > 1)
+ mDataRanges = QList<QCPDataRange>() << mDataRanges.first();
+ if (mDataRanges.first().length() > 1)
+ mDataRanges.first().setEnd(mDataRanges.first().begin()+1);
+ }
+ break;
+ }
+ case QCP::stDataRange:
+ {
+ mDataRanges = QList<QCPDataRange>() << span();
+ break;
+ }
+ case QCP::stMultipleDataRanges:
+ {
+ // this is the selection type that allows all concievable combinations of ranges, so do nothing
+ break;
+ }
+ }
+}
+
+/*!
+ Returns true if the data selection \a other is contained entirely in this data selection, i.e.
+ all data point indices that are in \a other are also in this data selection.
+
+ \see QCPDataRange::contains
+*/
+bool QCPDataSelection::contains(const QCPDataSelection &other) const
+{
+ if (other.isEmpty()) return false;
+
+ int otherIndex = 0;
+ int thisIndex = 0;
+ while (thisIndex < mDataRanges.size() && otherIndex < other.mDataRanges.size())
+ {
+ if (mDataRanges.at(thisIndex).contains(other.mDataRanges.at(otherIndex)))
+ ++otherIndex;
+ else
+ ++thisIndex;
+ }
+ 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
+}
+
+/*!
+ Returns a data selection containing the points which are both in this data selection and in the
+ data range \a other.
+
+ A common use case is to limit an unknown data selection to the valid range of a data container,
+ using \ref QCPDataContainer::dataRange as \a other. One can then safely iterate over the returned
+ data selection without exceeding the data container's bounds.
+*/
+QCPDataSelection QCPDataSelection::intersection(const QCPDataRange &other) const
+{
+ QCPDataSelection result;
+ for (int i=0; i<mDataRanges.size(); ++i)
+ result.addDataRange(mDataRanges.at(i).intersection(other), false);
+ result.simplify();
+ return result;
+}
+
+/*!
+ Returns a data selection containing the points which are both in this data selection and in the
+ data selection \a other.
+*/
+QCPDataSelection QCPDataSelection::intersection(const QCPDataSelection &other) const
+{
+ QCPDataSelection result;
+ for (int i=0; i<other.dataRangeCount(); ++i)
+ result += intersection(other.dataRange(i));
+ result.simplify();
+ return result;
+}
+
+/*!
+ Returns a data selection which is the exact inverse of this data selection, with \a outerRange
+ defining the base range on which to invert. If \a outerRange is smaller than the \ref span of
+ this data selection, it is expanded accordingly.
+
+ For example, this method can be used to retrieve all unselected segments by setting \a outerRange
+ to the full data range of the plottable, and calling this method on a data selection holding the
+ selected segments.
+*/
+QCPDataSelection QCPDataSelection::inverse(const QCPDataRange &outerRange) const
+{
+ if (isEmpty())
+ return QCPDataSelection(outerRange);
+ QCPDataRange fullRange = outerRange.expanded(span());
+
+ QCPDataSelection result;
+ // first unselected segment:
+ if (mDataRanges.first().begin() != fullRange.begin())
+ result.addDataRange(QCPDataRange(fullRange.begin(), mDataRanges.first().begin()), false);
+ // intermediate unselected segments:
+ for (int i=1; i<mDataRanges.size(); ++i)
+ result.addDataRange(QCPDataRange(mDataRanges.at(i-1).end(), mDataRanges.at(i).begin()), false);
+ // last unselected segment:
+ if (mDataRanges.last().end() != fullRange.end())
+ result.addDataRange(QCPDataRange(mDataRanges.last().end(), fullRange.end()), false);
+ result.simplify();
+ return result;
+}
+/* end of 'src/selection.cpp' */
+
+
+/* including file 'src/selectionrect.cpp', size 9224 */
+/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
+
+////////////////////////////////////////////////////////////////////////////////////////////////////
+//////////////////// QCPSelectionRect
+////////////////////////////////////////////////////////////////////////////////////////////////////
+
+/*! \class QCPSelectionRect
+ \brief Provides rect/rubber-band data selection and range zoom interaction
+
+ QCPSelectionRect is used by QCustomPlot when the \ref QCustomPlot::setSelectionRectMode is not
+ \ref QCP::srmNone. When the user drags the mouse across the plot, the current selection rect
+ instance (\ref QCustomPlot::setSelectionRect) is forwarded these events and makes sure an
+ according rect shape is drawn. At the begin, during, and after completion of the interaction, it
+ emits the corresponding signals \ref started, \ref changed, \ref canceled, and \ref accepted.
+
+ The QCustomPlot instance connects own slots to the current selection rect instance, in order to
+ react to an accepted selection rect interaction accordingly.
+
+ \ref isActive can be used to check whether the selection rect is currently active. An ongoing
+ selection interaction can be cancelled programmatically via calling \ref cancel at any time.
+
+ The appearance of the selection rect can be controlled via \ref setPen and \ref setBrush.
+
+ If you wish to provide custom behaviour, e.g. a different visual representation of the selection
+ rect (\ref QCPSelectionRect::draw), you can subclass QCPSelectionRect and pass an instance of
+ your subclass to \ref QCustomPlot::setSelectionRect.
+*/
+
+/* start of documentation of inline functions */
+
+/*! \fn bool QCPSelectionRect::isActive() const
+
+ Returns true if there is currently a selection going on, i.e. the user has started dragging a
+ selection rect, but hasn't released the mouse button yet.
+
+ \see cancel
+*/
+
+/* end of documentation of inline functions */
+/* start documentation of signals */
+
+/*! \fn void QCPSelectionRect::started(QMouseEvent *event);
+
+ This signal is emitted when a selection rect interaction was initiated, i.e. the user just
+ started dragging the selection rect with the mouse.
+*/
+
+/*! \fn void QCPSelectionRect::changed(const QRect &rect, QMouseEvent *event);
+
+ This signal is emitted while the selection rect interaction is ongoing and the \a rect has
+ changed its size due to the user moving the mouse.
+
+ Note that \a rect may have a negative width or height, if the selection is being dragged to the
+ upper or left side of the selection rect origin.
+*/
+
+/*! \fn void QCPSelectionRect::canceled(const QRect &rect, QInputEvent *event);
+
+ This signal is emitted when the selection interaction was cancelled. Note that \a event is 0 if
+ the selection interaction was cancelled programmatically, by a call to \ref cancel.
+
+ The user may cancel the selection interaction by pressing the escape key. In this case, \a event
+ holds the respective input event.
+
+ Note that \a rect may have a negative width or height, if the selection is being dragged to the
+ upper or left side of the selection rect origin.
+*/
+
+/*! \fn void QCPSelectionRect::accepted(const QRect &rect, QMouseEvent *event);
+
+ This signal is emitted when the selection interaction was completed by the user releasing the
+ mouse button.
+
+ Note that \a rect may have a negative width or height, if the selection is being dragged to the
+ upper or left side of the selection rect origin.
+*/
+
+/* end documentation of signals */
+
+/*!
+ Creates a new QCPSelectionRect instance. To make QCustomPlot use the selection rect instance,
+ pass it to \ref QCustomPlot::setSelectionRect. \a parentPlot should be set to the same
+ QCustomPlot widget.
+*/
+QCPSelectionRect::QCPSelectionRect(QCustomPlot *parentPlot) :
+ QCPLayerable(parentPlot),
+ mPen(QBrush(Qt::gray), 0, Qt::DashLine),
+ mBrush(Qt::NoBrush),
+ mActive(false)
+{
+}
+
+QCPSelectionRect::~QCPSelectionRect()
+{
+ cancel();
+}
+
+/*!
+ A convenience function which returns the coordinate range of the provided \a axis, that this
+ selection rect currently encompasses.
+*/
+QCPRange QCPSelectionRect::range(const QCPAxis *axis) const
+{
+ if (axis)
+ {
+ if (axis->orientation() == Qt::Horizontal)
+ return QCPRange(axis->pixelToCoord(mRect.left()), axis->pixelToCoord(mRect.left()+mRect.width()));
+ else
+ return QCPRange(axis->pixelToCoord(mRect.top()+mRect.height()), axis->pixelToCoord(mRect.top()));
+ } else
+ {
+ qDebug() << Q_FUNC_INFO << "called with axis zero";
+ return QCPRange();
+ }
+}
+
+/*!
+ Sets the pen that will be used to draw the selection rect outline.
+
+ \see setBrush
+*/
+void QCPSelectionRect::setPen(const QPen &pen)
+{
+ mPen = pen;
+}
+
+/*!
+ Sets the brush that will be used to fill the selection rect. By default the selection rect is not
+ filled, i.e. \a brush is <tt>Qt::NoBrush</tt>.
+
+ \see setPen
+*/
+void QCPSelectionRect::setBrush(const QBrush &brush)
+{
+ mBrush = brush;
+}
+
+/*!
+ If there is currently a selection interaction going on (\ref isActive), the interaction is
+ canceled. The selection rect will emit the \ref canceled signal.
+*/
+void QCPSelectionRect::cancel()
+{
+ if (mActive)
+ {
+ mActive = false;
+ emit canceled(mRect, 0);
+ }
+}
+
+/*! \internal
+
+ This method is called by QCustomPlot to indicate that a selection rect interaction was initiated.
+ The default implementation sets the selection rect to active, initializes the selection rect
+ geometry and emits the \ref started signal.
+*/
+void QCPSelectionRect::startSelection(QMouseEvent *event)
+{
+ mActive = true;
+ mRect = QRect(event->pos(), event->pos());
+ emit started(event);
+}
+
+/*! \internal
+
+ This method is called by QCustomPlot to indicate that an ongoing selection rect interaction needs
+ to update its geometry. The default implementation updates the rect and emits the \ref changed
+ signal.
+*/
+void QCPSelectionRect::moveSelection(QMouseEvent *event)
+{
+ mRect.setBottomRight(event->pos());
+ emit changed(mRect, event);
+ layer()->replot();
+}
+
+/*! \internal
+
+ This method is called by QCustomPlot to indicate that an ongoing selection rect interaction has
+ finished by the user releasing the mouse button. The default implementation deactivates the
+ selection rect and emits the \ref accepted signal.
+*/
+void QCPSelectionRect::endSelection(QMouseEvent *event)
+{
+ mRect.setBottomRight(event->pos());
+ mActive = false;
+ emit accepted(mRect, event);
+}
+
+/*! \internal
+
+ This method is called by QCustomPlot when a key has been pressed by the user while the selection
+ rect interaction is active. The default implementation allows to \ref cancel the interaction by
+ hitting the escape key.
+*/
+void QCPSelectionRect::keyPressEvent(QKeyEvent *event)
+{
+ if (event->key() == Qt::Key_Escape && mActive)
+ {
+ mActive = false;
+ emit canceled(mRect, event);
+ }
+}
+
+/* inherits documentation from base class */
+void QCPSelectionRect::applyDefaultAntialiasingHint(QCPPainter *painter) const
+{
+ applyAntialiasingHint(painter, mAntialiased, QCP::aeOther);
+}
+
+/*! \internal
+
+ If the selection rect is active (\ref isActive), draws the selection rect defined by \a mRect.
+
+ \seebaseclassmethod
+*/
+void QCPSelectionRect::draw(QCPPainter *painter)
+{
+ if (mActive)
+ {
+ painter->setPen(mPen);
+ painter->setBrush(mBrush);
+ painter->drawRect(mRect);
+ }
+}
+/* end of 'src/selectionrect.cpp' */
+
+
+/* including file 'src/layout.cpp', size 74302 */
+/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPMarginGroup
@@ -1665,7 +3130,7 @@ void QCPMarginGroup::removeChild(QCP::MarginSide side, QCPLayoutElement *element
invisible by themselves, because they don't draw anything. Their only purpose is to manage the
position and size of other layout elements. This category of layout elements usually use
QCPLayout as base class. Then there is the category of layout elements which actually draw
- something. For example, QCPAxisRect, QCPLegend and QCPPlotTitle are of this category. This does
+ something. For example, QCPAxisRect, QCPLegend and QCPTextElement are of this category. This does
not necessarily mean that the latter category can't have child layout elements. QCPLegend for
instance, actually derives from QCPLayoutGrid and the individual legend items are child layout
elements in the grid layout.
@@ -1691,35 +3156,6 @@ void QCPMarginGroup::removeChild(QCP::MarginSide side, QCPLayoutElement *element
\ref setAutoMargins is enabled) according to the space required by the labels of the axes.
*/
-/*! \fn virtual void QCPLayoutElement::mousePressEvent(QMouseEvent *event)
-
- This event is called, if the mouse was pressed while being inside the outer rect of this layout
- element.
-*/
-
-/*! \fn virtual void QCPLayoutElement::mouseMoveEvent(QMouseEvent *event)
-
- This event is called, if the mouse is moved inside the outer rect of this layout element.
-*/
-
-/*! \fn virtual void QCPLayoutElement::mouseReleaseEvent(QMouseEvent *event)
-
- This event is called, if the mouse was previously pressed inside the outer rect of this layout
- element and is now released.
-*/
-
-/*! \fn virtual void QCPLayoutElement::mouseDoubleClickEvent(QMouseEvent *event)
-
- This event is called, if the mouse is double-clicked inside the outer rect of this layout
- element.
-*/
-
-/*! \fn virtual void QCPLayoutElement::wheelEvent(QWheelEvent *event)
-
- This event is called, if the mouse wheel is scrolled while the cursor is inside the rect of this
- layout element.
-*/
-
/* end documentation of inline functions */
/*!
@@ -1811,7 +3247,7 @@ void QCPLayoutElement::setMinimumMargins(const QMargins &margins)
Margin sides that are under automatic control may participate in a \ref QCPMarginGroup (see \ref
setMarginGroup), to synchronize (align) it with other layout elements in the plot.
- \see setMinimumMargins, setMargins
+ \see setMinimumMargins, setMargins, QCP::MarginSide
*/
void QCPLayoutElement::setAutoMargins(QCP::MarginSides sides)
{
@@ -1879,6 +3315,8 @@ void QCPLayoutElement::setMaximumSize(int width, int height)
Note that margin groups only work for margin sides that are set to automatic (\ref
setAutoMargins).
+
+ \see QCP::MarginSide
*/
void QCPLayoutElement::setMarginGroup(QCP::MarginSides sides, QCPMarginGroup *group)
{
@@ -2044,6 +3482,21 @@ int QCPLayoutElement::calculateAutoMargin(QCP::MarginSide side)
return qMax(QCP::getMarginValue(mMargins, side), QCP::getMarginValue(mMinimumMargins, side));
}
+/*! \internal
+
+ This virtual method is called when this layout element was moved to a different QCPLayout, or
+ when this layout element has changed its logical position (e.g. row and/or column) within the
+ same QCPLayout. Subclasses may use this to react accordingly.
+
+ Since this method is called after the completion of the move, you can access the new parent
+ layout via \ref layout().
+
+ The default implementation does nothing.
+*/
+void QCPLayoutElement::layoutChanged()
+{
+}
+
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPLayout
////////////////////////////////////////////////////////////////////////////////////////////////////
@@ -2294,6 +3747,7 @@ void QCPLayout::adoptElement(QCPLayoutElement *el)
el->setParent(this);
if (!el->parentPlot())
el->initializeParentPlot(mParentPlot);
+ el->layoutChanged();
} else
qDebug() << Q_FUNC_INFO << "Null element passed";
}
@@ -2469,26 +3923,50 @@ QVector<int> QCPLayout::getSectionSizes(QVector<int> maxSizes, QVector<int> minS
/*! \class QCPLayoutGrid
\brief A layout that arranges child elements in a grid
-
+
Elements are laid out in a grid with configurable stretch factors (\ref setColumnStretchFactor,
\ref setRowStretchFactor) and spacing (\ref setColumnSpacing, \ref setRowSpacing).
-
+
Elements can be added to cells via \ref addElement. The grid is expanded if the specified row or
column doesn't exist yet. Whether a cell contains a valid layout element can be checked with \ref
hasElement, that element can be retrieved with \ref element. If rows and columns that only have
empty cells shall be removed, call \ref simplify. Removal of elements is either done by just
adding the element to a different layout or by using the QCPLayout interface \ref take or \ref
remove.
-
+
+ If you use \ref addElement(QCPLayoutElement*) without explicit parameters for \a row and \a
+ column, the grid layout will choose the position according to the current \ref setFillOrder and
+ the wrapping (\ref setWrap).
+
Row and column insertion can be performed with \ref insertRow and \ref insertColumn.
*/
+/* start documentation of inline functions */
+
+/*! \fn int QCPLayoutGrid::rowCount() const
+
+ Returns the number of rows in the layout.
+
+ \see columnCount
+*/
+
+/*! \fn int QCPLayoutGrid::columnCount() const
+
+ Returns the number of columns in the layout.
+
+ \see rowCount
+*/
+
+/* end documentation of inline functions */
+
/*!
Creates an instance of QCPLayoutGrid and sets default values.
*/
QCPLayoutGrid::QCPLayoutGrid() :
mColumnSpacing(5),
- mRowSpacing(5)
+ mRowSpacing(5),
+ mWrap(0),
+ mFillOrder(foRowsFirst)
{
}
@@ -2524,58 +4002,77 @@ QCPLayoutElement *QCPLayoutGrid::element(int row, int column) const
return 0;
}
-/*!
- Returns the number of rows in the layout.
-
- \see columnCount
-*/
-int QCPLayoutGrid::rowCount() const
-{
- return mElements.size();
-}
-/*!
- Returns the number of columns in the layout.
-
- \see rowCount
-*/
-int QCPLayoutGrid::columnCount() const
-{
- if (mElements.size() > 0)
- return mElements.first().size();
- else
- return 0;
-}
+/*! \overload
-/*!
Adds the \a element to cell with \a row and \a column. If \a element is already in a layout, it
is first removed from there. If \a row or \a column don't exist yet, the layout is expanded
accordingly.
-
+
Returns true if the element was added successfully, i.e. if the cell at \a row and \a column
didn't already have an element.
-
+
+ Use the overload of this method without explicit row/column index to place the element according
+ to the configured fill order and wrapping settings.
+
\see element, hasElement, take, remove
*/
bool QCPLayoutGrid::addElement(int row, int column, QCPLayoutElement *element)
{
- if (element)
+ if (!hasElement(row, column))
{
- if (!hasElement(row, column))
- {
- if (element->layout()) // remove from old layout first
- element->layout()->take(element);
- expandTo(row+1, column+1);
- mElements[row][column] = element;
+ if (element && element->layout()) // remove from old layout first
+ element->layout()->take(element);
+ expandTo(row+1, column+1);
+ mElements[row][column] = element;
+ if (element)
adoptElement(element);
- return true;
- } else
- qDebug() << Q_FUNC_INFO << "There is already an element in the specified row/column:" << row << column;
+ return true;
} else
- qDebug() << Q_FUNC_INFO << "Can't add null element to row/column:" << row << column;
+ qDebug() << Q_FUNC_INFO << "There is already an element in the specified row/column:" << row << column;
return false;
}
+/*! \overload
+
+ Adds the \a element to the next empty cell according to the current fill order (\ref
+ setFillOrder) and wrapping (\ref setWrap). If \a element is already in a layout, it is first
+ removed from there. If necessary, the layout is expanded to hold the new element.
+
+ Returns true if the element was added successfully.
+
+ \see setFillOrder, setWrap, element, hasElement, take, remove
+*/
+bool QCPLayoutGrid::addElement(QCPLayoutElement *element)
+{
+ int rowIndex = 0;
+ int colIndex = 0;
+ if (mFillOrder == foColumnsFirst)
+ {
+ while (hasElement(rowIndex, colIndex))
+ {
+ ++colIndex;
+ if (colIndex >= mWrap && mWrap > 0)
+ {
+ colIndex = 0;
+ ++rowIndex;
+ }
+ }
+ } else
+ {
+ while (hasElement(rowIndex, colIndex))
+ {
+ ++rowIndex;
+ if (rowIndex >= mWrap && mWrap > 0)
+ {
+ rowIndex = 0;
+ ++colIndex;
+ }
+ }
+ }
+ return addElement(rowIndex, colIndex, element);
+}
+
/*!
Returns whether the cell at \a row and \a column exists and contains a valid element, i.e. isn't
empty.
@@ -2713,6 +4210,77 @@ void QCPLayoutGrid::setRowSpacing(int pixels)
}
/*!
+ Sets the maximum number of columns or rows that are used, before new elements added with \ref
+ addElement(QCPLayoutElement*) will start to fill the next row or column, respectively. It depends
+ on \ref setFillOrder, whether rows or columns are wrapped.
+
+ If \a count is set to zero, no wrapping will ever occur.
+
+ If you wish to re-wrap the elements currently in the layout, call \ref setFillOrder with \a
+ rearrange set to true (the actual fill order doesn't need to be changed for the rearranging to be
+ done).
+
+ Note that the method \ref addElement(int row, int column, QCPLayoutElement *element) with
+ explicitly stated row and column is not subject to wrapping and can place elements even beyond
+ the specified wrapping point.
+
+ \see setFillOrder
+*/
+void QCPLayoutGrid::setWrap(int count)
+{
+ mWrap = qMax(0, count);
+}
+
+/*!
+ Sets the filling order and wrapping behaviour that is used when adding new elements with the
+ method \ref addElement(QCPLayoutElement*).
+
+ The specified \a order defines whether rows or columns are filled first. Using \ref setWrap, you
+ can control at which row/column count wrapping into the next column/row will occur. If you set it
+ to zero, no wrapping will ever occur. Changing the fill order also changes the meaning of the
+ linear index used e.g. in \ref elementAt and \ref takeAt.
+
+ If you want to have all current elements arranged in the new order, set \a rearrange to true. The
+ elements will be rearranged in a way that tries to preserve their linear index. However, empty
+ cells are skipped during build-up of the new cell order, which shifts the succeding element's
+ index. The rearranging is performed even if the specified \a order is already the current fill
+ order. Thus this method can be used to re-wrap the current elements.
+
+ If \a rearrange is false, the current element arrangement is not changed, which means the
+ linear indexes change (because the linear index is dependent on the fill order).
+
+ Note that the method \ref addElement(int row, int column, QCPLayoutElement *element) with
+ explicitly stated row and column is not subject to wrapping and can place elements even beyond
+ the specified wrapping point.
+
+ \see setWrap, addElement(QCPLayoutElement*)
+*/
+void QCPLayoutGrid::setFillOrder(FillOrder order, bool rearrange)
+{
+ // if rearranging, take all elements via linear index of old fill order:
+ const int elCount = elementCount();
+ QVector<QCPLayoutElement*> tempElements;
+ if (rearrange)
+ {
+ tempElements.reserve(elCount);
+ for (int i=0; i<elCount; ++i)
+ {
+ if (elementAt(i))
+ tempElements.append(takeAt(i));
+ }
+ simplify();
+ }
+ // change fill order as requested:
+ mFillOrder = order;
+ // if rearranging, re-insert via linear index according to new fill order:
+ if (rearrange)
+ {
+ for (int i=0; i<tempElements.size(); ++i)
+ addElement(tempElements.at(i));
+ }
+}
+
+/*!
Expands the layout to have \a newRowCount rows and \a newColumnCount columns. So the last valid
row index will be \a newRowCount-1, the last valid column index will be \a newColumnCount-1.
@@ -2795,6 +4363,81 @@ void QCPLayoutGrid::insertColumn(int newIndex)
mElements[row].insert(newIndex, (QCPLayoutElement*)0);
}
+/*!
+ Converts the given \a row and \a column to the linear index used by some methods of \ref
+ QCPLayoutGrid and \ref QCPLayout.
+
+ The way the cells are indexed depends on \ref setFillOrder. If it is \ref foRowsFirst, the
+ indices increase left to right and then top to bottom. If it is \ref foColumnsFirst, the indices
+ increase top to bottom and then left to right.
+
+ For the returned index to be valid, \a row and \a column must be valid indices themselves, i.e.
+ greater or equal to zero and smaller than the current \ref rowCount/\ref columnCount.
+
+ \see indexToRowCol
+*/
+int QCPLayoutGrid::rowColToIndex(int row, int column) const
+{
+ if (row >= 0 && row < rowCount())
+ {
+ if (column >= 0 && column < columnCount())
+ {
+ switch (mFillOrder)
+ {
+ case foRowsFirst: return column*rowCount() + row;
+ case foColumnsFirst: return row*columnCount() + column;
+ }
+ } else
+ qDebug() << Q_FUNC_INFO << "row index out of bounds:" << row;
+ } else
+ qDebug() << Q_FUNC_INFO << "column index out of bounds:" << column;
+ return 0;
+}
+
+/*!
+ Converts the linear index to row and column indices and writes the result to \a row and \a
+ column.
+
+ The way the cells are indexed depends on \ref setFillOrder. If it is \ref foRowsFirst, the
+ indices increase left to right and then top to bottom. If it is \ref foColumnsFirst, the indices
+ increase top to bottom and then left to right.
+
+ If there are no cells (i.e. column or row count is zero), sets \a row and \a column to -1.
+
+ For the retrieved \a row and \a column to be valid, the passed \a index must be valid itself,
+ i.e. greater or equal to zero and smaller than the current \ref elementCount.
+
+ \see rowColToIndex
+*/
+void QCPLayoutGrid::indexToRowCol(int index, int &row, int &column) const
+{
+ row = -1;
+ column = -1;
+ if (columnCount() == 0 || rowCount() == 0)
+ return;
+ if (index < 0 || index >= elementCount())
+ {
+ qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
+ return;
+ }
+
+ switch (mFillOrder)
+ {
+ case foRowsFirst:
+ {
+ column = index / rowCount();
+ row = index % rowCount();
+ break;
+ }
+ case foColumnsFirst:
+ {
+ row = index / columnCount();
+ column = index % columnCount();
+ break;
+ }
+ }
+}
+
/* inherits documentation from base class */
void QCPLayoutGrid::updateLayout()
{
@@ -2824,28 +4467,41 @@ void QCPLayoutGrid::updateLayout()
}
}
-/* inherits documentation from base class */
-int QCPLayoutGrid::elementCount() const
-{
- return rowCount()*columnCount();
-}
+/*!
+ \seebaseclassmethod
-/* inherits documentation from base class */
+ Note that the association of the linear \a index to the row/column based cells depends on the
+ current setting of \ref setFillOrder.
+
+ \see rowColToIndex
+*/
QCPLayoutElement *QCPLayoutGrid::elementAt(int index) const
{
if (index >= 0 && index < elementCount())
- return mElements.at(index / columnCount()).at(index % columnCount());
- else
+ {
+ int row, col;
+ indexToRowCol(index, row, col);
+ return mElements.at(row).at(col);
+ } else
return 0;
}
-/* inherits documentation from base class */
+/*!
+ \seebaseclassmethod
+
+ Note that the association of the linear \a index to the row/column based cells depends on the
+ current setting of \ref setFillOrder.
+
+ \see rowColToIndex
+*/
QCPLayoutElement *QCPLayoutGrid::takeAt(int index)
{
if (QCPLayoutElement *el = elementAt(index))
{
releaseElement(el);
- mElements[index / columnCount()][index % columnCount()] = 0;
+ int row, col;
+ indexToRowCol(index, row, col);
+ mElements[row][col] = 0;
return el;
} else
{
@@ -2877,22 +4533,15 @@ bool QCPLayoutGrid::take(QCPLayoutElement *element)
QList<QCPLayoutElement*> QCPLayoutGrid::elements(bool recursive) const
{
QList<QCPLayoutElement*> result;
- int colC = columnCount();
- int rowC = rowCount();
+ const int elCount = elementCount();
#if QT_VERSION >= QT_VERSION_CHECK(4, 7, 0)
- result.reserve(colC*rowC);
+ result.reserve(elCount);
#endif
- for (int row=0; row<rowC; ++row)
- {
- for (int col=0; col<colC; ++col)
- {
- result.append(mElements.at(row).at(col));
- }
- }
+ for (int i=0; i<elCount; ++i)
+ result.append(elementAt(i));
if (recursive)
{
- int c = result.size();
- for (int i=0; i<c; ++i)
+ for (int i=0; i<elCount; ++i)
{
if (result.at(i))
result << result.at(i)->elements(recursive);
@@ -3355,8 +5004,12 @@ void QCPLayoutInset::addElement(QCPLayoutElement *element, const QRectF &rect)
} else
qDebug() << Q_FUNC_INFO << "Can't add null element";
}
+/* end of 'src/layout.cpp' */
+/* including file 'src/lineending.cpp', size 11536 */
+/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
+
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPLineEnding
////////////////////////////////////////////////////////////////////////////////////////////////////
@@ -3520,17 +5173,15 @@ double QCPLineEnding::realLength() const
Draws the line ending with the specified \a painter at the position \a pos. The direction of the
line ending is controlled with \a dir.
*/
-void QCPLineEnding::draw(QCPPainter *painter, const QVector2D &pos, const QVector2D &dir) const
+void QCPLineEnding::draw(QCPPainter *painter, const QCPVector2D &pos, const QCPVector2D &dir) const
{
if (mStyle == esNone)
return;
- QVector2D lengthVec(dir.normalized());
+ QCPVector2D lengthVec = dir.normalized() * mLength*(mInverted ? -1 : 1);
if (lengthVec.isNull())
- lengthVec = QVector2D(1, 0);
- QVector2D widthVec(-lengthVec.y(), lengthVec.x());
- lengthVec *= (float)(mLength*(mInverted ? -1 : 1));
- widthVec *= (float)(mWidth*0.5*(mInverted ? -1 : 1));
+ lengthVec = QCPVector2D(1, 0);
+ QCPVector2D widthVec = dir.normalized().perpendicular() * mWidth*0.5*(mInverted ? -1 : 1);
QPen penBackup = painter->pen();
QBrush brushBackup = painter->brush();
@@ -3557,7 +5208,7 @@ void QCPLineEnding::draw(QCPPainter *painter, const QVector2D &pos, const QVecto
{
QPointF points[4] = {pos.toPointF(),
(pos-lengthVec+widthVec).toPointF(),
- (pos-lengthVec*0.8f).toPointF(),
+ (pos-lengthVec*0.8).toPointF(),
(pos-lengthVec-widthVec).toPointF()
};
painter->setPen(miterPen);
@@ -3587,7 +5238,7 @@ void QCPLineEnding::draw(QCPPainter *painter, const QVector2D &pos, const QVecto
}
case esSquare:
{
- QVector2D widthVecPerp(-widthVec.y(), widthVec.x());
+ QCPVector2D widthVecPerp = widthVec.perpendicular();
QPointF points[4] = {(pos-widthVecPerp+widthVec).toPointF(),
(pos-widthVecPerp-widthVec).toPointF(),
(pos+widthVecPerp-widthVec).toPointF(),
@@ -3602,7 +5253,7 @@ void QCPLineEnding::draw(QCPPainter *painter, const QVector2D &pos, const QVecto
}
case esDiamond:
{
- QVector2D widthVecPerp(-widthVec.y(), widthVec.x());
+ QCPVector2D widthVecPerp = widthVec.perpendicular();
QPointF points[4] = {(pos-widthVecPerp).toPointF(),
(pos-widthVec).toPointF(),
(pos+widthVecPerp).toPointF(),
@@ -3630,13 +5281,13 @@ void QCPLineEnding::draw(QCPPainter *painter, const QVector2D &pos, const QVecto
if (qFuzzyIsNull(painter->pen().widthF()) && !painter->modes().testFlag(QCPPainter::pmNonCosmetic))
{
// if drawing with cosmetic pen (perfectly thin stroke, happens only in vector exports), draw bar exactly on tip of line
- painter->drawLine((pos+widthVec+lengthVec*0.2f*(mInverted?-1:1)).toPointF(),
- (pos-widthVec-lengthVec*0.2f*(mInverted?-1:1)).toPointF());
+ painter->drawLine((pos+widthVec+lengthVec*0.2*(mInverted?-1:1)).toPointF(),
+ (pos-widthVec-lengthVec*0.2*(mInverted?-1:1)).toPointF());
} else
{
// if drawing with thick (non-cosmetic) pen, shift bar a little in line direction to prevent line from sticking through bar slightly
- painter->drawLine((pos+widthVec+lengthVec*0.2f*(mInverted?-1:1)+dir.normalized()*qMax(1.0f, (float)painter->pen().widthF())*0.5f).toPointF(),
- (pos-widthVec-lengthVec*0.2f*(mInverted?-1:1)+dir.normalized()*qMax(1.0f, (float)painter->pen().widthF())*0.5f).toPointF());
+ painter->drawLine((pos+widthVec+lengthVec*0.2*(mInverted?-1:1)+dir.normalized()*qMax(1.0f, (float)painter->pen().widthF())*0.5f).toPointF(),
+ (pos-widthVec-lengthVec*0.2*(mInverted?-1:1)+dir.normalized()*qMax(1.0f, (float)painter->pen().widthF())*0.5f).toPointF());
}
break;
}
@@ -3648,10 +5299,1724 @@ void QCPLineEnding::draw(QCPPainter *painter, const QVector2D &pos, const QVecto
Draws the line ending. The direction is controlled with the \a angle parameter in radians.
*/
-void QCPLineEnding::draw(QCPPainter *painter, const QVector2D &pos, double angle) const
+void QCPLineEnding::draw(QCPPainter *painter, const QCPVector2D &pos, double angle) const
+{
+ draw(painter, pos, QCPVector2D(qCos(angle), qSin(angle)));
+}
+/* end of 'src/lineending.cpp' */
+
+
+/* including file 'src/axis/axisticker.cpp', size 18664 */
+/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
+
+////////////////////////////////////////////////////////////////////////////////////////////////////
+//////////////////// QCPAxisTicker
+////////////////////////////////////////////////////////////////////////////////////////////////////
+/*! \class QCPAxisTicker
+ \brief The base class tick generator used by QCPAxis to create tick positions and tick labels
+
+ Each QCPAxis has an internal QCPAxisTicker (or a subclass) in order to generate tick positions
+ and tick labels for the current axis range. The ticker of an axis can be set via \ref
+ QCPAxis::setTicker. Since that method takes a <tt>QSharedPointer<QCPAxisTicker></tt>, multiple
+ axes can share the same ticker instance.
+
+ This base class generates normal tick coordinates and numeric labels for linear axes. It picks a
+ reasonable tick step (the separation between ticks) which results in readable tick labels. The
+ number of ticks that should be approximately generated can be set via \ref setTickCount.
+ Depending on the current tick step strategy (\ref setTickStepStrategy), the algorithm either
+ sacrifices readability to better match the specified tick count (\ref
+ QCPAxisTicker::tssMeetTickCount) or relaxes the tick count in favor of better tick steps (\ref
+ QCPAxisTicker::tssReadability), which is the default.
+
+ The following more specialized axis ticker subclasses are available, see details in the
+ respective class documentation:
+
+ <center>
+ <table>
+ <tr><td style="text-align:right; padding: 0 1em">QCPAxisTickerFixed</td><td>\image html axisticker-fixed.png</td></tr>
+ <tr><td style="text-align:right; padding: 0 1em">QCPAxisTickerLog</td><td>\image html axisticker-log.png</td></tr>
+ <tr><td style="text-align:right; padding: 0 1em">QCPAxisTickerPi</td><td>\image html axisticker-pi.png</td></tr>
+ <tr><td style="text-align:right; padding: 0 1em">QCPAxisTickerText</td><td>\image html axisticker-text.png</td></tr>
+ <tr><td style="text-align:right; padding: 0 1em">QCPAxisTickerDateTime</td><td>\image html axisticker-datetime.png</td></tr>
+ <tr><td style="text-align:right; padding: 0 1em">QCPAxisTickerTime</td><td>\image html axisticker-time.png
+ \image html axisticker-time2.png</td></tr>
+ </table>
+ </center>
+
+ \section axisticker-subclassing Creating own axis tickers
+
+ Creating own axis tickers can be achieved very easily by sublassing QCPAxisTicker and
+ reimplementing some or all of the available virtual methods.
+
+ In the simplest case you might wish to just generate different tick steps than the other tickers,
+ so you only reimplement the method \ref getTickStep. If you additionally want control over the
+ string that will be shown as tick label, reimplement \ref getTickLabel.
+
+ If you wish to have complete control, you can generate the tick vectors and tick label vectors
+ yourself by reimplementing \ref createTickVector and \ref createLabelVector. The default
+ implementations use the previously mentioned virtual methods \ref getTickStep and \ref
+ getTickLabel, but your reimplementations don't necessarily need to do so. For example in the case
+ of unequal tick steps, the method \ref getTickStep loses its usefulness and can be ignored.
+
+ The sub tick count between major ticks can be controlled with \ref getSubTickCount. Full sub tick
+ placement control is obtained by reimplementing \ref createSubTickVector.
+
+ See the documentation of all these virtual methods in QCPAxisTicker for detailed information
+ about the parameters and expected return values.
+*/
+
+/*!
+ Constructs the ticker and sets reasonable default values. Axis tickers are commonly created
+ managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker.
+*/
+QCPAxisTicker::QCPAxisTicker() :
+ mTickStepStrategy(tssReadability),
+ mTickCount(5),
+ mTickOrigin(0)
+{
+}
+
+QCPAxisTicker::~QCPAxisTicker()
+{
+
+}
+
+/*!
+ Sets which strategy the axis ticker follows when choosing the size of the tick step. For the
+ available strategies, see \ref TickStepStrategy.
+*/
+void QCPAxisTicker::setTickStepStrategy(QCPAxisTicker::TickStepStrategy strategy)
+{
+ mTickStepStrategy = strategy;
+}
+
+/*!
+ Sets how many ticks this ticker shall aim to generate across the axis range. Note that \a count
+ is not guaranteed to be matched exactly, as generating readable tick intervals may conflict with
+ the requested number of ticks.
+
+ Whether the readability has priority over meeting the requested \a count can be specified with
+ \ref setTickStepStrategy.
+*/
+void QCPAxisTicker::setTickCount(int count)
+{
+ if (count > 0)
+ mTickCount = count;
+ else
+ qDebug() << Q_FUNC_INFO << "tick count must be greater than zero:" << count;
+}
+
+/*!
+ Sets the mathematical coordinate (or "offset") of the zeroth tick. This tick coordinate is just a
+ concept and doesn't need to be inside the currently visible axis range.
+
+ By default \a origin is zero, which for example yields ticks {-5, 0, 5, 10, 15,...} when the tick
+ step is five. If \a origin is now set to 1 instead, the correspondingly generated ticks would be
+ {-4, 1, 6, 11, 16,...}.
+*/
+void QCPAxisTicker::setTickOrigin(double origin)
+{
+ mTickOrigin = origin;
+}
+
+/*!
+ This is the method called by QCPAxis in order to actually generate tick coordinates (\a ticks),
+ tick label strings (\a tickLabels) and sub tick coordinates (\a subTicks).
+
+ The ticks are generated for the specified \a range. The generated labels typically follow the
+ specified \a locale, \a formatChar and number \a precision, however this might be different (or
+ even irrelevant) for certain QCPAxisTicker subclasses.
+
+ The output parameter \a ticks is filled with the generated tick positions in axis coordinates.
+ The output parameters \a subTicks and \a tickLabels are optional (set them to 0 if not needed)
+ and are respectively filled with sub tick coordinates, and tick label strings belonging to \a
+ ticks by index.
+*/
+void QCPAxisTicker::generate(const QCPRange &range, const QLocale &locale, QChar formatChar, int precision, QVector<double> &ticks, QVector<double> *subTicks, QVector<QString> *tickLabels)
+{
+ // generate (major) ticks:
+ double tickStep = getTickStep(range);
+ ticks = createTickVector(tickStep, range);
+ trimTicks(range, ticks, true); // trim ticks to visible range plus one outer tick on each side (incase a subclass createTickVector creates more)
+
+ // generate sub ticks between major ticks:
+ if (subTicks)
+ {
+ if (ticks.size() > 0)
+ {
+ *subTicks = createSubTickVector(getSubTickCount(tickStep), ticks);
+ trimTicks(range, *subTicks, false);
+ } else
+ *subTicks = QVector<double>();
+ }
+
+ // finally trim also outliers (no further clipping happens in axis drawing):
+ trimTicks(range, ticks, false);
+ // generate labels for visible ticks if requested:
+ if (tickLabels)
+ *tickLabels = createLabelVector(ticks, locale, formatChar, precision);
+}
+
+/*! \internal
+
+ Takes the entire currently visible axis range and returns a sensible tick step in
+ order to provide readable tick labels as well as a reasonable number of tick counts (see \ref
+ setTickCount, \ref setTickStepStrategy).
+
+ If a QCPAxisTicker subclass only wants a different tick step behaviour than the default
+ implementation, it should reimplement this method. See \ref cleanMantissa for a possible helper
+ function.
+*/
+double QCPAxisTicker::getTickStep(const QCPRange &range)
+{
+ double exactStep = range.size()/(double)(mTickCount+1e-10); // mTickCount ticks on average, the small addition is to prevent jitter on exact integers
+ return cleanMantissa(exactStep);
+}
+
+/*! \internal
+
+ Takes the \a tickStep, i.e. the distance between two consecutive ticks, and returns
+ an appropriate number of sub ticks for that specific tick step.
+
+ Note that a returned sub tick count of e.g. 4 will split each tick interval into 5 sections.
+*/
+int QCPAxisTicker::getSubTickCount(double tickStep)
+{
+ int result = 1; // default to 1, if no proper value can be found
+
+ // separate integer and fractional part of mantissa:
+ double epsilon = 0.01;
+ double intPartf;
+ int intPart;
+ double fracPart = modf(getMantissa(tickStep), &intPartf);
+ intPart = intPartf;
+
+ // handle cases with (almost) integer mantissa:
+ if (fracPart < epsilon || 1.0-fracPart < epsilon)
+ {
+ if (1.0-fracPart < epsilon)
+ ++intPart;
+ switch (intPart)
+ {
+ case 1: result = 4; break; // 1.0 -> 0.2 substep
+ case 2: result = 3; break; // 2.0 -> 0.5 substep
+ case 3: result = 2; break; // 3.0 -> 1.0 substep
+ case 4: result = 3; break; // 4.0 -> 1.0 substep
+ case 5: result = 4; break; // 5.0 -> 1.0 substep
+ case 6: result = 2; break; // 6.0 -> 2.0 substep
+ case 7: result = 6; break; // 7.0 -> 1.0 substep
+ case 8: result = 3; break; // 8.0 -> 2.0 substep
+ case 9: result = 2; break; // 9.0 -> 3.0 substep
+ }
+ } else
+ {
+ // handle cases with significantly fractional mantissa:
+ if (qAbs(fracPart-0.5) < epsilon) // *.5 mantissa
+ {
+ switch (intPart)
+ {
+ case 1: result = 2; break; // 1.5 -> 0.5 substep
+ case 2: result = 4; break; // 2.5 -> 0.5 substep
+ case 3: result = 4; break; // 3.5 -> 0.7 substep
+ case 4: result = 2; break; // 4.5 -> 1.5 substep
+ case 5: result = 4; break; // 5.5 -> 1.1 substep (won't occur with default getTickStep from here on)
+ case 6: result = 4; break; // 6.5 -> 1.3 substep
+ case 7: result = 2; break; // 7.5 -> 2.5 substep
+ case 8: result = 4; break; // 8.5 -> 1.7 substep
+ case 9: result = 4; break; // 9.5 -> 1.9 substep
+ }
+ }
+ // if mantissa fraction isn't 0.0 or 0.5, don't bother finding good sub tick marks, leave default
+ }
+
+ return result;
+}
+
+/*! \internal
+
+ This method returns the tick label string as it should be printed under the \a tick coordinate.
+ If a textual number is returned, it should respect the provided \a locale, \a formatChar and \a
+ precision.
+
+ If the returned value contains exponentials of the form "2e5" and beautifully typeset powers is
+ enabled in the QCPAxis number format (\ref QCPAxis::setNumberFormat), the exponential part will
+ be formatted accordingly using multiplication symbol and superscript during rendering of the
+ label automatically.
+*/
+QString QCPAxisTicker::getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision)
+{
+ return locale.toString(tick, formatChar.toLatin1(), precision);
+}
+
+/*! \internal
+
+ Returns a vector containing all coordinates of sub ticks that should be drawn. It generates \a
+ subTickCount sub ticks between each tick pair given in \a ticks.
+
+ If a QCPAxisTicker subclass needs maximal control over the generated sub ticks, it should
+ reimplement this method. Depending on the purpose of the subclass it doesn't necessarily need to
+ base its result on \a subTickCount or \a ticks.
+*/
+QVector<double> QCPAxisTicker::createSubTickVector(int subTickCount, const QVector<double> &ticks)
+{
+ QVector<double> result;
+ if (subTickCount <= 0 || ticks.size() < 2)
+ return result;
+
+ result.reserve((ticks.size()-1)*subTickCount);
+ for (int i=1; i<ticks.size(); ++i)
+ {
+ double subTickStep = (ticks.at(i)-ticks.at(i-1))/(double)(subTickCount+1);
+ for (int k=1; k<=subTickCount; ++k)
+ result.append(ticks.at(i-1) + k*subTickStep);
+ }
+ return result;
+}
+
+/*! \internal
+
+ Returns a vector containing all coordinates of ticks that should be drawn. The default
+ implementation generates ticks with a spacing of \a tickStep (mathematically starting at the tick
+ step origin, see \ref setTickOrigin) distributed over the passed \a range.
+
+ In order for the axis ticker to generate proper sub ticks, it is necessary that the first and
+ last tick coordinates returned by this method are just below/above the provided \a range.
+ Otherwise the outer intervals won't contain any sub ticks.
+
+ If a QCPAxisTicker subclass needs maximal control over the generated ticks, it should reimplement
+ this method. Depending on the purpose of the subclass it doesn't necessarily need to base its
+ result on \a tickStep, e.g. when the ticks are spaced unequally like in the case of
+ QCPAxisTickerLog.
+*/
+QVector<double> QCPAxisTicker::createTickVector(double tickStep, const QCPRange &range)
+{
+ QVector<double> result;
+ // Generate tick positions according to tickStep:
+ qint64 firstStep = floor((range.lower-mTickOrigin)/tickStep); // do not use qFloor here, or we'll lose 64 bit precision
+ qint64 lastStep = ceil((range.upper-mTickOrigin)/tickStep); // do not use qCeil here, or we'll lose 64 bit precision
+ int tickcount = lastStep-firstStep+1;
+ if (tickcount < 0) tickcount = 0;
+ result.resize(tickcount);
+ for (int i=0; i<tickcount; ++i)
+ result[i] = mTickOrigin + (firstStep+i)*tickStep;
+ return result;
+}
+
+/*! \internal
+
+ Returns a vector containing all tick label strings corresponding to the tick coordinates provided
+ in \a ticks. The default implementation calls \ref getTickLabel to generate the respective
+ strings.
+
+ It is possible but uncommon for QCPAxisTicker subclasses to reimplement this method, as
+ reimplementing \ref getTickLabel often achieves the intended result easier.
+*/
+QVector<QString> QCPAxisTicker::createLabelVector(const QVector<double> &ticks, const QLocale &locale, QChar formatChar, int precision)
+{
+ QVector<QString> result;
+ result.reserve(ticks.size());
+ for (int i=0; i<ticks.size(); ++i)
+ result.append(getTickLabel(ticks.at(i), locale, formatChar, precision));
+ return result;
+}
+
+/*! \internal
+
+ Removes tick coordinates from \a ticks which lie outside the specified \a range. If \a
+ keepOneOutlier is true, it preserves one tick just outside the range on both sides, if present.
+
+ The passed \a ticks must be sorted in ascending order.
+*/
+void QCPAxisTicker::trimTicks(const QCPRange &range, QVector<double> &ticks, bool keepOneOutlier) const
+{
+ bool lowFound = false;
+ bool highFound = false;
+ int lowIndex = 0;
+ int highIndex = -1;
+
+ for (int i=0; i < ticks.size(); ++i)
+ {
+ if (ticks.at(i) >= range.lower)
+ {
+ lowFound = true;
+ lowIndex = i;
+ break;
+ }
+ }
+ for (int i=ticks.size()-1; i >= 0; --i)
+ {
+ if (ticks.at(i) <= range.upper)
+ {
+ highFound = true;
+ highIndex = i;
+ break;
+ }
+ }
+
+ if (highFound && lowFound)
+ {
+ int trimFront = qMax(0, lowIndex-(keepOneOutlier ? 1 : 0));
+ int trimBack = qMax(0, ticks.size()-(keepOneOutlier ? 2 : 1)-highIndex);
+ if (trimFront > 0 || trimBack > 0)
+ ticks = ticks.mid(trimFront, ticks.size()-trimFront-trimBack);
+ } else // all ticks are either all below or all above the range
+ ticks.clear();
+}
+
+/*! \internal
+
+ Returns the coordinate contained in \a candidates which is closest to the provided \a target.
+
+ This method assumes \a candidates is not empty and sorted in ascending order.
+*/
+double QCPAxisTicker::pickClosest(double target, const QVector<double> &candidates) const
+{
+ if (candidates.size() == 1)
+ return candidates.first();
+ QVector<double>::const_iterator it = std::lower_bound(candidates.constBegin(), candidates.constEnd(), target);
+ if (it == candidates.constEnd())
+ return *(it-1);
+ else if (it == candidates.constBegin())
+ return *it;
+ else
+ return target-*(it-1) < *it-target ? *(it-1) : *it;
+}
+
+/*! \internal
+
+ Returns the decimal mantissa of \a input. Optionally, if \a magnitude is not set to zero, it also
+ returns the magnitude of \a input as a power of 10.
+
+ For example, an input of 142.6 will return a mantissa of 1.426 and a magnitude of 100.
+*/
+double QCPAxisTicker::getMantissa(double input, double *magnitude) const
+{
+ const double mag = qPow(10.0, qFloor(qLn(input)/qLn(10.0)));
+ if (magnitude) *magnitude = mag;
+ return input/mag;
+}
+
+/*! \internal
+
+ Returns a number that is close to \a input but has a clean, easier human readable mantissa. How
+ strongly the mantissa is altered, and thus how strong the result deviates from the original \a
+ input, depends on the current tick step strategy (see \ref setTickStepStrategy).
+*/
+double QCPAxisTicker::cleanMantissa(double input) const
+{
+ double magnitude;
+ const double mantissa = getMantissa(input, &magnitude);
+ switch (mTickStepStrategy)
+ {
+ case tssReadability:
+ {
+ return pickClosest(mantissa, QVector<double>() << 1.0 << 2.0 << 2.5 << 5.0 << 10.0)*magnitude;
+ }
+ case tssMeetTickCount:
+ {
+ // 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
+ if (mantissa <= 5.0)
+ return (int)(mantissa*2)/2.0*magnitude; // round digit after decimal point to 0.5
+ else
+ return (int)(mantissa/2.0)*2.0*magnitude; // round to first digit in multiples of 2
+ }
+ }
+ return input;
+}
+/* end of 'src/axis/axisticker.cpp' */
+
+
+/* including file 'src/axis/axistickerdatetime.cpp', size 14443 */
+/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
+
+////////////////////////////////////////////////////////////////////////////////////////////////////
+//////////////////// QCPAxisTickerDateTime
+////////////////////////////////////////////////////////////////////////////////////////////////////
+/*! \class QCPAxisTickerDateTime
+ \brief Specialized axis ticker for calendar dates and times as axis ticks
+
+ \image html axisticker-datetime.png
+
+ This QCPAxisTicker subclass generates ticks that correspond to real calendar dates and times. The
+ plot axis coordinate is interpreted as Unix Time, so seconds since Epoch (January 1, 1970, 00:00
+ UTC). This is also used for example by QDateTime in the <tt>toTime_t()/setTime_t()</tt> methods
+ with a precision of one second. Since Qt 4.7, millisecond accuracy can be obtained from QDateTime
+ by using <tt>QDateTime::fromMSecsSinceEpoch()/1000.0</tt>. The static methods \ref dateTimeToKey
+ and \ref keyToDateTime conveniently perform this conversion achieving a precision of one
+ millisecond on all Qt versions.
+
+ The format of the date/time display in the tick labels is controlled with \ref setDateTimeFormat.
+ If a different time spec (time zone) shall be used, see \ref setDateTimeSpec.
+
+ This ticker produces unequal tick spacing in order to provide intuitive date and time-of-day
+ ticks. For example, if the axis range spans a few years such that there is one tick per year,
+ ticks will be positioned on 1. January of every year. This is intuitive but, due to leap years,
+ will result in slightly unequal tick intervals (visually unnoticeable). The same can be seen in
+ the image above: even though the number of days varies month by month, this ticker generates
+ ticks on the same day of each month.
+
+ If you would like to change the date/time that is used as a (mathematical) starting date for the
+ ticks, use the \ref setTickOrigin(const QDateTime &origin) method overload, which takes a
+ QDateTime. If you pass 15. July, 9:45 to this method, the yearly ticks will end up on 15. July at
+ 9:45 of every year.
+
+ The ticker can be created and assigned to an axis like this:
+ \snippet documentation/doc-image-generator/mainwindow.cpp axistickerdatetime-creation
+
+ \note If you rather wish to display relative times in terms of days, hours, minutes, seconds and
+ milliseconds, and are not interested in the intricacies of real calendar dates with months and
+ (leap) years, have a look at QCPAxisTickerTime instead.
+*/
+
+/*!
+ Constructs the ticker and sets reasonable default values. Axis tickers are commonly created
+ managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker.
+*/
+QCPAxisTickerDateTime::QCPAxisTickerDateTime() :
+ mDateTimeFormat(QLatin1String("hh:mm:ss\ndd.MM.yy")),
+ mDateTimeSpec(Qt::LocalTime),
+ mDateStrategy(dsNone)
+{
+ setTickCount(4);
+}
+
+/*!
+ Sets the format in which dates and times are displayed as tick labels. For details about the \a
+ format string, see the documentation of QDateTime::toString().
+
+ Newlines can be inserted with "\n".
+
+ \see setDateTimeSpec
+*/
+void QCPAxisTickerDateTime::setDateTimeFormat(const QString &format)
+{
+ mDateTimeFormat = format;
+}
+
+/*!
+ Sets the time spec that is used for creating the tick labels from corresponding dates/times.
+
+ The default value of QDateTime objects (and also QCPAxisTickerDateTime) is
+ <tt>Qt::LocalTime</tt>. However, if the date time values passed to QCustomPlot (e.g. in the form
+ of axis ranges or keys of a plottable) are given in the UTC spec, set \a spec to <tt>Qt::UTC</tt>
+ to get the correct axis labels.
+
+ \see setDateTimeFormat
+*/
+void QCPAxisTickerDateTime::setDateTimeSpec(Qt::TimeSpec spec)
+{
+ mDateTimeSpec = spec;
+}
+
+/*!
+ Sets the tick origin (see \ref QCPAxisTicker::setTickOrigin) in seconds since Epoch (1. Jan 1970,
+ 00:00 UTC). For the date time ticker it might be more intuitive to use the overload which
+ directly takes a QDateTime, see \ref setTickOrigin(const QDateTime &origin).
+
+ This is useful to define the month/day/time recurring at greater tick interval steps. For
+ example, If you pass 15. July, 9:45 to this method and the tick interval happens to be one tick
+ per year, the ticks will end up on 15. July at 9:45 of every year.
+*/
+void QCPAxisTickerDateTime::setTickOrigin(double origin)
+{
+ QCPAxisTicker::setTickOrigin(origin);
+}
+
+/*!
+ Sets the tick origin (see \ref QCPAxisTicker::setTickOrigin) as a QDateTime \a origin.
+
+ This is useful to define the month/day/time recurring at greater tick interval steps. For
+ example, If you pass 15. July, 9:45 to this method and the tick interval happens to be one tick
+ per year, the ticks will end up on 15. July at 9:45 of every year.
+*/
+void QCPAxisTickerDateTime::setTickOrigin(const QDateTime &origin)
+{
+ setTickOrigin(dateTimeToKey(origin));
+}
+
+/*! \internal
+
+ Returns a sensible tick step with intervals appropriate for a date-time-display, such as weekly,
+ monthly, bi-monthly, etc.
+
+ Note that this tick step isn't used exactly when generating the tick vector in \ref
+ createTickVector, but only as a guiding value requiring some correction for each individual tick
+ interval. Otherwise this would lead to unintuitive date displays, e.g. jumping between first day
+ in the month to the last day in the previous month from tick to tick, due to the non-uniform
+ length of months. The same problem arises with leap years.
+
+ \seebaseclassmethod
+*/
+double QCPAxisTickerDateTime::getTickStep(const QCPRange &range)
+{
+ double result = range.size()/(double)(mTickCount+1e-10); // mTickCount ticks on average, the small addition is to prevent jitter on exact integers
+
+ mDateStrategy = dsNone;
+ if (result < 1) // ideal tick step is below 1 second -> use normal clean mantissa algorithm in units of seconds
+ {
+ result = cleanMantissa(result);
+ } else if (result < 86400*30.4375*12) // below a year
+ {
+ result = pickClosest(result, QVector<double>()
+ << 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
+ << 3600*2 << 3600*3 << 3600*6 << 3600*12 << 3600*24 // hour to day range
+ << 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)
+ if (result > 86400*30.4375-1) // month tick intervals or larger
+ mDateStrategy = dsUniformDayInMonth;
+ else if (result > 3600*24-1) // day tick intervals or larger
+ mDateStrategy = dsUniformTimeInDay;
+ } else // more than a year, go back to normal clean mantissa algorithm but in units of years
+ {
+ const double secondsPerYear = 86400*30.4375*12; // average including leap years
+ result = cleanMantissa(result/secondsPerYear)*secondsPerYear;
+ mDateStrategy = dsUniformDayInMonth;
+ }
+ return result;
+}
+
+/*! \internal
+
+ Returns a sensible sub tick count with intervals appropriate for a date-time-display, such as weekly,
+ monthly, bi-monthly, etc.
+
+ \seebaseclassmethod
+*/
+int QCPAxisTickerDateTime::getSubTickCount(double tickStep)
+{
+ int result = QCPAxisTicker::getSubTickCount(tickStep);
+ switch (qRound(tickStep)) // hand chosen subticks for specific minute/hour/day/week/month range (as specified in getTickStep)
+ {
+ case 5*60: result = 4; break;
+ case 10*60: result = 1; break;
+ case 15*60: result = 2; break;
+ case 30*60: result = 1; break;
+ case 60*60: result = 3; break;
+ case 3600*2: result = 3; break;
+ case 3600*3: result = 2; break;
+ case 3600*6: result = 1; break;
+ case 3600*12: result = 3; break;
+ case 3600*24: result = 3; break;
+ case 86400*2: result = 1; break;
+ case 86400*5: result = 4; break;
+ case 86400*7: result = 6; break;
+ case 86400*14: result = 1; break;
+ case (int)(86400*30.4375+0.5): result = 3; break;
+ case (int)(86400*30.4375*2+0.5): result = 1; break;
+ case (int)(86400*30.4375*3+0.5): result = 2; break;
+ case (int)(86400*30.4375*6+0.5): result = 5; break;
+ case (int)(86400*30.4375*12+0.5): result = 3; break;
+ }
+ return result;
+}
+
+/*! \internal
+
+ Generates a date/time tick label for tick coordinate \a tick, based on the currently set format
+ (\ref setDateTimeFormat) and time spec (\ref setDateTimeSpec).
+
+ \seebaseclassmethod
+*/
+QString QCPAxisTickerDateTime::getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision)
+{
+ Q_UNUSED(precision)
+ Q_UNUSED(formatChar)
+ return locale.toString(keyToDateTime(tick).toTimeSpec(mDateTimeSpec), mDateTimeFormat);
+}
+
+/*! \internal
+
+ Uses the passed \a tickStep as a guiding value and applies corrections in order to obtain
+ non-uniform tick intervals but intuitive tick labels, e.g. falling on the same day of each month.
+
+ \seebaseclassmethod
+*/
+QVector<double> QCPAxisTickerDateTime::createTickVector(double tickStep, const QCPRange &range)
+{
+ QVector<double> result = QCPAxisTicker::createTickVector(tickStep, range);
+ if (!result.isEmpty())
+ {
+ if (mDateStrategy == dsUniformTimeInDay)
+ {
+ QDateTime uniformDateTime = keyToDateTime(mTickOrigin); // the time of this datetime will be set for all other ticks, if possible
+ QDateTime tickDateTime;
+ for (int i=0; i<result.size(); ++i)
+ {
+ tickDateTime = keyToDateTime(result.at(i));
+ tickDateTime.setTime(uniformDateTime.time());
+ result[i] = dateTimeToKey(tickDateTime);
+ }
+ } else if (mDateStrategy == dsUniformDayInMonth)
+ {
+ QDateTime uniformDateTime = keyToDateTime(mTickOrigin); // this day (in month) and time will be set for all other ticks, if possible
+ QDateTime tickDateTime;
+ for (int i=0; i<result.size(); ++i)
+ {
+ tickDateTime = keyToDateTime(result.at(i));
+ tickDateTime.setTime(uniformDateTime.time());
+ 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)
+ 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
+ tickDateTime = tickDateTime.addMonths(1);
+ 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
+ tickDateTime = tickDateTime.addMonths(-1);
+ tickDateTime.setDate(QDate(tickDateTime.date().year(), tickDateTime.date().month(), thisUniformDay));
+ result[i] = dateTimeToKey(tickDateTime);
+ }
+ }
+ }
+ return result;
+}
+
+/*!
+ A convenience method which turns \a key (in seconds since Epoch 1. Jan 1970, 00:00 UTC) into a
+ QDateTime object. This can be used to turn axis coordinates to actual QDateTimes.
+
+ The accuracy achieved by this method is one millisecond, irrespective of the used Qt version (it
+ works around the lack of a QDateTime::fromMSecsSinceEpoch in Qt 4.6)
+
+ \see dateTimeToKey
+*/
+QDateTime QCPAxisTickerDateTime::keyToDateTime(double key)
+{
+# if QT_VERSION < QT_VERSION_CHECK(4, 7, 0)
+ return QDateTime::fromTime_t(key).addMSecs((key-(qint64)key)*1000);
+# else
+ return QDateTime::fromMSecsSinceEpoch(key*1000.0);
+# endif
+}
+
+/*! \overload
+
+ A convenience method which turns a QDateTime object into a double value that corresponds to
+ seconds since Epoch (1. Jan 1970, 00:00 UTC). This is the format used as axis coordinates by
+ QCPAxisTickerDateTime.
+
+ The accuracy achieved by this method is one millisecond, irrespective of the used Qt version (it
+ works around the lack of a QDateTime::toMSecsSinceEpoch in Qt 4.6)
+
+ \see keyToDateTime
+*/
+double QCPAxisTickerDateTime::dateTimeToKey(const QDateTime dateTime)
+{
+# if QT_VERSION < QT_VERSION_CHECK(4, 7, 0)
+ return dateTime.toTime_t()+dateTime.time().msec()/1000.0;
+# else
+ return dateTime.toMSecsSinceEpoch()/1000.0;
+# endif
+}
+
+/*! \overload
+
+ A convenience method which turns a QDate object into a double value that corresponds to
+ seconds since Epoch (1. Jan 1970, 00:00 UTC). This is the format used as axis coordinates by
+ QCPAxisTickerDateTime.
+
+ \see keyToDateTime
+*/
+double QCPAxisTickerDateTime::dateTimeToKey(const QDate date)
{
- draw(painter, pos, QVector2D(qCos(angle), qSin(angle)));
+# if QT_VERSION < QT_VERSION_CHECK(4, 7, 0)
+ return QDateTime(date).toTime_t();
+# else
+ return QDateTime(date).toMSecsSinceEpoch()/1000.0;
+# endif
}
+/* end of 'src/axis/axistickerdatetime.cpp' */
+
+
+/* including file 'src/axis/axistickertime.cpp', size 11747 */
+/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
+
+////////////////////////////////////////////////////////////////////////////////////////////////////
+//////////////////// QCPAxisTickerTime
+////////////////////////////////////////////////////////////////////////////////////////////////////
+/*! \class QCPAxisTickerTime
+ \brief Specialized axis ticker for time spans in units of milliseconds to days
+
+ \image html axisticker-time.png
+
+ This QCPAxisTicker subclass generates ticks that corresponds to time intervals.
+
+ The format of the time display in the tick labels is controlled with \ref setTimeFormat and \ref
+ setFieldWidth. The time coordinate is in the unit of seconds with respect to the time coordinate
+ zero. Unlike with QCPAxisTickerDateTime, the ticks don't correspond to a specific calendar date
+ and time.
+
+ The time can be displayed in milliseconds, seconds, minutes, hours and days. Depending on the
+ largest available unit in the format specified with \ref setTimeFormat, any time spans above will
+ be carried in that largest unit. So for example if the format string is "%m:%s" and a tick at
+ coordinate value 7815 (being 2 hours, 10 minutes and 15 seconds) is created, the resulting tick
+ label will show "130:15" (130 minutes, 15 seconds). If the format string is "%h:%m:%s", the hour
+ unit will be used and the label will thus be "02:10:15". Negative times with respect to the axis
+ zero will carry a leading minus sign.
+
+ The ticker can be created and assigned to an axis like this:
+ \snippet documentation/doc-image-generator/mainwindow.cpp axistickertime-creation
+
+ Here is an example of a time axis providing time information in days, hours and minutes. Due to
+ the axis range spanning a few days and the wanted tick count (\ref setTickCount), the ticker
+ decided to use tick steps of 12 hours:
+
+ \image html axisticker-time2.png
+
+ The format string for this example is
+ \snippet documentation/doc-image-generator/mainwindow.cpp axistickertime-creation-2
+
+ \note If you rather wish to display calendar dates and times, have a look at QCPAxisTickerDateTime
+ instead.
+*/
+
+/*!
+ Constructs the ticker and sets reasonable default values. Axis tickers are commonly created
+ managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker.
+*/
+QCPAxisTickerTime::QCPAxisTickerTime() :
+ mTimeFormat(QLatin1String("%h:%m:%s")),
+ mSmallestUnit(tuSeconds),
+ mBiggestUnit(tuHours)
+{
+ setTickCount(4);
+ mFieldWidth[tuMilliseconds] = 3;
+ mFieldWidth[tuSeconds] = 2;
+ mFieldWidth[tuMinutes] = 2;
+ mFieldWidth[tuHours] = 2;
+ mFieldWidth[tuDays] = 1;
+
+ mFormatPattern[tuMilliseconds] = QLatin1String("%z");
+ mFormatPattern[tuSeconds] = QLatin1String("%s");
+ mFormatPattern[tuMinutes] = QLatin1String("%m");
+ mFormatPattern[tuHours] = QLatin1String("%h");
+ mFormatPattern[tuDays] = QLatin1String("%d");
+}
+
+/*!
+ Sets the format that will be used to display time in the tick labels.
+
+ The available patterns are:
+ - %%z for milliseconds
+ - %%s for seconds
+ - %%m for minutes
+ - %%h for hours
+ - %%d for days
+
+ The field width (zero padding) can be controlled for each unit with \ref setFieldWidth.
+
+ The largest unit that appears in \a format will carry all the remaining time of a certain tick
+ coordinate, even if it overflows the natural limit of the unit. For example, if %%m is the
+ largest unit it might become larger than 59 in order to consume larger time values. If on the
+ other hand %%h is available, the minutes will wrap around to zero after 59 and the time will
+ carry to the hour digit.
+*/
+void QCPAxisTickerTime::setTimeFormat(const QString &format)
+{
+ mTimeFormat = format;
+
+ // determine smallest and biggest unit in format, to optimize unit replacement and allow biggest
+ // unit to consume remaining time of a tick value and grow beyond its modulo (e.g. min > 59)
+ mSmallestUnit = tuMilliseconds;
+ mBiggestUnit = tuMilliseconds;
+ bool hasSmallest = false;
+ for (int i = tuMilliseconds; i <= tuDays; ++i)
+ {
+ TimeUnit unit = static_cast<TimeUnit>(i);
+ if (mTimeFormat.contains(mFormatPattern.value(unit)))
+ {
+ if (!hasSmallest)
+ {
+ mSmallestUnit = unit;
+ hasSmallest = true;
+ }
+ mBiggestUnit = unit;
+ }
+ }
+}
+
+/*!
+ Sets the field widh of the specified \a unit to be \a width digits, when displayed in the tick
+ label. If the number for the specific unit is shorter than \a width, it will be padded with an
+ according number of zeros to the left in order to reach the field width.
+
+ \see setTimeFormat
+*/
+void QCPAxisTickerTime::setFieldWidth(QCPAxisTickerTime::TimeUnit unit, int width)
+{
+ mFieldWidth[unit] = qMax(width, 1);
+}
+
+/*! \internal
+
+ Returns the tick step appropriate for time displays, depending on the provided \a range and the
+ smallest available time unit in the current format (\ref setTimeFormat). For example if the unit
+ of seconds isn't available in the format, this method will not generate steps (like 2.5 minutes)
+ that require sub-minute precision to be displayed correctly.
+
+ \seebaseclassmethod
+*/
+double QCPAxisTickerTime::getTickStep(const QCPRange &range)
+{
+ double result = range.size()/(double)(mTickCount+1e-10); // mTickCount ticks on average, the small addition is to prevent jitter on exact integers
+
+ if (result < 1) // ideal tick step is below 1 second -> use normal clean mantissa algorithm in units of seconds
+ {
+ if (mSmallestUnit == tuMilliseconds)
+ result = qMax(cleanMantissa(result), 0.001); // smallest tick step is 1 millisecond
+ else // have no milliseconds available in format, so stick with 1 second tickstep
+ result = 1.0;
+ } else if (result < 3600*24) // below a day
+ {
+ // the filling of availableSteps seems a bit contorted but it fills in a sorted fashion and thus saves a post-fill sorting run
+ QVector<double> availableSteps;
+ // seconds range:
+ if (mSmallestUnit <= tuSeconds)
+ availableSteps << 1;
+ if (mSmallestUnit == tuMilliseconds)
+ availableSteps << 2.5; // only allow half second steps if milliseconds are there to display it
+ else if (mSmallestUnit == tuSeconds)
+ availableSteps << 2;
+ if (mSmallestUnit <= tuSeconds)
+ availableSteps << 5 << 10 << 15 << 30;
+ // minutes range:
+ if (mSmallestUnit <= tuMinutes)
+ availableSteps << 1*60;
+ if (mSmallestUnit <= tuSeconds)
+ availableSteps << 2.5*60; // only allow half minute steps if seconds are there to display it
+ else if (mSmallestUnit == tuMinutes)
+ availableSteps << 2*60;
+ if (mSmallestUnit <= tuMinutes)
+ availableSteps << 5*60 << 10*60 << 15*60 << 30*60;
+ // hours range:
+ if (mSmallestUnit <= tuHours)
+ availableSteps << 1*3600 << 2*3600 << 3*3600 << 6*3600 << 12*3600 << 24*3600;
+ // pick available step that is most appropriate to approximate ideal step:
+ result = pickClosest(result, availableSteps);
+ } else // more than a day, go back to normal clean mantissa algorithm but in units of days
+ {
+ const double secondsPerDay = 3600*24;
+ result = cleanMantissa(result/secondsPerDay)*secondsPerDay;
+ }
+ return result;
+}
+
+/*! \internal
+
+ Returns the sub tick count appropriate for the provided \a tickStep and time displays.
+
+ \seebaseclassmethod
+*/
+int QCPAxisTickerTime::getSubTickCount(double tickStep)
+{
+ int result = QCPAxisTicker::getSubTickCount(tickStep);
+ switch (qRound(tickStep)) // hand chosen subticks for specific minute/hour/day range (as specified in getTickStep)
+ {
+ case 5*60: result = 4; break;
+ case 10*60: result = 1; break;
+ case 15*60: result = 2; break;
+ case 30*60: result = 1; break;
+ case 60*60: result = 3; break;
+ case 3600*2: result = 3; break;
+ case 3600*3: result = 2; break;
+ case 3600*6: result = 1; break;
+ case 3600*12: result = 3; break;
+ case 3600*24: result = 3; break;
+ }
+ return result;
+}
+
+/*! \internal
+
+ Returns the tick label corresponding to the provided \a tick and the configured format and field
+ widths (\ref setTimeFormat, \ref setFieldWidth).
+
+ \seebaseclassmethod
+*/
+QString QCPAxisTickerTime::getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision)
+{
+ Q_UNUSED(precision)
+ Q_UNUSED(formatChar)
+ Q_UNUSED(locale)
+ bool negative = tick < 0;
+ if (negative) tick *= -1;
+ double values[tuDays+1]; // contains the msec/sec/min/... value with its respective modulo (e.g. minute 0..59)
+ double restValues[tuDays+1]; // contains the msec/sec/min/... value as if it's the largest available unit and thus consumes the remaining time
+
+ restValues[tuMilliseconds] = tick*1000;
+ values[tuMilliseconds] = modf(restValues[tuMilliseconds]/1000, &restValues[tuSeconds])*1000;
+ values[tuSeconds] = modf(restValues[tuSeconds]/60, &restValues[tuMinutes])*60;
+ values[tuMinutes] = modf(restValues[tuMinutes]/60, &restValues[tuHours])*60;
+ values[tuHours] = modf(restValues[tuHours]/24, &restValues[tuDays])*24;
+ // no need to set values[tuDays] because days are always a rest value (there is no higher unit so it consumes all remaining time)
+
+ QString result = mTimeFormat;
+ for (int i = mSmallestUnit; i <= mBiggestUnit; ++i)
+ {
+ TimeUnit iUnit = static_cast<TimeUnit>(i);
+ replaceUnit(result, iUnit, qRound(iUnit == mBiggestUnit ? restValues[iUnit] : values[iUnit]));
+ }
+ if (negative)
+ result.prepend(QLatin1Char('-'));
+ return result;
+}
+
+/*! \internal
+
+ Replaces all occurrences of the format pattern belonging to \a unit in \a text with the specified
+ \a value, using the field width as specified with \ref setFieldWidth for the \a unit.
+*/
+void QCPAxisTickerTime::replaceUnit(QString &text, QCPAxisTickerTime::TimeUnit unit, int value) const
+{
+ QString valueStr = QString::number(value);
+ while (valueStr.size() < mFieldWidth.value(unit))
+ valueStr.prepend(QLatin1Char('0'));
+
+ text.replace(mFormatPattern.value(unit), valueStr);
+}
+/* end of 'src/axis/axistickertime.cpp' */
+
+
+/* including file 'src/axis/axistickerfixed.cpp', size 5583 */
+/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
+
+////////////////////////////////////////////////////////////////////////////////////////////////////
+//////////////////// QCPAxisTickerFixed
+////////////////////////////////////////////////////////////////////////////////////////////////////
+/*! \class QCPAxisTickerFixed
+ \brief Specialized axis ticker with a fixed tick step
+
+ \image html axisticker-fixed.png
+
+ This QCPAxisTicker subclass generates ticks with a fixed tick step set with \ref setTickStep. It
+ is also possible to allow integer multiples and integer powers of the specified tick step with
+ \ref setScaleStrategy.
+
+ A typical application of this ticker is to make an axis only display integers, by setting the
+ tick step of the ticker to 1.0 and the scale strategy to \ref ssMultiples.
+
+ Another case is when a certain number has a special meaning and axis ticks should only appear at
+ multiples of that value. In this case you might also want to consider \ref QCPAxisTickerPi
+ because despite the name it is not limited to only pi symbols/values.
+
+ The ticker can be created and assigned to an axis like this:
+ \snippet documentation/doc-image-generator/mainwindow.cpp axistickerfixed-creation
+*/
+
+/*!
+ Constructs the ticker and sets reasonable default values. Axis tickers are commonly created
+ managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker.
+*/
+QCPAxisTickerFixed::QCPAxisTickerFixed() :
+ mTickStep(1.0),
+ mScaleStrategy(ssNone)
+{
+}
+
+/*!
+ Sets the fixed tick interval to \a step.
+
+ The axis ticker will only use this tick step when generating axis ticks. This might cause a very
+ high tick density and overlapping labels if the axis range is zoomed out. Using \ref
+ setScaleStrategy it is possible to relax the fixed step and also allow multiples or powers of \a
+ step. This will enable the ticker to reduce the number of ticks to a reasonable amount (see \ref
+ setTickCount).
+*/
+void QCPAxisTickerFixed::setTickStep(double step)
+{
+ if (step > 0)
+ mTickStep = step;
+ else
+ qDebug() << Q_FUNC_INFO << "tick step must be greater than zero:" << step;
+}
+
+/*!
+ Sets whether the specified tick step (\ref setTickStep) is absolutely fixed or whether
+ modifications may be applied to it before calculating the finally used tick step, such as
+ permitting multiples or powers. See \ref ScaleStrategy for details.
+
+ The default strategy is \ref ssNone, which means the tick step is absolutely fixed.
+*/
+void QCPAxisTickerFixed::setScaleStrategy(QCPAxisTickerFixed::ScaleStrategy strategy)
+{
+ mScaleStrategy = strategy;
+}
+
+/*! \internal
+
+ Determines the actually used tick step from the specified tick step and scale strategy (\ref
+ setTickStep, \ref setScaleStrategy).
+
+ This method either returns the specified tick step exactly, or, if the scale strategy is not \ref
+ ssNone, a modification of it to allow varying the number of ticks in the current axis range.
+
+ \seebaseclassmethod
+*/
+double QCPAxisTickerFixed::getTickStep(const QCPRange &range)
+{
+ switch (mScaleStrategy)
+ {
+ case ssNone:
+ {
+ return mTickStep;
+ }
+ case ssMultiples:
+ {
+ double exactStep = range.size()/(double)(mTickCount+1e-10); // mTickCount ticks on average, the small addition is to prevent jitter on exact integers
+ if (exactStep < mTickStep)
+ return mTickStep;
+ else
+ return (qint64)(cleanMantissa(exactStep/mTickStep)+0.5)*mTickStep;
+ }
+ case ssPowers:
+ {
+ double exactStep = range.size()/(double)(mTickCount+1e-10); // mTickCount ticks on average, the small addition is to prevent jitter on exact integers
+ return qPow(mTickStep, (int)(qLn(exactStep)/qLn(mTickStep)+0.5));
+ }
+ }
+ return mTickStep;
+}
+/* end of 'src/axis/axistickerfixed.cpp' */
+
+
+/* including file 'src/axis/axistickertext.cpp', size 8653 */
+/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
+
+////////////////////////////////////////////////////////////////////////////////////////////////////
+//////////////////// QCPAxisTickerText
+////////////////////////////////////////////////////////////////////////////////////////////////////
+/*! \class QCPAxisTickerText
+ \brief Specialized axis ticker which allows arbitrary labels at specified coordinates
+
+ \image html axisticker-text.png
+
+ This QCPAxisTicker subclass generates ticks which can be directly specified by the user as
+ coordinates and associated strings. They can be passed as a whole with \ref setTicks or one at a
+ time with \ref addTick. Alternatively you can directly access the internal storage via \ref ticks
+ and modify the tick/label data there.
+
+ This is useful for cases where the axis represents categories rather than numerical values.
+
+ If you are updating the ticks of this ticker regularly and in a dynamic fasion (e.g. dependent on
+ the axis range), it is a sign that you should probably create an own ticker by subclassing
+ QCPAxisTicker, instead of using this one.
+
+ The ticker can be created and assigned to an axis like this:
+ \snippet documentation/doc-image-generator/mainwindow.cpp axistickertext-creation
+*/
+
+/* start of documentation of inline functions */
+
+/*! \fn QMap<double, QString> &QCPAxisTickerText::ticks()
+
+ Returns a non-const reference to the internal map which stores the tick coordinates and their
+ labels.
+
+ You can access the map directly in order to add, remove or manipulate ticks, as an alternative to
+ using the methods provided by QCPAxisTickerText, such as \ref setTicks and \ref addTick.
+*/
+
+/* end of documentation of inline functions */
+
+/*!
+ Constructs the ticker and sets reasonable default values. Axis tickers are commonly created
+ managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker.
+*/
+QCPAxisTickerText::QCPAxisTickerText() :
+ mSubTickCount(0)
+{
+}
+
+/*! \overload
+
+ Sets the ticks that shall appear on the axis. The map key of \a ticks corresponds to the axis
+ coordinate, and the map value is the string that will appear as tick label.
+
+ An alternative to manipulate ticks is to directly access the internal storage with the \ref ticks
+ getter.
+
+ \see addTicks, addTick, clear
+*/
+void QCPAxisTickerText::setTicks(const QMap<double, QString> &ticks)
+{
+ mTicks = ticks;
+}
+
+/*! \overload
+
+ Sets the ticks that shall appear on the axis. The entries of \a positions correspond to the axis
+ coordinates, and the entries of \a labels are the respective strings that will appear as tick
+ labels.
+
+ \see addTicks, addTick, clear
+*/
+void QCPAxisTickerText::setTicks(const QVector<double> &positions, const QVector<QString> labels)
+{
+ clear();
+ addTicks(positions, labels);
+}
+
+/*!
+ Sets the number of sub ticks that shall appear between ticks. For QCPAxisTickerText, there is no
+ automatic sub tick count calculation. So if sub ticks are needed, they must be configured with this
+ method.
+*/
+void QCPAxisTickerText::setSubTickCount(int subTicks)
+{
+ if (subTicks >= 0)
+ mSubTickCount = subTicks;
+ else
+ qDebug() << Q_FUNC_INFO << "sub tick count can't be negative:" << subTicks;
+}
+
+/*!
+ Clears all ticks.
+
+ An alternative to manipulate ticks is to directly access the internal storage with the \ref ticks
+ getter.
+
+ \see setTicks, addTicks, addTick
+*/
+void QCPAxisTickerText::clear()
+{
+ mTicks.clear();
+}
+
+/*!
+ Adds a single tick to the axis at the given axis coordinate \a position, with the provided tick \a
+ label.
+
+ \see addTicks, setTicks, clear
+*/
+void QCPAxisTickerText::addTick(double position, QString label)
+{
+ mTicks.insert(position, label);
+}
+
+/*! \overload
+
+ Adds the provided \a ticks to the ones already existing. The map key of \a ticks corresponds to
+ the axis coordinate, and the map value is the string that will appear as tick label.
+
+ An alternative to manipulate ticks is to directly access the internal storage with the \ref ticks
+ getter.
+
+ \see addTick, setTicks, clear
+*/
+void QCPAxisTickerText::addTicks(const QMap<double, QString> &ticks)
+{
+ mTicks.unite(ticks);
+}
+
+/*! \overload
+
+ Adds the provided ticks to the ones already existing. The entries of \a positions correspond to
+ the axis coordinates, and the entries of \a labels are the respective strings that will appear as
+ tick labels.
+
+ An alternative to manipulate ticks is to directly access the internal storage with the \ref ticks
+ getter.
+
+ \see addTick, setTicks, clear
+*/
+void QCPAxisTickerText::addTicks(const QVector<double> &positions, const QVector<QString> &labels)
+{
+ if (positions.size() != labels.size())
+ qDebug() << Q_FUNC_INFO << "passed unequal length vectors for positions and labels:" << positions.size() << labels.size();
+ int n = qMin(positions.size(), labels.size());
+ for (int i=0; i<n; ++i)
+ mTicks.insert(positions.at(i), labels.at(i));
+}
+
+/*!
+ Since the tick coordinates are provided externally, this method implementation does nothing.
+
+ \seebaseclassmethod
+*/
+double QCPAxisTickerText::getTickStep(const QCPRange &range)
+{
+ // text axis ticker has manual tick positions, so doesn't need this method
+ Q_UNUSED(range)
+ return 1.0;
+}
+
+/*!
+ Returns the sub tick count that was configured with \ref setSubTickCount.
+
+ \seebaseclassmethod
+*/
+int QCPAxisTickerText::getSubTickCount(double tickStep)
+{
+ Q_UNUSED(tickStep)
+ return mSubTickCount;
+}
+
+/*!
+ Returns the tick label which corresponds to the key \a tick in the internal tick storage. Since
+ the labels are provided externally, \a locale, \a formatChar, and \a precision are ignored.
+
+ \seebaseclassmethod
+*/
+QString QCPAxisTickerText::getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision)
+{
+ Q_UNUSED(locale)
+ Q_UNUSED(formatChar)
+ Q_UNUSED(precision)
+ return mTicks.value(tick);
+}
+
+/*!
+ Returns the externally provided tick coordinates which are in the specified \a range. If
+ available, one tick above and below the range is provided in addition, to allow possible sub tick
+ calculation. The parameter \a tickStep is ignored.
+
+ \seebaseclassmethod
+*/
+QVector<double> QCPAxisTickerText::createTickVector(double tickStep, const QCPRange &range)
+{
+ Q_UNUSED(tickStep)
+ QVector<double> result;
+ if (mTicks.isEmpty())
+ return result;
+
+ QMap<double, QString>::const_iterator start = mTicks.lowerBound(range.lower);
+ QMap<double, QString>::const_iterator end = mTicks.upperBound(range.upper);
+ // this method should try to give one tick outside of range so proper subticks can be generated:
+ if (start != mTicks.constBegin()) --start;
+ if (end != mTicks.constEnd()) ++end;
+ for (QMap<double, QString>::const_iterator it = start; it != end; ++it)
+ result.append(it.key());
+
+ return result;
+}
+/* end of 'src/axis/axistickertext.cpp' */
+
+
+/* including file 'src/axis/axistickerpi.cpp', size 11170 */
+/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
+
+////////////////////////////////////////////////////////////////////////////////////////////////////
+//////////////////// QCPAxisTickerPi
+////////////////////////////////////////////////////////////////////////////////////////////////////
+/*! \class QCPAxisTickerPi
+ \brief Specialized axis ticker to display ticks in units of an arbitrary constant, for example pi
+
+ \image html axisticker-pi.png
+
+ This QCPAxisTicker subclass generates ticks that are expressed with respect to a given symbolic
+ constant with a numerical value specified with \ref setPiValue and an appearance in the tick
+ labels specified with \ref setPiSymbol.
+
+ Ticks may be generated at fractions of the symbolic constant. How these fractions appear in the
+ tick label can be configured with \ref setFractionStyle.
+
+ The ticker can be created and assigned to an axis like this:
+ \snippet documentation/doc-image-generator/mainwindow.cpp axistickerpi-creation
+*/
+
+/*!
+ Constructs the ticker and sets reasonable default values. Axis tickers are commonly created
+ managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker.
+*/
+QCPAxisTickerPi::QCPAxisTickerPi() :
+ mPiSymbol(QLatin1String(" ")+QChar(0x03C0)),
+ mPiValue(M_PI),
+ mPeriodicity(0),
+ mFractionStyle(fsUnicodeFractions),
+ mPiTickStep(0)
+{
+ setTickCount(4);
+}
+
+/*!
+ Sets how the symbol part (which is always a suffix to the number) shall appear in the axis tick
+ label.
+
+ If a space shall appear between the number and the symbol, make sure the space is contained in \a
+ symbol.
+*/
+void QCPAxisTickerPi::setPiSymbol(QString symbol)
+{
+ mPiSymbol = symbol;
+}
+
+/*!
+ Sets the numerical value that the symbolic constant has.
+
+ This will be used to place the appropriate fractions of the symbol at the respective axis
+ coordinates.
+*/
+void QCPAxisTickerPi::setPiValue(double pi)
+{
+ mPiValue = pi;
+}
+
+/*!
+ Sets whether the axis labels shall appear periodicly and if so, at which multiplicity of the
+ symbolic constant.
+
+ To disable periodicity, set \a multiplesOfPi to zero.
+
+ For example, an axis that identifies 0 with 2pi would set \a multiplesOfPi to two.
+*/
+void QCPAxisTickerPi::setPeriodicity(int multiplesOfPi)
+{
+ mPeriodicity = qAbs(multiplesOfPi);
+}
+
+/*!
+ Sets how the numerical/fractional part preceding the symbolic constant is displayed in tick
+ labels. See \ref FractionStyle for the various options.
+*/
+void QCPAxisTickerPi::setFractionStyle(QCPAxisTickerPi::FractionStyle style)
+{
+ mFractionStyle = style;
+}
+
+/*! \internal
+
+ Returns the tick step, using the constant's value (\ref setPiValue) as base unit. In consequence
+ the numerical/fractional part preceding the symbolic constant is made to have a readable
+ mantissa.
+
+ \seebaseclassmethod
+*/
+double QCPAxisTickerPi::getTickStep(const QCPRange &range)
+{
+ mPiTickStep = range.size()/mPiValue/(double)(mTickCount+1e-10); // mTickCount ticks on average, the small addition is to prevent jitter on exact integers
+ mPiTickStep = cleanMantissa(mPiTickStep);
+ return mPiTickStep*mPiValue;
+}
+
+/*! \internal
+
+ Returns the sub tick count, using the constant's value (\ref setPiValue) as base unit. In
+ consequence the sub ticks divide the numerical/fractional part preceding the symbolic constant
+ reasonably, and not the total tick coordinate.
+
+ \seebaseclassmethod
+*/
+int QCPAxisTickerPi::getSubTickCount(double tickStep)
+{
+ return QCPAxisTicker::getSubTickCount(tickStep/mPiValue);
+}
+
+/*! \internal
+
+ Returns the tick label as a fractional/numerical part and a symbolic string as suffix. The
+ formatting of the fraction is done according to the specified \ref setFractionStyle. The appended
+ symbol is specified with \ref setPiSymbol.
+
+ \seebaseclassmethod
+*/
+QString QCPAxisTickerPi::getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision)
+{
+ double tickInPis = tick/mPiValue;
+ if (mPeriodicity > 0)
+ tickInPis = fmod(tickInPis, mPeriodicity);
+
+ if (mFractionStyle != fsFloatingPoint && mPiTickStep > 0.09 && mPiTickStep < 50)
+ {
+ // simply construct fraction from decimal like 1.234 -> 1234/1000 and then simplify fraction, smaller digits are irrelevant due to mPiTickStep conditional above
+ int denominator = 1000;
+ int numerator = qRound(tickInPis*denominator);
+ simplifyFraction(numerator, denominator);
+ if (qAbs(numerator) == 1 && denominator == 1)
+ return (numerator < 0 ? QLatin1String("-") : QLatin1String("")) + mPiSymbol.trimmed();
+ else if (numerator == 0)
+ return QLatin1String("0");
+ else
+ return fractionToString(numerator, denominator) + mPiSymbol;
+ } else
+ {
+ if (qFuzzyIsNull(tickInPis))
+ return QLatin1String("0");
+ else if (qFuzzyCompare(qAbs(tickInPis), 1.0))
+ return (tickInPis < 0 ? QLatin1String("-") : QLatin1String("")) + mPiSymbol.trimmed();
+ else
+ return QCPAxisTicker::getTickLabel(tickInPis, locale, formatChar, precision) + mPiSymbol;
+ }
+}
+
+/*! \internal
+
+ Takes the fraction given by \a numerator and \a denominator and modifies the values to make sure
+ the fraction is in irreducible form, i.e. numerator and denominator don't share any common
+ factors which could be cancelled.
+*/
+void QCPAxisTickerPi::simplifyFraction(int &numerator, int &denominator) const
+{
+ if (numerator == 0 || denominator == 0)
+ return;
+
+ int num = numerator;
+ int denom = denominator;
+ while (denom != 0) // euclidean gcd algorithm
+ {
+ int oldDenom = denom;
+ denom = num % denom;
+ num = oldDenom;
+ }
+ // num is now gcd of numerator and denominator
+ numerator /= num;
+ denominator /= num;
+}
+
+/*! \internal
+
+ Takes the fraction given by \a numerator and \a denominator and returns a string representation.
+ The result depends on the configured fraction style (\ref setFractionStyle).
+
+ This method is used to format the numerical/fractional part when generating tick labels. It
+ simplifies the passed fraction to an irreducible form using \ref simplifyFraction and factors out
+ any integer parts of the fraction (e.g. "10/4" becomes "2 1/2").
+*/
+QString QCPAxisTickerPi::fractionToString(int numerator, int denominator) const
+{
+ if (denominator == 0)
+ {
+ qDebug() << Q_FUNC_INFO << "called with zero denominator";
+ return QString();
+ }
+ if (mFractionStyle == fsFloatingPoint) // should never be the case when calling this function
+ {
+ qDebug() << Q_FUNC_INFO << "shouldn't be called with fraction style fsDecimal";
+ return QString::number(numerator/(double)denominator); // failsafe
+ }
+ int sign = numerator*denominator < 0 ? -1 : 1;
+ numerator = qAbs(numerator);
+ denominator = qAbs(denominator);
+
+ if (denominator == 1)
+ {
+ return QString::number(sign*numerator);
+ } else
+ {
+ int integerPart = numerator/denominator;
+ int remainder = numerator%denominator;
+ if (remainder == 0)
+ {
+ return QString::number(sign*integerPart);
+ } else
+ {
+ if (mFractionStyle == fsAsciiFractions)
+ {
+ return QString(QLatin1String("%1%2%3/%4"))
+ .arg(sign == -1 ? QLatin1String("-") : QLatin1String(""))
+ .arg(integerPart > 0 ? (QString::number(integerPart)+QLatin1String(" ")) : QString(""))
+ .arg(remainder)
+ .arg(denominator);
+ } else if (mFractionStyle == fsUnicodeFractions)
+ {
+ return QString(QLatin1String("%1%2%3"))
+ .arg(sign == -1 ? QLatin1String("-") : QLatin1String(""))
+ .arg(integerPart > 0 ? QString::number(integerPart) : QLatin1String(""))
+ .arg(unicodeFraction(remainder, denominator));
+ }
+ }
+ }
+ return QString();
+}
+
+/*! \internal
+
+ Returns the unicode string representation of the fraction given by \a numerator and \a
+ denominator. This is the representation used in \ref fractionToString when the fraction style
+ (\ref setFractionStyle) is \ref fsUnicodeFractions.
+
+ This method doesn't use the single-character common fractions but builds each fraction from a
+ superscript unicode number, the unicode fraction character, and a subscript unicode number.
+*/
+QString QCPAxisTickerPi::unicodeFraction(int numerator, int denominator) const
+{
+ return unicodeSuperscript(numerator)+QChar(0x2044)+unicodeSubscript(denominator);
+}
+
+/*! \internal
+
+ Returns the unicode string representing \a number as superscript. This is used to build
+ unicode fractions in \ref unicodeFraction.
+*/
+QString QCPAxisTickerPi::unicodeSuperscript(int number) const
+{
+ if (number == 0)
+ return QString(QChar(0x2070));
+
+ QString result;
+ while (number > 0)
+ {
+ const int digit = number%10;
+ switch (digit)
+ {
+ case 1: { result.prepend(QChar(0x00B9)); break; }
+ case 2: { result.prepend(QChar(0x00B2)); break; }
+ case 3: { result.prepend(QChar(0x00B3)); break; }
+ default: { result.prepend(QChar(0x2070+digit)); break; }
+ }
+ number /= 10;
+ }
+ return result;
+}
+
+/*! \internal
+
+ Returns the unicode string representing \a number as subscript. This is used to build unicode
+ fractions in \ref unicodeFraction.
+*/
+QString QCPAxisTickerPi::unicodeSubscript(int number) const
+{
+ if (number == 0)
+ return QString(QChar(0x2080));
+
+ QString result;
+ while (number > 0)
+ {
+ result.prepend(QChar(0x2080+number%10));
+ number /= 10;
+ }
+ return result;
+}
+/* end of 'src/axis/axistickerpi.cpp' */
+
+
+/* including file 'src/axis/axistickerlog.cpp', size 7106 */
+/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
+
+////////////////////////////////////////////////////////////////////////////////////////////////////
+//////////////////// QCPAxisTickerLog
+////////////////////////////////////////////////////////////////////////////////////////////////////
+/*! \class QCPAxisTickerLog
+ \brief Specialized axis ticker suited for logarithmic axes
+
+ \image html axisticker-log.png
+
+ This QCPAxisTicker subclass generates ticks with unequal tick intervals suited for logarithmic
+ axis scales. The ticks are placed at powers of the specified log base (\ref setLogBase).
+
+ Especially in the case of a log base equal to 10 (the default), it might be desirable to have
+ tick labels in the form of powers of ten without mantissa display. To achieve this, set the
+ number precision (\ref QCPAxis::setNumberPrecision) to zero and the number format (\ref
+ QCPAxis::setNumberFormat) to scientific (exponential) display with beautifully typeset decimal
+ powers, so a format string of <tt>"eb"</tt>. This will result in the following axis tick labels:
+
+ \image html axisticker-log-powers.png
+
+ The ticker can be created and assigned to an axis like this:
+ \snippet documentation/doc-image-generator/mainwindow.cpp axistickerlog-creation
+*/
+
+/*!
+ Constructs the ticker and sets reasonable default values. Axis tickers are commonly created
+ managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker.
+*/
+QCPAxisTickerLog::QCPAxisTickerLog() :
+ mLogBase(10.0),
+ mSubTickCount(8), // generates 10 intervals
+ mLogBaseLnInv(1.0/qLn(mLogBase))
+{
+}
+
+/*!
+ Sets the logarithm base used for tick coordinate generation. The ticks will be placed at integer
+ powers of \a base.
+*/
+void QCPAxisTickerLog::setLogBase(double base)
+{
+ if (base > 0)
+ {
+ mLogBase = base;
+ mLogBaseLnInv = 1.0/qLn(mLogBase);
+ } else
+ qDebug() << Q_FUNC_INFO << "log base has to be greater than zero:" << base;
+}
+
+/*!
+ Sets the number of sub ticks in a tick interval. Within each interval, the sub ticks are spaced
+ linearly to provide a better visual guide, so the sub tick density increases toward the higher
+ tick.
+
+ Note that \a subTicks is the number of sub ticks (not sub intervals) in one tick interval. So in
+ the case of logarithm base 10 an intuitive sub tick spacing would be achieved with eight sub
+ ticks (the default). This means e.g. between the ticks 10 and 100 there will be eight ticks,
+ namely at 20, 30, 40, 50, 60, 70, 80 and 90.
+*/
+void QCPAxisTickerLog::setSubTickCount(int subTicks)
+{
+ if (subTicks >= 0)
+ mSubTickCount = subTicks;
+ else
+ qDebug() << Q_FUNC_INFO << "sub tick count can't be negative:" << subTicks;
+}
+
+/*! \internal
+
+ Since logarithmic tick steps are necessarily different for each tick interval, this method does
+ nothing in the case of QCPAxisTickerLog
+
+ \seebaseclassmethod
+*/
+double QCPAxisTickerLog::getTickStep(const QCPRange &range)
+{
+ // Logarithmic axis ticker has unequal tick spacing, so doesn't need this method
+ Q_UNUSED(range)
+ return 1.0;
+}
+
+/*! \internal
+
+ Returns the sub tick count specified in \ref setSubTickCount. For QCPAxisTickerLog, there is no
+ automatic sub tick count calculation necessary.
+
+ \seebaseclassmethod
+*/
+int QCPAxisTickerLog::getSubTickCount(double tickStep)
+{
+ Q_UNUSED(tickStep)
+ return mSubTickCount;
+}
+
+/*! \internal
+
+ Creates ticks with a spacing given by the logarithm base and an increasing integer power in the
+ provided \a range. The step in which the power increases tick by tick is chosen in order to keep
+ the total number of ticks as close as possible to the tick count (\ref setTickCount). The
+ parameter \a tickStep is ignored for QCPAxisTickerLog
+
+ \seebaseclassmethod
+*/
+QVector<double> QCPAxisTickerLog::createTickVector(double tickStep, const QCPRange &range)
+{
+ Q_UNUSED(tickStep)
+ QVector<double> result;
+ if (range.lower > 0 && range.upper > 0) // positive range
+ {
+ double exactPowerStep = qLn(range.upper/range.lower)*mLogBaseLnInv/(double)(mTickCount+1e-10);
+ double newLogBase = qPow(mLogBase, qMax((int)cleanMantissa(exactPowerStep), 1));
+ double currentTick = qPow(newLogBase, qFloor(qLn(range.lower)/qLn(newLogBase)));
+ result.append(currentTick);
+ while (currentTick < range.upper && currentTick > 0) // currentMag might be zero for ranges ~1e-300, just cancel in that case
+ {
+ currentTick *= newLogBase;
+ result.append(currentTick);
+ }
+ } else if (range.lower < 0 && range.upper < 0) // negative range
+ {
+ double exactPowerStep = qLn(range.lower/range.upper)*mLogBaseLnInv/(double)(mTickCount+1e-10);
+ double newLogBase = qPow(mLogBase, qMax((int)cleanMantissa(exactPowerStep), 1));
+ double currentTick = -qPow(newLogBase, qCeil(qLn(-range.lower)/qLn(newLogBase)));
+ result.append(currentTick);
+ while (currentTick < range.upper && currentTick < 0) // currentMag might be zero for ranges ~1e-300, just cancel in that case
+ {
+ currentTick /= newLogBase;
+ result.append(currentTick);
+ }
+ } else // invalid range for logarithmic scale, because lower and upper have different sign
+ {
+ qDebug() << Q_FUNC_INFO << "Invalid range for logarithmic plot: " << range.lower << ".." << range.upper;
+ }
+
+ return result;
+}
+/* end of 'src/axis/axistickerlog.cpp' */
+
+
+/* including file 'src/axis/axis.cpp', size 94458 */
+/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
////////////////////////////////////////////////////////////////////////////////////////////////////
@@ -3771,7 +7136,7 @@ void QCPGrid::draw(QCPPainter *painter)
{
if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; }
- if (mSubGridVisible)
+ if (mParentAxis->subTicks() && mSubGridVisible)
drawSubGridLines(painter);
drawGridLines(painter);
}
@@ -3786,8 +7151,7 @@ void QCPGrid::drawGridLines(QCPPainter *painter) const
{
if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; }
- int lowTick = mParentAxis->mLowestVisibleTick;
- int highTick = mParentAxis->mHighestVisibleTick;
+ const int tickCount = mParentAxis->mTickVector.size();
double t; // helper variable, result of coordinate-to-pixel transforms
if (mParentAxis->orientation() == Qt::Horizontal)
{
@@ -3798,7 +7162,7 @@ void QCPGrid::drawGridLines(QCPPainter *painter) const
applyAntialiasingHint(painter, mAntialiasedZeroLine, QCP::aeZeroLine);
painter->setPen(mZeroLinePen);
double epsilon = mParentAxis->range().size()*1E-6; // for comparing double to zero
- for (int i=lowTick; i <= highTick; ++i)
+ for (int i=0; i<tickCount; ++i)
{
if (qAbs(mParentAxis->mTickVector.at(i)) < epsilon)
{
@@ -3812,7 +7176,7 @@ void QCPGrid::drawGridLines(QCPPainter *painter) const
// draw grid lines:
applyDefaultAntialiasingHint(painter);
painter->setPen(mPen);
- for (int i=lowTick; i <= highTick; ++i)
+ for (int i=0; i<tickCount; ++i)
{
if (i == zeroLineIndex) continue; // don't draw a gridline on top of the zeroline
t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // x
@@ -3827,7 +7191,7 @@ void QCPGrid::drawGridLines(QCPPainter *painter) const
applyAntialiasingHint(painter, mAntialiasedZeroLine, QCP::aeZeroLine);
painter->setPen(mZeroLinePen);
double epsilon = mParentAxis->mRange.size()*1E-6; // for comparing double to zero
- for (int i=lowTick; i <= highTick; ++i)
+ for (int i=0; i<tickCount; ++i)
{
if (qAbs(mParentAxis->mTickVector.at(i)) < epsilon)
{
@@ -3841,7 +7205,7 @@ void QCPGrid::drawGridLines(QCPPainter *painter) const
// draw grid lines:
applyDefaultAntialiasingHint(painter);
painter->setPen(mPen);
- for (int i=lowTick; i <= highTick; ++i)
+ for (int i=0; i<tickCount; ++i)
{
if (i == zeroLineIndex) continue; // don't draw a gridline on top of the zeroline
t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // y
@@ -3900,17 +7264,21 @@ void QCPGrid::drawSubGridLines(QCPPainter *painter) const
\image html AxisRectSpacingOverview.png
<center>Overview of the spacings and paddings that define the geometry of an axis. The dashed gray line
on the left represents the QCustomPlot widget border.</center>
-
+
+ Each axis holds an instance of QCPAxisTicker which is used to generate the tick coordinates and
+ tick labels. You can access the currently installed \ref ticker or set a new one (possibly one of
+ the specialized subclasses, or your own subclass) via \ref setTicker. For details, see the
+ documentation of QCPAxisTicker.
*/
/* start of documentation of inline functions */
/*! \fn Qt::Orientation QCPAxis::orientation() const
-
+
Returns the orientation of this axis. The axis orientation (horizontal or vertical) is deduced
from the axis type (left, top, right or bottom).
-
- \see orientation(AxisType type)
+
+ \see orientation(AxisType type), pixelOrientation
*/
/*! \fn QCPGrid *QCPAxis::grid() const
@@ -3920,30 +7288,50 @@ void QCPGrid::drawSubGridLines(QCPPainter *painter) const
*/
/*! \fn static Qt::Orientation QCPAxis::orientation(AxisType type)
-
+
Returns the orientation of the specified axis type
-
- \see orientation()
+
+ \see orientation(), pixelOrientation
*/
-/* end of documentation of inline functions */
-/* start of documentation of signals */
+/*! \fn int QCPAxis::pixelOrientation() const
-/*! \fn void QCPAxis::ticksRequest()
-
- This signal is emitted when \ref setAutoTicks is false and the axis is about to generate tick
- labels for a replot.
-
- Modifying the tick positions can be done with \ref setTickVector. If you also want to control the
- tick labels, set \ref setAutoTickLabels to false and also provide the labels with \ref
- setTickVectorLabels.
-
- If you only want static ticks you probably don't need this signal, since you can just set the
- tick vector (and possibly tick label vector) once. However, if you want to provide ticks (and
- maybe labels) dynamically, e.g. depending on the current axis range, connect a slot to this
- signal and set the vector/vectors there.
+ Returns which direction points towards higher coordinate values/keys, in pixel space.
+
+ This method returns either 1 or -1. If it returns 1, then going in the positive direction along
+ the orientation of the axis in pixels corresponds to going from lower to higher axis coordinates.
+ On the other hand, if this method returns -1, going to smaller pixel values corresponds to going
+ from lower to higher axis coordinates.
+
+ For example, this is useful to easily shift axis coordinates by a certain amount given in pixels,
+ without having to care about reversed or vertically aligned axes:
+
+ \code
+ double newKey = keyAxis->pixelToCoord(keyAxis->coordToPixel(oldKey)+10*keyAxis->pixelOrientation());
+ \endcode
+
+ \a newKey will then contain a key that is ten pixels towards higher keys, starting from \a oldKey.
+*/
+
+/*! \fn QSharedPointer<QCPAxisTicker> QCPAxis::ticker() const
+
+ Returns a modifiable shared pointer to the currently installed axis ticker. The axis ticker is
+ responsible for generating the tick positions and tick labels of this axis. You can access the
+ \ref QCPAxisTicker with this method and modify basic properties such as the approximate tick count
+ (\ref QCPAxisTicker::setTickCount).
+
+ You can gain more control over the axis ticks by setting a different \ref QCPAxisTicker subclass, see
+ the documentation there. A new axis ticker can be set with \ref setTicker.
+
+ Since the ticker is stored in the axis as a shared pointer, multiple axes may share the same axis
+ ticker simply by passing the same shared pointer to multiple axes.
+
+ \see setTicker
*/
+/* end of documentation of inline functions */
+/* start of documentation of signals */
+
/*! \fn void QCPAxis::rangeChanged(const QCPRange &newRange)
This signal is emitted when the range of this axis has changed. You can connect it to the \ref
@@ -3952,11 +7340,10 @@ void QCPGrid::drawSubGridLines(QCPPainter *painter) const
You may also manipulate/correct the range with \ref setRange in a slot connected to this signal.
This is useful if for example a maximum range span shall not be exceeded, or if the lower/upper
- range shouldn't go beyond certain values. For example, the following slot would limit the x axis
- to only positive ranges:
+ range shouldn't go beyond certain values (see \ref QCPRange::bounded). For example, the following
+ slot would limit the x axis to ranges between 0 and 10:
\code
- if (newRange.lower < 0)
- plot->xAxis->setRange(0, newRange.size());
+ customPlot->xAxis->setRange(newRange.bounded(0, 10))
\endcode
*/
@@ -4011,25 +7398,16 @@ QCPAxis::QCPAxis(QCPAxisRect *parent, AxisType type) :
mSelectedLabelColor(Qt::blue),
// tick labels:
mTickLabels(true),
- mAutoTickLabels(true),
- mTickLabelType(ltNumber),
mTickLabelFont(mParentPlot->font()),
mSelectedTickLabelFont(QFont(mTickLabelFont.family(), mTickLabelFont.pointSize(), QFont::Bold)),
mTickLabelColor(Qt::black),
mSelectedTickLabelColor(Qt::blue),
- mDateTimeFormat(QLatin1String("hh:mm:ss\ndd.MM.yy")),
- mDateTimeSpec(Qt::LocalTime),
mNumberPrecision(6),
mNumberFormatChar('g'),
mNumberBeautifulPowers(true),
// ticks and subticks:
mTicks(true),
- mTickStep(1),
- mSubTickCount(4),
- mAutoTickCount(6),
- mAutoTicks(true),
- mAutoTickStep(true),
- mAutoSubTicks(true),
+ mSubTicks(true),
mTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
mSelectedTickPen(QPen(Qt::blue, 2)),
mSubTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
@@ -4038,16 +7416,14 @@ QCPAxis::QCPAxis(QCPAxisRect *parent, AxisType type) :
mRange(0, 5),
mRangeReversed(false),
mScaleType(stLinear),
- mScaleLogBase(10),
- mScaleLogBaseLogInv(1.0/qLn(mScaleLogBase)),
// internal members:
mGrid(new QCPGrid(this)),
mAxisPainter(new QCPAxisPainterPrivate(parent->parentPlot())),
- mLowestVisibleTick(0),
- mHighestVisibleTick(-1),
+ mTicker(new QCPAxisTicker),
mCachedMarginValid(false),
mCachedMargin(0)
{
+ setParent(parent);
mGrid->setVisible(false);
setAntialiased(false);
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
@@ -4158,17 +7534,14 @@ QCPLineEnding QCPAxis::upperEnding() const
}
/*!
- Sets whether the axis uses a linear scale or a logarithmic scale. If \a type is set to \ref
- stLogarithmic, the logarithm base can be set with \ref setScaleLogBase. In logarithmic axis
- scaling, major tick marks appear at all powers of the logarithm base. Properties like tick step
- (\ref setTickStep) don't apply in logarithmic scaling. If you wish a decimal base but less major
- ticks, consider choosing a logarithm base of 100, 1000 or even higher.
+ Sets whether the axis uses a linear scale or a logarithmic scale.
+
+ Note that this method controls the coordinate transformation. You will likely also want to use a
+ logarithmic tick spacing and labeling, which can be achieved by setting an instance of \ref
+ QCPAxisTickerLog via \ref setTicker. See the documentation of \ref QCPAxisTickerLog about the
+ details of logarithmic axis tick creation.
- If \a type is \ref stLogarithmic and the number format (\ref setNumberFormat) uses the 'b' option
- (beautifully typeset decimal powers), the display usually is "1 [multiplication sign] 10
- [superscript] n", which looks unnatural for logarithmic scaling (the "1 [multiplication sign]"
- part). To only display the decimal power, set the number precision to zero with
- \ref setNumberPrecision.
+ \ref setNumberPrecision
*/
void QCPAxis::setScaleType(QCPAxis::ScaleType type)
{
@@ -4183,24 +7556,6 @@ void QCPAxis::setScaleType(QCPAxis::ScaleType type)
}
/*!
- If \ref setScaleType is set to \ref stLogarithmic, \a base will be the logarithm base of the
- scaling. In logarithmic axis scaling, major tick marks appear at all powers of \a base.
-
- Properties like tick step (\ref setTickStep) don't apply in logarithmic scaling. If you wish a decimal base but
- less major ticks, consider choosing \a base 100, 1000 or even higher.
-*/
-void QCPAxis::setScaleLogBase(double base)
-{
- if (base > 1)
- {
- mScaleLogBase = base;
- mScaleLogBaseLogInv = 1.0/qLn(mScaleLogBase); // buffer for faster baseLog() calculation
- mCachedMarginValid = false;
- } else
- qDebug() << Q_FUNC_INFO << "Invalid logarithmic scale base (must be greater 1):" << base;
-}
-
-/*!
Sets the range of the axis.
This slot may be connected with the \ref rangeChanged signal of another axis so this axis
@@ -4222,7 +7577,6 @@ void QCPAxis::setRange(const QCPRange &range)
{
mRange = range.sanitizedForLinScale();
}
- mCachedMarginValid = false;
emit rangeChanged(mRange);
emit rangeChanged(mRange, oldRange);
}
@@ -4295,7 +7649,6 @@ void QCPAxis::setRange(double lower, double upper)
{
mRange = mRange.sanitizedForLinScale();
}
- mCachedMarginValid = false;
emit rangeChanged(mRange);
emit rangeChanged(mRange, oldRange);
}
@@ -4339,7 +7692,6 @@ void QCPAxis::setRangeLower(double lower)
{
mRange = mRange.sanitizedForLinScale();
}
- mCachedMarginValid = false;
emit rangeChanged(mRange);
emit rangeChanged(mRange, oldRange);
}
@@ -4362,7 +7714,6 @@ void QCPAxis::setRangeUpper(double upper)
{
mRange = mRange.sanitizedForLinScale();
}
- mCachedMarginValid = false;
emit rangeChanged(mRange);
emit rangeChanged(mRange, oldRange);
}
@@ -4378,122 +7729,29 @@ void QCPAxis::setRangeUpper(double upper)
*/
void QCPAxis::setRangeReversed(bool reversed)
{
- if (mRangeReversed != reversed)
- {
- mRangeReversed = reversed;
- mCachedMarginValid = false;
- }
+ mRangeReversed = reversed;
}
/*!
- Sets whether the tick positions should be calculated automatically (either from an automatically
- generated tick step or a tick step provided manually via \ref setTickStep, see \ref setAutoTickStep).
+ The axis ticker is responsible for generating the tick positions and tick labels. See the
+ documentation of QCPAxisTicker for details on how to work with axis tickers.
- If \a on is set to false, you must provide the tick positions manually via \ref setTickVector.
- For these manual ticks you may let QCPAxis generate the appropriate labels automatically by
- leaving \ref setAutoTickLabels set to true. If you also wish to control the displayed labels
- manually, set \ref setAutoTickLabels to false and provide the label strings with \ref
- setTickVectorLabels.
+ You can change the tick positioning/labeling behaviour of this axis by setting a different
+ QCPAxisTicker subclass using this method. If you only wish to modify the currently installed axis
+ ticker, access it via \ref ticker.
- If you need dynamically calculated tick vectors (and possibly tick label vectors), set the
- vectors in a slot connected to the \ref ticksRequest signal.
+ Since the ticker is stored in the axis as a shared pointer, multiple axes may share the same axis
+ ticker simply by passing the same shared pointer to multiple axes.
- \see setAutoTickLabels, setAutoSubTicks, setAutoTickCount, setAutoTickStep
+ \see ticker
*/
-void QCPAxis::setAutoTicks(bool on)
+void QCPAxis::setTicker(QSharedPointer<QCPAxisTicker> ticker)
{
- if (mAutoTicks != on)
- {
- mAutoTicks = on;
- mCachedMarginValid = false;
- }
-}
-
-/*!
- When \ref setAutoTickStep is true, \a approximateCount determines how many ticks should be
- generated in the visible range, approximately.
-
- It's not guaranteed that this number of ticks is met exactly, but approximately within a
- tolerance of about two.
-
- Only values greater than zero are accepted as \a approximateCount.
-
- \see setAutoTickStep, setAutoTicks, setAutoSubTicks
-*/
-void QCPAxis::setAutoTickCount(int approximateCount)
-{
- if (mAutoTickCount != approximateCount)
- {
- if (approximateCount > 0)
- {
- mAutoTickCount = approximateCount;
- mCachedMarginValid = false;
- } else
- qDebug() << Q_FUNC_INFO << "approximateCount must be greater than zero:" << approximateCount;
- }
-}
-
-/*!
- Sets whether the tick labels are generated automatically. Depending on the tick label type (\ref
- ltNumber or \ref ltDateTime), the labels will either show the coordinate as floating point
- number (\ref setNumberFormat), or a date/time formatted according to \ref setDateTimeFormat.
-
- If \a on is set to false, you should provide the tick labels via \ref setTickVectorLabels. This
- is usually used in a combination with \ref setAutoTicks set to false for complete control over
- tick positions and labels, e.g. when the ticks should be at multiples of pi and show "2pi", "3pi"
- etc. as tick labels.
-
- If you need dynamically calculated tick vectors (and possibly tick label vectors), set the
- vectors in a slot connected to the \ref ticksRequest signal.
-
- \see setAutoTicks
-*/
-void QCPAxis::setAutoTickLabels(bool on)
-{
- if (mAutoTickLabels != on)
- {
- mAutoTickLabels = on;
- mCachedMarginValid = false;
- }
-}
-
-/*!
- Sets whether the tick step, i.e. the interval between two (major) ticks, is calculated
- automatically. If \a on is set to true, the axis finds a tick step that is reasonable for human
- readable plots.
-
- The number of ticks the algorithm aims for within the visible range can be specified with \ref
- setAutoTickCount.
-
- If \a on is set to false, you may set the tick step manually with \ref setTickStep.
-
- \see setAutoTicks, setAutoSubTicks, setAutoTickCount
-*/
-void QCPAxis::setAutoTickStep(bool on)
-{
- if (mAutoTickStep != on)
- {
- mAutoTickStep = on;
- mCachedMarginValid = false;
- }
-}
-
-/*!
- Sets whether the number of sub ticks in one tick interval is determined automatically. This
- works, as long as the tick step mantissa is a multiple of 0.5. When \ref setAutoTickStep is
- enabled, this is always the case.
-
- When \a on is set to false, you may set the sub tick count with \ref setSubTickCount manually.
-
- \see setAutoTickCount, setAutoTicks, setAutoTickStep
-*/
-void QCPAxis::setAutoSubTicks(bool on)
-{
- if (mAutoSubTicks != on)
- {
- mAutoSubTicks = on;
- mCachedMarginValid = false;
- }
+ if (ticker)
+ mTicker = ticker;
+ else
+ qDebug() << Q_FUNC_INFO << "can not set 0 as axis ticker";
+ // no need to invalidate margin cache here because produced tick labels are checked for changes in setupTickVector
}
/*!
@@ -4501,6 +7759,8 @@ void QCPAxis::setAutoSubTicks(bool on)
Note that setting \a show to false does not imply that tick labels are invisible, too. To achieve
that, see \ref setTickLabels.
+
+ \see setSubTicks
*/
void QCPAxis::setTicks(bool show)
{
@@ -4520,6 +7780,8 @@ void QCPAxis::setTickLabels(bool show)
{
mTickLabels = show;
mCachedMarginValid = false;
+ if (!mTickLabels)
+ mTickVectorLabels.clear();
}
}
@@ -4537,36 +7799,6 @@ void QCPAxis::setTickLabelPadding(int padding)
}
/*!
- Sets whether the tick labels display numbers or dates/times.
-
- If \a type is set to \ref ltNumber, the format specifications of \ref setNumberFormat apply.
-
- If \a type is set to \ref ltDateTime, the format specifications of \ref setDateTimeFormat apply.
-
- In QCustomPlot, date/time coordinates are <tt>double</tt> numbers representing the seconds since
- 1970-01-01T00:00:00 UTC. This format can be retrieved from QDateTime objects with the
- QDateTime::toTime_t() function. Since this only gives a resolution of one second, there is also
- the QDateTime::toMSecsSinceEpoch() function which returns the timespan described above in
- milliseconds. Divide its return value by 1000.0 to get a value with the format needed for
- date/time plotting, with a resolution of one millisecond.
-
- Using the toMSecsSinceEpoch function allows dates that go back to 2nd January 4713 B.C.
- (represented by a negative number), unlike the toTime_t function, which works with unsigned
- integers and thus only goes back to 1st January 1970. So both for range and accuracy, use of
- toMSecsSinceEpoch()/1000.0 should be preferred as key coordinate for date/time axes.
-
- \see setTickLabels
-*/
-void QCPAxis::setTickLabelType(LabelType type)
-{
- if (mTickLabelType != type)
- {
- mTickLabelType = type;
- mCachedMarginValid = false;
- }
-}
-
-/*!
Sets the font of the tick labels.
\see setTickLabels, setTickLabelColor
@@ -4587,11 +7819,7 @@ void QCPAxis::setTickLabelFont(const QFont &font)
*/
void QCPAxis::setTickLabelColor(const QColor &color)
{
- if (color != mTickLabelColor)
- {
- mTickLabelColor = color;
- mCachedMarginValid = false;
- }
+ mTickLabelColor = color;
}
/*!
@@ -4626,45 +7854,13 @@ void QCPAxis::setTickLabelSide(LabelSide side)
}
/*!
- Sets the format in which dates and times are displayed as tick labels, if \ref setTickLabelType is \ref ltDateTime.
- for details about the \a format string, see the documentation of QDateTime::toString().
-
- Newlines can be inserted with "\n".
-
- \see setDateTimeSpec
-*/
-void QCPAxis::setDateTimeFormat(const QString &format)
-{
- if (mDateTimeFormat != format)
- {
- mDateTimeFormat = format;
- mCachedMarginValid = false;
- }
-}
-
-/*!
- Sets the time spec that is used for the date time values when \ref setTickLabelType is \ref
- ltDateTime.
-
- The default value of QDateTime objects (and also QCustomPlot) is <tt>Qt::LocalTime</tt>. However,
- if the date time values passed to QCustomPlot are given in the UTC spec, set \a
- timeSpec to <tt>Qt::UTC</tt> to get the correct axis labels.
+ Sets the number format for the numbers in tick labels. This \a formatCode is an extended version
+ of the format code used e.g. by QString::number() and QLocale::toString(). For reference about
+ that, see the "Argument Formats" section in the detailed description of the QString class.
- \see setDateTimeFormat
-*/
-void QCPAxis::setDateTimeSpec(const Qt::TimeSpec &timeSpec)
-{
- mDateTimeSpec = timeSpec;
-}
-
-/*!
- Sets the number format for the numbers drawn as tick labels (if tick label type is \ref
- ltNumber). This \a formatCode is an extended version of the format code used e.g. by
- QString::number() and QLocale::toString(). For reference about that, see the "Argument Formats"
- section in the detailed description of the QString class. \a formatCode is a string of one, two
- or three characters. The first character is identical to the normal format code used by Qt. In
- short, this means: 'e'/'E' scientific format, 'f' fixed format, 'g'/'G' scientific or fixed,
- whichever is shorter.
+ \a formatCode is a string of one, two or three characters. The first character is identical to
+ the normal format code used by Qt. In short, this means: 'e'/'E' scientific format, 'f' fixed
+ format, 'g'/'G' scientific or fixed, whichever is shorter.
The second and third characters are optional and specific to QCustomPlot:\n
If the first char was 'e' or 'g', numbers are/might be displayed in the scientific format, e.g.
@@ -4675,12 +7871,6 @@ void QCPAxis::setDateTimeSpec(const Qt::TimeSpec &timeSpec)
be set to 'c'. The inserted multiplication signs are the UTF-8 characters 215 (0xD7) for the
cross and 183 (0xB7) for the dot.
- If the scale type (\ref setScaleType) is \ref stLogarithmic and the \a formatCode uses the 'b'
- option (beautifully typeset decimal powers), the display usually is "1 [multiplication sign] 10
- [superscript] n", which looks unnatural for logarithmic scaling (the "1 [multiplication sign]"
- part). To only display the decimal power, set the number precision to zero with \ref
- setNumberPrecision.
-
Examples for \a formatCode:
\li \c g normal format code behaviour. If number is small, fixed format is used, if number is large,
normal scientific format is used
@@ -4752,12 +7942,6 @@ void QCPAxis::setNumberFormat(const QString &formatCode)
Sets the precision of the tick label numbers. See QLocale::toString(double i, char f, int prec)
for details. The effect of precisions are most notably for number Formats starting with 'e', see
\ref setNumberFormat
-
- If the scale type (\ref setScaleType) is \ref stLogarithmic and the number format (\ref
- setNumberFormat) uses the 'b' format code (beautifully typeset decimal powers), the display
- usually is "1 [multiplication sign] 10 [superscript] n", which looks unnatural for logarithmic
- scaling (the redundant "1 [multiplication sign]" part). To only display the decimal power "10
- [superscript] n", set \a precision to zero.
*/
void QCPAxis::setNumberPrecision(int precision)
{
@@ -4769,58 +7953,6 @@ void QCPAxis::setNumberPrecision(int precision)
}
/*!
- If \ref setAutoTickStep is set to false, use this function to set the tick step manually.
- The tick step is the interval between (major) ticks, in plot coordinates.
- \see setSubTickCount
-*/
-void QCPAxis::setTickStep(double step)
-{
- if (mTickStep != step)
- {
- mTickStep = step;
- mCachedMarginValid = false;
- }
-}
-
-/*!
- If you want full control over what ticks (and possibly labels) the axes show, this function is
- used to set the coordinates at which ticks will appear.\ref setAutoTicks must be disabled, else
- the provided tick vector will be overwritten with automatically generated tick coordinates upon
- replot. The labels of the ticks can be generated automatically when \ref setAutoTickLabels is
- left enabled. If it is disabled, you can set the labels manually with \ref setTickVectorLabels.
-
- \a vec is a vector containing the positions of the ticks, in plot coordinates.
-
- \warning \a vec must be sorted in ascending order, no additional checks are made to ensure this.
-
- \see setTickVectorLabels
-*/
-void QCPAxis::setTickVector(const QVector<double> &vec)
-{
- // don't check whether mTickVector != vec here, because it takes longer than we would save
- mTickVector = vec;
- mCachedMarginValid = false;
-}
-
-/*!
- If you want full control over what ticks and labels the axes show, this function is used to set a
- number of QStrings that will be displayed at the tick positions which you need to provide with
- \ref setTickVector. These two vectors should have the same size. (Note that you need to disable
- \ref setAutoTicks and \ref setAutoTickLabels first.)
-
- \a vec is a vector containing the labels of the ticks. The entries correspond to the respective
- indices in the tick vector, passed via \ref setTickVector.
-
- \see setTickVector
-*/
-void QCPAxis::setTickVectorLabels(const QVector<QString> &vec)
-{
- // don't check whether mTickVectorLabels != vec here, because it takes longer than we would save
- mTickVectorLabels = vec;
- mCachedMarginValid = false;
-}
-
-/*!
Sets the length of the ticks in pixels. \a inside is the length the ticks will reach inside the
plot and \a outside is the length they will reach outside the plot. If \a outside is greater than
zero, the tick labels and axis label will increase their distance to the axis accordingly, so
@@ -4865,19 +7997,19 @@ void QCPAxis::setTickLengthOut(int outside)
}
/*!
- Sets the number of sub ticks in one (major) tick step. A sub tick count of three for example,
- divides the tick intervals in four sub intervals.
+ Sets whether sub tick marks are displayed.
- By default, the number of sub ticks is chosen automatically in a reasonable manner as long as the
- mantissa of the tick step is a multiple of 0.5. When \ref setAutoTickStep is enabled, this is
- always the case.
-
- If you want to disable automatic sub tick count and use this function to set the count manually,
- see \ref setAutoSubTicks.
+ Sub ticks are only potentially visible if (major) ticks are also visible (see \ref setTicks)
+
+ \see setTicks
*/
-void QCPAxis::setSubTickCount(int count)
+void QCPAxis::setSubTicks(bool show)
{
- mSubTickCount = count;
+ if (mSubTicks != show)
+ {
+ mSubTicks = show;
+ mCachedMarginValid = false;
+ }
}
/*!
@@ -5164,16 +8296,32 @@ void QCPAxis::moveRange(double diff)
mRange.lower *= diff;
mRange.upper *= diff;
}
- mCachedMarginValid = false;
emit rangeChanged(mRange);
emit rangeChanged(mRange, oldRange);
}
/*!
+ Scales the range of this axis by \a factor around the center of the current axis range. For
+ example, if \a factor is 2.0, then the axis range will double its size, and the point at the axis
+ range center won't have changed its position in the QCustomPlot widget (i.e. coordinates around
+ the center will have moved symmetrically closer).
+
+ If you wish to scale around a different coordinate than the current axis range center, use the
+ overload \ref scaleRange(double factor, double center).
+*/
+void QCPAxis::scaleRange(double factor)
+{
+ scaleRange(factor, range().center());
+}
+
+/*! \overload
+
Scales the range of this axis by \a factor around the coordinate \a center. For example, if \a
factor is 2.0, \a center is 1.0, then the axis range will double its size, and the point at
coordinate 1.0 won't have changed its position in the QCustomPlot widget (i.e. coordinates
around 1.0 will have moved symmetrically closer to 1.0).
+
+ \see scaleRange(double factor)
*/
void QCPAxis::scaleRange(double factor, double center)
{
@@ -5197,7 +8345,6 @@ void QCPAxis::scaleRange(double factor, double center)
} else
qDebug() << Q_FUNC_INFO << "Center of scaling operation doesn't lie in same logarithmic sign domain as range:" << center;
}
- mCachedMarginValid = false;
emit rangeChanged(mRange);
emit rangeChanged(mRange, oldRange);
}
@@ -5250,9 +8397,9 @@ void QCPAxis::rescale(bool onlyVisiblePlottables)
continue;
QCPRange plottableRange;
bool currentFoundRange;
- QCPAbstractPlottable::SignDomain signDomain = QCPAbstractPlottable::sdBoth;
+ QCP::SignDomain signDomain = QCP::sdBoth;
if (mScaleType == stLogarithmic)
- signDomain = (mRange.upper < 0 ? QCPAbstractPlottable::sdNegative : QCPAbstractPlottable::sdPositive);
+ signDomain = (mRange.upper < 0 ? QCP::sdNegative : QCP::sdPositive);
if (p.at(i)->keyAxis() == this)
plottableRange = p.at(i)->getKeyRange(currentFoundRange, signDomain);
else
@@ -5345,9 +8492,9 @@ double QCPAxis::coordToPixel(double value) const
else
{
if (!mRangeReversed)
- return baseLog(value/mRange.lower)/baseLog(mRange.upper/mRange.lower)*mAxisRect->width()+mAxisRect->left();
+ return qLn(value/mRange.lower)/qLn(mRange.upper/mRange.lower)*mAxisRect->width()+mAxisRect->left();
else
- return baseLog(mRange.upper/value)/baseLog(mRange.upper/mRange.lower)*mAxisRect->width()+mAxisRect->left();
+ return qLn(mRange.upper/value)/qLn(mRange.upper/mRange.lower)*mAxisRect->width()+mAxisRect->left();
}
}
} else // orientation() == Qt::Vertical
@@ -5367,9 +8514,9 @@ double QCPAxis::coordToPixel(double value) const
else
{
if (!mRangeReversed)
- return mAxisRect->bottom()-baseLog(value/mRange.lower)/baseLog(mRange.upper/mRange.lower)*mAxisRect->height();
+ return mAxisRect->bottom()-qLn(value/mRange.lower)/qLn(mRange.upper/mRange.lower)*mAxisRect->height();
else
- return mAxisRect->bottom()-baseLog(mRange.upper/value)/baseLog(mRange.upper/mRange.lower)*mAxisRect->height();
+ return mAxisRect->bottom()-qLn(mRange.upper/value)/qLn(mRange.upper/mRange.lower)*mAxisRect->height();
}
}
}
@@ -5509,238 +8656,6 @@ QCPAxis::AxisType QCPAxis::opposite(QCPAxis::AxisType type)
}
}
-/*! \internal
-
- This function is called to prepare the tick vector, sub tick vector and tick label vector. If
- \ref setAutoTicks is set to true, appropriate tick values are determined automatically via \ref
- generateAutoTicks. If it's set to false, the signal ticksRequest is emitted, which can be used to
- provide external tick positions. Then the sub tick vectors and tick label vectors are created.
-*/
-void QCPAxis::setupTickVectors()
-{
- if (!mParentPlot) return;
- if ((!mTicks && !mTickLabels && !mGrid->visible()) || mRange.size() <= 0) return;
-
- // fill tick vectors, either by auto generating or by notifying user to fill the vectors himself
- if (mAutoTicks)
- {
- generateAutoTicks();
- } else
- {
- emit ticksRequest();
- }
-
- visibleTickBounds(mLowestVisibleTick, mHighestVisibleTick);
- if (mTickVector.isEmpty())
- {
- mSubTickVector.clear();
- return;
- }
-
- // generate subticks between ticks:
- mSubTickVector.resize((mTickVector.size()-1)*mSubTickCount);
- if (mSubTickCount > 0)
- {
- double subTickStep = 0;
- double subTickPosition = 0;
- int subTickIndex = 0;
- bool done = false;
- int lowTick = mLowestVisibleTick > 0 ? mLowestVisibleTick-1 : mLowestVisibleTick;
- int highTick = mHighestVisibleTick < mTickVector.size()-1 ? mHighestVisibleTick+1 : mHighestVisibleTick;
- for (int i=lowTick+1; i<=highTick; ++i)
- {
- subTickStep = (mTickVector.at(i)-mTickVector.at(i-1))/(double)(mSubTickCount+1);
- for (int k=1; k<=mSubTickCount; ++k)
- {
- subTickPosition = mTickVector.at(i-1) + k*subTickStep;
- if (subTickPosition < mRange.lower)
- continue;
- if (subTickPosition > mRange.upper)
- {
- done = true;
- break;
- }
- mSubTickVector[subTickIndex] = subTickPosition;
- subTickIndex++;
- }
- if (done) break;
- }
- mSubTickVector.resize(subTickIndex);
- }
-
- // generate tick labels according to tick positions:
- if (mAutoTickLabels)
- {
- int vecsize = mTickVector.size();
- mTickVectorLabels.resize(vecsize);
- if (mTickLabelType == ltNumber)
- {
- for (int i=mLowestVisibleTick; i<=mHighestVisibleTick; ++i)
- mTickVectorLabels[i] = mParentPlot->locale().toString(mTickVector.at(i), mNumberFormatChar.toLatin1(), mNumberPrecision);
- } else if (mTickLabelType == ltDateTime)
- {
- for (int i=mLowestVisibleTick; i<=mHighestVisibleTick; ++i)
- {
-#if QT_VERSION < QT_VERSION_CHECK(4, 7, 0) // use fromMSecsSinceEpoch function if available, to gain sub-second accuracy on tick labels (e.g. for format "hh:mm:ss:zzz")
- mTickVectorLabels[i] = mParentPlot->locale().toString(QDateTime::fromTime_t(mTickVector.at(i)).toTimeSpec(mDateTimeSpec), mDateTimeFormat);
-#else
- mTickVectorLabels[i] = mParentPlot->locale().toString(QDateTime::fromMSecsSinceEpoch(mTickVector.at(i)*1000).toTimeSpec(mDateTimeSpec), mDateTimeFormat);
-#endif
- }
- }
- } else // mAutoTickLabels == false
- {
- if (mAutoTicks) // ticks generated automatically, but not ticklabels, so emit ticksRequest here for labels
- {
- emit ticksRequest();
- }
- // make sure provided tick label vector has correct (minimal) length:
- if (mTickVectorLabels.size() < mTickVector.size())
- mTickVectorLabels.resize(mTickVector.size());
- }
-}
-
-/*! \internal
-
- If \ref setAutoTicks is set to true, this function is called by \ref setupTickVectors to
- generate reasonable tick positions (and subtick count). The algorithm tries to create
- approximately <tt>mAutoTickCount</tt> ticks (set via \ref setAutoTickCount).
-
- If the scale is logarithmic, \ref setAutoTickCount is ignored, and one tick is generated at every
- power of the current logarithm base, set via \ref setScaleLogBase.
-*/
-void QCPAxis::generateAutoTicks()
-{
- if (mScaleType == stLinear)
- {
- if (mAutoTickStep)
- {
- // Generate tick positions according to linear scaling:
- mTickStep = mRange.size()/(double)(mAutoTickCount+1e-10); // mAutoTickCount ticks on average, the small addition is to prevent jitter on exact integers
- double magnitudeFactor = qPow(10.0, qFloor(qLn(mTickStep)/qLn(10.0))); // get magnitude factor e.g. 0.01, 1, 10, 1000 etc.
- double tickStepMantissa = mTickStep/magnitudeFactor;
- if (tickStepMantissa < 5)
- {
- // round digit after decimal point to 0.5
- mTickStep = (int)(tickStepMantissa*2)/2.0*magnitudeFactor;
- } else
- {
- // round to first digit in multiples of 2
- mTickStep = (int)(tickStepMantissa/2.0)*2.0*magnitudeFactor;
- }
- }
- if (mAutoSubTicks)
- mSubTickCount = calculateAutoSubTickCount(mTickStep);
- // Generate tick positions according to mTickStep:
- qint64 firstStep = floor(mRange.lower/mTickStep); // do not use qFloor here, or we'll lose 64 bit precision
- qint64 lastStep = ceil(mRange.upper/mTickStep); // do not use qCeil here, or we'll lose 64 bit precision
- int tickcount = lastStep-firstStep+1;
- if (tickcount < 0) tickcount = 0;
- mTickVector.resize(tickcount);
- for (int i=0; i<tickcount; ++i)
- mTickVector[i] = (firstStep+i)*mTickStep;
- } else // mScaleType == stLogarithmic
- {
- // Generate tick positions according to logbase scaling:
- if (mRange.lower > 0 && mRange.upper > 0) // positive range
- {
- double lowerMag = basePow(qFloor(baseLog(mRange.lower)));
- double currentMag = lowerMag;
- mTickVector.clear();
- mTickVector.append(currentMag);
- while (currentMag < mRange.upper && currentMag > 0) // currentMag might be zero for ranges ~1e-300, just cancel in that case
- {
- currentMag *= mScaleLogBase;
- mTickVector.append(currentMag);
- }
- } else if (mRange.lower < 0 && mRange.upper < 0) // negative range
- {
- double lowerMag = -basePow(qCeil(baseLog(-mRange.lower)));
- double currentMag = lowerMag;
- mTickVector.clear();
- mTickVector.append(currentMag);
- while (currentMag < mRange.upper && currentMag < 0) // currentMag might be zero for ranges ~1e-300, just cancel in that case
- {
- currentMag /= mScaleLogBase;
- mTickVector.append(currentMag);
- }
- } else // invalid range for logarithmic scale, because lower and upper have different sign
- {
- mTickVector.clear();
- qDebug() << Q_FUNC_INFO << "Invalid range for logarithmic plot: " << mRange.lower << "-" << mRange.upper;
- }
- }
-}
-
-/*! \internal
-
- Called by generateAutoTicks when \ref setAutoSubTicks is set to true. Depending on the \a
- tickStep between two major ticks on the axis, a different number of sub ticks is appropriate. For
- Example taking 4 sub ticks for a \a tickStep of 1 makes more sense than taking 5 sub ticks,
- because this corresponds to a sub tick step of 0.2, instead of the less intuitive 0.16667. Note
- that a subtick count of 4 means dividing the major tick step into 5 sections.
-
- This is implemented by a hand made lookup for integer tick steps as well as fractional tick steps
- with a fractional part of (approximately) 0.5. If a tick step is different (i.e. has no
- fractional part close to 0.5), the currently set sub tick count (\ref setSubTickCount) is
- returned.
-*/
-int QCPAxis::calculateAutoSubTickCount(double tickStep) const
-{
- int result = mSubTickCount; // default to current setting, if no proper value can be found
-
- // get mantissa of tickstep:
- double magnitudeFactor = qPow(10.0, qFloor(qLn(tickStep)/qLn(10.0))); // get magnitude factor e.g. 0.01, 1, 10, 1000 etc.
- double tickStepMantissa = tickStep/magnitudeFactor;
-
- // separate integer and fractional part of mantissa:
- double epsilon = 0.01;
- double intPartf;
- int intPart;
- double fracPart = modf(tickStepMantissa, &intPartf);
- intPart = intPartf;
-
- // handle cases with (almost) integer mantissa:
- if (fracPart < epsilon || 1.0-fracPart < epsilon)
- {
- if (1.0-fracPart < epsilon)
- ++intPart;
- switch (intPart)
- {
- case 1: result = 4; break; // 1.0 -> 0.2 substep
- case 2: result = 3; break; // 2.0 -> 0.5 substep
- case 3: result = 2; break; // 3.0 -> 1.0 substep
- case 4: result = 3; break; // 4.0 -> 1.0 substep
- case 5: result = 4; break; // 5.0 -> 1.0 substep
- case 6: result = 2; break; // 6.0 -> 2.0 substep
- case 7: result = 6; break; // 7.0 -> 1.0 substep
- case 8: result = 3; break; // 8.0 -> 2.0 substep
- case 9: result = 2; break; // 9.0 -> 3.0 substep
- }
- } else
- {
- // handle cases with significantly fractional mantissa:
- if (qAbs(fracPart-0.5) < epsilon) // *.5 mantissa
- {
- switch (intPart)
- {
- case 1: result = 2; break; // 1.5 -> 0.5 substep
- case 2: result = 4; break; // 2.5 -> 0.5 substep
- case 3: result = 4; break; // 3.5 -> 0.7 substep
- case 4: result = 2; break; // 4.5 -> 1.5 substep
- case 5: result = 4; break; // 5.5 -> 1.1 substep (won't occur with autoTickStep from here on)
- case 6: result = 4; break; // 6.5 -> 1.3 substep
- case 7: result = 2; break; // 7.5 -> 2.5 substep
- case 8: result = 4; break; // 8.5 -> 1.7 substep
- case 9: result = 4; break; // 9.5 -> 1.9 substep
- }
- }
- // if mantissa fraction isnt 0.0 or 0.5, don't bother finding good sub tick marks, leave default
- }
-
- return result;
-}
-
/* inherits documentation from base class */
void QCPAxis::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
{
@@ -5775,6 +8690,8 @@ void QCPAxis::deselectEvent(bool *selectionStateChanged)
overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
QCustomPlot::setNotAntialiasedElements.
+ \seebaseclassmethod
+
\see setAntialiased
*/
void QCPAxis::applyDefaultAntialiasingHint(QCPPainter *painter) const
@@ -5786,34 +8703,34 @@ void QCPAxis::applyDefaultAntialiasingHint(QCPPainter *painter) const
Draws the axis with the specified \a painter, using the internal QCPAxisPainterPrivate instance.
+ \seebaseclassmethod
*/
void QCPAxis::draw(QCPPainter *painter)
{
- const int lowTick = mLowestVisibleTick;
- const int highTick = mHighestVisibleTick;
QVector<double> subTickPositions; // the final coordToPixel transformed vector passed to QCPAxisPainter
QVector<double> tickPositions; // the final coordToPixel transformed vector passed to QCPAxisPainter
QVector<QString> tickLabels; // the final vector passed to QCPAxisPainter
- tickPositions.reserve(highTick-lowTick+1);
- tickLabels.reserve(highTick-lowTick+1);
+ tickPositions.reserve(mTickVector.size());
+ tickLabels.reserve(mTickVector.size());
subTickPositions.reserve(mSubTickVector.size());
if (mTicks)
{
- for (int i=lowTick; i<=highTick; ++i)
+ for (int i=0; i<mTickVector.size(); ++i)
{
tickPositions.append(coordToPixel(mTickVector.at(i)));
if (mTickLabels)
tickLabels.append(mTickVectorLabels.at(i));
}
-
- if (mSubTickCount > 0)
+
+ if (mSubTicks)
{
const int subTickCount = mSubTickVector.size();
- for (int i=0; i<subTickCount; ++i) // no need to check bounds because subticks are always only created inside current mRange
+ for (int i=0; i<subTickCount; ++i)
subTickPositions.append(coordToPixel(mSubTickVector.at(i)));
}
}
+
// transfer all properties of this axis to QCPAxisPainterPrivate which it needs to draw the axis.
// Note that some axis painter properties are already set by direct feed-through with QCPAxis setters
mAxisPainter->type = mAxisType;
@@ -5821,7 +8738,7 @@ void QCPAxis::draw(QCPPainter *painter)
mAxisPainter->labelFont = getLabelFont();
mAxisPainter->labelColor = getLabelColor();
mAxisPainter->label = mLabel;
- mAxisPainter->substituteExponent = mAutoTickLabels && mNumberBeautifulPowers && mTickLabelType == ltNumber;
+ mAxisPainter->substituteExponent = mNumberBeautifulPowers;
mAxisPainter->tickPen = getTickPen();
mAxisPainter->subTickPen = getSubTickPen();
mAxisPainter->tickLabelFont = getTickLabelFont();
@@ -5838,75 +8755,20 @@ void QCPAxis::draw(QCPPainter *painter)
/*! \internal
- Returns via \a lowIndex and \a highIndex, which ticks in the current tick vector are visible in
- the current range. The return values are indices of the tick vector, not the positions of the
- ticks themselves.
-
- The actual use of this function is when an external tick vector is provided, since it might
- exceed far beyond the currently displayed range, and would cause unnecessary calculations e.g. of
- subticks.
-
- If all ticks are outside the axis range, an inverted range is returned, i.e. highIndex will be
- smaller than lowIndex. There is one case, where this function returns indices that are not really
- visible in the current axis range: When the tick spacing is larger than the axis range size and
- one tick is below the axis range and the next tick is already above the axis range. Because in
- such cases it is usually desirable to know the tick pair, to draw proper subticks.
-*/
-void QCPAxis::visibleTickBounds(int &lowIndex, int &highIndex) const
-{
- bool lowFound = false;
- bool highFound = false;
- lowIndex = 0;
- highIndex = -1;
-
- for (int i=0; i < mTickVector.size(); ++i)
- {
- if (mTickVector.at(i) >= mRange.lower)
- {
- lowFound = true;
- lowIndex = i;
- break;
- }
- }
- for (int i=mTickVector.size()-1; i >= 0; --i)
- {
- if (mTickVector.at(i) <= mRange.upper)
- {
- highFound = true;
- highIndex = i;
- break;
- }
- }
-
- if (!lowFound && highFound)
- lowIndex = highIndex+1;
- else if (lowFound && !highFound)
- highIndex = lowIndex-1;
-}
-
-/*! \internal
-
- A log function with the base mScaleLogBase, used mostly for coordinate transforms in logarithmic
- scales with arbitrary log base. Uses the buffered mScaleLogBaseLogInv for faster calculation.
- This is set to <tt>1.0/qLn(mScaleLogBase)</tt> in \ref setScaleLogBase.
+ Prepares the internal tick vector, sub tick vector and tick label vector. This is done by calling
+ QCPAxisTicker::generate on the currently installed ticker.
- \see basePow, setScaleLogBase, setScaleType
+ If a change in the label text/count is detected, the cached axis margin is invalidated to make
+ sure the next margin calculation recalculates the label sizes and returns an up-to-date value.
*/
-double QCPAxis::baseLog(double value) const
+void QCPAxis::setupTickVectors()
{
- return qLn(value)*mScaleLogBaseLogInv;
-}
-
-/*! \internal
-
- A power function with the base mScaleLogBase, used mostly for coordinate transforms in
- logarithmic scales with arbitrary log base.
+ if (!mParentPlot) return;
+ if ((!mTicks && !mTickLabels && !mGrid->visible()) || mRange.size() <= 0) return;
- \see baseLog, setScaleLogBase, setScaleType
-*/
-double QCPAxis::basePow(double value) const
-{
- return qPow(mScaleLogBase, value);
+ QVector<QString> oldLabels = mTickVectorLabels;
+ mTicker->generate(mRange, mParentPlot->locale(), mNumberFormatChar, mNumberPrecision, mTickVector, mSubTicks ? &mSubTickVector : 0, mTickLabels ? &mTickVectorLabels : 0);
+ mCachedMarginValid &= mTickVectorLabels == oldLabels; // if labels have changed, margin might have changed, too
}
/*! \internal
@@ -6001,18 +8863,17 @@ int QCPAxis::calculateMargin()
if (mCachedMarginValid)
return mCachedMargin;
- // run through similar steps as QCPAxis::draw, and caluclate margin needed to fit axis and its labels
+ // run through similar steps as QCPAxis::draw, and calculate margin needed to fit axis and its labels
int margin = 0;
- int lowTick, highTick;
- visibleTickBounds(lowTick, highTick);
QVector<double> tickPositions; // the final coordToPixel transformed vector passed to QCPAxisPainter
QVector<QString> tickLabels; // the final vector passed to QCPAxisPainter
- tickPositions.reserve(highTick-lowTick+1);
- tickLabels.reserve(highTick-lowTick+1);
+ tickPositions.reserve(mTickVector.size());
+ tickLabels.reserve(mTickVector.size());
+
if (mTicks)
{
- for (int i=lowTick; i<=highTick; ++i)
+ for (int i=0; i<mTickVector.size(); ++i)
{
tickPositions.append(coordToPixel(mTickVector.at(i)));
if (mTickLabels)
@@ -6175,11 +9036,11 @@ void QCPAxisPainterPrivate::draw(QCPPainter *painter)
bool antialiasingBackup = painter->antialiasing();
painter->setAntialiasing(true); // always want endings to be antialiased, even if base and ticks themselves aren't
painter->setBrush(QBrush(basePen.color()));
- QVector2D baseLineVector(baseLine.dx(), baseLine.dy());
+ QCPVector2D baseLineVector(baseLine.dx(), baseLine.dy());
if (lowerEnding.style() != QCPLineEnding::esNone)
- lowerEnding.draw(painter, QVector2D(baseLine.p1())-baseLineVector.normalized()*lowerEnding.realLength()*(lowerEnding.inverted()?-1:1), -baseLineVector);
+ lowerEnding.draw(painter, QCPVector2D(baseLine.p1())-baseLineVector.normalized()*lowerEnding.realLength()*(lowerEnding.inverted()?-1:1), -baseLineVector);
if (upperEnding.style() != QCPLineEnding::esNone)
- upperEnding.draw(painter, QVector2D(baseLine.p2())+baseLineVector.normalized()*upperEnding.realLength()*(upperEnding.inverted()?-1:1), baseLineVector);
+ upperEnding.draw(painter, QCPVector2D(baseLine.p2())+baseLineVector.normalized()*upperEnding.realLength()*(upperEnding.inverted()?-1:1), baseLineVector);
painter->setAntialiasing(antialiasingBackup);
// tick labels:
@@ -6347,6 +9208,7 @@ void QCPAxisPainterPrivate::clearCache()
QByteArray QCPAxisPainterPrivate::generateLabelParameterHash() const
{
QByteArray result;
+ result.append(QByteArray::number(mParentPlot->bufferDevicePixelRatio()));
result.append(QByteArray::number(tickLabelRotation));
result.append(QByteArray::number((int)tickLabelSide));
result.append(QByteArray::number((int)substituteExponent));
@@ -6396,6 +9258,14 @@ void QCPAxisPainterPrivate::placeTickLabel(QCPPainter *painter, double position,
cachedLabel = new CachedLabel;
TickLabelData labelData = getTickLabelData(painter->font(), text);
cachedLabel->offset = getTickLabelDrawOffset(labelData)+labelData.rotatedTotalBounds.topLeft();
+ if (!qFuzzyCompare(1.0, mParentPlot->bufferDevicePixelRatio()))
+ {
+ cachedLabel->pixmap = QPixmap(labelData.rotatedTotalBounds.size()*mParentPlot->bufferDevicePixelRatio());
+#ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
+ cachedLabel->pixmap.setDevicePixelRatio(mParentPlot->devicePixelRatio());
+#endif
+ } else
+ cachedLabel->pixmap = QPixmap(labelData.rotatedTotalBounds.size());
cachedLabel->pixmap = QPixmap(labelData.rotatedTotalBounds.size());
cachedLabel->pixmap.fill(Qt::transparent);
QCPPainter cachePainter(&cachedLabel->pixmap);
@@ -6407,14 +9277,14 @@ void QCPAxisPainterPrivate::placeTickLabel(QCPPainter *painter, double position,
if (tickLabelSide == QCPAxis::lsOutside)
{
if (QCPAxis::orientation(type) == Qt::Horizontal)
- labelClippedByBorder = labelAnchor.x()+cachedLabel->offset.x()+cachedLabel->pixmap.width() > viewportRect.right() || labelAnchor.x()+cachedLabel->offset.x() < viewportRect.left();
+ labelClippedByBorder = labelAnchor.x()+cachedLabel->offset.x()+cachedLabel->pixmap.width()/mParentPlot->bufferDevicePixelRatio() > viewportRect.right() || labelAnchor.x()+cachedLabel->offset.x() < viewportRect.left();
else
- labelClippedByBorder = labelAnchor.y()+cachedLabel->offset.y()+cachedLabel->pixmap.height() > viewportRect.bottom() || labelAnchor.y()+cachedLabel->offset.y() < viewportRect.top();
+ labelClippedByBorder = labelAnchor.y()+cachedLabel->offset.y()+cachedLabel->pixmap.height()/mParentPlot->bufferDevicePixelRatio() > viewportRect.bottom() || labelAnchor.y()+cachedLabel->offset.y() < viewportRect.top();
}
if (!labelClippedByBorder)
{
painter->drawPixmap(labelAnchor+cachedLabel->offset, cachedLabel->pixmap);
- finalSize = cachedLabel->pixmap.size();
+ finalSize = cachedLabel->pixmap.size()/mParentPlot->bufferDevicePixelRatio();
}
mLabelCache.insert(text, cachedLabel); // return label to cache or insert for the first time if newly created
} else // label caching disabled, draw text directly on surface:
@@ -6469,6 +9339,8 @@ void QCPAxisPainterPrivate::drawTickLabel(QCPPainter *painter, double x, double
{
painter->setFont(labelData.baseFont);
painter->drawText(0, 0, 0, 0, Qt::TextDontClip, labelData.basePart);
+ if (!labelData.suffixPart.isEmpty())
+ painter->drawText(labelData.baseBounds.width()+1+labelData.expBounds.width(), 0, 0, 0, Qt::TextDontClip, labelData.suffixPart);
painter->setFont(labelData.expFont);
painter->drawText(labelData.baseBounds.width()+1, 0, labelData.expBounds.width(), labelData.expBounds.height(), Qt::TextDontClip, labelData.expPart);
} else
@@ -6496,12 +9368,19 @@ QCPAxisPainterPrivate::TickLabelData QCPAxisPainterPrivate::getTickLabelData(con
// determine whether beautiful decimal powers should be used
bool useBeautifulPowers = false;
- int ePos = -1;
+ int ePos = -1; // first index of exponent part, text before that will be basePart, text until eLast will be expPart
+ int eLast = -1; // last index of exponent part, rest of text after this will be suffixPart
if (substituteExponent)
{
ePos = text.indexOf(QLatin1Char('e'));
- if (ePos > -1)
- useBeautifulPowers = true;
+ if (ePos > 0 && text.at(ePos-1).isDigit())
+ {
+ eLast = ePos;
+ while (eLast+1 < text.size() && (text.at(eLast+1) == QLatin1Char('+') || text.at(eLast+1) == QLatin1Char('-') || text.at(eLast+1).isDigit()))
+ ++eLast;
+ if (eLast > ePos) // only if also to right of 'e' is a digit/+/- interpret it as beautifiable power
+ useBeautifulPowers = true;
+ }
}
// calculate text bounding rects and do string preparation for beautiful decimal powers:
@@ -6512,12 +9391,13 @@ QCPAxisPainterPrivate::TickLabelData QCPAxisPainterPrivate::getTickLabelData(con
{
// split text into parts of number/symbol that will be drawn normally and part that will be drawn as exponent:
result.basePart = text.left(ePos);
+ result.suffixPart = text.mid(eLast+1); // also drawn normally but after exponent
// in log scaling, we want to turn "1*10^n" into "10^n", else add multiplication sign and decimal base:
if (abbreviateDecimalPowers && result.basePart == QLatin1String("1"))
result.basePart = QLatin1String("10");
else
result.basePart += (numberMultiplyCross ? QString(QChar(215)) : QString(QChar(183))) + QLatin1String("10");
- result.expPart = text.mid(ePos+1);
+ result.expPart = text.mid(ePos+1, eLast-ePos);
// clip "+" and leading zeros off expPart:
while (result.expPart.length() > 2 && result.expPart.at(1) == QLatin1Char('0')) // length > 2 so we leave one zero when numberFormatChar is 'e'
result.expPart.remove(1, 1);
@@ -6529,10 +9409,12 @@ QCPAxisPainterPrivate::TickLabelData QCPAxisPainterPrivate::getTickLabelData(con
result.expFont.setPointSize(result.expFont.pointSize()*0.75);
else
result.expFont.setPixelSize(result.expFont.pixelSize()*0.75);
- // calculate bounding rects of base part, exponent part and total one:
+ // calculate bounding rects of base part(s), exponent part and total one:
result.baseBounds = QFontMetrics(result.baseFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.basePart);
result.expBounds = QFontMetrics(result.expFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.expPart);
- result.totalBounds = result.baseBounds.adjusted(0, 0, result.expBounds.width()+2, 0); // +2 consists of the 1 pixel spacing between base and exponent (see drawTickLabel) and an extra pixel to include AA
+ if (!result.suffixPart.isEmpty())
+ result.suffixBounds = QFontMetrics(result.baseFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.suffixPart);
+ 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
} else // useBeautifulPowers == false
{
result.basePart = text;
@@ -6669,7 +9551,7 @@ void QCPAxisPainterPrivate::getMaxTickLabelSize(const QFont &font, const QString
if (mParentPlot->plottingHints().testFlag(QCP::phCacheLabels) && mLabelCache.contains(text)) // label caching enabled and have cached label
{
const CachedLabel *cachedLabel = mLabelCache.object(text);
- finalSize = cachedLabel->pixmap.size();
+ finalSize = cachedLabel->pixmap.size()/mParentPlot->bufferDevicePixelRatio();
} else // label caching disabled or no label with this text cached:
{
TickLabelData labelData = getTickLabelData(font, text);
@@ -6682,6 +9564,656 @@ void QCPAxisPainterPrivate::getMaxTickLabelSize(const QFont &font, const QString
if (finalSize.height() > tickLabelsSize->height())
tickLabelsSize->setHeight(finalSize.height());
}
+/* end of 'src/axis/axis.cpp' */
+
+
+/* including file 'src/scatterstyle.cpp', size 17420 */
+/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
+
+////////////////////////////////////////////////////////////////////////////////////////////////////
+//////////////////// QCPScatterStyle
+////////////////////////////////////////////////////////////////////////////////////////////////////
+
+/*! \class QCPScatterStyle
+ \brief Represents the visual appearance of scatter points
+
+ This class holds information about shape, color and size of scatter points. In plottables like
+ QCPGraph it is used to store how scatter points shall be drawn. For example, \ref
+ QCPGraph::setScatterStyle takes a QCPScatterStyle instance.
+
+ A scatter style consists of a shape (\ref setShape), a line color (\ref setPen) and possibly a
+ fill (\ref setBrush), if the shape provides a fillable area. Further, the size of the shape can
+ be controlled with \ref setSize.
+
+ \section QCPScatterStyle-defining Specifying a scatter style
+
+ You can set all these configurations either by calling the respective functions on an instance:
+ \snippet documentation/doc-code-snippets/mainwindow.cpp qcpscatterstyle-creation-1
+
+ Or you can use one of the various constructors that take different parameter combinations, making
+ it easy to specify a scatter style in a single call, like so:
+ \snippet documentation/doc-code-snippets/mainwindow.cpp qcpscatterstyle-creation-2
+
+ \section QCPScatterStyle-undefinedpen Leaving the color/pen up to the plottable
+
+ There are two constructors which leave the pen undefined: \ref QCPScatterStyle() and \ref
+ QCPScatterStyle(ScatterShape shape, double size). If those constructors are used, a call to \ref
+ isPenDefined will return false. It leads to scatter points that inherit the pen from the
+ plottable that uses the scatter style. Thus, if such a scatter style is passed to QCPGraph, the line
+ color of the graph (\ref QCPGraph::setPen) will be used by the scatter points. This makes
+ it very convenient to set up typical scatter settings:
+
+ \snippet documentation/doc-code-snippets/mainwindow.cpp qcpscatterstyle-shortcreation
+
+ Notice that it wasn't even necessary to explicitly call a QCPScatterStyle constructor. This works
+ because QCPScatterStyle provides a constructor that can transform a \ref ScatterShape directly
+ into a QCPScatterStyle instance (that's the \ref QCPScatterStyle(ScatterShape shape, double size)
+ constructor with a default for \a size). In those cases, C++ allows directly supplying a \ref
+ ScatterShape, where actually a QCPScatterStyle is expected.
+
+ \section QCPScatterStyle-custompath-and-pixmap Custom shapes and pixmaps
+
+ QCPScatterStyle supports drawing custom shapes and arbitrary pixmaps as scatter points.
+
+ For custom shapes, you can provide a QPainterPath with the desired shape to the \ref
+ setCustomPath function or call the constructor that takes a painter path. The scatter shape will
+ automatically be set to \ref ssCustom.
+
+ For pixmaps, you call \ref setPixmap with the desired QPixmap. Alternatively you can use the
+ constructor that takes a QPixmap. The scatter shape will automatically be set to \ref ssPixmap.
+ Note that \ref setSize does not influence the appearance of the pixmap.
+*/
+
+/* start documentation of inline functions */
+
+/*! \fn bool QCPScatterStyle::isNone() const
+
+ Returns whether the scatter shape is \ref ssNone.
+
+ \see setShape
+*/
+
+/*! \fn bool QCPScatterStyle::isPenDefined() const
+
+ Returns whether a pen has been defined for this scatter style.
+
+ The pen is undefined if a constructor is called that does not carry \a pen as parameter. Those
+ are \ref QCPScatterStyle() and \ref QCPScatterStyle(ScatterShape shape, double size). If the pen
+ is undefined, the pen of the respective plottable will be used for drawing scatters.
+
+ If a pen was defined for this scatter style instance, and you now wish to undefine the pen, call
+ \ref undefinePen.
+
+ \see setPen
+*/
+
+/* end documentation of inline functions */
+
+/*!
+ Creates a new QCPScatterStyle instance with size set to 6. No shape, pen or brush is defined.
+
+ Since the pen is undefined (\ref isPenDefined returns false), the scatter color will be inherited
+ from the plottable that uses this scatter style.
+*/
+QCPScatterStyle::QCPScatterStyle() :
+ mSize(6),
+ mShape(ssNone),
+ mPen(Qt::NoPen),
+ mBrush(Qt::NoBrush),
+ mPenDefined(false)
+{
+}
+
+/*!
+ Creates a new QCPScatterStyle instance with shape set to \a shape and size to \a size. No pen or
+ brush is defined.
+
+ Since the pen is undefined (\ref isPenDefined returns false), the scatter color will be inherited
+ from the plottable that uses this scatter style.
+*/
+QCPScatterStyle::QCPScatterStyle(ScatterShape shape, double size) :
+ mSize(size),
+ mShape(shape),
+ mPen(Qt::NoPen),
+ mBrush(Qt::NoBrush),
+ mPenDefined(false)
+{
+}
+
+/*!
+ Creates a new QCPScatterStyle instance with shape set to \a shape, the pen color set to \a color,
+ and size to \a size. No brush is defined, i.e. the scatter point will not be filled.
+*/
+QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QColor &color, double size) :
+ mSize(size),
+ mShape(shape),
+ mPen(QPen(color)),
+ mBrush(Qt::NoBrush),
+ mPenDefined(true)
+{
+}
+
+/*!
+ Creates a new QCPScatterStyle instance with shape set to \a shape, the pen color set to \a color,
+ the brush color to \a fill (with a solid pattern), and size to \a size.
+*/
+QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QColor &color, const QColor &fill, double size) :
+ mSize(size),
+ mShape(shape),
+ mPen(QPen(color)),
+ mBrush(QBrush(fill)),
+ mPenDefined(true)
+{
+}
+
+/*!
+ Creates a new QCPScatterStyle instance with shape set to \a shape, the pen set to \a pen, the
+ brush to \a brush, and size to \a size.
+
+ \warning In some cases it might be tempting to directly use a pen style like <tt>Qt::NoPen</tt> as \a pen
+ and a color like <tt>Qt::blue</tt> as \a brush. Notice however, that the corresponding call\n
+ <tt>QCPScatterStyle(QCPScatterShape::ssCircle, Qt::NoPen, Qt::blue, 5)</tt>\n
+ doesn't necessarily lead C++ to use this constructor in some cases, but might mistake
+ <tt>Qt::NoPen</tt> for a QColor and use the
+ \ref QCPScatterStyle(ScatterShape shape, const QColor &color, const QColor &fill, double size)
+ constructor instead (which will lead to an unexpected look of the scatter points). To prevent
+ this, be more explicit with the parameter types. For example, use <tt>QBrush(Qt::blue)</tt>
+ instead of just <tt>Qt::blue</tt>, to clearly point out to the compiler that this constructor is
+ wanted.
+*/
+QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QPen &pen, const QBrush &brush, double size) :
+ mSize(size),
+ mShape(shape),
+ mPen(pen),
+ mBrush(brush),
+ mPenDefined(pen.style() != Qt::NoPen)
+{
+}
+
+/*!
+ Creates a new QCPScatterStyle instance which will show the specified \a pixmap. The scatter shape
+ is set to \ref ssPixmap.
+*/
+QCPScatterStyle::QCPScatterStyle(const QPixmap &pixmap) :
+ mSize(5),
+ mShape(ssPixmap),
+ mPen(Qt::NoPen),
+ mBrush(Qt::NoBrush),
+ mPixmap(pixmap),
+ mPenDefined(false)
+{
+}
+
+/*!
+ Creates a new QCPScatterStyle instance with a custom shape that is defined via \a customPath. The
+ scatter shape is set to \ref ssCustom.
+
+ The custom shape line will be drawn with \a pen and filled with \a brush. The size has a slightly
+ different meaning than for built-in scatter points: The custom path will be drawn scaled by a
+ factor of \a size/6.0. Since the default \a size is 6, the custom path will appear at a its
+ natural size by default. To double the size of the path for example, set \a size to 12.
+*/
+QCPScatterStyle::QCPScatterStyle(const QPainterPath &customPath, const QPen &pen, const QBrush &brush, double size) :
+ mSize(size),
+ mShape(ssCustom),
+ mPen(pen),
+ mBrush(brush),
+ mCustomPath(customPath),
+ mPenDefined(pen.style() != Qt::NoPen)
+{
+}
+
+/*!
+ Copies the specified \a properties from the \a other scatter style to this scatter style.
+*/
+void QCPScatterStyle::setFromOther(const QCPScatterStyle &other, ScatterProperties properties)
+{
+ if (properties.testFlag(spPen))
+ {
+ setPen(other.pen());
+ if (!other.isPenDefined())
+ undefinePen();
+ }
+ if (properties.testFlag(spBrush))
+ setBrush(other.brush());
+ if (properties.testFlag(spSize))
+ setSize(other.size());
+ if (properties.testFlag(spShape))
+ {
+ setShape(other.shape());
+ if (other.shape() == ssPixmap)
+ setPixmap(other.pixmap());
+ else if (other.shape() == ssCustom)
+ setCustomPath(other.customPath());
+ }
+}
+
+/*!
+ Sets the size (pixel diameter) of the drawn scatter points to \a size.
+
+ \see setShape
+*/
+void QCPScatterStyle::setSize(double size)
+{
+ mSize = size;
+}
+
+/*!
+ Sets the shape to \a shape.
+
+ Note that the calls \ref setPixmap and \ref setCustomPath automatically set the shape to \ref
+ ssPixmap and \ref ssCustom, respectively.
+
+ \see setSize
+*/
+void QCPScatterStyle::setShape(QCPScatterStyle::ScatterShape shape)
+{
+ mShape = shape;
+}
+
+/*!
+ Sets the pen that will be used to draw scatter points to \a pen.
+
+ If the pen was previously undefined (see \ref isPenDefined), the pen is considered defined after
+ a call to this function, even if \a pen is <tt>Qt::NoPen</tt>. If you have defined a pen
+ previously by calling this function and now wish to undefine the pen, call \ref undefinePen.
+
+ \see setBrush
+*/
+void QCPScatterStyle::setPen(const QPen &pen)
+{
+ mPenDefined = true;
+ mPen = pen;
+}
+
+/*!
+ Sets the brush that will be used to fill scatter points to \a brush. Note that not all scatter
+ shapes have fillable areas. For example, \ref ssPlus does not while \ref ssCircle does.
+
+ \see setPen
+*/
+void QCPScatterStyle::setBrush(const QBrush &brush)
+{
+ mBrush = brush;
+}
+
+/*!
+ Sets the pixmap that will be drawn as scatter point to \a pixmap.
+
+ Note that \ref setSize does not influence the appearance of the pixmap.
+
+ The scatter shape is automatically set to \ref ssPixmap.
+*/
+void QCPScatterStyle::setPixmap(const QPixmap &pixmap)
+{
+ setShape(ssPixmap);
+ mPixmap = pixmap;
+}
+
+/*!
+ Sets the custom shape that will be drawn as scatter point to \a customPath.
+
+ The scatter shape is automatically set to \ref ssCustom.
+*/
+void QCPScatterStyle::setCustomPath(const QPainterPath &customPath)
+{
+ setShape(ssCustom);
+ mCustomPath = customPath;
+}
+
+/*!
+ Sets this scatter style to have an undefined pen (see \ref isPenDefined for what an undefined pen
+ implies).
+
+ A call to \ref setPen will define a pen.
+*/
+void QCPScatterStyle::undefinePen()
+{
+ mPenDefined = false;
+}
+
+/*!
+ Applies the pen and the brush of this scatter style to \a painter. If this scatter style has an
+ undefined pen (\ref isPenDefined), sets the pen of \a painter to \a defaultPen instead.
+
+ This function is used by plottables (or any class that wants to draw scatters) just before a
+ number of scatters with this style shall be drawn with the \a painter.
+
+ \see drawShape
+*/
+void QCPScatterStyle::applyTo(QCPPainter *painter, const QPen &defaultPen) const
+{
+ painter->setPen(mPenDefined ? mPen : defaultPen);
+ painter->setBrush(mBrush);
+}
+
+/*!
+ Draws the scatter shape with \a painter at position \a pos.
+
+ This function does not modify the pen or the brush on the painter, as \ref applyTo is meant to be
+ called before scatter points are drawn with \ref drawShape.
+
+ \see applyTo
+*/
+void QCPScatterStyle::drawShape(QCPPainter *painter, const QPointF &pos) const
+{
+ drawShape(painter, pos.x(), pos.y());
+}
+
+/*! \overload
+ Draws the scatter shape with \a painter at position \a x and \a y.
+*/
+void QCPScatterStyle::drawShape(QCPPainter *painter, double x, double y) const
+{
+ double w = mSize/2.0;
+ switch (mShape)
+ {
+ case ssNone: break;
+ case ssDot:
+ {
+ painter->drawLine(QPointF(x, y), QPointF(x+0.0001, y));
+ break;
+ }
+ case ssCross:
+ {
+ painter->drawLine(QLineF(x-w, y-w, x+w, y+w));
+ painter->drawLine(QLineF(x-w, y+w, x+w, y-w));
+ break;
+ }
+ case ssPlus:
+ {
+ painter->drawLine(QLineF(x-w, y, x+w, y));
+ painter->drawLine(QLineF( x, y+w, x, y-w));
+ break;
+ }
+ case ssCircle:
+ {
+ painter->drawEllipse(QPointF(x , y), w, w);
+ break;
+ }
+ case ssDisc:
+ {
+ QBrush b = painter->brush();
+ painter->setBrush(painter->pen().color());
+ painter->drawEllipse(QPointF(x , y), w, w);
+ painter->setBrush(b);
+ break;
+ }
+ case ssSquare:
+ {
+ painter->drawRect(QRectF(x-w, y-w, mSize, mSize));
+ break;
+ }
+ case ssDiamond:
+ {
+ painter->drawLine(QLineF(x-w, y, x, y-w));
+ painter->drawLine(QLineF( x, y-w, x+w, y));
+ painter->drawLine(QLineF(x+w, y, x, y+w));
+ painter->drawLine(QLineF( x, y+w, x-w, y));
+ break;
+ }
+ case ssStar:
+ {
+ painter->drawLine(QLineF(x-w, y, x+w, y));
+ painter->drawLine(QLineF( x, y+w, x, y-w));
+ painter->drawLine(QLineF(x-w*0.707, y-w*0.707, x+w*0.707, y+w*0.707));
+ painter->drawLine(QLineF(x-w*0.707, y+w*0.707, x+w*0.707, y-w*0.707));
+ break;
+ }
+ case ssTriangle:
+ {
+ painter->drawLine(QLineF(x-w, y+0.755*w, x+w, y+0.755*w));
+ painter->drawLine(QLineF(x+w, y+0.755*w, x, y-0.977*w));
+ painter->drawLine(QLineF( x, y-0.977*w, x-w, y+0.755*w));
+ break;
+ }
+ case ssTriangleInverted:
+ {
+ painter->drawLine(QLineF(x-w, y-0.755*w, x+w, y-0.755*w));
+ painter->drawLine(QLineF(x+w, y-0.755*w, x, y+0.977*w));
+ painter->drawLine(QLineF( x, y+0.977*w, x-w, y-0.755*w));
+ break;
+ }
+ case ssCrossSquare:
+ {
+ painter->drawLine(QLineF(x-w, y-w, x+w*0.95, y+w*0.95));
+ painter->drawLine(QLineF(x-w, y+w*0.95, x+w*0.95, y-w));
+ painter->drawRect(QRectF(x-w, y-w, mSize, mSize));
+ break;
+ }
+ case ssPlusSquare:
+ {
+ painter->drawLine(QLineF(x-w, y, x+w*0.95, y));
+ painter->drawLine(QLineF( x, y+w, x, y-w));
+ painter->drawRect(QRectF(x-w, y-w, mSize, mSize));
+ break;
+ }
+ case ssCrossCircle:
+ {
+ painter->drawLine(QLineF(x-w*0.707, y-w*0.707, x+w*0.670, y+w*0.670));
+ painter->drawLine(QLineF(x-w*0.707, y+w*0.670, x+w*0.670, y-w*0.707));
+ painter->drawEllipse(QPointF(x, y), w, w);
+ break;
+ }
+ case ssPlusCircle:
+ {
+ painter->drawLine(QLineF(x-w, y, x+w, y));
+ painter->drawLine(QLineF( x, y+w, x, y-w));
+ painter->drawEllipse(QPointF(x, y), w, w);
+ break;
+ }
+ case ssPeace:
+ {
+ painter->drawLine(QLineF(x, y-w, x, y+w));
+ painter->drawLine(QLineF(x, y, x-w*0.707, y+w*0.707));
+ painter->drawLine(QLineF(x, y, x+w*0.707, y+w*0.707));
+ painter->drawEllipse(QPointF(x, y), w, w);
+ break;
+ }
+ case ssPixmap:
+ {
+ const double widthHalf = mPixmap.width()*0.5;
+ const double heightHalf = mPixmap.height()*0.5;
+#if QT_VERSION < QT_VERSION_CHECK(4, 8, 0)
+ const QRectF clipRect = painter->clipRegion().boundingRect().adjusted(-widthHalf, -heightHalf, widthHalf, heightHalf);
+#else
+ const QRectF clipRect = painter->clipBoundingRect().adjusted(-widthHalf, -heightHalf, widthHalf, heightHalf);
+#endif
+ if (clipRect.contains(x, y))
+ painter->drawPixmap(x-widthHalf, y-heightHalf, mPixmap);
+ break;
+ }
+ case ssCustom:
+ {
+ QTransform oldTransform = painter->transform();
+ painter->translate(x, y);
+ painter->scale(mSize/6.0, mSize/6.0);
+ painter->drawPath(mCustomPath);
+ painter->setTransform(oldTransform);
+ break;
+ }
+ }
+}
+/* end of 'src/scatterstyle.cpp' */
+
+//amalgamation: add datacontainer.cpp
+
+/* including file 'src/plottable.cpp', size 38861 */
+/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
+
+////////////////////////////////////////////////////////////////////////////////////////////////////
+//////////////////// QCPSelectionDecorator
+////////////////////////////////////////////////////////////////////////////////////////////////////
+
+/*! \class QCPSelectionDecorator
+ \brief Controls how a plottable's data selection is drawn
+
+ Each \ref QCPAbstractPlottable instance has one \ref QCPSelectionDecorator (accessible via \ref
+ QCPAbstractPlottable::selectionDecorator) and uses it when drawing selected segments of its data.
+
+ The selection decorator controls both pen (\ref setPen) and brush (\ref setBrush), as well as the
+ scatter style (\ref setScatterStyle) if the plottable draws scatters. Since a \ref
+ QCPScatterStyle is itself composed of different properties such as color shape and size, the
+ decorator allows specifying exactly which of those properties shall be used for the selected data
+ point, via \ref setUsedScatterProperties.
+
+ A \ref QCPSelectionDecorator subclass instance can be passed to a plottable via \ref
+ QCPAbstractPlottable::setSelectionDecorator, allowing greater customizability of the appearance
+ of selected segments.
+
+ Use \ref copyFrom to easily transfer the settings of one decorator to another one. This is
+ especially useful since plottables take ownership of the passed selection decorator, and thus the
+ same decorator instance can not be passed to multiple plottables.
+
+ Selection decorators can also themselves perform drawing operations by reimplementing \ref
+ drawDecoration, which is called by the plottable's draw method. The base class \ref
+ QCPSelectionDecorator does not make use of this however. For example, \ref
+ QCPSelectionDecoratorBracket draws brackets around selected data segments.
+*/
+
+/*!
+ Creates a new QCPSelectionDecorator instance with default values
+*/
+QCPSelectionDecorator::QCPSelectionDecorator() :
+ mPen(QColor(80, 80, 255), 2.5),
+ mBrush(Qt::NoBrush),
+ mScatterStyle(QCPScatterStyle::ssNone, QPen(Qt::blue, 2), Qt::NoBrush, 6.0),
+ mUsedScatterProperties(QCPScatterStyle::spPen),
+ mPlottable(0)
+{
+}
+
+QCPSelectionDecorator::~QCPSelectionDecorator()
+{
+}
+
+/*!
+ Sets the pen that will be used by the parent plottable to draw selected data segments.
+*/
+void QCPSelectionDecorator::setPen(const QPen &pen)
+{
+ mPen = pen;
+}
+
+/*!
+ Sets the brush that will be used by the parent plottable to draw selected data segments.
+*/
+void QCPSelectionDecorator::setBrush(const QBrush &brush)
+{
+ mBrush = brush;
+}
+
+/*!
+ Sets the scatter style that will be used by the parent plottable to draw scatters in selected
+ data segments.
+
+ \a usedProperties specifies which parts of the passed \a scatterStyle will be used by the
+ plottable. The used properties can also be changed via \ref setUsedScatterProperties.
+*/
+void QCPSelectionDecorator::setScatterStyle(const QCPScatterStyle &scatterStyle, QCPScatterStyle::ScatterProperties usedProperties)
+{
+ mScatterStyle = scatterStyle;
+ setUsedScatterProperties(usedProperties);
+}
+
+/*!
+ Use this method to define which properties of the scatter style (set via \ref setScatterStyle)
+ will be used for selected data segments. All properties of the scatter style that are not
+ specified in \a properties will remain as specified in the plottable's original scatter style.
+*/
+void QCPSelectionDecorator::setUsedScatterProperties(const QCPScatterStyle::ScatterProperties &properties)
+{
+ mUsedScatterProperties = properties;
+}
+
+/*!
+ Sets the pen of \a painter to the pen of this selection decorator.
+
+ \see applyBrush, getFinalScatterStyle
+*/
+void QCPSelectionDecorator::applyPen(QCPPainter *painter) const
+{
+ painter->setPen(mPen);
+}
+
+/*!
+ Sets the brush of \a painter to the brush of this selection decorator.
+
+ \see applyPen, getFinalScatterStyle
+*/
+void QCPSelectionDecorator::applyBrush(QCPPainter *painter) const
+{
+ painter->setBrush(mBrush);
+}
+
+/*!
+ Returns the scatter style that the parent plottable shall use for selected scatter points. The
+ plottable's original (unselected) scatter style must be passed as \a unselectedStyle. Depending
+ on the setting of \ref setUsedScatterProperties, the returned scatter style is a mixture of this
+ selecion decorator's scatter style (\ref setScatterStyle), and \a unselectedStyle.
+
+ \see applyPen, applyBrush, setScatterStyle
+*/
+QCPScatterStyle QCPSelectionDecorator::getFinalScatterStyle(const QCPScatterStyle &unselectedStyle) const
+{
+ QCPScatterStyle result(unselectedStyle);
+ result.setFromOther(mScatterStyle, mUsedScatterProperties);
+
+ // if style shall inherit pen from plottable (has no own pen defined), give it the selected
+ // plottable pen explicitly, so it doesn't use the unselected plottable pen when used in the
+ // plottable:
+ if (!result.isPenDefined())
+ result.setPen(mPen);
+
+ return result;
+}
+
+/*!
+ Copies all properties (e.g. color, fill, scatter style) of the \a other selection decorator to
+ this selection decorator.
+*/
+void QCPSelectionDecorator::copyFrom(const QCPSelectionDecorator *other)
+{
+ setPen(other->pen());
+ setBrush(other->brush());
+ setScatterStyle(other->scatterStyle(), other->usedScatterProperties());
+}
+
+/*!
+ This method is called by all plottables' draw methods to allow custom selection decorations to be
+ drawn. Use the passed \a painter to perform the drawing operations. \a selection carries the data
+ selection for which the decoration shall be drawn.
+
+ The default base class implementation of \ref QCPSelectionDecorator has no special decoration, so
+ this method does nothing.
+*/
+void QCPSelectionDecorator::drawDecoration(QCPPainter *painter, QCPDataSelection selection)
+{
+ Q_UNUSED(painter)
+ Q_UNUSED(selection)
+}
+
+/*! \internal
+
+ This method is called as soon as a selection decorator is associated with a plottable, by a call
+ to \ref QCPAbstractPlottable::setSelectionDecorator. This way the selection decorator can obtain a pointer to the plottable that uses it (e.g. to access
+ data points via the \ref QCPAbstractPlottable::interface1D interface).
+
+ If the selection decorator was already added to a different plottable before, this method aborts
+ the registration and returns false.
+*/
+bool QCPSelectionDecorator::registerWithPlottable(QCPAbstractPlottable *plottable)
+{
+ if (!mPlottable)
+ {
+ mPlottable = plottable;
+ return true;
+ } else
+ {
+ qDebug() << Q_FUNC_INFO << "This selection decorator is already registered with plottable:" << reinterpret_cast<quintptr>(mPlottable);
+ return false;
+ }
+}
////////////////////////////////////////////////////////////////////////////////////////////////////
@@ -6693,10 +10225,13 @@ void QCPAxisPainterPrivate::getMaxTickLabelSize(const QFont &font, const QString
It defines a very basic interface like name, pen, brush, visibility etc. Since this class is
abstract, it can't be instantiated. Use one of the subclasses or create a subclass yourself to
- create new ways of displaying data (see "Creating own plottables" below).
+ create new ways of displaying data (see "Creating own plottables" below). Plottables that display
+ one-dimensional data (i.e. data points have a single key dimension and one or multiple values at
+ each key) are based off of the template subclass \ref QCPAbstractPlottable1D, see details
+ there.
All further specifics are in the subclasses, for example:
- \li A normal graph with possibly a line, scatter points and error bars: \ref QCPGraph
+ \li A normal graph with possibly a line and/or scatter points \ref QCPGraph
(typically created with \ref QCustomPlot::addGraph)
\li A parametric curve: \ref QCPCurve
\li A bar chart: \ref QCPBars
@@ -6706,9 +10241,13 @@ void QCPAxisPainterPrivate::getMaxTickLabelSize(const QFont &font, const QString
\section plottables-subclassing Creating own plottables
- To create an own plottable, you implement a subclass of QCPAbstractPlottable. These are the pure
- virtual functions, you must implement:
- \li \ref clearData
+ Subclassing directly from QCPAbstractPlottable is only recommended if you wish to display
+ two-dimensional data like \ref QCPColorMap, i.e. two logical key dimensions and one (or more)
+ data dimensions. If you want to display data with only one logical key dimension, you should
+ rather derive from \ref QCPAbstractPlottable1D.
+
+ If subclassing QCPAbstractPlottable directly, these are the pure virtual functions you must
+ implement:
\li \ref selectTest
\li \ref draw
\li \ref drawLegendIcon
@@ -6735,33 +10274,72 @@ void QCPAxisPainterPrivate::getMaxTickLabelSize(const QFont &font, const QString
<td>The name of the plottable.</td>
</tr><tr>
<td>QPen \b mPen</td>
- <td>The generic pen of the plottable. You should use this pen for the most prominent data representing lines in the plottable (e.g QCPGraph uses this pen for its graph lines and scatters)</td>
- </tr><tr>
- <td>QPen \b mSelectedPen</td>
- <td>The generic pen that should be used when the plottable is selected (hint: \ref mainPen gives you the right pen, depending on selection state).</td>
+ <td>The generic pen of the plottable. You should use this pen for the most prominent data representing lines in the plottable
+ (e.g QCPGraph uses this pen for its graph lines and scatters)</td>
</tr><tr>
<td>QBrush \b mBrush</td>
- <td>The generic brush of the plottable. You should use this brush for the most prominent fillable structures in the plottable (e.g. QCPGraph uses this brush to control filling under the graph)</td>
+ <td>The generic brush of the plottable. You should use this brush for the most prominent fillable structures in the plottable
+ (e.g. QCPGraph uses this brush to control filling under the graph)</td>
+ </tr><tr>
+ <td>QPointer<\ref QCPAxis> \b mKeyAxis, \b mValueAxis</td>
+ <td>The key and value axes this plottable is attached to. Call their QCPAxis::coordToPixel functions to translate coordinates
+ to pixels in either the key or value dimension. Make sure to check whether the pointer is null before using it. If one of
+ the axes is null, don't draw the plottable.</td>
</tr><tr>
- <td>QBrush \b mSelectedBrush</td>
- <td>The generic brush that should be used when the plottable is selected (hint: \ref mainBrush gives you the right brush, depending on selection state).</td>
+ <td>\ref QCPSelectionDecorator \b mSelectionDecorator</td>
+ <td>The currently set selection decorator which specifies how selected data of the plottable shall be drawn and decorated.
+ When drawing your data, you must consult this decorator for the appropriate pen/brush before drawing unselected/selected data segments.
+ Finally, you should call its \ref QCPSelectionDecorator::drawDecoration method at the end of your \ref draw implementation.</td>
</tr><tr>
- <td>QPointer<QCPAxis>\b mKeyAxis, \b mValueAxis</td>
- <td>The key and value axes this plottable is attached to. Call their QCPAxis::coordToPixel functions to translate coordinates to pixels in either the key or value dimension.
- Make sure to check whether the pointer is null before using it. If one of the axes is null, don't draw the plottable.</td>
+ <td>\ref QCP::SelectionType \b mSelectable</td>
+ <td>In which composition, if at all, this plottable's data may be selected. Enforcing this setting on the data selection is done
+ by QCPAbstractPlottable automatically.</td>
</tr><tr>
- <td>bool \b mSelected</td>
- <td>indicates whether the plottable is selected or not.</td>
+ <td>\ref QCPDataSelection \b mSelection</td>
+ <td>Holds the current selection state of the plottable's data, i.e. the selected data ranges (\ref QCPDataRange).</td>
</tr>
</table>
*/
-/* start of documentation of pure virtual functions */
+/* start of documentation of inline functions */
+
+/*! \fn QCPSelectionDecorator *QCPAbstractPlottable::selectionDecorator() const
+
+ Provides access to the selection decorator of this plottable. The selection decorator controls
+ how selected data ranges are drawn (e.g. their pen color and fill), see \ref
+ QCPSelectionDecorator for details.
+
+ If you wish to use an own \ref QCPSelectionDecorator subclass, pass an instance of it to \ref
+ setSelectionDecorator.
+*/
+
+/*! \fn bool QCPAbstractPlottable::selected() const
+
+ Returns true if there are any data points of the plottable currently selected. Use \ref selection
+ to retrieve the current \ref QCPDataSelection.
+*/
+
+/*! \fn QCPDataSelection QCPAbstractPlottable::selection() const
+
+ Returns a \ref QCPDataSelection encompassing all the data points that are currently selected on
+ this plottable.
+
+ \see selected, setSelection, setSelectable
+*/
-/*! \fn void QCPAbstractPlottable::clearData() = 0
- Clears all data in the plottable.
+/*! \fn virtual QCPPlottableInterface1D *QCPAbstractPlottable::interface1D()
+
+ If this plottable is a one-dimensional plottable, i.e. it implements the \ref
+ QCPPlottableInterface1D, returns the \a this pointer with that type. Otherwise (e.g. in the case
+ of a \ref QCPColorMap) returns zero.
+
+ You can use this method to gain read access to data coordinates while holding a pointer to the
+ abstract base class only.
*/
+/* end of documentation of inline functions */
+/* start of documentation of pure virtual functions */
+
/*! \fn void QCPAbstractPlottable::drawLegendIcon(QCPPainter *painter, const QRect &rect) const = 0
\internal
@@ -6772,36 +10350,42 @@ void QCPAxisPainterPrivate::getMaxTickLabelSize(const QFont &font, const QString
appear outside the legend icon border.
*/
-/*! \fn QCPRange QCPAbstractPlottable::getKeyRange(bool &foundRange, SignDomain inSignDomain) const = 0
- \internal
+/*! \fn QCPRange QCPAbstractPlottable::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const = 0
- called by rescaleAxes functions to get the full data key bounds. For logarithmic plots, one can
- set \a inSignDomain to either \ref sdNegative or \ref sdPositive in order to restrict the
- returned range to that sign domain. E.g. when only negative range is wanted, set \a inSignDomain
- to \ref sdNegative and all positive points will be ignored for range calculation. For no
- restriction, just set \a inSignDomain to \ref sdBoth (default). \a foundRange is an output
- parameter that indicates whether a range could be found or not. If this is false, you shouldn't
- use the returned range (e.g. no points in data).
+ Returns the coordinate range that all data in this plottable span in the key axis dimension. For
+ logarithmic plots, one can set \a inSignDomain to either \ref QCP::sdNegative or \ref
+ QCP::sdPositive in order to restrict the returned range to that sign domain. E.g. when only
+ negative range is wanted, set \a inSignDomain to \ref QCP::sdNegative and all positive points
+ will be ignored for range calculation. For no restriction, just set \a inSignDomain to \ref
+ QCP::sdBoth (default). \a foundRange is an output parameter that indicates whether a range could
+ be found or not. If this is false, you shouldn't use the returned range (e.g. no points in data).
Note that \a foundRange is not the same as \ref QCPRange::validRange, since the range returned by
- this function may have size zero, which wouldn't count as a valid range.
+ this function may have size zero (e.g. when there is only one data point). In this case \a
+ foundRange would return true, but the returned range is not a valid range in terms of \ref
+ QCPRange::validRange.
\see rescaleAxes, getValueRange
*/
-/*! \fn QCPRange QCPAbstractPlottable::getValueRange(bool &foundRange, SignDomain inSignDomain) const = 0
- \internal
+/*! \fn QCPRange QCPAbstractPlottable::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const = 0
+
+ Returns the coordinate range that the data points in the specified key range (\a inKeyRange) span
+ in the value axis dimension. For logarithmic plots, one can set \a inSignDomain to either \ref
+ QCP::sdNegative or \ref QCP::sdPositive in order to restrict the returned range to that sign
+ domain. E.g. when only negative range is wanted, set \a inSignDomain to \ref QCP::sdNegative and
+ all positive points will be ignored for range calculation. For no restriction, just set \a
+ inSignDomain to \ref QCP::sdBoth (default). \a foundRange is an output parameter that indicates
+ whether a range could be found or not. If this is false, you shouldn't use the returned range
+ (e.g. no points in data).
- called by rescaleAxes functions to get the full data value bounds. For logarithmic plots, one can
- set \a inSignDomain to either \ref sdNegative or \ref sdPositive in order to restrict the
- returned range to that sign domain. E.g. when only negative range is wanted, set \a inSignDomain
- to \ref sdNegative and all positive points will be ignored for range calculation. For no
- restriction, just set \a inSignDomain to \ref sdBoth (default). \a foundRange is an output
- parameter that indicates whether a range could be found or not. If this is false, you shouldn't
- use the returned range (e.g. no points in data).
+ If \a inKeyRange has both lower and upper bound set to zero (is equal to <tt>QCPRange()</tt>),
+ all data points are considered, without any restriction on the keys.
Note that \a foundRange is not the same as \ref QCPRange::validRange, since the range returned by
- this function may have size zero, which wouldn't count as a valid range.
+ this function may have size zero (e.g. when there is only one data point). In this case \a
+ foundRange would return true, but the returned range is not a valid range in terms of \ref
+ QCPRange::validRange.
\see rescaleAxes, getKeyRange
*/
@@ -6812,10 +10396,22 @@ void QCPAxisPainterPrivate::getMaxTickLabelSize(const QFont &font, const QString
/*! \fn void QCPAbstractPlottable::selectionChanged(bool selected)
This signal is emitted when the selection state of this plottable has changed, either by user
- interaction or by a direct call to \ref setSelected.
+ interaction or by a direct call to \ref setSelection. The parameter \a selected indicates whether
+ there are any points selected or not.
+
+ \see selectionChanged(const QCPDataSelection &selection)
+*/
+
+/*! \fn void QCPAbstractPlottable::selectionChanged(const QCPDataSelection &selection)
+
+ This signal is emitted when the selection state of this plottable has changed, either by user
+ interaction or by a direct call to \ref setSelection. The parameter \a selection holds the
+ currently selected data ranges.
+
+ \see selectionChanged(bool selected)
*/
-/*! \fn void QCPAbstractPlottable::selectableChanged(bool selectable);
+/*! \fn void QCPAbstractPlottable::selectableChanged(QCP::SelectionType selectable);
This signal is emitted when the selectability of this plottable has changed.
@@ -6840,20 +10436,29 @@ QCPAbstractPlottable::QCPAbstractPlottable(QCPAxis *keyAxis, QCPAxis *valueAxis)
mName(),
mAntialiasedFill(true),
mAntialiasedScatters(true),
- mAntialiasedErrorBars(false),
mPen(Qt::black),
- mSelectedPen(Qt::black),
mBrush(Qt::NoBrush),
- mSelectedBrush(Qt::NoBrush),
mKeyAxis(keyAxis),
mValueAxis(valueAxis),
- mSelectable(true),
- mSelected(false)
+ mSelectable(QCP::stWhole),
+ mSelectionDecorator(0)
{
if (keyAxis->parentPlot() != valueAxis->parentPlot())
qDebug() << Q_FUNC_INFO << "Parent plot of keyAxis is not the same as that of valueAxis.";
if (keyAxis->orientation() == valueAxis->orientation())
qDebug() << Q_FUNC_INFO << "keyAxis and valueAxis must be orthogonal to each other.";
+
+ mParentPlot->registerPlottable(this);
+ setSelectionDecorator(new QCPSelectionDecorator);
+}
+
+QCPAbstractPlottable::~QCPAbstractPlottable()
+{
+ if (mSelectionDecorator)
+ {
+ delete mSelectionDecorator;
+ mSelectionDecorator = 0;
+ }
}
/*!
@@ -6888,18 +10493,6 @@ void QCPAbstractPlottable::setAntialiasedScatters(bool enabled)
}
/*!
- Sets whether the error bars of this plottable are drawn antialiased or not.
-
- Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref
- QCustomPlot::setNotAntialiasedElements.
-*/
-void QCPAbstractPlottable::setAntialiasedErrorBars(bool enabled)
-{
- mAntialiasedErrorBars = enabled;
-}
-
-
-/*!
The pen is used to draw basic lines that make up the plottable representation in the
plot.
@@ -6913,17 +10506,6 @@ void QCPAbstractPlottable::setPen(const QPen &pen)
}
/*!
- When the plottable is selected, this pen is used to draw basic lines instead of the normal
- pen set via \ref setPen.
-
- \see setSelected, setSelectable, setSelectedBrush, selectTest
-*/
-void QCPAbstractPlottable::setSelectedPen(const QPen &pen)
-{
- mSelectedPen = pen;
-}
-
-/*!
The brush is used to draw basic fills of the plottable representation in the
plot. The Fill can be a color, gradient or texture, see the usage of QBrush.
@@ -6938,17 +10520,6 @@ void QCPAbstractPlottable::setBrush(const QBrush &brush)
}
/*!
- When the plottable is selected, this brush is used to draw fills instead of the normal
- brush set via \ref setBrush.
-
- \see setSelected, setSelectable, setSelectedPen, selectTest
-*/
-void QCPAbstractPlottable::setSelectedBrush(const QBrush &brush)
-{
- mSelectedBrush = brush;
-}
-
-/*!
The key axis of a plottable can be set to any axis of a QCustomPlot, as long as it is orthogonal
to the plottable's value axis. This function performs no checks to make sure this is the case.
The typical mathematical choice is to use the x-axis (QCustomPlot::xAxis) as key axis and the
@@ -6980,47 +10551,166 @@ void QCPAbstractPlottable::setValueAxis(QCPAxis *axis)
mValueAxis = axis;
}
+
/*!
- Sets whether the user can (de-)select this plottable by clicking on the QCustomPlot surface.
- (When \ref QCustomPlot::setInteractions contains iSelectPlottables.)
+ Sets which data ranges of this plottable are selected. Selected data ranges are drawn differently
+ (e.g. color) in the plot. This can be controlled via the selection decorator (see \ref
+ selectionDecorator).
- However, even when \a selectable was set to false, it is possible to set the selection manually,
- by calling \ref setSelected directly.
+ The entire selection mechanism for plottables is handled automatically when \ref
+ QCustomPlot::setInteractions contains iSelectPlottables. You only need to call this function when
+ you wish to change the selection state programmatically.
+
+ Using \ref setSelectable you can further specify for each plottable whether and to which
+ granularity it is selectable. If \a selection is not compatible with the current \ref
+ QCP::SelectionType set via \ref setSelectable, the resulting selection will be adjusted
+ accordingly (see \ref QCPDataSelection::enforceType).
+
+ emits the \ref selectionChanged signal when \a selected is different from the previous selection state.
+
+ \see setSelectable, selectTest
+*/
+void QCPAbstractPlottable::setSelection(QCPDataSelection selection)
+{
+ selection.enforceType(mSelectable);
+ if (mSelection != selection)
+ {
+ mSelection = selection;
+ emit selectionChanged(selected());
+ emit selectionChanged(mSelection);
+ }
+}
+
+/*!
+ Use this method to set an own QCPSelectionDecorator (subclass) instance. This allows you to
+ customize the visual representation of selected data ranges further than by using the default
+ QCPSelectionDecorator.
+
+ The plottable takes ownership of the \a decorator.
+
+ The currently set decorator can be accessed via \ref selectionDecorator.
+*/
+void QCPAbstractPlottable::setSelectionDecorator(QCPSelectionDecorator *decorator)
+{
+ if (decorator)
+ {
+ if (decorator->registerWithPlottable(this))
+ {
+ if (mSelectionDecorator) // delete old decorator if necessary
+ delete mSelectionDecorator;
+ mSelectionDecorator = decorator;
+ }
+ } else if (mSelectionDecorator) // just clear decorator
+ {
+ delete mSelectionDecorator;
+ mSelectionDecorator = 0;
+ }
+}
+
+/*!
+ Sets whether and to which granularity this plottable can be selected.
+
+ A selection can happen by clicking on the QCustomPlot surface (When \ref
+ QCustomPlot::setInteractions contains \ref QCP::iSelectPlottables), by dragging a selection rect
+ (When \ref QCustomPlot::setSelectionRectMode is \ref QCP::srmSelect), or programmatically by
+ calling \ref setSelection.
- \see setSelected
+ \see setSelection, QCP::SelectionType
*/
-void QCPAbstractPlottable::setSelectable(bool selectable)
+void QCPAbstractPlottable::setSelectable(QCP::SelectionType selectable)
{
if (mSelectable != selectable)
{
mSelectable = selectable;
+ QCPDataSelection oldSelection = mSelection;
+ mSelection.enforceType(mSelectable);
emit selectableChanged(mSelectable);
+ if (mSelection != oldSelection)
+ {
+ emit selectionChanged(selected());
+ emit selectionChanged(mSelection);
+ }
}
}
+
/*!
- Sets whether this plottable is selected or not. When selected, it uses a different pen and brush
- to draw its lines and fills, see \ref setSelectedPen and \ref setSelectedBrush.
+ Convenience function for transforming a key/value pair to pixels on the QCustomPlot surface,
+ taking the orientations of the axes associated with this plottable into account (e.g. whether key
+ represents x or y).
- The entire selection mechanism for plottables is handled automatically when \ref
- QCustomPlot::setInteractions contains iSelectPlottables. You only need to call this function when
- you wish to change the selection state manually.
-
- This function can change the selection state even when \ref setSelectable was set to false.
+ \a key and \a value are transformed to the coodinates in pixels and are written to \a x and \a y.
+
+ \see pixelsToCoords, QCPAxis::coordToPixel
+*/
+void QCPAbstractPlottable::coordsToPixels(double key, double value, double &x, double &y) const
+{
+ QCPAxis *keyAxis = mKeyAxis.data();
+ QCPAxis *valueAxis = mValueAxis.data();
+ if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
- emits the \ref selectionChanged signal when \a selected is different from the previous selection state.
+ if (keyAxis->orientation() == Qt::Horizontal)
+ {
+ x = keyAxis->coordToPixel(key);
+ y = valueAxis->coordToPixel(value);
+ } else
+ {
+ y = keyAxis->coordToPixel(key);
+ x = valueAxis->coordToPixel(value);
+ }
+}
+
+/*! \overload
+
+ Transforms the given \a key and \a value to pixel coordinates and returns them in a QPointF.
+*/
+const QPointF QCPAbstractPlottable::coordsToPixels(double key, double value) const
+{
+ QCPAxis *keyAxis = mKeyAxis.data();
+ QCPAxis *valueAxis = mValueAxis.data();
+ if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPointF(); }
- \see setSelectable, selectTest
+ if (keyAxis->orientation() == Qt::Horizontal)
+ return QPointF(keyAxis->coordToPixel(key), valueAxis->coordToPixel(value));
+ else
+ return QPointF(valueAxis->coordToPixel(value), keyAxis->coordToPixel(key));
+}
+
+/*!
+ Convenience function for transforming a x/y pixel pair on the QCustomPlot surface to plot coordinates,
+ taking the orientations of the axes associated with this plottable into account (e.g. whether key
+ represents x or y).
+
+ \a x and \a y are transformed to the plot coodinates and are written to \a key and \a value.
+
+ \see coordsToPixels, QCPAxis::coordToPixel
*/
-void QCPAbstractPlottable::setSelected(bool selected)
+void QCPAbstractPlottable::pixelsToCoords(double x, double y, double &key, double &value) const
{
- if (mSelected != selected)
+ QCPAxis *keyAxis = mKeyAxis.data();
+ QCPAxis *valueAxis = mValueAxis.data();
+ if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
+
+ if (keyAxis->orientation() == Qt::Horizontal)
{
- mSelected = selected;
- emit selectionChanged(mSelected);
+ key = keyAxis->pixelToCoord(x);
+ value = valueAxis->pixelToCoord(y);
+ } else
+ {
+ key = keyAxis->pixelToCoord(y);
+ value = valueAxis->pixelToCoord(x);
}
}
+/*! \overload
+
+ Returns the pixel input \a pixelPos as plot coordinates \a key and \a value.
+*/
+void QCPAbstractPlottable::pixelsToCoords(const QPointF &pixelPos, double &key, double &value) const
+{
+ pixelsToCoords(pixelPos.x(), pixelPos.y(), key, value);
+}
+
/*!
Rescales the key and value axes associated with this plottable to contain all displayed data, so
the whole plottable is visible. If the scaling of an axis is logarithmic, rescaleAxes will make
@@ -7050,9 +10740,9 @@ void QCPAbstractPlottable::rescaleKeyAxis(bool onlyEnlarge) const
QCPAxis *keyAxis = mKeyAxis.data();
if (!keyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; }
- SignDomain signDomain = sdBoth;
+ QCP::SignDomain signDomain = QCP::sdBoth;
if (keyAxis->scaleType() == QCPAxis::stLogarithmic)
- signDomain = (keyAxis->range().upper < 0 ? sdNegative : sdPositive);
+ signDomain = (keyAxis->range().upper < 0 ? QCP::sdNegative : QCP::sdPositive);
bool foundRange;
QCPRange newRange = getKeyRange(foundRange, signDomain);
@@ -7078,24 +10768,27 @@ void QCPAbstractPlottable::rescaleKeyAxis(bool onlyEnlarge) const
}
/*!
- Rescales the value axis of the plottable so the whole plottable is visible.
-
+ Rescales the value axis of the plottable so the whole plottable is visible. If \a inKeyRange is
+ set to true, only the data points which are in the currently visible key axis range are
+ considered.
+
Returns true if the axis was actually scaled. This might not be the case if this plottable has an
invalid range, e.g. because it has no data points.
-
+
See \ref rescaleAxes for detailed behaviour.
*/
-void QCPAbstractPlottable::rescaleValueAxis(bool onlyEnlarge) const
+void QCPAbstractPlottable::rescaleValueAxis(bool onlyEnlarge, bool inKeyRange) const
{
+ QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
- if (!valueAxis) { qDebug() << Q_FUNC_INFO << "invalid value axis"; return; }
+ if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
- SignDomain signDomain = sdBoth;
+ QCP::SignDomain signDomain = QCP::sdBoth;
if (valueAxis->scaleType() == QCPAxis::stLogarithmic)
- signDomain = (valueAxis->range().upper < 0 ? sdNegative : sdPositive);
+ signDomain = (valueAxis->range().upper < 0 ? QCP::sdNegative : QCP::sdPositive);
bool foundRange;
- QCPRange newRange = getValueRange(foundRange, signDomain);
+ QCPRange newRange = getValueRange(foundRange, signDomain, inKeyRange ? keyAxis->range() : QCPRange());
if (foundRange)
{
if (onlyEnlarge)
@@ -7117,166 +10810,106 @@ void QCPAbstractPlottable::rescaleValueAxis(bool onlyEnlarge) const
}
}
-/*!
- Adds this plottable to the legend of the parent QCustomPlot (QCustomPlot::legend).
-
- Normally, a QCPPlottableLegendItem is created and inserted into the legend. If the plottable
- needs a more specialized representation in the legend, this function will take this into account
- and instead create the specialized subclass of QCPAbstractLegendItem.
-
- Returns true on success, i.e. when the legend exists and a legend item associated with this plottable isn't already in
- the legend.
-
+/*! \overload
+
+ Adds this plottable to the specified \a legend.
+
+ Creates a QCPPlottableLegendItem which is inserted into the legend. Returns true on success, i.e.
+ when the legend exists and a legend item associated with this plottable isn't already in the
+ legend.
+
+ If the plottable needs a more specialized representation in the legend, you can create a
+ corresponding subclass of \ref QCPPlottableLegendItem and add it to the legend manually instead
+ of calling this method.
+
\see removeFromLegend, QCPLegend::addItem
*/
-bool QCPAbstractPlottable::addToLegend()
+bool QCPAbstractPlottable::addToLegend(QCPLegend *legend)
{
- if (!mParentPlot || !mParentPlot->legend)
+ if (!legend)
+ {
+ qDebug() << Q_FUNC_INFO << "passed legend is null";
return false;
+ }
+ if (legend->parentPlot() != mParentPlot)
+ {
+ qDebug() << Q_FUNC_INFO << "passed legend isn't in the same QCustomPlot as this plottable";
+ return false;
+ }
- if (!mParentPlot->legend->hasItemWithPlottable(this))
+ if (!legend->hasItemWithPlottable(this))
{
- mParentPlot->legend->addItem(new QCPPlottableLegendItem(mParentPlot->legend, this));
+ legend->addItem(new QCPPlottableLegendItem(legend, this));
return true;
} else
return false;
}
-/*!
- Removes the plottable from the legend of the parent QCustomPlot. This means the
- QCPAbstractLegendItem (usually a QCPPlottableLegendItem) that is associated with this plottable
- is removed.
-
- Returns true on success, i.e. if the legend exists and a legend item associated with this
- plottable was found and removed.
-
- \see addToLegend, QCPLegend::removeItem
+/*! \overload
+
+ Adds this plottable to the legend of the parent QCustomPlot (\ref QCustomPlot::legend).
+
+ \see removeFromLegend
*/
-bool QCPAbstractPlottable::removeFromLegend() const
+bool QCPAbstractPlottable::addToLegend()
{
- if (!mParentPlot->legend)
+ if (!mParentPlot || !mParentPlot->legend)
return false;
-
- if (QCPPlottableLegendItem *lip = mParentPlot->legend->itemWithPlottable(this))
- return mParentPlot->legend->removeItem(lip);
else
- return false;
+ return addToLegend(mParentPlot->legend);
}
-/* inherits documentation from base class */
-QRect QCPAbstractPlottable::clipRect() const
-{
- if (mKeyAxis && mValueAxis)
- return mKeyAxis.data()->axisRect()->rect() & mValueAxis.data()->axisRect()->rect();
- else
- return QRect();
-}
+/*! \overload
-/* inherits documentation from base class */
-QCP::Interaction QCPAbstractPlottable::selectionCategory() const
-{
- return QCP::iSelectPlottables;
-}
+ Removes the plottable from the specifed \a legend. This means the \ref QCPPlottableLegendItem
+ that is associated with this plottable is removed.
-/*! \internal
-
- Convenience function for transforming a key/value pair to pixels on the QCustomPlot surface,
- taking the orientations of the axes associated with this plottable into account (e.g. whether key
- represents x or y).
-
- \a key and \a value are transformed to the coodinates in pixels and are written to \a x and \a y.
-
- \see pixelsToCoords, QCPAxis::coordToPixel
+ Returns true on success, i.e. if the legend exists and a legend item associated with this
+ plottable was found and removed.
+
+ \see addToLegend, QCPLegend::removeItem
*/
-void QCPAbstractPlottable::coordsToPixels(double key, double value, double &x, double &y) const
+bool QCPAbstractPlottable::removeFromLegend(QCPLegend *legend) const
{
- QCPAxis *keyAxis = mKeyAxis.data();
- QCPAxis *valueAxis = mValueAxis.data();
- if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
-
- if (keyAxis->orientation() == Qt::Horizontal)
+ if (!legend)
{
- x = keyAxis->coordToPixel(key);
- y = valueAxis->coordToPixel(value);
- } else
- {
- y = keyAxis->coordToPixel(key);
- x = valueAxis->coordToPixel(value);
+ qDebug() << Q_FUNC_INFO << "passed legend is null";
+ return false;
}
-}
-
-/*! \internal
- \overload
-
- Returns the input as pixel coordinates in a QPointF.
-*/
-const QPointF QCPAbstractPlottable::coordsToPixels(double key, double value) const
-{
- QCPAxis *keyAxis = mKeyAxis.data();
- QCPAxis *valueAxis = mValueAxis.data();
- if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPointF(); }
- if (keyAxis->orientation() == Qt::Horizontal)
- return QPointF(keyAxis->coordToPixel(key), valueAxis->coordToPixel(value));
+ if (QCPPlottableLegendItem *lip = legend->itemWithPlottable(this))
+ return legend->removeItem(lip);
else
- return QPointF(valueAxis->coordToPixel(value), keyAxis->coordToPixel(key));
+ return false;
}
-/*! \internal
-
- Convenience function for transforming a x/y pixel pair on the QCustomPlot surface to plot coordinates,
- taking the orientations of the axes associated with this plottable into account (e.g. whether key
- represents x or y).
-
- \a x and \a y are transformed to the plot coodinates and are written to \a key and \a value.
-
- \see coordsToPixels, QCPAxis::coordToPixel
-*/
-void QCPAbstractPlottable::pixelsToCoords(double x, double y, double &key, double &value) const
-{
- QCPAxis *keyAxis = mKeyAxis.data();
- QCPAxis *valueAxis = mValueAxis.data();
- if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
-
- if (keyAxis->orientation() == Qt::Horizontal)
- {
- key = keyAxis->pixelToCoord(x);
- value = valueAxis->pixelToCoord(y);
- } else
- {
- key = keyAxis->pixelToCoord(y);
- value = valueAxis->pixelToCoord(x);
- }
-}
+/*! \overload
-/*! \internal
- \overload
+ Removes the plottable from the legend of the parent QCustomPlot.
- Returns the pixel input \a pixelPos as plot coordinates \a key and \a value.
+ \see addToLegend
*/
-void QCPAbstractPlottable::pixelsToCoords(const QPointF &pixelPos, double &key, double &value) const
+bool QCPAbstractPlottable::removeFromLegend() const
{
- pixelsToCoords(pixelPos.x(), pixelPos.y(), key, value);
+ if (!mParentPlot || !mParentPlot->legend)
+ return false;
+ else
+ return removeFromLegend(mParentPlot->legend);
}
-/*! \internal
-
- Returns the pen that should be used for drawing lines of the plottable. Returns mPen when the
- graph is not selected and mSelectedPen when it is.
-*/
-QPen QCPAbstractPlottable::mainPen() const
+/* inherits documentation from base class */
+QRect QCPAbstractPlottable::clipRect() const
{
- return mSelected ? mSelectedPen : mPen;
+ if (mKeyAxis && mValueAxis)
+ return mKeyAxis.data()->axisRect()->rect() & mValueAxis.data()->axisRect()->rect();
+ else
+ return QRect();
}
-/*! \internal
-
- Returns the brush that should be used for drawing fills of the plottable. Returns mBrush when the
- graph is not selected and mSelectedBrush when it is.
-*/
-QBrush QCPAbstractPlottable::mainBrush() const
+/* inherits documentation from base class */
+QCP::Interaction QCPAbstractPlottable::selectionCategory() const
{
- return mSelected ? mSelectedBrush : mBrush;
+ return QCP::iSelectPlottables;
}
/*! \internal
@@ -7290,7 +10923,9 @@ QBrush QCPAbstractPlottable::mainBrush() const
overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
QCustomPlot::setNotAntialiasedElements.
- \see setAntialiased, applyFillAntialiasingHint, applyScattersAntialiasingHint, applyErrorBarsAntialiasingHint
+ \seebaseclassmethod
+
+ \see setAntialiased, applyFillAntialiasingHint, applyScattersAntialiasingHint
*/
void QCPAbstractPlottable::applyDefaultAntialiasingHint(QCPPainter *painter) const
{
@@ -7306,7 +10941,7 @@ void QCPAbstractPlottable::applyDefaultAntialiasingHint(QCPPainter *painter) con
overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
QCustomPlot::setNotAntialiasedElements.
- \see setAntialiased, applyDefaultAntialiasingHint, applyScattersAntialiasingHint, applyErrorBarsAntialiasingHint
+ \see setAntialiased, applyDefaultAntialiasingHint, applyScattersAntialiasingHint
*/
void QCPAbstractPlottable::applyFillAntialiasingHint(QCPPainter *painter) const
{
@@ -7322,86 +10957,60 @@ void QCPAbstractPlottable::applyFillAntialiasingHint(QCPPainter *painter) const
overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
QCustomPlot::setNotAntialiasedElements.
- \see setAntialiased, applyFillAntialiasingHint, applyDefaultAntialiasingHint, applyErrorBarsAntialiasingHint
+ \see setAntialiased, applyFillAntialiasingHint, applyDefaultAntialiasingHint
*/
void QCPAbstractPlottable::applyScattersAntialiasingHint(QCPPainter *painter) const
{
applyAntialiasingHint(painter, mAntialiasedScatters, QCP::aeScatters);
}
-/*! \internal
-
- A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
- before drawing plottable error bars.
-
- This function takes into account the local setting of the antialiasing flag as well as the
- overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
- QCustomPlot::setNotAntialiasedElements.
-
- \see setAntialiased, applyFillAntialiasingHint, applyScattersAntialiasingHint, applyDefaultAntialiasingHint
-*/
-void QCPAbstractPlottable::applyErrorBarsAntialiasingHint(QCPPainter *painter) const
-{
- applyAntialiasingHint(painter, mAntialiasedErrorBars, QCP::aeErrorBars);
-}
-
-/*! \internal
-
- Finds the shortest squared distance of \a point to the line segment defined by \a start and \a
- end.
-
- This function may be used to help with the implementation of the \ref selectTest function for
- specific plottables.
-
- \note This function is identical to QCPAbstractItem::distSqrToLine
-*/
-double QCPAbstractPlottable::distSqrToLine(const QPointF &start, const QPointF &end, const QPointF &point) const
-{
- QVector2D a(start);
- QVector2D b(end);
- QVector2D p(point);
- QVector2D v(b-a);
-
- double vLengthSqr = v.lengthSquared();
- if (!qFuzzyIsNull(vLengthSqr))
- {
- double mu = QVector2D::dotProduct(p-a, v)/vLengthSqr;
- if (mu < 0)
- return (a-p).lengthSquared();
- else if (mu > 1)
- return (b-p).lengthSquared();
- else
- return ((a + mu*v)-p).lengthSquared();
- } else
- return (a-p).lengthSquared();
-}
-
/* inherits documentation from base class */
void QCPAbstractPlottable::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
{
Q_UNUSED(event)
- Q_UNUSED(details)
- if (mSelectable)
+
+ if (mSelectable != QCP::stNone)
{
- bool selBefore = mSelected;
- setSelected(additive ? !mSelected : true);
+ QCPDataSelection newSelection = details.value<QCPDataSelection>();
+ QCPDataSelection selectionBefore = mSelection;
+ if (additive)
+ {
+ if (mSelectable == QCP::stWhole) // in whole selection mode, we toggle to no selection even if currently unselected point was hit
+ {
+ if (selected())
+ setSelection(QCPDataSelection());
+ else
+ setSelection(newSelection);
+ } else // in all other selection modes we toggle selections of homogeneously selected/unselected segments
+ {
+ if (mSelection.contains(newSelection)) // if entire newSelection is already selected, toggle selection
+ setSelection(mSelection-newSelection);
+ else
+ setSelection(mSelection+newSelection);
+ }
+ } else
+ setSelection(newSelection);
if (selectionStateChanged)
- *selectionStateChanged = mSelected != selBefore;
+ *selectionStateChanged = mSelection != selectionBefore;
}
}
/* inherits documentation from base class */
void QCPAbstractPlottable::deselectEvent(bool *selectionStateChanged)
{
- if (mSelectable)
+ if (mSelectable != QCP::stNone)
{
- bool selBefore = mSelected;
- setSelected(false);
+ QCPDataSelection selectionBefore = mSelection;
+ setSelection(QCPDataSelection());
if (selectionStateChanged)
- *selectionStateChanged = mSelected != selBefore;
+ *selectionStateChanged = mSelection != selectionBefore;
}
}
+/* end of 'src/plottable.cpp' */
+
+/* including file 'src/item.cpp', size 49269 */
+/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPItemAnchor
@@ -7447,7 +11056,7 @@ void QCPAbstractPlottable::deselectEvent(bool *selectionStateChanged)
you want to make a new item subclass. Use \ref QCPAbstractItem::createAnchor instead, as
explained in the subclassing section of the QCPAbstractItem documentation.
*/
-QCPItemAnchor::QCPItemAnchor(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString name, int anchorId) :
+QCPItemAnchor::QCPItemAnchor(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString &name, int anchorId) :
mName(name),
mParentPlot(parentPlot),
mParentItem(parentItem),
@@ -7476,13 +11085,13 @@ QCPItemAnchor::~QCPItemAnchor()
The pixel information is internally retrieved via QCPAbstractItem::anchorPixelPosition of the
parent item, QCPItemAnchor is just an intermediary.
*/
-QPointF QCPItemAnchor::pixelPoint() const
+QPointF QCPItemAnchor::pixelPosition() const
{
if (mParentItem)
{
if (mAnchorId > -1)
{
- return mParentItem->anchorPixelPoint(mAnchorId);
+ return mParentItem->anchorPixelPosition(mAnchorId);
} else
{
qDebug() << Q_FUNC_INFO << "no valid anchor id set:" << mAnchorId;
@@ -7584,9 +11193,9 @@ void QCPItemAnchor::removeChildY(QCPItemPosition *pos)
Note that every QCPItemPosition inherits from QCPItemAnchor and thus can itself be used as parent
anchor for other positions.
- To set the apparent pixel position on the QCustomPlot surface directly, use \ref setPixelPoint. This
+ To set the apparent pixel position on the QCustomPlot surface directly, use \ref setPixelPosition. This
works no matter what type this QCPItemPosition is or what parent-child situation it is in, as \ref
- setPixelPoint transforms the coordinates appropriately, to make the position appear at the specified
+ setPixelPosition transforms the coordinates appropriately, to make the position appear at the specified
pixel values.
*/
@@ -7620,7 +11229,7 @@ void QCPItemAnchor::removeChildY(QCPItemPosition *pos)
you want to make a new item subclass. Use \ref QCPAbstractItem::createPosition instead, as
explained in the subclassing section of the QCPAbstractItem documentation.
*/
-QCPItemPosition::QCPItemPosition(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString name) :
+QCPItemPosition::QCPItemPosition(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString &name) :
QCPItemAnchor(parentPlot, parentItem, name),
mPositionTypeX(ptAbsolute),
mPositionTypeY(ptAbsolute),
@@ -7635,7 +11244,7 @@ QCPItemPosition::~QCPItemPosition()
{
// unregister as parent at children:
// Note: this is done in ~QCPItemAnchor again, but it's important QCPItemPosition does it itself, because only then
- // the setParentAnchor(0) call the correct QCPItemPosition::pixelPoint function instead of QCPItemAnchor::pixelPoint
+ // the setParentAnchor(0) call the correct QCPItemPosition::pixelPosition function instead of QCPItemAnchor::pixelPosition
foreach (QCPItemPosition *child, mChildrenX.toList())
{
if (child->parentAnchorX() == this)
@@ -7702,7 +11311,7 @@ void QCPItemPosition::setTypeX(QCPItemPosition::PositionType type)
if (mPositionTypeX != type)
{
// if switching from or to coordinate type that isn't valid (e.g. because axes or axis rect
- // were deleted), don't try to recover the pixelPoint() because it would output a qDebug warning.
+ // were deleted), don't try to recover the pixelPosition() because it would output a qDebug warning.
bool retainPixelPosition = true;
if ((mPositionTypeX == ptPlotCoords || type == ptPlotCoords) && (!mKeyAxis || !mValueAxis))
retainPixelPosition = false;
@@ -7711,12 +11320,12 @@ void QCPItemPosition::setTypeX(QCPItemPosition::PositionType type)
QPointF pixel;
if (retainPixelPosition)
- pixel = pixelPoint();
+ pixel = pixelPosition();
mPositionTypeX = type;
if (retainPixelPosition)
- setPixelPoint(pixel);
+ setPixelPosition(pixel);
}
}
@@ -7732,7 +11341,7 @@ void QCPItemPosition::setTypeY(QCPItemPosition::PositionType type)
if (mPositionTypeY != type)
{
// if switching from or to coordinate type that isn't valid (e.g. because axes or axis rect
- // were deleted), don't try to recover the pixelPoint() because it would output a qDebug warning.
+ // were deleted), don't try to recover the pixelPosition() because it would output a qDebug warning.
bool retainPixelPosition = true;
if ((mPositionTypeY == ptPlotCoords || type == ptPlotCoords) && (!mKeyAxis || !mValueAxis))
retainPixelPosition = false;
@@ -7741,12 +11350,12 @@ void QCPItemPosition::setTypeY(QCPItemPosition::PositionType type)
QPointF pixel;
if (retainPixelPosition)
- pixel = pixelPoint();
+ pixel = pixelPosition();
mPositionTypeY = type;
if (retainPixelPosition)
- setPixelPoint(pixel);
+ setPixelPosition(pixel);
}
}
@@ -7824,7 +11433,7 @@ bool QCPItemPosition::setParentAnchorX(QCPItemAnchor *parentAnchor, bool keepPix
// save pixel position:
QPointF pixelP;
if (keepPixelPosition)
- pixelP = pixelPoint();
+ pixelP = pixelPosition();
// unregister at current parent anchor:
if (mParentAnchorX)
mParentAnchorX->removeChildX(this);
@@ -7834,7 +11443,7 @@ bool QCPItemPosition::setParentAnchorX(QCPItemAnchor *parentAnchor, bool keepPix
mParentAnchorX = parentAnchor;
// restore pixel position under new parent:
if (keepPixelPosition)
- setPixelPoint(pixelP);
+ setPixelPosition(pixelP);
else
setCoords(0, coords().y());
return true;
@@ -7889,7 +11498,7 @@ bool QCPItemPosition::setParentAnchorY(QCPItemAnchor *parentAnchor, bool keepPix
// save pixel position:
QPointF pixelP;
if (keepPixelPosition)
- pixelP = pixelPoint();
+ pixelP = pixelPosition();
// unregister at current parent anchor:
if (mParentAnchorY)
mParentAnchorY->removeChildY(this);
@@ -7899,7 +11508,7 @@ bool QCPItemPosition::setParentAnchorY(QCPItemAnchor *parentAnchor, bool keepPix
mParentAnchorY = parentAnchor;
// restore pixel position under new parent:
if (keepPixelPosition)
- setPixelPoint(pixelP);
+ setPixelPosition(pixelP);
else
setCoords(coords().x(), 0);
return true;
@@ -7920,7 +11529,7 @@ bool QCPItemPosition::setParentAnchorY(QCPItemAnchor *parentAnchor, bool keepPix
value must also be provided in the different coordinate systems. Here, the X type refers to \a
key, and the Y type refers to \a value.
- \see setPixelPoint
+ \see setPixelPosition
*/
void QCPItemPosition::setCoords(double key, double value)
{
@@ -7942,9 +11551,9 @@ void QCPItemPosition::setCoords(const QPointF &pos)
Returns the final absolute pixel position of the QCPItemPosition on the QCustomPlot surface. It
includes all effects of type (\ref setType) and possible parent anchors (\ref setParentAnchor).
- \see setPixelPoint
+ \see setPixelPosition
*/
-QPointF QCPItemPosition::pixelPoint() const
+QPointF QCPItemPosition::pixelPosition() const
{
QPointF result;
@@ -7955,14 +11564,14 @@ QPointF QCPItemPosition::pixelPoint() const
{
result.rx() = mKey;
if (mParentAnchorX)
- result.rx() += mParentAnchorX->pixelPoint().x();
+ result.rx() += mParentAnchorX->pixelPosition().x();
break;
}
case ptViewportRatio:
{
result.rx() = mKey*mParentPlot->viewport().width();
if (mParentAnchorX)
- result.rx() += mParentAnchorX->pixelPoint().x();
+ result.rx() += mParentAnchorX->pixelPosition().x();
else
result.rx() += mParentPlot->viewport().left();
break;
@@ -7973,7 +11582,7 @@ QPointF QCPItemPosition::pixelPoint() const
{
result.rx() = mKey*mAxisRect.data()->width();
if (mParentAnchorX)
- result.rx() += mParentAnchorX->pixelPoint().x();
+ result.rx() += mParentAnchorX->pixelPosition().x();
else
result.rx() += mAxisRect.data()->left();
} else
@@ -7999,14 +11608,14 @@ QPointF QCPItemPosition::pixelPoint() const
{
result.ry() = mValue;
if (mParentAnchorY)
- result.ry() += mParentAnchorY->pixelPoint().y();
+ result.ry() += mParentAnchorY->pixelPosition().y();
break;
}
case ptViewportRatio:
{
result.ry() = mValue*mParentPlot->viewport().height();
if (mParentAnchorY)
- result.ry() += mParentAnchorY->pixelPoint().y();
+ result.ry() += mParentAnchorY->pixelPosition().y();
else
result.ry() += mParentPlot->viewport().top();
break;
@@ -8017,7 +11626,7 @@ QPointF QCPItemPosition::pixelPoint() const
{
result.ry() = mValue*mAxisRect.data()->height();
if (mParentAnchorY)
- result.ry() += mParentAnchorY->pixelPoint().y();
+ result.ry() += mParentAnchorY->pixelPosition().y();
else
result.ry() += mAxisRect.data()->top();
} else
@@ -8068,25 +11677,25 @@ void QCPItemPosition::setAxisRect(QCPAxisRect *axisRect)
Only if the type is \ref ptAbsolute and no parent anchor is set, this function's effect is
identical to that of \ref setCoords.
- \see pixelPoint, setCoords
+ \see pixelPosition, setCoords
*/
-void QCPItemPosition::setPixelPoint(const QPointF &pixelPoint)
+void QCPItemPosition::setPixelPosition(const QPointF &pixelPosition)
{
- double x = pixelPoint.x();
- double y = pixelPoint.y();
+ double x = pixelPosition.x();
+ double y = pixelPosition.y();
switch (mPositionTypeX)
{
case ptAbsolute:
{
if (mParentAnchorX)
- x -= mParentAnchorX->pixelPoint().x();
+ x -= mParentAnchorX->pixelPosition().x();
break;
}
case ptViewportRatio:
{
if (mParentAnchorX)
- x -= mParentAnchorX->pixelPoint().x();
+ x -= mParentAnchorX->pixelPosition().x();
else
x -= mParentPlot->viewport().left();
x /= (double)mParentPlot->viewport().width();
@@ -8097,7 +11706,7 @@ void QCPItemPosition::setPixelPoint(const QPointF &pixelPoint)
if (mAxisRect)
{
if (mParentAnchorX)
- x -= mParentAnchorX->pixelPoint().x();
+ x -= mParentAnchorX->pixelPosition().x();
else
x -= mAxisRect.data()->left();
x /= (double)mAxisRect.data()->width();
@@ -8122,13 +11731,13 @@ void QCPItemPosition::setPixelPoint(const QPointF &pixelPoint)
case ptAbsolute:
{
if (mParentAnchorY)
- y -= mParentAnchorY->pixelPoint().y();
+ y -= mParentAnchorY->pixelPosition().y();
break;
}
case ptViewportRatio:
{
if (mParentAnchorY)
- y -= mParentAnchorY->pixelPoint().y();
+ y -= mParentAnchorY->pixelPosition().y();
else
y -= mParentPlot->viewport().top();
y /= (double)mParentPlot->viewport().height();
@@ -8139,7 +11748,7 @@ void QCPItemPosition::setPixelPoint(const QPointF &pixelPoint)
if (mAxisRect)
{
if (mParentAnchorY)
- y -= mParentAnchorY->pixelPoint().y();
+ y -= mParentAnchorY->pixelPosition().y();
else
y -= mAxisRect.data()->top();
y /= (double)mAxisRect.data()->height();
@@ -8262,7 +11871,7 @@ void QCPItemPosition::setPixelPoint(const QPointF &pixelPoint)
To give your item a visual representation, reimplement the \ref draw function and use the passed
QCPPainter to draw the item. You can retrieve the item position in pixel coordinates from the
- position member(s) via \ref QCPItemPosition::pixelPoint.
+ position member(s) via \ref QCPItemPosition::pixelPosition.
To optimize performance you should calculate a bounding rect first (don't forget to take the pen
width into account), check whether it intersects the \ref clipRect, and only draw the item at all
@@ -8270,10 +11879,10 @@ void QCPItemPosition::setPixelPoint(const QPointF &pixelPoint)
\subsection items-selection The selectTest function
- Your implementation of the \ref selectTest function may use the helpers \ref distSqrToLine and
- \ref rectSelectTest. With these, the implementation of the selection test becomes significantly
- simpler for most items. See the documentation of \ref selectTest for what the function parameters
- mean and what the function should return.
+ Your implementation of the \ref selectTest function may use the helpers \ref
+ QCPVector2D::distanceSquaredToLine and \ref rectDistance. With these, the implementation of the
+ selection test becomes significantly simpler for most items. See the documentation of \ref
+ selectTest for what the function parameters mean and what the function should return.
\subsection anchors Providing anchors
@@ -8285,7 +11894,7 @@ void QCPItemPosition::setPixelPoint(const QPointF &pixelPoint)
and create it in the constructor with the \ref createAnchor function, assigning it a name and an
anchor id (an integer enumerating all anchors on the item, you may create an own enum for this).
Since anchors can be placed anywhere, relative to the item's position(s), your item needs to
- provide the position of every anchor with the reimplementation of the \ref anchorPixelPoint(int
+ provide the position of every anchor with the reimplementation of the \ref anchorPixelPosition(int
anchorId) function.
In essence the QCPItemAnchor is merely an intermediary that itself asks your item for the pixel
@@ -8341,6 +11950,8 @@ QCPAbstractItem::QCPAbstractItem(QCustomPlot *parentPlot) :
mSelectable(true),
mSelected(false)
{
+ parentPlot->registerItem(this);
+
QList<QCPAxisRect*> rects = parentPlot->axisRects();
if (rects.size() > 0)
{
@@ -8493,7 +12104,7 @@ bool QCPAbstractItem::hasAnchor(const QString &name) const
Returns the rect the visual representation of this item is clipped to. This depends on the
current setting of \ref setClipToAxisRect as well as the axis rect set with \ref setClipAxisRect.
- If the item is not clipped to an axis rect, the \ref QCustomPlot::viewport rect is returned.
+ If the item is not clipped to an axis rect, QCustomPlot's viewport rect is returned.
\see draw
*/
@@ -8525,39 +12136,6 @@ void QCPAbstractItem::applyDefaultAntialiasingHint(QCPPainter *painter) const
/*! \internal
- Finds the shortest squared distance of \a point to the line segment defined by \a start and \a
- end.
-
- This function may be used to help with the implementation of the \ref selectTest function for
- specific items.
-
- \note This function is identical to QCPAbstractPlottable::distSqrToLine
-
- \see rectSelectTest
-*/
-double QCPAbstractItem::distSqrToLine(const QPointF &start, const QPointF &end, const QPointF &point) const
-{
- QVector2D a(start);
- QVector2D b(end);
- QVector2D p(point);
- QVector2D v(b-a);
-
- double vLengthSqr = v.lengthSquared();
- if (!qFuzzyIsNull(vLengthSqr))
- {
- double mu = QVector2D::dotProduct(p-a, v)/vLengthSqr;
- if (mu < 0)
- return (a-p).lengthSquared();
- else if (mu > 1)
- return (b-p).lengthSquared();
- else
- return ((a + mu*v)-p).lengthSquared();
- } else
- return (a-p).lengthSquared();
-}
-
-/*! \internal
-
A convenience function which returns the selectTest value for a specified \a rect and a specified
click position \a pos. \a filledRect defines whether a click inside the rect should also be
considered a hit or whether only the rect border is sensitive to hits.
@@ -8566,12 +12144,10 @@ double QCPAbstractItem::distSqrToLine(const QPointF &start, const QPointF &end,
specific items.
For example, if your item consists of four rects, call this function four times, once for each
- rect, in your \ref selectTest reimplementation. Finally, return the minimum of all four returned
- values.
-
- \see distSqrToLine
+ rect, in your \ref selectTest reimplementation. Finally, return the minimum (non -1) of all four
+ returned values.
*/
-double QCPAbstractItem::rectSelectTest(const QRectF &rect, const QPointF &pos, bool filledRect) const
+double QCPAbstractItem::rectDistance(const QRectF &rect, const QPointF &pos, bool filledRect) const
{
double result = -1;
@@ -8582,7 +12158,7 @@ double QCPAbstractItem::rectSelectTest(const QRectF &rect, const QPointF &pos, b
double minDistSqr = std::numeric_limits<double>::max();
for (int i=0; i<lines.size(); ++i)
{
- double distSqr = distSqrToLine(lines.at(i).p1(), lines.at(i).p2(), pos);
+ double distSqr = QCPVector2D(pos).distanceSquaredToLine(lines.at(i).p1(), lines.at(i).p2());
if (distSqr < minDistSqr)
minDistSqr = distSqr;
}
@@ -8607,7 +12183,7 @@ double QCPAbstractItem::rectSelectTest(const QRectF &rect, const QPointF &pos, b
\see createAnchor
*/
-QPointF QCPAbstractItem::anchorPixelPoint(int anchorId) const
+QPointF QCPAbstractItem::anchorPixelPosition(int anchorId) const
{
qDebug() << Q_FUNC_INFO << "called on item which shouldn't have any anchors (this method not reimplemented). anchorId" << anchorId;
return QPointF();
@@ -8650,7 +12226,7 @@ QCPItemPosition *QCPAbstractItem::createPosition(const QString &name)
The \a anchorId must be a number identifying the created anchor. It is recommended to create an
enum (e.g. "AnchorIndex") for this on each item that uses anchors. This id is used by the anchor
- to identify itself when it calls QCPAbstractItem::anchorPixelPoint. That function then returns
+ to identify itself when it calls QCPAbstractItem::anchorPixelPosition. That function then returns
the correct pixel coordinates for the passed anchor id.
Don't delete anchors created by this function manually, as the item will take care of it.
@@ -8701,11 +12277,11 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const
{
return QCP::iSelectItems;
}
+/* end of 'src/item.cpp' */
-/*! \file */
-
-
+/* including file 'src/core.cpp', size 124243 */
+/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCustomPlot
@@ -8722,19 +12298,12 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const
/* start of documentation of inline functions */
-/*! \fn QRect QCustomPlot::viewport() const
+/*! \fn QCPSelectionRect *QCustomPlot::selectionRect() const
- Returns the viewport rect of this QCustomPlot instance. The viewport is the area the plot is
- drawn in, all mechanisms, e.g. margin caluclation take the viewport to be the outer border of the
- plot. The viewport normally is the rect() of the QCustomPlot widget, i.e. a rect with top left
- (0, 0) and size of the QCustomPlot widget.
-
- Don't confuse the viewport with the axis rect (QCustomPlot::axisRect). An axis rect is typically
- an area enclosed by four axes, where the graphs/plottables are drawn in. The viewport is larger
- and contains also the axes themselves, their tick numbers, their labels, the plot title etc.
+ Allows access to the currently used QCPSelectionRect instance (or subclass thereof), that is used
+ to handle and draw selection rect interactions (see \ref setSelectionRectMode).
- Only when saving to a file (see \ref savePng, \ref savePdf etc.) the viewport is temporarily
- modified to allow saving plots with sizes independent of the current widget size.
+ \see setSelectionRect
*/
/*! \fn QCPLayoutGrid *QCustomPlot::plotLayout() const
@@ -8792,23 +12361,25 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const
QCPAxisRect::setRangeZoomAxes or \ref QCPAxisRect::setRangeZoomFactor.
*/
-/*! \fn void QCustomPlot::plottableClick(QCPAbstractPlottable *plottable, QMouseEvent *event)
-
+/*! \fn void QCustomPlot::plottableClick(QCPAbstractPlottable *plottable, int dataIndex, QMouseEvent *event)
+
This signal is emitted when a plottable is clicked.
\a event is the mouse event that caused the click and \a plottable is the plottable that received
- the click.
-
+ the click. The parameter \a dataIndex indicates the data point that was closest to the click
+ position.
+
\see plottableDoubleClick
*/
-/*! \fn void QCustomPlot::plottableDoubleClick(QCPAbstractPlottable *plottable, QMouseEvent *event)
-
+/*! \fn void QCustomPlot::plottableDoubleClick(QCPAbstractPlottable *plottable, int dataIndex, QMouseEvent *event)
+
This signal is emitted when a plottable is double clicked.
-
+
\a event is the mouse event that caused the click and \a plottable is the plottable that received
- the click.
-
+ the click. The parameter \a dataIndex indicates the data point that was closest to the click
+ position.
+
\see plottableClick
*/
@@ -8876,35 +12447,16 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const
\see legendClick
*/
-/*! \fn void QCustomPlot:: titleClick(QMouseEvent *event, QCPPlotTitle *title)
-
- This signal is emitted when a plot title is clicked.
-
- \a event is the mouse event that caused the click and \a title is the plot title that received
- the click.
-
- \see titleDoubleClick
-*/
-
-/*! \fn void QCustomPlot::titleDoubleClick(QMouseEvent *event, QCPPlotTitle *title)
-
- This signal is emitted when a plot title is double clicked.
-
- \a event is the mouse event that caused the click and \a title is the plot title that received
- the click.
-
- \see titleClick
-*/
-
/*! \fn void QCustomPlot::selectionChangedByUser()
This signal is emitted after the user has changed the selection in the QCustomPlot, e.g. by
clicking. It is not emitted when the selection state of an object has changed programmatically by
- a direct call to setSelected() on an object or by calling \ref deselectAll.
+ a direct call to <tt>setSelected()</tt>/<tt>setSelection()</tt> on an object or by calling \ref
+ deselectAll.
- In addition to this signal, selectable objects also provide individual signals, for example
- QCPAxis::selectionChanged or QCPAbstractPlottable::selectionChanged. Note that those signals are
- emitted even if the selection state is changed programmatically.
+ In addition to this signal, selectable objects also provide individual signals, for example \ref
+ QCPAxis::selectionChanged or \ref QCPAbstractPlottable::selectionChanged. Note that those signals
+ are emitted even if the selection state is changed programmatically.
See the documentation of \ref setInteractions for details about the selection mechanism.
@@ -8947,6 +12499,11 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const
QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the
default legend is removed due to manipulation of the layout system (e.g. by removing the main
axis rect), the corresponding pointers become 0.
+
+ If an axis convenience pointer is currently zero and a new axis rect or a corresponding axis is
+ added in the place of the main axis rect, QCustomPlot resets the convenience pointers to the
+ according new axes. Similarly the \ref legend convenience pointer will be reset if a legend is
+ added after the main legend was removed before.
*/
/*! \var QCPAxis *QCustomPlot::yAxis
@@ -8960,6 +12517,11 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const
QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the
default legend is removed due to manipulation of the layout system (e.g. by removing the main
axis rect), the corresponding pointers become 0.
+
+ If an axis convenience pointer is currently zero and a new axis rect or a corresponding axis is
+ added in the place of the main axis rect, QCustomPlot resets the convenience pointers to the
+ according new axes. Similarly the \ref legend convenience pointer will be reset if a legend is
+ added after the main legend was removed before.
*/
/*! \var QCPAxis *QCustomPlot::xAxis2
@@ -8975,6 +12537,11 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const
QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the
default legend is removed due to manipulation of the layout system (e.g. by removing the main
axis rect), the corresponding pointers become 0.
+
+ If an axis convenience pointer is currently zero and a new axis rect or a corresponding axis is
+ added in the place of the main axis rect, QCustomPlot resets the convenience pointers to the
+ according new axes. Similarly the \ref legend convenience pointer will be reset if a legend is
+ added after the main legend was removed before.
*/
/*! \var QCPAxis *QCustomPlot::yAxis2
@@ -8990,6 +12557,11 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const
QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the
default legend is removed due to manipulation of the layout system (e.g. by removing the main
axis rect), the corresponding pointers become 0.
+
+ If an axis convenience pointer is currently zero and a new axis rect or a corresponding axis is
+ added in the place of the main axis rect, QCustomPlot resets the convenience pointers to the
+ according new axes. Similarly the \ref legend convenience pointer will be reset if a legend is
+ added after the main legend was removed before.
*/
/*! \var QCPLegend *QCustomPlot::legend
@@ -9005,6 +12577,11 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const
QCPAxisRect::insetLayout "inset layout", and must then also be accessed via the inset layout. If
the default legend is removed due to manipulation of the layout system (e.g. by removing the main
axis rect), the corresponding pointer becomes 0.
+
+ If an axis convenience pointer is currently zero and a new axis rect or a corresponding axis is
+ added in the place of the main axis rect, QCustomPlot resets the convenience pointers to the
+ according new axes. Similarly the \ref legend convenience pointer will be reset if a legend is
+ added after the main legend was removed before.
*/
/* end of documentation of public members */
@@ -9019,6 +12596,7 @@ QCustomPlot::QCustomPlot(QWidget *parent) :
xAxis2(0),
yAxis2(0),
legend(0),
+ mBufferDevicePixelRatio(1.0), // will be adapted to primary screen below
mPlotLayout(0),
mAutoAddPlottableToLegend(true),
mAntialiasedElements(QCP::aeNone),
@@ -9030,27 +12608,42 @@ QCustomPlot::QCustomPlot(QWidget *parent) :
mBackgroundScaled(true),
mBackgroundScaledMode(Qt::KeepAspectRatioByExpanding),
mCurrentLayer(0),
- mPlottingHints(QCP::phCacheLabels|QCP::phForceRepaint),
+ mPlottingHints(QCP::phCacheLabels|QCP::phImmediateRefresh),
mMultiSelectModifier(Qt::ControlModifier),
- mPaintBuffer(size()),
- mMouseEventElement(0),
- mReplotting(false)
+ mSelectionRectMode(QCP::srmNone),
+ mSelectionRect(0),
+ mOpenGl(false),
+ mMouseHasMoved(false),
+ mMouseEventLayerable(0),
+ mReplotting(false),
+ mReplotQueued(false),
+ mOpenGlMultisamples(16),
+ mOpenGlAntialiasedElementsBackup(QCP::aeNone),
+ mOpenGlCacheLabelsBackup(true)
{
setAttribute(Qt::WA_NoMousePropagation);
setAttribute(Qt::WA_OpaquePaintEvent);
+ setFocusPolicy(Qt::ClickFocus);
setMouseTracking(true);
QLocale currentLocale = locale();
currentLocale.setNumberOptions(QLocale::OmitGroupSeparator);
setLocale(currentLocale);
+#ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
+ setBufferDevicePixelRatio(QWidget::devicePixelRatio());
+#endif
+ mOpenGlAntialiasedElementsBackup = mAntialiasedElements;
+ mOpenGlCacheLabelsBackup = mPlottingHints.testFlag(QCP::phCacheLabels);
// create initial layers:
mLayers.append(new QCPLayer(this, QLatin1String("background")));
mLayers.append(new QCPLayer(this, QLatin1String("grid")));
mLayers.append(new QCPLayer(this, QLatin1String("main")));
mLayers.append(new QCPLayer(this, QLatin1String("axes")));
mLayers.append(new QCPLayer(this, QLatin1String("legend")));
+ mLayers.append(new QCPLayer(this, QLatin1String("overlay")));
updateLayerIndices();
setCurrentLayer(QLatin1String("main"));
+ layer(QLatin1String("overlay"))->setMode(QCPLayer::lmBuffered);
// create initial layout, axis rect and legend:
mPlotLayout = new QCPLayoutGrid;
@@ -9079,9 +12672,13 @@ QCustomPlot::QCustomPlot(QWidget *parent) :
yAxis2->grid()->setLayer(QLatin1String("grid"));
legend->setLayer(QLatin1String("legend"));
+ // create selection rect instance:
+ mSelectionRect = new QCPSelectionRect(this);
+ mSelectionRect->setLayer(QLatin1String("overlay"));
+
setViewport(rect()); // needs to be called after mPlotLayout has been created
- replot();
+ replot(rpQueuedReplot);
}
QCustomPlot::~QCustomPlot()
@@ -9195,7 +12792,7 @@ void QCustomPlot::setNotAntialiasedElement(QCP::AntialiasedElement notAntialiase
If set to true, adding a plottable (e.g. a graph) to the QCustomPlot automatically also adds the
plottable to the legend (QCustomPlot::legend).
- \see addPlottable, addGraph, QCPLegend::addItem
+ \see addGraph, QCPLegend::addItem
*/
void QCustomPlot::setAutoAddPlottableToLegend(bool on)
{
@@ -9212,14 +12809,14 @@ void QCustomPlot::setAutoAddPlottableToLegend(bool on)
QCPAxisRect::setRangeDrag, \ref QCPAxisRect::setRangeZoom, \ref QCPAxisRect::setRangeDragAxes,
\ref QCPAxisRect::setRangeZoomAxes.
- <b>Plottable selection</b> is controlled by \ref QCP::iSelectPlottables. If \ref QCP::iSelectPlottables is
- set, the user may select plottables (graphs, curves, bars,...) by clicking on them or in their
- vicinity (\ref setSelectionTolerance). Whether the user can actually select a plottable can
- further be restricted with the \ref QCPAbstractPlottable::setSelectable function on the specific
- plottable. To find out whether a specific plottable is selected, call
- QCPAbstractPlottable::selected(). To retrieve a list of all currently selected plottables, call
- \ref selectedPlottables. If you're only interested in QCPGraphs, you may use the convenience
- function \ref selectedGraphs.
+ <b>Plottable data selection</b> is controlled by \ref QCP::iSelectPlottables. If \ref
+ QCP::iSelectPlottables is set, the user may select plottables (graphs, curves, bars,...) and
+ their data by clicking on them or in their vicinity (\ref setSelectionTolerance). Whether the
+ user can actually select a plottable and its data can further be restricted with the \ref
+ QCPAbstractPlottable::setSelectable method on the specific plottable. For details, see the
+ special page about the \ref dataselection "data selection mechanism". To retrieve a list of all
+ currently selected plottables, call \ref selectedPlottables. If you're only interested in
+ QCPGraphs, you may use the convenience function \ref selectedGraphs.
<b>Item selection</b> is controlled by \ref QCP::iSelectItems. If \ref QCP::iSelectItems is set, the user
may select items (QCPItemLine, QCPItemText,...) by clicking on them or in their vicinity. To find
@@ -9239,7 +12836,7 @@ void QCustomPlot::setAutoAddPlottableToLegend(bool on)
find out which child items are selected, call \ref QCPLegend::selectedItems.
<b>All other selectable elements</b> The selection of all other selectable objects (e.g.
- QCPPlotTitle, or your own layerable subclasses) is controlled with \ref QCP::iSelectOther. If set, the
+ QCPTextElement, or your own layerable subclasses) is controlled with \ref QCP::iSelectOther. If set, the
user may select those objects by clicking on them. To find out which are currently selected, you
need to check their selected state explicitly.
@@ -9338,8 +12935,8 @@ void QCustomPlot::setPlottingHint(QCP::PlottingHint hint, bool enabled)
/*!
Sets the keyboard modifier that will be recognized as multi-select-modifier.
- If \ref QCP::iMultiSelect is specified in \ref setInteractions, the user may select multiple objects
- by clicking on them one after the other while holding down \a modifier.
+ If \ref QCP::iMultiSelect is specified in \ref setInteractions, the user may select multiple
+ objects (or data points) by clicking on them one after the other while holding down \a modifier.
By default the multi-select-modifier is set to Qt::ControlModifier.
@@ -9351,9 +12948,158 @@ void QCustomPlot::setMultiSelectModifier(Qt::KeyboardModifier modifier)
}
/*!
- Sets the viewport of this QCustomPlot. The Viewport is the area that the top level layout
- (QCustomPlot::plotLayout()) uses as its rect. Normally, the viewport is the entire widget rect.
+ Sets how QCustomPlot processes mouse click-and-drag interactions by the user.
+
+ If \a mode is \ref QCP::srmNone, the mouse drag is forwarded to the underlying objects. For
+ example, QCPAxisRect may process a mouse drag by dragging axis ranges, see \ref
+ QCPAxisRect::setRangeDrag. If \a mode is not \ref QCP::srmNone, the current selection rect (\ref
+ selectionRect) becomes activated and allows e.g. rect zooming and data point selection.
+
+ If you wish to provide your user both with axis range dragging and data selection/range zooming,
+ use this method to switch between the modes just before the interaction is processed, e.g. in
+ reaction to the \ref mousePress or \ref mouseMove signals. For example you could check whether
+ the user is holding a certain keyboard modifier, and then decide which \a mode shall be set.
+
+ If a selection rect interaction is currently active, and \a mode is set to \ref QCP::srmNone, the
+ interaction is canceled (\ref QCPSelectionRect::cancel). Switching between any of the other modes
+ will keep the selection rect active. Upon completion of the interaction, the behaviour is as
+ defined by the currently set \a mode, not the mode that was set when the interaction started.
+
+ \see setInteractions, setSelectionRect, QCPSelectionRect
+*/
+void QCustomPlot::setSelectionRectMode(QCP::SelectionRectMode mode)
+{
+ if (mSelectionRect)
+ {
+ if (mode == QCP::srmNone)
+ mSelectionRect->cancel(); // when switching to none, we immediately want to abort a potentially active selection rect
+
+ // disconnect old connections:
+ if (mSelectionRectMode == QCP::srmSelect)
+ disconnect(mSelectionRect, SIGNAL(accepted(QRect,QMouseEvent*)), this, SLOT(processRectSelection(QRect,QMouseEvent*)));
+ else if (mSelectionRectMode == QCP::srmZoom)
+ disconnect(mSelectionRect, SIGNAL(accepted(QRect,QMouseEvent*)), this, SLOT(processRectZoom(QRect,QMouseEvent*)));
+
+ // establish new ones:
+ if (mode == QCP::srmSelect)
+ connect(mSelectionRect, SIGNAL(accepted(QRect,QMouseEvent*)), this, SLOT(processRectSelection(QRect,QMouseEvent*)));
+ else if (mode == QCP::srmZoom)
+ connect(mSelectionRect, SIGNAL(accepted(QRect,QMouseEvent*)), this, SLOT(processRectZoom(QRect,QMouseEvent*)));
+ }
+
+ mSelectionRectMode = mode;
+}
+
+/*!
+ Sets the \ref QCPSelectionRect instance that QCustomPlot will use if \a mode is not \ref
+ QCP::srmNone and the user performs a click-and-drag interaction. QCustomPlot takes ownership of
+ the passed \a selectionRect. It can be accessed later via \ref selectionRect.
+
+ This method is useful if you wish to replace the default QCPSelectionRect instance with an
+ instance of a QCPSelectionRect subclass, to introduce custom behaviour of the selection rect.
+ \see setSelectionRectMode
+*/
+void QCustomPlot::setSelectionRect(QCPSelectionRect *selectionRect)
+{
+ if (mSelectionRect)
+ delete mSelectionRect;
+
+ mSelectionRect = selectionRect;
+
+ if (mSelectionRect)
+ {
+ // establish connections with new selection rect:
+ if (mSelectionRectMode == QCP::srmSelect)
+ connect(mSelectionRect, SIGNAL(accepted(QRect,QMouseEvent*)), this, SLOT(processRectSelection(QRect,QMouseEvent*)));
+ else if (mSelectionRectMode == QCP::srmZoom)
+ connect(mSelectionRect, SIGNAL(accepted(QRect,QMouseEvent*)), this, SLOT(processRectZoom(QRect,QMouseEvent*)));
+ }
+}
+
+/*!
+ This method allows to enable OpenGL plot rendering, for increased plotting performance of
+ graphically demanding plots (thick lines, translucent fills, etc.).
+
+ If \a enabled is set to true, QCustomPlot will try to initialize OpenGL and, if successful,
+ continue plotting with hardware acceleration. The parameter \a multisampling controls how many
+ samples will be used per pixel, it essentially controls the antialiasing quality. If \a
+ multisampling is set too high for the current graphics hardware, the maximum allowed value will
+ be used.
+
+ You can test whether switching to OpenGL rendering was successful by checking whether the
+ according getter \a QCustomPlot::openGl() returns true. If the OpenGL initialization fails,
+ rendering continues with the regular software rasterizer, and an according qDebug output is
+ generated.
+
+ If switching to OpenGL was successful, this method disables label caching (\ref setPlottingHint
+ "setPlottingHint(QCP::phCacheLabels, false)") and turns on QCustomPlot's antialiasing override
+ for all elements (\ref setAntialiasedElements "setAntialiasedElements(QCP::aeAll)"), leading to a
+ higher quality output. The antialiasing override allows for pixel-grid aligned drawing in the
+ OpenGL paint device. As stated before, in OpenGL rendering the actual antialiasing of the plot is
+ controlled with \a multisampling. If \a enabled is set to false, the antialiasing/label caching
+ settings are restored to what they were before OpenGL was enabled, if they weren't altered in the
+ meantime.
+
+ \note OpenGL support is only enabled if QCustomPlot is compiled with the macro \c QCUSTOMPLOT_USE_OPENGL
+ defined. This define must be set before including the QCustomPlot header both during compilation
+ of the QCustomPlot library as well as when compiling your application. It is best to just include
+ the line <tt>DEFINES += QCUSTOMPLOT_USE_OPENGL</tt> in the respective qmake project files.
+ \note If you are using a Qt version before 5.0, you must also add the module "opengl" to your \c
+ QT variable in the qmake project files. For Qt versions 5.0 and higher, QCustomPlot switches to a
+ newer OpenGL interface which is already in the "gui" module.
+*/
+void QCustomPlot::setOpenGl(bool enabled, int multisampling)
+{
+ mOpenGlMultisamples = qMax(0, multisampling);
+#ifdef QCUSTOMPLOT_USE_OPENGL
+ mOpenGl = enabled;
+ if (mOpenGl)
+ {
+ if (setupOpenGl())
+ {
+ // backup antialiasing override and labelcaching setting so we can restore upon disabling OpenGL
+ mOpenGlAntialiasedElementsBackup = mAntialiasedElements;
+ mOpenGlCacheLabelsBackup = mPlottingHints.testFlag(QCP::phCacheLabels);
+ // set antialiasing override to antialias all (aligns gl pixel grid properly), and disable label caching (would use software rasterizer for pixmap caches):
+ setAntialiasedElements(QCP::aeAll);
+ setPlottingHint(QCP::phCacheLabels, false);
+ } else
+ {
+ qDebug() << Q_FUNC_INFO << "Failed to enable OpenGL, continuing plotting without hardware acceleration.";
+ mOpenGl = false;
+ }
+ } else
+ {
+ // restore antialiasing override and labelcaching to what it was before enabling OpenGL, if nobody changed it in the meantime:
+ if (mAntialiasedElements == QCP::aeAll)
+ setAntialiasedElements(mOpenGlAntialiasedElementsBackup);
+ if (!mPlottingHints.testFlag(QCP::phCacheLabels))
+ setPlottingHint(QCP::phCacheLabels, mOpenGlCacheLabelsBackup);
+ freeOpenGl();
+ }
+ // recreate all paint buffers:
+ mPaintBuffers.clear();
+ setupPaintBuffers();
+#else
+ Q_UNUSED(enabled)
+ 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)";
+#endif
+}
+
+/*!
+ Sets the viewport of this QCustomPlot. Usually users of QCustomPlot don't need to change the
+ viewport manually.
+
+ The viewport is the area in which the plot is drawn. All mechanisms, e.g. margin caluclation take
+ the viewport to be the outer border of the plot. The viewport normally is the rect() of the
+ QCustomPlot widget, i.e. a rect with top left (0, 0) and size of the QCustomPlot widget.
+
+ Don't confuse the viewport with the axis rect (QCustomPlot::axisRect). An axis rect is typically
+ an area enclosed by four axes, where the graphs/plottables are drawn in. The viewport is larger
+ and contains also the axes themselves, their tick numbers, their labels, or even additional axis
+ rects, color scales and other layout elements.
+
This function is used to allow arbitrary size exports with \ref toPixmap, \ref savePng, \ref
savePdf, etc. by temporarily changing the viewport size.
*/
@@ -9365,6 +13111,33 @@ void QCustomPlot::setViewport(const QRect &rect)
}
/*!
+ Sets the device pixel ratio used by the paint buffers of this QCustomPlot instance.
+
+ Normally, this doesn't need to be set manually, because it is initialized with the regular \a
+ QWidget::devicePixelRatio which is configured by Qt to fit the display device (e.g. 1 for normal
+ displays, 2 for High-DPI displays).
+
+ Device pixel ratios are supported by Qt only for Qt versions since 5.4. If this method is called
+ when QCustomPlot is being used with older Qt versions, outputs an according qDebug message and
+ leaves the internal buffer device pixel ratio at 1.0.
+*/
+void QCustomPlot::setBufferDevicePixelRatio(double ratio)
+{
+ if (!qFuzzyCompare(ratio, mBufferDevicePixelRatio))
+ {
+#ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
+ mBufferDevicePixelRatio = ratio;
+ for (int i=0; i<mPaintBuffers.size(); ++i)
+ mPaintBuffers.at(i)->setDevicePixelRatio(mBufferDevicePixelRatio);
+ // Note: axis label cache has devicePixelRatio as part of cache hash, so no need to manually clear cache here
+#else
+ qDebug() << Q_FUNC_INFO << "Device pixel ratios not supported for Qt versions before 5.4";
+ mBufferDevicePixelRatio = 1.0;
+#endif
+ }
+}
+
+/*!
Sets \a pm as the viewport background pixmap (see \ref setViewport). The pixmap is always drawn
below all other objects in the plot.
@@ -9450,7 +13223,7 @@ void QCustomPlot::setBackgroundScaledMode(Qt::AspectRatioMode mode)
There is an overloaded version of this function with no parameter which returns the last added
plottable, see QCustomPlot::plottable()
- \see plottableCount, addPlottable
+ \see plottableCount
*/
QCPAbstractPlottable *QCustomPlot::plottable(int index)
{
@@ -9466,10 +13239,10 @@ QCPAbstractPlottable *QCustomPlot::plottable(int index)
/*! \overload
- Returns the last plottable that was added with \ref addPlottable. If there are no plottables in
- the plot, returns 0.
+ Returns the last plottable that was added to the plot. If there are no plottables in the plot,
+ returns 0.
- \see plottableCount, addPlottable
+ \see plottableCount
*/
QCPAbstractPlottable *QCustomPlot::plottable()
{
@@ -9481,46 +13254,12 @@ QCPAbstractPlottable *QCustomPlot::plottable()
}
/*!
- Adds the specified plottable to the plot and, if \ref setAutoAddPlottableToLegend is enabled, to
- the legend (QCustomPlot::legend). QCustomPlot takes ownership of the plottable.
-
- Returns true on success, i.e. when \a plottable isn't already in the plot and the parent plot of
- \a plottable is this QCustomPlot (the latter is controlled by what axes were passed in the
- plottable's constructor).
-
- \see plottable, plottableCount, removePlottable, clearPlottables
-*/
-bool QCustomPlot::addPlottable(QCPAbstractPlottable *plottable)
-{
- if (mPlottables.contains(plottable))
- {
- qDebug() << Q_FUNC_INFO << "plottable already added to this QCustomPlot:" << reinterpret_cast<quintptr>(plottable);
- return false;
- }
- if (plottable->parentPlot() != this)
- {
- qDebug() << Q_FUNC_INFO << "plottable not created with this QCustomPlot as parent:" << reinterpret_cast<quintptr>(plottable);
- return false;
- }
-
- mPlottables.append(plottable);
- // possibly add plottable to legend:
- if (mAutoAddPlottableToLegend)
- plottable->addToLegend();
- // special handling for QCPGraphs to maintain the simple graph interface:
- if (QCPGraph *graph = qobject_cast<QCPGraph*>(plottable))
- mGraphs.append(graph);
- if (!plottable->layer()) // usually the layer is already set in the constructor of the plottable (via QCPLayerable constructor)
- plottable->setLayer(currentLayer());
- return true;
-}
-
-/*!
- Removes the specified plottable from the plot and, if necessary, from the legend (QCustomPlot::legend).
+ Removes the specified plottable from the plot and deletes it. If necessary, the corresponding
+ legend item is also removed from the default legend (QCustomPlot::legend).
Returns true on success.
- \see addPlottable, clearPlottables
+ \see clearPlottables
*/
bool QCustomPlot::removePlottable(QCPAbstractPlottable *plottable)
{
@@ -9543,7 +13282,7 @@ bool QCustomPlot::removePlottable(QCPAbstractPlottable *plottable)
/*! \overload
- Removes the plottable by its \a index.
+ Removes and deletes the plottable by its \a index.
*/
bool QCustomPlot::removePlottable(int index)
{
@@ -9557,7 +13296,8 @@ bool QCustomPlot::removePlottable(int index)
}
/*!
- Removes all plottables from the plot (and the QCustomPlot::legend, if necessary).
+ Removes all plottables from the plot and deletes them. Corresponding legend items are also
+ removed from the default legend (QCustomPlot::legend).
Returns the number of plottables removed.
@@ -9574,7 +13314,7 @@ int QCustomPlot::clearPlottables()
/*!
Returns the number of currently existing plottables in the plot
- \see plottable, addPlottable
+ \see plottable
*/
int QCustomPlot::plottableCount() const
{
@@ -9586,7 +13326,7 @@ int QCustomPlot::plottableCount() const
There is a convenience function if you're only interested in selected graphs, see \ref selectedGraphs.
- \see setInteractions, QCPAbstractPlottable::setSelectable, QCPAbstractPlottable::setSelected
+ \see setInteractions, QCPAbstractPlottable::setSelectable, QCPAbstractPlottable::setSelection
*/
QList<QCPAbstractPlottable*> QCustomPlot::selectedPlottables() const
{
@@ -9636,8 +13376,6 @@ QCPAbstractPlottable *QCustomPlot::plottableAt(const QPointF &pos, bool onlySele
/*!
Returns whether this QCustomPlot instance contains the \a plottable.
-
- \see addPlottable
*/
bool QCustomPlot::hasPlottable(QCPAbstractPlottable *plottable) const
{
@@ -9708,21 +13446,15 @@ QCPGraph *QCustomPlot::addGraph(QCPAxis *keyAxis, QCPAxis *valueAxis)
}
QCPGraph *newGraph = new QCPGraph(keyAxis, valueAxis);
- if (addPlottable(newGraph))
- {
- newGraph->setName(QLatin1String("Graph ")+QString::number(mGraphs.size()));
- return newGraph;
- } else
- {
- delete newGraph;
- return 0;
- }
+ newGraph->setName(QLatin1String("Graph ")+QString::number(mGraphs.size()));
+ return newGraph;
}
/*!
- Removes the specified \a graph from the plot and, if necessary, from the QCustomPlot::legend. If
- any other graphs in the plot have a channel fill set towards the removed graph, the channel fill
- property of those graphs is reset to zero (no channel fill).
+ Removes the specified \a graph from the plot and deletes it. If necessary, the corresponding
+ legend item is also removed from the default legend (QCustomPlot::legend). If any other graphs in
+ the plot have a channel fill set towards the removed graph, the channel fill property of those
+ graphs is reset to zero (no channel fill).
Returns true on success.
@@ -9735,7 +13467,7 @@ bool QCustomPlot::removeGraph(QCPGraph *graph)
/*! \overload
- Removes the graph by its \a index.
+ Removes and deletes the graph by its \a index.
*/
bool QCustomPlot::removeGraph(int index)
{
@@ -9746,7 +13478,8 @@ bool QCustomPlot::removeGraph(int index)
}
/*!
- Removes all graphs from the plot (and the QCustomPlot::legend, if necessary).
+ Removes all graphs from the plot and deletes them. Corresponding legend items are also removed
+ from the default legend (QCustomPlot::legend).
Returns the number of graphs removed.
@@ -9776,7 +13509,7 @@ int QCustomPlot::graphCount() const
If you are not only interested in selected graphs but other plottables like QCPCurve, QCPBars,
etc., use \ref selectedPlottables.
- \see setInteractions, selectedPlottables, QCPAbstractPlottable::setSelectable, QCPAbstractPlottable::setSelected
+ \see setInteractions, selectedPlottables, QCPAbstractPlottable::setSelectable, QCPAbstractPlottable::setSelection
*/
QList<QCPGraph*> QCustomPlot::selectedGraphs() const
{
@@ -9795,7 +13528,7 @@ QList<QCPGraph*> QCustomPlot::selectedGraphs() const
There is an overloaded version of this function with no parameter which returns the last added
item, see QCustomPlot::item()
- \see itemCount, addItem
+ \see itemCount
*/
QCPAbstractItem *QCustomPlot::item(int index) const
{
@@ -9811,10 +13544,10 @@ QCPAbstractItem *QCustomPlot::item(int index) const
/*! \overload
- Returns the last item, that was added with \ref addItem. If there are no items in the plot,
+ Returns the last item that was added to this plot. If there are no items in the plot,
returns 0.
- \see itemCount, addItem
+ \see itemCount
*/
QCPAbstractItem *QCustomPlot::item() const
{
@@ -9826,32 +13559,11 @@ QCPAbstractItem *QCustomPlot::item() const
}
/*!
- Adds the specified item to the plot. QCustomPlot takes ownership of the item.
-
- Returns true on success, i.e. when \a item wasn't already in the plot and the parent plot of \a
- item is this QCustomPlot.
-
- \see item, itemCount, removeItem, clearItems
-*/
-bool QCustomPlot::addItem(QCPAbstractItem *item)
-{
- if (!mItems.contains(item) && item->parentPlot() == this)
- {
- mItems.append(item);
- return true;
- } else
- {
- qDebug() << Q_FUNC_INFO << "item either already in list or not created with this QCustomPlot as parent:" << reinterpret_cast<quintptr>(item);
- return false;
- }
-}
-
-/*!
- Removes the specified item from the plot.
+ Removes the specified item from the plot and deletes it.
Returns true on success.
- \see addItem, clearItems
+ \see clearItems
*/
bool QCustomPlot::removeItem(QCPAbstractItem *item)
{
@@ -9869,7 +13581,7 @@ bool QCustomPlot::removeItem(QCPAbstractItem *item)
/*! \overload
- Removes the item by its \a index.
+ Removes and deletes the item by its \a index.
*/
bool QCustomPlot::removeItem(int index)
{
@@ -9883,7 +13595,7 @@ bool QCustomPlot::removeItem(int index)
}
/*!
- Removes all items from the plot.
+ Removes all items from the plot and deletes them.
Returns the number of items removed.
@@ -9900,7 +13612,7 @@ int QCustomPlot::clearItems()
/*!
Returns the number of currently existing items in the plot
- \see item, addItem
+ \see item
*/
int QCustomPlot::itemCount() const
{
@@ -9962,7 +13674,7 @@ QCPAbstractItem *QCustomPlot::itemAt(const QPointF &pos, bool onlySelectable) co
/*!
Returns whether this QCustomPlot contains the \a item.
- \see addItem
+ \see item
*/
bool QCustomPlot::hasItem(QCPAbstractItem *item) const
{
@@ -10096,6 +13808,7 @@ bool QCustomPlot::addLayer(const QString &name, QCPLayer *otherLayer, QCustomPlo
QCPLayer *newLayer = new QCPLayer(this, name);
mLayers.insert(otherLayer->index() + (insertMode==limAbove ? 1:0), newLayer);
updateLayerIndices();
+ setupPaintBuffers(); // associates new layer with the appropriate paint buffer
return true;
}
@@ -10143,6 +13856,9 @@ bool QCustomPlot::removeLayer(QCPLayer *layer)
// if removed layer is current layer, change current layer to layer below/above:
if (layer == mCurrentLayer)
setCurrentLayer(targetLayer);
+ // invalidate the paint buffer that was responsible for this layer:
+ if (!layer->mPaintBuffer.isNull())
+ layer->mPaintBuffer.data()->setInvalidated();
// remove layer:
delete layer;
mLayers.removeOne(layer);
@@ -10172,7 +13888,17 @@ bool QCustomPlot::moveLayer(QCPLayer *layer, QCPLayer *otherLayer, QCustomPlot::
return false;
}
- mLayers.move(layer->index(), otherLayer->index() + (insertMode==limAbove ? 1:0));
+ if (layer->index() > otherLayer->index())
+ mLayers.move(layer->index(), otherLayer->index() + (insertMode==limAbove ? 1:0));
+ else if (layer->index() < otherLayer->index())
+ mLayers.move(layer->index(), otherLayer->index() + (insertMode==limAbove ? 0:-1));
+
+ // invalidate the paint buffers that are responsible for the layers:
+ if (!layer->mPaintBuffer.isNull())
+ layer->mPaintBuffer.data()->setInvalidated();
+ if (!otherLayer->mPaintBuffer.isNull())
+ otherLayer->mPaintBuffer.data()->setInvalidated();
+
updateLayerIndices();
return true;
}
@@ -10271,6 +13997,39 @@ QCPLayoutElement *QCustomPlot::layoutElementAt(const QPointF &pos) const
}
/*!
+ Returns the layout element of type \ref QCPAxisRect at pixel position \a pos. This method ignores
+ other layout elements even if they are visually in front of the axis rect (e.g. a \ref
+ QCPLegend). If there is no axis rect at that position, returns 0.
+
+ Only visible axis rects are used. If \ref QCPLayoutElement::setVisible on the axis rect itself or
+ on any of its parent elements is set to false, it will not be considered.
+
+ \see layoutElementAt
+*/
+QCPAxisRect *QCustomPlot::axisRectAt(const QPointF &pos) const
+{
+ QCPAxisRect *result = 0;
+ QCPLayoutElement *currentElement = mPlotLayout;
+ bool searchSubElements = true;
+ while (searchSubElements && currentElement)
+ {
+ searchSubElements = false;
+ foreach (QCPLayoutElement *subElement, currentElement->elements(false))
+ {
+ if (subElement && subElement->realVisibility() && subElement->selectTest(pos, false) >= 0)
+ {
+ currentElement = subElement;
+ searchSubElements = true;
+ if (QCPAxisRect *ar = qobject_cast<QCPAxisRect*>(currentElement))
+ result = ar;
+ break;
+ }
+ }
+ }
+ return result;
+}
+
+/*!
Returns the axes that currently have selected parts, i.e. whose selection state is not \ref
QCPAxis::spNone.
@@ -10345,41 +14104,60 @@ void QCustomPlot::deselectAll()
}
/*!
- Causes a complete replot into the internal buffer. Finally, update() is called, to redraw the
- buffer on the QCustomPlot widget surface. This is the method that must be called to make changes,
- for example on the axis ranges or data points of graphs, visible.
-
+ Causes a complete replot into the internal paint buffer(s). Finally, the widget surface is
+ refreshed with the new buffer contents. This is the method that must be called to make changes to
+ the plot, e.g. on the axis ranges or data points of graphs, visible.
+
+ The parameter \a refreshPriority can be used to fine-tune the timing of the replot. For example
+ if your application calls \ref replot very quickly in succession (e.g. multiple independent
+ functions change some aspects of the plot and each wants to make sure the change gets replotted),
+ it is advisable to set \a refreshPriority to \ref QCustomPlot::rpQueuedReplot. This way, the
+ actual replotting is deferred to the next event loop iteration. Multiple successive calls of \ref
+ replot with this priority will only cause a single replot, avoiding redundant replots and
+ improving performance.
+
Under a few circumstances, QCustomPlot causes a replot by itself. Those are resize events of the
QCustomPlot widget and user interactions (object selection and range dragging/zooming).
-
+
Before the replot happens, the signal \ref beforeReplot is emitted. After the replot, \ref
afterReplot is emitted. It is safe to mutually connect the replot slot with any of those two
signals on two QCustomPlots to make them replot synchronously, it won't cause an infinite
recursion.
+
+ If a layer is in mode \ref QCPLayer::lmBuffered (\ref QCPLayer::setMode), it is also possible to
+ replot only that specific layer via \ref QCPLayer::replot. See the documentation there for
+ details.
*/
void QCustomPlot::replot(QCustomPlot::RefreshPriority refreshPriority)
{
+ if (refreshPriority == QCustomPlot::rpQueuedReplot)
+ {
+ if (!mReplotQueued)
+ {
+ mReplotQueued = true;
+ QTimer::singleShot(0, this, SLOT(replot()));
+ }
+ return;
+ }
+
if (mReplotting) // incase signals loop back to replot slot
return;
mReplotting = true;
+ mReplotQueued = false;
emit beforeReplot();
- mPaintBuffer.fill(mBackgroundBrush.style() == Qt::SolidPattern ? mBackgroundBrush.color() : Qt::transparent);
- QCPPainter painter;
- painter.begin(&mPaintBuffer);
- if (painter.isActive())
- {
- painter.setRenderHint(QPainter::HighQualityAntialiasing); // to make Antialiasing look good if using the OpenGL graphicssystem
- if (mBackgroundBrush.style() != Qt::SolidPattern && mBackgroundBrush.style() != Qt::NoBrush)
- painter.fillRect(mViewport, mBackgroundBrush);
- draw(&painter);
- painter.end();
- if ((refreshPriority == rpHint && mPlottingHints.testFlag(QCP::phForceRepaint)) || refreshPriority==rpImmediate)
- repaint();
- else
- update();
- } else // might happen if QCustomPlot has width or height zero
- qDebug() << Q_FUNC_INFO << "Couldn't activate painter on buffer. This usually happens because QCustomPlot has width or height zero.";
+ updateLayout();
+ // draw all layered objects (grid, axes, plottables, items, legend,...) into their buffers:
+ setupPaintBuffers();
+ foreach (QCPLayer *layer, mLayers)
+ layer->drawToPaintBuffer();
+ for (int i=0; i<mPaintBuffers.size(); ++i)
+ mPaintBuffers.at(i)->setInvalidated(false);
+
+ if ((refreshPriority == rpRefreshHint && mPlottingHints.testFlag(QCP::phImmediateRefresh)) || refreshPriority==rpImmediateRefresh)
+ repaint();
+ else
+ update();
emit afterReplot();
mReplotting = false;
@@ -10410,20 +14188,20 @@ void QCustomPlot::rescaleAxes(bool onlyVisiblePlottables)
pixel width and height. If either \a width or \a height is zero, the exported image will have the
same dimensions as the QCustomPlot widget currently has.
- \a noCosmeticPen disables the use of cosmetic pens when drawing to the PDF file. Cosmetic pens
- are pens with numerical width 0, which are always drawn as a one pixel wide line, no matter what
- zoom factor is set in the PDF-Viewer. For more information about cosmetic pens, see the QPainter
- and QPen documentation.
-
+ Setting \a exportPen to \ref QCP::epNoCosmetic allows to disable the use of cosmetic pens when
+ drawing to the PDF file. Cosmetic pens are pens with numerical width 0, which are always drawn as
+ a one pixel wide line, no matter what zoom factor is set in the PDF-Viewer. For more information
+ about cosmetic pens, see the QPainter and QPen documentation.
+
The objects of the plot will appear in the current selection state. If you don't want any
selected objects to be painted in their selected look, deselect everything with \ref deselectAll
before calling this function.
Returns true on success.
-
+
\warning
- \li If you plan on editing the exported PDF file with a vector graphics editor like
- Inkscape, it is advised to set \a noCosmeticPen to true to avoid losing those cosmetic lines
+ \li If you plan on editing the exported PDF file with a vector graphics editor like Inkscape, it
+ is advised to set \a exportPen to \ref QCP::epNoCosmetic to avoid losing those cosmetic lines
(which might be quite many, because cosmetic pens are the default for e.g. axes and tick marks).
\li If calling this function inside the constructor of the parent of the QCustomPlot widget
(i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide
@@ -10431,21 +14209,21 @@ void QCustomPlot::rescaleAxes(bool onlyVisiblePlottables)
function uses the current width and height of the QCustomPlot widget. However, in Qt, these
aren't defined yet inside the constructor, so you would get an image that has strange
widths/heights.
-
+
\a pdfCreator and \a pdfTitle may be used to set the according metadata fields in the resulting
PDF file.
-
+
\note On Android systems, this method does nothing and issues an according qDebug warning
- message. This is also the case if for other reasons the define flag QT_NO_PRINTER is set.
-
+ message. This is also the case if for other reasons the define flag \c QT_NO_PRINTER is set.
+
\see savePng, saveBmp, saveJpg, saveRastered
*/
-bool QCustomPlot::savePdf(const QString &fileName, bool noCosmeticPen, int width, int height, const QString &pdfCreator, const QString &pdfTitle)
+bool QCustomPlot::savePdf(const QString &fileName, int width, int height, QCP::ExportPen exportPen, const QString &pdfCreator, const QString &pdfTitle)
{
bool success = false;
#ifdef QT_NO_PRINTER
Q_UNUSED(fileName)
- Q_UNUSED(noCosmeticPen)
+ Q_UNUSED(exportPen)
Q_UNUSED(width)
Q_UNUSED(height)
Q_UNUSED(pdfCreator)
@@ -10487,7 +14265,7 @@ bool QCustomPlot::savePdf(const QString &fileName, bool noCosmeticPen, int width
{
printpainter.setMode(QCPPainter::pmVectorized);
printpainter.setMode(QCPPainter::pmNoCaching);
- printpainter.setMode(QCPPainter::pmNonCosmetic, noCosmeticPen);
+ printpainter.setMode(QCPPainter::pmNonCosmetic, exportPen==QCP::epNoCosmetic);
printpainter.setWindow(mViewport);
if (mBackgroundBrush.style() != Qt::NoBrush &&
mBackgroundBrush.color() != Qt::white &&
@@ -10505,61 +14283,87 @@ bool QCustomPlot::savePdf(const QString &fileName, bool noCosmeticPen, int width
/*!
Saves a PNG image file to \a fileName on disc. The output plot will have the dimensions \a width
- and \a height in pixels. If either \a width or \a height is zero, the exported image will have
- the same dimensions as the QCustomPlot widget currently has. Line widths and texts etc. are not
- scaled up when larger widths/heights are used. If you want that effect, use the \a scale parameter.
+ and \a height in pixels, multiplied by \a scale. If either \a width or \a height is zero, the
+ current width and height of the QCustomPlot widget is used instead. Line widths and texts etc.
+ are not scaled up when larger widths/heights are used. If you want that effect, use the \a scale
+ parameter.
For example, if you set both \a width and \a height to 100 and \a scale to 2, you will end up with an
image file of size 200*200 in which all graphical elements are scaled up by factor 2 (line widths,
texts, etc.). This scaling is not done by stretching a 100*100 image, the result will have full
200*200 pixel resolution.
-
- If you use a high scaling factor, it is recommended to enable antialiasing for all elements via
+
+ If you use a high scaling factor, it is recommended to enable antialiasing for all elements by
temporarily setting \ref QCustomPlot::setAntialiasedElements to \ref QCP::aeAll as this allows
QCustomPlot to place objects with sub-pixel accuracy.
+ image compression can be controlled with the \a quality parameter which must be between 0 and 100
+ or -1 to use the default setting.
+
+ The \a resolution will be written to the image file header and has no direct consequence for the
+ quality or the pixel size. However, if opening the image with a tool which respects the metadata,
+ it will be able to scale the image to match either a given size in real units of length (inch,
+ centimeters, etc.), or the target display DPI. You can specify in which units \a resolution is
+ given, by setting \a resolutionUnit. The \a resolution is converted to the format's expected
+ resolution unit internally.
+
+ Returns true on success. If this function fails, most likely the PNG format isn't supported by
+ the system, see Qt docs about QImageWriter::supportedImageFormats().
+
+ The objects of the plot will appear in the current selection state. If you don't want any selected
+ objects to be painted in their selected look, deselect everything with \ref deselectAll before calling
+ this function.
+
+ If you want the PNG to have a transparent background, call \ref setBackground(const QBrush &brush)
+ with no brush (Qt::NoBrush) or a transparent color (Qt::transparent), before saving.
+
\warning If calling this function inside the constructor of the parent of the QCustomPlot widget
(i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide
explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this
function uses the current width and height of the QCustomPlot widget. However, in Qt, these
aren't defined yet inside the constructor, so you would get an image that has strange
widths/heights.
-
- The objects of the plot will appear in the current selection state. If you don't want any selected
- objects to be painted in their selected look, deselect everything with \ref deselectAll before calling
- this function.
-
- If you want the PNG to have a transparent background, call \ref setBackground(const QBrush
- &brush) with no brush (Qt::NoBrush) or a transparent color (Qt::transparent), before saving.
-
- PNG compression can be controlled with the \a quality parameter which must be between 0 and 100 or
- -1 to use the default setting.
-
- Returns true on success. If this function fails, most likely the PNG format isn't supported by
- the system, see Qt docs about QImageWriter::supportedImageFormats().
\see savePdf, saveBmp, saveJpg, saveRastered
*/
-bool QCustomPlot::savePng(const QString &fileName, int width, int height, double scale, int quality)
+bool QCustomPlot::savePng(const QString &fileName, int width, int height, double scale, int quality, int resolution, QCP::ResolutionUnit resolutionUnit)
{
- return saveRastered(fileName, width, height, scale, "PNG", quality);
+ return saveRastered(fileName, width, height, scale, "PNG", quality, resolution, resolutionUnit);
}
/*!
- Saves a JPG image file to \a fileName on disc. The output plot will have the dimensions \a width
- and \a height in pixels. If either \a width or \a height is zero, the exported image will have
- the same dimensions as the QCustomPlot widget currently has. Line widths and texts etc. are not
- scaled up when larger widths/heights are used. If you want that effect, use the \a scale parameter.
+ Saves a JPEG image file to \a fileName on disc. The output plot will have the dimensions \a width
+ and \a height in pixels, multiplied by \a scale. If either \a width or \a height is zero, the
+ current width and height of the QCustomPlot widget is used instead. Line widths and texts etc.
+ are not scaled up when larger widths/heights are used. If you want that effect, use the \a scale
+ parameter.
For example, if you set both \a width and \a height to 100 and \a scale to 2, you will end up with an
image file of size 200*200 in which all graphical elements are scaled up by factor 2 (line widths,
texts, etc.). This scaling is not done by stretching a 100*100 image, the result will have full
200*200 pixel resolution.
-
- If you use a high scaling factor, it is recommended to enable antialiasing for all elements via
+
+ If you use a high scaling factor, it is recommended to enable antialiasing for all elements by
temporarily setting \ref QCustomPlot::setAntialiasedElements to \ref QCP::aeAll as this allows
QCustomPlot to place objects with sub-pixel accuracy.
+ image compression can be controlled with the \a quality parameter which must be between 0 and 100
+ or -1 to use the default setting.
+
+ The \a resolution will be written to the image file header and has no direct consequence for the
+ quality or the pixel size. However, if opening the image with a tool which respects the metadata,
+ it will be able to scale the image to match either a given size in real units of length (inch,
+ centimeters, etc.), or the target display DPI. You can specify in which units \a resolution is
+ given, by setting \a resolutionUnit. The \a resolution is converted to the format's expected
+ resolution unit internally.
+
+ Returns true on success. If this function fails, most likely the JPEG format isn't supported by
+ the system, see Qt docs about QImageWriter::supportedImageFormats().
+
+ The objects of the plot will appear in the current selection state. If you don't want any selected
+ objects to be painted in their selected look, deselect everything with \ref deselectAll before calling
+ this function.
+
\warning If calling this function inside the constructor of the parent of the QCustomPlot widget
(i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide
explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this
@@ -10567,38 +14371,43 @@ bool QCustomPlot::savePng(const QString &fileName, int width, int height, double
aren't defined yet inside the constructor, so you would get an image that has strange
widths/heights.
- The objects of the plot will appear in the current selection state. If you don't want any selected
- objects to be painted in their selected look, deselect everything with \ref deselectAll before calling
- this function.
-
- JPG compression can be controlled with the \a quality parameter which must be between 0 and 100 or
- -1 to use the default setting.
-
- Returns true on success. If this function fails, most likely the JPG format isn't supported by
- the system, see Qt docs about QImageWriter::supportedImageFormats().
-
\see savePdf, savePng, saveBmp, saveRastered
*/
-bool QCustomPlot::saveJpg(const QString &fileName, int width, int height, double scale, int quality)
+bool QCustomPlot::saveJpg(const QString &fileName, int width, int height, double scale, int quality, int resolution, QCP::ResolutionUnit resolutionUnit)
{
- return saveRastered(fileName, width, height, scale, "JPG", quality);
+ return saveRastered(fileName, width, height, scale, "JPG", quality, resolution, resolutionUnit);
}
/*!
Saves a BMP image file to \a fileName on disc. The output plot will have the dimensions \a width
- and \a height in pixels. If either \a width or \a height is zero, the exported image will have
- the same dimensions as the QCustomPlot widget currently has. Line widths and texts etc. are not
- scaled up when larger widths/heights are used. If you want that effect, use the \a scale parameter.
+ and \a height in pixels, multiplied by \a scale. If either \a width or \a height is zero, the
+ current width and height of the QCustomPlot widget is used instead. Line widths and texts etc.
+ are not scaled up when larger widths/heights are used. If you want that effect, use the \a scale
+ parameter.
For example, if you set both \a width and \a height to 100 and \a scale to 2, you will end up with an
image file of size 200*200 in which all graphical elements are scaled up by factor 2 (line widths,
texts, etc.). This scaling is not done by stretching a 100*100 image, the result will have full
200*200 pixel resolution.
-
- If you use a high scaling factor, it is recommended to enable antialiasing for all elements via
+
+ If you use a high scaling factor, it is recommended to enable antialiasing for all elements by
temporarily setting \ref QCustomPlot::setAntialiasedElements to \ref QCP::aeAll as this allows
QCustomPlot to place objects with sub-pixel accuracy.
+ The \a resolution will be written to the image file header and has no direct consequence for the
+ quality or the pixel size. However, if opening the image with a tool which respects the metadata,
+ it will be able to scale the image to match either a given size in real units of length (inch,
+ centimeters, etc.), or the target display DPI. You can specify in which units \a resolution is
+ given, by setting \a resolutionUnit. The \a resolution is converted to the format's expected
+ resolution unit internally.
+
+ Returns true on success. If this function fails, most likely the BMP format isn't supported by
+ the system, see Qt docs about QImageWriter::supportedImageFormats().
+
+ The objects of the plot will appear in the current selection state. If you don't want any selected
+ objects to be painted in their selected look, deselect everything with \ref deselectAll before calling
+ this function.
+
\warning If calling this function inside the constructor of the parent of the QCustomPlot widget
(i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide
explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this
@@ -10606,18 +14415,11 @@ bool QCustomPlot::saveJpg(const QString &fileName, int width, int height, double
aren't defined yet inside the constructor, so you would get an image that has strange
widths/heights.
- The objects of the plot will appear in the current selection state. If you don't want any selected
- objects to be painted in their selected look, deselect everything with \ref deselectAll before calling
- this function.
-
- Returns true on success. If this function fails, most likely the BMP format isn't supported by
- the system, see Qt docs about QImageWriter::supportedImageFormats().
-
\see savePdf, savePng, saveJpg, saveRastered
*/
-bool QCustomPlot::saveBmp(const QString &fileName, int width, int height, double scale)
+bool QCustomPlot::saveBmp(const QString &fileName, int width, int height, double scale, int resolution, QCP::ResolutionUnit resolutionUnit)
{
- return saveRastered(fileName, width, height, scale, "BMP");
+ return saveRastered(fileName, width, height, scale, "BMP", -1, resolution, resolutionUnit);
}
/*! \internal
@@ -10651,245 +14453,253 @@ QSize QCustomPlot::sizeHint() const
void QCustomPlot::paintEvent(QPaintEvent *event)
{
Q_UNUSED(event);
- QPainter painter(this);
- painter.drawPixmap(0, 0, mPaintBuffer);
+ QCPPainter painter(this);
+ if (painter.isActive())
+ {
+ painter.setRenderHint(QPainter::HighQualityAntialiasing); // to make Antialiasing look good if using the OpenGL graphicssystem
+ if (mBackgroundBrush.style() != Qt::NoBrush)
+ painter.fillRect(mViewport, mBackgroundBrush);
+ drawBackground(&painter);
+ for (int bufferIndex = 0; bufferIndex < mPaintBuffers.size(); ++bufferIndex)
+ mPaintBuffers.at(bufferIndex)->draw(&painter);
+ }
}
/*! \internal
- Event handler for a resize of the QCustomPlot widget. Causes the internal buffer to be resized to
- the new size. The viewport (which becomes the outer rect of mPlotLayout) is resized
- appropriately. Finally a \ref replot is performed.
+ Event handler for a resize of the QCustomPlot widget. The viewport (which becomes the outer rect
+ of mPlotLayout) is resized appropriately. Finally a \ref replot is performed.
*/
void QCustomPlot::resizeEvent(QResizeEvent *event)
{
+ Q_UNUSED(event)
// resize and repaint the buffer:
- mPaintBuffer = QPixmap(event->size());
setViewport(rect());
- replot(rpQueued); // queued update is important here, to prevent painting issues in some contexts
+ replot(rpQueuedRefresh); // queued refresh is important here, to prevent painting issues in some contexts (e.g. MDI subwindow)
}
/*! \internal
- Event handler for when a double click occurs. Emits the \ref mouseDoubleClick signal, then emits
- the specialized signals when certain objecs are clicked (e.g. \ref plottableDoubleClick, \ref
- axisDoubleClick, etc.). Finally determines the affected layout element and forwards the event to
- it.
+ Event handler for when a double click occurs. Emits the \ref mouseDoubleClick signal, then
+ determines the layerable under the cursor and forwards the event to it. Finally, emits the
+ specialized signals when certain objecs are clicked (e.g. \ref plottableDoubleClick, \ref
+ axisDoubleClick, etc.).
\see mousePressEvent, mouseReleaseEvent
*/
void QCustomPlot::mouseDoubleClickEvent(QMouseEvent *event)
{
emit mouseDoubleClick(event);
+ mMouseHasMoved = false;
+ mMousePressPos = event->pos();
- QVariant details;
- QCPLayerable *clickedLayerable = layerableAt(event->pos(), false, &details);
+ // determine layerable under the cursor (this event is called instead of the second press event in a double-click):
+ QList<QVariant> details;
+ QList<QCPLayerable*> candidates = layerableListAt(mMousePressPos, false, &details);
+ for (int i=0; i<candidates.size(); ++i)
+ {
+ event->accept(); // default impl of QCPLayerable's mouse events ignore the event, in that case propagate to next candidate in list
+ candidates.at(i)->mouseDoubleClickEvent(event, details.at(i));
+ if (event->isAccepted())
+ {
+ mMouseEventLayerable = candidates.at(i);
+ mMouseEventLayerableDetails = details.at(i);
+ break;
+ }
+ }
// emit specialized object double click signals:
- if (QCPAbstractPlottable *ap = qobject_cast<QCPAbstractPlottable*>(clickedLayerable))
- emit plottableDoubleClick(ap, event);
- else if (QCPAxis *ax = qobject_cast<QCPAxis*>(clickedLayerable))
- emit axisDoubleClick(ax, details.value<QCPAxis::SelectablePart>(), event);
- else if (QCPAbstractItem *ai = qobject_cast<QCPAbstractItem*>(clickedLayerable))
- emit itemDoubleClick(ai, event);
- else if (QCPLegend *lg = qobject_cast<QCPLegend*>(clickedLayerable))
- emit legendDoubleClick(lg, 0, event);
- else if (QCPAbstractLegendItem *li = qobject_cast<QCPAbstractLegendItem*>(clickedLayerable))
- emit legendDoubleClick(li->parentLegend(), li, event);
- else if (QCPPlotTitle *pt = qobject_cast<QCPPlotTitle*>(clickedLayerable))
- emit titleDoubleClick(event, pt);
-
- // call double click event of affected layout element:
- if (QCPLayoutElement *el = layoutElementAt(event->pos()))
- el->mouseDoubleClickEvent(event);
-
- // call release event of affected layout element (as in mouseReleaseEvent, since the mouseDoubleClick replaces the second release event in double click case):
- if (mMouseEventElement)
+ if (!candidates.isEmpty())
{
- mMouseEventElement->mouseReleaseEvent(event);
- mMouseEventElement = 0;
+ if (QCPAbstractPlottable *ap = qobject_cast<QCPAbstractPlottable*>(candidates.first()))
+ {
+ int dataIndex = 0;
+ if (!details.first().value<QCPDataSelection>().isEmpty())
+ dataIndex = details.first().value<QCPDataSelection>().dataRange().begin();
+ emit plottableDoubleClick(ap, dataIndex, event);
+ } else if (QCPAxis *ax = qobject_cast<QCPAxis*>(candidates.first()))
+ emit axisDoubleClick(ax, details.first().value<QCPAxis::SelectablePart>(), event);
+ else if (QCPAbstractItem *ai = qobject_cast<QCPAbstractItem*>(candidates.first()))
+ emit itemDoubleClick(ai, event);
+ else if (QCPLegend *lg = qobject_cast<QCPLegend*>(candidates.first()))
+ emit legendDoubleClick(lg, 0, event);
+ else if (QCPAbstractLegendItem *li = qobject_cast<QCPAbstractLegendItem*>(candidates.first()))
+ emit legendDoubleClick(li->parentLegend(), li, event);
}
- //QWidget::mouseDoubleClickEvent(event); don't call base class implementation because it would just cause a mousePress/ReleaseEvent, which we don't want.
+ event->accept(); // in case QCPLayerable reimplementation manipulates event accepted state. In QWidget event system, QCustomPlot wants to accept the event.
}
/*! \internal
- Event handler for when a mouse button is pressed. Emits the mousePress signal. Then determines
- the affected layout element and forwards the event to it.
+ Event handler for when a mouse button is pressed. Emits the mousePress signal.
+
+ If the current \ref setSelectionRectMode is not \ref QCP::srmNone, passes the event to the
+ selection rect. Otherwise determines the layerable under the cursor and forwards the event to it.
\see mouseMoveEvent, mouseReleaseEvent
*/
void QCustomPlot::mousePressEvent(QMouseEvent *event)
{
emit mousePress(event);
- mMousePressPos = event->pos(); // need this to determine in releaseEvent whether it was a click (no position change between press and release)
+ // save some state to tell in releaseEvent whether it was a click:
+ mMouseHasMoved = false;
+ mMousePressPos = event->pos();
- // call event of affected layout element:
- mMouseEventElement = layoutElementAt(event->pos());
- if (mMouseEventElement)
- mMouseEventElement->mousePressEvent(event);
+ if (mSelectionRect && mSelectionRectMode != QCP::srmNone)
+ {
+ if (mSelectionRectMode != QCP::srmZoom || qobject_cast<QCPAxisRect*>(axisRectAt(mMousePressPos))) // in zoom mode only activate selection rect if on an axis rect
+ mSelectionRect->startSelection(event);
+ } else
+ {
+ // no selection rect interaction, so forward event to layerable under the cursor:
+ QList<QVariant> details;
+ QList<QCPLayerable*> candidates = layerableListAt(mMousePressPos, false, &details);
+ for (int i=0; i<candidates.size(); ++i)
+ {
+ event->accept(); // default impl of QCPLayerable's mouse events ignore the event, in that case propagate to next candidate in list
+ candidates.at(i)->mousePressEvent(event, details.at(i));
+ if (event->isAccepted())
+ {
+ mMouseEventLayerable = candidates.at(i);
+ mMouseEventLayerableDetails = details.at(i);
+ break;
+ }
+ }
+ }
- QWidget::mousePressEvent(event);
+ event->accept(); // in case QCPLayerable reimplementation manipulates event accepted state. In QWidget event system, QCustomPlot wants to accept the event.
}
/*! \internal
Event handler for when the cursor is moved. Emits the \ref mouseMove signal.
- If a layout element has mouse capture focus (a mousePressEvent happened on top of the layout
- element before), the mouseMoveEvent is forwarded to that element.
+ If the selection rect (\ref setSelectionRect) is currently active, the event is forwarded to it
+ in order to update the rect geometry.
+
+ Otherwise, if a layout element has mouse capture focus (a mousePressEvent happened on top of the
+ layout element before), the mouseMoveEvent is forwarded to that element.
\see mousePressEvent, mouseReleaseEvent
*/
void QCustomPlot::mouseMoveEvent(QMouseEvent *event)
{
emit mouseMove(event);
-
- // call event of affected layout element:
- if (mMouseEventElement)
- mMouseEventElement->mouseMoveEvent(event);
- QWidget::mouseMoveEvent(event);
+ if (!mMouseHasMoved && (mMousePressPos-event->pos()).manhattanLength() > 3)
+ mMouseHasMoved = true; // moved too far from mouse press position, don't handle as click on mouse release
+
+ if (mSelectionRect && mSelectionRect->isActive())
+ mSelectionRect->moveSelection(event);
+ else if (mMouseEventLayerable) // call event of affected layerable:
+ mMouseEventLayerable->mouseMoveEvent(event, mMousePressPos);
+
+ event->accept(); // in case QCPLayerable reimplementation manipulates event accepted state. In QWidget event system, QCustomPlot wants to accept the event.
}
/*! \internal
-
+
Event handler for when a mouse button is released. Emits the \ref mouseRelease signal.
-
+
If the mouse was moved less than a certain threshold in any direction since the \ref
mousePressEvent, it is considered a click which causes the selection mechanism (if activated via
\ref setInteractions) to possibly change selection states accordingly. Further, specialized mouse
click signals are emitted (e.g. \ref plottableClick, \ref axisClick, etc.)
-
- If a layout element has mouse capture focus (a \ref mousePressEvent happened on top of the layout
- element before), the \ref mouseReleaseEvent is forwarded to that element.
-
+
+ If a layerable is the mouse capturer (a \ref mousePressEvent happened on top of the layerable
+ before), the \ref mouseReleaseEvent is forwarded to that element.
+
\see mousePressEvent, mouseMoveEvent
*/
void QCustomPlot::mouseReleaseEvent(QMouseEvent *event)
{
emit mouseRelease(event);
- bool doReplot = false;
- if ((mMousePressPos-event->pos()).manhattanLength() < 5) // determine whether it was a click operation
+ if (!mMouseHasMoved) // mouse hasn't moved (much) between press and release, so handle as click
{
+ if (mSelectionRect && mSelectionRect->isActive()) // a simple click shouldn't successfully finish a selection rect, so cancel it here
+ mSelectionRect->cancel();
if (event->button() == Qt::LeftButton)
- {
- // handle selection mechanism:
- QVariant details;
- QCPLayerable *clickedLayerable = layerableAt(event->pos(), true, &details);
- bool selectionStateChanged = false;
- bool additive = mInteractions.testFlag(QCP::iMultiSelect) && event->modifiers().testFlag(mMultiSelectModifier);
- // deselect all other layerables if not additive selection:
- if (!additive)
- {
- foreach (QCPLayer *layer, mLayers)
- {
- foreach (QCPLayerable *layerable, layer->children())
- {
- if (layerable != clickedLayerable && mInteractions.testFlag(layerable->selectionCategory()))
- {
- bool selChanged = false;
- layerable->deselectEvent(&selChanged);
- selectionStateChanged |= selChanged;
- }
- }
- }
- }
- if (clickedLayerable && mInteractions.testFlag(clickedLayerable->selectionCategory()))
- {
- // a layerable was actually clicked, call its selectEvent:
- bool selChanged = false;
- clickedLayerable->selectEvent(event, additive, details, &selChanged);
- selectionStateChanged |= selChanged;
- }
- if (selectionStateChanged)
- {
- doReplot = true;
- emit selectionChangedByUser();
- }
- }
+ processPointSelection(event);
- // emit specialized object click signals:
- QVariant details;
- QCPLayerable *clickedLayerable = layerableAt(event->pos(), false, &details); // for these signals, selectability is ignored, that's why we call this again with onlySelectable set to false
- if (QCPAbstractPlottable *ap = qobject_cast<QCPAbstractPlottable*>(clickedLayerable))
- emit plottableClick(ap, event);
- else if (QCPAxis *ax = qobject_cast<QCPAxis*>(clickedLayerable))
- emit axisClick(ax, details.value<QCPAxis::SelectablePart>(), event);
- else if (QCPAbstractItem *ai = qobject_cast<QCPAbstractItem*>(clickedLayerable))
+ // emit specialized click signals of QCustomPlot instance:
+ if (QCPAbstractPlottable *ap = qobject_cast<QCPAbstractPlottable*>(mMouseEventLayerable))
+ {
+ int dataIndex = 0;
+ if (!mMouseEventLayerableDetails.value<QCPDataSelection>().isEmpty())
+ dataIndex = mMouseEventLayerableDetails.value<QCPDataSelection>().dataRange().begin();
+ emit plottableClick(ap, dataIndex, event);
+ } else if (QCPAxis *ax = qobject_cast<QCPAxis*>(mMouseEventLayerable))
+ emit axisClick(ax, mMouseEventLayerableDetails.value<QCPAxis::SelectablePart>(), event);
+ else if (QCPAbstractItem *ai = qobject_cast<QCPAbstractItem*>(mMouseEventLayerable))
emit itemClick(ai, event);
- else if (QCPLegend *lg = qobject_cast<QCPLegend*>(clickedLayerable))
+ else if (QCPLegend *lg = qobject_cast<QCPLegend*>(mMouseEventLayerable))
emit legendClick(lg, 0, event);
- else if (QCPAbstractLegendItem *li = qobject_cast<QCPAbstractLegendItem*>(clickedLayerable))
+ else if (QCPAbstractLegendItem *li = qobject_cast<QCPAbstractLegendItem*>(mMouseEventLayerable))
emit legendClick(li->parentLegend(), li, event);
- else if (QCPPlotTitle *pt = qobject_cast<QCPPlotTitle*>(clickedLayerable))
- emit titleClick(event, pt);
}
- // call event of affected layout element:
- if (mMouseEventElement)
+ if (mSelectionRect && mSelectionRect->isActive()) // Note: if a click was detected above, the selection rect is canceled there
+ {
+ // finish selection rect, the appropriate action will be taken via signal-slot connection:
+ mSelectionRect->endSelection(event);
+ } else
{
- mMouseEventElement->mouseReleaseEvent(event);
- mMouseEventElement = 0;
+ // call event of affected layerable:
+ if (mMouseEventLayerable)
+ {
+ mMouseEventLayerable->mouseReleaseEvent(event, mMousePressPos);
+ mMouseEventLayerable = 0;
+ }
}
- if (doReplot || noAntialiasingOnDrag())
- replot();
+ if (noAntialiasingOnDrag())
+ replot(rpQueuedReplot);
- QWidget::mouseReleaseEvent(event);
+ event->accept(); // in case QCPLayerable reimplementation manipulates event accepted state. In QWidget event system, QCustomPlot wants to accept the event.
}
/*! \internal
-
+
Event handler for mouse wheel events. First, the \ref mouseWheel signal is emitted. Then
- determines the affected layout element and forwards the event to it.
-
+ determines the affected layerable and forwards the event to it.
*/
void QCustomPlot::wheelEvent(QWheelEvent *event)
{
emit mouseWheel(event);
-
- // call event of affected layout element:
- if (QCPLayoutElement *el = layoutElementAt(event->pos()))
- el->wheelEvent(event);
-
- QWidget::wheelEvent(event);
+ // forward event to layerable under cursor:
+ QList<QCPLayerable*> candidates = layerableListAt(event->pos(), false);
+ for (int i=0; i<candidates.size(); ++i)
+ {
+ event->accept(); // default impl of QCPLayerable's mouse events ignore the event, in that case propagate to next candidate in list
+ candidates.at(i)->wheelEvent(event);
+ if (event->isAccepted())
+ break;
+ }
+ event->accept(); // in case QCPLayerable reimplementation manipulates event accepted state. In QWidget event system, QCustomPlot wants to accept the event.
}
/*! \internal
- This is the main draw function. It draws the entire plot, including background pixmap, with the
- specified \a painter. Note that it does not fill the background with the background brush (as the
- user may specify with \ref setBackground(const QBrush &brush)), this is up to the respective
- functions calling this method (e.g. \ref replot, \ref toPixmap and \ref toPainter).
+ This function draws the entire plot, including background pixmap, with the specified \a painter.
+ It does not make use of the paint buffers like \ref replot, so this is the function typically
+ used by saving/exporting methods such as \ref savePdf or \ref toPainter.
+
+ Note that it does not fill the background with the background brush (as the user may specify with
+ \ref setBackground(const QBrush &brush)), this is up to the respective functions calling this
+ method.
*/
void QCustomPlot::draw(QCPPainter *painter)
{
- // run through layout phases:
- mPlotLayout->update(QCPLayoutElement::upPreparation);
- mPlotLayout->update(QCPLayoutElement::upMargins);
- mPlotLayout->update(QCPLayoutElement::upLayout);
+ updateLayout();
// draw viewport background pixmap:
drawBackground(painter);
// draw all layered objects (grid, axes, plottables, items, legend,...):
foreach (QCPLayer *layer, mLayers)
- {
- foreach (QCPLayerable *child, layer->children())
- {
- if (child->realVisibility())
- {
- painter->save();
- painter->setClipRect(child->clipRect().translated(0, -1));
- child->applyDefaultAntialiasingHint(painter);
- child->draw(painter);
- painter->restore();
- }
- }
- }
+ layer->draw(painter);
/* Debug code to draw all layout element rects
foreach (QCPLayoutElement* el, findChildren<QCPLayoutElement*>())
@@ -10904,6 +14714,22 @@ void QCustomPlot::draw(QCPPainter *painter)
}
/*! \internal
+
+ Performs the layout update steps defined by \ref QCPLayoutElement::UpdatePhase, by calling \ref
+ QCPLayoutElement::update on the main plot layout.
+
+ Here, the layout elements calculate their positions and margins, and prepare for the following
+ draw call.
+*/
+void QCustomPlot::updateLayout()
+{
+ // run through layout phases:
+ mPlotLayout->update(QCPLayoutElement::upPreparation);
+ mPlotLayout->update(QCPLayoutElement::upMargins);
+ mPlotLayout->update(QCPLayoutElement::upLayout);
+}
+
+/*! \internal
Draws the viewport background pixmap of the plot.
@@ -10915,8 +14741,8 @@ void QCustomPlot::draw(QCPPainter *painter)
dependent on the \ref setBackgroundScaledMode), or when a differend axis background pixmap was
set.
- Note that this function does not draw a fill with the background brush (\ref setBackground(const
- QBrush &brush)) beneath the pixmap.
+ Note that this function does not draw a fill with the background brush
+ (\ref setBackground(const QBrush &brush)) beneath the pixmap.
\see setBackground, setBackgroundScaled, setBackgroundScaledMode
*/
@@ -10942,6 +14768,187 @@ void QCustomPlot::drawBackground(QCPPainter *painter)
}
}
+/*! \internal
+
+ Goes through the layers and makes sure this QCustomPlot instance holds the correct number of
+ paint buffers and that they have the correct configuration (size, pixel ratio, etc.).
+ Allocations, reallocations and deletions of paint buffers are performed as necessary. It also
+ associates the paint buffers with the layers, so they draw themselves into the right buffer when
+ \ref QCPLayer::drawToPaintBuffer is called. This means it associates adjacent \ref
+ QCPLayer::lmLogical layers to a mutual paint buffer and creates dedicated paint buffers for
+ layers in \ref QCPLayer::lmBuffered mode.
+
+ This method uses \ref createPaintBuffer to create new paint buffers.
+
+ After this method, the paint buffers are empty (filled with \c Qt::transparent) and invalidated
+ (so an attempt to replot only a single buffered layer causes a full replot).
+
+ This method is called in every \ref replot call, prior to actually drawing the layers (into their
+ associated paint buffer). If the paint buffers don't need changing/reallocating, this method
+ basically leaves them alone and thus finishes very fast.
+*/
+void QCustomPlot::setupPaintBuffers()
+{
+ int bufferIndex = 0;
+ if (mPaintBuffers.isEmpty())
+ mPaintBuffers.append(QSharedPointer<QCPAbstractPaintBuffer>(createPaintBuffer()));
+
+ for (int layerIndex = 0; layerIndex < mLayers.size(); ++layerIndex)
+ {
+ QCPLayer *layer = mLayers.at(layerIndex);
+ if (layer->mode() == QCPLayer::lmLogical)
+ {
+ layer->mPaintBuffer = mPaintBuffers.at(bufferIndex).toWeakRef();
+ } else if (layer->mode() == QCPLayer::lmBuffered)
+ {
+ ++bufferIndex;
+ if (bufferIndex >= mPaintBuffers.size())
+ mPaintBuffers.append(QSharedPointer<QCPAbstractPaintBuffer>(createPaintBuffer()));
+ layer->mPaintBuffer = mPaintBuffers.at(bufferIndex).toWeakRef();
+ 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
+ {
+ ++bufferIndex;
+ if (bufferIndex >= mPaintBuffers.size())
+ mPaintBuffers.append(QSharedPointer<QCPAbstractPaintBuffer>(createPaintBuffer()));
+ }
+ }
+ }
+ // remove unneeded buffers:
+ while (mPaintBuffers.size()-1 > bufferIndex)
+ mPaintBuffers.removeLast();
+ // resize buffers to viewport size and clear contents:
+ for (int i=0; i<mPaintBuffers.size(); ++i)
+ {
+ mPaintBuffers.at(i)->setSize(viewport().size()); // won't do anything if already correct size
+ mPaintBuffers.at(i)->clear(Qt::transparent);
+ mPaintBuffers.at(i)->setInvalidated();
+ }
+}
+
+/*! \internal
+
+ This method is used by \ref setupPaintBuffers when it needs to create new paint buffers.
+
+ Depending on the current setting of \ref setOpenGl, and the current Qt version, different
+ backends (subclasses of \ref QCPAbstractPaintBuffer) are created, initialized with the proper
+ size and device pixel ratio, and returned.
+*/
+QCPAbstractPaintBuffer *QCustomPlot::createPaintBuffer()
+{
+ if (mOpenGl)
+ {
+#if defined(QCP_OPENGL_FBO)
+ return new QCPPaintBufferGlFbo(viewport().size(), mBufferDevicePixelRatio, mGlContext, mGlPaintDevice);
+#elif defined(QCP_OPENGL_PBUFFER)
+ return new QCPPaintBufferGlPbuffer(viewport().size(), mBufferDevicePixelRatio, mOpenGlMultisamples);
+#else
+ 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.";
+ return new QCPPaintBufferPixmap(viewport().size(), mBufferDevicePixelRatio);
+#endif
+ } else
+ return new QCPPaintBufferPixmap(viewport().size(), mBufferDevicePixelRatio);
+}
+
+/*!
+ This method returns whether any of the paint buffers held by this QCustomPlot instance are
+ invalidated.
+
+ If any buffer is invalidated, a partial replot (\ref QCPLayer::replot) is not allowed and always
+ causes a full replot (\ref QCustomPlot::replot) of all layers. This is the case when for example
+ the layer order has changed, new layers were added, layers were removed, or layer modes were
+ changed (\ref QCPLayer::setMode).
+
+ \see QCPAbstractPaintBuffer::setInvalidated
+*/
+bool QCustomPlot::hasInvalidatedPaintBuffers()
+{
+ for (int i=0; i<mPaintBuffers.size(); ++i)
+ {
+ if (mPaintBuffers.at(i)->invalidated())
+ return true;
+ }
+ return false;
+}
+
+/*! \internal
+
+ When \ref setOpenGl is set to true, this method is used to initialize OpenGL (create a context,
+ surface, paint device).
+
+ Returns true on success.
+
+ If this method is successful, all paint buffers should be deleted and then reallocated by calling
+ \ref setupPaintBuffers, so the OpenGL-based paint buffer subclasses (\ref
+ QCPPaintBufferGlPbuffer, \ref QCPPaintBufferGlFbo) are used for subsequent replots.
+
+ \see freeOpenGl
+*/
+bool QCustomPlot::setupOpenGl()
+{
+#ifdef QCP_OPENGL_FBO
+ freeOpenGl();
+ QSurfaceFormat proposedSurfaceFormat;
+ proposedSurfaceFormat.setSamples(mOpenGlMultisamples);
+#ifdef QCP_OPENGL_OFFSCREENSURFACE
+ QOffscreenSurface *surface = new QOffscreenSurface;
+#else
+ QWindow *surface = new QWindow;
+ surface->setSurfaceType(QSurface::OpenGLSurface);
+#endif
+ surface->setFormat(proposedSurfaceFormat);
+ surface->create();
+ mGlSurface = QSharedPointer<QSurface>(surface);
+ mGlContext = QSharedPointer<QOpenGLContext>(new QOpenGLContext);
+ mGlContext->setFormat(mGlSurface->format());
+ if (!mGlContext->create())
+ {
+ qDebug() << Q_FUNC_INFO << "Failed to create OpenGL context";
+ mGlContext.clear();
+ mGlSurface.clear();
+ return false;
+ }
+ if (!mGlContext->makeCurrent(mGlSurface.data())) // context needs to be current to create paint device
+ {
+ qDebug() << Q_FUNC_INFO << "Failed to make opengl context current";
+ mGlContext.clear();
+ mGlSurface.clear();
+ return false;
+ }
+ if (!QOpenGLFramebufferObject::hasOpenGLFramebufferObjects())
+ {
+ qDebug() << Q_FUNC_INFO << "OpenGL of this system doesn't support frame buffer objects";
+ mGlContext.clear();
+ mGlSurface.clear();
+ return false;
+ }
+ mGlPaintDevice = QSharedPointer<QOpenGLPaintDevice>(new QOpenGLPaintDevice);
+ return true;
+#elif defined(QCP_OPENGL_PBUFFER)
+ return QGLFormat::hasOpenGL();
+#else
+ return false;
+#endif
+}
+
+/*! \internal
+
+ When \ref setOpenGl is set to false, this method is used to deinitialize OpenGL (releases the
+ context and frees resources).
+
+ After OpenGL is disabled, all paint buffers should be deleted and then reallocated by calling
+ \ref setupPaintBuffers, so the standard software rendering paint buffer subclass (\ref
+ QCPPaintBufferPixmap) is used for subsequent replots.
+
+ \see setupOpenGl
+*/
+void QCustomPlot::freeOpenGl()
+{
+#ifdef QCP_OPENGL_FBO
+ mGlPaintDevice.clear();
+ mGlContext.clear();
+ mGlSurface.clear();
+#endif
+}
/*! \internal
@@ -10975,6 +14982,261 @@ void QCustomPlot::legendRemoved(QCPLegend *legend)
/*! \internal
+ This slot is connected to the selection rect's \ref QCPSelectionRect::accepted signal when \ref
+ setSelectionRectMode is set to \ref QCP::srmSelect.
+
+ First, it determines which axis rect was the origin of the selection rect judging by the starting
+ point of the selection. Then it goes through the plottables (\ref QCPAbstractPlottable1D to be
+ precise) associated with that axis rect and finds the data points that are in \a rect. It does
+ this by querying their \ref QCPAbstractPlottable1D::selectTestRect method.
+
+ Then, the actual selection is done by calling the plottables' \ref
+ QCPAbstractPlottable::selectEvent, placing the found selected data points in the \a details
+ parameter as <tt>QVariant(\ref QCPDataSelection)</tt>. All plottables that weren't touched by \a
+ rect receive a \ref QCPAbstractPlottable::deselectEvent.
+
+ \see processRectZoom
+*/
+void QCustomPlot::processRectSelection(QRect rect, QMouseEvent *event)
+{
+ bool selectionStateChanged = false;
+
+ if (mInteractions.testFlag(QCP::iSelectPlottables))
+ {
+ QMap<int, QPair<QCPAbstractPlottable*, QCPDataSelection> > potentialSelections; // map key is number of selected data points, so we have selections sorted by size
+ QRectF rectF(rect.normalized());
+ if (QCPAxisRect *affectedAxisRect = axisRectAt(rectF.topLeft()))
+ {
+ // determine plottables that were hit by the rect and thus are candidates for selection:
+ foreach (QCPAbstractPlottable *plottable, affectedAxisRect->plottables())
+ {
+ if (QCPPlottableInterface1D *plottableInterface = plottable->interface1D())
+ {
+ QCPDataSelection dataSel = plottableInterface->selectTestRect(rectF, true);
+ if (!dataSel.isEmpty())
+ potentialSelections.insertMulti(dataSel.dataPointCount(), QPair<QCPAbstractPlottable*, QCPDataSelection>(plottable, dataSel));
+ }
+ }
+
+ if (!mInteractions.testFlag(QCP::iMultiSelect))
+ {
+ // only leave plottable with most selected points in map, since we will only select a single plottable:
+ if (!potentialSelections.isEmpty())
+ {
+ QMap<int, QPair<QCPAbstractPlottable*, QCPDataSelection> >::iterator it = potentialSelections.begin();
+ while (it != potentialSelections.end()-1) // erase all except last element
+ it = potentialSelections.erase(it);
+ }
+ }
+
+ bool additive = event->modifiers().testFlag(mMultiSelectModifier);
+ // deselect all other layerables if not additive selection:
+ if (!additive)
+ {
+ // emit deselection except to those plottables who will be selected afterwards:
+ foreach (QCPLayer *layer, mLayers)
+ {
+ foreach (QCPLayerable *layerable, layer->children())
+ {
+ if ((potentialSelections.isEmpty() || potentialSelections.constBegin()->first != layerable) && mInteractions.testFlag(layerable->selectionCategory()))
+ {
+ bool selChanged = false;
+ layerable->deselectEvent(&selChanged);
+ selectionStateChanged |= selChanged;
+ }
+ }
+ }
+ }
+
+ // go through selections in reverse (largest selection first) and emit select events:
+ QMap<int, QPair<QCPAbstractPlottable*, QCPDataSelection> >::const_iterator it = potentialSelections.constEnd();
+ while (it != potentialSelections.constBegin())
+ {
+ --it;
+ if (mInteractions.testFlag(it.value().first->selectionCategory()))
+ {
+ bool selChanged = false;
+ it.value().first->selectEvent(event, additive, QVariant::fromValue(it.value().second), &selChanged);
+ selectionStateChanged |= selChanged;
+ }
+ }
+ }
+ }
+
+ if (selectionStateChanged)
+ {
+ emit selectionChangedByUser();
+ replot(rpQueuedReplot);
+ } else if (mSelectionRect)
+ mSelectionRect->layer()->replot();
+}
+
+/*! \internal
+
+ This slot is connected to the selection rect's \ref QCPSelectionRect::accepted signal when \ref
+ setSelectionRectMode is set to \ref QCP::srmZoom.
+
+ It determines which axis rect was the origin of the selection rect judging by the starting point
+ of the selection, and then zooms the axes defined via \ref QCPAxisRect::setRangeZoomAxes to the
+ provided \a rect (see \ref QCPAxisRect::zoom).
+
+ \see processRectSelection
+*/
+void QCustomPlot::processRectZoom(QRect rect, QMouseEvent *event)
+{
+ Q_UNUSED(event)
+ if (QCPAxisRect *axisRect = axisRectAt(rect.topLeft()))
+ {
+ QList<QCPAxis*> affectedAxes = QList<QCPAxis*>() << axisRect->rangeZoomAxes(Qt::Horizontal) << axisRect->rangeZoomAxes(Qt::Vertical);
+ affectedAxes.removeAll(static_cast<QCPAxis*>(0));
+ axisRect->zoom(QRectF(rect), affectedAxes);
+ }
+ replot(rpQueuedReplot); // always replot to make selection rect disappear
+}
+
+/*! \internal
+
+ This method is called when a simple left mouse click was detected on the QCustomPlot surface.
+
+ It first determines the layerable that was hit by the click, and then calls its \ref
+ QCPLayerable::selectEvent. All other layerables receive a QCPLayerable::deselectEvent (unless the
+ multi-select modifier was pressed, see \ref setMultiSelectModifier).
+
+ In this method the hit layerable is determined a second time using \ref layerableAt (after the
+ one in \ref mousePressEvent), because we want \a onlySelectable set to true this time. This
+ implies that the mouse event grabber (mMouseEventLayerable) may be a different one from the
+ clicked layerable determined here. For example, if a non-selectable layerable is in front of a
+ selectable layerable at the click position, the front layerable will receive mouse events but the
+ selectable one in the back will receive the \ref QCPLayerable::selectEvent.
+
+ \see processRectSelection, QCPLayerable::selectTest
+*/
+void QCustomPlot::processPointSelection(QMouseEvent *event)
+{
+ QVariant details;
+ QCPLayerable *clickedLayerable = layerableAt(event->pos(), true, &details);
+ bool selectionStateChanged = false;
+ bool additive = mInteractions.testFlag(QCP::iMultiSelect) && event->modifiers().testFlag(mMultiSelectModifier);
+ // deselect all other layerables if not additive selection:
+ if (!additive)
+ {
+ foreach (QCPLayer *layer, mLayers)
+ {
+ foreach (QCPLayerable *layerable, layer->children())
+ {
+ if (layerable != clickedLayerable && mInteractions.testFlag(layerable->selectionCategory()))
+ {
+ bool selChanged = false;
+ layerable->deselectEvent(&selChanged);
+ selectionStateChanged |= selChanged;
+ }
+ }
+ }
+ }
+ if (clickedLayerable && mInteractions.testFlag(clickedLayerable->selectionCategory()))
+ {
+ // a layerable was actually clicked, call its selectEvent:
+ bool selChanged = false;
+ clickedLayerable->selectEvent(event, additive, details, &selChanged);
+ selectionStateChanged |= selChanged;
+ }
+ if (selectionStateChanged)
+ {
+ emit selectionChangedByUser();
+ replot(rpQueuedReplot);
+ }
+}
+
+/*! \internal
+
+ Registers the specified plottable with this QCustomPlot and, if \ref setAutoAddPlottableToLegend
+ is enabled, adds it to the legend (QCustomPlot::legend). QCustomPlot takes ownership of the
+ plottable.
+
+ Returns true on success, i.e. when \a plottable isn't already in this plot and the parent plot of
+ \a plottable is this QCustomPlot.
+
+ This method is called automatically in the QCPAbstractPlottable base class constructor.
+*/
+bool QCustomPlot::registerPlottable(QCPAbstractPlottable *plottable)
+{
+ if (mPlottables.contains(plottable))
+ {
+ qDebug() << Q_FUNC_INFO << "plottable already added to this QCustomPlot:" << reinterpret_cast<quintptr>(plottable);
+ return false;
+ }
+ if (plottable->parentPlot() != this)
+ {
+ qDebug() << Q_FUNC_INFO << "plottable not created with this QCustomPlot as parent:" << reinterpret_cast<quintptr>(plottable);
+ return false;
+ }
+
+ mPlottables.append(plottable);
+ // possibly add plottable to legend:
+ if (mAutoAddPlottableToLegend)
+ plottable->addToLegend();
+ if (!plottable->layer()) // usually the layer is already set in the constructor of the plottable (via QCPLayerable constructor)
+ plottable->setLayer(currentLayer());
+ return true;
+}
+
+/*! \internal
+
+ In order to maintain the simplified graph interface of QCustomPlot, this method is called by the
+ QCPGraph constructor to register itself with this QCustomPlot's internal graph list. Returns true
+ on success, i.e. if \a graph is valid and wasn't already registered with this QCustomPlot.
+
+ This graph specific registration happens in addition to the call to \ref registerPlottable by the
+ QCPAbstractPlottable base class.
+*/
+bool QCustomPlot::registerGraph(QCPGraph *graph)
+{
+ if (!graph)
+ {
+ qDebug() << Q_FUNC_INFO << "passed graph is zero";
+ return false;
+ }
+ if (mGraphs.contains(graph))
+ {
+ qDebug() << Q_FUNC_INFO << "graph already registered with this QCustomPlot";
+ return false;
+ }
+
+ mGraphs.append(graph);
+ return true;
+}
+
+
+/*! \internal
+
+ Registers the specified item with this QCustomPlot. QCustomPlot takes ownership of the item.
+
+ Returns true on success, i.e. when \a item wasn't already in the plot and the parent plot of \a
+ item is this QCustomPlot.
+
+ This method is called automatically in the QCPAbstractItem base class constructor.
+*/
+bool QCustomPlot::registerItem(QCPAbstractItem *item)
+{
+ if (mItems.contains(item))
+ {
+ qDebug() << Q_FUNC_INFO << "item already added to this QCustomPlot:" << reinterpret_cast<quintptr>(item);
+ return false;
+ }
+ if (item->parentPlot() != this)
+ {
+ qDebug() << Q_FUNC_INFO << "item not created with this QCustomPlot as parent:" << reinterpret_cast<quintptr>(item);
+ return false;
+ }
+
+ mItems.append(item);
+ if (!item->layer()) // usually the layer is already set in the constructor of the item (via QCPLayerable constructor)
+ item->setLayer(currentLayer());
+ return true;
+}
+
+/*! \internal
+
Assigns all layers their index (QCPLayer::mIndex) in the mLayers list. This method is thus called
after every operation that changes the layer indices, like layer removal, layer creation, layer
moving.
@@ -10986,41 +15248,71 @@ void QCustomPlot::updateLayerIndices() const
}
/*! \internal
+
+ Returns the top-most layerable at pixel position \a pos. If \a onlySelectable is set to true,
+ only those layerables that are selectable will be considered. (Layerable subclasses communicate
+ their selectability via the QCPLayerable::selectTest method, by returning -1.)
+
+ \a selectionDetails is an output parameter that contains selection specifics of the affected
+ layerable. This is useful if the respective layerable shall be given a subsequent
+ QCPLayerable::selectEvent (like in \ref mouseReleaseEvent). \a selectionDetails usually contains
+ information about which part of the layerable was hit, in multi-part layerables (e.g.
+ QCPAxis::SelectablePart). If the layerable is a plottable, \a selectionDetails contains a \ref
+ QCPDataSelection instance with the single data point which is closest to \a pos.
- Returns the layerable at pixel position \a pos. If \a onlySelectable is set to true, only those
+ \see layerableListAt, layoutElementAt, axisRectAt
+*/
+QCPLayerable *QCustomPlot::layerableAt(const QPointF &pos, bool onlySelectable, QVariant *selectionDetails) const
+{
+ QList<QVariant> details;
+ QList<QCPLayerable*> candidates = layerableListAt(pos, onlySelectable, selectionDetails ? &details : 0);
+ if (selectionDetails && !details.isEmpty())
+ *selectionDetails = details.first();
+ if (!candidates.isEmpty())
+ return candidates.first();
+ else
+ return 0;
+}
+
+/*! \internal
+
+ Returns the layerables at pixel position \a pos. If \a onlySelectable is set to true, only those
layerables that are selectable will be considered. (Layerable subclasses communicate their
selectability via the QCPLayerable::selectTest method, by returning -1.)
+ The returned list is sorted by the layerable/drawing order. If you only need to know the top-most
+ layerable, rather use \ref layerableAt.
+
\a selectionDetails is an output parameter that contains selection specifics of the affected
layerable. This is useful if the respective layerable shall be given a subsequent
QCPLayerable::selectEvent (like in \ref mouseReleaseEvent). \a selectionDetails usually contains
information about which part of the layerable was hit, in multi-part layerables (e.g.
- QCPAxis::SelectablePart).
+ QCPAxis::SelectablePart). If the layerable is a plottable, \a selectionDetails contains a \ref
+ QCPDataSelection instance with the single data point which is closest to \a pos.
+
+ \see layerableAt, layoutElementAt, axisRectAt
*/
-QCPLayerable *QCustomPlot::layerableAt(const QPointF &pos, bool onlySelectable, QVariant *selectionDetails) const
+QList<QCPLayerable*> QCustomPlot::layerableListAt(const QPointF &pos, bool onlySelectable, QList<QVariant> *selectionDetails) const
{
+ QList<QCPLayerable*> result;
for (int layerIndex=mLayers.size()-1; layerIndex>=0; --layerIndex)
{
const QList<QCPLayerable*> layerables = mLayers.at(layerIndex)->children();
- double minimumDistance = selectionTolerance()*1.1;
- QCPLayerable *minimumDistanceLayerable = 0;
for (int i=layerables.size()-1; i>=0; --i)
{
if (!layerables.at(i)->realVisibility())
continue;
QVariant details;
- double dist = layerables.at(i)->selectTest(pos, onlySelectable, &details);
- if (dist >= 0 && dist < minimumDistance)
+ double dist = layerables.at(i)->selectTest(pos, onlySelectable, selectionDetails ? &details : 0);
+ if (dist >= 0 && dist < selectionTolerance())
{
- minimumDistance = dist;
- minimumDistanceLayerable = layerables.at(i);
- if (selectionDetails) *selectionDetails = details;
+ result.append(layerables.at(i));
+ if (selectionDetails)
+ selectionDetails->append(details);
}
}
- if (minimumDistance < selectionTolerance())
- return minimumDistanceLayerable;
}
- return 0;
+ return result;
}
/*!
@@ -11028,15 +15320,32 @@ QCPLayerable *QCustomPlot::layerableAt(const QPointF &pos, bool onlySelectable,
sized to \a width and \a height in pixels and scaled with \a scale. (width 100 and scale 2.0 lead
to a full resolution file with width 200.) If the \a format supports compression, \a quality may
be between 0 and 100 to control it.
-
+
Returns true on success. If this function fails, most likely the given \a format isn't supported
by the system, see Qt docs about QImageWriter::supportedImageFormats().
-
+
+ The \a resolution will be written to the image file header (if the file format supports this) and
+ has no direct consequence for the quality or the pixel size. However, if opening the image with a
+ tool which respects the metadata, it will be able to scale the image to match either a given size
+ in real units of length (inch, centimeters, etc.), or the target display DPI. You can specify in
+ which units \a resolution is given, by setting \a resolutionUnit. The \a resolution is converted
+ to the format's expected resolution unit internally.
+
\see saveBmp, saveJpg, savePng, savePdf
*/
-bool QCustomPlot::saveRastered(const QString &fileName, int width, int height, double scale, const char *format, int quality)
+bool QCustomPlot::saveRastered(const QString &fileName, int width, int height, double scale, const char *format, int quality, int resolution, QCP::ResolutionUnit resolutionUnit)
{
- QPixmap buffer = toPixmap(width, height, scale);
+ QImage buffer = toPixmap(width, height, scale).toImage();
+
+ int dotsPerMeter = 0;
+ switch (resolutionUnit)
+ {
+ case QCP::ruDotsPerMeter: dotsPerMeter = resolution; break;
+ case QCP::ruDotsPerCentimeter: dotsPerMeter = resolution*100; break;
+ case QCP::ruDotsPerInch: dotsPerMeter = resolution/0.0254; break;
+ }
+ buffer.setDotsPerMeterX(dotsPerMeter); // this is saved together with some image formats, e.g. PNG, and is relevant when opening image in other tools
+ buffer.setDotsPerMeterY(dotsPerMeter); // this is saved together with some image formats, e.g. PNG, and is relevant when opening image in other tools
if (!buffer.isNull())
return buffer.save(fileName, format, quality);
else
@@ -11133,6 +15442,12 @@ void QCustomPlot::toPainter(QCPPainter *painter, int width, int height)
} else
qDebug() << Q_FUNC_INFO << "Passed painter is not active";
}
+/* end of 'src/core.cpp' */
+
+//amalgamation: add plottable1d.cpp
+
+/* including file 'src/colorgradient.cpp', size 24646 */
+/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
////////////////////////////////////////////////////////////////////////////////////////////////////
@@ -11151,11 +15466,15 @@ void QCustomPlot::toPainter(QCPPainter *painter, int width, int height)
Alternatively, load one of the preset color gradients shown in the image below, with \ref
loadPreset, or by directly specifying the preset in the constructor.
+ Apart from red, green and blue components, the gradient also interpolates the alpha values of the
+ configured color stops. This allows to display some portions of the data range as transparent in
+ the plot.
+
\image html QCPColorGradient.png
- The fact that the \ref QCPColorGradient(GradientPreset preset) constructor allows directly
- converting a \ref GradientPreset to a QCPColorGradient, you can also directly pass \ref
- GradientPreset to all the \a setGradient methods, e.g.:
+ The \ref QCPColorGradient(GradientPreset preset) constructor allows directly converting a \ref
+ GradientPreset to a QCPColorGradient. This means that you can directly pass \ref GradientPreset
+ to all the \a setGradient methods, e.g.:
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolorgradient-setgradient
The total number of levels used in the gradient can be set with \ref setLevelCount. Whether the
@@ -11164,9 +15483,24 @@ void QCustomPlot::toPainter(QCPPainter *painter, int width, int height)
*/
/*!
+ Constructs a new, empty QCPColorGradient with no predefined color stops. You can add own color
+ stops with \ref setColorStopAt.
+
+ The color level count is initialized to 350.
+*/
+QCPColorGradient::QCPColorGradient() :
+ mLevelCount(350),
+ mColorInterpolation(ciRGB),
+ mPeriodic(false),
+ mColorBufferInvalidated(true)
+{
+ mColorBuffer.fill(qRgb(0, 0, 0), mLevelCount);
+}
+
+/*!
Constructs a new QCPColorGradient initialized with the colors and color interpolation according
to \a preset.
-
+
The color level count is initialized to 350.
*/
QCPColorGradient::QCPColorGradient(GradientPreset preset) :
@@ -11190,8 +15524,8 @@ bool QCPColorGradient::operator==(const QCPColorGradient &other) const
/*!
Sets the number of discretization levels of the color gradient to \a n. The default is 350 which
- is typically enough to create a smooth appearance.
-
+ is typically enough to create a smooth appearance. The minimum number of levels is 2.
+
\image html QCPColorGradient-levelcount.png
*/
void QCPColorGradient::setLevelCount(int n)
@@ -11214,7 +15548,8 @@ void QCPColorGradient::setLevelCount(int n)
is interpolated according to \ref setColorInterpolation.
A more convenient way to create a custom gradient may be to clear all color stops with \ref
- clearColorStops and then adding them one by one with \ref setColorStopAt.
+ clearColorStops (or creating a new, empty QCPColorGradient) and then adding them one by one with
+ \ref setColorStopAt.
\see clearColorStops
*/
@@ -11272,21 +15607,27 @@ void QCPColorGradient::setPeriodic(bool enabled)
mPeriodic = enabled;
}
-/*!
+/*! \overload
+
This method is used to quickly convert a \a data array to colors. The colors will be output in
the array \a scanLine. Both \a data and \a scanLine must have the length \a n when passed to this
function. The data range that shall be used for mapping the data value to the gradient is passed
in \a range. \a logarithmic indicates whether the data values shall be mapped to colors
logarithmically.
-
+
if \a data actually contains 2D-data linearized via <tt>[row*columnCount + column]</tt>, you can
set \a dataIndexFactor to <tt>columnCount</tt> to convert a column instead of a row of the data
array, in \a scanLine. \a scanLine will remain a regular (1D) array. This works because \a data
is addressed <tt>data[i*dataIndexFactor]</tt>.
+
+ Use the overloaded method to additionally provide alpha map data.
+
+ The QRgb values that are placed in \a scanLine have their r, g and b components premultiplied
+ with alpha (see QImage::Format_ARGB32_Premultiplied).
*/
void QCPColorGradient::colorize(const double *data, const QCPRange &range, QRgb *scanLine, int n, int dataIndexFactor, bool logarithmic)
{
- // If you change something here, make sure to also adapt ::color()
+ // If you change something here, make sure to also adapt color() and the other colorize() overload
if (!data)
{
qDebug() << Q_FUNC_INFO << "null pointer given as data";
@@ -11350,14 +15691,128 @@ void QCPColorGradient::colorize(const double *data, const QCPRange &range, QRgb
}
}
-/*! \internal
+/*! \overload
+
+ Additionally to the other overload of \ref colorize, this method takes the array \a alpha, which
+ has the same size and structure as \a data and encodes the alpha information per data point.
+
+ The QRgb values that are placed in \a scanLine have their r, g and b components premultiplied
+ with alpha (see QImage::Format_ARGB32_Premultiplied).
+*/
+void QCPColorGradient::colorize(const double *data, const unsigned char *alpha, const QCPRange &range, QRgb *scanLine, int n, int dataIndexFactor, bool logarithmic)
+{
+ // If you change something here, make sure to also adapt color() and the other colorize() overload
+ if (!data)
+ {
+ qDebug() << Q_FUNC_INFO << "null pointer given as data";
+ return;
+ }
+ if (!alpha)
+ {
+ qDebug() << Q_FUNC_INFO << "null pointer given as alpha";
+ return;
+ }
+ if (!scanLine)
+ {
+ qDebug() << Q_FUNC_INFO << "null pointer given as scanLine";
+ return;
+ }
+ if (mColorBufferInvalidated)
+ updateColorBuffer();
+ if (!logarithmic)
+ {
+ const double posToIndexFactor = (mLevelCount-1)/range.size();
+ if (mPeriodic)
+ {
+ for (int i=0; i<n; ++i)
+ {
+ int index = (int)((data[dataIndexFactor*i]-range.lower)*posToIndexFactor) % mLevelCount;
+ if (index < 0)
+ index += mLevelCount;
+ if (alpha[dataIndexFactor*i] == 255)
+ {
+ scanLine[i] = mColorBuffer.at(index);
+ } else
+ {
+ const QRgb rgb = mColorBuffer.at(index);
+ const float alphaF = alpha[dataIndexFactor*i]/255.0f;
+ scanLine[i] = qRgba(qRed(rgb)*alphaF, qGreen(rgb)*alphaF, qBlue(rgb)*alphaF, qAlpha(rgb)*alphaF);
+ }
+ }
+ } else
+ {
+ for (int i=0; i<n; ++i)
+ {
+ int index = (data[dataIndexFactor*i]-range.lower)*posToIndexFactor;
+ if (index < 0)
+ index = 0;
+ else if (index >= mLevelCount)
+ index = mLevelCount-1;
+ if (alpha[dataIndexFactor*i] == 255)
+ {
+ scanLine[i] = mColorBuffer.at(index);
+ } else
+ {
+ const QRgb rgb = mColorBuffer.at(index);
+ const float alphaF = alpha[dataIndexFactor*i]/255.0f;
+ scanLine[i] = qRgba(qRed(rgb)*alphaF, qGreen(rgb)*alphaF, qBlue(rgb)*alphaF, qAlpha(rgb)*alphaF);
+ }
+ }
+ }
+ } else // logarithmic == true
+ {
+ if (mPeriodic)
+ {
+ for (int i=0; i<n; ++i)
+ {
+ int index = (int)(qLn(data[dataIndexFactor*i]/range.lower)/qLn(range.upper/range.lower)*(mLevelCount-1)) % mLevelCount;
+ if (index < 0)
+ index += mLevelCount;
+ if (alpha[dataIndexFactor*i] == 255)
+ {
+ scanLine[i] = mColorBuffer.at(index);
+ } else
+ {
+ const QRgb rgb = mColorBuffer.at(index);
+ const float alphaF = alpha[dataIndexFactor*i]/255.0f;
+ scanLine[i] = qRgba(qRed(rgb)*alphaF, qGreen(rgb)*alphaF, qBlue(rgb)*alphaF, qAlpha(rgb)*alphaF);
+ }
+ }
+ } else
+ {
+ for (int i=0; i<n; ++i)
+ {
+ int index = qLn(data[dataIndexFactor*i]/range.lower)/qLn(range.upper/range.lower)*(mLevelCount-1);
+ if (index < 0)
+ index = 0;
+ else if (index >= mLevelCount)
+ index = mLevelCount-1;
+ if (alpha[dataIndexFactor*i] == 255)
+ {
+ scanLine[i] = mColorBuffer.at(index);
+ } else
+ {
+ const QRgb rgb = mColorBuffer.at(index);
+ const float alphaF = alpha[dataIndexFactor*i]/255.0f;
+ scanLine[i] = qRgba(qRed(rgb)*alphaF, qGreen(rgb)*alphaF, qBlue(rgb)*alphaF, qAlpha(rgb)*alphaF);
+ }
+ }
+ }
+ }
+}
+
+/*! \internal
+
This method is used to colorize a single data value given in \a position, to colors. The data
range that shall be used for mapping the data value to the gradient is passed in \a range. \a
logarithmic indicates whether the data value shall be mapped to a color logarithmically.
-
+
If an entire array of data values shall be converted, rather use \ref colorize, for better
performance.
+
+ The returned QRgb has its r, g and b components premultiplied with alpha (see
+ QImage::Format_ARGB32_Premultiplied).
*/
QRgb QCPColorGradient::color(double position, const QCPRange &range, bool logarithmic)
{
@@ -11523,29 +15978,42 @@ QCPColorGradient QCPColorGradient::inverted() const
/*! \internal
+ Returns true if the color gradient uses transparency, i.e. if any of the configured color stops
+ has an alpha value below 255.
+*/
+bool QCPColorGradient::stopsUseAlpha() const
+{
+ for (QMap<double, QColor>::const_iterator it=mColorStops.constBegin(); it!=mColorStops.constEnd(); ++it)
+ {
+ if (it.value().alpha() < 255)
+ return true;
+ }
+ return false;
+}
+
+/*! \internal
+
Updates the internal color buffer which will be used by \ref colorize and \ref color, to quickly
convert positions to colors. This is where the interpolation between color stops is calculated.
*/
void QCPColorGradient::updateColorBuffer()
{
- // use const reference to mColorStops to enforce const method calls
- const QMap<double, QColor> &colorStopsConst = mColorStops;
-
if (mColorBuffer.size() != mLevelCount)
mColorBuffer.resize(mLevelCount);
if (mColorStops.size() > 1)
{
double indexToPosFactor = 1.0/(double)(mLevelCount-1);
+ const bool useAlpha = stopsUseAlpha();
for (int i=0; i<mLevelCount; ++i)
{
double position = i*indexToPosFactor;
- QMap<double, QColor>::const_iterator it = colorStopsConst.lowerBound(position);
- if (it == colorStopsConst.constEnd()) // position is on or after last stop, use color of last stop
+ QMap<double, QColor>::const_iterator it = mColorStops.lowerBound(position);
+ if (it == mColorStops.constEnd()) // position is on or after last stop, use color of last stop
{
- mColorBuffer[i] = (it-1).value().rgb();
- } else if (it == colorStopsConst.constBegin()) // position is on or before first stop, use color of first stop
+ mColorBuffer[i] = (it-1).value().rgba();
+ } else if (it == mColorStops.constBegin()) // position is on or before first stop, use color of first stop
{
- mColorBuffer[i] = it.value().rgb();
+ mColorBuffer[i] = it.value().rgba();
} else // position is in between stops (or on an intermediate stop), interpolate color
{
QMap<double, QColor>::const_iterator high = it;
@@ -11555,9 +16023,20 @@ void QCPColorGradient::updateColorBuffer()
{
case ciRGB:
{
- mColorBuffer[i] = qRgb((1-t)*low.value().red() + t*high.value().red(),
- (1-t)*low.value().green() + t*high.value().green(),
- (1-t)*low.value().blue() + t*high.value().blue());
+ if (useAlpha)
+ {
+ const int alpha = (1-t)*low.value().alpha() + t*high.value().alpha();
+ const float alphaPremultiplier = alpha/255.0f; // since we use QImage::Format_ARGB32_Premultiplied
+ mColorBuffer[i] = qRgba(((1-t)*low.value().red() + t*high.value().red())*alphaPremultiplier,
+ ((1-t)*low.value().green() + t*high.value().green())*alphaPremultiplier,
+ ((1-t)*low.value().blue() + t*high.value().blue())*alphaPremultiplier,
+ alpha);
+ } else
+ {
+ mColorBuffer[i] = qRgb(((1-t)*low.value().red() + t*high.value().red()),
+ ((1-t)*low.value().green() + t*high.value().green()),
+ ((1-t)*low.value().blue() + t*high.value().blue()));
+ }
break;
}
case ciHSV:
@@ -11574,21 +16053,327 @@ void QCPColorGradient::updateColorBuffer()
hue = lowHsv.hueF() + t*hueDiff;
if (hue < 0) hue += 1.0;
else if (hue >= 1.0) hue -= 1.0;
- mColorBuffer[i] = QColor::fromHsvF(hue, (1-t)*lowHsv.saturationF() + t*highHsv.saturationF(), (1-t)*lowHsv.valueF() + t*highHsv.valueF()).rgb();
+ if (useAlpha)
+ {
+ const QRgb rgb = QColor::fromHsvF(hue,
+ (1-t)*lowHsv.saturationF() + t*highHsv.saturationF(),
+ (1-t)*lowHsv.valueF() + t*highHsv.valueF()).rgb();
+ const float alpha = (1-t)*lowHsv.alphaF() + t*highHsv.alphaF();
+ mColorBuffer[i] = qRgba(qRed(rgb)*alpha, qGreen(rgb)*alpha, qBlue(rgb)*alpha, 255*alpha);
+ }
+ else
+ {
+ mColorBuffer[i] = QColor::fromHsvF(hue,
+ (1-t)*lowHsv.saturationF() + t*highHsv.saturationF(),
+ (1-t)*lowHsv.valueF() + t*highHsv.valueF()).rgb();
+ }
break;
}
}
}
}
- } else if (colorStopsConst.size() == 1)
+ } else if (mColorStops.size() == 1)
{
- mColorBuffer.fill(colorStopsConst.constBegin().value().rgb());
+ const QRgb rgb = mColorStops.constBegin().value().rgb();
+ const float alpha = mColorStops.constBegin().value().alphaF();
+ mColorBuffer.fill(qRgba(qRed(rgb)*alpha, qGreen(rgb)*alpha, qBlue(rgb)*alpha, 255*alpha));
} else // mColorStops is empty, fill color buffer with black
{
mColorBuffer.fill(qRgb(0, 0, 0));
}
mColorBufferInvalidated = false;
}
+/* end of 'src/colorgradient.cpp' */
+
+
+/* including file 'src/selectiondecorator-bracket.cpp', size 12313 */
+/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
+
+////////////////////////////////////////////////////////////////////////////////////////////////////
+//////////////////// QCPSelectionDecoratorBracket
+////////////////////////////////////////////////////////////////////////////////////////////////////
+
+/*! \class QCPSelectionDecoratorBracket
+ \brief A selection decorator which draws brackets around each selected data segment
+
+ Additionally to the regular highlighting of selected segments via color, fill and scatter style,
+ this \ref QCPSelectionDecorator subclass draws markers at the begin and end of each selected data
+ segment of the plottable.
+
+ The shape of the markers can be controlled with \ref setBracketStyle, \ref setBracketWidth and
+ \ref setBracketHeight. The color/fill can be controlled with \ref setBracketPen and \ref
+ setBracketBrush.
+
+ To introduce custom bracket styles, it is only necessary to sublcass \ref
+ QCPSelectionDecoratorBracket and reimplement \ref drawBracket. The rest will be managed by the
+ base class.
+*/
+
+/*!
+ Creates a new QCPSelectionDecoratorBracket instance with default values.
+*/
+QCPSelectionDecoratorBracket::QCPSelectionDecoratorBracket() :
+ mBracketPen(QPen(Qt::black)),
+ mBracketBrush(Qt::NoBrush),
+ mBracketWidth(5),
+ mBracketHeight(50),
+ mBracketStyle(bsSquareBracket),
+ mTangentToData(false),
+ mTangentAverage(2)
+{
+
+}
+
+QCPSelectionDecoratorBracket::~QCPSelectionDecoratorBracket()
+{
+}
+
+/*!
+ Sets the pen that will be used to draw the brackets at the beginning and end of each selected
+ data segment.
+*/
+void QCPSelectionDecoratorBracket::setBracketPen(const QPen &pen)
+{
+ mBracketPen = pen;
+}
+
+/*!
+ Sets the brush that will be used to draw the brackets at the beginning and end of each selected
+ data segment.
+*/
+void QCPSelectionDecoratorBracket::setBracketBrush(const QBrush &brush)
+{
+ mBracketBrush = brush;
+}
+
+/*!
+ Sets the width of the drawn bracket. The width dimension is always parallel to the key axis of
+ the data, or the tangent direction of the current data slope, if \ref setTangentToData is
+ enabled.
+*/
+void QCPSelectionDecoratorBracket::setBracketWidth(int width)
+{
+ mBracketWidth = width;
+}
+
+/*!
+ Sets the height of the drawn bracket. The height dimension is always perpendicular to the key axis
+ of the data, or the tangent direction of the current data slope, if \ref setTangentToData is
+ enabled.
+*/
+void QCPSelectionDecoratorBracket::setBracketHeight(int height)
+{
+ mBracketHeight = height;
+}
+
+/*!
+ Sets the shape that the bracket/marker will have.
+
+ \see setBracketWidth, setBracketHeight
+*/
+void QCPSelectionDecoratorBracket::setBracketStyle(QCPSelectionDecoratorBracket::BracketStyle style)
+{
+ mBracketStyle = style;
+}
+
+/*!
+ Sets whether the brackets will be rotated such that they align with the slope of the data at the
+ position that they appear in.
+
+ For noisy data, it might be more visually appealing to average the slope over multiple data
+ points. This can be configured via \ref setTangentAverage.
+*/
+void QCPSelectionDecoratorBracket::setTangentToData(bool enabled)
+{
+ mTangentToData = enabled;
+}
+
+/*!
+ Controls over how many data points the slope shall be averaged, when brackets shall be aligned
+ with the data (if \ref setTangentToData is true).
+
+ From the position of the bracket, \a pointCount points towards the selected data range will be
+ taken into account. The smallest value of \a pointCount is 1, which is effectively equivalent to
+ disabling \ref setTangentToData.
+*/
+void QCPSelectionDecoratorBracket::setTangentAverage(int pointCount)
+{
+ mTangentAverage = pointCount;
+ if (mTangentAverage < 1)
+ mTangentAverage = 1;
+}
+
+/*!
+ Draws the bracket shape with \a painter. The parameter \a direction is either -1 or 1 and
+ indicates whether the bracket shall point to the left or the right (i.e. is a closing or opening
+ bracket, respectively).
+
+ The passed \a painter already contains all transformations that are necessary to position and
+ rotate the bracket appropriately. Painting operations can be performed as if drawing upright
+ brackets on flat data with horizontal key axis, with (0, 0) being the center of the bracket.
+
+ If you wish to sublcass \ref QCPSelectionDecoratorBracket in order to provide custom bracket
+ shapes (see \ref QCPSelectionDecoratorBracket::bsUserStyle), this is the method you should
+ reimplement.
+*/
+void QCPSelectionDecoratorBracket::drawBracket(QCPPainter *painter, int direction) const
+{
+ switch (mBracketStyle)
+ {
+ case bsSquareBracket:
+ {
+ painter->drawLine(QLineF(mBracketWidth*direction, -mBracketHeight*0.5, 0, -mBracketHeight*0.5));
+ painter->drawLine(QLineF(mBracketWidth*direction, mBracketHeight*0.5, 0, mBracketHeight*0.5));
+ painter->drawLine(QLineF(0, -mBracketHeight*0.5, 0, mBracketHeight*0.5));
+ break;
+ }
+ case bsHalfEllipse:
+ {
+ painter->drawArc(-mBracketWidth*0.5, -mBracketHeight*0.5, mBracketWidth, mBracketHeight, -90*16, -180*16*direction);
+ break;
+ }
+ case bsEllipse:
+ {
+ painter->drawEllipse(-mBracketWidth*0.5, -mBracketHeight*0.5, mBracketWidth, mBracketHeight);
+ break;
+ }
+ case bsPlus:
+ {
+ painter->drawLine(QLineF(0, -mBracketHeight*0.5, 0, mBracketHeight*0.5));
+ painter->drawLine(QLineF(-mBracketWidth*0.5, 0, mBracketWidth*0.5, 0));
+ break;
+ }
+ default:
+ {
+ qDebug() << Q_FUNC_INFO << "unknown/custom bracket style can't be handeld by default implementation:" << static_cast<int>(mBracketStyle);
+ break;
+ }
+ }
+}
+
+/*!
+ Draws the bracket decoration on the data points at the begin and end of each selected data
+ segment given in \a seletion.
+
+ It uses the method \ref drawBracket to actually draw the shapes.
+
+ \seebaseclassmethod
+*/
+void QCPSelectionDecoratorBracket::drawDecoration(QCPPainter *painter, QCPDataSelection selection)
+{
+ if (!mPlottable || selection.isEmpty()) return;
+
+ if (QCPPlottableInterface1D *interface1d = mPlottable->interface1D())
+ {
+ foreach (const QCPDataRange &dataRange, selection.dataRanges())
+ {
+ // determine position and (if tangent mode is enabled) angle of brackets:
+ int openBracketDir = (mPlottable->keyAxis() && !mPlottable->keyAxis()->rangeReversed()) ? 1 : -1;
+ int closeBracketDir = -openBracketDir;
+ QPointF openBracketPos = getPixelCoordinates(interface1d, dataRange.begin());
+ QPointF closeBracketPos = getPixelCoordinates(interface1d, dataRange.end()-1);
+ double openBracketAngle = 0;
+ double closeBracketAngle = 0;
+ if (mTangentToData)
+ {
+ openBracketAngle = getTangentAngle(interface1d, dataRange.begin(), openBracketDir);
+ closeBracketAngle = getTangentAngle(interface1d, dataRange.end()-1, closeBracketDir);
+ }
+ // draw opening bracket:
+ QTransform oldTransform = painter->transform();
+ painter->setPen(mBracketPen);
+ painter->setBrush(mBracketBrush);
+ painter->translate(openBracketPos);
+ painter->rotate(openBracketAngle/M_PI*180.0);
+ drawBracket(painter, openBracketDir);
+ painter->setTransform(oldTransform);
+ // draw closing bracket:
+ painter->setPen(mBracketPen);
+ painter->setBrush(mBracketBrush);
+ painter->translate(closeBracketPos);
+ painter->rotate(closeBracketAngle/M_PI*180.0);
+ drawBracket(painter, closeBracketDir);
+ painter->setTransform(oldTransform);
+ }
+ }
+}
+
+/*! \internal
+
+ If \ref setTangentToData is enabled, brackets need to be rotated according to the data slope.
+ This method returns the angle in radians by which a bracket at the given \a dataIndex must be
+ rotated.
+
+ The parameter \a direction must be set to either -1 or 1, representing whether it is an opening
+ or closing bracket. Since for slope calculation multiple data points are required, this defines
+ the direction in which the algorithm walks, starting at \a dataIndex, to average those data
+ points. (see \ref setTangentToData and \ref setTangentAverage)
+
+ \a interface1d is the interface to the plottable's data which is used to query data coordinates.
+*/
+double QCPSelectionDecoratorBracket::getTangentAngle(const QCPPlottableInterface1D *interface1d, int dataIndex, int direction) const
+{
+ if (!interface1d || dataIndex < 0 || dataIndex >= interface1d->dataCount())
+ return 0;
+ direction = direction < 0 ? -1 : 1; // enforce direction is either -1 or 1
+
+ // how many steps we can actually go from index in the given direction without exceeding data bounds:
+ int averageCount;
+ if (direction < 0)
+ averageCount = qMin(mTangentAverage, dataIndex);
+ else
+ averageCount = qMin(mTangentAverage, interface1d->dataCount()-1-dataIndex);
+ qDebug() << averageCount;
+ // calculate point average of averageCount points:
+ QVector<QPointF> points(averageCount);
+ QPointF pointsAverage;
+ int currentIndex = dataIndex;
+ for (int i=0; i<averageCount; ++i)
+ {
+ points[i] = getPixelCoordinates(interface1d, currentIndex);
+ pointsAverage += points[i];
+ currentIndex += direction;
+ }
+ pointsAverage /= (double)averageCount;
+
+ // calculate slope of linear regression through points:
+ double numSum = 0;
+ double denomSum = 0;
+ for (int i=0; i<averageCount; ++i)
+ {
+ const double dx = points.at(i).x()-pointsAverage.x();
+ const double dy = points.at(i).y()-pointsAverage.y();
+ numSum += dx*dy;
+ denomSum += dx*dx;
+ }
+ if (!qFuzzyIsNull(denomSum) && !qFuzzyIsNull(numSum))
+ {
+ return qAtan2(numSum, denomSum);
+ } else // undetermined angle, probably mTangentAverage == 1, so using only one data point
+ return 0;
+}
+
+/*! \internal
+
+ Returns the pixel coordinates of the data point at \a dataIndex, using \a interface1d to access
+ the data points.
+*/
+QPointF QCPSelectionDecoratorBracket::getPixelCoordinates(const QCPPlottableInterface1D *interface1d, int dataIndex) const
+{
+ QCPAxis *keyAxis = mPlottable->keyAxis();
+ QCPAxis *valueAxis = mPlottable->valueAxis();
+ if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPointF(0, 0); }
+
+ if (keyAxis->orientation() == Qt::Horizontal)
+ return QPointF(keyAxis->coordToPixel(interface1d->dataMainKey(dataIndex)), valueAxis->coordToPixel(interface1d->dataMainValue(dataIndex)));
+ else
+ return QPointF(valueAxis->coordToPixel(interface1d->dataMainValue(dataIndex)), keyAxis->coordToPixel(interface1d->dataMainKey(dataIndex)));
+}
+/* end of 'src/selectiondecorator-bracket.cpp' */
+
+
+/* including file 'src/layoutelements/layoutelement-axisrect.cpp', size 47509 */
+/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
////////////////////////////////////////////////////////////////////////////////////////////////////
@@ -11842,21 +16627,22 @@ QList<QCPAxis*> QCPAxisRect::axes() const
/*!
Adds a new axis to the axis rect side specified with \a type, and returns it. If \a axis is 0, a
- new QCPAxis instance is created internally.
+ new QCPAxis instance is created internally. QCustomPlot owns the returned axis, so if you want to
+ remove an axis, use \ref removeAxis instead of deleting it manually.
You may inject QCPAxis instances (or sublasses of QCPAxis) by setting \a axis to an axis that was
previously created outside QCustomPlot. It is important to note that QCustomPlot takes ownership
of the axis, so you may not delete it afterwards. Further, the \a axis must have been created
with this axis rect as parent and with the same axis type as specified in \a type. If this is not
the case, a debug output is generated, the axis is not added, and the method returns 0.
-
+
This method can not be used to move \a axis between axis rects. The same \a axis instance must
not be added multiple times to the same or different axis rects.
-
+
If an axis rect side already contains one or more axes, the lower and upper endings of the new
axis (\ref QCPAxis::setLowerEnding, \ref QCPAxis::setUpperEnding) are set to \ref
QCPLineEnding::esHalfBar.
-
+
\see addAxes, setupFullAxesBox
*/
QCPAxis *QCPAxisRect::addAxis(QCPAxis::AxisType type, QCPAxis *axis)
@@ -11890,6 +16676,19 @@ QCPAxis *QCPAxisRect::addAxis(QCPAxis::AxisType type, QCPAxis *axis)
newAxis->setUpperEnding(QCPLineEnding(QCPLineEnding::esHalfBar, 6, 10, invert));
}
mAxes[type].append(newAxis);
+
+ // reset convenience axis pointers on parent QCustomPlot if they are unset:
+ if (mParentPlot && mParentPlot->axisRectCount() > 0 && mParentPlot->axisRect(0) == this)
+ {
+ switch (type)
+ {
+ case QCPAxis::atBottom: { if (!mParentPlot->xAxis) mParentPlot->xAxis = newAxis; break; }
+ case QCPAxis::atLeft: { if (!mParentPlot->yAxis) mParentPlot->yAxis = newAxis; break; }
+ case QCPAxis::atTop: { if (!mParentPlot->xAxis2) mParentPlot->xAxis2 = newAxis; break; }
+ case QCPAxis::atRight: { if (!mParentPlot->yAxis2) mParentPlot->yAxis2 = newAxis; break; }
+ }
+ }
+
return newAxis;
}
@@ -11943,27 +16742,59 @@ bool QCPAxisRect::removeAxis(QCPAxis *axis)
}
/*!
+ Zooms in (or out) to the passed rectangular region \a pixelRect, given in pixel coordinates.
+
+ All axes of this axis rect will have their range zoomed accordingly. If you only wish to zoom
+ specific axes, use the overloaded version of this method.
+
+ \see QCustomPlot::setSelectionRectMode
+*/
+void QCPAxisRect::zoom(const QRectF &pixelRect)
+{
+ zoom(pixelRect, axes());
+}
+
+/*! \overload
+
+ Zooms in (or out) to the passed rectangular region \a pixelRect, given in pixel coordinates.
+
+ Only the axes passed in \a affectedAxes will have their ranges zoomed accordingly.
+
+ \see QCustomPlot::setSelectionRectMode
+*/
+void QCPAxisRect::zoom(const QRectF &pixelRect, const QList<QCPAxis*> &affectedAxes)
+{
+ foreach (QCPAxis *axis, affectedAxes)
+ {
+ if (!axis)
+ {
+ qDebug() << Q_FUNC_INFO << "a passed axis was zero";
+ continue;
+ }
+ QCPRange pixelRange;
+ if (axis->orientation() == Qt::Horizontal)
+ pixelRange = QCPRange(pixelRect.left(), pixelRect.right());
+ else
+ pixelRange = QCPRange(pixelRect.top(), pixelRect.bottom());
+ axis->setRange(axis->pixelToCoord(pixelRange.lower), axis->pixelToCoord(pixelRange.upper));
+ }
+}
+
+/*!
Convenience function to create an axis on each side that doesn't have any axes yet and set their
visibility to true. Further, the top/right axes are assigned the following properties of the
bottom/left axes:
-
+
\li range (\ref QCPAxis::setRange)
\li range reversed (\ref QCPAxis::setRangeReversed)
\li scale type (\ref QCPAxis::setScaleType)
- \li scale log base (\ref QCPAxis::setScaleLogBase)
- \li ticks (\ref QCPAxis::setTicks)
- \li auto (major) tick count (\ref QCPAxis::setAutoTickCount)
- \li sub tick count (\ref QCPAxis::setSubTickCount)
- \li auto sub ticks (\ref QCPAxis::setAutoSubTicks)
- \li tick step (\ref QCPAxis::setTickStep)
- \li auto tick step (\ref QCPAxis::setAutoTickStep)
+ \li tick visibility (\ref QCPAxis::setTicks)
\li number format (\ref QCPAxis::setNumberFormat)
\li number precision (\ref QCPAxis::setNumberPrecision)
- \li tick label type (\ref QCPAxis::setTickLabelType)
- \li date time format (\ref QCPAxis::setDateTimeFormat)
- \li date time spec (\ref QCPAxis::setDateTimeSpec)
-
- Tick labels (\ref QCPAxis::setTickLabels) of the right and top axes are set to false.
+ \li tick count of ticker (\ref QCPAxisTicker::setTickCount)
+ \li tick origin of ticker (\ref QCPAxisTicker::setTickOrigin)
+
+ Tick label visibility (\ref QCPAxis::setTickLabels) of the right and top axes are set to false.
If \a connectRanges is true, the \ref QCPAxis::rangeChanged "rangeChanged" signals of the bottom
and left axes are connected to the \ref QCPAxis::setRange slots of the top and right axes.
@@ -12001,34 +16832,20 @@ void QCPAxisRect::setupFullAxesBox(bool connectRanges)
xAxis2->setRange(xAxis->range());
xAxis2->setRangeReversed(xAxis->rangeReversed());
xAxis2->setScaleType(xAxis->scaleType());
- xAxis2->setScaleLogBase(xAxis->scaleLogBase());
xAxis2->setTicks(xAxis->ticks());
- xAxis2->setAutoTickCount(xAxis->autoTickCount());
- xAxis2->setSubTickCount(xAxis->subTickCount());
- xAxis2->setAutoSubTicks(xAxis->autoSubTicks());
- xAxis2->setTickStep(xAxis->tickStep());
- xAxis2->setAutoTickStep(xAxis->autoTickStep());
xAxis2->setNumberFormat(xAxis->numberFormat());
xAxis2->setNumberPrecision(xAxis->numberPrecision());
- xAxis2->setTickLabelType(xAxis->tickLabelType());
- xAxis2->setDateTimeFormat(xAxis->dateTimeFormat());
- xAxis2->setDateTimeSpec(xAxis->dateTimeSpec());
-
+ xAxis2->ticker()->setTickCount(xAxis->ticker()->tickCount());
+ xAxis2->ticker()->setTickOrigin(xAxis->ticker()->tickOrigin());
+
yAxis2->setRange(yAxis->range());
yAxis2->setRangeReversed(yAxis->rangeReversed());
yAxis2->setScaleType(yAxis->scaleType());
- yAxis2->setScaleLogBase(yAxis->scaleLogBase());
yAxis2->setTicks(yAxis->ticks());
- yAxis2->setAutoTickCount(yAxis->autoTickCount());
- yAxis2->setSubTickCount(yAxis->subTickCount());
- yAxis2->setAutoSubTicks(yAxis->autoSubTicks());
- yAxis2->setTickStep(yAxis->tickStep());
- yAxis2->setAutoTickStep(yAxis->autoTickStep());
yAxis2->setNumberFormat(yAxis->numberFormat());
yAxis2->setNumberPrecision(yAxis->numberPrecision());
- yAxis2->setTickLabelType(yAxis->tickLabelType());
- yAxis2->setDateTimeFormat(yAxis->dateTimeFormat());
- yAxis2->setDateTimeSpec(yAxis->dateTimeSpec());
+ yAxis2->ticker()->setTickCount(yAxis->ticker()->tickCount());
+ yAxis2->ticker()->setTickOrigin(yAxis->ticker()->tickOrigin());
if (connectRanges)
{
@@ -12051,7 +16868,7 @@ QList<QCPAbstractPlottable*> QCPAxisRect::plottables() const
QList<QCPAbstractPlottable*> result;
for (int i=0; i<mParentPlot->mPlottables.size(); ++i)
{
- if (mParentPlot->mPlottables.at(i)->keyAxis()->axisRect() == this ||mParentPlot->mPlottables.at(i)->valueAxis()->axisRect() == this)
+ if (mParentPlot->mPlottables.at(i)->keyAxis()->axisRect() == this || mParentPlot->mPlottables.at(i)->valueAxis()->axisRect() == this)
result.append(mParentPlot->mPlottables.at(i));
}
return result;
@@ -12121,6 +16938,8 @@ QList<QCPAbstractItem *> QCPAxisRect::items() const
Calls the base class implementation to update the margins (see \ref QCPLayoutElement::update),
and finally passes the \ref rect to the inset layout (\ref insetLayout) and calls its
QCPInsetLayout::update function.
+
+ \seebaseclassmethod
*/
void QCPAxisRect::update(UpdatePhase phase)
{
@@ -12252,23 +17071,83 @@ void QCPAxisRect::setBackgroundScaledMode(Qt::AspectRatioMode mode)
}
/*!
- Returns the range drag axis of the \a orientation provided.
-
+ Returns the range drag axis of the \a orientation provided. If multiple axes were set, returns
+ the first one (use \ref rangeDragAxes to retrieve a list with all set axes).
+
\see setRangeDragAxes
*/
QCPAxis *QCPAxisRect::rangeDragAxis(Qt::Orientation orientation)
{
- return (orientation == Qt::Horizontal ? mRangeDragHorzAxis.data() : mRangeDragVertAxis.data());
+ if (orientation == Qt::Horizontal)
+ return mRangeDragHorzAxis.isEmpty() ? 0 : mRangeDragHorzAxis.first().data();
+ else
+ return mRangeDragVertAxis.isEmpty() ? 0 : mRangeDragVertAxis.first().data();
}
/*!
- Returns the range zoom axis of the \a orientation provided.
-
+ Returns the range zoom axis of the \a orientation provided. If multiple axes were set, returns
+ the first one (use \ref rangeZoomAxes to retrieve a list with all set axes).
+
\see setRangeZoomAxes
*/
QCPAxis *QCPAxisRect::rangeZoomAxis(Qt::Orientation orientation)
{
- return (orientation == Qt::Horizontal ? mRangeZoomHorzAxis.data() : mRangeZoomVertAxis.data());
+ if (orientation == Qt::Horizontal)
+ return mRangeZoomHorzAxis.isEmpty() ? 0 : mRangeZoomHorzAxis.first().data();
+ else
+ return mRangeZoomVertAxis.isEmpty() ? 0 : mRangeZoomVertAxis.first().data();
+}
+
+/*!
+ Returns all range drag axes of the \a orientation provided.
+
+ \see rangeZoomAxis, setRangeZoomAxes
+*/
+QList<QCPAxis*> QCPAxisRect::rangeDragAxes(Qt::Orientation orientation)
+{
+ QList<QCPAxis*> result;
+ if (orientation == Qt::Horizontal)
+ {
+ for (int i=0; i<mRangeDragHorzAxis.size(); ++i)
+ {
+ if (!mRangeDragHorzAxis.at(i).isNull())
+ result.append(mRangeDragHorzAxis.at(i).data());
+ }
+ } else
+ {
+ for (int i=0; i<mRangeDragVertAxis.size(); ++i)
+ {
+ if (!mRangeDragVertAxis.at(i).isNull())
+ result.append(mRangeDragVertAxis.at(i).data());
+ }
+ }
+ return result;
+}
+
+/*!
+ Returns all range zoom axes of the \a orientation provided.
+
+ \see rangeDragAxis, setRangeDragAxes
+*/
+QList<QCPAxis*> QCPAxisRect::rangeZoomAxes(Qt::Orientation orientation)
+{
+ QList<QCPAxis*> result;
+ if (orientation == Qt::Horizontal)
+ {
+ for (int i=0; i<mRangeZoomHorzAxis.size(); ++i)
+ {
+ if (!mRangeZoomHorzAxis.at(i).isNull())
+ result.append(mRangeZoomHorzAxis.at(i).data());
+ }
+ } else
+ {
+ for (int i=0; i<mRangeZoomVertAxis.size(); ++i)
+ {
+ if (!mRangeZoomVertAxis.at(i).isNull())
+ result.append(mRangeZoomVertAxis.at(i).data());
+ }
+ }
+ return result;
}
/*!
@@ -12322,29 +17201,146 @@ void QCPAxisRect::setRangeZoom(Qt::Orientations orientations)
mRangeZoom = orientations;
}
-/*!
- Sets the axes whose range will be dragged when \ref setRangeDrag enables mouse range dragging
- on the QCustomPlot widget.
+/*! \overload
+ Sets the axes whose range will be dragged when \ref setRangeDrag enables mouse range dragging on
+ the QCustomPlot widget. Pass 0 if no axis shall be dragged in the respective orientation.
+
+ Use the overload taking a list of axes, if multiple axes (more than one per orientation) shall
+ react to dragging interactions.
+
\see setRangeZoomAxes
*/
void QCPAxisRect::setRangeDragAxes(QCPAxis *horizontal, QCPAxis *vertical)
{
- mRangeDragHorzAxis = horizontal;
- mRangeDragVertAxis = vertical;
+ QList<QCPAxis*> horz, vert;
+ if (horizontal)
+ horz.append(horizontal);
+ if (vertical)
+ vert.append(vertical);
+ setRangeDragAxes(horz, vert);
+}
+
+/*! \overload
+
+ This method allows to set up multiple axes to react to horizontal and vertical dragging. The drag
+ orientation that the respective axis will react to is deduced from its orientation (\ref
+ QCPAxis::orientation).
+
+ In the unusual case that you wish to e.g. drag a vertically oriented axis with a horizontal drag
+ motion, use the overload taking two separate lists for horizontal and vertical dragging.
+*/
+void QCPAxisRect::setRangeDragAxes(QList<QCPAxis*> axes)
+{
+ QList<QCPAxis*> horz, vert;
+ foreach (QCPAxis *ax, axes)
+ {
+ if (ax->orientation() == Qt::Horizontal)
+ horz.append(ax);
+ else
+ vert.append(ax);
+ }
+ setRangeDragAxes(horz, vert);
+}
+
+/*! \overload
+
+ This method allows to set multiple axes up to react to horizontal and vertical dragging, and
+ define specifically which axis reacts to which drag orientation (irrespective of the axis
+ orientation).
+*/
+void QCPAxisRect::setRangeDragAxes(QList<QCPAxis*> horizontal, QList<QCPAxis*> vertical)
+{
+ mRangeDragHorzAxis.clear();
+ foreach (QCPAxis *ax, horizontal)
+ {
+ QPointer<QCPAxis> axPointer(ax);
+ if (!axPointer.isNull())
+ mRangeDragHorzAxis.append(axPointer);
+ else
+ qDebug() << Q_FUNC_INFO << "invalid axis passed in horizontal list:" << reinterpret_cast<quintptr>(ax);
+ }
+ mRangeDragVertAxis.clear();
+ foreach (QCPAxis *ax, vertical)
+ {
+ QPointer<QCPAxis> axPointer(ax);
+ if (!axPointer.isNull())
+ mRangeDragVertAxis.append(axPointer);
+ else
+ qDebug() << Q_FUNC_INFO << "invalid axis passed in vertical list:" << reinterpret_cast<quintptr>(ax);
+ }
}
/*!
- Sets the axes whose range will be zoomed when \ref setRangeZoom enables mouse wheel zooming on the
- QCustomPlot widget. The two axes can be zoomed with different strengths, when different factors
- are passed to \ref setRangeZoomFactor(double horizontalFactor, double verticalFactor).
-
+ Sets the axes whose range will be zoomed when \ref setRangeZoom enables mouse wheel zooming on
+ the QCustomPlot widget. Pass 0 if no axis shall be zoomed in the respective orientation.
+
+ The two axes can be zoomed with different strengths, when different factors are passed to \ref
+ setRangeZoomFactor(double horizontalFactor, double verticalFactor).
+
+ Use the overload taking a list of axes, if multiple axes (more than one per orientation) shall
+ react to zooming interactions.
+
\see setRangeDragAxes
*/
void QCPAxisRect::setRangeZoomAxes(QCPAxis *horizontal, QCPAxis *vertical)
{
- mRangeZoomHorzAxis = horizontal;
- mRangeZoomVertAxis = vertical;
+ QList<QCPAxis*> horz, vert;
+ if (horizontal)
+ horz.append(horizontal);
+ if (vertical)
+ vert.append(vertical);
+ setRangeZoomAxes(horz, vert);
+}
+
+/*! \overload
+
+ This method allows to set up multiple axes to react to horizontal and vertical range zooming. The
+ zoom orientation that the respective axis will react to is deduced from its orientation (\ref
+ QCPAxis::orientation).
+
+ In the unusual case that you wish to e.g. zoom a vertically oriented axis with a horizontal zoom
+ interaction, use the overload taking two separate lists for horizontal and vertical zooming.
+*/
+void QCPAxisRect::setRangeZoomAxes(QList<QCPAxis*> axes)
+{
+ QList<QCPAxis*> horz, vert;
+ foreach (QCPAxis *ax, axes)
+ {
+ if (ax->orientation() == Qt::Horizontal)
+ horz.append(ax);
+ else
+ vert.append(ax);
+ }
+ setRangeZoomAxes(horz, vert);
+}
+
+/*! \overload
+
+ This method allows to set multiple axes up to react to horizontal and vertical zooming, and
+ define specifically which axis reacts to which zoom orientation (irrespective of the axis
+ orientation).
+*/
+void QCPAxisRect::setRangeZoomAxes(QList<QCPAxis*> horizontal, QList<QCPAxis*> vertical)
+{
+ mRangeZoomHorzAxis.clear();
+ foreach (QCPAxis *ax, horizontal)
+ {
+ QPointer<QCPAxis> axPointer(ax);
+ if (!axPointer.isNull())
+ mRangeZoomHorzAxis.append(axPointer);
+ else
+ qDebug() << Q_FUNC_INFO << "invalid axis passed in horizontal list:" << reinterpret_cast<quintptr>(ax);
+ }
+ mRangeZoomVertAxis.clear();
+ foreach (QCPAxis *ax, vertical)
+ {
+ QPointer<QCPAxis> axPointer(ax);
+ if (!axPointer.isNull())
+ mRangeZoomVertAxis.append(axPointer);
+ else
+ qDebug() << Q_FUNC_INFO << "invalid axis passed in vertical list:" << reinterpret_cast<quintptr>(ax);
+ }
}
/*!
@@ -12386,7 +17382,7 @@ void QCPAxisRect::setRangeZoomFactor(double factor)
the axis rect with the provided \a painter. The scaled version is buffered in
mScaledBackgroundPixmap to prevent expensive rescaling at every redraw. It is only updated, when
the axis rect has changed in a way that requires a rescale of the background pixmap (this is
- dependant on the \ref setBackgroundScaledMode), or when a differend axis backgroud pixmap was
+ dependent on the \ref setBackgroundScaledMode), or when a differend axis background pixmap was
set.
\see setBackground, setBackgroundScaled, setBackgroundScaledMode
@@ -12463,6 +17459,31 @@ int QCPAxisRect::calculateAutoMargin(QCP::MarginSide side)
/*! \internal
+ Reacts to a change in layout to potentially set the convenience axis pointers \ref
+ QCustomPlot::xAxis, \ref QCustomPlot::yAxis, etc. of the parent QCustomPlot to the respective
+ axes of this axis rect. This is only done if the respective convenience pointer is currently zero
+ and if there is no QCPAxisRect at position (0, 0) of the plot layout.
+
+ This automation makes it simpler to replace the main axis rect with a newly created one, without
+ the need to manually reset the convenience pointers.
+*/
+void QCPAxisRect::layoutChanged()
+{
+ if (mParentPlot && mParentPlot->axisRectCount() > 0 && mParentPlot->axisRect(0) == this)
+ {
+ if (axisCount(QCPAxis::atBottom) > 0 && !mParentPlot->xAxis)
+ mParentPlot->xAxis = axis(QCPAxis::atBottom);
+ if (axisCount(QCPAxis::atLeft) > 0 && !mParentPlot->yAxis)
+ mParentPlot->yAxis = axis(QCPAxis::atLeft);
+ if (axisCount(QCPAxis::atTop) > 0 && !mParentPlot->xAxis2)
+ mParentPlot->xAxis2 = axis(QCPAxis::atTop);
+ if (axisCount(QCPAxis::atRight) > 0 && !mParentPlot->yAxis2)
+ mParentPlot->yAxis2 = axis(QCPAxis::atRight);
+ }
+}
+
+/*! \internal
+
Event handler for when a mouse button is pressed on the axis rect. If the left mouse button is
pressed, the range dragging interaction is initialized (the actual range manipulation happens in
the \ref mouseMoveEvent).
@@ -12472,8 +17493,9 @@ int QCPAxisRect::calculateAutoMargin(QCP::MarginSide side)
\see mouseMoveEvent, mouseReleaseEvent
*/
-void QCPAxisRect::mousePressEvent(QMouseEvent *event)
+void QCPAxisRect::mousePressEvent(QMouseEvent *event, const QVariant &details)
{
+ Q_UNUSED(details)
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)
if (event->buttons() & Qt::LeftButton)
{
@@ -12487,10 +17509,12 @@ void QCPAxisRect::mousePressEvent(QMouseEvent *event)
// Mouse range dragging interaction:
if (mParentPlot->interactions().testFlag(QCP::iRangeDrag))
{
- if (mRangeDragHorzAxis)
- mDragStartHorzRange = mRangeDragHorzAxis.data()->range();
- if (mRangeDragVertAxis)
- mDragStartVertRange = mRangeDragVertAxis.data()->range();
+ mDragStartHorzRange.clear();
+ for (int i=0; i<mRangeDragHorzAxis.size(); ++i)
+ mDragStartHorzRange.append(mRangeDragHorzAxis.at(i).isNull() ? QCPRange() : mRangeDragHorzAxis.at(i)->range());
+ mDragStartVertRange.clear();
+ for (int i=0; i<mRangeDragVertAxis.size(); ++i)
+ mDragStartVertRange.append(mRangeDragVertAxis.at(i).isNull() ? QCPRange() : mRangeDragVertAxis.at(i)->range());
}
}
}
@@ -12502,54 +17526,70 @@ void QCPAxisRect::mousePressEvent(QMouseEvent *event)
\see mousePressEvent, mouseReleaseEvent
*/
-void QCPAxisRect::mouseMoveEvent(QMouseEvent *event)
+void QCPAxisRect::mouseMoveEvent(QMouseEvent *event, const QPointF &startPos)
{
+ Q_UNUSED(startPos)
// Mouse range dragging interaction:
if (mDragging && mParentPlot->interactions().testFlag(QCP::iRangeDrag))
{
+
if (mRangeDrag.testFlag(Qt::Horizontal))
{
- if (QCPAxis *rangeDragHorzAxis = mRangeDragHorzAxis.data())
+ for (int i=0; i<mRangeDragHorzAxis.size(); ++i)
{
- if (rangeDragHorzAxis->mScaleType == QCPAxis::stLinear)
+ QCPAxis *ax = mRangeDragHorzAxis.at(i).data();
+ if (!ax)
+ continue;
+ if (i >= mDragStartHorzRange.size())
+ break;
+ if (ax->mScaleType == QCPAxis::stLinear)
{
- double diff = rangeDragHorzAxis->pixelToCoord(mDragStart.x()) - rangeDragHorzAxis->pixelToCoord(event->pos().x());
- rangeDragHorzAxis->setRange(mDragStartHorzRange.lower+diff, mDragStartHorzRange.upper+diff);
- } else if (rangeDragHorzAxis->mScaleType == QCPAxis::stLogarithmic)
+ double diff = ax->pixelToCoord(mDragStart.x()) - ax->pixelToCoord(event->pos().x());
+ ax->setRange(mDragStartHorzRange.at(i).lower+diff, mDragStartHorzRange.at(i).upper+diff);
+ } else if (ax->mScaleType == QCPAxis::stLogarithmic)
{
- double diff = rangeDragHorzAxis->pixelToCoord(mDragStart.x()) / rangeDragHorzAxis->pixelToCoord(event->pos().x());
- rangeDragHorzAxis->setRange(mDragStartHorzRange.lower*diff, mDragStartHorzRange.upper*diff);
+ double diff = ax->pixelToCoord(mDragStart.x()) / ax->pixelToCoord(event->pos().x());
+ ax->setRange(mDragStartHorzRange.at(i).lower*diff, mDragStartHorzRange.at(i).upper*diff);
}
}
}
+
if (mRangeDrag.testFlag(Qt::Vertical))
{
- if (QCPAxis *rangeDragVertAxis = mRangeDragVertAxis.data())
+ for (int i=0; i<mRangeDragVertAxis.size(); ++i)
{
- if (rangeDragVertAxis->mScaleType == QCPAxis::stLinear)
+ QCPAxis *ax = mRangeDragVertAxis.at(i).data();
+ if (!ax)
+ continue;
+ if (i >= mDragStartVertRange.size())
+ break;
+ if (ax->mScaleType == QCPAxis::stLinear)
{
- double diff = rangeDragVertAxis->pixelToCoord(mDragStart.y()) - rangeDragVertAxis->pixelToCoord(event->pos().y());
- rangeDragVertAxis->setRange(mDragStartVertRange.lower+diff, mDragStartVertRange.upper+diff);
- } else if (rangeDragVertAxis->mScaleType == QCPAxis::stLogarithmic)
+ double diff = ax->pixelToCoord(mDragStart.y()) - ax->pixelToCoord(event->pos().y());
+ ax->setRange(mDragStartVertRange.at(i).lower+diff, mDragStartVertRange.at(i).upper+diff);
+ } else if (ax->mScaleType == QCPAxis::stLogarithmic)
{
- double diff = rangeDragVertAxis->pixelToCoord(mDragStart.y()) / rangeDragVertAxis->pixelToCoord(event->pos().y());
- rangeDragVertAxis->setRange(mDragStartVertRange.lower*diff, mDragStartVertRange.upper*diff);
+ double diff = ax->pixelToCoord(mDragStart.y()) / ax->pixelToCoord(event->pos().y());
+ ax->setRange(mDragStartVertRange.at(i).lower*diff, mDragStartVertRange.at(i).upper*diff);
}
}
}
+
if (mRangeDrag != 0) // if either vertical or horizontal drag was enabled, do a replot
{
if (mParentPlot->noAntialiasingOnDrag())
mParentPlot->setNotAntialiasedElements(QCP::aeAll);
mParentPlot->replot();
}
+
}
}
/* inherits documentation from base class */
-void QCPAxisRect::mouseReleaseEvent(QMouseEvent *event)
+void QCPAxisRect::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos)
{
Q_UNUSED(event)
+ Q_UNUSED(startPos)
mDragging = false;
if (mParentPlot->noAntialiasingOnDrag())
{
@@ -12563,7 +17603,7 @@ void QCPAxisRect::mouseReleaseEvent(QMouseEvent *event)
Event handler for mouse wheel events. If rangeZoom is Qt::Horizontal, Qt::Vertical or both, the
ranges of the axes defined as rangeZoomHorzAxis and rangeZoomVertAxis are scaled. The center of
the scaling operation is the current cursor position inside the axis rect. The scaling factor is
- dependant on the mouse wheel delta (which direction the wheel was rotated) to provide a natural
+ dependent on the mouse wheel delta (which direction the wheel was rotated) to provide a natural
zooming feel. The Strength of the zoom can be controlled via \ref setRangeZoomFactor.
Note, that event->delta() is usually +/-120 for single rotation steps. However, if the mouse
@@ -12584,21 +17624,31 @@ void QCPAxisRect::wheelEvent(QWheelEvent *event)
if (mRangeZoom.testFlag(Qt::Horizontal))
{
factor = qPow(mRangeZoomFactorHorz, wheelSteps);
- if (mRangeZoomHorzAxis.data())
- mRangeZoomHorzAxis.data()->scaleRange(factor, mRangeZoomHorzAxis.data()->pixelToCoord(event->pos().x()));
+ for (int i=0; i<mRangeZoomHorzAxis.size(); ++i)
+ {
+ if (!mRangeZoomHorzAxis.at(i).isNull())
+ mRangeZoomHorzAxis.at(i)->scaleRange(factor, mRangeZoomHorzAxis.at(i)->pixelToCoord(event->pos().x()));
+ }
}
if (mRangeZoom.testFlag(Qt::Vertical))
{
factor = qPow(mRangeZoomFactorVert, wheelSteps);
- if (mRangeZoomVertAxis.data())
- mRangeZoomVertAxis.data()->scaleRange(factor, mRangeZoomVertAxis.data()->pixelToCoord(event->pos().y()));
+ for (int i=0; i<mRangeZoomVertAxis.size(); ++i)
+ {
+ if (!mRangeZoomVertAxis.at(i).isNull())
+ mRangeZoomVertAxis.at(i)->scaleRange(factor, mRangeZoomVertAxis.at(i)->pixelToCoord(event->pos().y()));
+ }
}
mParentPlot->replot();
}
}
}
+/* end of 'src/layoutelements/layoutelement-axisrect.cpp' */
+/* including file 'src/layoutelements/layoutelement-legend.cpp', size 30933 */
+/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
+
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// QCPAbstractLegendItem
////////////////////////////////////////////////////////////////////////////////////////////////////
@@ -12652,7 +17702,7 @@ QCPAbstractLegendItem::QCPAbstractLegendItem(QCPLegend *parent) :
mSelected(false)
{
setLayer(QLatin1String("legend"));
- setMargins(QMargins(8, 2, 8, 2));
+ setMargins(QMargins(0, 0, 0, 0));
}
/*!
@@ -12821,6 +17871,7 @@ QCPPlottableLegendItem::QCPPlottableLegendItem(QCPLegend *parent, QCPAbstractPlo
QCPAbstractLegendItem(parent),
mPlottable(plottable)
{
+ setAntialiased(false);
}
/*! \internal
@@ -12879,6 +17930,8 @@ void QCPPlottableLegendItem::draw(QCPPainter *painter)
{
painter->setPen(getIconBorderPen());
painter->setBrush(Qt::NoBrush);
+ int halfPen = qCeil(painter->pen().widthF()*0.5)+1;
+ painter->setClipRect(mOuterRect.adjusted(-halfPen, -halfPen, halfPen, halfPen)); // extend default clip rect so thicker pens (especially during selection) are not clipped
painter->drawRect(iconRect);
}
}
@@ -12887,6 +17940,8 @@ void QCPPlottableLegendItem::draw(QCPPainter *painter)
Calculates and returns the size of this item. This includes the icon, the text and the padding in
between.
+
+ \seebaseclassmethod
*/
QSize QCPPlottableLegendItem::minimumSizeHint() const
{
@@ -12910,24 +17965,30 @@ QSize QCPPlottableLegendItem::minimumSizeHint() const
\brief Manages a legend inside a QCustomPlot.
A legend is a small box somewhere in the plot which lists plottables with their name and icon.
-
+
Normally, the legend is populated by calling \ref QCPAbstractPlottable::addToLegend. The
respective legend item can be removed with \ref QCPAbstractPlottable::removeFromLegend. However,
QCPLegend also offers an interface to add and manipulate legend items directly: \ref item, \ref
itemWithPlottable, \ref itemCount, \ref addItem, \ref removeItem, etc.
-
- The QCPLegend derives from QCPLayoutGrid and as such can be placed in any position a
- QCPLayoutElement may be positioned. The legend items are themselves QCPLayoutElements which are
- placed in the grid layout of the legend. QCPLegend only adds an interface specialized for
- handling child elements of type QCPAbstractLegendItem, as mentioned above. In principle, any
- other layout elements may also be added to a legend via the normal \ref QCPLayoutGrid interface.
- However, the QCPAbstractLegendItem-Interface will ignore those elements (e.g. \ref itemCount will
- only return the number of items with QCPAbstractLegendItems type).
- By default, every QCustomPlot has one legend (QCustomPlot::legend) which is placed in the inset
- layout of the main axis rect (\ref QCPAxisRect::insetLayout). To move the legend to another
+ Since \ref QCPLegend derives from \ref QCPLayoutGrid, it can be placed in any position a \ref
+ QCPLayoutElement may be positioned. The legend items are themselves \ref QCPLayoutElement
+ "QCPLayoutElements" which are placed in the grid layout of the legend. \ref QCPLegend only adds
+ an interface specialized for handling child elements of type \ref QCPAbstractLegendItem, as
+ mentioned above. In principle, any other layout elements may also be added to a legend via the
+ normal \ref QCPLayoutGrid interface. See the special page about \link thelayoutsystem The Layout
+ System\endlink for examples on how to add other elements to the legend and move it outside the axis
+ rect.
+
+ Use the methods \ref setFillOrder and \ref setWrap inherited from \ref QCPLayoutGrid to control
+ in which order (column first or row first) the legend is filled up when calling \ref addItem, and
+ at which column or row wrapping occurs.
+
+ By default, every QCustomPlot has one legend (\ref QCustomPlot::legend) which is placed in the
+ inset layout of the main axis rect (\ref QCPAxisRect::insetLayout). To move the legend to another
position inside the axis rect, use the methods of the \ref QCPLayoutInset. To move the legend
- outside of the axis rect, place it anywhere else with the QCPLayout/QCPLayoutElement interface.
+ outside of the axis rect, place it anywhere else with the \ref QCPLayout/\ref QCPLayoutElement
+ interface.
*/
/* start of documentation of signals */
@@ -12942,16 +18003,19 @@ QSize QCPPlottableLegendItem::minimumSizeHint() const
/* end of documentation of signals */
/*!
- Constructs a new QCPLegend instance with \a parentPlot as the containing plot and default values.
+ Constructs a new QCPLegend instance with default values.
- Note that by default, QCustomPlot already contains a legend ready to be used as
+ Note that by default, QCustomPlot already contains a legend ready to be used as \ref
QCustomPlot::legend
*/
QCPLegend::QCPLegend()
{
- setRowSpacing(0);
- setColumnSpacing(10);
- setMargins(QMargins(2, 3, 2, 2));
+ setFillOrder(QCPLayoutGrid::foRowsFirst);
+ setWrap(0);
+
+ setRowSpacing(3);
+ setColumnSpacing(8);
+ setMargins(QMargins(7, 5, 7, 4));
setAntialiased(false);
setIconSize(32, 18);
@@ -12960,7 +18024,7 @@ QCPLegend::QCPLegend()
setSelectableParts(spLegendBox | spItems);
setSelectedParts(spNone);
- setBorderPen(QPen(Qt::black));
+ setBorderPen(QPen(Qt::black, 0));
setSelectedBorderPen(QPen(Qt::blue, 2));
setIconBorderPen(Qt::NoPen);
setSelectedIconBorderPen(QPen(Qt::blue, 2));
@@ -13221,8 +18285,10 @@ void QCPLegend::setSelectedTextColor(const QColor &color)
/*!
Returns the item with index \a i.
-
- \see itemCount
+
+ Note that the linear index depends on the current fill order (\ref setFillOrder).
+
+ \see itemCount, addItem, itemWithPlottable
*/
QCPAbstractLegendItem *QCPLegend::item(int index) const
{
@@ -13250,6 +18316,10 @@ QCPPlottableLegendItem *QCPLegend::itemWithPlottable(const QCPAbstractPlottable
/*!
Returns the number of items currently in the legend.
+
+ Note that if empty cells are in the legend (e.g. by calling methods of the \ref QCPLayoutGrid
+ base class which allows creating empty cells), they are included in the returned count.
+
\see item
*/
int QCPLegend::itemCount() const
@@ -13258,7 +18328,9 @@ int QCPLegend::itemCount() const
}
/*!
- Returns whether the legend contains \a itm.
+ Returns whether the legend contains \a item.
+
+ \see hasItemWithPlottable
*/
bool QCPLegend::hasItem(QCPAbstractLegendItem *item) const
{
@@ -13282,26 +18354,31 @@ bool QCPLegend::hasItemWithPlottable(const QCPAbstractPlottable *plottable) cons
}
/*!
- Adds \a item to the legend, if it's not present already.
-
- Returns true on success, i.e. if the item wasn't in the list already and has been successfuly added.
-
+ Adds \a item to the legend, if it's not present already. The element is arranged according to the
+ current fill order (\ref setFillOrder) and wrapping (\ref setWrap).
+
+ Returns true on sucess, i.e. if the item wasn't in the list already and has been successfuly added.
+
The legend takes ownership of the item.
+
+ \see removeItem, item, hasItem
*/
bool QCPLegend::addItem(QCPAbstractLegendItem *item)
{
- if (!hasItem(item))
- {
- return addElement(rowCount(), 0, item);
- } else
- return false;
+ return addElement(item);
}
-/*!
- Removes the item with index \a index from the legend.
+/*! \overload
+
+ Removes the item with the specified \a index from the legend and deletes it.
+
+ After successful removal, the legend is reordered according to the current fill order (\ref
+ setFillOrder) and wrapping (\ref setWrap), so no empty cell remains where the removed \a item
+ was. If you don't want this, rather use the raw element interface of \ref QCPLayoutGrid.
+
+ Returns true, if successful. Unlike \ref QCPLayoutGrid::removeAt, this method only removes
+ elements derived from \ref QCPAbstractLegendItem.
- Returns true, if successful.
-
\see itemCount, clearItems
*/
bool QCPLegend::removeItem(int index)
@@ -13309,24 +18386,30 @@ bool QCPLegend::removeItem(int index)
if (QCPAbstractLegendItem *ali = item(index))
{
bool success = remove(ali);
- simplify();
+ if (success)
+ setFillOrder(fillOrder(), true); // gets rid of empty cell by reordering
return success;
} else
return false;
}
/*! \overload
-
- Removes \a item from the legend.
+
+ Removes \a item from the legend and deletes it.
+
+ After successful removal, the legend is reordered according to the current fill order (\ref
+ setFillOrder) and wrapping (\ref setWrap), so no empty cell remains where the removed \a item
+ was. If you don't want this, rather use the raw element interface of \ref QCPLayoutGrid.
Returns true, if successful.
-
+
\see clearItems
*/
bool QCPLegend::removeItem(QCPAbstractLegendItem *item)
{
bool success = remove(item);
- simplify();
+ if (success)
+ setFillOrder(fillOrder(), true); // gets rid of empty cell by reordering
return success;
}
@@ -13370,6 +18453,8 @@ QList<QCPAbstractLegendItem *> QCPLegend::selectedItems() const
overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
QCustomPlot::setNotAntialiasedElements.
+ \seebaseclassmethod
+
\see setAntialiased
*/
void QCPLegend::applyDefaultAntialiasingHint(QCPPainter *painter) const
@@ -13467,32 +18552,32 @@ QCP::Interaction QCPAbstractLegendItem::selectionCategory() const
/* inherits documentation from base class */
void QCPLegend::parentPlotInitialized(QCustomPlot *parentPlot)
{
- Q_UNUSED(parentPlot)
+ if (parentPlot && !parentPlot->legend)
+ parentPlot->legend = this;
}
+/* end of 'src/layoutelements/layoutelement-legend.cpp' */
+/* including file 'src/layoutelements/layoutelement-textelement.cpp', size 12759 */
+/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
+
////////////////////////////////////////////////////////////////////////////////////////////////////
-//////////////////// QCPPlotTitle
+//////////////////// QCPTextElement
////////////////////////////////////////////////////////////////////////////////////////////////////
-/*! \class QCPPlotTitle
- \brief A layout element displaying a plot title text
-
- The text may be specified with \ref setText, theformatting can be controlled with \ref setFont
- and \ref setTextColor.
-
- A plot title can be added as follows:
- \snippet documentation/doc-code-snippets/mainwindow.cpp qcpplottitle-creation
-
- Since a plot title is a common requirement, QCustomPlot offers specialized selection signals for
- easy interaction with QCPPlotTitle. If a layout element of type QCPPlotTitle is clicked, the
- signal \ref QCustomPlot::titleClick is emitted. A double click emits the \ref
- QCustomPlot::titleDoubleClick signal.
+/*! \class QCPTextElement
+ \brief A layout element displaying a text
+
+ The text may be specified with \ref setText, the formatting can be controlled with \ref setFont,
+ \ref setTextColor, and \ref setTextFlags.
+
+ A text element can be added as follows:
+ \snippet documentation/doc-code-snippets/mainwindow.cpp qcptextelement-creation
*/
/* start documentation of signals */
-/*! \fn void QCPPlotTitle::selectionChanged(bool selected)
+/*! \fn void QCPTextElement::selectionChanged(bool selected)
This signal is emitted when the selection state has changed to \a selected, either by user
interaction or by a direct call to \ref setSelected.
@@ -13500,106 +18585,220 @@ void QCPLegend::parentPlotInitialized(QCustomPlot *parentPlot)
\see setSelected, setSelectable
*/
+/*! \fn void QCPTextElement::clicked(QMouseEvent *event)
+
+ This signal is emitted when the text element is clicked.
+
+ \see doubleClicked, selectTest
+*/
+
+/*! \fn void QCPTextElement::doubleClicked(QMouseEvent *event)
+
+ This signal is emitted when the text element is double clicked.
+
+ \see clicked, selectTest
+*/
+
/* end documentation of signals */
-/*!
- Creates a new QCPPlotTitle instance and sets default values. The initial text is empty (\ref setText).
+/*! \overload
- To set the title text in the constructor, rather use \ref QCPPlotTitle(QCustomPlot *parentPlot, const QString &text).
+ Creates a new QCPTextElement instance and sets default values. The initial text is empty (\ref
+ setText).
*/
-QCPPlotTitle::QCPPlotTitle(QCustomPlot *parentPlot) :
+QCPTextElement::QCPTextElement(QCustomPlot *parentPlot) :
QCPLayoutElement(parentPlot),
- mFont(QFont(QLatin1String("sans serif"), 13*1.5, QFont::Bold)),
+ mText(),
+ mTextFlags(Qt::AlignCenter|Qt::TextWordWrap),
+ mFont(QFont(QLatin1String("sans serif"), 12)), // will be taken from parentPlot if available, see below
mTextColor(Qt::black),
- mSelectedFont(QFont(QLatin1String("sans serif"), 13*1.6, QFont::Bold)),
+ mSelectedFont(QFont(QLatin1String("sans serif"), 12)), // will be taken from parentPlot if available, see below
mSelectedTextColor(Qt::blue),
mSelectable(false),
mSelected(false)
{
if (parentPlot)
{
- setLayer(parentPlot->currentLayer());
- mFont = QFont(parentPlot->font().family(), parentPlot->font().pointSize()*1.5, QFont::Bold);
- mSelectedFont = QFont(parentPlot->font().family(), parentPlot->font().pointSize()*1.6, QFont::Bold);
+ mFont = parentPlot->font();
+ mSelectedFont = parentPlot->font();
}
- setMargins(QMargins(5, 5, 5, 0));
+ setMargins(QMargins(2, 2, 2, 2));
}
/*! \overload
- Creates a new QCPPlotTitle instance and sets default values. The initial text is set to \a text.
+ Creates a new QCPTextElement instance and sets default values.
+
+ The initial text is set to \a text.
*/
-QCPPlotTitle::QCPPlotTitle(QCustomPlot *parentPlot, const QString &text) :
+QCPTextElement::QCPTextElement(QCustomPlot *parentPlot, const QString &text) :
QCPLayoutElement(parentPlot),
mText(text),
- mFont(QFont(parentPlot->font().family(), parentPlot->font().pointSize()*1.5, QFont::Bold)),
+ mTextFlags(Qt::AlignCenter|Qt::TextWordWrap),
+ mFont(QFont(QLatin1String("sans serif"), 12)), // will be taken from parentPlot if available, see below
mTextColor(Qt::black),
- mSelectedFont(QFont(parentPlot->font().family(), parentPlot->font().pointSize()*1.6, QFont::Bold)),
+ mSelectedFont(QFont(QLatin1String("sans serif"), 12)), // will be taken from parentPlot if available, see below
mSelectedTextColor(Qt::blue),
mSelectable(false),
mSelected(false)
{
- setLayer(QLatin1String("axes"));
- setMargins(QMargins(5, 5, 5, 0));
+ if (parentPlot)
+ {
+ mFont = parentPlot->font();
+ mSelectedFont = parentPlot->font();
+ }
+ setMargins(QMargins(2, 2, 2, 2));
+}
+
+/*! \overload
+
+ Creates a new QCPTextElement instance and sets default values.
+
+ The initial text is set to \a text with \a pointSize.
+*/
+QCPTextElement::QCPTextElement(QCustomPlot *parentPlot, const QString &text, double pointSize) :
+ QCPLayoutElement(parentPlot),
+ mText(text),
+ mTextFlags(Qt::AlignCenter|Qt::TextWordWrap),
+ mFont(QFont(QLatin1String("sans serif"), pointSize)), // will be taken from parentPlot if available, see below
+ mTextColor(Qt::black),
+ mSelectedFont(QFont(QLatin1String("sans serif"), pointSize)), // will be taken from parentPlot if available, see below
+ mSelectedTextColor(Qt::blue),
+ mSelectable(false),
+ mSelected(false)
+{
+ if (parentPlot)
+ {
+ mFont = parentPlot->font();
+ mFont.setPointSizeF(pointSize);
+ mSelectedFont = parentPlot->font();
+ mSelectedFont.setPointSizeF(pointSize);
+ }
+ setMargins(QMargins(2, 2, 2, 2));
+}
+
+/*! \overload
+
+ Creates a new QCPTextElement instance and sets default values.
+
+ The initial text is set to \a text with \a pointSize and the specified \a fontFamily.
+*/
+QCPTextElement::QCPTextElement(QCustomPlot *parentPlot, const QString &text, const QString &fontFamily, double pointSize) :
+ QCPLayoutElement(parentPlot),
+ mText(text),
+ mTextFlags(Qt::AlignCenter|Qt::TextWordWrap),
+ mFont(QFont(fontFamily, pointSize)),
+ mTextColor(Qt::black),
+ mSelectedFont(QFont(fontFamily, pointSize)),
+ mSelectedTextColor(Qt::blue),
+ mSelectable(false),
+ mSelected(false)
+{
+ setMargins(QMargins(2, 2, 2, 2));
+}
+
+/*! \overload
+
+ Creates a new QCPTextElement instance and sets default values.
+
+ The initial text is set to \a text with the specified \a font.
+*/
+QCPTextElement::QCPTextElement(QCustomPlot *parentPlot, const QString &text, const QFont &font) :
+ QCPLayoutElement(parentPlot),
+ mText(text),
+ mTextFlags(Qt::AlignCenter|Qt::TextWordWrap),
+ mFont(font),
+ mTextColor(Qt::black),
+ mSelectedFont(font),
+ mSelectedTextColor(Qt::blue),
+ mSelectable(false),
+ mSelected(false)
+{
+ setMargins(QMargins(2, 2, 2, 2));
}
/*!
Sets the text that will be displayed to \a text. Multiple lines can be created by insertion of "\n".
- \see setFont, setTextColor
+ \see setFont, setTextColor, setTextFlags
*/
-void QCPPlotTitle::setText(const QString &text)
+void QCPTextElement::setText(const QString &text)
{
mText = text;
}
/*!
- Sets the \a font of the title text.
+ Sets options for text alignment and wrapping behaviour. \a flags is a bitwise OR-combination of
+ \c Qt::AlignmentFlag and \c Qt::TextFlag enums.
+
+ Possible enums are:
+ - Qt::AlignLeft
+ - Qt::AlignRight
+ - Qt::AlignHCenter
+ - Qt::AlignJustify
+ - Qt::AlignTop
+ - Qt::AlignBottom
+ - Qt::AlignVCenter
+ - Qt::AlignCenter
+ - Qt::TextDontClip
+ - Qt::TextSingleLine
+ - Qt::TextExpandTabs
+ - Qt::TextShowMnemonic
+ - Qt::TextWordWrap
+ - Qt::TextIncludeTrailingSpaces
+*/
+void QCPTextElement::setTextFlags(int flags)
+{
+ mTextFlags = flags;
+}
+
+/*!
+ Sets the \a font of the text.
\see setTextColor, setSelectedFont
*/
-void QCPPlotTitle::setFont(const QFont &font)
+void QCPTextElement::setFont(const QFont &font)
{
mFont = font;
}
/*!
- Sets the \a color of the title text.
+ Sets the \a color of the text.
\see setFont, setSelectedTextColor
*/
-void QCPPlotTitle::setTextColor(const QColor &color)
+void QCPTextElement::setTextColor(const QColor &color)
{
mTextColor = color;
}
/*!
- Sets the \a font of the title text that will be used if the plot title is selected (\ref setSelected).
+ Sets the \a font of the text that will be used if the text element is selected (\ref setSelected).
\see setFont
*/
-void QCPPlotTitle::setSelectedFont(const QFont &font)
+void QCPTextElement::setSelectedFont(const QFont &font)
{
mSelectedFont = font;
}
/*!
- Sets the \a color of the title text that will be used if the plot title is selected (\ref setSelected).
+ Sets the \a color of the text that will be used if the text element is selected (\ref setSelected).
\see setTextColor
*/
-void QCPPlotTitle::setSelectedTextColor(const QColor &color)
+void QCPTextElement::setSelectedTextColor(const QColor &color)
{
mSelectedTextColor = color;
}
/*!
- Sets whether the user may select this plot title to \a selectable.
+ Sets whether the user may select this text element.
Note that even when \a selectable is set to <tt>false</tt>, the selection state may be changed
programmatically via \ref setSelected.
*/
-void QCPPlotTitle::setSelectable(bool selectable)
+void QCPTextElement::setSelectable(bool selectable)
{
if (mSelectable != selectable)
{
@@ -13609,13 +18808,13 @@ void QCPPlotTitle::setSelectable(bool selectable)
}
/*!
- Sets the selection state of this plot title to \a selected. If the selection has changed, \ref
+ Sets the selection state of this text element to \a selected. If the selection has changed, \ref
selectionChanged is emitted.
Note that this function can change the selection state independently of the current \ref
setSelectable state.
*/
-void QCPPlotTitle::setSelected(bool selected)
+void QCPTextElement::setSelected(bool selected)
{
if (mSelected != selected)
{
@@ -13625,13 +18824,13 @@ void QCPPlotTitle::setSelected(bool selected)
}
/* inherits documentation from base class */
-void QCPPlotTitle::applyDefaultAntialiasingHint(QCPPainter *painter) const
+void QCPTextElement::applyDefaultAntialiasingHint(QCPPainter *painter) const
{
- applyAntialiasingHint(painter, mAntialiased, QCP::aeNone);
+ applyAntialiasingHint(painter, mAntialiased, QCP::aeOther);
}
/* inherits documentation from base class */
-void QCPPlotTitle::draw(QCPPainter *painter)
+void QCPTextElement::draw(QCPPainter *painter)
{
painter->setFont(mainFont());
painter->setPen(QPen(mainTextColor()));
@@ -13639,7 +18838,7 @@ void QCPPlotTitle::draw(QCPPainter *painter)
}
/* inherits documentation from base class */
-QSize QCPPlotTitle::minimumSizeHint() const
+QSize QCPTextElement::minimumSizeHint() const
{
QFontMetrics metrics(mFont);
QSize result = metrics.boundingRect(0, 0, 0, 0, Qt::AlignCenter, mText).size();
@@ -13649,7 +18848,7 @@ QSize QCPPlotTitle::minimumSizeHint() const
}
/* inherits documentation from base class */
-QSize QCPPlotTitle::maximumSizeHint() const
+QSize QCPTextElement::maximumSizeHint() const
{
QFontMetrics metrics(mFont);
QSize result = metrics.boundingRect(0, 0, 0, 0, Qt::AlignCenter, mText).size();
@@ -13659,7 +18858,7 @@ QSize QCPPlotTitle::maximumSizeHint() const
}
/* inherits documentation from base class */
-void QCPPlotTitle::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
+void QCPTextElement::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
{
Q_UNUSED(event)
Q_UNUSED(details)
@@ -13673,7 +18872,7 @@ void QCPPlotTitle::selectEvent(QMouseEvent *event, bool additive, const QVariant
}
/* inherits documentation from base class */
-void QCPPlotTitle::deselectEvent(bool *selectionStateChanged)
+void QCPTextElement::deselectEvent(bool *selectionStateChanged)
{
if (mSelectable)
{
@@ -13684,8 +18883,17 @@ void QCPPlotTitle::deselectEvent(bool *selectionStateChanged)
}
}
-/* inherits documentation from base class */
-double QCPPlotTitle::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
+/*!
+ Returns 0.99*selectionTolerance (see \ref QCustomPlot::setSelectionTolerance) when \a pos is
+ within the bounding box of the text element's text. Note that this bounding box is updated in the
+ draw call.
+
+ If \a pos is outside the text's bounding box or if \a onlySelectable is true and this text
+ element is not selectable (\ref setSelectable), returns -1.
+
+ \seebaseclassmethod
+*/
+double QCPTextElement::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
Q_UNUSED(details)
if (onlySelectable && !mSelectable)
@@ -13697,12 +18905,47 @@ double QCPPlotTitle::selectTest(const QPointF &pos, bool onlySelectable, QVarian
return -1;
}
+/*!
+ Accepts the mouse event in order to emit the according click signal in the \ref
+ mouseReleaseEvent.
+
+ \seebaseclassmethod
+*/
+void QCPTextElement::mousePressEvent(QMouseEvent *event, const QVariant &details)
+{
+ Q_UNUSED(details)
+ event->accept();
+}
+
+/*!
+ Emits the \ref clicked signal if the cursor hasn't moved by more than a few pixels since the \ref
+ mousePressEvent.
+
+ \seebaseclassmethod
+*/
+void QCPTextElement::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos)
+{
+ if ((QPointF(event->pos())-startPos).manhattanLength() <= 3)
+ emit clicked(event);
+}
+
+/*!
+ Emits the \ref doubleClicked signal.
+
+ \seebaseclassmethod
+*/
+void QCPTextElement::mouseDoubleClickEvent(QMouseEvent *event, const QVariant &details)
+{
+ Q_UNUSED(details)
+ emit doubleClicked(event);
+}
+
/*! \internal
Returns the main font to be used. This is mSelectedFont if \ref setSelected is set to
<tt>true</tt>, else mFont is returned.
*/
-QFont QCPPlotTitle::mainFont() const
+QFont QCPTextElement::mainFont() const
{
return mSelected ? mSelectedFont : mFont;
}
@@ -13712,10 +18955,15 @@ QFont QCPPlotTitle::mainFont() const
Returns the main color to be used. This is mSelectedTextColor if \ref setSelected is set to
<tt>true</tt>, else mTextColor is returned.
*/
-QColor QCPPlotTitle::mainTextColor() const
+QColor QCPTextElement::mainTextColor() const
{
return mSelected ? mSelectedTextColor : mTextColor;
}
+/* end of 'src/layoutelements/layoutelement-textelement.cpp' */
+
+
+/* including file 'src/layoutelements/layoutelement-colorscale.cpp', size 25910 */
+/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
////////////////////////////////////////////////////////////////////////////////////////////////////
@@ -13741,7 +18989,7 @@ QColor QCPPlotTitle::mainTextColor() const
To have finer control over the number display and axis behaviour, you can directly access the
\ref axis. See the documentation of QCPAxis for details about configuring axes. For example, if
you want to change the number of automatically generated ticks, call
- \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolorscale-autotickcount
+ \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolorscale-tickcount
Placing a color scale next to the main axis rect works like with any other layout element:
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolorscale-creation
@@ -13778,7 +19026,7 @@ QColor QCPPlotTitle::mainTextColor() const
/* end documentation of signals */
/* start documentation of signals */
-/*! \fn void QCPColorScale::dataRangeChanged(QCPRange newRange);
+/*! \fn void QCPColorScale::dataRangeChanged(const QCPRange &newRange);
This signal is emitted when the data range changes.
@@ -13792,7 +19040,7 @@ QColor QCPPlotTitle::mainTextColor() const
\see setDataScaleType
*/
-/*! \fn void QCPColorScale::gradientChanged(QCPColorGradient newGradient);
+/*! \fn void QCPColorScale::gradientChanged(const QCPColorGradient &newGradient);
This signal is emitted when the gradient changes.
@@ -13866,7 +19114,7 @@ bool QCPColorScale::rangeZoom() const
Note that after setting \a type to a different value, the axis returned by \ref axis() will
be a different one. The new axis will adopt the following properties from the previous axis: The
- range, scale type, log base and label.
+ range, scale type, label and ticker (the latter will be shared and not copied).
*/
void QCPColorScale::setType(QCPAxis::AxisType type)
{
@@ -13879,14 +19127,15 @@ void QCPColorScale::setType(QCPAxis::AxisType type)
{
mType = type;
QCPRange rangeTransfer(0, 6);
- double logBaseTransfer = 10;
QString labelTransfer;
- // revert some settings on old axis:
- if (mColorAxis)
+ QSharedPointer<QCPAxisTicker> tickerTransfer;
+ // transfer/revert some settings on old axis if it exists:
+ bool doTransfer = (bool)mColorAxis;
+ if (doTransfer)
{
rangeTransfer = mColorAxis.data()->range();
labelTransfer = mColorAxis.data()->label();
- logBaseTransfer = mColorAxis.data()->scaleLogBase();
+ tickerTransfer = mColorAxis.data()->ticker();
mColorAxis.data()->setLabel(QString());
disconnect(mColorAxis.data(), SIGNAL(rangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange)));
disconnect(mColorAxis.data(), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType)));
@@ -13900,13 +19149,15 @@ void QCPColorScale::setType(QCPAxis::AxisType type)
// set new mColorAxis pointer:
mColorAxis = mAxisRect.data()->axis(mType);
// transfer settings to new axis:
- mColorAxis.data()->setRange(rangeTransfer); // transfer range of old axis to new one (necessary if axis changes from vertical to horizontal or vice versa)
- mColorAxis.data()->setLabel(labelTransfer);
- mColorAxis.data()->setScaleLogBase(logBaseTransfer); // scaleType is synchronized among axes in realtime via signals (connected in QCPColorScale ctor), so we only need to take care of log base here
+ if (doTransfer)
+ {
+ 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)
+ mColorAxis.data()->setLabel(labelTransfer);
+ mColorAxis.data()->setTicker(tickerTransfer);
+ }
connect(mColorAxis.data(), SIGNAL(rangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange)));
connect(mColorAxis.data(), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType)));
- mAxisRect.data()->setRangeDragAxes(QCPAxis::orientation(mType) == Qt::Horizontal ? mColorAxis.data() : 0,
- QCPAxis::orientation(mType) == Qt::Vertical ? mColorAxis.data() : 0);
+ mAxisRect.data()->setRangeDragAxes(QList<QCPAxis*>() << mColorAxis.data());
}
}
@@ -14061,9 +19312,9 @@ void QCPColorScale::rescaleDataRange(bool onlyVisibleMaps)
QList<QCPColorMap*> maps = colorMaps();
QCPRange newRange;
bool haveRange = false;
- int sign = 0; // TODO: should change this to QCPAbstractPlottable::SignDomain later (currently is protected, maybe move to QCP namespace)
+ QCP::SignDomain sign = QCP::sdBoth;
if (mDataScaleType == QCPAxis::stLogarithmic)
- sign = (mDataRange.upper < 0 ? -1 : 1);
+ sign = (mDataRange.upper < 0 ? QCP::sdNegative : QCP::sdPositive);
for (int i=0; i<maps.size(); ++i)
{
if (!maps.at(i)->realVisibility() && onlyVisibleMaps)
@@ -14073,13 +19324,13 @@ void QCPColorScale::rescaleDataRange(bool onlyVisibleMaps)
{
bool currentFoundRange = true;
mapRange = maps.at(i)->data()->dataBounds();
- if (sign == 1)
+ if (sign == QCP::sdPositive)
{
if (mapRange.lower <= 0 && mapRange.upper > 0)
mapRange.lower = mapRange.upper*1e-3;
else if (mapRange.lower <= 0 && mapRange.upper <= 0)
currentFoundRange = false;
- } else if (sign == -1)
+ } else if (sign == QCP::sdNegative)
{
if (mapRange.upper >= 0 && mapRange.lower < 0)
mapRange.upper = mapRange.lower*1e-3;
@@ -14158,36 +19409,36 @@ void QCPColorScale::applyDefaultAntialiasingHint(QCPPainter *painter) const
}
/* inherits documentation from base class */
-void QCPColorScale::mousePressEvent(QMouseEvent *event)
+void QCPColorScale::mousePressEvent(QMouseEvent *event, const QVariant &details)
{
if (!mAxisRect)
{
qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
return;
}
- mAxisRect.data()->mousePressEvent(event);
+ mAxisRect.data()->mousePressEvent(event, details);
}
/* inherits documentation from base class */
-void QCPColorScale::mouseMoveEvent(QMouseEvent *event)
+void QCPColorScale::mouseMoveEvent(QMouseEvent *event, const QPointF &startPos)
{
if (!mAxisRect)
{
qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
return;
}
- mAxisRect.data()->mouseMoveEvent(event);
+ mAxisRect.data()->mouseMoveEvent(event, startPos);
}
/* inherits documentation from base class */
-void QCPColorScale::mouseReleaseEvent(QMouseEvent *event)
+void QCPColorScale::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos)
{
if (!mAxisRect)
{
qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
return;
}
- mAxisRect.data()->mouseReleaseEvent(event);
+ mAxisRect.data()->mouseReleaseEvent(event, startPos);
}
/* inherits documentation from base class */
@@ -14253,8 +19504,11 @@ QCPColorScaleAxisRectPrivate::QCPColorScaleAxisRectPrivate(QCPColorScale *parent
}
/*! \internal
+
Updates the color gradient image if necessary, by calling \ref updateGradientImage, then draws
it. Then the axes are drawn by calling the \ref QCPAxisRect::draw base class implementation.
+
+ \seebaseclassmethod
*/
void QCPColorScaleAxisRectPrivate::draw(QCPPainter *painter)
{
@@ -14283,6 +19537,7 @@ void QCPColorScaleAxisRectPrivate::updateGradientImage()
if (rect().isEmpty())
return;
+ const QImage::Format format = QImage::Format_ARGB32_Premultiplied;
int n = mParentColorScale->mGradient.levelCount();
int w, h;
QVector<double> data(n);
@@ -14292,7 +19547,7 @@ void QCPColorScaleAxisRectPrivate::updateGradientImage()
{
w = n;
h = rect().height();
- mGradientImage = QImage(w, h, QImage::Format_RGB32);
+ mGradientImage = QImage(w, h, format);
QVector<QRgb*> pixels;
for (int y=0; y<h; ++y)
pixels.append(reinterpret_cast<QRgb*>(mGradientImage.scanLine(y)));
@@ -14303,7 +19558,7 @@ void QCPColorScaleAxisRectPrivate::updateGradientImage()
{
w = rect().width();
h = n;
- mGradientImage = QImage(w, h, QImage::Format_RGB32);
+ mGradientImage = QImage(w, h, format);
for (int y=0; y<h; ++y)
{
QRgb *pixels = reinterpret_cast<QRgb*>(mGradientImage.scanLine(y));
@@ -14364,51 +19619,98 @@ void QCPColorScaleAxisRectPrivate::axisSelectableChanged(QCPAxis::SelectablePart
}
}
}
+/* end of 'src/layoutelements/layoutelement-colorscale.cpp' */
+/* including file 'src/plottables/plottable-graph.cpp', size 72363 */
+/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
+
////////////////////////////////////////////////////////////////////////////////////////////////////
-//////////////////// QCPData
+//////////////////// QCPGraphData
////////////////////////////////////////////////////////////////////////////////////////////////////
-/*! \class QCPData
+/*! \class QCPGraphData
\brief Holds the data of one single data point for QCPGraph.
- The container for storing multiple data points is \ref QCPDataMap.
-
The stored data is:
- \li \a key: coordinate on the key axis of this data point
- \li \a value: coordinate on the value axis of this data point
- \li \a keyErrorMinus: negative error in the key dimension (for error bars)
- \li \a keyErrorPlus: positive error in the key dimension (for error bars)
- \li \a valueErrorMinus: negative error in the value dimension (for error bars)
- \li \a valueErrorPlus: positive error in the value dimension (for error bars)
+ \li \a key: coordinate on the key axis of this data point (this is the \a mainKey and the \a sortKey)
+ \li \a value: coordinate on the value axis of this data point (this is the \a mainValue)
+
+ The container for storing multiple data points is \ref QCPGraphDataContainer. It is a typedef for
+ \ref QCPDataContainer with \ref QCPGraphData as the DataType template parameter. See the
+ documentation there for an explanation regarding the data type's generic methods.
- \see QCPDataMap
+ \see QCPGraphDataContainer
*/
+/* start documentation of inline functions */
+
+/*! \fn double QCPGraphData::sortKey() const
+
+ Returns the \a key member of this data point.
+
+ For a general explanation of what this method is good for in the context of the data container,
+ see the documentation of \ref QCPDataContainer.
+*/
+
+/*! \fn static QCPGraphData QCPGraphData::fromSortKey(double sortKey)
+
+ Returns a data point with the specified \a sortKey. All other members are set to zero.
+
+ For a general explanation of what this method is good for in the context of the data container,
+ see the documentation of \ref QCPDataContainer.
+*/
+
+/*! \fn static static bool QCPGraphData::sortKeyIsMainKey()
+
+ Since the member \a key is both the data point key coordinate and the data ordering parameter,
+ this method returns true.
+
+ For a general explanation of what this method is good for in the context of the data container,
+ see the documentation of \ref QCPDataContainer.
+*/
+
+/*! \fn double QCPGraphData::mainKey() const
+
+ Returns the \a key member of this data point.
+
+ For a general explanation of what this method is good for in the context of the data container,
+ see the documentation of \ref QCPDataContainer.
+*/
+
+/*! \fn double QCPGraphData::mainValue() const
+
+ Returns the \a value member of this data point.
+
+ For a general explanation of what this method is good for in the context of the data container,
+ see the documentation of \ref QCPDataContainer.
+*/
+
+/*! \fn QCPRange QCPGraphData::valueRange() const
+
+ Returns a QCPRange with both lower and upper boundary set to \a value of this data point.
+
+ For a general explanation of what this method is good for in the context of the data container,
+ see the documentation of \ref QCPDataContainer.
+*/
+
+/* end documentation of inline functions */
+
/*!
- Constructs a data point with key, value and all errors set to zero.
+ Constructs a data point with key and value set to zero.
*/
-QCPData::QCPData() :
+QCPGraphData::QCPGraphData() :
key(0),
- value(0),
- keyErrorPlus(0),
- keyErrorMinus(0),
- valueErrorPlus(0),
- valueErrorMinus(0)
+ value(0)
{
}
/*!
- Constructs a data point with the specified \a key and \a value. All errors are set to zero.
+ Constructs a data point with the specified \a key and \a value.
*/
-QCPData::QCPData(double key, double value) :
+QCPGraphData::QCPGraphData(double key, double value) :
key(key),
- value(value),
- keyErrorPlus(0),
- keyErrorMinus(0),
- valueErrorPlus(0),
- valueErrorMinus(0)
+ value(value)
{
}
@@ -14422,12 +19724,12 @@ QCPData::QCPData(double key, double value) :
\image html QCPGraph.png
- Usually QCustomPlot creates graphs internally via QCustomPlot::addGraph and the resulting
- instance is accessed via QCustomPlot::graph.
+ Usually you create new graphs by calling QCustomPlot::addGraph. The resulting instance can be
+ accessed via QCustomPlot::graph.
To plot data, assign it with the \ref setData or \ref addData functions. Alternatively, you can
- also access and modify the graph's data via the \ref data method, which returns a pointer to the
- internal \ref QCPDataMap.
+ also access and modify the data via the \ref data method, which returns a pointer to the internal
+ \ref QCPGraphDataContainer.
Graphs are used to display single-valued data. Single-valued means that there should only be one
data point per unique key coordinate. In other words, the graph can't have \a loops. If you do
@@ -14437,7 +19739,7 @@ QCPData::QCPData(double key, double value) :
(<tt>qQNaN()</tt> or <tt>std::numeric_limits<double>::quiet_NaN()</tt>) in between the two data points that shall be
separated.
- \section appearance Changing the appearance
+ \section qcpgraph-appearance Changing the appearance
The appearance of the graph is mainly determined by the line style, scatter style, brush and pen
of the graph (\ref setLineStyle, \ref setScatterStyle, \ref setBrush, \ref setPen).
@@ -14457,11 +19759,11 @@ QCPData::QCPData(double key, double value) :
/* start of documentation of inline functions */
-/*! \fn QCPDataMap *QCPGraph::data() const
+/*! \fn QSharedPointer<QCPGraphDataContainer> QCPGraph::data() const
- Returns a pointer to the internal data storage of type \ref QCPDataMap. You may use it to
- directly manipulate the data, which may be more convenient and faster than using the regular \ref
- setData or \ref addData methods, in certain situations.
+ Returns a shared pointer to the internal data storage of type \ref QCPGraphDataContainer. You may
+ use it to directly manipulate the data, which may be more convenient and faster than using the
+ regular \ref setData or \ref addData methods.
*/
/* end of documentation of inline functions */
@@ -14472,249 +19774,68 @@ QCPData::QCPData(double key, double value) :
the same orientation. If either of these restrictions is violated, a corresponding message is
printed to the debug output (qDebug), the construction is not aborted, though.
- The constructed QCPGraph can be added to the plot with QCustomPlot::addPlottable, QCustomPlot
- then takes ownership of the graph.
+ The created QCPGraph is automatically registered with the QCustomPlot instance inferred from \a
+ keyAxis. This QCustomPlot instance takes ownership of the QCPGraph, so do not delete it manually
+ but use QCustomPlot::removePlottable() instead.
To directly create a graph inside a plot, you can also use the simpler QCustomPlot::addGraph function.
*/
QCPGraph::QCPGraph(QCPAxis *keyAxis, QCPAxis *valueAxis) :
- QCPAbstractPlottable(keyAxis, valueAxis)
+ QCPAbstractPlottable1D<QCPGraphData>(keyAxis, valueAxis)
{
- mData = new QCPDataMap;
-
+ // special handling for QCPGraphs to maintain the simple graph interface:
+ mParentPlot->registerGraph(this);
+
setPen(QPen(Qt::blue, 0));
- setErrorPen(QPen(Qt::black));
setBrush(Qt::NoBrush);
- setSelectedPen(QPen(QColor(80, 80, 255), 2.5));
- setSelectedBrush(Qt::NoBrush);
setLineStyle(lsLine);
- setErrorType(etNone);
- setErrorBarSize(6);
- setErrorBarSkipSymbol(true);
+ setScatterSkip(0);
setChannelFillGraph(0);
setAdaptiveSampling(true);
}
QCPGraph::~QCPGraph()
{
- delete mData;
}
-/*!
- Replaces the current data with the provided \a data.
+/*! \overload
- If \a copy is set to true, data points in \a data will only be copied. if false, the graph
- takes ownership of the passed data and replaces the internal data pointer with it. This is
- significantly faster than copying for large datasets.
+ Replaces the current data container with the provided \a data container.
+
+ Since a QSharedPointer is used, multiple QCPGraphs may share the same data container safely.
+ Modifying the data in the container will then affect all graphs that share the container. Sharing
+ can be achieved by simply exchanging the data containers wrapped in shared pointers:
+ \snippet documentation/doc-code-snippets/mainwindow.cpp qcpgraph-datasharing-1
- Alternatively, you can also access and modify the graph's data via the \ref data method, which
- returns a pointer to the internal \ref QCPDataMap.
+ If you do not wish to share containers, but create a copy from an existing container, rather use
+ the \ref QCPDataContainer<DataType>::set method on the graph's data container directly:
+ \snippet documentation/doc-code-snippets/mainwindow.cpp qcpgraph-datasharing-2
+
+ \see addData
*/
-void QCPGraph::setData(QCPDataMap *data, bool copy)
+void QCPGraph::setData(QSharedPointer<QCPGraphDataContainer> data)
{
- if (mData == data)
- {
- qDebug() << Q_FUNC_INFO << "The data pointer is already in (and owned by) this plottable" << reinterpret_cast<quintptr>(data);
- return;
- }
- if (copy)
- {
- *mData = *data;
- } else
- {
- delete mData;
- mData = data;
- }
+ mDataContainer = data;
}
/*! \overload
- Replaces the current data with the provided points in \a key and \a value pairs. The provided
+ Replaces the current data with the provided points in \a keys and \a values. The provided
vectors should have equal length. Else, the number of added points will be the size of the
smallest vector.
-*/
-void QCPGraph::setData(const QVector<double> &key, const QVector<double> &value)
-{
- mData->clear();
- int n = key.size();
- n = qMin(n, value.size());
- QCPData newData;
- for (int i=0; i<n; ++i)
- {
- newData.key = key[i];
- newData.value = value[i];
- mData->insertMulti(newData.key, newData);
- }
-}
-
-/*!
- Replaces the current data with the provided points in \a key and \a value pairs. Additionally the
- symmetrical value error of the data points are set to the values in \a valueError.
- For error bars to show appropriately, see \ref setErrorType.
- The provided vectors should have equal length. Else, the number of added points will be the size of the
- smallest vector.
-
- For asymmetrical errors (plus different from minus), see the overloaded version of this function.
-*/
-void QCPGraph::setDataValueError(const QVector<double> &key, const QVector<double> &value, const QVector<double> &valueError)
-{
- mData->clear();
- int n = key.size();
- n = qMin(n, value.size());
- n = qMin(n, valueError.size());
- QCPData newData;
- for (int i=0; i<n; ++i)
- {
- newData.key = key[i];
- newData.value = value[i];
- newData.valueErrorMinus = valueError[i];
- newData.valueErrorPlus = valueError[i];
- mData->insertMulti(key[i], newData);
- }
-}
-
-/*!
- \overload
- Replaces the current data with the provided points in \a key and \a value pairs. Additionally the
- negative value error of the data points are set to the values in \a valueErrorMinus, the positive
- value error to \a valueErrorPlus.
- For error bars to show appropriately, see \ref setErrorType.
- The provided vectors should have equal length. Else, the number of added points will be the size of the
- smallest vector.
-*/
-void QCPGraph::setDataValueError(const QVector<double> &key, const QVector<double> &value, const QVector<double> &valueErrorMinus, const QVector<double> &valueErrorPlus)
-{
- mData->clear();
- int n = key.size();
- n = qMin(n, value.size());
- n = qMin(n, valueErrorMinus.size());
- n = qMin(n, valueErrorPlus.size());
- QCPData newData;
- for (int i=0; i<n; ++i)
- {
- newData.key = key[i];
- newData.value = value[i];
- newData.valueErrorMinus = valueErrorMinus[i];
- newData.valueErrorPlus = valueErrorPlus[i];
- mData->insertMulti(key[i], newData);
- }
-}
-
-/*!
- Replaces the current data with the provided points in \a key and \a value pairs. Additionally the
- symmetrical key error of the data points are set to the values in \a keyError.
- For error bars to show appropriately, see \ref setErrorType.
- The provided vectors should have equal length. Else, the number of added points will be the size of the
- smallest vector.
- For asymmetrical errors (plus different from minus), see the overloaded version of this function.
-*/
-void QCPGraph::setDataKeyError(const QVector<double> &key, const QVector<double> &value, const QVector<double> &keyError)
-{
- mData->clear();
- int n = key.size();
- n = qMin(n, value.size());
- n = qMin(n, keyError.size());
- QCPData newData;
- for (int i=0; i<n; ++i)
- {
- newData.key = key[i];
- newData.value = value[i];
- newData.keyErrorMinus = keyError[i];
- newData.keyErrorPlus = keyError[i];
- mData->insertMulti(key[i], newData);
- }
-}
-
-/*!
- \overload
- Replaces the current data with the provided points in \a key and \a value pairs. Additionally the
- negative key error of the data points are set to the values in \a keyErrorMinus, the positive
- key error to \a keyErrorPlus.
- For error bars to show appropriately, see \ref setErrorType.
- The provided vectors should have equal length. Else, the number of added points will be the size of the
- smallest vector.
-*/
-void QCPGraph::setDataKeyError(const QVector<double> &key, const QVector<double> &value, const QVector<double> &keyErrorMinus, const QVector<double> &keyErrorPlus)
-{
- mData->clear();
- int n = key.size();
- n = qMin(n, value.size());
- n = qMin(n, keyErrorMinus.size());
- n = qMin(n, keyErrorPlus.size());
- QCPData newData;
- for (int i=0; i<n; ++i)
- {
- newData.key = key[i];
- newData.value = value[i];
- newData.keyErrorMinus = keyErrorMinus[i];
- newData.keyErrorPlus = keyErrorPlus[i];
- mData->insertMulti(key[i], newData);
- }
-}
-
-/*!
- Replaces the current data with the provided points in \a key and \a value pairs. Additionally the
- symmetrical key and value errors of the data points are set to the values in \a keyError and \a valueError.
- For error bars to show appropriately, see \ref setErrorType.
- The provided vectors should have equal length. Else, the number of added points will be the size of the
- smallest vector.
+ If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
+ can set \a alreadySorted to true, to improve performance by saving a sorting run.
- For asymmetrical errors (plus different from minus), see the overloaded version of this function.
-*/
-void QCPGraph::setDataBothError(const QVector<double> &key, const QVector<double> &value, const QVector<double> &keyError, const QVector<double> &valueError)
-{
- mData->clear();
- int n = key.size();
- n = qMin(n, value.size());
- n = qMin(n, valueError.size());
- n = qMin(n, keyError.size());
- QCPData newData;
- for (int i=0; i<n; ++i)
- {
- newData.key = key[i];
- newData.value = value[i];
- newData.keyErrorMinus = keyError[i];
- newData.keyErrorPlus = keyError[i];
- newData.valueErrorMinus = valueError[i];
- newData.valueErrorPlus = valueError[i];
- mData->insertMulti(key[i], newData);
- }
-}
-
-/*!
- \overload
- Replaces the current data with the provided points in \a key and \a value pairs. Additionally the
- negative key and value errors of the data points are set to the values in \a keyErrorMinus and \a valueErrorMinus. The positive
- key and value errors are set to the values in \a keyErrorPlus \a valueErrorPlus.
- For error bars to show appropriately, see \ref setErrorType.
- The provided vectors should have equal length. Else, the number of added points will be the size of the
- smallest vector.
+ \see addData
*/
-void QCPGraph::setDataBothError(const QVector<double> &key, const QVector<double> &value, const QVector<double> &keyErrorMinus, const QVector<double> &keyErrorPlus, const QVector<double> &valueErrorMinus, const QVector<double> &valueErrorPlus)
+void QCPGraph::setData(const QVector<double> &keys, const QVector<double> &values, bool alreadySorted)
{
- mData->clear();
- int n = key.size();
- n = qMin(n, value.size());
- n = qMin(n, valueErrorMinus.size());
- n = qMin(n, valueErrorPlus.size());
- n = qMin(n, keyErrorMinus.size());
- n = qMin(n, keyErrorPlus.size());
- QCPData newData;
- for (int i=0; i<n; ++i)
- {
- newData.key = key[i];
- newData.value = value[i];
- newData.keyErrorMinus = keyErrorMinus[i];
- newData.keyErrorPlus = keyErrorPlus[i];
- newData.valueErrorMinus = valueErrorMinus[i];
- newData.valueErrorPlus = valueErrorPlus[i];
- mData->insertMulti(key[i], newData);
- }
+ mDataContainer->clear();
+ addData(keys, values, alreadySorted);
}
-
/*!
Sets how the single data points are connected in the plot. For scatter-only plots, set \a ls to
\ref lsNone and \ref setScatterStyle to the desired scatter style.
@@ -14738,49 +19859,19 @@ void QCPGraph::setScatterStyle(const QCPScatterStyle &style)
}
/*!
- Sets which kind of error bars (Key Error, Value Error or both) should be drawn on each data
- point. If you set \a errorType to something other than \ref etNone, make sure to actually pass
- error data via the specific setData functions along with the data points (e.g. \ref
- setDataValueError, \ref setDataKeyError, \ref setDataBothError).
+ If scatters are displayed (scatter style not \ref QCPScatterStyle::ssNone), \a skip number of
+ scatter points are skipped/not drawn after every drawn scatter point.
- \see ErrorType
-*/
-void QCPGraph::setErrorType(ErrorType errorType)
-{
- mErrorType = errorType;
-}
-
-/*!
- Sets the pen with which the error bars will be drawn.
- \see setErrorBarSize, setErrorType
-*/
-void QCPGraph::setErrorPen(const QPen &pen)
-{
- mErrorPen = pen;
-}
+ This can be used to make the data appear sparser while for example still having a smooth line,
+ and to improve performance for very high density plots.
-/*!
- Sets the width of the handles at both ends of an error bar in pixels.
-*/
-void QCPGraph::setErrorBarSize(double size)
-{
- mErrorBarSize = size;
-}
+ If \a skip is set to 0 (default), all scatter points are drawn.
-/*!
- If \a enabled is set to true, the error bar will not be drawn as a solid line under the scatter symbol but
- leave some free space around the symbol.
-
- This feature uses the current scatter size (\ref QCPScatterStyle::setSize) to determine the size
- of the area to leave blank. So when drawing Pixmaps as scatter points (\ref
- QCPScatterStyle::ssPixmap), the scatter size must be set manually to a value corresponding to the
- size of the Pixmap, if the error bars should leave gaps to its boundaries.
-
- \ref setErrorType, setErrorBarSize, setScatterStyle
+ \see setScatterStyle
*/
-void QCPGraph::setErrorBarSkipSymbol(bool enabled)
+void QCPGraph::setScatterSkip(int skip)
{
- mErrorBarSkipSymbol = enabled;
+ mScatterSkip = qMax(0, skip);
}
/*!
@@ -14848,273 +19939,149 @@ void QCPGraph::setAdaptiveSampling(bool enabled)
mAdaptiveSampling = enabled;
}
-/*!
- Adds the provided data points in \a dataMap to the current data.
-
- Alternatively, you can also access and modify the graph's data via the \ref data method, which
- returns a pointer to the internal \ref QCPDataMap.
-
- \see removeData
-*/
-void QCPGraph::addData(const QCPDataMap &dataMap)
-{
- mData->unite(dataMap);
-}
-
-/*! \overload
- Adds the provided single data point in \a data to the current data.
-
- Alternatively, you can also access and modify the graph's data via the \ref data method, which
- returns a pointer to the internal \ref QCPDataMap.
-
- \see removeData
-*/
-void QCPGraph::addData(const QCPData &data)
-{
- mData->insertMulti(data.key, data);
-}
-
/*! \overload
- Adds the provided single data point as \a key and \a value pair to the current data.
-
- Alternatively, you can also access and modify the graph's data via the \ref data method, which
- returns a pointer to the internal \ref QCPDataMap.
- \see removeData
-*/
-void QCPGraph::addData(double key, double value)
-{
- QCPData newData;
- newData.key = key;
- newData.value = value;
- mData->insertMulti(newData.key, newData);
-}
-
-/*! \overload
- Adds the provided data points as \a key and \a value pairs to the current data.
+ Adds the provided points in \a keys and \a values to the current data. The provided vectors
+ should have equal length. Else, the number of added points will be the size of the smallest
+ vector.
- Alternatively, you can also access and modify the graph's data via the \ref data method, which
- returns a pointer to the internal \ref QCPDataMap.
+ If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
+ can set \a alreadySorted to true, to improve performance by saving a sorting run.
- \see removeData
+ Alternatively, you can also access and modify the data directly via the \ref data method, which
+ returns a pointer to the internal data container.
*/
-void QCPGraph::addData(const QVector<double> &keys, const QVector<double> &values)
+void QCPGraph::addData(const QVector<double> &keys, const QVector<double> &values, bool alreadySorted)
{
- int n = qMin(keys.size(), values.size());
- QCPData newData;
- for (int i=0; i<n; ++i)
+ if (keys.size() != values.size())
+ qDebug() << Q_FUNC_INFO << "keys and values have different sizes:" << keys.size() << values.size();
+ const int n = qMin(keys.size(), values.size());
+ QVector<QCPGraphData> tempData(n);
+ QVector<QCPGraphData>::iterator it = tempData.begin();
+ const QVector<QCPGraphData>::iterator itEnd = tempData.end();
+ int i = 0;
+ while (it != itEnd)
{
- newData.key = keys[i];
- newData.value = values[i];
- mData->insertMulti(newData.key, newData);
+ it->key = keys[i];
+ it->value = values[i];
+ ++it;
+ ++i;
}
-}
-
-/*!
- Removes all data points with keys smaller than \a key.
- \see addData, clearData
-*/
-void QCPGraph::removeDataBefore(double key)
-{
- QCPDataMap::iterator it = mData->begin();
- while (it != mData->end() && it.key() < key)
- it = mData->erase(it);
-}
-
-/*!
- Removes all data points with keys greater than \a key.
- \see addData, clearData
-*/
-void QCPGraph::removeDataAfter(double key)
-{
- if (mData->isEmpty()) return;
- QCPDataMap::iterator it = mData->upperBound(key);
- while (it != mData->end())
- it = mData->erase(it);
-}
-
-/*!
- Removes all data points with keys between \a fromKey and \a toKey.
- if \a fromKey is greater or equal to \a toKey, the function does nothing. To remove
- a single data point with known key, use \ref removeData(double key).
-
- \see addData, clearData
-*/
-void QCPGraph::removeData(double fromKey, double toKey)
-{
- if (fromKey >= toKey || mData->isEmpty()) return;
- QCPDataMap::iterator it = mData->upperBound(fromKey);
- QCPDataMap::iterator itEnd = mData->upperBound(toKey);
- while (it != itEnd)
- it = mData->erase(it);
+ mDataContainer->add(tempData, alreadySorted); // don't modify tempData beyond this to prevent copy on write
}
/*! \overload
- Removes a single data point at \a key. If the position is not known with absolute precision,
- consider using \ref removeData(double fromKey, double toKey) with a small fuzziness interval around
- the suspected position, depeding on the precision with which the key is known.
-
- \see addData, clearData
-*/
-void QCPGraph::removeData(double key)
-{
- mData->remove(key);
-}
-
-/*!
- Removes all data points.
- \see removeData, removeDataAfter, removeDataBefore
+ Adds the provided data point as \a key and \a value to the current data.
+
+ Alternatively, you can also access and modify the data directly via the \ref data method, which
+ returns a pointer to the internal data container.
*/
-void QCPGraph::clearData()
+void QCPGraph::addData(double key, double value)
{
- mData->clear();
+ mDataContainer->add(QCPGraphData(key, value));
}
/* inherits documentation from base class */
double QCPGraph::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
- Q_UNUSED(details)
- if ((onlySelectable && !mSelectable) || mData->isEmpty())
+ if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
return -1;
- if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; }
-
- if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()))
- return pointDistance(pos);
- else
+ if (!mKeyAxis || !mValueAxis)
return -1;
-}
-
-/*! \overload
-
- Allows to define whether error bars are taken into consideration when determining the new axis
- range.
-
- \see rescaleKeyAxis, rescaleValueAxis, QCPAbstractPlottable::rescaleAxes, QCustomPlot::rescaleAxes
-*/
-void QCPGraph::rescaleAxes(bool onlyEnlarge, bool includeErrorBars) const
-{
- rescaleKeyAxis(onlyEnlarge, includeErrorBars);
- rescaleValueAxis(onlyEnlarge, includeErrorBars);
-}
-
-/*! \overload
-
- Allows to define whether error bars (of kind \ref QCPGraph::etKey) are taken into consideration
- when determining the new axis range.
-
- \see rescaleAxes, QCPAbstractPlottable::rescaleKeyAxis
-*/
-void QCPGraph::rescaleKeyAxis(bool onlyEnlarge, bool includeErrorBars) const
-{
- // this code is a copy of QCPAbstractPlottable::rescaleKeyAxis with the only change
- // that getKeyRange is passed the includeErrorBars value.
- if (mData->isEmpty()) return;
-
- QCPAxis *keyAxis = mKeyAxis.data();
- if (!keyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; }
-
- SignDomain signDomain = sdBoth;
- if (keyAxis->scaleType() == QCPAxis::stLogarithmic)
- signDomain = (keyAxis->range().upper < 0 ? sdNegative : sdPositive);
- bool foundRange;
- QCPRange newRange = getKeyRange(foundRange, signDomain, includeErrorBars);
-
- if (foundRange)
+ if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()))
{
- if (onlyEnlarge)
+ QCPGraphDataContainer::const_iterator closestDataPoint = mDataContainer->constEnd();
+ double result = pointDistance(pos, closestDataPoint);
+ if (details)
{
- if (keyAxis->range().lower < newRange.lower)
- newRange.lower = keyAxis->range().lower;
- if (keyAxis->range().upper > newRange.upper)
- newRange.upper = keyAxis->range().upper;
+ int pointIndex = closestDataPoint-mDataContainer->constBegin();
+ details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1)));
}
- keyAxis->setRange(newRange);
- }
+ return result;
+ } else
+ return -1;
}
-/*! \overload
-
- Allows to define whether error bars (of kind \ref QCPGraph::etValue) are taken into consideration
- when determining the new axis range.
-
- \see rescaleAxes, QCPAbstractPlottable::rescaleValueAxis
-*/
-void QCPGraph::rescaleValueAxis(bool onlyEnlarge, bool includeErrorBars) const
+/* inherits documentation from base class */
+QCPRange QCPGraph::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const
{
- // this code is a copy of QCPAbstractPlottable::rescaleValueAxis with the only change
- // is that getValueRange is passed the includeErrorBars value.
- if (mData->isEmpty()) return;
-
- QCPAxis *valueAxis = mValueAxis.data();
- if (!valueAxis) { qDebug() << Q_FUNC_INFO << "invalid value axis"; return; }
+ return mDataContainer->keyRange(foundRange, inSignDomain);
+}
- SignDomain signDomain = sdBoth;
- if (valueAxis->scaleType() == QCPAxis::stLogarithmic)
- signDomain = (valueAxis->range().upper < 0 ? sdNegative : sdPositive);
-
- bool foundRange;
- QCPRange newRange = getValueRange(foundRange, signDomain, includeErrorBars);
-
- if (foundRange)
- {
- if (onlyEnlarge)
- {
- if (valueAxis->range().lower < newRange.lower)
- newRange.lower = valueAxis->range().lower;
- if (valueAxis->range().upper > newRange.upper)
- newRange.upper = valueAxis->range().upper;
- }
- valueAxis->setRange(newRange);
- }
+/* inherits documentation from base class */
+QCPRange QCPGraph::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const
+{
+ return mDataContainer->valueRange(foundRange, inSignDomain, inKeyRange);
}
/* inherits documentation from base class */
void QCPGraph::draw(QCPPainter *painter)
{
if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
- if (mKeyAxis.data()->range().size() <= 0 || mData->isEmpty()) return;
+ if (mKeyAxis.data()->range().size() <= 0 || mDataContainer->isEmpty()) return;
if (mLineStyle == lsNone && mScatterStyle.isNone()) return;
- // allocate line and (if necessary) point vectors:
- QVector<QPointF> *lineData = new QVector<QPointF>;
- QVector<QCPData> *scatterData = 0;
- if (!mScatterStyle.isNone())
- scatterData = new QVector<QCPData>;
-
- // fill vectors with data appropriate to plot style:
- getPlotData(lineData, scatterData);
+ QVector<QPointF> lines, scatters; // line and (if necessary) scatter pixel coordinates will be stored here while iterating over segments
- // check data validity if flag set:
-#ifdef QCUSTOMPLOT_CHECK_DATA
- QCPDataMap::const_iterator it;
- for (it = mData->constBegin(); it != mData->constEnd(); ++it)
+ // loop over and draw segments of unselected/selected data:
+ QList<QCPDataRange> selectedSegments, unselectedSegments, allSegments;
+ getDataSegments(selectedSegments, unselectedSegments);
+ allSegments << unselectedSegments << selectedSegments;
+ for (int i=0; i<allSegments.size(); ++i)
{
- if (QCP::isInvalidData(it.value().key, it.value().value) ||
- QCP::isInvalidData(it.value().keyErrorPlus, it.value().keyErrorMinus) ||
- QCP::isInvalidData(it.value().valueErrorPlus, it.value().valueErrorPlus))
- qDebug() << Q_FUNC_INFO << "Data point at" << it.key() << "invalid." << "Plottable name:" << name();
- }
+ bool isSelectedSegment = i >= unselectedSegments.size();
+ // get line pixel points appropriate to line style:
+ 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)
+ getLines(&lines, lineDataRange);
+
+ // check data validity if flag set:
+#ifdef QCUSTOMPLOT_CHECK_DATA
+ QCPGraphDataContainer::const_iterator it;
+ for (it = mDataContainer->constBegin(); it != mDataContainer->constEnd(); ++it)
+ {
+ if (QCP::isInvalidData(it->key, it->value))
+ qDebug() << Q_FUNC_INFO << "Data point at" << it->key << "invalid." << "Plottable name:" << name();
+ }
#endif
-
- // draw fill of graph:
- drawFill(painter, lineData);
-
- // draw line:
- if (mLineStyle == lsImpulse)
- drawImpulsePlot(painter, lineData);
- else if (mLineStyle != lsNone)
- drawLinePlot(painter, lineData); // also step plots can be drawn as a line plot
-
- // draw scatters:
- if (scatterData)
- drawScatterPlot(painter, scatterData);
+
+ // draw fill of graph:
+ if (isSelectedSegment && mSelectionDecorator)
+ mSelectionDecorator->applyBrush(painter);
+ else
+ painter->setBrush(mBrush);
+ painter->setPen(Qt::NoPen);
+ drawFill(painter, &lines);
+
+ // draw line:
+ if (mLineStyle != lsNone)
+ {
+ if (isSelectedSegment && mSelectionDecorator)
+ mSelectionDecorator->applyPen(painter);
+ else
+ painter->setPen(mPen);
+ painter->setBrush(Qt::NoBrush);
+ if (mLineStyle == lsImpulse)
+ drawImpulsePlot(painter, lines);
+ else
+ drawLinePlot(painter, lines); // also step plots can be drawn as a line plot
+ }
+
+ // draw scatters:
+ QCPScatterStyle finalScatterStyle = mScatterStyle;
+ if (isSelectedSegment && mSelectionDecorator)
+ finalScatterStyle = mSelectionDecorator->getFinalScatterStyle(mScatterStyle);
+ if (!finalScatterStyle.isNone())
+ {
+ getScatters(&scatters, allSegments.at(i));
+ drawScatterPlot(painter, scatters, finalScatterStyle);
+ }
+ }
- // free allocated line and point vectors:
- delete lineData;
- if (scatterData)
- delete scatterData;
+ // draw other selection decoration that isn't just line/scatter pens and brushes:
+ if (mSelectionDecorator)
+ mSelectionDecorator->drawDecoration(painter, selection());
}
/* inherits documentation from base class */
@@ -15154,889 +20121,786 @@ void QCPGraph::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
/*! \internal
- This function branches out to the line style specific "get(...)PlotData" functions, according to
- the line style of the graph.
-
- \a lineData will be filled with raw points that will be drawn with the according draw functions,
- e.g. \ref drawLinePlot and \ref drawImpulsePlot. These aren't necessarily the original data
- points, since for step plots for example, additional points are needed for drawing lines that
- make up steps. If the line style of the graph is \ref lsNone, the \a lineData vector will be left
- untouched.
-
- \a scatterData will be filled with the original data points so \ref drawScatterPlot can draw the
- scatter symbols accordingly. If no scatters need to be drawn, i.e. the scatter style's shape is
- \ref QCPScatterStyle::ssNone, pass 0 as \a scatterData, and this step will be skipped.
-
- \see getScatterPlotData, getLinePlotData, getStepLeftPlotData, getStepRightPlotData,
- getStepCenterPlotData, getImpulsePlotData
+ This method retrieves an optimized set of data points via \ref getOptimizedLineData, an branches
+ out to the line style specific functions such as \ref dataToLines, \ref dataToStepLeftLines, etc.
+ according to the line style of the graph.
+
+ \a lines will be filled with points in pixel coordinates, that can be drawn with the according
+ draw functions like \ref drawLinePlot and \ref drawImpulsePlot. The points returned in \a lines
+ aren't necessarily the original data points. For example, step line styles require additional
+ points to form the steps when drawn. If the line style of the graph is \ref lsNone, the \a
+ lines vector will be empty.
+
+ \a dataRange specifies the beginning and ending data indices that will be taken into account for
+ conversion. In this function, the specified range may exceed the total data bounds without harm:
+ a correspondingly trimmed data range will be used. This takes the burden off the user of this
+ function to check for valid indices in \a dataRange, e.g. when extending ranges coming from \ref
+ getDataSegments.
+
+ \see getScatters
*/
-void QCPGraph::getPlotData(QVector<QPointF> *lineData, QVector<QCPData> *scatterData) const
+void QCPGraph::getLines(QVector<QPointF> *lines, const QCPDataRange &dataRange) const
{
- switch(mLineStyle)
+ if (!lines) return;
+ QCPGraphDataContainer::const_iterator begin, end;
+ getVisibleDataBounds(begin, end, dataRange);
+ if (begin == end)
+ {
+ lines->clear();
+ return;
+ }
+
+ QVector<QCPGraphData> lineData;
+ if (mLineStyle != lsNone)
+ getOptimizedLineData(&lineData, begin, end);
+
+ switch (mLineStyle)
{
- case lsNone: getScatterPlotData(scatterData); break;
- case lsLine: getLinePlotData(lineData, scatterData); break;
- case lsStepLeft: getStepLeftPlotData(lineData, scatterData); break;
- case lsStepRight: getStepRightPlotData(lineData, scatterData); break;
- case lsStepCenter: getStepCenterPlotData(lineData, scatterData); break;
- case lsImpulse: getImpulsePlotData(lineData, scatterData); break;
+ case lsNone: lines->clear(); break;
+ case lsLine: *lines = dataToLines(lineData); break;
+ case lsStepLeft: *lines = dataToStepLeftLines(lineData); break;
+ case lsStepRight: *lines = dataToStepRightLines(lineData); break;
+ case lsStepCenter: *lines = dataToStepCenterLines(lineData); break;
+ case lsImpulse: *lines = dataToImpulseLines(lineData); break;
}
}
/*! \internal
-
- If line style is \ref lsNone and the scatter style's shape is not \ref QCPScatterStyle::ssNone,
- this function serves at providing the visible data points in \a scatterData, so the \ref
- drawScatterPlot function can draw the scatter points accordingly.
-
- If line style is not \ref lsNone, this function is not called and the data for the scatter points
- are (if needed) calculated inside the corresponding other "get(...)PlotData" functions.
-
- \see drawScatterPlot
+
+ This method retrieves an optimized set of data points via \ref getOptimizedScatterData and then
+ converts them to pixel coordinates. The resulting points are returned in \a scatters, and can be
+ passed to \ref drawScatterPlot.
+
+ \a dataRange specifies the beginning and ending data indices that will be taken into account for
+ conversion. In this function, the specified range may exceed the total data bounds without harm:
+ a correspondingly trimmed data range will be used. This takes the burden off the user of this
+ function to check for valid indices in \a dataRange, e.g. when extending ranges coming from \ref
+ getDataSegments.
*/
-void QCPGraph::getScatterPlotData(QVector<QCPData> *scatterData) const
+void QCPGraph::getScatters(QVector<QPointF> *scatters, const QCPDataRange &dataRange) const
{
- getPreparedData(0, scatterData);
+ if (!scatters) return;
+ QCPAxis *keyAxis = mKeyAxis.data();
+ QCPAxis *valueAxis = mValueAxis.data();
+ if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; scatters->clear(); return; }
+
+ QCPGraphDataContainer::const_iterator begin, end;
+ getVisibleDataBounds(begin, end, dataRange);
+ if (begin == end)
+ {
+ scatters->clear();
+ return;
+ }
+
+ QVector<QCPGraphData> data;
+ getOptimizedScatterData(&data, begin, end);
+ scatters->resize(data.size());
+ if (keyAxis->orientation() == Qt::Vertical)
+ {
+ for (int i=0; i<data.size(); ++i)
+ {
+ if (!qIsNaN(data.at(i).value))
+ {
+ (*scatters)[i].setX(valueAxis->coordToPixel(data.at(i).value));
+ (*scatters)[i].setY(keyAxis->coordToPixel(data.at(i).key));
+ }
+ }
+ } else
+ {
+ for (int i=0; i<data.size(); ++i)
+ {
+ if (!qIsNaN(data.at(i).value))
+ {
+ (*scatters)[i].setX(keyAxis->coordToPixel(data.at(i).key));
+ (*scatters)[i].setY(valueAxis->coordToPixel(data.at(i).value));
+ }
+ }
+ }
}
/*! \internal
-
- Places the raw data points needed for a normal linearly connected graph in \a linePixelData.
- As for all plot data retrieval functions, \a scatterData just contains all unaltered data (scatter)
- points that are visible for drawing scatter points, if necessary. If drawing scatter points is
- disabled (i.e. the scatter style's shape is \ref QCPScatterStyle::ssNone), pass 0 as \a
- scatterData, and the function will skip filling the vector.
+ Takes raw data points in plot coordinates as \a data, and returns a vector containing pixel
+ coordinate points which are suitable for drawing the line style \ref lsLine.
- \see drawLinePlot
+ The source of \a data is usually \ref getOptimizedLineData, and this method is called in \a
+ getLines if the line style is set accordingly.
+
+ \see dataToStepLeftLines, dataToStepRightLines, dataToStepCenterLines, dataToImpulseLines, getLines, drawLinePlot
*/
-void QCPGraph::getLinePlotData(QVector<QPointF> *linePixelData, QVector<QCPData> *scatterData) const
+QVector<QPointF> QCPGraph::dataToLines(const QVector<QCPGraphData> &data) const
{
+ QVector<QPointF> result;
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
- if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
- if (!linePixelData) { qDebug() << Q_FUNC_INFO << "null pointer passed as linePixelData"; return; }
-
- QVector<QCPData> lineData;
- getPreparedData(&lineData, scatterData);
- linePixelData->reserve(lineData.size()+2); // added 2 to reserve memory for lower/upper fill base points that might be needed for fill
- linePixelData->resize(lineData.size());
+ if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return result; }
+
+ result.reserve(data.size()+2); // added 2 to reserve memory for lower/upper fill base points that might be needed for fill
+ result.resize(data.size());
- // transform lineData points to pixels:
+ // transform data points to pixels:
if (keyAxis->orientation() == Qt::Vertical)
{
- for (int i=0; i<lineData.size(); ++i)
+ for (int i=0; i<data.size(); ++i)
{
- (*linePixelData)[i].setX(valueAxis->coordToPixel(lineData.at(i).value));
- (*linePixelData)[i].setY(keyAxis->coordToPixel(lineData.at(i).key));
+ result[i].setX(valueAxis->coordToPixel(data.at(i).value));
+ result[i].setY(keyAxis->coordToPixel(data.at(i).key));
}
} else // key axis is horizontal
{
- for (int i=0; i<lineData.size(); ++i)
+ for (int i=0; i<data.size(); ++i)
{
- (*linePixelData)[i].setX(keyAxis->coordToPixel(lineData.at(i).key));
- (*linePixelData)[i].setY(valueAxis->coordToPixel(lineData.at(i).value));
+ result[i].setX(keyAxis->coordToPixel(data.at(i).key));
+ result[i].setY(valueAxis->coordToPixel(data.at(i).value));
}
}
+ return result;
}
-/*!
- \internal
- Places the raw data points needed for a step plot with left oriented steps in \a lineData.
+/*! \internal
- As for all plot data retrieval functions, \a scatterData just contains all unaltered data (scatter)
- points that are visible for drawing scatter points, if necessary. If drawing scatter points is
- disabled (i.e. the scatter style's shape is \ref QCPScatterStyle::ssNone), pass 0 as \a
- scatterData, and the function will skip filling the vector.
+ Takes raw data points in plot coordinates as \a data, and returns a vector containing pixel
+ coordinate points which are suitable for drawing the line style \ref lsStepLeft.
- \see drawLinePlot
+ The source of \a data is usually \ref getOptimizedLineData, and this method is called in \a
+ getLines if the line style is set accordingly.
+
+ \see dataToLines, dataToStepRightLines, dataToStepCenterLines, dataToImpulseLines, getLines, drawLinePlot
*/
-void QCPGraph::getStepLeftPlotData(QVector<QPointF> *linePixelData, QVector<QCPData> *scatterData) const
+QVector<QPointF> QCPGraph::dataToStepLeftLines(const QVector<QCPGraphData> &data) const
{
+ QVector<QPointF> result;
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
- if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
- if (!linePixelData) { qDebug() << Q_FUNC_INFO << "null pointer passed as lineData"; return; }
+ if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return result; }
- QVector<QCPData> lineData;
- getPreparedData(&lineData, scatterData);
- linePixelData->reserve(lineData.size()*2+2); // added 2 to reserve memory for lower/upper fill base points that might be needed for fill
- linePixelData->resize(lineData.size()*2);
+ result.reserve(data.size()*2+2); // added 2 to reserve memory for lower/upper fill base points that might be needed for fill
+ result.resize(data.size()*2);
- // calculate steps from lineData and transform to pixel coordinates:
+ // calculate steps from data and transform to pixel coordinates:
if (keyAxis->orientation() == Qt::Vertical)
{
- double lastValue = valueAxis->coordToPixel(lineData.first().value);
- double key;
- for (int i=0; i<lineData.size(); ++i)
+ double lastValue = valueAxis->coordToPixel(data.first().value);
+ for (int i=0; i<data.size(); ++i)
{
- key = keyAxis->coordToPixel(lineData.at(i).key);
- (*linePixelData)[i*2+0].setX(lastValue);
- (*linePixelData)[i*2+0].setY(key);
- lastValue = valueAxis->coordToPixel(lineData.at(i).value);
- (*linePixelData)[i*2+1].setX(lastValue);
- (*linePixelData)[i*2+1].setY(key);
+ const double key = keyAxis->coordToPixel(data.at(i).key);
+ result[i*2+0].setX(lastValue);
+ result[i*2+0].setY(key);
+ lastValue = valueAxis->coordToPixel(data.at(i).value);
+ result[i*2+1].setX(lastValue);
+ result[i*2+1].setY(key);
}
} else // key axis is horizontal
{
- double lastValue = valueAxis->coordToPixel(lineData.first().value);
- double key;
- for (int i=0; i<lineData.size(); ++i)
+ double lastValue = valueAxis->coordToPixel(data.first().value);
+ for (int i=0; i<data.size(); ++i)
{
- key = keyAxis->coordToPixel(lineData.at(i).key);
- (*linePixelData)[i*2+0].setX(key);
- (*linePixelData)[i*2+0].setY(lastValue);
- lastValue = valueAxis->coordToPixel(lineData.at(i).value);
- (*linePixelData)[i*2+1].setX(key);
- (*linePixelData)[i*2+1].setY(lastValue);
+ const double key = keyAxis->coordToPixel(data.at(i).key);
+ result[i*2+0].setX(key);
+ result[i*2+0].setY(lastValue);
+ lastValue = valueAxis->coordToPixel(data.at(i).value);
+ result[i*2+1].setX(key);
+ result[i*2+1].setY(lastValue);
}
}
+ return result;
}
-/*!
- \internal
- Places the raw data points needed for a step plot with right oriented steps in \a lineData.
+/*! \internal
- As for all plot data retrieval functions, \a scatterData just contains all unaltered data (scatter)
- points that are visible for drawing scatter points, if necessary. If drawing scatter points is
- disabled (i.e. the scatter style's shape is \ref QCPScatterStyle::ssNone), pass 0 as \a
- scatterData, and the function will skip filling the vector.
+ Takes raw data points in plot coordinates as \a data, and returns a vector containing pixel
+ coordinate points which are suitable for drawing the line style \ref lsStepRight.
- \see drawLinePlot
+ The source of \a data is usually \ref getOptimizedLineData, and this method is called in \a
+ getLines if the line style is set accordingly.
+
+ \see dataToLines, dataToStepLeftLines, dataToStepCenterLines, dataToImpulseLines, getLines, drawLinePlot
*/
-void QCPGraph::getStepRightPlotData(QVector<QPointF> *linePixelData, QVector<QCPData> *scatterData) const
+QVector<QPointF> QCPGraph::dataToStepRightLines(const QVector<QCPGraphData> &data) const
{
+ QVector<QPointF> result;
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
- if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
- if (!linePixelData) { qDebug() << Q_FUNC_INFO << "null pointer passed as lineData"; return; }
+ if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return result; }
- QVector<QCPData> lineData;
- getPreparedData(&lineData, scatterData);
- linePixelData->reserve(lineData.size()*2+2); // added 2 to reserve memory for lower/upper fill base points that might be needed for fill
- linePixelData->resize(lineData.size()*2);
+ result.reserve(data.size()*2+2); // added 2 to reserve memory for lower/upper fill base points that might be needed for fill
+ result.resize(data.size()*2);
- // calculate steps from lineData and transform to pixel coordinates:
+ // calculate steps from data and transform to pixel coordinates:
if (keyAxis->orientation() == Qt::Vertical)
{
- double lastKey = keyAxis->coordToPixel(lineData.first().key);
- double value;
- for (int i=0; i<lineData.size(); ++i)
+ double lastKey = keyAxis->coordToPixel(data.first().key);
+ for (int i=0; i<data.size(); ++i)
{
- value = valueAxis->coordToPixel(lineData.at(i).value);
- (*linePixelData)[i*2+0].setX(value);
- (*linePixelData)[i*2+0].setY(lastKey);
- lastKey = keyAxis->coordToPixel(lineData.at(i).key);
- (*linePixelData)[i*2+1].setX(value);
- (*linePixelData)[i*2+1].setY(lastKey);
+ const double value = valueAxis->coordToPixel(data.at(i).value);
+ result[i*2+0].setX(value);
+ result[i*2+0].setY(lastKey);
+ lastKey = keyAxis->coordToPixel(data.at(i).key);
+ result[i*2+1].setX(value);
+ result[i*2+1].setY(lastKey);
}
} else // key axis is horizontal
{
- double lastKey = keyAxis->coordToPixel(lineData.first().key);
- double value;
- for (int i=0; i<lineData.size(); ++i)
+ double lastKey = keyAxis->coordToPixel(data.first().key);
+ for (int i=0; i<data.size(); ++i)
{
- value = valueAxis->coordToPixel(lineData.at(i).value);
- (*linePixelData)[i*2+0].setX(lastKey);
- (*linePixelData)[i*2+0].setY(value);
- lastKey = keyAxis->coordToPixel(lineData.at(i).key);
- (*linePixelData)[i*2+1].setX(lastKey);
- (*linePixelData)[i*2+1].setY(value);
+ const double value = valueAxis->coordToPixel(data.at(i).value);
+ result[i*2+0].setX(lastKey);
+ result[i*2+0].setY(value);
+ lastKey = keyAxis->coordToPixel(data.at(i).key);
+ result[i*2+1].setX(lastKey);
+ result[i*2+1].setY(value);
}
}
+ return result;
}
-/*!
- \internal
- Places the raw data points needed for a step plot with centered steps in \a lineData.
+/*! \internal
- As for all plot data retrieval functions, \a scatterData just contains all unaltered data (scatter)
- points that are visible for drawing scatter points, if necessary. If drawing scatter points is
- disabled (i.e. the scatter style's shape is \ref QCPScatterStyle::ssNone), pass 0 as \a
- scatterData, and the function will skip filling the vector.
+ Takes raw data points in plot coordinates as \a data, and returns a vector containing pixel
+ coordinate points which are suitable for drawing the line style \ref lsStepCenter.
- \see drawLinePlot
+ The source of \a data is usually \ref getOptimizedLineData, and this method is called in \a
+ getLines if the line style is set accordingly.
+
+ \see dataToLines, dataToStepLeftLines, dataToStepRightLines, dataToImpulseLines, getLines, drawLinePlot
*/
-void QCPGraph::getStepCenterPlotData(QVector<QPointF> *linePixelData, QVector<QCPData> *scatterData) const
+QVector<QPointF> QCPGraph::dataToStepCenterLines(const QVector<QCPGraphData> &data) const
{
+ QVector<QPointF> result;
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
- if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
- if (!linePixelData) { qDebug() << Q_FUNC_INFO << "null pointer passed as lineData"; return; }
+ if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return result; }
- QVector<QCPData> lineData;
- getPreparedData(&lineData, scatterData);
- linePixelData->reserve(lineData.size()*2+2); // added 2 to reserve memory for lower/upper fill base points that might be needed for fill
- linePixelData->resize(lineData.size()*2);
- // calculate steps from lineData and transform to pixel coordinates:
+ result.reserve(data.size()*2+2); // added 2 to reserve memory for lower/upper fill base points that might be needed for fill
+ result.resize(data.size()*2);
+
+ // calculate steps from data and transform to pixel coordinates:
if (keyAxis->orientation() == Qt::Vertical)
{
- double lastKey = keyAxis->coordToPixel(lineData.first().key);
- double lastValue = valueAxis->coordToPixel(lineData.first().value);
- double key;
- (*linePixelData)[0].setX(lastValue);
- (*linePixelData)[0].setY(lastKey);
- for (int i=1; i<lineData.size(); ++i)
- {
- key = (keyAxis->coordToPixel(lineData.at(i).key)+lastKey)*0.5;
- (*linePixelData)[i*2-1].setX(lastValue);
- (*linePixelData)[i*2-1].setY(key);
- lastValue = valueAxis->coordToPixel(lineData.at(i).value);
- lastKey = keyAxis->coordToPixel(lineData.at(i).key);
- (*linePixelData)[i*2+0].setX(lastValue);
- (*linePixelData)[i*2+0].setY(key);
- }
- (*linePixelData)[lineData.size()*2-1].setX(lastValue);
- (*linePixelData)[lineData.size()*2-1].setY(lastKey);
+ double lastKey = keyAxis->coordToPixel(data.first().key);
+ double lastValue = valueAxis->coordToPixel(data.first().value);
+ result[0].setX(lastValue);
+ result[0].setY(lastKey);
+ for (int i=1; i<data.size(); ++i)
+ {
+ const double key = (keyAxis->coordToPixel(data.at(i).key)+lastKey)*0.5;
+ result[i*2-1].setX(lastValue);
+ result[i*2-1].setY(key);
+ lastValue = valueAxis->coordToPixel(data.at(i).value);
+ lastKey = keyAxis->coordToPixel(data.at(i).key);
+ result[i*2+0].setX(lastValue);
+ result[i*2+0].setY(key);
+ }
+ result[data.size()*2-1].setX(lastValue);
+ result[data.size()*2-1].setY(lastKey);
} else // key axis is horizontal
{
- double lastKey = keyAxis->coordToPixel(lineData.first().key);
- double lastValue = valueAxis->coordToPixel(lineData.first().value);
- double key;
- (*linePixelData)[0].setX(lastKey);
- (*linePixelData)[0].setY(lastValue);
- for (int i=1; i<lineData.size(); ++i)
+ double lastKey = keyAxis->coordToPixel(data.first().key);
+ double lastValue = valueAxis->coordToPixel(data.first().value);
+ result[0].setX(lastKey);
+ result[0].setY(lastValue);
+ for (int i=1; i<data.size(); ++i)
{
- key = (keyAxis->coordToPixel(lineData.at(i).key)+lastKey)*0.5;
- (*linePixelData)[i*2-1].setX(key);
- (*linePixelData)[i*2-1].setY(lastValue);
- lastValue = valueAxis->coordToPixel(lineData.at(i).value);
- lastKey = keyAxis->coordToPixel(lineData.at(i).key);
- (*linePixelData)[i*2+0].setX(key);
- (*linePixelData)[i*2+0].setY(lastValue);
+ const double key = (keyAxis->coordToPixel(data.at(i).key)+lastKey)*0.5;
+ result[i*2-1].setX(key);
+ result[i*2-1].setY(lastValue);
+ lastValue = valueAxis->coordToPixel(data.at(i).value);
+ lastKey = keyAxis->coordToPixel(data.at(i).key);
+ result[i*2+0].setX(key);
+ result[i*2+0].setY(lastValue);
}
- (*linePixelData)[lineData.size()*2-1].setX(lastKey);
- (*linePixelData)[lineData.size()*2-1].setY(lastValue);
+ result[data.size()*2-1].setX(lastKey);
+ result[data.size()*2-1].setY(lastValue);
}
-
+ return result;
}
-/*!
- \internal
- Places the raw data points needed for an impulse plot in \a lineData.
+/*! \internal
- As for all plot data retrieval functions, \a scatterData just contains all unaltered data (scatter)
- points that are visible for drawing scatter points, if necessary. If drawing scatter points is
- disabled (i.e. the scatter style's shape is \ref QCPScatterStyle::ssNone), pass 0 as \a
- scatterData, and the function will skip filling the vector.
+ Takes raw data points in plot coordinates as \a data, and returns a vector containing pixel
+ coordinate points which are suitable for drawing the line style \ref lsImpulse.
- \see drawImpulsePlot
+ The source of \a data is usually \ref getOptimizedLineData, and this method is called in \a
+ getLines if the line style is set accordingly.
+
+ \see dataToLines, dataToStepLeftLines, dataToStepRightLines, dataToStepCenterLines, getLines, drawImpulsePlot
*/
-void QCPGraph::getImpulsePlotData(QVector<QPointF> *linePixelData, QVector<QCPData> *scatterData) const
+QVector<QPointF> QCPGraph::dataToImpulseLines(const QVector<QCPGraphData> &data) const
{
+ QVector<QPointF> result;
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
- if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
- if (!linePixelData) { qDebug() << Q_FUNC_INFO << "null pointer passed as linePixelData"; return; }
+ if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return result; }
- QVector<QCPData> lineData;
- getPreparedData(&lineData, scatterData);
- linePixelData->resize(lineData.size()*2); // no need to reserve 2 extra points because impulse plot has no fill
+ result.resize(data.size()*2); // no need to reserve 2 extra points because impulse plot has no fill
- // transform lineData points to pixels:
+ // transform data points to pixels:
if (keyAxis->orientation() == Qt::Vertical)
{
- double zeroPointX = valueAxis->coordToPixel(0);
- double key;
- for (int i=0; i<lineData.size(); ++i)
+ for (int i=0; i<data.size(); ++i)
{
- key = keyAxis->coordToPixel(lineData.at(i).key);
- (*linePixelData)[i*2+0].setX(zeroPointX);
- (*linePixelData)[i*2+0].setY(key);
- (*linePixelData)[i*2+1].setX(valueAxis->coordToPixel(lineData.at(i).value));
- (*linePixelData)[i*2+1].setY(key);
+ const double key = keyAxis->coordToPixel(data.at(i).key);
+ result[i*2+0].setX(valueAxis->coordToPixel(0));
+ result[i*2+0].setY(key);
+ result[i*2+1].setX(valueAxis->coordToPixel(data.at(i).value));
+ result[i*2+1].setY(key);
}
} else // key axis is horizontal
{
- double zeroPointY = valueAxis->coordToPixel(0);
- double key;
- for (int i=0; i<lineData.size(); ++i)
+ for (int i=0; i<data.size(); ++i)
{
- key = keyAxis->coordToPixel(lineData.at(i).key);
- (*linePixelData)[i*2+0].setX(key);
- (*linePixelData)[i*2+0].setY(zeroPointY);
- (*linePixelData)[i*2+1].setX(key);
- (*linePixelData)[i*2+1].setY(valueAxis->coordToPixel(lineData.at(i).value));
+ const double key = keyAxis->coordToPixel(data.at(i).key);
+ result[i*2+0].setX(key);
+ result[i*2+0].setY(valueAxis->coordToPixel(0));
+ result[i*2+1].setX(key);
+ result[i*2+1].setY(valueAxis->coordToPixel(data.at(i).value));
}
}
+ return result;
}
/*! \internal
-
- Draws the fill of the graph with the specified brush.
- If the fill is a normal fill towards the zero-value-line, only the \a lineData is required (and
- two extra points at the zero-value-line, which are added by \ref addFillBasePoints and removed by
- \ref removeFillBasePoints after the fill drawing is done).
+ Draws the fill of the graph using the specified \a painter, with the currently set brush.
- If the fill is a channel fill between this QCPGraph and another QCPGraph (mChannelFillGraph), the
- more complex polygon is calculated with the \ref getChannelFillPolygon function.
-
- \see drawLinePlot
+ \a lines contains the points of the graph line, in pixel coordinates.
+
+ If the fill is a normal fill towards the zero-value-line, only the points in \a lines are
+ required and two extra points at the zero-value-line, which are added by \ref addFillBasePoints
+ and removed by \ref removeFillBasePoints after the fill drawing is done.
+
+ On the other hand if the fill is a channel fill between this QCPGraph and another QCPGraph (\a
+ mChannelFillGraph), the more complex polygon is calculated with the \ref getChannelFillPolygon
+ function, and then drawn.
+
+ \see drawLinePlot, drawImpulsePlot, drawScatterPlot
*/
-void QCPGraph::drawFill(QCPPainter *painter, QVector<QPointF> *lineData) const
+void QCPGraph::drawFill(QCPPainter *painter, QVector<QPointF> *lines) const
{
if (mLineStyle == lsImpulse) return; // fill doesn't make sense for impulse plot
- if (mainBrush().style() == Qt::NoBrush || mainBrush().color().alpha() == 0) return;
+ if (painter->brush().style() == Qt::NoBrush || painter->brush().color().alpha() == 0) return;
applyFillAntialiasingHint(painter);
if (!mChannelFillGraph)
{
// draw base fill under graph, fill goes all the way to the zero-value-line:
- addFillBasePoints(lineData);
- painter->setPen(Qt::NoPen);
- painter->setBrush(mainBrush());
- painter->drawPolygon(QPolygonF(*lineData));
- removeFillBasePoints(lineData);
+ addFillBasePoints(lines);
+ painter->drawPolygon(QPolygonF(*lines));
+ removeFillBasePoints(lines);
} else
{
// draw channel fill between this graph and mChannelFillGraph:
- painter->setPen(Qt::NoPen);
- painter->setBrush(mainBrush());
- painter->drawPolygon(getChannelFillPolygon(lineData));
+ painter->drawPolygon(getChannelFillPolygon(lines));
}
}
/*! \internal
-
- Draws scatter symbols at every data point passed in \a scatterData. scatter symbols are independent
- of the line style and are always drawn if the scatter style's shape is not \ref
- QCPScatterStyle::ssNone. Hence, the \a scatterData vector is outputted by all "get(...)PlotData"
- functions, together with the (line style dependent) line data.
-
+
+ Draws scatter symbols at every point passed in \a scatters, given in pixel coordinates. The
+ scatters will be drawn with \a painter and have the appearance as specified in \a style.
+
\see drawLinePlot, drawImpulsePlot
*/
-void QCPGraph::drawScatterPlot(QCPPainter *painter, QVector<QCPData> *scatterData) const
+void QCPGraph::drawScatterPlot(QCPPainter *painter, const QVector<QPointF> &scatters, const QCPScatterStyle &style) const
{
- QCPAxis *keyAxis = mKeyAxis.data();
- QCPAxis *valueAxis = mValueAxis.data();
- if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
-
- // draw error bars:
- if (mErrorType != etNone)
- {
- applyErrorBarsAntialiasingHint(painter);
- painter->setPen(mErrorPen);
- if (keyAxis->orientation() == Qt::Vertical)
- {
- for (int i=0; i<scatterData->size(); ++i)
- drawError(painter, valueAxis->coordToPixel(scatterData->at(i).value), keyAxis->coordToPixel(scatterData->at(i).key), scatterData->at(i));
- } else
- {
- for (int i=0; i<scatterData->size(); ++i)
- drawError(painter, keyAxis->coordToPixel(scatterData->at(i).key), valueAxis->coordToPixel(scatterData->at(i).value), scatterData->at(i));
- }
- }
-
- // draw scatter point symbols:
applyScattersAntialiasingHint(painter);
- mScatterStyle.applyTo(painter, mPen);
- if (keyAxis->orientation() == Qt::Vertical)
- {
- for (int i=0; i<scatterData->size(); ++i)
- if (!qIsNaN(scatterData->at(i).value))
- mScatterStyle.drawShape(painter, valueAxis->coordToPixel(scatterData->at(i).value), keyAxis->coordToPixel(scatterData->at(i).key));
- } else
- {
- for (int i=0; i<scatterData->size(); ++i)
- if (!qIsNaN(scatterData->at(i).value))
- mScatterStyle.drawShape(painter, keyAxis->coordToPixel(scatterData->at(i).key), valueAxis->coordToPixel(scatterData->at(i).value));
- }
+ style.applyTo(painter, mPen);
+ for (int i=0; i<scatters.size(); ++i)
+ style.drawShape(painter, scatters.at(i).x(), scatters.at(i).y());
}
/*! \internal
- Draws line graphs from the provided data. It connects all points in \a lineData, which was
- created by one of the "get(...)PlotData" functions for line styles that require simple line
- connections between the point vector they create. These are for example \ref getLinePlotData,
- \ref getStepLeftPlotData, \ref getStepRightPlotData and \ref getStepCenterPlotData.
+ Draws lines between the points in \a lines, given in pixel coordinates.
- \see drawScatterPlot, drawImpulsePlot
+ \see drawScatterPlot, drawImpulsePlot, QCPAbstractPlottable1D::drawPolyline
*/
-void QCPGraph::drawLinePlot(QCPPainter *painter, QVector<QPointF> *lineData) const
+void QCPGraph::drawLinePlot(QCPPainter *painter, const QVector<QPointF> &lines) const
{
- // draw line of graph:
- if (mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0)
+ if (painter->pen().style() != Qt::NoPen && painter->pen().color().alpha() != 0)
{
applyDefaultAntialiasingHint(painter);
- painter->setPen(mainPen());
- painter->setBrush(Qt::NoBrush);
-
- /* Draws polyline in batches, currently not used:
- int p = 0;
- while (p < lineData->size())
- {
- int batch = qMin(25, lineData->size()-p);
- if (p != 0)
- {
- ++batch;
- --p; // to draw the connection lines between two batches
- }
- painter->drawPolyline(lineData->constData()+p, batch);
- p += batch;
- }
- */
-
- // if drawing solid line and not in PDF, use much faster line drawing instead of polyline:
- if (mParentPlot->plottingHints().testFlag(QCP::phFastPolylines) &&
- painter->pen().style() == Qt::SolidLine &&
- !painter->modes().testFlag(QCPPainter::pmVectorized) &&
- !painter->modes().testFlag(QCPPainter::pmNoCaching))
- {
- int i = 0;
- bool lastIsNan = false;
- const int lineDataSize = lineData->size();
- while (i < lineDataSize && (qIsNaN(lineData->at(i).y()) || qIsNaN(lineData->at(i).x()))) // make sure first point is not NaN
- ++i;
- ++i; // because drawing works in 1 point retrospect
- while (i < lineDataSize)
- {
- if (!qIsNaN(lineData->at(i).y()) && !qIsNaN(lineData->at(i).x())) // NaNs create a gap in the line
- {
- if (!lastIsNan)
- painter->drawLine(lineData->at(i-1), lineData->at(i));
- else
- lastIsNan = false;
- } else
- lastIsNan = true;
- ++i;
- }
- } else
- {
- int segmentStart = 0;
- int i = 0;
- const int lineDataSize = lineData->size();
- while (i < lineDataSize)
- {
- if (qIsNaN(lineData->at(i).y()) || qIsNaN(lineData->at(i).x())) // NaNs create a gap in the line
- {
- painter->drawPolyline(lineData->constData()+segmentStart, i-segmentStart); // i, because we don't want to include the current NaN point
- segmentStart = i+1;
- }
- ++i;
- }
- // draw last segment:
- painter->drawPolyline(lineData->constData()+segmentStart, lineDataSize-segmentStart);
- }
+ drawPolyline(painter, lines);
}
}
/*! \internal
-
- Draws impulses from the provided data, i.e. it connects all line pairs in \a lineData, which was
- created by \ref getImpulsePlotData.
-
- \see drawScatterPlot, drawLinePlot
+
+ Draws impulses from the provided data, i.e. it connects all line pairs in \a lines, given in
+ pixel coordinates. The \a lines necessary for impulses are generated by \ref dataToImpulseLines
+ from the regular graph data points.
+
+ \see drawLinePlot, drawScatterPlot
*/
-void QCPGraph::drawImpulsePlot(QCPPainter *painter, QVector<QPointF> *lineData) const
+void QCPGraph::drawImpulsePlot(QCPPainter *painter, const QVector<QPointF> &lines) const
{
- // draw impulses:
- if (mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0)
+ if (painter->pen().style() != Qt::NoPen && painter->pen().color().alpha() != 0)
{
applyDefaultAntialiasingHint(painter);
- QPen pen = mainPen();
- pen.setCapStyle(Qt::FlatCap); // so impulse line doesn't reach beyond zero-line
- painter->setPen(pen);
- painter->setBrush(Qt::NoBrush);
- painter->drawLines(*lineData);
+ QPen oldPen = painter->pen();
+ QPen newPen = painter->pen();
+ newPen.setCapStyle(Qt::FlatCap); // so impulse line doesn't reach beyond zero-line
+ painter->setPen(newPen);
+ painter->drawLines(lines);
+ painter->setPen(oldPen);
}
}
/*! \internal
-
- Returns the \a lineData and \a scatterData that need to be plotted for this graph taking into
- consideration the current axis ranges and, if \ref setAdaptiveSampling is enabled, local point
- densities.
-
- 0 may be passed as \a lineData or \a scatterData to indicate that the respective dataset isn't
- needed. For example, if the scatter style (\ref setScatterStyle) is \ref QCPScatterStyle::ssNone, \a
- scatterData should be 0 to prevent unnecessary calculations.
-
- This method is used by the various "get(...)PlotData" methods to get the basic working set of data.
+
+ Returns via \a lineData the data points that need to be visualized for this graph when plotting
+ graph lines, taking into consideration the currently visible axis ranges and, if \ref
+ setAdaptiveSampling is enabled, local point densities. The considered data can be restricted
+ further by \a begin and \a end, e.g. to only plot a certain segment of the data (see \ref
+ getDataSegments).
+
+ This method is used by \ref getLines to retrieve the basic working set of data.
+
+ \see getOptimizedScatterData
*/
-void QCPGraph::getPreparedData(QVector<QCPData> *lineData, QVector<QCPData> *scatterData) const
+void QCPGraph::getOptimizedLineData(QVector<QCPGraphData> *lineData, const QCPGraphDataContainer::const_iterator &begin, const QCPGraphDataContainer::const_iterator &end) const
{
+ if (!lineData) return;
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
- // get visible data range:
- QCPDataMap::const_iterator lower, upper; // note that upper is the actual upper point, and not 1 step after the upper point
- getVisibleDataBounds(lower, upper);
- if (lower == mData->constEnd() || upper == mData->constEnd())
- return;
+ if (begin == end) return;
- // count points in visible range, taking into account that we only need to count to the limit maxCount if using adaptive sampling:
+ int dataCount = end-begin;
int maxCount = std::numeric_limits<int>::max();
if (mAdaptiveSampling)
{
- int keyPixelSpan = qAbs(keyAxis->coordToPixel(lower.key())-keyAxis->coordToPixel(upper.key()));
- maxCount = 2*keyPixelSpan+2;
+ double keyPixelSpan = qAbs(keyAxis->coordToPixel(begin->key)-keyAxis->coordToPixel((end-1)->key));
+ if (2*keyPixelSpan+2 < (double)std::numeric_limits<int>::max())
+ maxCount = 2*keyPixelSpan+2;
}
- int dataCount = countDataInBounds(lower, upper, maxCount);
if (mAdaptiveSampling && dataCount >= maxCount) // use adaptive sampling only if there are at least two points per pixel on average
{
- if (lineData)
- {
- QCPDataMap::const_iterator it = lower;
- QCPDataMap::const_iterator upperEnd = upper+1;
- double minValue = it.value().value;
- double maxValue = it.value().value;
- QCPDataMap::const_iterator currentIntervalFirstPoint = it;
- int reversedFactor = keyAxis->rangeReversed() != (keyAxis->orientation()==Qt::Vertical) ? -1 : 1; // is used to calculate keyEpsilon pixel into the correct direction
- int reversedRound = keyAxis->rangeReversed() != (keyAxis->orientation()==Qt::Vertical) ? 1 : 0; // is used to switch between floor (normal) and ceil (reversed) rounding of currentIntervalStartKey
- double currentIntervalStartKey = keyAxis->pixelToCoord((int)(keyAxis->coordToPixel(lower.key())+reversedRound));
- double lastIntervalEndKey = currentIntervalStartKey;
- double keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor)); // interval of one pixel on screen when mapped to plot key coordinates
- bool keyEpsilonVariable = keyAxis->scaleType() == QCPAxis::stLogarithmic; // indicates whether keyEpsilon needs to be updated after every interval (for log axes)
- int intervalDataCount = 1;
- ++it; // advance iterator to second data point because adaptive sampling works in 1 point retrospect
- while (it != upperEnd)
+ QCPGraphDataContainer::const_iterator it = begin;
+ double minValue = it->value;
+ double maxValue = it->value;
+ QCPGraphDataContainer::const_iterator currentIntervalFirstPoint = it;
+ int reversedFactor = keyAxis->pixelOrientation(); // is used to calculate keyEpsilon pixel into the correct direction
+ int reversedRound = reversedFactor==-1 ? 1 : 0; // is used to switch between floor (normal) and ceil (reversed) rounding of currentIntervalStartKey
+ double currentIntervalStartKey = keyAxis->pixelToCoord((int)(keyAxis->coordToPixel(begin->key)+reversedRound));
+ double lastIntervalEndKey = currentIntervalStartKey;
+ double keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor)); // interval of one pixel on screen when mapped to plot key coordinates
+ bool keyEpsilonVariable = keyAxis->scaleType() == QCPAxis::stLogarithmic; // indicates whether keyEpsilon needs to be updated after every interval (for log axes)
+ int intervalDataCount = 1;
+ ++it; // advance iterator to second data point because adaptive sampling works in 1 point retrospect
+ while (it != end)
+ {
+ if (it->key < currentIntervalStartKey+keyEpsilon) // data point is still within same pixel, so skip it and expand value span of this cluster if necessary
{
- if (it.key() < currentIntervalStartKey+keyEpsilon) // data point is still within same pixel, so skip it and expand value span of this cluster if necessary
- {
- if (it.value().value < minValue)
- minValue = it.value().value;
- else if (it.value().value > maxValue)
- maxValue = it.value().value;
- ++intervalDataCount;
- } else // new pixel interval started
+ if (it->value < minValue)
+ minValue = it->value;
+ else if (it->value > maxValue)
+ maxValue = it->value;
+ ++intervalDataCount;
+ } else // new pixel interval started
+ {
+ if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them to a cluster
{
- if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them to a cluster
- {
- if (lastIntervalEndKey < currentIntervalStartKey-keyEpsilon) // last point is further away, so first point of this cluster must be at a real data point
- lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.2, currentIntervalFirstPoint.value().value));
- lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.25, minValue));
- lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.75, maxValue));
- 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
- lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.8, (it-1).value().value));
- } else
- lineData->append(QCPData(currentIntervalFirstPoint.key(), currentIntervalFirstPoint.value().value));
- lastIntervalEndKey = (it-1).value().key;
- minValue = it.value().value;
- maxValue = it.value().value;
- currentIntervalFirstPoint = it;
- currentIntervalStartKey = keyAxis->pixelToCoord((int)(keyAxis->coordToPixel(it.key())+reversedRound));
- if (keyEpsilonVariable)
- keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor));
- intervalDataCount = 1;
- }
- ++it;
+ if (lastIntervalEndKey < currentIntervalStartKey-keyEpsilon) // last point is further away, so first point of this cluster must be at a real data point
+ lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.2, currentIntervalFirstPoint->value));
+ lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.25, minValue));
+ lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.75, maxValue));
+ 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
+ lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.8, (it-1)->value));
+ } else
+ lineData->append(QCPGraphData(currentIntervalFirstPoint->key, currentIntervalFirstPoint->value));
+ lastIntervalEndKey = (it-1)->key;
+ minValue = it->value;
+ maxValue = it->value;
+ currentIntervalFirstPoint = it;
+ currentIntervalStartKey = keyAxis->pixelToCoord((int)(keyAxis->coordToPixel(it->key)+reversedRound));
+ if (keyEpsilonVariable)
+ keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor));
+ intervalDataCount = 1;
}
- // handle last interval:
- if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them to a cluster
- {
- if (lastIntervalEndKey < currentIntervalStartKey-keyEpsilon) // last point wasn't a cluster, so first point of this cluster must be at a real data point
- lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.2, currentIntervalFirstPoint.value().value));
- lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.25, minValue));
- lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.75, maxValue));
- } else
- lineData->append(QCPData(currentIntervalFirstPoint.key(), currentIntervalFirstPoint.value().value));
+ ++it;
}
+ // handle last interval:
+ if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them to a cluster
+ {
+ if (lastIntervalEndKey < currentIntervalStartKey-keyEpsilon) // last point wasn't a cluster, so first point of this cluster must be at a real data point
+ lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.2, currentIntervalFirstPoint->value));
+ lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.25, minValue));
+ lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.75, maxValue));
+ } else
+ lineData->append(QCPGraphData(currentIntervalFirstPoint->key, currentIntervalFirstPoint->value));
- if (scatterData)
- {
- double valueMaxRange = valueAxis->range().upper;
- double valueMinRange = valueAxis->range().lower;
- QCPDataMap::const_iterator it = lower;
- QCPDataMap::const_iterator upperEnd = upper+1;
- double minValue = it.value().value;
- double maxValue = it.value().value;
- QCPDataMap::const_iterator minValueIt = it;
- QCPDataMap::const_iterator maxValueIt = it;
- QCPDataMap::const_iterator currentIntervalStart = it;
- int reversedFactor = keyAxis->rangeReversed() ? -1 : 1; // is used to calculate keyEpsilon pixel into the correct direction
- int reversedRound = keyAxis->rangeReversed() ? 1 : 0; // is used to switch between floor (normal) and ceil (reversed) rounding of currentIntervalStartKey
- double currentIntervalStartKey = keyAxis->pixelToCoord((int)(keyAxis->coordToPixel(lower.key())+reversedRound));
- double keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor)); // interval of one pixel on screen when mapped to plot key coordinates
- bool keyEpsilonVariable = keyAxis->scaleType() == QCPAxis::stLogarithmic; // indicates whether keyEpsilon needs to be updated after every interval (for log axes)
- int intervalDataCount = 1;
- ++it; // advance iterator to second data point because adaptive sampling works in 1 point retrospect
- while (it != upperEnd)
- {
- if (it.key() < currentIntervalStartKey+keyEpsilon) // data point is still within same pixel, so skip it and expand value span of this pixel if necessary
- {
- if (it.value().value < minValue && it.value().value > valueMinRange && it.value().value < valueMaxRange)
- {
- minValue = it.value().value;
- minValueIt = it;
- } else if (it.value().value > maxValue && it.value().value > valueMinRange && it.value().value < valueMaxRange)
- {
- maxValue = it.value().value;
- maxValueIt = it;
- }
- ++intervalDataCount;
- } else // new pixel started
- {
- if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them
- {
- // determine value pixel span and add as many points in interval to maintain certain vertical data density (this is specific to scatter plot):
- double valuePixelSpan = qAbs(valueAxis->coordToPixel(minValue)-valueAxis->coordToPixel(maxValue));
- int dataModulo = qMax(1, qRound(intervalDataCount/(valuePixelSpan/4.0))); // approximately every 4 value pixels one data point on average
- QCPDataMap::const_iterator intervalIt = currentIntervalStart;
- int c = 0;
- while (intervalIt != it)
- {
- if ((c % dataModulo == 0 || intervalIt == minValueIt || intervalIt == maxValueIt) && intervalIt.value().value > valueMinRange && intervalIt.value().value < valueMaxRange)
- scatterData->append(intervalIt.value());
- ++c;
- ++intervalIt;
- }
- } else if (currentIntervalStart.value().value > valueMinRange && currentIntervalStart.value().value < valueMaxRange)
- scatterData->append(currentIntervalStart.value());
- minValue = it.value().value;
- maxValue = it.value().value;
- currentIntervalStart = it;
- currentIntervalStartKey = keyAxis->pixelToCoord((int)(keyAxis->coordToPixel(it.key())+reversedRound));
- if (keyEpsilonVariable)
- keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor));
- intervalDataCount = 1;
- }
- ++it;
- }
- // handle last interval:
- if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them
- {
- // determine value pixel span and add as many points in interval to maintain certain vertical data density (this is specific to scatter plot):
- double valuePixelSpan = qAbs(valueAxis->coordToPixel(minValue)-valueAxis->coordToPixel(maxValue));
- int dataModulo = qMax(1, qRound(intervalDataCount/(valuePixelSpan/4.0))); // approximately every 4 value pixels one data point on average
- QCPDataMap::const_iterator intervalIt = currentIntervalStart;
- int c = 0;
- while (intervalIt != it)
- {
- if ((c % dataModulo == 0 || intervalIt == minValueIt || intervalIt == maxValueIt) && intervalIt.value().value > valueMinRange && intervalIt.value().value < valueMaxRange)
- scatterData->append(intervalIt.value());
- ++c;
- ++intervalIt;
- }
- } else if (currentIntervalStart.value().value > valueMinRange && currentIntervalStart.value().value < valueMaxRange)
- scatterData->append(currentIntervalStart.value());
- }
- } else // don't use adaptive sampling algorithm, transfer points one-to-one from the map into the output parameters
- {
- QVector<QCPData> *dataVector = 0;
- if (lineData)
- dataVector = lineData;
- else if (scatterData)
- dataVector = scatterData;
- if (dataVector)
- {
- QCPDataMap::const_iterator it = lower;
- QCPDataMap::const_iterator upperEnd = upper+1;
- dataVector->reserve(dataCount+2); // +2 for possible fill end points
- while (it != upperEnd)
- {
- dataVector->append(it.value());
- ++it;
- }
+ } else // don't use adaptive sampling algorithm, transfer points one-to-one from the data container into the output
+ {
+ QCPGraphDataContainer::const_iterator it = begin;
+ lineData->reserve(dataCount+2); // +2 for possible fill end points
+ while (it != end)
+ {
+ lineData->append(*it);
+ ++it;
}
- if (lineData && scatterData)
- *scatterData = *dataVector;
}
}
-/*! \internal
-
- called by the scatter drawing function (\ref drawScatterPlot) to draw the error bars on one data
- point. \a x and \a y pixel positions of the data point are passed since they are already known in
- pixel coordinates in the drawing function, so we save some extra coordToPixel transforms here. \a
- data is therefore only used for the errors, not key and value.
+/*! \internal
+
+ Returns via \a scatterData the data points that need to be visualized for this graph when
+ plotting scatter points, taking into consideration the currently visible axis ranges and, if \ref
+ setAdaptiveSampling is enabled, local point densities. The considered data can be restricted
+ further by \a begin and \a end, e.g. to only plot a certain segment of the data (see \ref
+ getDataSegments).
+
+ This method is used by \ref getScatters to retrieve the basic working set of data.
+
+ \see getOptimizedLineData
*/
-void QCPGraph::drawError(QCPPainter *painter, double x, double y, const QCPData &data) const
+void QCPGraph::getOptimizedScatterData(QVector<QCPGraphData> *scatterData, QCPGraphDataContainer::const_iterator begin, QCPGraphDataContainer::const_iterator end) const
{
- if (qIsNaN(data.value))
- return;
+ if (!scatterData) return;
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
- double a, b; // positions of error bar bounds in pixels
- double barWidthHalf = mErrorBarSize*0.5;
- double skipSymbolMargin = mScatterStyle.size(); // pixels left blank per side, when mErrorBarSkipSymbol is true
-
- if (keyAxis->orientation() == Qt::Vertical)
+ const int scatterModulo = mScatterSkip+1;
+ const bool doScatterSkip = mScatterSkip > 0;
+ int beginIndex = begin-mDataContainer->constBegin();
+ int endIndex = end-mDataContainer->constBegin();
+ while (doScatterSkip && begin != end && beginIndex % scatterModulo != 0) // advance begin iterator to first non-skipped scatter
+ {
+ ++beginIndex;
+ ++begin;
+ }
+ if (begin == end) return;
+ int dataCount = end-begin;
+ int maxCount = std::numeric_limits<int>::max();
+ if (mAdaptiveSampling)
+ {
+ int keyPixelSpan = qAbs(keyAxis->coordToPixel(begin->key)-keyAxis->coordToPixel((end-1)->key));
+ maxCount = 2*keyPixelSpan+2;
+ }
+
+ if (mAdaptiveSampling && dataCount >= maxCount) // use adaptive sampling only if there are at least two points per pixel on average
{
- // draw key error vertically and value error horizontally
- if (mErrorType == etKey || mErrorType == etBoth)
+ double valueMaxRange = valueAxis->range().upper;
+ double valueMinRange = valueAxis->range().lower;
+ QCPGraphDataContainer::const_iterator it = begin;
+ int itIndex = beginIndex;
+ double minValue = it->value;
+ double maxValue = it->value;
+ QCPGraphDataContainer::const_iterator minValueIt = it;
+ QCPGraphDataContainer::const_iterator maxValueIt = it;
+ QCPGraphDataContainer::const_iterator currentIntervalStart = it;
+ int reversedFactor = keyAxis->pixelOrientation(); // is used to calculate keyEpsilon pixel into the correct direction
+ int reversedRound = reversedFactor==-1 ? 1 : 0; // is used to switch between floor (normal) and ceil (reversed) rounding of currentIntervalStartKey
+ double currentIntervalStartKey = keyAxis->pixelToCoord((int)(keyAxis->coordToPixel(begin->key)+reversedRound));
+ double keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor)); // interval of one pixel on screen when mapped to plot key coordinates
+ bool keyEpsilonVariable = keyAxis->scaleType() == QCPAxis::stLogarithmic; // indicates whether keyEpsilon needs to be updated after every interval (for log axes)
+ int intervalDataCount = 1;
+ // advance iterator to second (non-skipped) data point because adaptive sampling works in 1 point retrospect:
+ if (!doScatterSkip)
+ ++it;
+ else
{
- a = keyAxis->coordToPixel(data.key-data.keyErrorMinus);
- b = keyAxis->coordToPixel(data.key+data.keyErrorPlus);
- if (keyAxis->rangeReversed())
- qSwap(a,b);
- // draw spine:
- if (mErrorBarSkipSymbol)
+ itIndex += scatterModulo;
+ if (itIndex < endIndex) // make sure we didn't jump over end
+ it += scatterModulo;
+ else
{
- if (a-y > skipSymbolMargin) // don't draw spine if error is so small it's within skipSymbolmargin
- painter->drawLine(QLineF(x, a, x, y+skipSymbolMargin));
- if (y-b > skipSymbolMargin)
- painter->drawLine(QLineF(x, y-skipSymbolMargin, x, b));
- } else
- painter->drawLine(QLineF(x, a, x, b));
- // draw handles:
- painter->drawLine(QLineF(x-barWidthHalf, a, x+barWidthHalf, a));
- painter->drawLine(QLineF(x-barWidthHalf, b, x+barWidthHalf, b));
- }
- if (mErrorType == etValue || mErrorType == etBoth)
- {
- a = valueAxis->coordToPixel(data.value-data.valueErrorMinus);
- b = valueAxis->coordToPixel(data.value+data.valueErrorPlus);
- if (valueAxis->rangeReversed())
- qSwap(a,b);
- // draw spine:
- if (mErrorBarSkipSymbol)
+ it = end;
+ itIndex = endIndex;
+ }
+ }
+ // main loop over data points:
+ while (it != end)
+ {
+ if (it->key < currentIntervalStartKey+keyEpsilon) // data point is still within same pixel, so skip it and expand value span of this pixel if necessary
{
- if (x-a > skipSymbolMargin) // don't draw spine if error is so small it's within skipSymbolmargin
- painter->drawLine(QLineF(a, y, x-skipSymbolMargin, y));
- if (b-x > skipSymbolMargin)
- painter->drawLine(QLineF(x+skipSymbolMargin, y, b, y));
- } else
- painter->drawLine(QLineF(a, y, b, y));
- // draw handles:
- painter->drawLine(QLineF(a, y-barWidthHalf, a, y+barWidthHalf));
- painter->drawLine(QLineF(b, y-barWidthHalf, b, y+barWidthHalf));
- }
- } else // mKeyAxis->orientation() is Qt::Horizontal
- {
- // draw value error vertically and key error horizontally
- if (mErrorType == etKey || mErrorType == etBoth)
- {
- a = keyAxis->coordToPixel(data.key-data.keyErrorMinus);
- b = keyAxis->coordToPixel(data.key+data.keyErrorPlus);
- if (keyAxis->rangeReversed())
- qSwap(a,b);
- // draw spine:
- if (mErrorBarSkipSymbol)
+ if (it->value < minValue && it->value > valueMinRange && it->value < valueMaxRange)
+ {
+ minValue = it->value;
+ minValueIt = it;
+ } else if (it->value > maxValue && it->value > valueMinRange && it->value < valueMaxRange)
+ {
+ maxValue = it->value;
+ maxValueIt = it;
+ }
+ ++intervalDataCount;
+ } else // new pixel started
{
- if (x-a > skipSymbolMargin) // don't draw spine if error is so small it's within skipSymbolmargin
- painter->drawLine(QLineF(a, y, x-skipSymbolMargin, y));
- if (b-x > skipSymbolMargin)
- painter->drawLine(QLineF(x+skipSymbolMargin, y, b, y));
- } else
- painter->drawLine(QLineF(a, y, b, y));
- // draw handles:
- painter->drawLine(QLineF(a, y-barWidthHalf, a, y+barWidthHalf));
- painter->drawLine(QLineF(b, y-barWidthHalf, b, y+barWidthHalf));
- }
- if (mErrorType == etValue || mErrorType == etBoth)
- {
- a = valueAxis->coordToPixel(data.value-data.valueErrorMinus);
- b = valueAxis->coordToPixel(data.value+data.valueErrorPlus);
- if (valueAxis->rangeReversed())
- qSwap(a,b);
- // draw spine:
- if (mErrorBarSkipSymbol)
+ if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them
+ {
+ // determine value pixel span and add as many points in interval to maintain certain vertical data density (this is specific to scatter plot):
+ double valuePixelSpan = qAbs(valueAxis->coordToPixel(minValue)-valueAxis->coordToPixel(maxValue));
+ int dataModulo = qMax(1, qRound(intervalDataCount/(valuePixelSpan/4.0))); // approximately every 4 value pixels one data point on average
+ QCPGraphDataContainer::const_iterator intervalIt = currentIntervalStart;
+ int c = 0;
+ while (intervalIt != it)
+ {
+ if ((c % dataModulo == 0 || intervalIt == minValueIt || intervalIt == maxValueIt) && intervalIt->value > valueMinRange && intervalIt->value < valueMaxRange)
+ scatterData->append(*intervalIt);
+ ++c;
+ if (!doScatterSkip)
+ ++intervalIt;
+ else
+ intervalIt += scatterModulo; // since we know indices of "currentIntervalStart", "intervalIt" and "it" are multiples of scatterModulo, we can't accidentally jump over "it" here
+ }
+ } else if (currentIntervalStart->value > valueMinRange && currentIntervalStart->value < valueMaxRange)
+ scatterData->append(*currentIntervalStart);
+ minValue = it->value;
+ maxValue = it->value;
+ currentIntervalStart = it;
+ currentIntervalStartKey = keyAxis->pixelToCoord((int)(keyAxis->coordToPixel(it->key)+reversedRound));
+ if (keyEpsilonVariable)
+ keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor));
+ intervalDataCount = 1;
+ }
+ // advance to next data point:
+ if (!doScatterSkip)
+ ++it;
+ else
{
- if (a-y > skipSymbolMargin) // don't draw spine if error is so small it's within skipSymbolmargin
- painter->drawLine(QLineF(x, a, x, y+skipSymbolMargin));
- if (y-b > skipSymbolMargin)
- painter->drawLine(QLineF(x, y-skipSymbolMargin, x, b));
- } else
- painter->drawLine(QLineF(x, a, x, b));
- // draw handles:
- painter->drawLine(QLineF(x-barWidthHalf, a, x+barWidthHalf, a));
- painter->drawLine(QLineF(x-barWidthHalf, b, x+barWidthHalf, b));
+ itIndex += scatterModulo;
+ if (itIndex < endIndex) // make sure we didn't jump over end
+ it += scatterModulo;
+ else
+ {
+ it = end;
+ itIndex = endIndex;
+ }
+ }
}
- }
-}
-
-/*! \internal
-
- called by \ref getPreparedData to determine which data (key) range is visible at the current key
- axis range setting, so only that needs to be processed.
-
- \a lower returns an iterator to the lowest data point that needs to be taken into account when
- plotting. Note that in order to get a clean plot all the way to the edge of the axis rect, \a
- lower may still be just outside the visible range.
-
- \a upper returns an iterator to the highest data point. Same as before, \a upper may also lie
- just outside of the visible range.
-
- if the graph contains no data, both \a lower and \a upper point to constEnd.
-*/
-void QCPGraph::getVisibleDataBounds(QCPDataMap::const_iterator &lower, QCPDataMap::const_iterator &upper) const
-{
- if (!mKeyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; }
- if (mData->isEmpty())
+ // handle last interval:
+ if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them
+ {
+ // determine value pixel span and add as many points in interval to maintain certain vertical data density (this is specific to scatter plot):
+ double valuePixelSpan = qAbs(valueAxis->coordToPixel(minValue)-valueAxis->coordToPixel(maxValue));
+ int dataModulo = qMax(1, qRound(intervalDataCount/(valuePixelSpan/4.0))); // approximately every 4 value pixels one data point on average
+ QCPGraphDataContainer::const_iterator intervalIt = currentIntervalStart;
+ int intervalItIndex = intervalIt-mDataContainer->constBegin();
+ int c = 0;
+ while (intervalIt != it)
+ {
+ if ((c % dataModulo == 0 || intervalIt == minValueIt || intervalIt == maxValueIt) && intervalIt->value > valueMinRange && intervalIt->value < valueMaxRange)
+ scatterData->append(*intervalIt);
+ ++c;
+ if (!doScatterSkip)
+ ++intervalIt;
+ 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:
+ {
+ intervalItIndex += scatterModulo;
+ if (intervalItIndex < itIndex)
+ intervalIt += scatterModulo;
+ else
+ {
+ intervalIt = it;
+ intervalItIndex = itIndex;
+ }
+ }
+ }
+ } else if (currentIntervalStart->value > valueMinRange && currentIntervalStart->value < valueMaxRange)
+ scatterData->append(*currentIntervalStart);
+
+ } else // don't use adaptive sampling algorithm, transfer points one-to-one from the data container into the output
{
- lower = mData->constEnd();
- upper = mData->constEnd();
- return;
+ QCPGraphDataContainer::const_iterator it = begin;
+ int itIndex = beginIndex;
+ scatterData->reserve(dataCount);
+ while (it != end)
+ {
+ scatterData->append(*it);
+ // advance to next data point:
+ if (!doScatterSkip)
+ ++it;
+ else
+ {
+ itIndex += scatterModulo;
+ if (itIndex < endIndex)
+ it += scatterModulo;
+ else
+ {
+ it = end;
+ itIndex = endIndex;
+ }
+ }
+ }
}
-
- // get visible data range as QMap iterators
- QCPDataMap::const_iterator lbound = static_cast<const QCPDataMap*>(mData)->lowerBound(mKeyAxis.data()->range().lower);
- QCPDataMap::const_iterator ubound = static_cast<const QCPDataMap*>(mData)->upperBound(mKeyAxis.data()->range().upper);
- bool lowoutlier = lbound != mData->constBegin(); // indicates whether there exist points below axis range
- bool highoutlier = ubound != mData->constEnd(); // indicates whether there exist points above axis range
-
- lower = (lowoutlier ? lbound-1 : lbound); // data point range that will be actually drawn
- upper = (highoutlier ? ubound : ubound-1); // data point range that will be actually drawn
}
-/*! \internal
-
- Counts the number of data points between \a lower and \a upper (including them), up to a maximum
- of \a maxCount.
-
- This function is used by \ref getPreparedData to determine whether adaptive sampling shall be
- used (if enabled via \ref setAdaptiveSampling) or not. This is also why counting of data points
- only needs to be done until \a maxCount is reached, which should be set to the number of data
- points at which adaptive sampling sets in.
+/*!
+ This method outputs the currently visible data range via \a begin and \a end. The returned range
+ will also never exceed \a rangeRestriction.
+
+ This method takes into account that the drawing of data lines at the axis rect border always
+ requires the points just outside the visible axis range. So \a begin and \a end may actually
+ indicate a range that contains one additional data point to the left and right of the visible
+ axis range.
*/
-int QCPGraph::countDataInBounds(const QCPDataMap::const_iterator &lower, const QCPDataMap::const_iterator &upper, int maxCount) const
+void QCPGraph::getVisibleDataBounds(QCPGraphDataContainer::const_iterator &begin, QCPGraphDataContainer::const_iterator &end, const QCPDataRange &rangeRestriction) const
{
- if (upper == mData->constEnd() && lower == mData->constEnd())
- return 0;
- QCPDataMap::const_iterator it = lower;
- int count = 1;
- while (it != upper && count < maxCount)
+ if (rangeRestriction.isEmpty())
{
- ++it;
- ++count;
+ end = mDataContainer->constEnd();
+ begin = end;
+ } else
+ {
+ QCPAxis *keyAxis = mKeyAxis.data();
+ QCPAxis *valueAxis = mValueAxis.data();
+ if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
+ // get visible data range:
+ begin = mDataContainer->findBegin(keyAxis->range().lower);
+ end = mDataContainer->findEnd(keyAxis->range().upper);
+ // limit lower/upperEnd to rangeRestriction:
+ mDataContainer->limitIteratorsToDataRange(begin, end, rangeRestriction); // this also ensures rangeRestriction outside data bounds doesn't break anything
}
- return count;
}
/*! \internal
- The line data vector generated by e.g. getLinePlotData contains only the line that connects the
- data points. If the graph needs to be filled, two additional points need to be added at the
+ The line vector generated by e.g. \ref getLines describes only the line that connects the data
+ points. If the graph needs to be filled, two additional points need to be added at the
value-zero-line in the lower and upper key positions of the graph. This function calculates these
points and adds them to the end of \a lineData. Since the fill is typically drawn before the line
stroke, these added points need to be removed again after the fill is done, with the
removeFillBasePoints function.
-
- The expanding of \a lineData by two points will not cause unnecessary memory reallocations,
- because the data vector generation functions (getLinePlotData etc.) reserve two extra points when
- they allocate memory for \a lineData.
+
+ The expanding of \a lines by two points will not cause unnecessary memory reallocations, because
+ the data vector generation functions (e.g. \ref getLines) reserve two extra points when they
+ allocate memory for \a lines.
\see removeFillBasePoints, lowerFillBasePoint, upperFillBasePoint
*/
-void QCPGraph::addFillBasePoints(QVector<QPointF> *lineData) const
+void QCPGraph::addFillBasePoints(QVector<QPointF> *lines) const
{
if (!mKeyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; }
+ if (!lines) { qDebug() << Q_FUNC_INFO << "passed null as lineData"; return; }
+ if (lines->isEmpty()) return;
// append points that close the polygon fill at the key axis:
if (mKeyAxis.data()->orientation() == Qt::Vertical)
{
- *lineData << upperFillBasePoint(lineData->last().y());
- *lineData << lowerFillBasePoint(lineData->first().y());
+ *lines << upperFillBasePoint(lines->last().y());
+ *lines << lowerFillBasePoint(lines->first().y());
} else
{
- *lineData << upperFillBasePoint(lineData->last().x());
- *lineData << lowerFillBasePoint(lineData->first().x());
+ *lines << upperFillBasePoint(lines->last().x());
+ *lines << lowerFillBasePoint(lines->first().x());
}
}
/*! \internal
- removes the two points from \a lineData that were added by \ref addFillBasePoints.
+ removes the two points from \a lines that were added by \ref addFillBasePoints.
\see addFillBasePoints, lowerFillBasePoint, upperFillBasePoint
*/
-void QCPGraph::removeFillBasePoints(QVector<QPointF> *lineData) const
+void QCPGraph::removeFillBasePoints(QVector<QPointF> *lines) const
{
- lineData->remove(lineData->size()-2, 2);
+ if (!lines) { qDebug() << Q_FUNC_INFO << "passed null as lineData"; return; }
+ if (lines->isEmpty()) return;
+
+ lines->remove(lines->size()-2, 2);
}
/*! \internal
@@ -16047,7 +20911,7 @@ void QCPGraph::removeFillBasePoints(QVector<QPointF> *lineData) const
infinity. So this case is handled separately by just closing the fill polygon on the axis which
lies in the direction towards the zero value.
- \a lowerKey will be the key (in pixels) of the returned point. Depending on whether the key
+ \a lowerKey will be the the key (in pixels) of the returned point. Depending on whether the key
axis is horizontal or vertical, \a lowerKey will end up as the x or y value of the returned
point, respectively.
@@ -16112,7 +20976,7 @@ QPointF QCPGraph::lowerFillBasePoint(double lowerKey) const
negative infinity. So this case is handled separately by just closing the fill polygon on the
axis which lies in the direction towards the zero value.
- \a upperKey will be the key (in pixels) of the returned point. Depending on whether the key
+ \a upperKey will be the the key (in pixels) of the returned point. Depending on whether the key
axis is horizontal or vertical, \a upperKey will end up as the x or y value of the returned
point, respectively.
@@ -16171,14 +21035,17 @@ QPointF QCPGraph::upperFillBasePoint(double upperKey) const
/*! \internal
- Generates the polygon needed for drawing channel fills between this graph (data passed via \a
- lineData) and the graph specified by mChannelFillGraph (data generated by calling its \ref
- getPlotData function). May return an empty polygon if the key ranges have no overlap or fill
- target graph and this graph don't have same orientation (i.e. both key axes horizontal or both
- key axes vertical). For increased performance (due to implicit sharing), keep the returned
- QPolygonF const.
+ Generates the polygon needed for drawing channel fills between this graph and the graph specified
+ in \a mChannelFillGraph (see \ref setChannelFillGraph). The data points representing the line of
+ this graph in pixel coordinates must be passed in \a lines, the corresponding points of the other
+ graph are generated by calling its \ref getLines method.
+
+ This method may return an empty polygon if the key ranges of the two graphs have no overlap of if
+ they don't have the same orientation (e.g. one key axis vertical, the other horizontal). For
+ increased performance (due to implicit sharing), it is recommended to keep the returned QPolygonF
+ const.
*/
-const QPolygonF QCPGraph::getChannelFillPolygon(const QVector<QPointF> *lineData) const
+const QPolygonF QCPGraph::getChannelFillPolygon(const QVector<QPointF> *lines) const
{
if (!mChannelFillGraph)
return QPolygonF();
@@ -16191,14 +21058,14 @@ const QPolygonF QCPGraph::getChannelFillPolygon(const QVector<QPointF> *lineData
if (mChannelFillGraph.data()->mKeyAxis.data()->orientation() != keyAxis->orientation())
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)
- if (lineData->isEmpty()) return QPolygonF();
+ if (lines->isEmpty()) return QPolygonF();
QVector<QPointF> otherData;
- mChannelFillGraph.data()->getPlotData(&otherData, 0);
+ mChannelFillGraph.data()->getLines(&otherData, QCPDataRange(0, mChannelFillGraph.data()->dataCount()));
if (otherData.isEmpty()) return QPolygonF();
QVector<QPointF> thisData;
- thisData.reserve(lineData->size()+otherData.size()); // because we will join both vectors at end of this function
- for (int i=0; i<lineData->size(); ++i) // don't use the vector<<(vector), it squeezes internally, which ruins the performance tuning with reserve()
- thisData << lineData->at(i);
+ thisData.reserve(lines->size()+otherData.size()); // because we will join both vectors at end of this function
+ for (int i=0; i<lines->size(); ++i) // don't use the vector<<(vector), it squeezes internally, which ruins the performance tuning with reserve()
+ thisData << lines->at(i);
// pointers to be able to swap them, depending which data range needs cropping:
QVector<QPointF> *staticData = &thisData;
@@ -16381,72 +21248,61 @@ int QCPGraph::findIndexAboveY(const QVector<QPointF> *data, double y) const
/*! \internal
- Calculates the (minimum) distance (in pixels) the graph's representation has from the given \a
- pixelPoint in pixels. This is used to determine whether the graph was clicked or not, e.g. in
- \ref selectTest.
+ Calculates the minimum distance in pixels the graph's representation has from the given \a
+ pixelPoint. This is used to determine whether the graph was clicked or not, e.g. in \ref
+ selectTest. The closest data point to \a pixelPoint is returned in \a closestData. Note that if
+ the graph has a line representation, the returned distance may be smaller than the distance to
+ the \a closestData point, since the distance to the graph line is also taken into account.
If either the graph has no data or if the line style is \ref lsNone and the scatter style's shape
is \ref QCPScatterStyle::ssNone (i.e. there is no visual representation of the graph), returns -1.0.
*/
-double QCPGraph::pointDistance(const QPointF &pixelPoint) const
+double QCPGraph::pointDistance(const QPointF &pixelPoint, QCPGraphDataContainer::const_iterator &closestData) const
{
- if (mData->isEmpty())
+ closestData = mDataContainer->constEnd();
+ if (mDataContainer->isEmpty())
return -1.0;
if (mLineStyle == lsNone && mScatterStyle.isNone())
return -1.0;
- // calculate minimum distances to graph representation:
- if (mLineStyle == lsNone)
- {
- // no line displayed, only calculate distance to scatter points:
- QVector<QCPData> scatterData;
- getScatterPlotData(&scatterData);
- if (scatterData.size() > 0)
+ // calculate minimum distances to graph data points and find closestData iterator:
+ double minDistSqr = std::numeric_limits<double>::max();
+ // determine which key range comes into question, taking selection tolerance around pos into account:
+ double posKeyMin, posKeyMax, dummy;
+ pixelsToCoords(pixelPoint-QPointF(mParentPlot->selectionTolerance(), mParentPlot->selectionTolerance()), posKeyMin, dummy);
+ pixelsToCoords(pixelPoint+QPointF(mParentPlot->selectionTolerance(), mParentPlot->selectionTolerance()), posKeyMax, dummy);
+ if (posKeyMin > posKeyMax)
+ qSwap(posKeyMin, posKeyMax);
+ // iterate over found data points and then choose the one with the shortest distance to pos:
+ QCPGraphDataContainer::const_iterator begin = mDataContainer->findBegin(posKeyMin, true);
+ QCPGraphDataContainer::const_iterator end = mDataContainer->findEnd(posKeyMax, true);
+ for (QCPGraphDataContainer::const_iterator it=begin; it!=end; ++it)
+ {
+ const double currentDistSqr = QCPVector2D(coordsToPixels(it->key, it->value)-pixelPoint).lengthSquared();
+ if (currentDistSqr < minDistSqr)
{
- double minDistSqr = std::numeric_limits<double>::max();
- for (int i=0; i<scatterData.size(); ++i)
- {
- double currentDistSqr = QVector2D(coordsToPixels(scatterData.at(i).key, scatterData.at(i).value)-pixelPoint).lengthSquared();
- if (currentDistSqr < minDistSqr)
- minDistSqr = currentDistSqr;
- }
- return qSqrt(minDistSqr);
- } else // no data available in view to calculate distance to
- return -1.0;
- } else
+ minDistSqr = currentDistSqr;
+ closestData = it;
+ }
+ }
+
+ // calculate distance to graph line if there is one (if so, will probably be smaller than distance to closest data point):
+ if (mLineStyle != lsNone)
{
// line displayed, calculate distance to line segments:
QVector<QPointF> lineData;
- getPlotData(&lineData, 0); // unlike with getScatterPlotData we get pixel coordinates here
- if (lineData.size() > 1) // at least one line segment, compare distance to line segments
- {
- double minDistSqr = std::numeric_limits<double>::max();
- if (mLineStyle == lsImpulse)
- {
- // impulse plot differs from other line styles in that the lineData points are only pairwise connected:
- for (int i=0; i<lineData.size()-1; i+=2) // iterate pairs
- {
- double currentDistSqr = distSqrToLine(lineData.at(i), lineData.at(i+1), pixelPoint);
- if (currentDistSqr < minDistSqr)
- minDistSqr = currentDistSqr;
- }
- } else
- {
- // all other line plots (line and step) connect points directly:
- for (int i=0; i<lineData.size()-1; ++i)
- {
- double currentDistSqr = distSqrToLine(lineData.at(i), lineData.at(i+1), pixelPoint);
- if (currentDistSqr < minDistSqr)
- minDistSqr = currentDistSqr;
- }
- }
- return qSqrt(minDistSqr);
- } else if (lineData.size() > 0) // only single data point, calculate distance to that point
+ getLines(&lineData, QCPDataRange(0, dataCount()));
+ QCPVector2D p(pixelPoint);
+ const int step = mLineStyle==lsImpulse ? 2 : 1; // impulse plot differs from other line styles in that the lineData points are only pairwise connected
+ for (int i=0; i<lineData.size()-1; i+=step)
{
- return QVector2D(lineData.at(0)-pixelPoint).length();
- } else // no data available in view to calculate distance to
- return -1.0;
+ const double currentDistSqr = p.distanceSquaredToLine(lineData.at(i), lineData.at(i+1));
+ if (currentDistSqr < minDistSqr)
+ minDistSqr = currentDistSqr;
+ }
}
+
+ return qSqrt(minDistSqr);
}
/*! \internal
@@ -16471,271 +21327,85 @@ int QCPGraph::findIndexBelowY(const QVector<QPointF> *data, double y) const
}
return -1;
}
+/* end of 'src/plottables/plottable-graph.cpp' */
-/* inherits documentation from base class */
-QCPRange QCPGraph::getKeyRange(bool &foundRange, SignDomain inSignDomain) const
-{
- // just call the specialized version which takes an additional argument whether error bars
- // should also be taken into consideration for range calculation. We set this to true here.
- return getKeyRange(foundRange, inSignDomain, true);
-}
-/* inherits documentation from base class */
-QCPRange QCPGraph::getValueRange(bool &foundRange, SignDomain inSignDomain) const
-{
- // just call the specialized version which takes an additional argument whether error bars
- // should also be taken into consideration for range calculation. We set this to true here.
- return getValueRange(foundRange, inSignDomain, true);
-}
+/* including file 'src/plottables/plottable-curve.cpp', size 60009 */
+/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */
-/*! \overload
+////////////////////////////////////////////////////////////////////////////////////////////////////
+//////////////////// QCPCurveData
+////////////////////////////////////////////////////////////////////////////////////////////////////
+
+/*! \class QCPCurveData
+ \brief Holds the data of one single data point for QCPCurve.
- Allows to specify whether the error bars should be included in the range calculation.
+ The stored data is:
+ \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)
+ \li \a key: coordinate on the key axis of this curve point (this is the \a mainKey)
+ \li \a value: coordinate on the value axis of this curve point (this is the \a mainValue)
- \see getKeyRange(bool &foundRange, SignDomain inSignDomain)
-*/
-QCPRange QCPGraph::getKeyRange(bool &foundRange, SignDomain inSignDomain, bool includeErrors) const
-{
- QCPRange range;
- bool haveLower = false;
- bool haveUpper = false;
+ The container for storing multiple data points is \ref QCPCurveDataContainer. It is a typedef for
+ \ref QCPDataContainer with \ref QCPCurveData as the DataType template parameter. See the
+ documentation there for an explanation regarding the data type's generic methods.
- double current, currentErrorMinus, currentErrorPlus;
+ \see QCPCurveDataContainer
+*/
+
+/* start documentation of inline functions */
+
+/*! \fn double QCPCurveData::sortKey() const
- if (inSignDomain == sdBoth) // range may be anywhere
- {
- QCPDataMap::const_iterator it = mData->constBegin();
- while (it != mData->constEnd())
- {
- if (!qIsNaN(it.value().value))
- {
- current = it.value().key;
- currentErrorMinus = (includeErrors ? it.value().keyErrorMinus : 0);
- currentErrorPlus = (includeErrors ? it.value().keyErrorPlus : 0);
- if (current-currentErrorMinus < range.lower || !haveLower)
- {
- range.lower = current-currentErrorMinus;
- haveLower = true;
- }
- if (current+currentErrorPlus > range.upper || !haveUpper)
- {
- range.upper = current+currentErrorPlus;
- haveUpper = true;
- }
- }
- ++it;
- }
- } else if (inSignDomain == sdNegative) // range may only be in the negative sign domain
- {
- QCPDataMap::const_iterator it = mData->constBegin();
- while (it != mData->constEnd())
- {
- if (!qIsNaN(it.value().value))
- {
- current = it.value().key;
- currentErrorMinus = (includeErrors ? it.value().keyErrorMinus : 0);
- currentErrorPlus = (includeErrors ? it.value().keyErrorPlus : 0);
- if ((current-currentErrorMinus < range.lower || !haveLower) && current-currentErrorMinus < 0)
- {
- range.lower = current-currentErrorMinus;
- haveLower = true;
- }
- if ((current+currentErrorPlus > range.upper || !haveUpper) && current+currentErrorPlus < 0)
- {
- range.upper = current+currentErrorPlus;
- haveUpper = true;
- }
- if (includeErrors) // in case point is in valid sign domain but errobars stretch beyond it, we still want to geht that point.
- {
- if ((current < range.lower || !haveLower) && current < 0)
- {
- range.lower = current;
- haveLower = true;
- }
- if ((current > range.upper || !haveUpper) && current < 0)
- {
- range.upper = current;
- haveUpper = true;
- }
- }
- }
- ++it;
- }
- } else if (inSignDomain == sdPositive) // range may only be in the positive sign domain
- {
- QCPDataMap::const_iterator it = mData->constBegin();
- while (it != mData->constEnd())
- {
- if (!qIsNaN(it.value().value))
- {
- current = it.value().key;
- currentErrorMinus = (includeErrors ? it.value().keyErrorMinus : 0);
- currentErrorPlus = (includeErrors ? it.value().keyErrorPlus : 0);
- if ((current-currentErrorMinus < range.lower || !haveLower) && current-currentErrorMinus > 0)
- {
- range.lower = current-currentErrorMinus;
- haveLower = true;
- }
- if ((current+currentErrorPlus > range.upper || !haveUpper) && current+currentErrorPlus > 0)
- {
- range.upper = current+currentErrorPlus;
- haveUpper = true;
- }
- if (includeErrors) // in case point is in valid sign domain but errobars stretch beyond it, we still want to get that point.
- {
- if ((current < range.lower || !haveLower) && current > 0)
- {
- range.lower = current;
- haveLower = true;
- }
- if ((current > range.upper || !haveUpper) && current > 0)
- {
- range.upper = current;
- haveUpper = true;
- }
- }
- }
- ++it;
- }
- }
+ Returns the \a t member of this data point.
- foundRange = haveLower && haveUpper;
- return range;
-}
+ For a general explanation of what this method is good for in the context of the data container,
+ see the documentation of \ref QCPDataContainer.
+*/
-/*! \overload
+/*! \fn static QCPCurveData QCPCurveData::fromSortKey(double sortKey)
- Allows to specify whether the error bars should be included in the range calculation.
+ Returns a data point with the specified \a sortKey (assigned to the data point's \a t member).
+ All other members are set to zero.
- \see getValueRange(bool &foundRange, SignDomain inSignDomain)
+ For a general explanation of what this method is good for in the context of the data container,
+ see the documentation of \ref QCPDataContainer.
*/
-QCPRange QCPGraph::getValueRange(bool &foundRange, SignDomain inSignDomain, bool includeErrors) const
-{
- QCPRange range;
- bool haveLower = false;
- bool haveUpper = false;
-
- double current, currentErrorMinus, currentErrorPlus;
+
+/*! \fn static static bool QCPCurveData::sortKeyIsMainKey()
- if (inSignDomain == sdBoth) // range may be anywhere
- {
- QCPDataMap::const_iterator it = mData->constBegin();
- while (it != mData->constEnd())
- {
- current = it.value().value;
- if (!qIsNaN(current))
- {
- currentErrorMinus = (includeErrors ? it.value().valueErrorMinus : 0);
- currentErrorPlus = (includeErrors ? it.value().valueErrorPlus : 0);
- if (current-currentErrorMinus < range.lower || !haveLower)
- {
- range.lower = current-currentErrorMinus;
- haveLower = true;
- }
- if (current+currentErrorPlus > range.upper || !haveUpper)
- {
- range.upper = current+currentErrorPlus;
- haveUpper = true;
- }
- }
- ++it;
- }
- } else if (inSignDomain == sdNegative) // range may only be in the negative sign domain
- {
- QCPDataMap::const_iterator it = mData->constBegin();
- while (it != mData->constEnd())
- {
- current = it.value().value;
- if (!qIsNaN(current))
- {
- currentErrorMinus = (includeErrors ? it.value().valueErrorMinus : 0);
- currentErrorPlus = (includeErrors ? it.value().valueErrorPlus : 0);
- if ((current-currentErrorMinus < range.lower || !haveLower) && current-currentErrorMinus < 0)
- {
- range.lower = current-currentErrorMinus;
- haveLower = true;
- }
- if ((current+currentErrorPlus > range.upper || !haveUpper) && current+currentErrorPlus < 0)
- {
- range.upper = current+currentErrorPlus;
- haveUpper = true;
- }
- if (includeErrors) // in case point is in valid sign domain but errobars stretch beyond it, we still want to get that point.
- {
- if ((current < range.lower || !haveLower) && current < 0)
- {
- range.lower = current;
- haveLower = true;
- }
- if ((current > range.upper || !haveUpper) && current < 0)
- {
- range.upper = current;
- haveUpper = true;
- }
- }
- }
- ++it;
- }
- } else if (inSignDomain == sdPositive) // range may only be in the positive sign domain
- {
- QCPDataMap::const_iterator it = mData->constBegin();
- while (it != mData->constEnd())
- {
- current = it.value().value;
- if (!qIsNaN(current))
- {
- currentErrorMinus = (includeErrors ? it.value().valueErrorMinus : 0);
- currentErrorPlus = (includeErrors ? it.value().valueErrorPlus : 0);
- if ((current-currentErrorMinus < range.lower || !haveLower) && current-currentErrorMinus > 0)
- {
- range.lower = current-currentErrorMinus;
- haveLower = true;
- }
- if ((current+currentErrorPlus > range.upper || !haveUpper) && current+currentErrorPlus > 0)
- {
- range.upper = current+currentErrorPlus;
- haveUpper = true;
- }
- if (includeErrors) // in case point is in valid sign domain but errobars stretch beyond it, we still want to geht that point.
- {
- if ((current < range.lower || !haveLower) && current > 0)
- {
- range.lower = current;
- haveLower = true;
- }
- if ((current > range.upper || !haveUpper) && current > 0)
- {
- range.upper = current;
- haveUpper = true;
- }
- }
- }
- ++it;
- }
- }
+ Since the member \a key is the data point key coordinate and the member \a t is the data ordering
+ parameter, this method returns false.
- foundRange = haveLower && haveUpper;
- return range;
-}
-
+ For a general explanation of what this method is good for in the context of the data container,
+ see the documentation of \ref QCPDataContainer.
+*/
-////////////////////////////////////////////////////////////////////////////////////////////////////
-//////////////////// QCPCurveData
-////////////////////////////////////////////////////////////////////////////////////////////////////
+/*! \fn double QCPCurveData::mainKey() const
+
+ Returns the \a key member of this data point.
+
+ For a general explanation of what this method is good for in the context of the data container,
+ see the documentation of \ref QCPDataContainer.
+*/
-/*! \class QCPCurveData
- \brief Holds the data of one single data point for QCPCurve.
+/*! \fn double QCPCurveData::mainValue() const
- The container for storing multiple data points is \ref QCPCurveDataMap.
+ Returns the \a value member of this data point.
- The stored data is:
- \li \a t: the free parameter of the curve at this curve point (cp. the mathematical vector <em>(x(t), y(t))</em>)
- \li \a key: coordinate on the key axis of this curve point
- \li \a value: coordinate on the value axis of this curve point
+ For a general explanation of what this method is good for in the context of the data container,
+ see the documentation of \ref QCPDataContainer.
+*/
+
+/*! \fn QCPRange QCPCurveData::valueRange() const
- \see QCPCurveDataMap
+ Returns a QCPRange with both lower and upper boundary set to \a value of this data point.
+
+ For a general explanation of what this method is good for in the context of the data container,
+ see the documentation of \ref QCPDataContainer.
*/
+/* end documentation of inline functions */
+
/*!
Constructs a curve data point with t, key and value set to zero.
*/
@@ -16771,47 +21441,59 @@ QCPCurveData::QCPCurveData(double t, double key, double value) :
coordinate \a t, which defines the order of the points described by the other two coordinates \a
x and \a y.
- To plot data, assign it with the \ref setData or \ref addData functions.
+ To plot data, assign it with the \ref setData or \ref addData functions. Alternatively, you can
+ also access and modify the curve's data via the \ref data method, which returns a pointer to the
+ internal \ref QCPCurveDataContainer.
Gaps in the curve can be created by adding data points with NaN as key and value
(<tt>qQNaN()</tt> or <tt>std::numeric_limits<double>::quiet_NaN()</tt>) in between the two data points that shall be
separated.
- \section appearance Changing the appearance
+ \section qcpcurve-appearance Changing the appearance
The appearance of the curve is determined by the pen and the brush (\ref setPen, \ref setBrush).
- \section usage Usage
- Like all data representing objects in QCustomPlot, the QCPCurve is a plottable (QCPAbstractPlottable). So
- the plottable-interface of QCustomPlot applies (QCustomPlot::plottable, QCustomPlot::addPlottable, QCustomPlot::removePlottable, etc.)
+ \section qcpcurve-usage Usage
+
+ Like all data representing objects in QCustomPlot, the QCPCurve is a plottable
+ (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies
+ (QCustomPlot::plottable, QCustomPlot::removePlottable, etc.)
- Usually, you first create an instance and add it to the customPlot:
+ Usually, you first create an instance:
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpcurve-creation-1
- and then modify the properties of the newly created plottable, e.g.:
+ which registers it with the QCustomPlot instance of the passed axes. Note that this QCustomPlot instance takes
+ ownership of the plottable, so do not delete it manually but use QCustomPlot::removePlottable() instead.
+ The newly created plottable can be modified, e.g.:
\snippet documentation/doc-code-snippets/mainwindow.cpp qcpcurve-creation-2
*/
+/* start of documentation of inline functions */
+
+/*! \fn QSharedPointer<QCPCurveDataContainer> QCPCurve::data() const
+
+ Returns a shared pointer to the internal data storage of type \ref QCPCurveDataContainer. You may
+ use it to directly manipulate the data, which may be more convenient and faster than using the
+ regular \ref setData or \ref addData methods.
+*/
+
+/* end of documentation of inline functions */
+
/*!
Constructs a curve which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value
axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have
the same orientation. If either of these restrictions is violated, a corresponding message is
printed to the debug output (qDebug), the construction is not aborted, though.
- The constructed QCPCurve can be added to the plot with QCustomPlot::addPlottable, QCustomPlot
- then takes ownership of the graph.
+ The created QCPCurve is automatically registered with the QCustomPlot instance inferred from \a
+ keyAxis. This QCustomPlot instance takes ownership of the QCPCurve, so do not delete it manually
+ but use QCustomPlot::removePlottable() instead.
*/
QCPCurve::QCPCurve(QCPAxis *keyAxis, QCPAxis *valueAxis) :
- QCPAbstractPlottable(keyAxis, valueAxis)
+ QCPAbstractPlottable1D<QCPCurveData>(keyAxis, valueAxis)
{
- mData = new QCPCurveDataMap;
- mPen.setColor(Qt::blue);
- mPen.setStyle(Qt::SolidLine);
- mBrush.setColor(Qt::blue);
- mBrush.setStyle(Qt::NoBrush);
- mSelectedPen = mPen;
- mSelectedPen.setWidthF(2.5);
- mSelectedPen.setColor(QColor(80, 80, 255)); // lighter than Qt::blue of mPen
- mSelectedBrush = mBrush;
+ // modify inherited properties from abstract plottable:
+ setPen(QPen(Qt::blue, 0));
+ setBrush(Qt::NoBrush);
setScatterStyle(QCPScatterStyle());
setLineStyle(lsLine);
@@ -16819,73 +21501,61 @@ QCPCurve::QCPCurve(QCPAxis *keyAxis, QCPAxis *valueAxis) :
QCPCurve::~QCPCurve()
{
- delete mData;
}
-/*!
- Replaces the current data with the provided \a data.
+/*! \overload
- If \a copy is set to true, data points in \a data will only be copied. if false, the plottable
- takes ownership of the passed data and replaces the internal data pointer with it. This is
- significantly faster than copying for large datasets.
+ Replaces the current data container with the provided \a data container.
+
+ Since a QSharedPointer is used, multiple QCPCurves may share the same data container safely.
+ Modifying the data in the container will then affect all curves that share the container. Sharing
+ can be achieved by simply exchanging the data containers wrapped in shared pointers:
+ \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcurve-datasharing-1
+
+ If you do not wish to share containers, but create a copy from an existing container, rather use
+ the \ref QCPDataContainer<DataType>::set method on the curve's data container directly:
+ \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcurve-datasharing-2
+
+ \see addData
*/
-void QCPCurve::setData(QCPCurveDataMap *data, bool copy)
+void QCPCurve::setData(QSharedPointer<QCPCurveDataContainer> data)
{
- if (mData == data)
- {
- qDebug() << Q_FUNC_INFO << "The data pointer is already in (and owned by) this plottable" << reinterpret_cast<quintptr>(data);
- return;
- }
- if (copy)
- {
- *mData = *data;
- } else
- {
- delete mData;
- mData = data;
- }
+ mDataContainer = data;
}
/*! \overload
- Replaces the current data with the provided points in \a t, \a key and \a value tuples. The
- provided vectors should have equal length. Else, the number of added points will be the size of
- the smallest vector.
+ Replaces the current data with the provided points in \a t, \a keys and \a values. The provided
+ vectors should have equal length. Else, the number of added points will be the size of the
+ smallest vector.
+
+ If you can guarantee that the passed data points are sorted by \a t in ascending order, you can
+ set \a alreadySorted to true, to improve performance by saving a sorting run.
+
+ \see addData
*/
-void QCPCurve::setData(const QVector<double> &t, const QVector<double> &key, const QVector<double> &value)
+void QCPCurve::setData(const QVector<double> &t, const QVector<double> &keys, const QVector<double> &values, bool alreadySorted)
{
- mData->clear();
- int n = t.size();
- n = qMin(n, key.size());
- n = qMin(n, value.size());
- QCPCurveData newData;
- for (int i=0; i<n; ++i)
- {
- newData.t = t[i];
- newData.key = key[i];
- newData.value = value[i];
- mData->insertMulti(newData.t, newData);
- }
+ mDataContainer->clear();
+ addData(t, keys, values, alreadySorted);
}
+
/*! \overload
- Replaces the current data with the provided \a key and \a value pairs. The t parameter
- of each data point will be set to the integer index of the respective key/value pair.
+ Replaces the current data with the provided points in \a keys and \a values. The provided vectors
+ should have equal length. Else, the number of added points will be the size of the smallest
+ vector.
+
+ The t parameter of each data point will be set to the integer index of the respective key/value
+ pair.
+
+ \see addData
*/
-void QCPCurve::setData(const QVector<double> &key, const QVector<double> &value)
+void QCPCurve::setData(const QVector<double> &keys, const QVector<double> &values)
{
- mData->clear();
- int n = key.size();
- n = qMin(n, value.size());
- QCPCurveData newData;
- for (int i=0; i<n; ++i)
- {
- newData.t = i; // no t vector given, so we assign t the index of the key/value pair
- newData.key = key[i];
- newData.value = value[i];
- mData->insertMulti(newData.t, newData);
- }
+ mDataContainer->clear();
+ addData(keys, values);
}
/*!
@@ -16901,6 +21571,22 @@ void QCPCurve::setScatterStyle(const QCPScatterStyle &style)
}
/*!
+ If scatters are displayed (scatter style not \ref QCPScatterStyle::ssNone), \a skip number of
+ scatter points are skipped/not drawn after every drawn scatter point.
+
+ This can be used to make the data appear sparser while for example still having a smooth line,
+ and to improve performance for very high density plots.
+
+ If \a skip is set to 0 (default), all scatter points are drawn.
+
+ \see setScatterStyle
+*/
+void QCPCurve::setScatterSkip(int skip)
+{
+ mScatterSkip = qMax(0, skip);
+}
+
+/*!
Sets how the single data points are connected in the plot or how they are represented visually
apart from the scatter symbol. For scatter-only plots, set \a style to \ref lsNone and \ref
setScatterStyle to the desired scatter style.
@@ -16912,238 +21598,204 @@ void QCPCurve::setLineStyle(QCPCurve::LineStyle style)
mLineStyle = style;
}
-/*!
- Adds the provided data points in \a dataMap to the current data.
- \see removeData
-*/
-void QCPCurve::addData(const QCPCurveDataMap &dataMap)
-{
- mData->unite(dataMap);
-}
-
/*! \overload
- Adds the provided single data point in \a data to the current data.
- \see removeData
-*/
-void QCPCurve::addData(const QCPCurveData &data)
-{
- mData->insertMulti(data.t, data);
-}
-
-/*! \overload
- Adds the provided single data point as \a t, \a key and \a value tuple to the current data
- \see removeData
+
+ Adds the provided points in \a t, \a keys and \a values to the current data. The provided vectors
+ should have equal length. Else, the number of added points will be the size of the smallest
+ vector.
+
+ If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
+ can set \a alreadySorted to true, to improve performance by saving a sorting run.
+
+ Alternatively, you can also access and modify the data directly via the \ref data method, which
+ returns a pointer to the internal data container.
*/
-void QCPCurve::addData(double t, double key, double value)
+void QCPCurve::addData(const QVector<double> &t, const QVector<double> &keys, const QVector<double> &values, bool alreadySorted)
{
- QCPCurveData newData;
- newData.t = t;
- newData.key = key;
- newData.value = value;
- mData->insertMulti(newData.t, newData);
+ if (t.size() != keys.size() || t.size() != values.size())
+ qDebug() << Q_FUNC_INFO << "ts, keys and values have different sizes:" << t.size() << keys.size() << values.size();
+ const int n = qMin(qMin(t.size(), keys.size()), values.size());
+ QVector<QCPCurveData> tempData(n);
+ QVector<QCPCurveData>::iterator it = tempData.begin();
+ const QVector<QCPCurveData>::iterator itEnd = tempData.end();
+ int i = 0;
+ while (it != itEnd)
+ {
+ it->t = t[i];
+ it->key = keys[i];
+ it->value = values[i];
+ ++it;
+ ++i;
+ }
+ mDataContainer->add(tempData, alreadySorted); // don't modify tempData beyond this to prevent copy on write
}
/*! \overload
- Adds the provided single data point as \a key and \a value pair to the current data The t
- parameter of the data point is set to the t of the last data point plus 1. If there is no last
- data point, t will be set to 0.
+ Adds the provided points in \a keys and \a values to the current data. The provided vectors
+ should have equal length. Else, the number of added points will be the size of the smallest
+ vector.
+
+ The t parameter of each data point will be set to the integer index of the respective key/value
+ pair.
- \see removeData
+ Alternatively, you can also access and modify the data directly via the \ref data method, which
+ returns a pointer to the internal data container.
*/
-void QCPCurve::addData(double key, double value)
+void QCPCurve::addData(const QVector<double> &keys, const QVector<double> &values)
{
- QCPCurveData newData;
- if (!mData->isEmpty())
- newData.t = (mData->constEnd()-1).key()+1;
+ if (keys.size() != values.size())
+ qDebug() << Q_FUNC_INFO << "keys and values have different sizes:" << keys.size() << values.size();
+ const int n = qMin(keys.size(), values.size());
+ double tStart;
+ if (!mDataContainer->isEmpty())
+ tStart = (mDataContainer->constEnd()-1)->t + 1.0;
else
- newData.t = 0;
- newData.key = key;
- newData.value = value;
- mData->insertMulti(newData.t, newData);
-}
-
-/*! \overload
- Adds the provided data points as \a t, \a key and \a value tuples to the current data.
- \see removeData
-*/
-void QCPCurve::addData(const QVector<double> &ts, const QVector<double> &keys, const QVector<double> &values)
-{
- int n = ts.size();
- n = qMin(n, keys.size());
- n = qMin(n, values.size());
- QCPCurveData newData;
- for (int i=0; i<n; ++i)
+ tStart = 0;
+ QVector<QCPCurveData> tempData(n);
+ QVector<QCPCurveData>::iterator it = tempData.begin();
+ const QVector<QCPCurveData>::iterator itEnd = tempData.end();
+ int i = 0;
+ while (it != itEnd)
{
- newData.t = ts[i];
- newData.key = keys[i];
- newData.value = values[i];
- mData->insertMulti(newData.t, newData);
+ it->t = tStart + i;
+ it->key = keys[i];
+ it->value = values[i];
+ ++it;
+ ++i;
}
+ mDataContainer->add(tempData, true); // don't modify tempData beyond this to prevent copy on write
}
-/*!
- Removes all data points with curve parameter t smaller than \a t.
- \see addData, clearData
-*/
-void QCPCurve::removeDataBefore(double t)
-{
- QCPCurveDataMap::iterator it = mData->begin();
- while (it != mData->end() && it.key() < t)
- it = mData->erase(it);
-}
-
-/*!
- Removes all data points with curve parameter t greater than \a t.
- \see addData, clearData
-*/
-void QCPCurve::removeDataAfter(double t)
-{
- if (mData->isEmpty()) return;
- QCPCurveDataMap::iterator it = mData->upperBound(t);
- while (it != mData->end())
- it = mData->erase(it);
-}
-
-/*!
- Removes all data points with curve parameter t between \a fromt and \a tot. if \a fromt is
- greater or equal to \a tot, the function does nothing. To remove a single data point with known
- t, use \ref removeData(double t).
+/*! \overload
+ Adds the provided data point as \a t, \a key and \a value to the current data.
- \see addData, clearData
+ Alternatively, you can also access and modify the data directly via the \ref data method, which
+ returns a pointer to the internal data container.
*/
-void QCPCurve::removeData(double fromt, double tot)
+void QCPCurve::addData(double t, double key, double value)
{
- if (fromt >= tot || mData->isEmpty()) return;
- QCPCurveDataMap::iterator it = mData->upperBound(fromt);
- QCPCurveDataMap::iterator itEnd = mData->upperBound(tot);
- while (it != itEnd)
- it = mData->erase(it);
+ mDataContainer->add(QCPCurveData(t, key, value));
}
/*! \overload
- Removes a single data point at curve parameter \a t. If the position is not known with absolute
- precision, consider using \ref removeData(double fromt, double tot) with a small fuzziness
- interval around the suspected position, depeding on the precision with which the curve parameter
- is known.
+ Adds the provided data point as \a key and \a value to the current data.
- \see addData, clearData
-*/
-void QCPCurve::removeData(double t)
-{
- mData->remove(t);
-}
-
-/*!
- Removes all data points.
- \see removeData, removeDataAfter, removeDataBefore
+ The t parameter is generated automatically by increments of 1 for each point, starting at the
+ highest t of previously existing data or 0, if the curve data is empty.
+
+ Alternatively, you can also access and modify the data directly via the \ref data method, which
+ returns a pointer to the internal data container.
*/
-void QCPCurve::clearData()
+void QCPCurve::addData(double key, double value)
{
- mData->clear();
+ if (!mDataContainer->isEmpty())
+ mDataContainer->add(QCPCurveData((mDataContainer->constEnd()-1)->t + 1.0, key, value));
+ else
+ mDataContainer->add(QCPCurveData(0.0, key, value));
}
/* inherits documentation from base class */
double QCPCurve::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
{
- Q_UNUSED(details)
- if ((onlySelectable && !mSelectable) || mData->isEmpty())
+ if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
+ return -1;
+ if (!mKeyAxis || !mValueAxis)
return -1;
- if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; }
if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()))
- return pointDistance(pos);
- else
+ {
+ QCPCurveDataContainer::const_iterator closestDataPoint = mDataContainer->constEnd();
+ double result = pointDistance(pos, closestDataPoint);
+ if (details)
+ {
+ int pointIndex = closestDataPoint-mDataContainer->constBegin();
+ details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1)));
+ }
+ return result;
+ } else
return -1;
}
/* inherits documentation from base class */
+QCPRange QCPCurve::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const
+{
+ return mDataContainer->keyRange(foundRange, inSignDomain);
+}
+
+/* inherits documentation from base class */
+QCPRange QCPCurve::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const
+{
+ return mDataContainer->valueRange(foundRange, inSignDomain, inKeyRange);
+}
+
+/* inherits documentation from base class */
void QCPCurve::draw(QCPPainter *painter)
{
- if (mData->isEmpty()) return;
+ if (mDataContainer->isEmpty()) return;
// allocate line vector:
- QVector<QPointF> *lineData = new QVector<QPointF>;
-
- // fill with curve data:
- getCurveData(lineData);
-
- // check data validity if flag set:
-#ifdef QCUSTOMPLOT_CHECK_DATA
- QCPCurveDataMap::const_iterator it;
- for (it = mData->constBegin(); it != mData->constEnd(); ++it)
- {
- if (QCP::isInvalidData(it.value().t) ||
- QCP::isInvalidData(it.value().key, it.value().value))
- qDebug() << Q_FUNC_INFO << "Data point at" << it.key() << "invalid." << "Plottable name:" << name();
- }
-#endif
+ QVector<QPointF> lines, scatters;
- // draw curve fill:
- if (mainBrush().style() != Qt::NoBrush && mainBrush().color().alpha() != 0)
+ // loop over and draw segments of unselected/selected data:
+ QList<QCPDataRange> selectedSegments, unselectedSegments, allSegments;
+ getDataSegments(selectedSegments, unselectedSegments);
+ allSegments << unselectedSegments << selectedSegments;
+ for (int i=0; i<allSegments.size(); ++i)
{
+ bool isSelectedSegment = i >= unselectedSegments.size();
+
+ // fill with curve data:
+ QPen finalCurvePen = mPen; // determine the final pen already here, because the line optimization depends on its stroke width
+ if (isSelectedSegment && mSelectionDecorator)
+ finalCurvePen = mSelectionDecorator->pen();
+
+ 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)
+ getCurveLines(&lines, lineDataRange, finalCurvePen.widthF());
+
+ // check data validity if flag set:
+ #ifdef QCUSTOMPLOT_CHECK_DATA
+ for (QCPCurveDataContainer::const_iterator it = mDataContainer->constBegin(); it != mDataContainer->constEnd(); ++it)
+ {
+ if (QCP::isInvalidData(it->t) ||
+ QCP::isInvalidData(it->key, it->value))
+ qDebug() << Q_FUNC_INFO << "Data point at" << it->key << "invalid." << "Plottable name:" << name();
+ }
+ #endif
+
+ // draw curve fill:
applyFillAntialiasingHint(painter);
+ if (isSelectedSegment && mSelectionDecorator)
+ mSelectionDecorator->applyBrush(painter);
+ else
+ painter->setBrush(mBrush);
painter->setPen(Qt::NoPen);
- painter->setBrush(mainBrush());
- painter->drawPolygon(QPolygonF(*lineData));
- }
-
- // draw curve line:
- if (mLineStyle != lsNone && mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0)
- {
- applyDefaultAntialiasingHint(painter);
- painter->setPen(mainPen());
- painter->setBrush(Qt::NoBrush);
- // if drawing solid line and not in PDF, use much faster line drawing instead of polyline:
- if (mParentPlot->plottingHints().testFlag(QCP::phFastPolylines) &&
- painter->pen().style() == Qt::SolidLine &&
- !painter->modes().testFlag(QCPPainter::pmVectorized) &&
- !painter->modes().testFlag(QCPPainter::pmNoCaching))
- {
- int i = 0;
- bool lastIsNan = false;
- const int lineDataSize = lineData->size();
- while (i < lineDataSize && (qIsNaN(lineData->at(i).y()) || qIsNaN(lineData->at(i).x()))) // make sure first point is not NaN
- ++i;
- ++i; // because drawing works in 1 point retrospect
- while (i < lineDataSize)
- {
- if (!qIsNaN(lineData->at(i).y()) && !qIsNaN(lineData->at(i).x())) // NaNs create a gap in the line
- {
- if (!lastIsNan)
- painter->drawLine(lineData->at(i-1), lineData->at(i));
- else
- lastIsNan = false;
- } else
- lastIsNan = true;
- ++i;
- }
- } else
+ if (painter->brush().style() != Qt::NoBrush && painter->brush().color().alpha() != 0)
+ painter->drawPolygon(QPolygonF(lines));
+
+ // draw curve line:
+ if (mLineStyle != lsNone)
{
- int segmentStart = 0;
- int i = 0;
- const int lineDataSize = lineData->size();
- while (i < lineDataSize)
- {
- if (qIsNaN(lineData->at(i).y()) || qIsNaN(lineData->at(i).x())) // NaNs create a gap in the line
- {
- painter->drawPolyline(lineData->constData()+segmentStart, i-segmentStart); // i, because we don't want to include the current NaN point
- segmentStart = i+1;
- }
- ++i;
- }
- // draw last segment:
- painter->drawPolyline(lineData->constData()+segmentStart, lineDataSize-segmentStart);
+ painter->setPen(finalCurvePen);
+ painter->setBrush(Qt::NoBrush);
+ drawCurveLine(painter, lines);
+ }
+
+ // draw scatters:
+ QCPScatterStyle finalScatterStyle = mScatterStyle;
+ if (isSelectedSegment && mSelectionDecorator)
+ finalScatterStyle = mSelectionDecorator->getFinalScatterStyle(mScatterStyle);
+ if (!finalScatterStyle.isNone())
+ {
+ getScatters(&scatters, allSegments.at(i), finalScatterStyle.size());
+ drawScatterPlot(painter, scatters, finalScatterStyle);
}
}
- // draw scatters:
- if (!mScatterStyle.isNone())
- drawScatterPlot(painter, lineData);
-
- // free allocated line data:
- delete lineData;
+ // draw other selection decoration that isn't just line/scatter pens and brushes:
+ if (mSelectionDecorator)
+ mSelectionDecorator->drawDecoration(painter, selection());
}
/* inherits documentation from base class */
@@ -17181,56 +21833,92 @@ void QCPCurve::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
}
}
+/*! \internal
+
+ Draws lines between the points in \a lines, given in pixel coordinates.
+
+ \see drawScatterPlot, getCurveLines
+*/
+void QCPCurve::drawCurveLine(QCPPainter *painter, const QVector<QPointF> &lines) const
+{
+ if (painter->pen().style() != Qt::NoPen && painter->pen().color().alpha() != 0)
+ {
+ applyDefaultAntialiasingHint(painter);
+ drawPolyline(painter, lines);
+ }
+}
+
/*! \internal
-
- Draws scatter symbols at every data point passed in \a pointData. scatter symbols are independent of
- the line style and are always drawn if scatter shape is not \ref QCPScatterStyle::ssNone.
+
+ Draws scatter symbols at every point passed in \a points, given in pixel coordinates. The
+ scatters will be drawn with \a painter and have the appearance as specified in \a style.
+
+ \see drawCurveLine, getCurveLines
*/
-void QCPCurve::drawScatterPlot(QCPPainter *painter, const QVector<QPointF> *pointData) const
+void QCPCurve::drawScatterPlot(QCPPainter *painter, const QVector<QPointF> &points, const QCPScatterStyle &style) const
{
// draw scatter point symbols:
applyScattersAntialiasingHint(painter);
- mScatterStyle.applyTo(painter, mPen);
- for (int i=0; i<pointData->size(); ++i)
- if (!qIsNaN(pointData->at(i).x()) && !qIsNaN(pointData->at(i).y()))
- mScatterStyle.drawShape(painter, pointData->at(i));
+ style.applyTo(painter, mPen);
+ for (int i=0; i<points.size(); ++i)
+ if (!qIsNaN(points.at(i).x()) && !qIsNaN(points.at(i).y()))
+ style.drawShape(painter, points.at(i));
}
/*! \internal
-
- called by QCPCurve::draw to generate a point vector (in pixel coordinates) which represents the
- line of the curve.
+
+ Called by \ref draw to generate points in pixel coordinates which represent the line of the
+ curve.
Line segments that aren't visible in the current axis rect are handled in an optimized way. They
are projected onto a rectangle slightly larger than the visible axis rect and simplified
regarding point count. The algorithm makes sure to preserve appearance of lines and fills inside
the visible axis rect by generating new temporary points on the outer rect if necessary.
-
+
+ \a lines will be filled with points in pixel coordinates, that can be drawn with \ref
+ drawCurveLine.
+
+ \a dataRange specifies the beginning and ending data indices that will be taken into account for
+ conversion. In this function, the specified range may exceed the total data bounds without harm:
+ a correspondingly trimmed data range will be used. This takes the burden off the user of this
+ function to check for valid indices in \a dataRange, e.g. when extending ranges coming from \ref
+ getDataSegments.
+
+ \a penWidth specifies the pen width that will be used to later draw the lines generated by this
+ function. This is needed here to calculate an accordingly wider margin around the axis rect when
+ performing the line optimization.
+
Methods that are also involved in the algorithm are: \ref getRegion, \ref getOptimizedPoint, \ref
getOptimizedCornerPoints \ref mayTraverse, \ref getTraverse, \ref getTraverseCornerPoints.
+
+ \see drawCurveLine, drawScatterPlot
*/
-void QCPCurve::getCurveData(QVector<QPointF> *lineData) const
+void QCPCurve::getCurveLines(QVector<QPointF> *lines, const QCPDataRange &dataRange, double penWidth) const
{
+ if (!lines) return;
+ lines->clear();
QCPAxis *keyAxis = mKeyAxis.data();
QCPAxis *valueAxis = mValueAxis.data();
if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
// add margins to rect to compensate for stroke width
- double strokeMargin = qMax(qreal(1.0), qreal(mainPen().widthF()*0.75)); // stroke radius + 50% safety
- if (!mScatterStyle.isNone())
- strokeMargin = qMax(strokeMargin, mScatterStyle.size());
- double rectLeft = keyAxis->pixelToCoord(keyAxis->coordToPixel(keyAxis->range().lower)-strokeMargin*((keyAxis->orientation()==Qt::Vertical)!=keyAxis->rangeReversed()?-1:1));
- double rectRight = keyAxis->pixelToCoord(keyAxis->coordToPixel(keyAxis->range().upper)+strokeMargin*((keyAxis->orientation()==Qt::Vertical)!=keyAxis->rangeReversed()?-1:1));
- double rectBottom = valueAxis->pixelToCoord(valueAxis->coordToPixel(valueAxis->range().lower)+strokeMargin*((valueAxis->orientation()==Qt::Horizontal)!=valueAxis->rangeReversed()?-1:1));
- double rectTop = valueAxis->pixelToCoord(valueAxis->coordToPixel(valueAxis->range().upper)-strokeMargin*((valueAxis->orientation()==Qt::Horizontal)!=valueAxis->rangeReversed()?-1:1));
- int currentRegion;
- QCPCurveDataMap::const_iterator it = mData->constBegin();
- QCPCurveDataMap::const_iterator prevIt = mData->constEnd()-1;
- int prevRegion = getRegion(prevIt.value().key, prevIt.value().value, rectLeft, rectTop, rectRight, rectBottom);
+ const double strokeMargin = qMax(qreal(1.0), qreal(penWidth*0.75)); // stroke radius + 50% safety
+ const double keyMin = keyAxis->pixelToCoord(keyAxis->coordToPixel(keyAxis->range().lower)-strokeMargin*keyAxis->pixelOrientation());
+ const double keyMax = keyAxis->pixelToCoord(keyAxis->coordToPixel(keyAxis->range().upper)+strokeMargin*keyAxis->pixelOrientation());
+ const double valueMin = valueAxis->pixelToCoord(valueAxis->coordToPixel(valueAxis->range().lower)-strokeMargin*valueAxis->pixelOrientation());
+ const double valueMax = valueAxis->pixelToCoord(valueAxis->coordToPixel(valueAxis->range().upper)+strokeMargin*valueAxis->pixelOrientation());
+ QCPCurveDataContainer::const_iterator itBegin = mDataContainer->constBegin();
+ QCPCurveDataContainer::const_iterator itEnd = mDataContainer->constEnd();
+ mDataContainer->limitIteratorsToDataRange(itBegin, itEnd, dataRange);
+ if (itBegin == itEnd)
+ return;
+ QCPCurveDataContainer::const_iterator it = itBegin;
+ QCPCurveDataContainer::const_iterator prevIt = itEnd-1;
+ int prevRegion = getRegion(prevIt->key, prevIt->value, keyMin, valueMax, keyMax, valueMin);
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)
- while (it != mData->constEnd())
+ while (it != itEnd)
{
- currentRegion = getRegion(it.value().key, it.value().value, rectLeft, rectTop, rectRight, rectBottom);
+ const int currentRegion = getRegion(it->key, it->value, keyMin, valueMax, keyMax, valueMin);
if (currentRegion != prevRegion) // changed region, possibly need to add some optimized edge points or original points if entering R
{
if (currentRegion != 5) // segment doesn't end in R, so it's a candidate for removal
@@ -17238,44 +21926,44 @@ void QCPCurve::getCurveData(QVector<QPointF> *lineData) const
QPointF crossA, crossB;
if (prevRegion == 5) // we're coming from R, so add this point optimized
{
- lineData->append(getOptimizedPoint(currentRegion, it.value().key, it.value().value, prevIt.value().key, prevIt.value().value, rectLeft, rectTop, rectRight, rectBottom));
+ lines->append(getOptimizedPoint(currentRegion, it->key, it->value, prevIt->key, prevIt->value, keyMin, valueMax, keyMax, valueMin));
// 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
- *lineData << getOptimizedCornerPoints(prevRegion, currentRegion, prevIt.value().key, prevIt.value().value, it.value().key, it.value().value, rectLeft, rectTop, rectRight, rectBottom);
+ *lines << getOptimizedCornerPoints(prevRegion, currentRegion, prevIt->key, prevIt->value, it->key, it->value, keyMin, valueMax, keyMax, valueMin);
} else if (mayTraverse(prevRegion, currentRegion) &&
- getTraverse(prevIt.value().key, prevIt.value().value, it.value().key, it.value().value, rectLeft, rectTop, rectRight, rectBottom, crossA, crossB))
+ getTraverse(prevIt->key, prevIt->value, it->key, it->value, keyMin, valueMax, keyMax, valueMin, crossA, crossB))
{
// add the two cross points optimized if segment crosses R and if segment isn't virtual zeroth segment between last and first curve point:
QVector<QPointF> beforeTraverseCornerPoints, afterTraverseCornerPoints;
- getTraverseCornerPoints(prevRegion, currentRegion, rectLeft, rectTop, rectRight, rectBottom, beforeTraverseCornerPoints, afterTraverseCornerPoints);
- if (it != mData->constBegin())
+ getTraverseCornerPoints(prevRegion, currentRegion, keyMin, valueMax, keyMax, valueMin, beforeTraverseCornerPoints, afterTraverseCornerPoints);
+ if (it != itBegin)
{
- *lineData << beforeTraverseCornerPoints;
- lineData->append(crossA);
- lineData->append(crossB);
- *lineData << afterTraverseCornerPoints;
+ *lines << beforeTraverseCornerPoints;
+ lines->append(crossA);
+ lines->append(crossB);
+ *lines << afterTraverseCornerPoints;
} else
{
- lineData->append(crossB);
- *lineData << afterTraverseCornerPoints;
+ lines->append(crossB);
+ *lines << afterTraverseCornerPoints;
trailingPoints << beforeTraverseCornerPoints << crossA ;
}
} 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)
{
- *lineData << getOptimizedCornerPoints(prevRegion, currentRegion, prevIt.value().key, prevIt.value().value, it.value().key, it.value().value, rectLeft, rectTop, rectRight, rectBottom);
+ *lines << getOptimizedCornerPoints(prevRegion, currentRegion, prevIt->key, prevIt->value, it->key, it->value, keyMin, valueMax, keyMax, valueMin);
}
} else // segment does end in R, so we add previous point optimized and this point at original position
{
- if (it == mData->constBegin()) // it is first point in curve and prevIt is last one. So save optimized point for adding it to the lineData in the end
- trailingPoints << getOpti