diff --git a/libs/qcustomplot-source/changelog.txt b/libs/qcustomplot-source/changelog.txt index 7acf22a6..5e51a149 100644 --- a/libs/qcustomplot-source/changelog.txt +++ b/libs/qcustomplot-source/changelog.txt @@ -1,3 +1,120 @@ +#### Version 2.0.0-beta released on 13.09.16 #### + +Added major features: + - Axis tick and tick label generation was completely refactored and is now handled in the QCPAxisTicker class (also see QCPAxis::setTicker). Available ticker subclasses for special uses cases: + QCPAxisTicker, QCPAxisTickerFixed, QCPAxisTickerLog, QCPAxisTickerPi, QCPAxisTickerTime, QCPAxisTickerDateTime, QCPAxisTickerText + - Data container is now based on QCPDataContainer template for unified data interface and significantly improved memory footprint and better performance for common use-cases, especially data adding/removing. + - New data selection mechanism allows selection of single data points and data ranges for plottables. See special documentation page "data selection mechanism". + - Rubber band/selection rect for data point selection and axis zooming is now available, see documentation of QCustomPlot::setSelectionRectMode and QCPSelectionRect. For this purpose, the new default + layer "overlay" was introduced, which is now the top layer, and holds the QCustomPlot's QCPSelectionRect instance. + - Data sharing between plottables of the same type (see setData methods taking a QSharedPointer) + - OpenGL hardware acceleration is now available across all Qt versions (including Qt4) in a unified, simple interface, with QCustomPlot::setOpenGl + - QCPStatisticalBox can now display a series of statistical boxes instead of only a single one + - New QCPErrorBars plottable allows attaching error bars to any one-dimensional plottable (QCPGraph has thus lost its own error-bar capability) + - QCPColorMap now supports transparency via alpha in its color gradient stops, and via a dedicated cell-wise alpha map (see QCPColorMapData::setAlpha) + - Layers may now be individually replotted (QCPLayer::replot), if the mode (QCPLayer::setMode) is set to lmBuffered. Mutually adjacent lmLogical layers share a single paint buffer to save resources. + By default, the new topmost "overlay" layer which contains the selection rect is an lmBuffered layer. Updating the selection rect is thus very fast, independent of the plot contents. + - QCPLayerable (and thus practically all objects in QCP) now have virtual methods to receive mouse press/move/release/doubleclick/wheel events. Before, only QCPLayoutElement provided them. + this makes it much easier to subclass e.g. items and plottables to provide custom mouse interactions that were cumbersome and awkward with the simpler signal-based interface + +Added minor features: + - High-DPI support for Qt versions 5.0 and up, using device pixel ratio detected by Qt (can be changed manually via QCustomPlot::setBufferDevicePixelRatio). + - QCPGraph and QCPCurve can now be configured to only display every n'th scatter symbol, see ::setScatterSkip() method + - QCPFinancial allows to define bar width in absolute pixels and axis rect ratio, instead of only in plot key coordinates (see QCPFinancial::setWidthType) + - Range dragging/zooming can now be configured to affect more than one axis per orientation (see new overloads of QCPAxisRect::setRangeDragAxes/setRangeZoomAxes) + - Added QCPTextElement (replaces QCPPlotTitle) for general texts in layouts. Provides clicked and doubleClicked signals, as replacement for the removed QCustomPlot::titleClicked/titleDoubleClicked + - Export functions (QCustomPlot::savePng etc.) now support specifying the resolution that will be written to the image file header. This improves operability with other tools which respect metadata. + - Replots can now be queued to the next event loop iteration with replot(QCP::rpQueuedReplot). This way you can successively ask for a replot at multiple code locations without causing redundant replots + - QCPAxisRect::zoom(...) allows to zoom to a specific rectangular region given in pixel coordinates, either affecting all axes or a specified subset of axes. + - QCPRange::bounded returns a bounded range, trying to preserve its size. Works with rangeChanged signal to limit the allowed range (see rangeChanged doc) + - Plottable rescaleValueAxis method (and getValueRange) now take parameter inKeyRange, which allows rescaling of the value axis only with respect to data in the currently visible key range + - plottableClick and plottableDoubleClick signals now carry the clicked data point index as second parameter + - Added QCPAxis::scaleRange overload without "center" argument, which scales around the current axis range center + - Added QCPRange::expand/expanded overloads which take only one double parameter + - Plottables addToLegend/removeFromLegend methods now have overloads that take any QCPLegend, to make working with non-default legends easier (legends that are not QCustomPlot::legend) + - Added QCPStatisticalBox::setWhiskerAntialiased to allow controlling antialiasing state of whiskers independently of quartile box/median line + - The virtual method QCPLayoutElement::layoutChanged() now allows subclasses to react on a move of the layout element between logical positions in the parent layout, or between layouts + - QCPMarginGroup::commonMargin is now virtual, to facilitate subclassing of QCPMarginGroup + - QCPGraph::getPreparedData is now virtual, and thus allows subclasses to easily generate own plotted data, e.g. on-the-fly. + - Added QCPRange qDebug stream operator + - QCPLayoutGrid (and thus QCPLegend) can now wrap rows or columns at specified row/column counts, see setFillOrder, setWrap and the new addElement overload which doesn't have row/column index + +Bugfixes [Also backported to 1.3.2]: + - Fixed possible crash when having a QCPGraph with scatters only and a non-transparent main/fill brush of the graph + - Fixed QCPItemPixmap not updating internally cached scaled pixmap if new pixmap set with same scaled dimensions + - When using log axis scale and zooming out as far as possible (~1e-280..1e280), axis doesn't end up in (via mouse) unrecoverable range with strange axis ticks anymore + - Axis tick label algorithm for beautifully typeset powers now checks whether "e" in tick label is actually part of a number before converting the exponent to superscript + - Fixed QCustomPlot::moveLayer performing incorrect move and possible crash in certain situations + - Fixed possible crash on QCustomPlot destruction due to wrong QObject-hierarchy. Only occurs if a QCPAxisRect is removed from the normal QCustomPlot destruction hierarchy by taking it out of its layout + - Fixed possible freeze when data values become infinity after coord-to-pixel transformation (e.g. maximally zoomed out log axis), and line style is not solid (e.g. dashed) or phFastPolylines is disabled + - Fixed a few missing enums in meta type system, by unifying usage of Q_ENUMS, Q_FLAGS and Q_DECLARE_METATYPE +Bugfixes [Not in 1.3.2]: + - Fixed QCPItemLine/QCPItemStraightLine not being selectable when defining coords are many orders of magnitude (>1e8) larger than currently viewed range + - Fixed/worked around crash due to bug in QPainter::drawPixmap with very large negative x/y pixel coordinates, when drawing sparse pixmap scatters + - Fixed possible (but unlikely) int overflow in adaptive sampling algorithm, that could cause plot artifacts when using extremely sparse data (with respect to current key axis range). + - Fixed QCPBarsGroup bug which caused stPlotCoords spacing to be wrong with vertical key axes + - A QCPBars axis rescale in the main window constructor (i.e. without well-defined plot size) now falls back to a datapoint-tight rescaling instead of doing nothing (because bar width can't be determined) + - Improved QCPBars stacking when using bars with very large keys and key separation at limit of double precision + +Summary of backward incompatible changes: + Plottable related: + - Removed QCustomPlot::addPlottable, not needed anymore as plottables now automatically register in their constructor + - Removed QCustomPlot::addItem, not needed anymore as items now automatically register in their constructor + - QCPAbstractPlottable::addToLegend/removeFromLegend are not virtual anymore. If your plottable requires a custom legend item, add it to the legend manually. + - setData/addData method overloads of plottables have changed to facilitate data sharing and new data container (see documentation) + - plottableClick and plottableDoubleClick signals now carry the clicked data point index as second parameter, and the QMouseEvent parameter has moved to third. + Check all your usages of those signals, because Qt's connect method only reports problems during runtime! + - setSelectable now not only limits what can be selected by the user, but limits also any programmatic selection changes via setSelected. + - enum QCPAbstractPlottable::SignDomain has changed namespace to QCP::SignDomain + Axis related: + - Removed QCPAxis::setAutoTicks, setAutoTickCount, setAutoTickLabels, setAutoTickStep, setAutoSubTicks, setTickLabelType, setDateTimeFormat, setDateTimeSpec, + setTickStep, setTickVector, setTickVectorLabels, setSubTickCount in favor of new QCPAxisTicker-based interface + - Added QCPAxis::setSubTicks to enable/disable subticks (manually controlling the subtick count needs subclassing of QCPAxisTicker, e.g. QCPAxisTickerText and QCPAxisTickerLog provide setSubTickCount) + Item related: + - Renamed QCPAbstractItem::rectSelectTest to rectDistance, to prevent confusion with new QCPAbstractPlottable1D::selectTestRect + - Renamed QCPItemAnchor::pixelPoint to QCPItemAnchor::pixelPosition (also affects subclass QCPItemPosition) + General: + - Renamed QCustomPlot::RefreshPriority enums (parameter of the replot() method): rpImmediate to rpImmediateRefresh, rpQueued to rpQueuedRefresh, rpHint to rpRefreshHint + - Renamed QCustomPlot::PlottingHint enum phForceRepaint to phImmediateRefresh + - Removed QCPPlotTitle layout element (See new QCPTextElement for almost drop-in replacement) + - Removed signals QCustomPlot::titleClicked/titleDoubleClicked, replaced by QCPTextElement signals clicked/doubleClicked. + - QCustomPlot::savePdf has changed parameters from (fileName, bool noCosmeticPen, width, height,...) to (fileName, width, height, QCP::ExportPen exportPen,...) + - Virtual methods QCPLayoutElement::mouseMoveEvent/mouseReleaseEvent (which are now introduced already in the superclass QCPLayerable) have gained an additional parameter const QPointF &startPos. + If you have reimplemented these methods, make sure to update your function signatures, otherwise your reimplementations will likely be ignored by the compiler without warning + - Creating a new QCPColorGradient without supplying a preset parameter in the constructor now creates an empty gradient, instead of loading the gpCold preset + +Other: + - Replaced usage of Qt's QVector2D with own QCPVector2D which uses double precision and offers some convenience functions + - Extended relative range to which QCPItemLine/QCPItemStraightLine can be zoomed before vanishing from ~1e9 to ~1e16 + - Removed QCPItemStraightLine::distToStraightLine (replaced by QCPVector2D::distanceToStraightLine) + - Removed QCPAbstractPlottable::distSqrToLine and QCPAbstractItem::distSqrToLine (replaced by QCPVector2D::distanceSquaredToLine) + - Qt5.5 compatibility (If you use PDF export, test your outputs, as output dimensions might change when switching Qt versions -- QCP does not try to emulate previous Qt version behaviour here) + - QCP now includes instead of just because some users had problems with the latter. Please report if you now experience issues due to the new include. + - QCPGraph can now use a brush (filled polygon under the graph data) without having a graph line (line style lsNone) + - QCPFinancial is now two-colored (setTwoColored(true)) by default, and has green/red as default two-colored brushes and pens + - Plottable pixelsToCoords/coordsToPixels methods are now public, and offer transformations from pixel to plot coordinates and vice versa, using the plottable's axes + - Plottable getKeyRange/getValueRange methods are now public + - QCPBarsGroup now always places the QCPBars that was added to the group first towards lower keys, independent of axis orientation or direction (the ordering used to flip with axis orientation) + - Default focus policy for QCustomPlot is now Qt::ClickFocus, instead of Qt::NoFocus. + - tweaked QCPLegend and QCPAbstractLegendItem margins: The items have by default zero own margins, and QCPLegend row- and column spacing was increased to compensate. Legend was made slightly denser by default. + - Used doxygen version is now 1.8.12, and documentation/postprocessing-scripts were adapted accordingly. Expect minor issues and some warnings when using older doxygen. + +#### Version 1.3.2 released on 22.12.15 #### + + Bugfixes [Backported from 2.0.0 branch]: + - Fixed possible crash when having a QCPGraph with scatters only and a non-transparent main/fill brush of the graph + - Fixed QCPItemPixmap not updating internally cached scaled pixmap if new pixmap set with same scaled dimensions + - When using log axis scale and zooming out as far as possible (~1e-280..1e280), axis doesn't end up in (via mouse) unrecoverable range with strange axis ticks anymore + - Axis tick label algorithm for beautifully typeset powers now checks whether "e" in tick label is actually part of a number before converting the exponent to superscript + - Fixed QCustomPlot::moveLayer performing incorrect move and possible crash in certain situations + - Fixed possible crash on QCustomPlot destruction due to wrong QObject-hierarchy. Only occurs if a QCPAxisRect is removed from the normal QCustomPlot destruction hierarchy by taking it out of its layout + - Fixed possible freeze when data values become infinity after coord-to-pixel transformation (e.g. maximally zoomed out log axis), and line style is not solid (e.g. dashed) or phFastPolylines is disabled + + Other [Backported from 2.0.0 branch]: + - A few documentation fixes/improvements + - Qt5.5 compatibility (If you use PDF export, test your outputs, as output dimensions might change when switching Qt versions -- QCP does not try to emulate previous Qt version behaviour here) + - QCP now includes instead of just because some users had problems with the latter. Please report if you now experience issues due to the new include. + #### Version 1.3.1 released on 25.04.15 #### Bugfixes: diff --git a/libs/qcustomplot-source/qcustomplot.cpp b/libs/qcustomplot-source/qcustomplot.cpp index d7e54852..94cd3c20 100644 --- a/libs/qcustomplot-source/qcustomplot.cpp +++ b/libs/qcustomplot-source/qcustomplot.cpp @@ -1,7 +1,7 @@ /*************************************************************************** ** ** ** 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 ** @@ -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,426 +474,484 @@ 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 pure virtual functions */ + +/*! \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 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 bool QCPScatterStyle::isNone() const - - Returns whether the scatter shape is \ref ssNone. - - \see setShape -*/ +/*! \fn virtual void QCPAbstractPaintBuffer::donePainting() -/*! \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 + 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. -*/ -QCPScatterStyle::QCPScatterStyle() : - mSize(6), - mShape(ssNone), - mPen(Qt::NoPen), - mBrush(Qt::NoBrush), - mPenDefined(false) -{ -} + Creates a paint buffer and initializes it with the provided \a size and \a devicePixelRatio. -/*! - 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. + Subclasses must call their \ref reallocateBuffer implementation in their respective constructors. */ -QCPScatterStyle::QCPScatterStyle(ScatterShape shape, double size) : +QCPAbstractPaintBuffer::QCPAbstractPaintBuffer(const QSize &size, double devicePixelRatio) : mSize(size), - mShape(shape), - mPen(Qt::NoPen), - mBrush(Qt::NoBrush), - mPenDefined(false) + mDevicePixelRatio(devicePixelRatio), + mInvalidated(true) +{ +} + +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. -*/ -QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QColor &color, double size) : - mSize(size), - mShape(shape), - mPen(QPen(color)), - mBrush(Qt::NoBrush), - mPenDefined(true) -{ -} + Sets the paint buffer size. -/*! - 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) -{ -} + 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. -/*! - 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 Qt::NoPen as \a pen - and a color like Qt::blue as \a brush. Notice however, that the corresponding call\n - QCPScatterStyle(QCPScatterShape::ssCircle, Qt::NoPen, Qt::blue, 5)\n - doesn't necessarily lead C++ to use this constructor in some cases, but might mistake - Qt::NoPen 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 QBrush(Qt::blue) - instead of just Qt::blue, to clearly point out to the compiler that this constructor is - wanted. + If \a size is already the current buffer size, this method does nothing. */ -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::setSize(const QSize &size) { -} - -/*! - 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) -{ -} - -/*! - 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 Qt::NoPen. - - \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; -} - -/*! - 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, 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) + if (mSize != size) { - 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; - } + mSize = size; + reallocateBuffer(); } } +/*! + 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. +*/ +void QCPAbstractPaintBuffer::setInvalidated(bool invalidated) +{ + mInvalidated = invalidated; +} + +/*! + 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. +*/ +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 pixmap paint buffer instancen with the specified \a size and \a devicePixelRatio, if + applicable. +*/ +QCPPaintBufferPixmap::QCPPaintBufferPixmap(const QSize &size, double devicePixelRatio) : + QCPAbstractPaintBuffer(size, devicePixelRatio) +{ + QCPPaintBufferPixmap::reallocateBuffer(); +} + +QCPPaintBufferPixmap::~QCPPaintBufferPixmap() +{ +} + +/* inherits documentation from base class */ +QCPPainter *QCPPaintBufferPixmap::startPainting() +{ + QCPPainter *result = new QCPPainter(&mBuffer); + result->setRenderHint(QPainter::HighQualityAntialiasing); + return result; +} + +/* inherits documentation from base class */ +void QCPPaintBufferPixmap::draw(QCPPainter *painter) const +{ + if (painter && painter->isActive()) + painter->drawPixmap(0, 0, mBuffer); + else + qDebug() << Q_FUNC_INFO << "invalid or inactive painter passed"; +} + +/* inherits documentation from base class */ +void QCPPaintBufferPixmap::clear(const QColor &color) +{ + mBuffer.fill(color); +} + +/* inherits documentation from base class */ +void QCPPaintBufferPixmap::reallocateBuffer() +{ + 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. +*/ + +/*! + 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. +*/ +QCPPaintBufferGlPbuffer::QCPPaintBufferGlPbuffer(const QSize &size, double devicePixelRatio, int multisamples) : + QCPAbstractPaintBuffer(size, devicePixelRatio), + mGlPBuffer(0), + mMultisamples(qMax(0, multisamples)) +{ + QCPPaintBufferGlPbuffer::reallocateBuffer(); +} + +QCPPaintBufferGlPbuffer::~QCPPaintBufferGlPbuffer() +{ + if (mGlPBuffer) + delete mGlPBuffer; +} + +/* 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; + } + + 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; + + 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. +*/ + +/*! + 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 glContext, QWeakPointer glPaintDevice) : + QCPAbstractPaintBuffer(size, devicePixelRatio), + mGlContext(glContext), + mGlPaintDevice(glPaintDevice), + mGlFrameBuffer(0) +{ + QCPPaintBufferGlFbo::reallocateBuffer(); +} + +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; + } + + 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() +{ + if (mGlFrameBuffer && mGlFrameBuffer->isBound()) + mGlFrameBuffer->release(); + else + qDebug() << Q_FUNC_INFO << "Either OpenGL frame buffer not valid or was not bound"; +} + +/* inherits documentation from base class */ +void QCPPaintBufferGlFbo::draw(QCPPainter *painter) const +{ + if (!painter || !painter->isActive()) + { + 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 @@ -670,44 +959,58 @@ void QCPScatterStyle::drawShape(QCPPainter *painter, double x, double y) const /*! \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(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(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. First example: 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 + pressEvent – releaseEvent – doubleClickEvent – releaseEvent. + + 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; -} +/*! \overload -/*! - 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); -} - -/*! 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 @@ -1435,14 +2086,6 @@ QCPRange QCPRange::sanitizedForLinScale() const return sanitizedRange; } -/*! - 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. @@ -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 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= 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= 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() << mDataRanges.first(); + if (mDataRanges.first().length() > 1) + mDataRanges.first().setEnd(mDataRanges.first().begin()+1); + } + break; + } + case QCP::stDataRange: + { + mDataRanges = QList() << 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; iorientation() == 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 Qt::NoBrush. + + \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 QCPLayout::getSectionSizes(QVector maxSizes, QVector 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. @@ -2712,6 +4209,77 @@ void QCPLayoutGrid::setRowSpacing(int pixels) mRowSpacing = 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 tempElements; + if (rearrange) + { + tempElements.reserve(elCount); + for (int i=0; i= 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 QCPLayoutGrid::elements(bool recursive) const { QList 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; rowelements(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, QVector2D(qCos(angle), qSin(angle))); + 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 QSharedPointer, 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: + +
+ + + + + + + +
QCPAxisTickerFixed\image html axisticker-fixed.png
QCPAxisTickerLog\image html axisticker-log.png
QCPAxisTickerPi\image html axisticker-pi.png
QCPAxisTickerText\image html axisticker-text.png
QCPAxisTickerDateTime\image html axisticker-datetime.png
QCPAxisTickerTime\image html axisticker-time.png + \image html axisticker-time2.png
+
+ + \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 &ticks, QVector *subTicks, QVector *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(); + } + + // 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 QCPAxisTicker::createSubTickVector(int subTickCount, const QVector &ticks) +{ + QVector result; + if (subTickCount <= 0 || ticks.size() < 2) + return result; + + result.reserve((ticks.size()-1)*subTickCount); + for (int i=1; i QCPAxisTicker::createTickVector(double tickStep, const QCPRange &range) +{ + QVector 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 QCPAxisTicker::createLabelVector(const QVector &ticks, const QLocale &locale, QChar formatChar, int precision) +{ + QVector result; + result.reserve(ticks.size()); + for (int i=0; i &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 &candidates) const +{ + if (candidates.size() == 1) + return candidates.first(); + QVector::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() << 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 toTime_t()/setTime_t() methods + with a precision of one second. Since Qt 4.7, millisecond accuracy can be obtained from QDateTime + by using QDateTime::fromMSecsSinceEpoch()/1000.0. 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 + Qt::LocalTime. 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 Qt::UTC + 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() + << 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 QCPAxisTickerDateTime::createTickVector(double tickStep, const QCPRange &range) +{ + QVector 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 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) +{ +# 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(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 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(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 &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 &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 &positions, const QVector 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 &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 &positions, const QVector &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 QCPAxisTickerText::createTickVector(double tickStep, const QCPRange &range) +{ + Q_UNUSED(tickStep) + QVector result; + if (mTicks.isEmpty()) + return result; + + QMap::const_iterator start = mTicks.lowerBound(range.lower); + QMap::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::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(" ") : QLatin1String("")) + .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 "eb". 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 QCPAxisTickerLog::createTickVector(double tickStep, const QCPRange &range) +{ + Q_UNUSED(tickStep) + QVector 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; imTickVector.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; icoordToPixel(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; imTickVector.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; icoordToPixel(mParentAxis->mTickVector.at(i)); // y @@ -3900,17 +7264,21 @@ void QCPGrid::drawSubGridLines(QCPPainter *painter) const \image html AxisRectSpacingOverview.png
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.
- + + 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 +*/ + +/*! \fn int QCPAxis::pixelOrientation() const + + 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 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::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. -*/ - /*! \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. - 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. + 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. + + \ref setNumberPrecision */ void QCPAxis::setScaleType(QCPAxis::ScaleType type) { @@ -4182,24 +7555,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. @@ -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 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(); } } @@ -4536,36 +7798,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 double 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. @@ -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(). + 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. - 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 Qt::LocalTime. However, - if the date time values passed to QCustomPlot are given in the UTC spec, set \a - timeSpec to Qt::UTC to get the correct axis labels. - - \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) { @@ -4768,58 +7952,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 &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 &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 @@ -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 mAutoTickCount 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 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 subTickPositions; // the final coordToPixel transformed vector passed to QCPAxisPainter QVector tickPositions; // the final coordToPixel transformed vector passed to QCPAxisPainter QVector 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 0) + + if (mSubTicks) { const int subTickCount = mSubTickVector.size(); - for (int i=0; itype = 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. + Prepares the internal tick vector, sub tick vector and tick label vector. This is done by calling + QCPAxisTicker::generate on the currently installed ticker. - 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. + 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. */ -void QCPAxis::visibleTickBounds(int &lowIndex, int &highIndex) const +void QCPAxis::setupTickVectors() { - bool lowFound = false; - bool highFound = false; - lowIndex = 0; - highIndex = -1; + if (!mParentPlot) return; + if ((!mTicks && !mTickLabels && !mGrid->visible()) || mRange.size() <= 0) return; - 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 1.0/qLn(mScaleLogBase) in \ref setScaleLogBase. - - \see basePow, setScaleLogBase, setScaleType -*/ -double QCPAxis::baseLog(double value) const -{ - return qLn(value)*mScaleLogBaseLogInv; -} - -/*! \internal - - A power function with the base mScaleLogBase, used mostly for coordinate transforms in - logarithmic scales with arbitrary log base. - - \see baseLog, setScaleLogBase, setScaleType -*/ -double QCPAxis::basePow(double value) const -{ - return qPow(mScaleLogBase, value); + QVector 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 tickPositions; // the final coordToPixel transformed vector passed to QCPAxisPainter QVector 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; iantialiasing(); 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 Qt::NoPen as \a pen + and a color like Qt::blue as \a brush. Notice however, that the corresponding call\n + QCPScatterStyle(QCPScatterShape::ssCircle, Qt::NoPen, Qt::blue, 5)\n + doesn't necessarily lead C++ to use this constructor in some cases, but might mistake + Qt::NoPen 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 QBrush(Qt::blue) + instead of just Qt::blue, 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 Qt::NoPen. 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(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 The name of the plottable. QPen \b mPen - 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) - - QPen \b mSelectedPen - The generic pen that should be used when the plottable is selected (hint: \ref mainPen gives you the right pen, depending on selection state). + 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) QBrush \b mBrush - 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) + 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) - QBrush \b mSelectedBrush - The generic brush that should be used when the plottable is selected (hint: \ref mainBrush gives you the right brush, depending on selection state). + QPointer<\ref QCPAxis> \b mKeyAxis, \b mValueAxis + 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. - QPointer\b mKeyAxis, \b mValueAxis - 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. + \ref QCPSelectionDecorator \b mSelectionDecorator + 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. - bool \b mSelected - indicates whether the plottable is selected or not. + \ref QCP::SelectionType \b mSelectable + 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. + + \ref QCPDataSelection \b mSelection + Holds the current selection state of the plottable's data, i.e. the selected data ranges (\ref QCPDataRange). */ -/* start of documentation of pure virtual functions */ +/* start of documentation of inline functions */ -/*! \fn void QCPAbstractPlottable::clearData() = 0 - Clears all data in the plottable. +/*! \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 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 - 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). + 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). + + If \a inKeyRange has both lower and upper bound set to zero (is equal to QCPRange()), + 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::selectableChanged(bool selectable); +/*! \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(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; + } } /*! @@ -6887,18 +10492,6 @@ void QCPAbstractPlottable::setAntialiasedScatters(bool enabled) mAntialiasedScatters = 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. @@ -6912,17 +10505,6 @@ void QCPAbstractPlottable::setPen(const QPen &pen) mPen = 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. @@ -6937,17 +10519,6 @@ void QCPAbstractPlottable::setBrush(const QBrush &brush) mBrush = 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. @@ -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.) - - However, even when \a selectable was set to false, it is possible to set the selection manually, - by calling \ref setSelected directly. - - \see setSelected -*/ -void QCPAbstractPlottable::setSelectable(bool selectable) -{ - if (mSelectable != selectable) - { - mSelectable = selectable; - emit selectableChanged(mSelectable); - } -} /*! - 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. - + 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). + 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. + you wish to change the selection state programmatically. - This function can change the selection state even when \ref setSelectable was set to false. + 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::setSelected(bool selected) +void QCPAbstractPlottable::setSelection(QCPDataSelection selection) { - if (mSelected != selected) + selection.enforceType(mSelectable); + if (mSelection != selection) { - mSelected = selected; - emit selectionChanged(mSelected); + 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 setSelection, QCP::SelectionType +*/ +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); + } + } +} + + +/*! + 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 +*/ +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; } + + 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(); } + + 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::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 + + 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,50 +10810,91 @@ 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) - return false; - - if (!mParentPlot->legend->hasItemWithPlottable(this)) + if (!legend) { - mParentPlot->legend->addItem(new QCPPlottableLegendItem(mParentPlot->legend, this)); + 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 (!legend->hasItemWithPlottable(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. - +/*! \overload + + Adds this plottable to the legend of the parent QCustomPlot (\ref QCustomPlot::legend). + + \see removeFromLegend +*/ +bool QCPAbstractPlottable::addToLegend() +{ + if (!mParentPlot || !mParentPlot->legend) + return false; + else + return addToLegend(mParentPlot->legend); +} + +/*! \overload + + Removes the plottable from the specifed \a legend. This means the \ref 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 */ +bool QCPAbstractPlottable::removeFromLegend(QCPLegend *legend) const +{ + if (!legend) + { + qDebug() << Q_FUNC_INFO << "passed legend is null"; + return false; + } + + if (QCPPlottableLegendItem *lip = legend->itemWithPlottable(this)) + return legend->removeItem(lip); + else + return false; +} + +/*! \overload + + Removes the plottable from the legend of the parent QCustomPlot. + + \see addToLegend +*/ bool QCPAbstractPlottable::removeFromLegend() const { - 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 removeFromLegend(mParentPlot->legend); } /* inherits documentation from base class */ @@ -7178,107 +10912,6 @@ QCP::Interaction QCPAbstractPlottable::selectionCategory() const return QCP::iSelectPlottables; } -/*! \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 -*/ -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; } - - if (keyAxis->orientation() == Qt::Horizontal) - { - x = keyAxis->coordToPixel(key); - y = valueAxis->coordToPixel(value); - } else - { - y = keyAxis->coordToPixel(key); - x = valueAxis->coordToPixel(value); - } -} - -/*! \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)); - else - return QPointF(valueAxis->coordToPixel(value), keyAxis->coordToPixel(key)); -} - -/*! \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); - } -} - -/*! \internal - \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); -} - -/*! \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 -{ - return mSelected ? mSelectedPen : mPen; -} - -/*! \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 -{ - return mSelected ? mSelectedBrush : mBrush; -} - /*! \internal A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter @@ -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,87 +10957,61 @@ 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 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 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 */ @@ -8523,39 +12134,6 @@ void QCPAbstractItem::applyDefaultAntialiasingHint(QCPPainter *painter) const applyAntialiasingHint(painter, mAntialiased, QCP::aeItems); } -/*! \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 @@ -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::max(); for (int i=0; isetSelected()/setSelection() 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. - Plottable selection 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. + Plottable data selection 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. Item selection 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. All other selectable elements 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 DEFINES += QCUSTOMPLOT_USE_OPENGL 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. */ @@ -9364,6 +13110,33 @@ void QCustomPlot::setViewport(const QRect &rect) mPlotLayout->setOuterRect(mViewport); } +/*! + 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; isetDevicePixelRatio(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(plottable); - return false; - } - if (plottable->parentPlot() != this) - { - qDebug() << Q_FUNC_INFO << "plottable not created with this QCustomPlot as parent:" << reinterpret_cast(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(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 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 QCustomPlot::selectedGraphs() const { @@ -9795,7 +13528,7 @@ QList 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(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; } @@ -10270,6 +13996,39 @@ QCPLayoutElement *QCustomPlot::layoutElementAt(const QPointF &pos) const return currentElement; } +/*! + 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(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; isetInvalidated(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,60 +14283,39 @@ 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. - \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. + image compression can be controlled with the \a quality parameter which must be between 0 and 100 + or -1 to use the default setting. - 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. + 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. - 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) -{ - return saveRastered(fileName, width, height, scale, "PNG", quality); -} + 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. -/*! - 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. - - 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 - temporarily setting \ref QCustomPlot::setAntialiasedElements to \ref QCP::aeAll as this allows - QCustomPlot to place objects with sub-pixel accuracy. + 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 @@ -10567,38 +14324,90 @@ 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. + \see savePdf, saveBmp, saveJpg, saveRastered +*/ +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, resolution, resolutionUnit); +} + +/*! + 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 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. - 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(). + \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. \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); - - // emit specialized object double click signals: - if (QCPAbstractPlottable *ap = qobject_cast(clickedLayerable)) - emit plottableDoubleClick(ap, event); - else if (QCPAxis *ax = qobject_cast(clickedLayerable)) - emit axisDoubleClick(ax, details.value(), event); - else if (QCPAbstractItem *ai = qobject_cast(clickedLayerable)) - emit itemDoubleClick(ai, event); - else if (QCPLegend *lg = qobject_cast(clickedLayerable)) - emit legendDoubleClick(lg, 0, event); - else if (QCPAbstractLegendItem *li = qobject_cast(clickedLayerable)) - emit legendDoubleClick(li->parentLegend(), li, event); - else if (QCPPlotTitle *pt = qobject_cast(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) + // determine layerable under the cursor (this event is called instead of the second press event in a double-click): + QList details; + QList candidates = layerableListAt(mMousePressPos, false, &details); + for (int i=0; imouseReleaseEvent(event); - mMouseEventElement = 0; + 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; + } } - //QWidget::mouseDoubleClickEvent(event); don't call base class implementation because it would just cause a mousePress/ReleaseEvent, which we don't want. + // emit specialized object double click signals: + if (!candidates.isEmpty()) + { + if (QCPAbstractPlottable *ap = qobject_cast(candidates.first())) + { + int dataIndex = 0; + if (!details.first().value().isEmpty()) + dataIndex = details.first().value().dataRange().begin(); + emit plottableDoubleClick(ap, dataIndex, event); + } else if (QCPAxis *ax = qobject_cast(candidates.first())) + emit axisDoubleClick(ax, details.first().value(), event); + else if (QCPAbstractItem *ai = qobject_cast(candidates.first())) + emit itemDoubleClick(ai, event); + else if (QCPLegend *lg = qobject_cast(candidates.first())) + emit legendDoubleClick(lg, 0, event); + else if (QCPAbstractLegendItem *li = qobject_cast(candidates.first())) + emit legendDoubleClick(li->parentLegend(), li, 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 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(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 details; + QList candidates = layerableListAt(mMousePressPos, false, &details); + for (int i=0; iaccept(); // 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(clickedLayerable)) - emit plottableClick(ap, event); - else if (QCPAxis *ax = qobject_cast(clickedLayerable)) - emit axisClick(ax, details.value(), event); - else if (QCPAbstractItem *ai = qobject_cast(clickedLayerable)) + // emit specialized click signals of QCustomPlot instance: + if (QCPAbstractPlottable *ap = qobject_cast(mMouseEventLayerable)) + { + int dataIndex = 0; + if (!mMouseEventLayerableDetails.value().isEmpty()) + dataIndex = mMouseEventLayerableDetails.value().dataRange().begin(); + emit plottableClick(ap, dataIndex, event); + } else if (QCPAxis *ax = qobject_cast(mMouseEventLayerable)) + emit axisClick(ax, mMouseEventLayerableDetails.value(), event); + else if (QCPAbstractItem *ai = qobject_cast(mMouseEventLayerable)) emit itemClick(ai, event); - else if (QCPLegend *lg = qobject_cast(clickedLayerable)) + else if (QCPLegend *lg = qobject_cast(mMouseEventLayerable)) emit legendClick(lg, 0, event); - else if (QCPAbstractLegendItem *li = qobject_cast(clickedLayerable)) + else if (QCPAbstractLegendItem *li = qobject_cast(mMouseEventLayerable)) emit legendClick(li->parentLegend(), li, event); - else if (QCPPlotTitle *pt = qobject_cast(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 { - mMouseEventElement->mouseReleaseEvent(event); - mMouseEventElement = 0; + // finish selection rect, the appropriate action will be taken via signal-slot connection: + mSelectionRect->endSelection(event); + } else + { + // 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 candidates = layerableListAt(event->pos(), false); + for (int i=0; iaccept(); // 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()) @@ -10903,6 +14713,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(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(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(createPaintBuffer())); + } + } + } + // remove unneeded buffers: + while (mPaintBuffers.size()-1 > bufferIndex) + mPaintBuffers.removeLast(); + // resize buffers to viewport size and clear contents: + for (int i=0; isetSize(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; iinvalidated()) + 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(surface); + mGlContext = QSharedPointer(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(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 @@ -10973,6 +14980,261 @@ void QCustomPlot::legendRemoved(QCPLegend *legend) this->legend = 0; } +/*! \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 QVariant(\ref QCPDataSelection). 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 > 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(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 >::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 >::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 affectedAxes = QList() << axisRect->rangeZoomAxes(Qt::Horizontal) << axisRect->rangeZoomAxes(Qt::Vertical); + affectedAxes.removeAll(static_cast(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(plottable); + return false; + } + if (plottable->parentPlot() != this) + { + qDebug() << Q_FUNC_INFO << "plottable not created with this QCustomPlot as parent:" << reinterpret_cast(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(item); + return false; + } + if (item->parentPlot() != this) + { + qDebug() << Q_FUNC_INFO << "item not created with this QCustomPlot as parent:" << reinterpret_cast(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 @@ -10986,41 +15248,71 @@ void QCustomPlot::updateLayerIndices() const } /*! \internal - - Returns the 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.) + + 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). + 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 layerableListAt, layoutElementAt, axisRectAt */ QCPLayerable *QCustomPlot::layerableAt(const QPointF &pos, bool onlySelectable, QVariant *selectionDetails) const { + QList details; + QList 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). 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 +*/ +QList QCustomPlot::layerableListAt(const QPointF &pos, bool onlySelectable, QList *selectionDetails) const +{ + QList result; for (int layerIndex=mLayers.size()-1; layerIndex>=0; --layerIndex) { const QList 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 @@ -11163,10 +15482,25 @@ void QCustomPlot::toPainter(QCPPainter *painter, int width, int height) the data range specified on the plottable instance can be controlled with \ref setPeriodic. */ +/*! + 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 [row*columnCount + column], you can set \a dataIndexFactor to columnCount 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 data[i*dataIndexFactor]. + + 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= 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= 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) { @@ -11521,6 +15976,21 @@ QCPColorGradient QCPColorGradient::inverted() const return result; } +/*! \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::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 @@ -11533,16 +16003,17 @@ void QCPColorGradient::updateColorBuffer() if (mColorStops.size() > 1) { double indexToPosFactor = 1.0/(double)(mLevelCount-1); + const bool useAlpha = stopsUseAlpha(); for (int i=0; i::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(); + 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::const_iterator high = it; @@ -11552,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: @@ -11571,7 +16053,20 @@ 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; } } @@ -11579,13 +16074,306 @@ void QCPColorGradient::updateColorBuffer() } } else if (mColorStops.size() == 1) { - mColorBuffer.fill(mColorStops.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(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 points(averageCount); + QPointF pointsAverage; + int currentIndex = dataIndex; + for (int i=0; ikeyAxis(); + 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 */ //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -11839,21 +16627,22 @@ QList 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) @@ -11887,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; } @@ -11939,28 +16741,60 @@ bool QCPAxisRect::removeAxis(QCPAxis *axis) return false; } +/*! + 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 &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. @@ -11998,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) { @@ -12048,7 +16868,7 @@ QList QCPAxisRect::plottables() const QList result; for (int i=0; imPlottables.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; @@ -12118,6 +16938,8 @@ QList 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) { @@ -12249,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 QCPAxisRect::rangeDragAxes(Qt::Orientation orientation) +{ + QList result; + if (orientation == Qt::Horizontal) + { + for (int i=0; i QCPAxisRect::rangeZoomAxes(Qt::Orientation orientation) +{ + QList result; + if (orientation == Qt::Horizontal) + { + for (int i=0; i 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 axes) +{ + QList 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 horizontal, QList vertical) +{ + mRangeDragHorzAxis.clear(); + foreach (QCPAxis *ax, horizontal) + { + QPointer axPointer(ax); + if (!axPointer.isNull()) + mRangeDragHorzAxis.append(axPointer); + else + qDebug() << Q_FUNC_INFO << "invalid axis passed in horizontal list:" << reinterpret_cast(ax); + } + mRangeDragVertAxis.clear(); + foreach (QCPAxis *ax, vertical) + { + QPointer axPointer(ax); + if (!axPointer.isNull()) + mRangeDragVertAxis.append(axPointer); + else + qDebug() << Q_FUNC_INFO << "invalid axis passed in vertical list:" << reinterpret_cast(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 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 axes) +{ + QList 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 horizontal, QList vertical) +{ + mRangeZoomHorzAxis.clear(); + foreach (QCPAxis *ax, horizontal) + { + QPointer axPointer(ax); + if (!axPointer.isNull()) + mRangeZoomHorzAxis.append(axPointer); + else + qDebug() << Q_FUNC_INFO << "invalid axis passed in horizontal list:" << reinterpret_cast(ax); + } + mRangeZoomVertAxis.clear(); + foreach (QCPAxis *ax, vertical) + { + QPointer axPointer(ax); + if (!axPointer.isNull()) + mRangeZoomVertAxis.append(axPointer); + else + qDebug() << Q_FUNC_INFO << "invalid axis passed in vertical list:" << reinterpret_cast(ax); + } } /*! @@ -12383,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 @@ -12458,6 +17457,31 @@ int QCPAxisRect::calculateAutoMargin(QCP::MarginSide side) return 0; } +/*! \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 @@ -12469,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) { @@ -12484,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; irange()); + mDragStartVertRange.clear(); + for (int i=0; irange()); } } } @@ -12499,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; imScaleType == 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; imScaleType == 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()) { @@ -12560,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 @@ -12581,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; iscaleRange(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; iscaleRange(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 //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -12649,7 +17702,7 @@ QCPAbstractLegendItem::QCPAbstractLegendItem(QCPLegend *parent) : mSelected(false) { setLayer(QLatin1String("legend")); - setMargins(QMargins(8, 2, 8, 2)); + setMargins(QMargins(0, 0, 0, 0)); } /*! @@ -12818,6 +17871,7 @@ QCPPlottableLegendItem::QCPPlottableLegendItem(QCPLegend *parent, QCPAbstractPlo QCPAbstractLegendItem(parent), mPlottable(plottable) { + setAntialiased(false); } /*! \internal @@ -12876,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); } } @@ -12884,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 { @@ -12907,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 */ @@ -12939,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); @@ -12957,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)); @@ -13218,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 { @@ -13247,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 @@ -13255,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 { @@ -13279,26 +18354,31 @@ bool QCPLegend::hasItemWithPlottable(const QCPAbstractPlottable *plottable) cons } /*! - Adds \a item to the legend, if it's not present already. - + 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) @@ -13306,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; } @@ -13367,6 +18453,8 @@ QList QCPLegend::selectedItems() const overrides set with \ref QCustomPlot::setAntialiasedElements and \ref QCustomPlot::setNotAntialiasedElements. + \seebaseclassmethod + \see setAntialiased */ void QCPLegend::applyDefaultAntialiasingHint(QCPPainter *painter) const @@ -13464,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. @@ -13497,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 false, the selection state may be changed programmatically via \ref setSelected. */ -void QCPPlotTitle::setSelectable(bool selectable) +void QCPTextElement::setSelectable(bool selectable) { if (mSelectable != selectable) { @@ -13606,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) { @@ -13622,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())); @@ -13636,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(); @@ -13646,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(); @@ -13656,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) @@ -13670,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) { @@ -13681,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) @@ -13694,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 true, else mFont is returned. */ -QFont QCPPlotTitle::mainFont() const +QFont QCPTextElement::mainFont() const { return mSelected ? mSelectedFont : mFont; } @@ -13709,10 +18955,15 @@ QFont QCPPlotTitle::mainFont() const Returns the main color to be used. This is mSelectedTextColor if \ref setSelected is set to true, 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 */ //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -13738,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 @@ -13775,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. @@ -13789,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. @@ -13863,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) { @@ -13876,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 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))); @@ -13897,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() << mColorAxis.data()); } } @@ -14058,9 +19312,9 @@ void QCPColorScale::rescaleDataRange(bool onlyVisibleMaps) QList 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; irealVisibility() && onlyVisibleMaps) @@ -14070,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; @@ -14155,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 */ @@ -14250,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) { @@ -14280,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 data(n); @@ -14289,7 +19547,7 @@ void QCPColorScaleAxisRectPrivate::updateGradientImage() { w = n; h = rect().height(); - mGradientImage = QImage(w, h, QImage::Format_RGB32); + mGradientImage = QImage(w, h, format); QVector pixels; for (int y=0; y(mGradientImage.scanLine(y))); @@ -14300,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(mGradientImage.scanLine(y)); @@ -14361,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) - \see QCPDataMap + 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 QCPGraphDataContainer */ -/*! - Constructs a data point with key, value and all errors set to zero. +/* 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. */ -QCPData::QCPData() : + +/*! \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 and value set to zero. +*/ +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) { } @@ -14419,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 @@ -14434,7 +19739,7 @@ QCPData::QCPData(double key, double value) : (qQNaN() or std::numeric_limits::quiet_NaN()) 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). @@ -14454,11 +19759,11 @@ QCPData::QCPData(double key, double value) : /* start of documentation of inline functions */ -/*! \fn QCPDataMap *QCPGraph::data() const +/*! \fn QSharedPointer 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 */ @@ -14469,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(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. - - 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. - - 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. -*/ -void QCPGraph::setData(QCPDataMap *data, bool copy) -{ - if (mData == data) - { - qDebug() << Q_FUNC_INFO << "The data pointer is already in (and owned by) this plottable" << reinterpret_cast(data); - return; - } - if (copy) - { - *mData = *data; - } else - { - delete mData; - mData = data; - } } /*! \overload - Replaces the current data with the provided points in \a key and \a value pairs. The provided + 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 + + If you do not wish to share containers, but create a copy from an existing container, rather use + the \ref QCPDataContainer::set method on the graph's data container directly: + \snippet documentation/doc-code-snippets/mainwindow.cpp qcpgraph-datasharing-2 + + \see addData +*/ +void QCPGraph::setData(QSharedPointer data) +{ + mDataContainer = data; +} + +/*! \overload + + 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 &key, const QVector &value) -{ - mData->clear(); - int n = key.size(); - n = qMin(n, value.size()); - QCPData newData; - for (int i=0; iinsertMulti(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 &key, const QVector &value, const QVector &valueError) -{ - mData->clear(); - int n = key.size(); - n = qMin(n, value.size()); - n = qMin(n, valueError.size()); - QCPData newData; - for (int i=0; iinsertMulti(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 &key, const QVector &value, const QVector &valueErrorMinus, const QVector &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; iinsertMulti(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. + 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. + \see addData */ -void QCPGraph::setDataKeyError(const QVector &key, const QVector &value, const QVector &keyError) +void QCPGraph::setData(const QVector &keys, const QVector &values, bool alreadySorted) { - mData->clear(); - int n = key.size(); - n = qMin(n, value.size()); - n = qMin(n, keyError.size()); - QCPData newData; - for (int i=0; iinsertMulti(key[i], newData); - } + mDataContainer->clear(); + addData(keys, values, alreadySorted); } -/*! - \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 &key, const QVector &value, const QVector &keyErrorMinus, const QVector &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; iinsertMulti(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. - - For asymmetrical errors (plus different from minus), see the overloaded version of this function. -*/ -void QCPGraph::setDataBothError(const QVector &key, const QVector &value, const QVector &keyError, const QVector &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; iinsertMulti(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. -*/ -void QCPGraph::setDataBothError(const QVector &key, const QVector &value, const QVector &keyErrorMinus, const QVector &keyErrorPlus, const QVector &valueErrorMinus, const QVector &valueErrorPlus) -{ - 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; iinsertMulti(key[i], newData); - } -} - - /*! 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. @@ -14735,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; -} + 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 pen with which the error bars will be drawn. - \see setErrorBarSize, setErrorType -*/ -void QCPGraph::setErrorPen(const QPen &pen) -{ - mErrorPen = pen; -} + If \a skip is set to 0 (default), all scatter points are drawn. -/*! - Sets the width of the handles at both ends of an error bar in pixels. + \see setScatterStyle */ -void QCPGraph::setErrorBarSize(double size) +void QCPGraph::setScatterSkip(int skip) { - mErrorBarSize = size; -} - -/*! - 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 -*/ -void QCPGraph::setErrorBarSkipSymbol(bool enabled) -{ - mErrorBarSkipSymbol = enabled; + mScatterSkip = qMax(0, skip); } /*! @@ -14845,273 +19939,149 @@ void QCPGraph::setAdaptiveSampling(bool enabled) mAdaptiveSampling = enabled; } -/*! - Adds the provided data points in \a dataMap to the current data. +/*! \overload - 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. + 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. - \see removeData + 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 QCPGraph::addData(const QCPDataMap &dataMap) +void QCPGraph::addData(const QVector &keys, const QVector &values, bool alreadySorted) { - mData->unite(dataMap); + 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 tempData(n); + QVector::iterator it = tempData.begin(); + const QVector::iterator itEnd = tempData.end(); + int i = 0; + while (it != itEnd) + { + 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 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. + Adds the provided data point as \a key and \a value to the current data. - \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 + 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(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. - - 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 QVector &keys, const QVector &values) -{ - int n = qMin(keys.size(), values.size()); - QCPData newData; - for (int i=0; iinsertMulti(newData.key, newData); - } -} - -/*! - 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); -} - -/*! \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 -*/ -void QCPGraph::clearData() -{ - 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) 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 + { + QCPGraphDataContainer::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; } -/*! \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 +/* inherits documentation from base class */ +QCPRange QCPGraph::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const { - rescaleKeyAxis(onlyEnlarge, includeErrorBars); - rescaleValueAxis(onlyEnlarge, includeErrorBars); + return mDataContainer->keyRange(foundRange, inSignDomain); } -/*! \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 +/* inherits documentation from base class */ +QCPRange QCPGraph::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) 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 (onlyEnlarge) - { - if (keyAxis->range().lower < newRange.lower) - newRange.lower = keyAxis->range().lower; - if (keyAxis->range().upper > newRange.upper) - newRange.upper = keyAxis->range().upper; - } - keyAxis->setRange(newRange); - } -} - -/*! \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 -{ - // 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; } - - 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); - } + 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 *lineData = new QVector; - QVector *scatterData = 0; - if (!mScatterStyle.isNone()) - scatterData = new QVector; + QVector lines, scatters; // line and (if necessary) scatter pixel coordinates will be stored here while iterating over segments - // fill vectors with data appropriate to plot style: - getPlotData(lineData, scatterData); - - // 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 selectedSegments, unselectedSegments, allSegments; + getDataSegments(selectedSegments, unselectedSegments); + allSegments << unselectedSegments << selectedSegments; + for (int i=0; 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 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); + } + } - // 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); - - // 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 */ @@ -15151,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 *lineData, QVector *scatterData) const +void QCPGraph::getLines(QVector *lines, const QCPDataRange &dataRange) const { - switch(mLineStyle) + if (!lines) return; + QCPGraphDataContainer::const_iterator begin, end; + getVisibleDataBounds(begin, end, dataRange); + if (begin == end) { - 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; + lines->clear(); + return; + } + + QVector lineData; + if (mLineStyle != lsNone) + getOptimizedLineData(&lineData, begin, end); + + switch (mLineStyle) + { + 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 -*/ -void QCPGraph::getScatterPlotData(QVector *scatterData) const -{ - getPreparedData(0, scatterData); -} -/*! \internal - - Places the raw data points needed for a normal linearly connected graph in \a linePixelData. + 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. - 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. - - \see drawLinePlot + \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::getLinePlotData(QVector *linePixelData, QVector *scatterData) const +void QCPGraph::getScatters(QVector *scatters, const QCPDataRange &dataRange) const { + if (!scatters) return; 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"; scatters->clear(); return; } - QVector 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()); - - // transform lineData points to pixels: - if (keyAxis->orientation() == Qt::Vertical) + QCPGraphDataContainer::const_iterator begin, end; + getVisibleDataBounds(begin, end, dataRange); + if (begin == end) { - for (int i=0; icoordToPixel(lineData.at(i).value)); - (*linePixelData)[i].setY(keyAxis->coordToPixel(lineData.at(i).key)); - } - } else // key axis is horizontal - { - for (int i=0; icoordToPixel(lineData.at(i).key)); - (*linePixelData)[i].setY(valueAxis->coordToPixel(lineData.at(i).value)); - } + scatters->clear(); + return; } -} - -/*! - \internal - Places the raw data points needed for a step plot with left oriented steps in \a lineData. - - 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. - \see drawLinePlot -*/ -void QCPGraph::getStepLeftPlotData(QVector *linePixelData, QVector *scatterData) const -{ - 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; } - - QVector 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: + QVector data; + getOptimizedScatterData(&data, begin, end); + scatters->resize(data.size()); if (keyAxis->orientation() == Qt::Vertical) { - double lastValue = valueAxis->coordToPixel(lineData.first().value); - double key; - for (int i=0; icoordToPixel(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); + 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 // key axis is horizontal + } else { - double lastValue = valueAxis->coordToPixel(lineData.first().value); - double key; - for (int i=0; icoordToPixel(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); - } - } -} - -/*! - \internal - Places the raw data points needed for a step plot with right oriented steps in \a lineData. - - 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. - - \see drawLinePlot -*/ -void QCPGraph::getStepRightPlotData(QVector *linePixelData, QVector *scatterData) const -{ - 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; } - - QVector 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: - if (keyAxis->orientation() == Qt::Vertical) - { - double lastKey = keyAxis->coordToPixel(lineData.first().key); - double value; - for (int i=0; icoordToPixel(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); - } - } else // key axis is horizontal - { - double lastKey = keyAxis->coordToPixel(lineData.first().key); - double value; - for (int i=0; icoordToPixel(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); - } - } -} - -/*! - \internal - Places the raw data points needed for a step plot with centered steps in \a lineData. - - 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. - - \see drawLinePlot -*/ -void QCPGraph::getStepCenterPlotData(QVector *linePixelData, QVector *scatterData) const -{ - 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; } - - QVector 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: - 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; icoordToPixel(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); - } 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; icoordToPixel(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); - } - (*linePixelData)[lineData.size()*2-1].setX(lastKey); - (*linePixelData)[lineData.size()*2-1].setY(lastValue); - } - -} - -/*! - \internal - Places the raw data points needed for an impulse plot in \a lineData. - - 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. - - \see drawImpulsePlot -*/ -void QCPGraph::getImpulsePlotData(QVector *linePixelData, QVector *scatterData) const -{ - 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 lineData; - getPreparedData(&lineData, scatterData); - linePixelData->resize(lineData.size()*2); // no need to reserve 2 extra points because impulse plot has no fill - - // transform lineData points to pixels: - if (keyAxis->orientation() == Qt::Vertical) - { - double zeroPointX = valueAxis->coordToPixel(0); - double key; - for (int i=0; icoordToPixel(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); - } - } else // key axis is horizontal - { - double zeroPointY = valueAxis->coordToPixel(0); - double key; - for (int i=0; icoordToPixel(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)); + 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 - - 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). + 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. - 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 + 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::drawFill(QCPPainter *painter, QVector *lineData) const +QVector QCPGraph::dataToLines(const QVector &data) const +{ + QVector result; + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + 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 data points to pixels: + if (keyAxis->orientation() == Qt::Vertical) + { + for (int i=0; icoordToPixel(data.at(i).value)); + result[i].setY(keyAxis->coordToPixel(data.at(i).key)); + } + } else // key axis is horizontal + { + for (int i=0; icoordToPixel(data.at(i).key)); + result[i].setY(valueAxis->coordToPixel(data.at(i).value)); + } + } + return result; +} + +/*! \internal + + 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. + + 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 +*/ +QVector QCPGraph::dataToStepLeftLines(const QVector &data) const +{ + QVector result; + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return result; } + + 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 lastValue = valueAxis->coordToPixel(data.first().value); + for (int i=0; icoordToPixel(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(data.first().value); + for (int i=0; icoordToPixel(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 + + 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. + + 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 +*/ +QVector QCPGraph::dataToStepRightLines(const QVector &data) const +{ + QVector result; + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return result; } + + 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(data.first().key); + for (int i=0; icoordToPixel(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(data.first().key); + for (int i=0; icoordToPixel(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 + + 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. + + 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 +*/ +QVector QCPGraph::dataToStepCenterLines(const QVector &data) const +{ + QVector result; + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return result; } + + 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(data.first().key); + double lastValue = valueAxis->coordToPixel(data.first().value); + result[0].setX(lastValue); + result[0].setY(lastKey); + for (int i=1; icoordToPixel(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(data.first().key); + double lastValue = valueAxis->coordToPixel(data.first().value); + result[0].setX(lastKey); + result[0].setY(lastValue); + for (int i=1; icoordToPixel(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); + } + result[data.size()*2-1].setX(lastKey); + result[data.size()*2-1].setY(lastValue); + } + return result; +} + +/*! \internal + + 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. + + 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 +*/ +QVector QCPGraph::dataToImpulseLines(const QVector &data) const +{ + QVector result; + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return result; } + + result.resize(data.size()*2); // no need to reserve 2 extra points because impulse plot has no fill + + // transform data points to pixels: + if (keyAxis->orientation() == Qt::Vertical) + { + for (int i=0; icoordToPixel(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 + { + for (int i=0; icoordToPixel(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 using the specified \a painter, with the currently set brush. + + \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 *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 *scatterData) const +void QCPGraph::drawScatterPlot(QCPPainter *painter, const QVector &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; isize(); ++i) - drawError(painter, valueAxis->coordToPixel(scatterData->at(i).value), keyAxis->coordToPixel(scatterData->at(i).key), scatterData->at(i)); - } else - { - for (int i=0; isize(); ++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; isize(); ++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; isize(); ++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 *lineData) const +void QCPGraph::drawLinePlot(QCPPainter *painter, const QVector &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 *lineData) const +void QCPGraph::drawImpulsePlot(QCPPainter *painter, const QVector &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 *lineData, QVector *scatterData) const +void QCPGraph::getOptimizedLineData(QVector *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::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::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) + 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) { - 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) + 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 < 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 (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 (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 + } else // don't use adaptive sampling algorithm, transfer points one-to-one from the data container into the output { - QVector *dataVector = 0; - if (lineData) - dataVector = lineData; - else if (scatterData) - dataVector = scatterData; - if (dataVector) + QCPGraphDataContainer::const_iterator it = begin; + lineData->reserve(dataCount+2); // +2 for possible fill end points + while (it != end) { - 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; - } + 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 *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 { - // draw key error vertically and value 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 (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) - { - 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 + ++beginIndex; + ++begin; + } + if (begin == end) return; + int dataCount = end-begin; + int maxCount = std::numeric_limits::max(); + if (mAdaptiveSampling) { - // draw value error vertically and key error horizontally - if (mErrorType == etKey || mErrorType == etBoth) + 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 + { + 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 (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)); + it = end; + itIndex = endIndex; + } } - if (mErrorType == etValue || mErrorType == etBoth) + // main loop over data points: + while (it != end) { - 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 (it->key < currentIntervalStartKey+keyEpsilon) // data point is still within same pixel, so skip it and expand value span of this pixel if necessary { - 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 (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 (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 + { + itIndex += scatterModulo; + if (itIndex < endIndex) // make sure we didn't jump over end + it += scatterModulo; + else + { + it = end; + itIndex = endIndex; + } + } + } + // 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 + { + 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; + } + } } } } -/*! \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()) - { - lower = mData->constEnd(); - upper = mData->constEnd(); - return; - } - - // get visible data range as QMap iterators - QCPDataMap::const_iterator lbound = mData->lowerBound(mKeyAxis.data()->range().lower); - QCPDataMap::const_iterator ubound = 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 -} +/*! + This method outputs the currently visible data range via \a begin and \a end. The returned range + will also never exceed \a rangeRestriction. -/*! \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 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 *lineData) const +void QCPGraph::addFillBasePoints(QVector *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 *lineData) const +void QCPGraph::removeFillBasePoints(QVector *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 @@ -16168,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 *lineData) const +const QPolygonF QCPGraph::getChannelFillPolygon(const QVector *lines) const { if (!mChannelFillGraph) return QPolygonF(); @@ -16188,14 +21058,14 @@ const QPolygonF QCPGraph::getChannelFillPolygon(const QVector *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 otherData; - mChannelFillGraph.data()->getPlotData(&otherData, 0); + mChannelFillGraph.data()->getLines(&otherData, QCPDataRange(0, mChannelFillGraph.data()->dataCount())); if (otherData.isEmpty()) return QPolygonF(); QVector thisData; - thisData.reserve(lineData->size()+otherData.size()); // because we will join both vectors at end of this function - for (int i=0; isize(); ++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; isize(); ++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 *staticData = &thisData; @@ -16378,72 +21248,61 @@ int QCPGraph::findIndexAboveY(const QVector *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) + // calculate minimum distances to graph data points and find closestData iterator: + double minDistSqr = std::numeric_limits::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) { - // no line displayed, only calculate distance to scatter points: - QVector scatterData; - getScatterPlotData(&scatterData); - if (scatterData.size() > 0) + const double currentDistSqr = QCPVector2D(coordsToPixels(it->key, it->value)-pixelPoint).lengthSquared(); + if (currentDistSqr < minDistSqr) { - double minDistSqr = std::numeric_limits::max(); - for (int i=0; i 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 + 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::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 0) // only single data point, calculate distance to that point - { - 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 @@ -16468,253 +21327,11 @@ int QCPGraph::findIndexBelowY(const QVector *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); -} - -/*! \overload - - Allows to specify whether the error bars should be included in the range calculation. - - \see getKeyRange(bool &foundRange, SignDomain inSignDomain) -*/ -QCPRange QCPGraph::getKeyRange(bool &foundRange, SignDomain inSignDomain, bool includeErrors) const -{ - QCPRange range; - bool haveLower = false; - bool haveUpper = false; - - double current, currentErrorMinus, currentErrorPlus; - - 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; - } - } - - foundRange = haveLower && haveUpper; - return range; -} - -/*! \overload - - Allows to specify whether the error bars should be included in the range calculation. - - \see getValueRange(bool &foundRange, SignDomain inSignDomain) -*/ -QCPRange QCPGraph::getValueRange(bool &foundRange, SignDomain inSignDomain, bool includeErrors) const -{ - QCPRange range; - bool haveLower = false; - bool haveUpper = false; - - double current, currentErrorMinus, currentErrorPlus; - - 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; - } - } - - foundRange = haveLower && haveUpper; - return range; -} +/* including file 'src/plottables/plottable-curve.cpp', size 60009 */ +/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */ //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPCurveData @@ -16723,16 +21340,72 @@ QCPRange QCPGraph::getValueRange(bool &foundRange, SignDomain inSignDomain, bool /*! \class QCPCurveData \brief Holds the data of one single data point for QCPCurve. - The container for storing multiple data points is \ref QCPCurveDataMap. - The stored data is: - \li \a t: the free parameter of the curve at this curve point (cp. the mathematical vector (x(t), y(t))) - \li \a key: coordinate on the key axis of this curve point - \li \a value: coordinate on the value axis of this curve point + \li \a t: the free ordering parameter of this curve point, like in the mathematical vector (x(t), y(t)). (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 QCPCurveDataMap + 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. + + \see QCPCurveDataContainer */ +/* start documentation of inline functions */ + +/*! \fn double QCPCurveData::sortKey() const + + Returns the \a t 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 QCPCurveData QCPCurveData::fromSortKey(double sortKey) + + 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. + + 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 QCPCurveData::sortKeyIsMainKey() + + 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. + + 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 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. +*/ + +/*! \fn double QCPCurveData::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 QCPCurveData::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 curve data point with t, key and value set to zero. */ @@ -16768,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 (qQNaN() or std::numeric_limits::quiet_NaN()) 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 - Usually, you first create an instance and add it to the customPlot: + 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: \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 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(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); @@ -16816,73 +21501,61 @@ QCPCurve::QCPCurve(QCPAxis *keyAxis, QCPAxis *valueAxis) : QCPCurve::~QCPCurve() { - delete mData; -} - -/*! - Replaces the current data with the provided \a data. - - 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. -*/ -void QCPCurve::setData(QCPCurveDataMap *data, bool copy) -{ - if (mData == data) - { - qDebug() << Q_FUNC_INFO << "The data pointer is already in (and owned by) this plottable" << reinterpret_cast(data); - return; - } - if (copy) - { - *mData = *data; - } else - { - delete mData; - mData = 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 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::set method on the curve's data container directly: + \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcurve-datasharing-2 + + \see addData */ -void QCPCurve::setData(const QVector &t, const QVector &key, const QVector &value) +void QCPCurve::setData(QSharedPointer data) { - mData->clear(); - int n = t.size(); - n = qMin(n, key.size()); - n = qMin(n, value.size()); - QCPCurveData newData; - for (int i=0; iinsertMulti(newData.t, newData); - } + mDataContainer = data; } /*! \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 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 &key, const QVector &value) +void QCPCurve::setData(const QVector &t, const QVector &keys, const QVector &values, bool alreadySorted) { - mData->clear(); - int n = key.size(); - n = qMin(n, value.size()); - QCPCurveData newData; - for (int i=0; iinsertMulti(newData.t, newData); - } + mDataContainer->clear(); + addData(t, keys, values, alreadySorted); +} + + +/*! \overload + + 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 &keys, const QVector &values) +{ + mDataContainer->clear(); + addData(keys, values); } /*! @@ -16897,6 +21570,22 @@ void QCPCurve::setScatterStyle(const QCPScatterStyle &style) mScatterStyle = 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 @@ -16909,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 +/*! \overload + + 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(const QCPCurveDataMap &dataMap) +void QCPCurve::addData(const QVector &t, const QVector &keys, const QVector &values, bool alreadySorted) { - mData->unite(dataMap); + 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 tempData(n); + QVector::iterator it = tempData.begin(); + const QVector::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 in \a data to the current data. - \see removeData + + 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. + + 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(const QCPCurveData &data) +void QCPCurve::addData(const QVector &keys, const QVector &values) { - mData->insertMulti(data.t, data); + 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 + tStart = 0; + QVector tempData(n); + QVector::iterator it = tempData.begin(); + const QVector::iterator itEnd = tempData.end(); + int i = 0; + while (it != itEnd) + { + 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 } /*! \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 data point as \a t, \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 QCPCurve::addData(double t, double key, double value) { - QCPCurveData newData; - newData.t = t; - newData.key = key; - newData.value = value; - mData->insertMulti(newData.t, newData); + mDataContainer->add(QCPCurveData(t, key, value)); } /*! \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 data point as \a key and \a value to the current data. - \see removeData + 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::addData(double key, double value) { - QCPCurveData newData; - if (!mData->isEmpty()) - newData.t = (mData->constEnd()-1).key()+1; + if (!mDataContainer->isEmpty()) + mDataContainer->add(QCPCurveData((mDataContainer->constEnd()-1)->t + 1.0, key, value)); 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 &ts, const QVector &keys, const QVector &values) -{ - int n = ts.size(); - n = qMin(n, keys.size()); - n = qMin(n, values.size()); - QCPCurveData newData; - for (int i=0; iinsertMulti(newData.t, newData); - } -} - -/*! - 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). - - \see addData, clearData -*/ -void QCPCurve::removeData(double fromt, double tot) -{ - 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); -} - -/*! \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. - - \see addData, clearData -*/ -void QCPCurve::removeData(double t) -{ - mData->remove(t); -} - -/*! - Removes all data points. - \see removeData, removeDataAfter, removeDataBefore -*/ -void QCPCurve::clearData() -{ - mData->clear(); + 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 *lineData = new QVector; + QVector lines, scatters; - // 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 - - // draw curve fill: - if (mainBrush().style() != Qt::NoBrush && mainBrush().color().alpha() != 0) + // loop over and draw segments of unselected/selected data: + QList selectedSegments, unselectedSegments, allSegments; + getDataSegments(selectedSegments, unselectedSegments); + allSegments << unselectedSegments << selectedSegments; + for (int i=0; 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)) + if (painter->brush().style() != Qt::NoBrush && painter->brush().color().alpha() != 0) + painter->drawPolygon(QPolygonF(lines)); + + // draw curve line: + if (mLineStyle != lsNone) { - 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 + 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()) { - 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); + 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 */ @@ -17178,56 +21833,92 @@ void QCPCurve::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const } } -/*! \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. +/*! \internal + + Draws lines between the points in \a lines, given in pixel coordinates. + + \see drawScatterPlot, getCurveLines */ -void QCPCurve::drawScatterPlot(QCPPainter *painter, const QVector *pointData) const +void QCPCurve::drawCurveLine(QCPPainter *painter, const QVector &lines) const { - // draw scatter point symbols: - applyScattersAntialiasingHint(painter); - mScatterStyle.applyTo(painter, mPen); - for (int i=0; isize(); ++i) - if (!qIsNaN(pointData->at(i).x()) && !qIsNaN(pointData->at(i).y())) - mScatterStyle.drawShape(painter, pointData->at(i)); + if (painter->pen().style() != Qt::NoPen && painter->pen().color().alpha() != 0) + { + applyDefaultAntialiasingHint(painter); + drawPolyline(painter, lines); + } } /*! \internal - - called by QCPCurve::draw to generate a point vector (in pixel coordinates) which represents the - line of the curve. + + 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 &points, const QCPScatterStyle &style) const +{ + // draw scatter point symbols: + applyScattersAntialiasingHint(painter); + style.applyTo(painter, mPen); + for (int i=0; i *lineData) const +void QCPCurve::getCurveLines(QVector *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 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 @@ -17235,44 +21926,44 @@ void QCPCurve::getCurveData(QVector *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 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 << getOptimizedPoint(prevRegion, prevIt.value().key, prevIt.value().value, it.value().key, it.value().value, rectLeft, rectTop, rectRight, rectBottom); + if (it == itBegin) // it is first point in curve and prevIt is last one. So save optimized point for adding it to the lineData in the end + trailingPoints << getOptimizedPoint(prevRegion, prevIt->key, prevIt->value, it->key, it->value, keyMin, valueMax, keyMax, valueMin); else - lineData->append(getOptimizedPoint(prevRegion, prevIt.value().key, prevIt.value().value, it.value().key, it.value().value, rectLeft, rectTop, rectRight, rectBottom)); - lineData->append(coordsToPixels(it.value().key, it.value().value)); + lines->append(getOptimizedPoint(prevRegion, prevIt->key, prevIt->value, it->key, it->value, keyMin, valueMax, keyMax, valueMin)); + lines->append(coordsToPixels(it->key, it->value)); } } else // region didn't change { if (currentRegion == 5) // still in R, keep adding original points { - lineData->append(coordsToPixels(it.value().key, it.value().value)); + lines->append(coordsToPixels(it->key, it->value)); } else // still outside R, no need to add anything { // see how this is not doing anything? That's the main optimization... @@ -17282,50 +21973,150 @@ void QCPCurve::getCurveData(QVector *lineData) const prevRegion = currentRegion; ++it; } - *lineData << trailingPoints; + *lines << trailingPoints; } /*! \internal + + Called by \ref draw to generate points in pixel coordinates which represent the scatters of the + curve. If a scatter skip is configured (\ref setScatterSkip), the returned points are accordingly + sparser. + + Scatters that aren't visible in the current axis rect are optimized away. + + \a scatters will be filled with points in pixel coordinates, that can be drawn with \ref + drawScatterPlot. + + \a dataRange specifies the beginning and ending data indices that will be taken into account for + conversion. + + \a scatterWidth specifies the scatter width that will be used to later draw the scatters at pixel + coordinates generated by this function. This is needed here to calculate an accordingly wider + margin around the axis rect when performing the data point reduction. + + \see draw, drawScatterPlot +*/ +void QCPCurve::getScatters(QVector *scatters, const QCPDataRange &dataRange, double scatterWidth) const +{ + if (!scatters) return; + scatters->clear(); + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } - This function is part of the curve optimization algorithm of \ref getCurveData. + QCPCurveDataContainer::const_iterator begin = mDataContainer->constBegin(); + QCPCurveDataContainer::const_iterator end = mDataContainer->constEnd(); + mDataContainer->limitIteratorsToDataRange(begin, end, dataRange); + if (begin == end) + return; + const int scatterModulo = mScatterSkip+1; + const bool doScatterSkip = mScatterSkip > 0; + int endIndex = end-mDataContainer->constBegin(); - It returns the region of the given point (\a x, \a y) with respect to a rectangle defined by \a - rectLeft, \a rectTop, \a rectRight, and \a rectBottom. - - The regions are enumerated from top to bottom and left to right: + QCPRange keyRange = keyAxis->range(); + QCPRange valueRange = valueAxis->range(); + // extend range to include width of scatter symbols: + keyRange.lower = keyAxis->pixelToCoord(keyAxis->coordToPixel(keyRange.lower)-scatterWidth*keyAxis->pixelOrientation()); + keyRange.upper = keyAxis->pixelToCoord(keyAxis->coordToPixel(keyRange.upper)+scatterWidth*keyAxis->pixelOrientation()); + valueRange.lower = valueAxis->pixelToCoord(valueAxis->coordToPixel(valueRange.lower)-scatterWidth*valueAxis->pixelOrientation()); + valueRange.upper = valueAxis->pixelToCoord(valueAxis->coordToPixel(valueRange.upper)+scatterWidth*valueAxis->pixelOrientation()); + QCPCurveDataContainer::const_iterator it = begin; + int itIndex = begin-mDataContainer->constBegin(); + while (doScatterSkip && it != end && itIndex % scatterModulo != 0) // advance begin iterator to first non-skipped scatter + { + ++itIndex; + ++it; + } + if (keyAxis->orientation() == Qt::Vertical) + { + while (it != end) + { + if (!qIsNaN(it->value) && keyRange.contains(it->key) && valueRange.contains(it->value)) + scatters->append(QPointF(valueAxis->coordToPixel(it->value), keyAxis->coordToPixel(it->key))); + + // advance iterator to next (non-skipped) data point: + if (!doScatterSkip) + ++it; + else + { + itIndex += scatterModulo; + if (itIndex < endIndex) // make sure we didn't jump over end + it += scatterModulo; + else + { + it = end; + itIndex = endIndex; + } + } + } + } else + { + while (it != end) + { + if (!qIsNaN(it->value) && keyRange.contains(it->key) && valueRange.contains(it->value)) + scatters->append(QPointF(keyAxis->coordToPixel(it->key), valueAxis->coordToPixel(it->value))); + + // advance iterator to next (non-skipped) data point: + if (!doScatterSkip) + ++it; + else + { + itIndex += scatterModulo; + if (itIndex < endIndex) // make sure we didn't jump over end + it += scatterModulo; + else + { + it = end; + itIndex = endIndex; + } + } + } + } +} + +/*! \internal + + This function is part of the curve optimization algorithm of \ref getCurveLines. + + It returns the region of the given point (\a key, \a value) with respect to a rectangle defined + by \a keyMin, \a keyMax, \a valueMin, and \a valueMax. + + The regions are enumerated from top to bottom (\a valueMin to \a valueMax) and left to right (\a + keyMin to \a keyMax): +
147
258
369
- + With the rectangle being region 5, and the outer regions extending infinitely outwards. In the curve optimization algorithm, region 5 is considered to be the visible portion of the plot. */ -int QCPCurve::getRegion(double x, double y, double rectLeft, double rectTop, double rectRight, double rectBottom) const +int QCPCurve::getRegion(double key, double value, double keyMin, double valueMax, double keyMax, double valueMin) const { - if (x < rectLeft) // region 123 + if (key < keyMin) // region 123 { - if (y > rectTop) + if (value > valueMax) return 1; - else if (y < rectBottom) + else if (value < valueMin) return 3; else return 2; - } else if (x > rectRight) // region 789 + } else if (key > keyMax) // region 789 { - if (y > rectTop) + if (value > valueMax) return 7; - else if (y < rectBottom) + else if (value < valueMin) return 9; else return 8; } else // region 456 { - if (y > rectTop) + if (value > valueMax) return 4; - else if (y < rectBottom) + else if (value < valueMin) return 6; else return 5; @@ -17334,7 +22125,7 @@ int QCPCurve::getRegion(double x, double y, double rectLeft, double rectTop, dou /*! \internal - This function is part of the curve optimization algorithm of \ref getCurveData. + This function is part of the curve optimization algorithm of \ref getCurveLines. This method is used in case the current segment passes from inside the visible rect (region 5, see \ref getRegion) to any of the outer regions (\a otherRegion). The current segment is given by @@ -17347,43 +22138,43 @@ int QCPCurve::getRegion(double x, double y, double rectLeft, double rectTop, dou leaving it. It is important though that \a otherRegion correctly identifies the other region not equal to 5. */ -QPointF QCPCurve::getOptimizedPoint(int otherRegion, double otherKey, double otherValue, double key, double value, double rectLeft, double rectTop, double rectRight, double rectBottom) const +QPointF QCPCurve::getOptimizedPoint(int otherRegion, double otherKey, double otherValue, double key, double value, double keyMin, double valueMax, double keyMax, double valueMin) const { - double intersectKey = rectLeft; // initial value is just fail-safe - double intersectValue = rectTop; // initial value is just fail-safe + double intersectKey = keyMin; // initial value is just fail-safe + double intersectValue = valueMax; // initial value is just fail-safe switch (otherRegion) { case 1: // top and left edge { - intersectValue = rectTop; + intersectValue = valueMax; intersectKey = otherKey + (key-otherKey)/(value-otherValue)*(intersectValue-otherValue); - if (intersectKey < rectLeft || intersectKey > rectRight) // doesn't intersect, so must intersect other: + if (intersectKey < keyMin || intersectKey > keyMax) // doesn't intersect, so must intersect other: { - intersectKey = rectLeft; + intersectKey = keyMin; intersectValue = otherValue + (value-otherValue)/(key-otherKey)*(intersectKey-otherKey); } break; } case 2: // left edge { - intersectKey = rectLeft; + intersectKey = keyMin; intersectValue = otherValue + (value-otherValue)/(key-otherKey)*(intersectKey-otherKey); break; } case 3: // bottom and left edge { - intersectValue = rectBottom; + intersectValue = valueMin; intersectKey = otherKey + (key-otherKey)/(value-otherValue)*(intersectValue-otherValue); - if (intersectKey < rectLeft || intersectKey > rectRight) // doesn't intersect, so must intersect other: + if (intersectKey < keyMin || intersectKey > keyMax) // doesn't intersect, so must intersect other: { - intersectKey = rectLeft; + intersectKey = keyMin; intersectValue = otherValue + (value-otherValue)/(key-otherKey)*(intersectKey-otherKey); } break; } case 4: // top edge { - intersectValue = rectTop; + intersectValue = valueMax; intersectKey = otherKey + (key-otherKey)/(value-otherValue)*(intersectValue-otherValue); break; } @@ -17393,34 +22184,34 @@ QPointF QCPCurve::getOptimizedPoint(int otherRegion, double otherKey, double oth } case 6: // bottom edge { - intersectValue = rectBottom; + intersectValue = valueMin; intersectKey = otherKey + (key-otherKey)/(value-otherValue)*(intersectValue-otherValue); break; } case 7: // top and right edge { - intersectValue = rectTop; + intersectValue = valueMax; intersectKey = otherKey + (key-otherKey)/(value-otherValue)*(intersectValue-otherValue); - if (intersectKey < rectLeft || intersectKey > rectRight) // doesn't intersect, so must intersect other: + if (intersectKey < keyMin || intersectKey > keyMax) // doesn't intersect, so must intersect other: { - intersectKey = rectRight; + intersectKey = keyMax; intersectValue = otherValue + (value-otherValue)/(key-otherKey)*(intersectKey-otherKey); } break; } case 8: // right edge { - intersectKey = rectRight; + intersectKey = keyMax; intersectValue = otherValue + (value-otherValue)/(key-otherKey)*(intersectKey-otherKey); break; } case 9: // bottom and right edge { - intersectValue = rectBottom; + intersectValue = valueMin; intersectKey = otherKey + (key-otherKey)/(value-otherValue)*(intersectValue-otherValue); - if (intersectKey < rectLeft || intersectKey > rectRight) // doesn't intersect, so must intersect other: + if (intersectKey < keyMin || intersectKey > keyMax) // doesn't intersect, so must intersect other: { - intersectKey = rectRight; + intersectKey = keyMax; intersectValue = otherValue + (value-otherValue)/(key-otherKey)*(intersectKey-otherKey); } break; @@ -17431,7 +22222,7 @@ QPointF QCPCurve::getOptimizedPoint(int otherRegion, double otherKey, double oth /*! \internal - This function is part of the curve optimization algorithm of \ref getCurveData. + This function is part of the curve optimization algorithm of \ref getCurveLines. In situations where a single segment skips over multiple regions it might become necessary to add extra points at the corners of region 5 (see \ref getRegion) such that the optimized segment @@ -17447,7 +22238,7 @@ QPointF QCPCurve::getOptimizedPoint(int otherRegion, double otherKey, double oth the top left corner, making the optimized curve correctly pass from region 4 to 1 to 2 without traversing 5. */ -QVector QCPCurve::getOptimizedCornerPoints(int prevRegion, int currentRegion, double prevKey, double prevValue, double key, double value, double rectLeft, double rectTop, double rectRight, double rectBottom) const +QVector QCPCurve::getOptimizedCornerPoints(int prevRegion, int currentRegion, double prevKey, double prevValue, double key, double value, double keyMin, double valueMax, double keyMax, double valueMin) const { QVector result; switch (prevRegion) @@ -17456,17 +22247,17 @@ QVector QCPCurve::getOptimizedCornerPoints(int prevRegion, int currentR { switch (currentRegion) { - case 2: { result << coordsToPixels(rectLeft, rectTop); break; } - case 4: { result << coordsToPixels(rectLeft, rectTop); break; } - case 3: { result << coordsToPixels(rectLeft, rectTop) << coordsToPixels(rectLeft, rectBottom); break; } - case 7: { result << coordsToPixels(rectLeft, rectTop) << coordsToPixels(rectRight, rectTop); break; } - case 6: { result << coordsToPixels(rectLeft, rectTop) << coordsToPixels(rectLeft, rectBottom); result.append(result.last()); break; } - case 8: { result << coordsToPixels(rectLeft, rectTop) << coordsToPixels(rectRight, rectTop); result.append(result.last()); break; } + case 2: { result << coordsToPixels(keyMin, valueMax); break; } + case 4: { result << coordsToPixels(keyMin, valueMax); break; } + case 3: { result << coordsToPixels(keyMin, valueMax) << coordsToPixels(keyMin, valueMin); break; } + case 7: { result << coordsToPixels(keyMin, valueMax) << coordsToPixels(keyMax, valueMax); break; } + case 6: { result << coordsToPixels(keyMin, valueMax) << coordsToPixels(keyMin, valueMin); result.append(result.last()); break; } + case 8: { result << coordsToPixels(keyMin, valueMax) << coordsToPixels(keyMax, valueMax); result.append(result.last()); break; } case 9: { // in this case we need another distinction of cases: segment may pass below or above rect, requiring either bottom right or top left corner points - if ((value-prevValue)/(key-prevKey)*(rectLeft-key)+value < rectBottom) // segment passes below R - { result << coordsToPixels(rectLeft, rectTop) << coordsToPixels(rectLeft, rectBottom); result.append(result.last()); result << coordsToPixels(rectRight, rectBottom); } + if ((value-prevValue)/(key-prevKey)*(keyMin-key)+value < valueMin) // segment passes below R + { result << coordsToPixels(keyMin, valueMax) << coordsToPixels(keyMin, valueMin); result.append(result.last()); result << coordsToPixels(keyMax, valueMin); } else - { result << coordsToPixels(rectLeft, rectTop) << coordsToPixels(rectRight, rectTop); result.append(result.last()); result << coordsToPixels(rectRight, rectBottom); } + { result << coordsToPixels(keyMin, valueMax) << coordsToPixels(keyMax, valueMax); result.append(result.last()); result << coordsToPixels(keyMax, valueMin); } break; } } @@ -17476,12 +22267,12 @@ QVector QCPCurve::getOptimizedCornerPoints(int prevRegion, int currentR { switch (currentRegion) { - case 1: { result << coordsToPixels(rectLeft, rectTop); break; } - case 3: { result << coordsToPixels(rectLeft, rectBottom); break; } - case 4: { result << coordsToPixels(rectLeft, rectTop); result.append(result.last()); break; } - case 6: { result << coordsToPixels(rectLeft, rectBottom); result.append(result.last()); break; } - case 7: { result << coordsToPixels(rectLeft, rectTop); result.append(result.last()); result << coordsToPixels(rectRight, rectTop); break; } - case 9: { result << coordsToPixels(rectLeft, rectBottom); result.append(result.last()); result << coordsToPixels(rectRight, rectBottom); break; } + case 1: { result << coordsToPixels(keyMin, valueMax); break; } + case 3: { result << coordsToPixels(keyMin, valueMin); break; } + case 4: { result << coordsToPixels(keyMin, valueMax); result.append(result.last()); break; } + case 6: { result << coordsToPixels(keyMin, valueMin); result.append(result.last()); break; } + case 7: { result << coordsToPixels(keyMin, valueMax); result.append(result.last()); result << coordsToPixels(keyMax, valueMax); break; } + case 9: { result << coordsToPixels(keyMin, valueMin); result.append(result.last()); result << coordsToPixels(keyMax, valueMin); break; } } break; } @@ -17489,17 +22280,17 @@ QVector QCPCurve::getOptimizedCornerPoints(int prevRegion, int currentR { switch (currentRegion) { - case 2: { result << coordsToPixels(rectLeft, rectBottom); break; } - case 6: { result << coordsToPixels(rectLeft, rectBottom); break; } - case 1: { result << coordsToPixels(rectLeft, rectBottom) << coordsToPixels(rectLeft, rectTop); break; } - case 9: { result << coordsToPixels(rectLeft, rectBottom) << coordsToPixels(rectRight, rectBottom); break; } - case 4: { result << coordsToPixels(rectLeft, rectBottom) << coordsToPixels(rectLeft, rectTop); result.append(result.last()); break; } - case 8: { result << coordsToPixels(rectLeft, rectBottom) << coordsToPixels(rectRight, rectBottom); result.append(result.last()); break; } + case 2: { result << coordsToPixels(keyMin, valueMin); break; } + case 6: { result << coordsToPixels(keyMin, valueMin); break; } + case 1: { result << coordsToPixels(keyMin, valueMin) << coordsToPixels(keyMin, valueMax); break; } + case 9: { result << coordsToPixels(keyMin, valueMin) << coordsToPixels(keyMax, valueMin); break; } + case 4: { result << coordsToPixels(keyMin, valueMin) << coordsToPixels(keyMin, valueMax); result.append(result.last()); break; } + case 8: { result << coordsToPixels(keyMin, valueMin) << coordsToPixels(keyMax, valueMin); result.append(result.last()); break; } case 7: { // in this case we need another distinction of cases: segment may pass below or above rect, requiring either bottom right or top left corner points - if ((value-prevValue)/(key-prevKey)*(rectRight-key)+value < rectBottom) // segment passes below R - { result << coordsToPixels(rectLeft, rectBottom) << coordsToPixels(rectRight, rectBottom); result.append(result.last()); result << coordsToPixels(rectRight, rectTop); } + if ((value-prevValue)/(key-prevKey)*(keyMax-key)+value < valueMin) // segment passes below R + { result << coordsToPixels(keyMin, valueMin) << coordsToPixels(keyMax, valueMin); result.append(result.last()); result << coordsToPixels(keyMax, valueMax); } else - { result << coordsToPixels(rectLeft, rectBottom) << coordsToPixels(rectLeft, rectTop); result.append(result.last()); result << coordsToPixels(rectRight, rectTop); } + { result << coordsToPixels(keyMin, valueMin) << coordsToPixels(keyMin, valueMax); result.append(result.last()); result << coordsToPixels(keyMax, valueMax); } break; } } @@ -17509,12 +22300,12 @@ QVector QCPCurve::getOptimizedCornerPoints(int prevRegion, int currentR { switch (currentRegion) { - case 1: { result << coordsToPixels(rectLeft, rectTop); break; } - case 7: { result << coordsToPixels(rectRight, rectTop); break; } - case 2: { result << coordsToPixels(rectLeft, rectTop); result.append(result.last()); break; } - case 8: { result << coordsToPixels(rectRight, rectTop); result.append(result.last()); break; } - case 3: { result << coordsToPixels(rectLeft, rectTop); result.append(result.last()); result << coordsToPixels(rectLeft, rectBottom); break; } - case 9: { result << coordsToPixels(rectRight, rectTop); result.append(result.last()); result << coordsToPixels(rectRight, rectBottom); break; } + case 1: { result << coordsToPixels(keyMin, valueMax); break; } + case 7: { result << coordsToPixels(keyMax, valueMax); break; } + case 2: { result << coordsToPixels(keyMin, valueMax); result.append(result.last()); break; } + case 8: { result << coordsToPixels(keyMax, valueMax); result.append(result.last()); break; } + case 3: { result << coordsToPixels(keyMin, valueMax); result.append(result.last()); result << coordsToPixels(keyMin, valueMin); break; } + case 9: { result << coordsToPixels(keyMax, valueMax); result.append(result.last()); result << coordsToPixels(keyMax, valueMin); break; } } break; } @@ -17522,10 +22313,10 @@ QVector QCPCurve::getOptimizedCornerPoints(int prevRegion, int currentR { switch (currentRegion) { - case 1: { result << coordsToPixels(rectLeft, rectTop); break; } - case 7: { result << coordsToPixels(rectRight, rectTop); break; } - case 9: { result << coordsToPixels(rectRight, rectBottom); break; } - case 3: { result << coordsToPixels(rectLeft, rectBottom); break; } + case 1: { result << coordsToPixels(keyMin, valueMax); break; } + case 7: { result << coordsToPixels(keyMax, valueMax); break; } + case 9: { result << coordsToPixels(keyMax, valueMin); break; } + case 3: { result << coordsToPixels(keyMin, valueMin); break; } } break; } @@ -17533,12 +22324,12 @@ QVector QCPCurve::getOptimizedCornerPoints(int prevRegion, int currentR { switch (currentRegion) { - case 3: { result << coordsToPixels(rectLeft, rectBottom); break; } - case 9: { result << coordsToPixels(rectRight, rectBottom); break; } - case 2: { result << coordsToPixels(rectLeft, rectBottom); result.append(result.last()); break; } - case 8: { result << coordsToPixels(rectRight, rectBottom); result.append(result.last()); break; } - case 1: { result << coordsToPixels(rectLeft, rectBottom); result.append(result.last()); result << coordsToPixels(rectLeft, rectTop); break; } - case 7: { result << coordsToPixels(rectRight, rectBottom); result.append(result.last()); result << coordsToPixels(rectRight, rectTop); break; } + case 3: { result << coordsToPixels(keyMin, valueMin); break; } + case 9: { result << coordsToPixels(keyMax, valueMin); break; } + case 2: { result << coordsToPixels(keyMin, valueMin); result.append(result.last()); break; } + case 8: { result << coordsToPixels(keyMax, valueMin); result.append(result.last()); break; } + case 1: { result << coordsToPixels(keyMin, valueMin); result.append(result.last()); result << coordsToPixels(keyMin, valueMax); break; } + case 7: { result << coordsToPixels(keyMax, valueMin); result.append(result.last()); result << coordsToPixels(keyMax, valueMax); break; } } break; } @@ -17546,17 +22337,17 @@ QVector QCPCurve::getOptimizedCornerPoints(int prevRegion, int currentR { switch (currentRegion) { - case 4: { result << coordsToPixels(rectRight, rectTop); break; } - case 8: { result << coordsToPixels(rectRight, rectTop); break; } - case 1: { result << coordsToPixels(rectRight, rectTop) << coordsToPixels(rectLeft, rectTop); break; } - case 9: { result << coordsToPixels(rectRight, rectTop) << coordsToPixels(rectRight, rectBottom); break; } - case 2: { result << coordsToPixels(rectRight, rectTop) << coordsToPixels(rectLeft, rectTop); result.append(result.last()); break; } - case 6: { result << coordsToPixels(rectRight, rectTop) << coordsToPixels(rectRight, rectBottom); result.append(result.last()); break; } + case 4: { result << coordsToPixels(keyMax, valueMax); break; } + case 8: { result << coordsToPixels(keyMax, valueMax); break; } + case 1: { result << coordsToPixels(keyMax, valueMax) << coordsToPixels(keyMin, valueMax); break; } + case 9: { result << coordsToPixels(keyMax, valueMax) << coordsToPixels(keyMax, valueMin); break; } + case 2: { result << coordsToPixels(keyMax, valueMax) << coordsToPixels(keyMin, valueMax); result.append(result.last()); break; } + case 6: { result << coordsToPixels(keyMax, valueMax) << coordsToPixels(keyMax, valueMin); result.append(result.last()); break; } case 3: { // in this case we need another distinction of cases: segment may pass below or above rect, requiring either bottom right or top left corner points - if ((value-prevValue)/(key-prevKey)*(rectRight-key)+value < rectBottom) // segment passes below R - { result << coordsToPixels(rectRight, rectTop) << coordsToPixels(rectRight, rectBottom); result.append(result.last()); result << coordsToPixels(rectLeft, rectBottom); } + if ((value-prevValue)/(key-prevKey)*(keyMax-key)+value < valueMin) // segment passes below R + { result << coordsToPixels(keyMax, valueMax) << coordsToPixels(keyMax, valueMin); result.append(result.last()); result << coordsToPixels(keyMin, valueMin); } else - { result << coordsToPixels(rectRight, rectTop) << coordsToPixels(rectLeft, rectTop); result.append(result.last()); result << coordsToPixels(rectLeft, rectBottom); } + { result << coordsToPixels(keyMax, valueMax) << coordsToPixels(keyMin, valueMax); result.append(result.last()); result << coordsToPixels(keyMin, valueMin); } break; } } @@ -17566,12 +22357,12 @@ QVector QCPCurve::getOptimizedCornerPoints(int prevRegion, int currentR { switch (currentRegion) { - case 7: { result << coordsToPixels(rectRight, rectTop); break; } - case 9: { result << coordsToPixels(rectRight, rectBottom); break; } - case 4: { result << coordsToPixels(rectRight, rectTop); result.append(result.last()); break; } - case 6: { result << coordsToPixels(rectRight, rectBottom); result.append(result.last()); break; } - case 1: { result << coordsToPixels(rectRight, rectTop); result.append(result.last()); result << coordsToPixels(rectLeft, rectTop); break; } - case 3: { result << coordsToPixels(rectRight, rectBottom); result.append(result.last()); result << coordsToPixels(rectLeft, rectBottom); break; } + case 7: { result << coordsToPixels(keyMax, valueMax); break; } + case 9: { result << coordsToPixels(keyMax, valueMin); break; } + case 4: { result << coordsToPixels(keyMax, valueMax); result.append(result.last()); break; } + case 6: { result << coordsToPixels(keyMax, valueMin); result.append(result.last()); break; } + case 1: { result << coordsToPixels(keyMax, valueMax); result.append(result.last()); result << coordsToPixels(keyMin, valueMax); break; } + case 3: { result << coordsToPixels(keyMax, valueMin); result.append(result.last()); result << coordsToPixels(keyMin, valueMin); break; } } break; } @@ -17579,17 +22370,17 @@ QVector QCPCurve::getOptimizedCornerPoints(int prevRegion, int currentR { switch (currentRegion) { - case 6: { result << coordsToPixels(rectRight, rectBottom); break; } - case 8: { result << coordsToPixels(rectRight, rectBottom); break; } - case 3: { result << coordsToPixels(rectRight, rectBottom) << coordsToPixels(rectLeft, rectBottom); break; } - case 7: { result << coordsToPixels(rectRight, rectBottom) << coordsToPixels(rectRight, rectTop); break; } - case 2: { result << coordsToPixels(rectRight, rectBottom) << coordsToPixels(rectLeft, rectBottom); result.append(result.last()); break; } - case 4: { result << coordsToPixels(rectRight, rectBottom) << coordsToPixels(rectRight, rectTop); result.append(result.last()); break; } + case 6: { result << coordsToPixels(keyMax, valueMin); break; } + case 8: { result << coordsToPixels(keyMax, valueMin); break; } + case 3: { result << coordsToPixels(keyMax, valueMin) << coordsToPixels(keyMin, valueMin); break; } + case 7: { result << coordsToPixels(keyMax, valueMin) << coordsToPixels(keyMax, valueMax); break; } + case 2: { result << coordsToPixels(keyMax, valueMin) << coordsToPixels(keyMin, valueMin); result.append(result.last()); break; } + case 4: { result << coordsToPixels(keyMax, valueMin) << coordsToPixels(keyMax, valueMax); result.append(result.last()); break; } case 1: { // in this case we need another distinction of cases: segment may pass below or above rect, requiring either bottom right or top left corner points - if ((value-prevValue)/(key-prevKey)*(rectLeft-key)+value < rectBottom) // segment passes below R - { result << coordsToPixels(rectRight, rectBottom) << coordsToPixels(rectLeft, rectBottom); result.append(result.last()); result << coordsToPixels(rectLeft, rectTop); } + if ((value-prevValue)/(key-prevKey)*(keyMin-key)+value < valueMin) // segment passes below R + { result << coordsToPixels(keyMax, valueMin) << coordsToPixels(keyMin, valueMin); result.append(result.last()); result << coordsToPixels(keyMin, valueMax); } else - { result << coordsToPixels(rectRight, rectBottom) << coordsToPixels(rectRight, rectTop); result.append(result.last()); result << coordsToPixels(rectLeft, rectTop); } + { result << coordsToPixels(keyMax, valueMin) << coordsToPixels(keyMax, valueMax); result.append(result.last()); result << coordsToPixels(keyMin, valueMax); } break; } } @@ -17601,7 +22392,7 @@ QVector QCPCurve::getOptimizedCornerPoints(int prevRegion, int currentR /*! \internal - This function is part of the curve optimization algorithm of \ref getCurveData. + This function is part of the curve optimization algorithm of \ref getCurveLines. This method returns whether a segment going from \a prevRegion to \a currentRegion (see \ref getRegion) may traverse the visible region 5. This function assumes that neither \a prevRegion @@ -17703,7 +22494,7 @@ bool QCPCurve::mayTraverse(int prevRegion, int currentRegion) const /*! \internal - This function is part of the curve optimization algorithm of \ref getCurveData. + This function is part of the curve optimization algorithm of \ref getCurveLines. This method assumes that the \ref mayTraverse test has returned true, so there is a chance the segment defined by (\a prevKey, \a prevValue) and (\a key, \a value) goes through the visible @@ -17714,40 +22505,40 @@ bool QCPCurve::mayTraverse(int prevRegion, int currentRegion) const If the segment traverses 5, the output parameters \a crossA and \a crossB indicate the entry and exit points of region 5. They will become the optimized points for that segment. */ -bool QCPCurve::getTraverse(double prevKey, double prevValue, double key, double value, double rectLeft, double rectTop, double rectRight, double rectBottom, QPointF &crossA, QPointF &crossB) const +bool QCPCurve::getTraverse(double prevKey, double prevValue, double key, double value, double keyMin, double valueMax, double keyMax, double valueMin, QPointF &crossA, QPointF &crossB) const { QList intersections; // x of QPointF corresponds to key and y to value if (qFuzzyIsNull(key-prevKey)) // line is parallel to value axis { // due to region filter in mayTraverseR(), if line is parallel to value or key axis, R is traversed here - intersections.append(QPointF(key, rectBottom)); // direction will be taken care of at end of method - intersections.append(QPointF(key, rectTop)); + intersections.append(QPointF(key, valueMin)); // direction will be taken care of at end of method + intersections.append(QPointF(key, valueMax)); } else if (qFuzzyIsNull(value-prevValue)) // line is parallel to key axis { // due to region filter in mayTraverseR(), if line is parallel to value or key axis, R is traversed here - intersections.append(QPointF(rectLeft, value)); // direction will be taken care of at end of method - intersections.append(QPointF(rectRight, value)); + intersections.append(QPointF(keyMin, value)); // direction will be taken care of at end of method + intersections.append(QPointF(keyMax, value)); } else // line is skewed { double gamma; double keyPerValue = (key-prevKey)/(value-prevValue); // check top of rect: - gamma = prevKey + (rectTop-prevValue)*keyPerValue; - if (gamma >= rectLeft && gamma <= rectRight) - intersections.append(QPointF(gamma, rectTop)); + gamma = prevKey + (valueMax-prevValue)*keyPerValue; + if (gamma >= keyMin && gamma <= keyMax) + intersections.append(QPointF(gamma, valueMax)); // check bottom of rect: - gamma = prevKey + (rectBottom-prevValue)*keyPerValue; - if (gamma >= rectLeft && gamma <= rectRight) - intersections.append(QPointF(gamma, rectBottom)); + gamma = prevKey + (valueMin-prevValue)*keyPerValue; + if (gamma >= keyMin && gamma <= keyMax) + intersections.append(QPointF(gamma, valueMin)); double valuePerKey = 1.0/keyPerValue; // check left of rect: - gamma = prevValue + (rectLeft-prevKey)*valuePerKey; - if (gamma >= rectBottom && gamma <= rectTop) - intersections.append(QPointF(rectLeft, gamma)); + gamma = prevValue + (keyMin-prevKey)*valuePerKey; + if (gamma >= valueMin && gamma <= valueMax) + intersections.append(QPointF(keyMin, gamma)); // check right of rect: - gamma = prevValue + (rectRight-prevKey)*valuePerKey; - if (gamma >= rectBottom && gamma <= rectTop) - intersections.append(QPointF(rectRight, gamma)); + gamma = prevValue + (keyMax-prevKey)*valuePerKey; + if (gamma >= valueMin && gamma <= valueMax) + intersections.append(QPointF(keyMax, gamma)); } // handle cases where found points isn't exactly 2: @@ -17787,7 +22578,7 @@ bool QCPCurve::getTraverse(double prevKey, double prevValue, double key, double /*! \internal - This function is part of the curve optimization algorithm of \ref getCurveData. + This function is part of the curve optimization algorithm of \ref getCurveLines. This method assumes that the \ref getTraverse test has returned true, so the segment definitely traverses the visible region 5 when going from \a prevRegion to \a currentRegion. @@ -17810,7 +22601,7 @@ bool QCPCurve::getTraverse(double prevKey, double prevValue, double key, double corner points before and after the traverse. Then both \a beforeTraverse and \a afterTraverse return the respective corner points. */ -void QCPCurve::getTraverseCornerPoints(int prevRegion, int currentRegion, double rectLeft, double rectTop, double rectRight, double rectBottom, QVector &beforeTraverse, QVector &afterTraverse) const +void QCPCurve::getTraverseCornerPoints(int prevRegion, int currentRegion, double keyMin, double valueMax, double keyMax, double valueMin, QVector &beforeTraverse, QVector &afterTraverse) const { switch (prevRegion) { @@ -17818,9 +22609,9 @@ void QCPCurve::getTraverseCornerPoints(int prevRegion, int currentRegion, double { switch (currentRegion) { - case 6: { beforeTraverse << coordsToPixels(rectLeft, rectTop); break; } - case 9: { beforeTraverse << coordsToPixels(rectLeft, rectTop); afterTraverse << coordsToPixels(rectRight, rectBottom); break; } - case 8: { beforeTraverse << coordsToPixels(rectLeft, rectTop); break; } + case 6: { beforeTraverse << coordsToPixels(keyMin, valueMax); break; } + case 9: { beforeTraverse << coordsToPixels(keyMin, valueMax); afterTraverse << coordsToPixels(keyMax, valueMin); break; } + case 8: { beforeTraverse << coordsToPixels(keyMin, valueMax); break; } } break; } @@ -17828,8 +22619,8 @@ void QCPCurve::getTraverseCornerPoints(int prevRegion, int currentRegion, double { switch (currentRegion) { - case 7: { afterTraverse << coordsToPixels(rectRight, rectTop); break; } - case 9: { afterTraverse << coordsToPixels(rectRight, rectBottom); break; } + case 7: { afterTraverse << coordsToPixels(keyMax, valueMax); break; } + case 9: { afterTraverse << coordsToPixels(keyMax, valueMin); break; } } break; } @@ -17837,9 +22628,9 @@ void QCPCurve::getTraverseCornerPoints(int prevRegion, int currentRegion, double { switch (currentRegion) { - case 4: { beforeTraverse << coordsToPixels(rectLeft, rectBottom); break; } - case 7: { beforeTraverse << coordsToPixels(rectLeft, rectBottom); afterTraverse << coordsToPixels(rectRight, rectTop); break; } - case 8: { beforeTraverse << coordsToPixels(rectLeft, rectBottom); break; } + case 4: { beforeTraverse << coordsToPixels(keyMin, valueMin); break; } + case 7: { beforeTraverse << coordsToPixels(keyMin, valueMin); afterTraverse << coordsToPixels(keyMax, valueMax); break; } + case 8: { beforeTraverse << coordsToPixels(keyMin, valueMin); break; } } break; } @@ -17847,8 +22638,8 @@ void QCPCurve::getTraverseCornerPoints(int prevRegion, int currentRegion, double { switch (currentRegion) { - case 3: { afterTraverse << coordsToPixels(rectLeft, rectBottom); break; } - case 9: { afterTraverse << coordsToPixels(rectRight, rectBottom); break; } + case 3: { afterTraverse << coordsToPixels(keyMin, valueMin); break; } + case 9: { afterTraverse << coordsToPixels(keyMax, valueMin); break; } } break; } @@ -17857,8 +22648,8 @@ void QCPCurve::getTraverseCornerPoints(int prevRegion, int currentRegion, double { switch (currentRegion) { - case 1: { afterTraverse << coordsToPixels(rectLeft, rectTop); break; } - case 7: { afterTraverse << coordsToPixels(rectRight, rectTop); break; } + case 1: { afterTraverse << coordsToPixels(keyMin, valueMax); break; } + case 7: { afterTraverse << coordsToPixels(keyMax, valueMax); break; } } break; } @@ -17866,9 +22657,9 @@ void QCPCurve::getTraverseCornerPoints(int prevRegion, int currentRegion, double { switch (currentRegion) { - case 2: { beforeTraverse << coordsToPixels(rectRight, rectTop); break; } - case 3: { beforeTraverse << coordsToPixels(rectRight, rectTop); afterTraverse << coordsToPixels(rectLeft, rectBottom); break; } - case 6: { beforeTraverse << coordsToPixels(rectRight, rectTop); break; } + case 2: { beforeTraverse << coordsToPixels(keyMax, valueMax); break; } + case 3: { beforeTraverse << coordsToPixels(keyMax, valueMax); afterTraverse << coordsToPixels(keyMin, valueMin); break; } + case 6: { beforeTraverse << coordsToPixels(keyMax, valueMax); break; } } break; } @@ -17876,8 +22667,8 @@ void QCPCurve::getTraverseCornerPoints(int prevRegion, int currentRegion, double { switch (currentRegion) { - case 1: { afterTraverse << coordsToPixels(rectLeft, rectTop); break; } - case 3: { afterTraverse << coordsToPixels(rectLeft, rectBottom); break; } + case 1: { afterTraverse << coordsToPixels(keyMin, valueMax); break; } + case 3: { afterTraverse << coordsToPixels(keyMin, valueMin); break; } } break; } @@ -17885,9 +22676,9 @@ void QCPCurve::getTraverseCornerPoints(int prevRegion, int currentRegion, double { switch (currentRegion) { - case 2: { beforeTraverse << coordsToPixels(rectRight, rectBottom); break; } - case 1: { beforeTraverse << coordsToPixels(rectRight, rectBottom); afterTraverse << coordsToPixels(rectLeft, rectTop); break; } - case 4: { beforeTraverse << coordsToPixels(rectRight, rectBottom); break; } + case 2: { beforeTraverse << coordsToPixels(keyMax, valueMin); break; } + case 1: { beforeTraverse << coordsToPixels(keyMax, valueMin); afterTraverse << coordsToPixels(keyMin, valueMax); break; } + case 4: { beforeTraverse << coordsToPixels(keyMax, valueMin); break; } } break; } @@ -17898,106 +22689,64 @@ void QCPCurve::getTraverseCornerPoints(int prevRegion, int currentRegion, double Calculates the (minimum) distance (in pixels) the curve's representation has from the given \a pixelPoint in pixels. This is used to determine whether the curve was clicked or not, e.g. in - \ref selectTest. + \ref selectTest. The closest data point to \a pixelPoint is returned in \a closestData. Note that + if the curve has a line representation, the returned distance may be smaller than the distance to + the \a closestData point, since the distance to the curve line is also taken into account. + + If either the curve 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 curve), returns + -1.0. */ -double QCPCurve::pointDistance(const QPointF &pixelPoint) const +double QCPCurve::pointDistance(const QPointF &pixelPoint, QCPCurveDataContainer::const_iterator &closestData) const { - if (mData->isEmpty()) + closestData = mDataContainer->constEnd(); + if (mDataContainer->isEmpty()) + return -1.0; + if (mLineStyle == lsNone && mScatterStyle.isNone()) + return -1.0; + + if (mDataContainer->size() == 1) { - qDebug() << Q_FUNC_INFO << "requested point distance on curve" << mName << "without data"; - return 500; - } - if (mData->size() == 1) - { - QPointF dataPoint = coordsToPixels(mData->constBegin().key(), mData->constBegin().value().value); - return QVector2D(dataPoint-pixelPoint).length(); + QPointF dataPoint = coordsToPixels(mDataContainer->constBegin()->key, mDataContainer->constBegin()->value); + closestData = mDataContainer->constBegin(); + return QCPVector2D(dataPoint-pixelPoint).length(); } - // calculate minimum distance to line segments: - QVector *lineData = new QVector; - getCurveData(lineData); + // calculate minimum distances to curve data points and find closestData iterator: double minDistSqr = std::numeric_limits::max(); - for (int i=0; isize()-1; ++i) + // iterate over found data points and then choose the one with the shortest distance to pos: + QCPCurveDataContainer::const_iterator begin = mDataContainer->constBegin(); + QCPCurveDataContainer::const_iterator end = mDataContainer->constEnd(); + for (QCPCurveDataContainer::const_iterator it=begin; it!=end; ++it) { - double currentDistSqr = distSqrToLine(lineData->at(i), lineData->at(i+1), pixelPoint); + const double currentDistSqr = QCPVector2D(coordsToPixels(it->key, it->value)-pixelPoint).lengthSquared(); if (currentDistSqr < minDistSqr) + { minDistSqr = currentDistSqr; + closestData = it; + } } - delete lineData; + + // calculate distance to line if there is one (if so, will probably be smaller than distance to closest data point): + if (mLineStyle != lsNone) + { + QVector lines; + getCurveLines(&lines, QCPDataRange(0, dataCount()), mParentPlot->selectionTolerance()*1.2); // optimized lines outside axis rect shouldn't respond to clicks at the edge, so use 1.2*tolerance as pen width + for (int i=0; iconstBegin(); - while (it != mData->constEnd()) - { - current = it.value().key; - if (!qIsNaN(current) && !qIsNaN(it.value().value)) - { - if (inSignDomain == sdBoth || (inSignDomain == sdNegative && current < 0) || (inSignDomain == sdPositive && current > 0)) - { - if (current < range.lower || !haveLower) - { - range.lower = current; - haveLower = true; - } - if (current > range.upper || !haveUpper) - { - range.upper = current; - haveUpper = true; - } - } - } - ++it; - } - - foundRange = haveLower && haveUpper; - return range; -} -/* inherits documentation from base class */ -QCPRange QCPCurve::getValueRange(bool &foundRange, SignDomain inSignDomain) const -{ - QCPRange range; - bool haveLower = false; - bool haveUpper = false; - - double current; - - QCPCurveDataMap::const_iterator it = mData->constBegin(); - while (it != mData->constEnd()) - { - current = it.value().value; - if (!qIsNaN(current) && !qIsNaN(it.value().key)) - { - if (inSignDomain == sdBoth || (inSignDomain == sdNegative && current < 0) || (inSignDomain == sdPositive && current > 0)) - { - if (current < range.lower || !haveLower) - { - range.lower = current; - haveLower = true; - } - if (current > range.upper || !haveUpper) - { - range.upper = current; - haveUpper = true; - } - } - } - ++it; - } - - foundRange = haveLower && haveUpper; - return range; -} +/* including file 'src/plottables/plottable-bars.cpp', size 43512 */ +/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */ //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -18251,47 +23000,26 @@ double QCPBarsGroup::keyPixelOffset(const QCPBars *bars, double keyCoord) int index = baseBars.indexOf(thisBase); if (index >= 0) { - int startIndex; - double lowerPixelWidth, upperPixelWidth; if (baseBars.size() % 2 == 1 && index == (baseBars.size()-1)/2) // is center bar (int division on purpose) { return result; - } else if (index < (baseBars.size()-1)/2.0) // bar is to the left of center + } else { + double lowerPixelWidth, upperPixelWidth; + int startIndex; + int dir = (index <= (baseBars.size()-1)/2) ? -1 : 1; // if bar is to lower keys of center, dir is negative if (baseBars.size() % 2 == 0) // even number of bars { - startIndex = baseBars.size()/2-1; - result -= getPixelSpacing(baseBars.at(startIndex), keyCoord)*0.5; // half of middle spacing - } else // uneven number of bars - { - startIndex = (baseBars.size()-1)/2-1; - baseBars.at((baseBars.size()-1)/2)->getPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth); - result -= qAbs(upperPixelWidth-lowerPixelWidth)*0.5; // half of center bar - result -= getPixelSpacing(baseBars.at((baseBars.size()-1)/2), keyCoord); // center bar spacing - } - for (int i=startIndex; i>index; --i) // add widths and spacings of bars in between center and our bars - { - baseBars.at(i)->getPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth); - result -= qAbs(upperPixelWidth-lowerPixelWidth); - result -= getPixelSpacing(baseBars.at(i), keyCoord); - } - // finally half of our bars width: - baseBars.at(index)->getPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth); - result -= qAbs(upperPixelWidth-lowerPixelWidth)*0.5; - } else // bar is to the right of center - { - if (baseBars.size() % 2 == 0) // even number of bars - { - startIndex = baseBars.size()/2; + startIndex = baseBars.size()/2 + (dir < 0 ? -1 : 0); result += getPixelSpacing(baseBars.at(startIndex), keyCoord)*0.5; // half of middle spacing } else // uneven number of bars { - startIndex = (baseBars.size()-1)/2+1; + startIndex = (baseBars.size()-1)/2+dir; baseBars.at((baseBars.size()-1)/2)->getPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth); result += qAbs(upperPixelWidth-lowerPixelWidth)*0.5; // half of center bar result += getPixelSpacing(baseBars.at((baseBars.size()-1)/2), keyCoord); // center bar spacing } - for (int i=startIndex; igetPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth); result += qAbs(upperPixelWidth-lowerPixelWidth); @@ -18300,6 +23028,8 @@ double QCPBarsGroup::keyPixelOffset(const QCPBars *bars, double keyCoord) // finally half of our bars width: baseBars.at(index)->getPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth); result += qAbs(upperPixelWidth-lowerPixelWidth)*0.5; + // correct sign of result depending on orientation and direction of key axis: + result *= dir*thisBase->keyAxis()->pixelOrientation(); } } return result; @@ -18311,7 +23041,7 @@ double QCPBarsGroup::keyPixelOffset(const QCPBars *bars, double keyCoord) key coordinate \a keyCoord. \note Typically the returned value doesn't depend on \a bars or \a keyCoord. \a bars is only - needed to get acces to the key axis transformation and axis rect for the modes \ref + needed to get access to the key axis transformation and axis rect for the modes \ref stAxisRectRatio and \ref stPlotCoords. The \a keyCoord is only relevant for spacings given in \ref stPlotCoords on a logarithmic axis. */ @@ -18333,7 +23063,7 @@ double QCPBarsGroup::getPixelSpacing(const QCPBars *bars, double keyCoord) case stPlotCoords: { double keyPixel = bars->keyAxis()->coordToPixel(keyCoord); - return bars->keyAxis()->coordToPixel(keyCoord+mSpacing)-keyPixel; + return qAbs(bars->keyAxis()->coordToPixel(keyCoord+mSpacing)-keyPixel); } } return 0; @@ -18341,25 +23071,80 @@ double QCPBarsGroup::getPixelSpacing(const QCPBars *bars, double keyCoord) //////////////////////////////////////////////////////////////////////////////////////////////////// -//////////////////// QCPBarData +//////////////////// QCPBarsData //////////////////////////////////////////////////////////////////////////////////////////////////// -/*! \class QCPBarData +/*! \class QCPBarsData \brief Holds the data of one single data point (one bar) for QCPBars. - The container for storing multiple data points is \ref QCPBarDataMap. - The stored data is: - \li \a key: coordinate on the key axis of this bar - \li \a value: height coordinate on the value axis of this bar + \li \a key: coordinate on the key axis of this bar (this is the \a mainKey and the \a sortKey) + \li \a value: height coordinate on the value axis of this bar (this is the \a mainValue) - \see QCPBarDataaMap + The container for storing multiple data points is \ref QCPBarsDataContainer. It is a typedef for + \ref QCPDataContainer with \ref QCPBarsData as the DataType template parameter. See the + documentation there for an explanation regarding the data type's generic methods. + + \see QCPBarsDataContainer */ +/* start documentation of inline functions */ + +/*! \fn double QCPBarsData::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 QCPBarsData QCPBarsData::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 QCPBarsData::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 QCPBarsData::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 QCPBarsData::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 QCPBarsData::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 bar data point with key and value set to zero. */ -QCPBarData::QCPBarData() : +QCPBarsData::QCPBarsData() : key(0), value(0) { @@ -18368,7 +23153,7 @@ QCPBarData::QCPBarData() : /*! Constructs a bar data point with the specified \a key and \a value. */ -QCPBarData::QCPBarData(double key, double value) : +QCPBarsData::QCPBarsData(double key, double value) : key(key), value(value) { @@ -18386,7 +23171,7 @@ QCPBarData::QCPBarData(double key, double value) : To plot data, assign it with the \ref setData or \ref addData functions. - \section appearance Changing the appearance + \section qcpbars-appearance Changing the appearance The appearance of the bars is determined by the pen and the brush (\ref setPen, \ref setBrush). The width of the individual bars can be controlled with \ref setWidthType and \ref setWidth. @@ -18400,22 +23185,29 @@ QCPBarData::QCPBarData(double key, double value) : \image html QCPBarsGroup.png - \section usage Usage + \section qcpbars-usage Usage Like all data representing objects in QCustomPlot, the QCPBars is a plottable (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies - (QCustomPlot::plottable, QCustomPlot::addPlottable, QCustomPlot::removePlottable, etc.) + (QCustomPlot::plottable, QCustomPlot::removePlottable, etc.) Usually, you first create an instance: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpbars-creation-1 - add it to the customPlot with QCustomPlot::addPlottable: + 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 qcpbars-creation-2 - and then modify the properties of the newly created plottable, e.g.: - \snippet documentation/doc-code-snippets/mainwindow.cpp qcpbars-creation-3 */ /* start of documentation of inline functions */ +/*! \fn QSharedPointer QCPBars::data() const + + Returns a shared pointer to the internal data storage of type \ref QCPBarsDataContainer. 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. +*/ + /*! \fn QCPBars *QCPBars::barBelow() const Returns the bars plottable that is directly below this bars plottable. If there is no such plottable, returns 0. @@ -18438,26 +23230,24 @@ QCPBarData::QCPBarData(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 QCPBars can be added to the plot with QCustomPlot::addPlottable, QCustomPlot - then takes ownership of the bar chart. + The created QCPBars is automatically registered with the QCustomPlot instance inferred from \a + keyAxis. This QCustomPlot instance takes ownership of the QCPBars, so do not delete it manually + but use QCustomPlot::removePlottable() instead. */ QCPBars::QCPBars(QCPAxis *keyAxis, QCPAxis *valueAxis) : - QCPAbstractPlottable(keyAxis, valueAxis), - mData(new QCPBarDataMap), + QCPAbstractPlottable1D(keyAxis, valueAxis), mWidth(0.75), mWidthType(wtPlotCoords), mBarsGroup(0), - mBaseValue(0) + mBaseValue(0), + mStackingGap(0) { // modify inherited properties from abstract plottable: mPen.setColor(Qt::blue); mPen.setStyle(Qt::SolidLine); mBrush.setColor(QColor(40, 50, 255, 30)); mBrush.setStyle(Qt::SolidPattern); - mSelectedPen = mPen; - mSelectedPen.setWidthF(2.5); - mSelectedPen.setColor(QColor(80, 80, 255)); // lighter than Qt::blue of mPen - mSelectedBrush = mBrush; + mSelectionDecorator->setBrush(QBrush(QColor(160, 160, 255))); } QCPBars::~QCPBars() @@ -18465,7 +23255,43 @@ QCPBars::~QCPBars() setBarsGroup(0); if (mBarBelow || mBarAbove) connectBars(mBarBelow.data(), mBarAbove.data()); // take this bar out of any stacking - delete mData; +} + +/*! \overload + + Replaces the current data container with the provided \a data container. + + Since a QSharedPointer is used, multiple QCPBars may share the same data container safely. + Modifying the data in the container will then affect all bars 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 qcpbars-datasharing-1 + + If you do not wish to share containers, but create a copy from an existing container, rather use + the \ref QCPDataContainer::set method on the bar's data container directly: + \snippet documentation/doc-code-snippets/mainwindow.cpp qcpbars-datasharing-2 + + \see addData +*/ +void QCPBars::setData(QSharedPointer data) +{ + mDataContainer = data; +} + +/*! \overload + + 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. + + 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 addData +*/ +void QCPBars::setData(const QVector &keys, const QVector &values, bool alreadySorted) +{ + mDataContainer->clear(); + addData(keys, values, alreadySorted); } /*! @@ -18527,47 +23353,55 @@ void QCPBars::setBaseValue(double baseValue) } /*! - Replaces the current data with the provided \a data. - - 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. + If this bars plottable is stacked on top of another bars plottable (\ref moveAbove), this method + allows specifying a distance in \a pixels, by which the drawn bar rectangles will be separated by + the bars below it. */ -void QCPBars::setData(QCPBarDataMap *data, bool copy) +void QCPBars::setStackingGap(double pixels) { - if (mData == data) - { - qDebug() << Q_FUNC_INFO << "The data pointer is already in (and owned by) this plottable" << reinterpret_cast(data); - return; - } - if (copy) - { - *mData = *data; - } else - { - delete mData; - mData = data; - } + mStackingGap = pixels; } /*! \overload - Replaces the current data with the provided points in \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. + 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. + + 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 QCPBars::setData(const QVector &key, const QVector &value) +void QCPBars::addData(const QVector &keys, const QVector &values, bool alreadySorted) { - mData->clear(); - int n = key.size(); - n = qMin(n, value.size()); - QCPBarData newData; - for (int i=0; i tempData(n); + QVector::iterator it = tempData.begin(); + const QVector::iterator itEnd = tempData.end(); + int i = 0; + while (it != itEnd) { - newData.key = key[i]; - newData.value = value[i]; - mData->insertMulti(newData.key, newData); + 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 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 QCPBars::addData(double key, double value) +{ + mDataContainer->add(QCPBarsData(key, value)); } /*! @@ -18609,7 +23443,7 @@ void QCPBars::moveBelow(QCPBars *bars) plottable. Inserting into and removing from existing bar stacking is handled gracefully. If \a bars already - has a bars object below itself, this bars object is inserted between the two. If this bars object + has a bars object above itself, this bars object is inserted between the two. If this bars object is already between two other bars, the two other bars will be stacked on top of each other after the operation. @@ -18637,166 +23471,207 @@ void QCPBars::moveAbove(QCPBars *bars) } /*! - Adds the provided data points in \a dataMap to the current data. - \see removeData + \copydoc QCPPlottableInterface1D::selectTestRect */ -void QCPBars::addData(const QCPBarDataMap &dataMap) +QCPDataSelection QCPBars::selectTestRect(const QRectF &rect, bool onlySelectable) const { - mData->unite(dataMap); -} - -/*! \overload - Adds the provided single data point in \a data to the current data. - \see removeData -*/ -void QCPBars::addData(const QCPBarData &data) -{ - mData->insertMulti(data.key, data); -} - -/*! \overload - Adds the provided single data point as \a key and \a value tuple to the current data - \see removeData -*/ -void QCPBars::addData(double key, double value) -{ - QCPBarData newData; - newData.key = key; - newData.value = value; - mData->insertMulti(newData.key, newData); -} - -/*! \overload - Adds the provided data points as \a key and \a value tuples to the current data. - \see removeData -*/ -void QCPBars::addData(const QVector &keys, const QVector &values) -{ - int n = keys.size(); - n = qMin(n, values.size()); - QCPBarData newData; - for (int i=0; iisEmpty()) + return result; + if (!mKeyAxis || !mValueAxis) + return result; + + QCPBarsDataContainer::const_iterator visibleBegin, visibleEnd; + getVisibleDataBounds(visibleBegin, visibleEnd); + + for (QCPBarsDataContainer::const_iterator it=visibleBegin; it!=visibleEnd; ++it) { - newData.key = keys[i]; - newData.value = values[i]; - mData->insertMulti(newData.key, newData); + if (rect.intersects(getBarRect(it->key, it->value))) + result.addDataRange(QCPDataRange(it-mDataContainer->constBegin(), it-mDataContainer->constBegin()+1), false); } -} - -/*! - Removes all data points with key smaller than \a key. - \see addData, clearData -*/ -void QCPBars::removeDataBefore(double key) -{ - QCPBarDataMap::iterator it = mData->begin(); - while (it != mData->end() && it.key() < key) - it = mData->erase(it); -} - -/*! - Removes all data points with key greater than \a key. - \see addData, clearData -*/ -void QCPBars::removeDataAfter(double key) -{ - if (mData->isEmpty()) return; - QCPBarDataMap::iterator it = mData->upperBound(key); - while (it != mData->end()) - it = mData->erase(it); -} - -/*! - Removes all data points with key 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 QCPBars::removeData(double fromKey, double toKey) -{ - if (fromKey >= toKey || mData->isEmpty()) return; - QCPBarDataMap::iterator it = mData->upperBound(fromKey); - QCPBarDataMap::iterator itEnd = mData->upperBound(toKey); - while (it != itEnd) - it = mData->erase(it); -} - -/*! \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 QCPBars::removeData(double key) -{ - mData->remove(key); -} - -/*! - Removes all data points. - \see removeData, removeDataAfter, removeDataBefore -*/ -void QCPBars::clearData() -{ - mData->clear(); + result.simplify(); + return result; } /* inherits documentation from base class */ double QCPBars::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) - if (onlySelectable && !mSelectable) + 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())) { - QCPBarDataMap::ConstIterator it; - for (it = mData->constBegin(); it != mData->constEnd(); ++it) + // get visible data range: + QCPBarsDataContainer::const_iterator visibleBegin, visibleEnd; + getVisibleDataBounds(visibleBegin, visibleEnd); + for (QCPBarsDataContainer::const_iterator it=visibleBegin; it!=visibleEnd; ++it) { - if (getBarPolygon(it.value().key, it.value().value).boundingRect().contains(pos)) + if (getBarRect(it->key, it->value).contains(pos)) + { + if (details) + { + int pointIndex = it-mDataContainer->constBegin(); + details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1))); + } return mParentPlot->selectionTolerance()*0.99; + } } } return -1; } +/* inherits documentation from base class */ +QCPRange QCPBars::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const +{ + /* Note: If this QCPBars uses absolute pixels as width (or is in a QCPBarsGroup with spacing in + absolute pixels), using this method to adapt the key axis range to fit the bars into the + currently visible axis range will not work perfectly. Because in the moment the axis range is + changed to the new range, the fixed pixel widths/spacings will represent different coordinate + spans than before, which in turn would require a different key range to perfectly fit, and so on. + The only solution would be to iteratively approach the perfect fitting axis range, but the + mismatch isn't large enough in most applications, to warrant this here. If a user does need a + better fit, he should call the corresponding axis rescale multiple times in a row. + */ + QCPRange range; + range = mDataContainer->keyRange(foundRange, inSignDomain); + + // determine exact range of bars by including bar width and barsgroup offset: + if (foundRange && mKeyAxis) + { + double lowerPixelWidth, upperPixelWidth, keyPixel; + // lower range bound: + getPixelWidth(range.lower, lowerPixelWidth, upperPixelWidth); + keyPixel = mKeyAxis.data()->coordToPixel(range.lower) + lowerPixelWidth; + if (mBarsGroup) + keyPixel += mBarsGroup->keyPixelOffset(this, range.lower); + const double lowerCorrected = mKeyAxis.data()->pixelToCoord(keyPixel); + if (!qIsNaN(lowerCorrected) && qIsFinite(lowerCorrected) && range.lower > lowerCorrected) + range.lower = lowerCorrected; + // upper range bound: + getPixelWidth(range.upper, lowerPixelWidth, upperPixelWidth); + keyPixel = mKeyAxis.data()->coordToPixel(range.upper) + upperPixelWidth; + if (mBarsGroup) + keyPixel += mBarsGroup->keyPixelOffset(this, range.upper); + const double upperCorrected = mKeyAxis.data()->pixelToCoord(keyPixel); + if (!qIsNaN(upperCorrected) && qIsFinite(upperCorrected) && range.upper < upperCorrected) + range.upper = upperCorrected; + } + return range; +} + +/* inherits documentation from base class */ +QCPRange QCPBars::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const +{ + // Note: can't simply use mDataContainer->valueRange here because we need to + // take into account bar base value and possible stacking of multiple bars + QCPRange range; + range.lower = mBaseValue; + range.upper = mBaseValue; + bool haveLower = true; // set to true, because baseValue should always be visible in bar charts + bool haveUpper = true; // set to true, because baseValue should always be visible in bar charts + QCPBarsDataContainer::const_iterator itBegin = mDataContainer->constBegin(); + QCPBarsDataContainer::const_iterator itEnd = mDataContainer->constEnd(); + if (inKeyRange != QCPRange()) + { + itBegin = mDataContainer->findBegin(inKeyRange.lower); + itEnd = mDataContainer->findEnd(inKeyRange.upper); + } + for (QCPBarsDataContainer::const_iterator it = itBegin; it != itEnd; ++it) + { + const double current = it->value + getStackedBaseValue(it->key, it->value >= 0); + if (qIsNaN(current)) continue; + if (inSignDomain == QCP::sdBoth || (inSignDomain == QCP::sdNegative && current < 0) || (inSignDomain == QCP::sdPositive && current > 0)) + { + if (current < range.lower || !haveLower) + { + range.lower = current; + haveLower = true; + } + if (current > range.upper || !haveUpper) + { + range.upper = current; + haveUpper = true; + } + } + } + + foundRange = true; // return true because bar charts always have the 0-line visible + return range; +} + +/* inherits documentation from base class */ +QPointF QCPBars::dataPixelPosition(int index) const +{ + if (index >= 0 && index < mDataContainer->size()) + { + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPointF(); } + + const QCPDataContainer::const_iterator it = mDataContainer->constBegin()+index; + const double valuePixel = valueAxis->coordToPixel(getStackedBaseValue(it->key, it->value >= 0) + it->value); + const double keyPixel = keyAxis->coordToPixel(it->key) + (mBarsGroup ? mBarsGroup->keyPixelOffset(this, it->key) : 0); + if (keyAxis->orientation() == Qt::Horizontal) + return QPointF(keyPixel, valuePixel); + else + return QPointF(valuePixel, keyPixel); + } else + { + qDebug() << Q_FUNC_INFO << "Index out of bounds" << index; + return QPointF(); + } +} + /* inherits documentation from base class */ void QCPBars::draw(QCPPainter *painter) { if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } - if (mData->isEmpty()) return; + if (mDataContainer->isEmpty()) return; - QCPBarDataMap::const_iterator it, lower, upperEnd; - getVisibleDataBounds(lower, upperEnd); - for (it = lower; it != upperEnd; ++it) + QCPBarsDataContainer::const_iterator visibleBegin, visibleEnd; + getVisibleDataBounds(visibleBegin, visibleEnd); + + // loop over and draw segments of unselected/selected data: + QList selectedSegments, unselectedSegments, allSegments; + getDataSegments(selectedSegments, unselectedSegments); + allSegments << unselectedSegments << selectedSegments; + for (int i=0; i= unselectedSegments.size(); + QCPBarsDataContainer::const_iterator begin = visibleBegin; + QCPBarsDataContainer::const_iterator end = visibleEnd; + mDataContainer->limitIteratorsToDataRange(begin, end, allSegments.at(i)); + if (begin == end) + continue; + + for (QCPBarsDataContainer::const_iterator it=begin; it!=end; ++it) + { + // check data validity if flag set: #ifdef QCUSTOMPLOT_CHECK_DATA - if (QCP::isInvalidData(it.value().key, it.value().value)) - qDebug() << Q_FUNC_INFO << "Data point at" << it.key() << "of drawn range invalid." << "Plottable name:" << name(); + if (QCP::isInvalidData(it->key, it->value)) + qDebug() << Q_FUNC_INFO << "Data point at" << it->key << "of drawn range invalid." << "Plottable name:" << name(); #endif - QPolygonF barPolygon = getBarPolygon(it.key(), it.value().value); - // draw bar fill: - if (mainBrush().style() != Qt::NoBrush && mainBrush().color().alpha() != 0) - { - applyFillAntialiasingHint(painter); - painter->setPen(Qt::NoPen); - painter->setBrush(mainBrush()); - painter->drawPolygon(barPolygon); - } - // draw bar line: - if (mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0) - { + // draw bar: + if (isSelectedSegment && mSelectionDecorator) + { + mSelectionDecorator->applyBrush(painter); + mSelectionDecorator->applyPen(painter); + } else + { + painter->setBrush(mBrush); + painter->setPen(mPen); + } applyDefaultAntialiasingHint(painter); - painter->setPen(mainPen()); - painter->setBrush(Qt::NoBrush); - painter->drawPolyline(barPolygon); + painter->drawPolygon(getBarRect(it->key, it->value)); } } + + // draw other selection decoration that isn't just line/scatter pens and brushes: + if (mSelectionDecorator) + mSelectionDecorator->drawDecoration(painter, selection()); } /* inherits documentation from base class */ @@ -18816,57 +23691,63 @@ void QCPBars::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const called by \ref draw to determine which data (key) range is visible at the current key axis range setting, so only that needs to be processed. It also takes into account the bar width. - \a lower returns an iterator to the lowest data point that needs to be taken into account when + \a begin 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 upperEnd returns an iterator one higher than the highest visible data point. Same as before, \a - upperEnd may also lie just outside of the visible range. + \a end returns an iterator one higher than the highest visible data point. Same as before, \a end + may also lie just outside of the visible range. - if the bars plottable contains no data, both \a lower and \a upperEnd point to constEnd. + if the plottable contains no data, both \a begin and \a end point to constEnd. */ -void QCPBars::getVisibleDataBounds(QCPBarDataMap::const_iterator &lower, QCPBarDataMap::const_iterator &upperEnd) const +void QCPBars::getVisibleDataBounds(QCPBarsDataContainer::const_iterator &begin, QCPBarsDataContainer::const_iterator &end) const { - if (!mKeyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; } - if (mData->isEmpty()) + if (!mKeyAxis) { - lower = mData->constEnd(); - upperEnd = mData->constEnd(); + qDebug() << Q_FUNC_INFO << "invalid key axis"; + begin = mDataContainer->constEnd(); + end = mDataContainer->constEnd(); + return; + } + if (mDataContainer->isEmpty()) + { + begin = mDataContainer->constEnd(); + end = mDataContainer->constEnd(); return; } // get visible data range as QMap iterators - lower = mData->lowerBound(mKeyAxis.data()->range().lower); - upperEnd = mData->upperBound(mKeyAxis.data()->range().upper); + begin = mDataContainer->findBegin(mKeyAxis.data()->range().lower); + end = mDataContainer->findEnd(mKeyAxis.data()->range().upper); double lowerPixelBound = mKeyAxis.data()->coordToPixel(mKeyAxis.data()->range().lower); double upperPixelBound = mKeyAxis.data()->coordToPixel(mKeyAxis.data()->range().upper); bool isVisible = false; - // walk left from lbound to find lower bar that actually is completely outside visible pixel range: - QCPBarDataMap::const_iterator it = lower; - while (it != mData->constBegin()) + // walk left from begin to find lower bar that actually is completely outside visible pixel range: + QCPBarsDataContainer::const_iterator it = begin; + while (it != mDataContainer->constBegin()) { --it; - QRectF barBounds = getBarPolygon(it.value().key, it.value().value).boundingRect(); + const QRectF barRect = getBarRect(it->key, it->value); if (mKeyAxis.data()->orientation() == Qt::Horizontal) - isVisible = ((!mKeyAxis.data()->rangeReversed() && barBounds.right() >= lowerPixelBound) || (mKeyAxis.data()->rangeReversed() && barBounds.left() <= lowerPixelBound)); + isVisible = ((!mKeyAxis.data()->rangeReversed() && barRect.right() >= lowerPixelBound) || (mKeyAxis.data()->rangeReversed() && barRect.left() <= lowerPixelBound)); else // keyaxis is vertical - isVisible = ((!mKeyAxis.data()->rangeReversed() && barBounds.top() <= lowerPixelBound) || (mKeyAxis.data()->rangeReversed() && barBounds.bottom() >= lowerPixelBound)); + isVisible = ((!mKeyAxis.data()->rangeReversed() && barRect.top() <= lowerPixelBound) || (mKeyAxis.data()->rangeReversed() && barRect.bottom() >= lowerPixelBound)); if (isVisible) - lower = it; + begin = it; else break; } // walk right from ubound to find upper bar that actually is completely outside visible pixel range: - it = upperEnd; - while (it != mData->constEnd()) + it = end; + while (it != mDataContainer->constEnd()) { - QRectF barBounds = getBarPolygon(upperEnd.value().key, upperEnd.value().value).boundingRect(); + const QRectF barRect = getBarRect(it->key, it->value); if (mKeyAxis.data()->orientation() == Qt::Horizontal) - isVisible = ((!mKeyAxis.data()->rangeReversed() && barBounds.left() <= upperPixelBound) || (mKeyAxis.data()->rangeReversed() && barBounds.right() >= upperPixelBound)); + isVisible = ((!mKeyAxis.data()->rangeReversed() && barRect.left() <= upperPixelBound) || (mKeyAxis.data()->rangeReversed() && barRect.right() >= upperPixelBound)); else // keyaxis is vertical - isVisible = ((!mKeyAxis.data()->rangeReversed() && barBounds.bottom() >= upperPixelBound) || (mKeyAxis.data()->rangeReversed() && barBounds.top() <= upperPixelBound)); + isVisible = ((!mKeyAxis.data()->rangeReversed() && barRect.bottom() >= upperPixelBound) || (mKeyAxis.data()->rangeReversed() && barRect.top() <= upperPixelBound)); if (isVisible) - upperEnd = it+1; + end = it+1; else break; ++it; @@ -18875,17 +23756,16 @@ void QCPBars::getVisibleDataBounds(QCPBarDataMap::const_iterator &lower, QCPBarD /*! \internal - Returns the polygon of a single bar with \a key and \a value. The Polygon is open at the bottom - and shifted according to the bar stacking (see \ref moveAbove) and base value (see \ref - setBaseValue). + Returns the rect in pixel coordinates of a single bar with the specified \a key and \a value. The + rect is shifted according to the bar stacking (see \ref moveAbove) and base value (see \ref + setBaseValue), and to have non-overlapping border lines with the bars stacked below. */ -QPolygonF QCPBars::getBarPolygon(double key, double value) const +QRectF QCPBars::getBarRect(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 QPolygonF(); } + if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QRectF(); } - QPolygonF result; double lowerPixelWidth, upperPixelWidth; getPixelWidth(key, lowerPixelWidth, upperPixelWidth); double base = getStackedBaseValue(key, value >= 0); @@ -18894,20 +23774,18 @@ QPolygonF QCPBars::getBarPolygon(double key, double value) const double keyPixel = keyAxis->coordToPixel(key); if (mBarsGroup) keyPixel += mBarsGroup->keyPixelOffset(this, key); + double bottomOffset = (mBarBelow && mPen != Qt::NoPen ? 1 : 0)*(mPen.isCosmetic() ? 1 : mPen.widthF()); + bottomOffset += mBarBelow ? mStackingGap : 0; + bottomOffset *= (value<0 ? -1 : 1)*valueAxis->pixelOrientation(); + if (qAbs(valuePixel-basePixel) <= qAbs(bottomOffset)) + bottomOffset = valuePixel-basePixel; if (keyAxis->orientation() == Qt::Horizontal) { - result << QPointF(keyPixel+lowerPixelWidth, basePixel); - result << QPointF(keyPixel+lowerPixelWidth, valuePixel); - result << QPointF(keyPixel+upperPixelWidth, valuePixel); - result << QPointF(keyPixel+upperPixelWidth, basePixel); + return QRectF(QPointF(keyPixel+lowerPixelWidth, valuePixel), QPointF(keyPixel+upperPixelWidth, basePixel+bottomOffset)).normalized(); } else { - result << QPointF(basePixel, keyPixel+lowerPixelWidth); - result << QPointF(valuePixel, keyPixel+lowerPixelWidth); - result << QPointF(valuePixel, keyPixel+upperPixelWidth); - result << QPointF(basePixel, keyPixel+upperPixelWidth); + return QRectF(QPointF(basePixel+bottomOffset, keyPixel+lowerPixelWidth), QPointF(valuePixel, keyPixel+upperPixelWidth)).normalized(); } - return result; } /*! \internal @@ -18921,14 +23799,14 @@ QPolygonF QCPBars::getBarPolygon(double key, double value) const */ void QCPBars::getPixelWidth(double key, double &lower, double &upper) const { + lower = 0; + upper = 0; switch (mWidthType) { case wtAbsolute: { - upper = mWidth*0.5; + upper = mWidth*0.5*mKeyAxis.data()->pixelOrientation(); lower = -upper; - if (mKeyAxis && (mKeyAxis.data()->rangeReversed() ^ (mKeyAxis.data()->orientation() == Qt::Vertical))) - qSwap(lower, upper); break; } case wtAxisRectRatio: @@ -18936,12 +23814,10 @@ void QCPBars::getPixelWidth(double key, double &lower, double &upper) const if (mKeyAxis && mKeyAxis.data()->axisRect()) { if (mKeyAxis.data()->orientation() == Qt::Horizontal) - upper = mKeyAxis.data()->axisRect()->width()*mWidth*0.5; + upper = mKeyAxis.data()->axisRect()->width()*mWidth*0.5*mKeyAxis.data()->pixelOrientation(); else - upper = mKeyAxis.data()->axisRect()->height()*mWidth*0.5; + upper = mKeyAxis.data()->axisRect()->height()*mWidth*0.5*mKeyAxis.data()->pixelOrientation(); lower = -upper; - if (mKeyAxis && (mKeyAxis.data()->rangeReversed() ^ (mKeyAxis.data()->orientation() == Qt::Vertical))) - qSwap(lower, upper); } else qDebug() << Q_FUNC_INFO << "No key axis or axis rect defined"; break; @@ -18975,18 +23851,21 @@ double QCPBars::getStackedBaseValue(double key, bool positive) const { if (mBarBelow) { - double max = 0; // don't use mBaseValue here because only base value of bottom-most bar has meaning in a bar stack + double max = 0; // don't initialize with mBaseValue here because only base value of bottom-most bar has meaning in a bar stack // find bars of mBarBelow that are approximately at key and find largest one: - double epsilon = qAbs(key)*1e-6; // should be safe even when changed to use float at some point + double epsilon = qAbs(key)*(sizeof(key)==4 ? 1e-6 : 1e-14); // should be safe even when changed to use float at some point if (key == 0) - epsilon = 1e-6; - QCPBarDataMap::const_iterator it = mBarBelow.data()->mData->lowerBound(key-epsilon); - QCPBarDataMap::const_iterator itEnd = mBarBelow.data()->mData->upperBound(key+epsilon); + epsilon = (sizeof(key)==4 ? 1e-6 : 1e-14); + QCPBarsDataContainer::const_iterator it = mBarBelow.data()->mDataContainer->findBegin(key-epsilon); + QCPBarsDataContainer::const_iterator itEnd = mBarBelow.data()->mDataContainer->findEnd(key+epsilon); while (it != itEnd) { - if ((positive && it.value().value > max) || - (!positive && it.value().value < max)) - max = it.value().value; + if (it->key > key-epsilon && it->key < key+epsilon) + { + if ((positive && it->value > max) || + (!positive && it->value < max)) + max = it->value; + } ++it; } // recurse down the bar-stack to find the total height: @@ -19031,89 +23910,131 @@ void QCPBars::connectBars(QCPBars *lower, QCPBars *upper) upper->mBarBelow = lower; } } +/* end of 'src/plottables/plottable-bars.cpp' */ -/* inherits documentation from base class */ -QCPRange QCPBars::getKeyRange(bool &foundRange, SignDomain inSignDomain) const -{ - QCPRange range; - bool haveLower = false; - bool haveUpper = false; + +/* including file 'src/plottables/plottable-statisticalbox.cpp', size 28622 */ +/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */ + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPStatisticalBoxData +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPStatisticalBoxData + \brief Holds the data of one single data point for QCPStatisticalBox. - double current; - QCPBarDataMap::const_iterator it = mData->constBegin(); - while (it != mData->constEnd()) - { - current = it.value().key; - if (inSignDomain == sdBoth || (inSignDomain == sdNegative && current < 0) || (inSignDomain == sdPositive && current > 0)) - { - if (current < range.lower || !haveLower) - { - range.lower = current; - haveLower = true; - } - if (current > range.upper || !haveUpper) - { - range.upper = current; - haveUpper = true; - } - } - ++it; - } - // determine exact range of bars by including bar width and barsgroup offset: - if (haveLower && mKeyAxis) - { - double lowerPixelWidth, upperPixelWidth, keyPixel; - getPixelWidth(range.lower, lowerPixelWidth, upperPixelWidth); - keyPixel = mKeyAxis.data()->coordToPixel(range.lower) + lowerPixelWidth; - if (mBarsGroup) - keyPixel += mBarsGroup->keyPixelOffset(this, range.lower); - range.lower = mKeyAxis.data()->pixelToCoord(keyPixel); - } - if (haveUpper && mKeyAxis) - { - double lowerPixelWidth, upperPixelWidth, keyPixel; - getPixelWidth(range.upper, lowerPixelWidth, upperPixelWidth); - keyPixel = mKeyAxis.data()->coordToPixel(range.upper) + upperPixelWidth; - if (mBarsGroup) - keyPixel += mBarsGroup->keyPixelOffset(this, range.upper); - range.upper = mKeyAxis.data()->pixelToCoord(keyPixel); - } - foundRange = haveLower && haveUpper; - return range; + The stored data is: + + \li \a key: coordinate on the key axis of this data point (this is the \a mainKey and the \a sortKey) + + \li \a minimum: the position of the lower whisker, typically the minimum measurement of the + sample that's not considered an outlier. + + \li \a lowerQuartile: the lower end of the box. The lower and the upper quartiles are the two + statistical quartiles around the median of the sample, they should contain 50% of the sample + data. + + \li \a median: the value of the median mark inside the quartile box. The median separates the + sample data in half (50% of the sample data is below/above the median). (This is the \a mainValue) + + \li \a upperQuartile: the upper end of the box. The lower and the upper quartiles are the two + statistical quartiles around the median of the sample, they should contain 50% of the sample + data. + + \li \a maximum: the position of the upper whisker, typically the maximum measurement of the + sample that's not considered an outlier. + + \li \a outliers: a QVector of outlier values that will be drawn as scatter points at the \a key + coordinate of this data point (see \ref QCPStatisticalBox::setOutlierStyle) + + The container for storing multiple data points is \ref QCPStatisticalBoxDataContainer. It is a + typedef for \ref QCPDataContainer with \ref QCPStatisticalBoxData as the DataType template + parameter. See the documentation there for an explanation regarding the data type's generic + methods. + + \see QCPStatisticalBoxDataContainer +*/ + +/* start documentation of inline functions */ + +/*! \fn double QCPStatisticalBoxData::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 QCPStatisticalBoxData QCPStatisticalBoxData::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 QCPStatisticalBoxData::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 QCPStatisticalBoxData::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 QCPStatisticalBoxData::mainValue() const + + Returns the \a median 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 QCPStatisticalBoxData::valueRange() const + + Returns a QCPRange spanning from the \a minimum to the \a maximum member of this statistical box + data point, possibly further expanded by outliers. + + 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 and all values set to zero. +*/ +QCPStatisticalBoxData::QCPStatisticalBoxData() : + key(0), + minimum(0), + lowerQuartile(0), + median(0), + upperQuartile(0), + maximum(0) +{ } -/* inherits documentation from base class */ -QCPRange QCPBars::getValueRange(bool &foundRange, SignDomain inSignDomain) const +/*! + Constructs a data point with the specified \a key, \a minimum, \a lowerQuartile, \a median, \a + upperQuartile, \a maximum and optionally a number of \a outliers. +*/ +QCPStatisticalBoxData::QCPStatisticalBoxData(double key, double minimum, double lowerQuartile, double median, double upperQuartile, double maximum, const QVector &outliers) : + key(key), + minimum(minimum), + lowerQuartile(lowerQuartile), + median(median), + upperQuartile(upperQuartile), + maximum(maximum), + outliers(outliers) { - QCPRange range; - range.lower = mBaseValue; - range.upper = mBaseValue; - bool haveLower = true; // set to true, because baseValue should always be visible in bar charts - bool haveUpper = true; // set to true, because baseValue should always be visible in bar charts - double current; - - QCPBarDataMap::const_iterator it = mData->constBegin(); - while (it != mData->constEnd()) - { - current = it.value().value + getStackedBaseValue(it.value().key, it.value().value >= 0); - if (inSignDomain == sdBoth || (inSignDomain == sdNegative && current < 0) || (inSignDomain == sdPositive && current > 0)) - { - if (current < range.lower || !haveLower) - { - range.lower = current; - haveLower = true; - } - if (current > range.upper || !haveUpper) - { - range.upper = current; - haveUpper = true; - } - } - ++it; - } - - foundRange = true; // return true because bar charts always have the 0-line visible - return range; } @@ -19126,170 +24047,123 @@ QCPRange QCPBars::getValueRange(bool &foundRange, SignDomain inSignDomain) const \image html QCPStatisticalBox.png - To plot data, assign it with the individual parameter functions or use \ref setData to set all - parameters at once. The individual functions are: - \li \ref setMinimum - \li \ref setLowerQuartile - \li \ref setMedian - \li \ref setUpperQuartile - \li \ref setMaximum + To plot data, assign it with the \ref setData or \ref addData functions. Alternatively, you can + also access and modify the data via the \ref data method, which returns a pointer to the internal + \ref QCPStatisticalBoxDataContainer. - Additionally you can define a list of outliers, drawn as scatter datapoints: - \li \ref setOutliers + Additionally each data point can itself have a list of outliers, drawn as scatter points at the + key coordinate of the respective statistical box data point. They can either be set by using the + respective \ref addData(double,double,double,double,double,double,const QVector&) + "addData" method or accessing the individual data points through \ref data, and setting the + QVector outliers of the data points directly. - \section appearance Changing the appearance + \section qcpstatisticalbox-appearance Changing the appearance - The appearance of the box itself is controlled via \ref setPen and \ref setBrush. You may change - the width of the box with \ref setWidth in plot coordinates (not pixels). + The appearance of each data point box, ranging from the lower to the upper quartile, is + controlled via \ref setPen and \ref setBrush. You may change the width of the boxes with \ref + setWidth in plot coordinates. - Analog functions exist for the minimum/maximum-whiskers: \ref setWhiskerPen, \ref - setWhiskerBarPen, \ref setWhiskerWidth. The whisker width is the width of the bar at the top - (maximum) and bottom (minimum). + Each data point's visual representation also consists of two whiskers. Whiskers are the lines + which reach from the upper quartile to the maximum, and from the lower quartile to the minimum. + The appearance of the whiskers can be modified with: \ref setWhiskerPen, \ref setWhiskerBarPen, + \ref setWhiskerWidth. The whisker width is the width of the bar perpendicular to the whisker at + the top (for maximum) and bottom (for minimum). If the whisker pen is changed, make sure to set + the \c capStyle to \c Qt::FlatCap. Otherwise the backbone line might exceed the whisker bars by a + few pixels due to the pen cap being not perfectly flat. - The median indicator line has its own pen, \ref setMedianPen. + The median indicator line inside the box has its own pen, \ref setMedianPen. - If the whisker backbone pen is changed, make sure to set the capStyle to Qt::FlatCap. Else, the - backbone line might exceed the whisker bars by a few pixels due to the pen cap being not - perfectly flat. - - The Outlier data points are drawn as normal scatter points. Their look can be controlled with + The outlier data points are drawn as normal scatter points. Their look can be controlled with \ref setOutlierStyle - \section usage Usage + \section qcpstatisticalbox-usage Usage - Like all data representing objects in QCustomPlot, the QCPStatisticalBox is a plottable. - Usually, you first create an instance and add it to the customPlot: + Like all data representing objects in QCustomPlot, the QCPStatisticalBox is a plottable + (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies + (QCustomPlot::plottable, QCustomPlot::removePlottable, etc.) + + Usually, you first create an instance: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpstatisticalbox-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 qcpstatisticalbox-creation-2 */ +/* start documentation of inline functions */ + +/*! \fn QSharedPointer QCPStatisticalBox::data() const + + Returns a shared pointer to the internal data storage of type \ref + QCPStatisticalBoxDataContainer. 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 documentation of inline functions */ + /*! Constructs a statistical box 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 statistical box can be added to the plot with QCustomPlot::addPlottable, - QCustomPlot then takes ownership of the statistical box. + The created QCPStatisticalBox is automatically registered with the QCustomPlot instance inferred + from \a keyAxis. This QCustomPlot instance takes ownership of the QCPStatisticalBox, so do not + delete it manually but use QCustomPlot::removePlottable() instead. */ QCPStatisticalBox::QCPStatisticalBox(QCPAxis *keyAxis, QCPAxis *valueAxis) : - QCPAbstractPlottable(keyAxis, valueAxis), - mKey(0), - mMinimum(0), - mLowerQuartile(0), - mMedian(0), - mUpperQuartile(0), - mMaximum(0) + QCPAbstractPlottable1D(keyAxis, valueAxis), + mWidth(0.5), + mWhiskerWidth(0.2), + mWhiskerPen(Qt::black, 0, Qt::DashLine, Qt::FlatCap), + mWhiskerBarPen(Qt::black), + mWhiskerAntialiased(false), + mMedianPen(Qt::black, 3, Qt::SolidLine, Qt::FlatCap), + mOutlierStyle(QCPScatterStyle::ssCircle, Qt::blue, 6) { - setOutlierStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, Qt::blue, 6)); - setWhiskerWidth(0.2); - setWidth(0.5); - setPen(QPen(Qt::black)); - setSelectedPen(QPen(Qt::blue, 2.5)); - setMedianPen(QPen(Qt::black, 3, Qt::SolidLine, Qt::FlatCap)); - setWhiskerPen(QPen(Qt::black, 0, Qt::DashLine, Qt::FlatCap)); - setWhiskerBarPen(QPen(Qt::black)); setBrush(Qt::NoBrush); - setSelectedBrush(Qt::NoBrush); } -/*! - Sets the key coordinate of the statistical box. -*/ -void QCPStatisticalBox::setKey(double key) -{ - mKey = key; -} - -/*! - Sets the parameter "minimum" of the statistical box plot. This is the position of the lower - whisker, typically the minimum measurement of the sample that's not considered an outlier. +/*! \overload - \see setMaximum, setWhiskerPen, setWhiskerBarPen, setWhiskerWidth -*/ -void QCPStatisticalBox::setMinimum(double value) -{ - mMinimum = value; -} - -/*! - Sets the parameter "lower Quartile" of the statistical box plot. This is the lower end of the - box. The lower and the upper quartiles are the two statistical quartiles around the median of the - sample, they contain 50% of the sample data. + Replaces the current data container with the provided \a data container. - \see setUpperQuartile, setPen, setBrush, setWidth -*/ -void QCPStatisticalBox::setLowerQuartile(double value) -{ - mLowerQuartile = value; -} - -/*! - Sets the parameter "median" of the statistical box plot. This is the value of the median mark - inside the quartile box. The median separates the sample data in half (50% of the sample data is - below/above the median). + Since a QSharedPointer is used, multiple QCPStatisticalBoxes may share the same data container + safely. Modifying the data in the container will then affect all statistical boxes 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 qcpstatisticalbox-datasharing-1 - \see setMedianPen -*/ -void QCPStatisticalBox::setMedian(double value) -{ - mMedian = value; -} - -/*! - Sets the parameter "upper Quartile" of the statistical box plot. This is the upper end of the - box. The lower and the upper quartiles are the two statistical quartiles around the median of the - sample, they contain 50% of the sample data. + If you do not wish to share containers, but create a copy from an existing container, rather use + the \ref QCPDataContainer::set method on the statistical box data container directly: + \snippet documentation/doc-code-snippets/mainwindow.cpp qcpstatisticalbox-datasharing-2 - \see setLowerQuartile, setPen, setBrush, setWidth + \see addData */ -void QCPStatisticalBox::setUpperQuartile(double value) +void QCPStatisticalBox::setData(QSharedPointer data) { - mUpperQuartile = value; + mDataContainer = data; } - -/*! - Sets the parameter "maximum" of the statistical box plot. This is the position of the upper - whisker, typically the maximum measurement of the sample that's not considered an outlier. +/*! \overload - \see setMinimum, setWhiskerPen, setWhiskerBarPen, setWhiskerWidth -*/ -void QCPStatisticalBox::setMaximum(double value) -{ - mMaximum = value; -} - -/*! - Sets a vector of outlier values that will be drawn as scatters. Any data points in the sample - that are not within the whiskers (\ref setMinimum, \ref setMaximum) should be considered outliers - and displayed as such. + Replaces the current data with the provided points in \a keys, \a minimum, \a lowerQuartile, \a + median, \a upperQuartile and \a maximum. The provided vectors should have equal length. Else, the + number of added points will be the size of the smallest vector. - \see setOutlierStyle -*/ -void QCPStatisticalBox::setOutliers(const QVector &values) -{ - mOutliers = values; -} - -/*! - Sets all parameters of the statistical box plot at once. + 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 setKey, setMinimum, setLowerQuartile, setMedian, setUpperQuartile, setMaximum + \see addData */ -void QCPStatisticalBox::setData(double key, double minimum, double lowerQuartile, double median, double upperQuartile, double maximum) +void QCPStatisticalBox::setData(const QVector &keys, const QVector &minimum, const QVector &lowerQuartile, const QVector &median, const QVector &upperQuartile, const QVector &maximum, bool alreadySorted) { - setKey(key); - setMinimum(minimum); - setLowerQuartile(lowerQuartile); - setMedian(median); - setUpperQuartile(upperQuartile); - setMaximum(maximum); + mDataContainer->clear(); + addData(keys, minimum, lowerQuartile, median, upperQuartile, maximum, alreadySorted); } /*! - Sets the width of the box in key coordinates. + Sets the width of the boxes in key coordinates. \see setWhiskerWidth */ @@ -19299,7 +24173,10 @@ void QCPStatisticalBox::setWidth(double width) } /*! - Sets the width of the whiskers (\ref setMinimum, \ref setMaximum) in key coordinates. + Sets the width of the whiskers in key coordinates. + + Whiskers are the lines which reach from the upper quartile to the maximum, and from the lower + quartile to the minimum. \see setWidth */ @@ -19309,10 +24186,13 @@ void QCPStatisticalBox::setWhiskerWidth(double width) } /*! - Sets the pen used for drawing the whisker backbone (That's the line parallel to the value axis). + Sets the pen used for drawing the whisker backbone. - Make sure to set the \a pen capStyle to Qt::FlatCap to prevent the whisker backbone from reaching - a few pixels past the whisker bars, when using a non-zero pen width. + Whiskers are the lines which reach from the upper quartile to the maximum, and from the lower + quartile to the minimum. + + Make sure to set the \c capStyle of the passed \a pen to \c Qt::FlatCap. Otherwise the backbone + line might exceed the whisker bars by a few pixels due to the pen cap being not perfectly flat. \see setWhiskerBarPen */ @@ -19322,8 +24202,11 @@ void QCPStatisticalBox::setWhiskerPen(const QPen &pen) } /*! - Sets the pen used for drawing the whisker bars (Those are the lines parallel to the key axis at - each end of the whisker backbone). + Sets the pen used for drawing the whisker bars. Those are the lines parallel to the key axis at + each end of the whisker backbone. + + Whiskers are the lines which reach from the upper quartile to the maximum, and from the lower + quartile to the minimum. \see setWhiskerPen */ @@ -19333,7 +24216,18 @@ void QCPStatisticalBox::setWhiskerBarPen(const QPen &pen) } /*! - Sets the pen used for drawing the median indicator line inside the statistical box. + Sets whether the statistical boxes whiskers are drawn with antialiasing or not. + + Note that antialiasing settings may be overridden by QCustomPlot::setAntialiasedElements and + QCustomPlot::setNotAntialiasedElements. +*/ +void QCPStatisticalBox::setWhiskerAntialiased(bool enabled) +{ + mWhiskerAntialiased = enabled; +} + +/*! + Sets the pen used for drawing the median indicator line inside the statistical boxes. */ void QCPStatisticalBox::setMedianPen(const QPen &pen) { @@ -19342,77 +24236,215 @@ void QCPStatisticalBox::setMedianPen(const QPen &pen) /*! Sets the appearance of the outlier data points. - - \see setOutliers + + Outliers can be specified with the method + \ref addData(double key, double minimum, double lowerQuartile, double median, double upperQuartile, double maximum, const QVector &outliers) */ void QCPStatisticalBox::setOutlierStyle(const QCPScatterStyle &style) { mOutlierStyle = style; } -/* inherits documentation from base class */ -void QCPStatisticalBox::clearData() +/*! \overload + + Adds the provided points in \a keys, \a minimum, \a lowerQuartile, \a median, \a upperQuartile and + \a maximum 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 QCPStatisticalBox::addData(const QVector &keys, const QVector &minimum, const QVector &lowerQuartile, const QVector &median, const QVector &upperQuartile, const QVector &maximum, bool alreadySorted) { - setOutliers(QVector()); - setKey(0); - setMinimum(0); - setLowerQuartile(0); - setMedian(0); - setUpperQuartile(0); - setMaximum(0); + if (keys.size() != minimum.size() || minimum.size() != lowerQuartile.size() || lowerQuartile.size() != median.size() || + median.size() != upperQuartile.size() || upperQuartile.size() != maximum.size() || maximum.size() != keys.size()) + qDebug() << Q_FUNC_INFO << "keys, minimum, lowerQuartile, median, upperQuartile, maximum have different sizes:" + << keys.size() << minimum.size() << lowerQuartile.size() << median.size() << upperQuartile.size() << maximum.size(); + const int n = qMin(keys.size(), qMin(minimum.size(), qMin(lowerQuartile.size(), qMin(median.size(), qMin(upperQuartile.size(), maximum.size()))))); + QVector tempData(n); + QVector::iterator it = tempData.begin(); + const QVector::iterator itEnd = tempData.end(); + int i = 0; + while (it != itEnd) + { + it->key = keys[i]; + it->minimum = minimum[i]; + it->lowerQuartile = lowerQuartile[i]; + it->median = median[i]; + it->upperQuartile = upperQuartile[i]; + it->maximum = maximum[i]; + ++it; + ++i; + } + mDataContainer->add(tempData, alreadySorted); // don't modify tempData beyond this to prevent copy on write +} + +/*! \overload + + Adds the provided data point as \a key, \a minimum, \a lowerQuartile, \a median, \a upperQuartile + and \a maximum 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 QCPStatisticalBox::addData(double key, double minimum, double lowerQuartile, double median, double upperQuartile, double maximum, const QVector &outliers) +{ + mDataContainer->add(QCPStatisticalBoxData(key, minimum, lowerQuartile, median, upperQuartile, maximum, outliers)); +} + +/*! + \copydoc QCPPlottableInterface1D::selectTestRect +*/ +QCPDataSelection QCPStatisticalBox::selectTestRect(const QRectF &rect, bool onlySelectable) const +{ + QCPDataSelection result; + if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty()) + return result; + if (!mKeyAxis || !mValueAxis) + return result; + + QCPStatisticalBoxDataContainer::const_iterator visibleBegin, visibleEnd; + getVisibleDataBounds(visibleBegin, visibleEnd); + + for (QCPStatisticalBoxDataContainer::const_iterator it=visibleBegin; it!=visibleEnd; ++it) + { + if (rect.intersects(getQuartileBox(it))) + result.addDataRange(QCPDataRange(it-mDataContainer->constBegin(), it-mDataContainer->constBegin()+1), false); + } + result.simplify(); + return result; } /* inherits documentation from base class */ double QCPStatisticalBox::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) - if (onlySelectable && !mSelectable) + 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())) + if (mKeyAxis->axisRect()->rect().contains(pos.toPoint())) { - double posKey, posValue; - pixelsToCoords(pos, posKey, posValue); - // quartile box: - QCPRange keyRange(mKey-mWidth*0.5, mKey+mWidth*0.5); - QCPRange valueRange(mLowerQuartile, mUpperQuartile); - if (keyRange.contains(posKey) && valueRange.contains(posValue)) - return mParentPlot->selectionTolerance()*0.99; - - // min/max whiskers: - if (QCPRange(mMinimum, mMaximum).contains(posValue)) - return qAbs(mKeyAxis.data()->coordToPixel(mKey)-mKeyAxis.data()->coordToPixel(posKey)); + // get visible data range: + QCPStatisticalBoxDataContainer::const_iterator visibleBegin, visibleEnd; + QCPStatisticalBoxDataContainer::const_iterator closestDataPoint = mDataContainer->constEnd(); + getVisibleDataBounds(visibleBegin, visibleEnd); + double minDistSqr = std::numeric_limits::max(); + for (QCPStatisticalBoxDataContainer::const_iterator it=visibleBegin; it!=visibleEnd; ++it) + { + if (getQuartileBox(it).contains(pos)) // quartile box + { + double currentDistSqr = mParentPlot->selectionTolerance()*0.99 * mParentPlot->selectionTolerance()*0.99; + if (currentDistSqr < minDistSqr) + { + minDistSqr = currentDistSqr; + closestDataPoint = it; + } + } else // whiskers + { + const QVector whiskerBackbones(getWhiskerBackboneLines(it)); + for (int i=0; iconstBegin(); + details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1))); + } + return qSqrt(minDistSqr); } return -1; } +/* inherits documentation from base class */ +QCPRange QCPStatisticalBox::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const +{ + QCPRange range = mDataContainer->keyRange(foundRange, inSignDomain); + // determine exact range by including width of bars/flags: + if (foundRange) + { + if (inSignDomain != QCP::sdPositive || range.lower-mWidth*0.5 > 0) + range.lower -= mWidth*0.5; + if (inSignDomain != QCP::sdNegative || range.upper+mWidth*0.5 < 0) + range.upper += mWidth*0.5; + } + return range; +} + +/* inherits documentation from base class */ +QCPRange QCPStatisticalBox::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const +{ + return mDataContainer->valueRange(foundRange, inSignDomain, inKeyRange); +} + /* inherits documentation from base class */ void QCPStatisticalBox::draw(QCPPainter *painter) { - if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } - - // check data validity if flag set: -#ifdef QCUSTOMPLOT_CHECK_DATA - if (QCP::isInvalidData(mKey, mMedian) || - QCP::isInvalidData(mLowerQuartile, mUpperQuartile) || - QCP::isInvalidData(mMinimum, mMaximum)) - qDebug() << Q_FUNC_INFO << "Data point at" << mKey << "of drawn range has invalid data." << "Plottable name:" << name(); - for (int i=0; iisEmpty()) return; + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } - QRectF quartileBox; - drawQuartileBox(painter, &quartileBox); + QCPStatisticalBoxDataContainer::const_iterator visibleBegin, visibleEnd; + getVisibleDataBounds(visibleBegin, visibleEnd); - painter->save(); - painter->setClipRect(quartileBox, Qt::IntersectClip); - drawMedian(painter); - painter->restore(); + // loop over and draw segments of unselected/selected data: + QList selectedSegments, unselectedSegments, allSegments; + getDataSegments(selectedSegments, unselectedSegments); + allSegments << unselectedSegments << selectedSegments; + for (int i=0; i= unselectedSegments.size(); + QCPStatisticalBoxDataContainer::const_iterator begin = visibleBegin; + QCPStatisticalBoxDataContainer::const_iterator end = visibleEnd; + mDataContainer->limitIteratorsToDataRange(begin, end, allSegments.at(i)); + if (begin == end) + continue; + + for (QCPStatisticalBoxDataContainer::const_iterator it=begin; it!=end; ++it) + { + // check data validity if flag set: +# ifdef QCUSTOMPLOT_CHECK_DATA + if (QCP::isInvalidData(it->key, it->minimum) || + QCP::isInvalidData(it->lowerQuartile, it->median) || + QCP::isInvalidData(it->upperQuartile, it->maximum)) + qDebug() << Q_FUNC_INFO << "Data point at" << it->key << "of drawn range has invalid data." << "Plottable name:" << name(); + for (int i=0; ioutliers.size(); ++i) + if (QCP::isInvalidData(it->outliers.at(i))) + qDebug() << Q_FUNC_INFO << "Data point outlier at" << it->key << "of drawn range invalid." << "Plottable name:" << name(); +# endif + + if (isSelectedSegment && mSelectionDecorator) + { + mSelectionDecorator->applyPen(painter); + mSelectionDecorator->applyBrush(painter); + } else + { + painter->setPen(mPen); + painter->setBrush(mBrush); + } + QCPScatterStyle finalOutlierStyle = mOutlierStyle; + if (isSelectedSegment && mSelectionDecorator) + finalOutlierStyle = mSelectionDecorator->getFinalScatterStyle(mOutlierStyle); + drawStatisticalBox(painter, it, finalOutlierStyle); + } + } - drawWhiskers(painter); - drawOutliers(painter); + // draw other selection decoration that isn't just line/scatter pens and brushes: + if (mSelectionDecorator) + mSelectionDecorator->drawDecoration(painter, selection()); } /* inherits documentation from base class */ @@ -19427,147 +24459,116 @@ void QCPStatisticalBox::drawLegendIcon(QCPPainter *painter, const QRectF &rect) painter->drawRect(r); } -/*! \internal - - Draws the quartile box. \a box is an output parameter that returns the quartile box (in pixel - coordinates) which is used to set the clip rect of the painter before calling \ref drawMedian (so - the median doesn't draw outside the quartile box). -*/ -void QCPStatisticalBox::drawQuartileBox(QCPPainter *painter, QRectF *quartileBox) const -{ - QRectF box; - box.setTopLeft(coordsToPixels(mKey-mWidth*0.5, mUpperQuartile)); - box.setBottomRight(coordsToPixels(mKey+mWidth*0.5, mLowerQuartile)); - applyDefaultAntialiasingHint(painter); - painter->setPen(mainPen()); - painter->setBrush(mainBrush()); - painter->drawRect(box); - if (quartileBox) - *quartileBox = box; -} +/*! + Draws the graphical representation of a single statistical box with the data given by the + iterator \a it with the provided \a painter. -/*! \internal - - Draws the median line inside the quartile box. + If the statistical box has a set of outlier data points, they are drawn with \a outlierStyle. + + \see getQuartileBox, getWhiskerBackboneLines, getWhiskerBarLines */ -void QCPStatisticalBox::drawMedian(QCPPainter *painter) const +void QCPStatisticalBox::drawStatisticalBox(QCPPainter *painter, QCPStatisticalBoxDataContainer::const_iterator it, const QCPScatterStyle &outlierStyle) const { - QLineF medianLine; - medianLine.setP1(coordsToPixels(mKey-mWidth*0.5, mMedian)); - medianLine.setP2(coordsToPixels(mKey+mWidth*0.5, mMedian)); + // draw quartile box: applyDefaultAntialiasingHint(painter); + const QRectF quartileBox = getQuartileBox(it); + painter->drawRect(quartileBox); + // draw median line with cliprect set to quartile box: + painter->save(); + painter->setClipRect(quartileBox, Qt::IntersectClip); painter->setPen(mMedianPen); - painter->drawLine(medianLine); -} - -/*! \internal - - Draws both whisker backbones and bars. -*/ -void QCPStatisticalBox::drawWhiskers(QCPPainter *painter) const -{ - QLineF backboneMin, backboneMax, barMin, barMax; - backboneMax.setPoints(coordsToPixels(mKey, mUpperQuartile), coordsToPixels(mKey, mMaximum)); - backboneMin.setPoints(coordsToPixels(mKey, mLowerQuartile), coordsToPixels(mKey, mMinimum)); - barMax.setPoints(coordsToPixels(mKey-mWhiskerWidth*0.5, mMaximum), coordsToPixels(mKey+mWhiskerWidth*0.5, mMaximum)); - barMin.setPoints(coordsToPixels(mKey-mWhiskerWidth*0.5, mMinimum), coordsToPixels(mKey+mWhiskerWidth*0.5, mMinimum)); - applyErrorBarsAntialiasingHint(painter); + painter->drawLine(QLineF(coordsToPixels(it->key-mWidth*0.5, it->median), coordsToPixels(it->key+mWidth*0.5, it->median))); + painter->restore(); + // draw whisker lines: + applyAntialiasingHint(painter, mWhiskerAntialiased, QCP::aePlottables); painter->setPen(mWhiskerPen); - painter->drawLine(backboneMin); - painter->drawLine(backboneMax); + painter->drawLines(getWhiskerBackboneLines(it)); painter->setPen(mWhiskerBarPen); - painter->drawLine(barMin); - painter->drawLine(barMax); -} - -/*! \internal - - Draws the outlier scatter points. -*/ -void QCPStatisticalBox::drawOutliers(QCPPainter *painter) const -{ + painter->drawLines(getWhiskerBarLines(it)); + // draw outliers: applyScattersAntialiasingHint(painter); - mOutlierStyle.applyTo(painter, mPen); - for (int i=0; ioutliers.size(); ++i) + outlierStyle.drawShape(painter, coordsToPixels(it->key, it->outliers.at(i))); } -/* inherits documentation from base class */ -QCPRange QCPStatisticalBox::getKeyRange(bool &foundRange, SignDomain inSignDomain) const +/*! \internal + + called by \ref draw to determine which data (key) range is visible at the current key axis range + setting, so only that needs to be processed. It also takes into account the bar width. + + \a begin 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 end returns an iterator one higher than the highest visible data point. Same as before, \a end + may also lie just outside of the visible range. + + if the plottable contains no data, both \a begin and \a end point to constEnd. +*/ +void QCPStatisticalBox::getVisibleDataBounds(QCPStatisticalBoxDataContainer::const_iterator &begin, QCPStatisticalBoxDataContainer::const_iterator &end) const { - foundRange = true; - if (inSignDomain == sdBoth) + if (!mKeyAxis) { - return QCPRange(mKey-mWidth*0.5, mKey+mWidth*0.5); - } else if (inSignDomain == sdNegative) - { - if (mKey+mWidth*0.5 < 0) - return QCPRange(mKey-mWidth*0.5, mKey+mWidth*0.5); - else if (mKey < 0) - return QCPRange(mKey-mWidth*0.5, mKey); - else - { - foundRange = false; - return QCPRange(); - } - } else if (inSignDomain == sdPositive) - { - if (mKey-mWidth*0.5 > 0) - return QCPRange(mKey-mWidth*0.5, mKey+mWidth*0.5); - else if (mKey > 0) - return QCPRange(mKey, mKey+mWidth*0.5); - else - { - foundRange = false; - return QCPRange(); - } + qDebug() << Q_FUNC_INFO << "invalid key axis"; + begin = mDataContainer->constEnd(); + end = mDataContainer->constEnd(); + return; } - foundRange = false; - return QCPRange(); + begin = mDataContainer->findBegin(mKeyAxis.data()->range().lower-mWidth*0.5); // subtract half width of box to include partially visible data points + end = mDataContainer->findEnd(mKeyAxis.data()->range().upper+mWidth*0.5); // add half width of box to include partially visible data points } -/* inherits documentation from base class */ -QCPRange QCPStatisticalBox::getValueRange(bool &foundRange, SignDomain inSignDomain) const +/*! \internal + + Returns the box in plot coordinates (keys in x, values in y of the returned rect) that covers the + value range from the lower to the upper quartile, of the data given by \a it. + + \see drawStatisticalBox, getWhiskerBackboneLines, getWhiskerBarLines +*/ +QRectF QCPStatisticalBox::getQuartileBox(QCPStatisticalBoxDataContainer::const_iterator it) const { - QVector values; // values that must be considered (i.e. all outliers and the five box-parameters) - values.reserve(mOutliers.size() + 5); - values << mMaximum << mUpperQuartile << mMedian << mLowerQuartile << mMinimum; - values << mOutliers; - // go through values and find the ones in legal range: - bool haveUpper = false; - bool haveLower = false; - double upper = 0; - double lower = 0; - for (int i=0; i 0) || - (inSignDomain == sdBoth)) - { - if (values.at(i) > upper || !haveUpper) - { - upper = values.at(i); - haveUpper = true; - } - if (values.at(i) < lower || !haveLower) - { - lower = values.at(i); - haveLower = true; - } - } - } - // return the bounds if we found some sensible values: - if (haveLower && haveUpper) - { - foundRange = true; - return QCPRange(lower, upper); - } else // might happen if all values are in other sign domain - { - foundRange = false; - return QCPRange(); - } + QRectF result; + result.setTopLeft(coordsToPixels(it->key-mWidth*0.5, it->upperQuartile)); + result.setBottomRight(coordsToPixels(it->key+mWidth*0.5, it->lowerQuartile)); + return result; } +/*! \internal + + Returns the whisker backbones (keys in x, values in y of the returned lines) that cover the value + range from the minimum to the lower quartile, and from the upper quartile to the maximum of the + data given by \a it. + + \see drawStatisticalBox, getQuartileBox, getWhiskerBarLines +*/ +QVector QCPStatisticalBox::getWhiskerBackboneLines(QCPStatisticalBoxDataContainer::const_iterator it) const +{ + QVector result(2); + result[0].setPoints(coordsToPixels(it->key, it->lowerQuartile), coordsToPixels(it->key, it->minimum)); // min backbone + result[1].setPoints(coordsToPixels(it->key, it->upperQuartile), coordsToPixels(it->key, it->maximum)); // max backbone + return result; +} + +/*! \internal + + Returns the whisker bars (keys in x, values in y of the returned lines) that are placed at the + end of the whisker backbones, at the minimum and maximum of the data given by \a it. + + \see drawStatisticalBox, getQuartileBox, getWhiskerBackboneLines +*/ +QVector QCPStatisticalBox::getWhiskerBarLines(QCPStatisticalBoxDataContainer::const_iterator it) const +{ + QVector result(2); + result[0].setPoints(coordsToPixels(it->key-mWhiskerWidth*0.5, it->minimum), coordsToPixels(it->key+mWhiskerWidth*0.5, it->minimum)); // min bar + result[1].setPoints(coordsToPixels(it->key-mWhiskerWidth*0.5, it->maximum), coordsToPixels(it->key+mWhiskerWidth*0.5, it->maximum)); // max bar + return result; +} +/* end of 'src/plottables/plottable-statisticalbox.cpp' */ + + +/* including file 'src/plottables/plottable-colormap.cpp', size 47531 */ +/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */ //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPColorMapData @@ -19589,6 +24590,11 @@ QCPRange QCPStatisticalBox::getValueRange(bool &foundRange, SignDomain inSignDom coordinate with \ref setData. plot coordinate to cell index transformations and vice versa are provided by the functions \ref coordToCell and \ref cellToCoord. + A \ref QCPColorMapData also holds an on-demand two-dimensional array of alpha values which (if + allocated) has the same size as the data map. It can be accessed via \ref setAlpha, \ref + fillAlpha and \ref clearAlpha. The memory for the alpha map is only allocated if needed, i.e. on + the first call of \ref setAlpha. \ref clearAlpha restores full opacity and frees the alpha map. + This class also buffers the minimum and maximum values that are in the data set, to provide QCPColorMap::rescaleDataRange with the necessary information quickly. Setting a cell to a value that is greater than the current maximum increases this maximum to the new value. However, @@ -19625,6 +24631,7 @@ QCPColorMapData::QCPColorMapData(int keySize, int valueSize, const QCPRange &key mValueRange(valueRange), mIsEmpty(true), mData(0), + mAlpha(0), mDataModified(true) { setSize(keySize, valueSize); @@ -19635,6 +24642,8 @@ QCPColorMapData::~QCPColorMapData() { if (mData) delete[] mData; + if (mAlpha) + delete[] mAlpha; } /*! @@ -19645,13 +24654,15 @@ QCPColorMapData::QCPColorMapData(const QCPColorMapData &other) : mValueSize(0), mIsEmpty(true), mData(0), + mAlpha(0), mDataModified(true) { *this = other; } /*! - Overwrites this color map data instance with the data stored in \a other. + Overwrites this color map data instance with the data stored in \a other. The alpha map state is + transferred, too. */ QCPColorMapData &QCPColorMapData::operator=(const QCPColorMapData &other) { @@ -19659,10 +24670,18 @@ QCPColorMapData &QCPColorMapData::operator=(const QCPColorMapData &other) { const int keySize = other.keySize(); const int valueSize = other.valueSize(); + if (!other.mAlpha && mAlpha) + clearAlpha(); setSize(keySize, valueSize); + if (other.mAlpha && !mAlpha) + createAlpha(false); setRange(other.keyRange(), other.valueRange()); - if (!mIsEmpty) + if (!isEmpty()) + { memcpy(mData, other.mData, sizeof(mData[0])*keySize*valueSize); + if (mAlpha) + memcpy(mAlpha, other.mAlpha, sizeof(mAlpha[0])*keySize*valueSize); + } mDataBounds = other.mDataBounds; mDataModified = true; } @@ -19689,6 +24708,22 @@ double QCPColorMapData::cell(int keyIndex, int valueIndex) return 0; } +/*! + Returns the alpha map value of the cell with the indices \a keyIndex and \a valueIndex. + + If this color map data doesn't have an alpha map (because \ref setAlpha was never called after + creation or after a call to \ref clearAlpha), returns 255, which corresponds to full opacity. + + \see setAlpha +*/ +unsigned char QCPColorMapData::alpha(int keyIndex, int valueIndex) +{ + if (mAlpha && keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize) + return mAlpha[valueIndex*mKeySize + keyIndex]; + else + return 255; +} + /*! Resizes the data array to have \a keySize cells in the key dimension and \a valueSize cells in the value dimension. @@ -19725,6 +24760,10 @@ void QCPColorMapData::setSize(int keySize, int valueSize) qDebug() << Q_FUNC_INFO << "out of memory for data dimensions "<< mKeySize << "*" << mValueSize; } else mData = 0; + + if (mAlpha) // if we had an alpha map, recreate it with new size + createAlpha(); + mDataModified = true; } } @@ -19853,7 +24892,36 @@ void QCPColorMapData::setCell(int keyIndex, int valueIndex, double z) if (z > mDataBounds.upper) mDataBounds.upper = z; mDataModified = true; - } + } else + qDebug() << Q_FUNC_INFO << "index out of bounds:" << keyIndex << valueIndex; +} + +/*! + Sets the alpha of the color map cell given by \a keyIndex and \a valueIndex to \a alpha. A value + of 0 for \a alpha results in a fully transparent cell, and a value of 255 results in a fully + opaque cell. + + If an alpha map doesn't exist yet for this color map data, it will be created here. If you wish + to restore full opacity and free any allocated memory of the alpha map, call \ref clearAlpha. + + Note that the cell-wise alpha which can be configured here is independent of any alpha configured + in the color map's gradient (\ref QCPColorGradient). If a cell is affected both by the cell-wise + and gradient alpha, the alpha values will be blended accordingly during rendering of the color + map. + + \see fillAlpha, clearAlpha +*/ +void QCPColorMapData::setAlpha(int keyIndex, int valueIndex, unsigned char alpha) +{ + if (keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize) + { + if (mAlpha || createAlpha()) + { + mAlpha[valueIndex*mKeySize + keyIndex] = alpha; + mDataModified = true; + } + } else + qDebug() << Q_FUNC_INFO << "index out of bounds:" << keyIndex << valueIndex; } /*! @@ -19898,6 +24966,19 @@ void QCPColorMapData::clear() setSize(0, 0); } +/*! + Frees the internal alpha map. The color map will have full opacity again. +*/ +void QCPColorMapData::clearAlpha() +{ + if (mAlpha) + { + delete[] mAlpha; + mAlpha = 0; + mDataModified = true; + } +} + /*! Sets all cells to the value \a z. */ @@ -19910,6 +24991,26 @@ void QCPColorMapData::fill(double z) mDataModified = true; } +/*! + Sets the opacity of all color map cells to \a alpha. A value of 0 for \a alpha results in a fully + transparent color map, and a value of 255 results in a fully opaque color map. + + If you wish to restore opacity to 100% and free any used memory for the alpha map, rather use + \ref clearAlpha. + + \see setAlpha +*/ +void QCPColorMapData::fillAlpha(unsigned char alpha) +{ + if (mAlpha || createAlpha(false)) + { + const int dataCount = mValueSize*mKeySize; + for (int i=0; iclear(); -} - /* inherits documentation from base class */ double QCPColorMap::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) - if (onlySelectable && !mSelectable) + if ((onlySelectable && mSelectable == QCP::stNone) || mMapData->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())) { double posKey, posValue; pixelsToCoords(pos, posKey, posValue); if (mMapData->keyRange().contains(posKey) && mMapData->valueRange().contains(posValue)) + { + if (details) + details->setValue(QCPDataSelection(QCPDataRange(0, 1))); // temporary solution, to facilitate whole-plottable selection. Replace in future version with segmented 2D selection. return mParentPlot->selectionTolerance()*0.99; + } } return -1; } +/* inherits documentation from base class */ +QCPRange QCPColorMap::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const +{ + foundRange = true; + QCPRange result = mMapData->keyRange(); + result.normalize(); + if (inSignDomain == QCP::sdPositive) + { + if (result.lower <= 0 && result.upper > 0) + result.lower = result.upper*1e-3; + else if (result.lower <= 0 && result.upper <= 0) + foundRange = false; + } else if (inSignDomain == QCP::sdNegative) + { + if (result.upper >= 0 && result.lower < 0) + result.upper = result.lower*1e-3; + else if (result.upper >= 0 && result.lower >= 0) + foundRange = false; + } + return result; +} + +/* inherits documentation from base class */ +QCPRange QCPColorMap::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const +{ + if (inKeyRange != QCPRange()) + { + if (mMapData->keyRange().upper < inKeyRange.lower || mMapData->keyRange().lower > inKeyRange.upper) + { + foundRange = false; + return QCPRange(); + } + } + + foundRange = true; + QCPRange result = mMapData->valueRange(); + result.normalize(); + if (inSignDomain == QCP::sdPositive) + { + if (result.lower <= 0 && result.upper > 0) + result.lower = result.upper*1e-3; + else if (result.lower <= 0 && result.upper <= 0) + foundRange = false; + } else if (inSignDomain == QCP::sdNegative) + { + if (result.upper >= 0 && result.lower < 0) + result.upper = result.lower*1e-3; + else if (result.upper >= 0 && result.lower >= 0) + foundRange = false; + } + return result; +} + /*! \internal Updates the internal map image buffer by going through the internal \ref QCPColorMapData and @@ -20333,6 +25539,7 @@ void QCPColorMap::updateMapImage() if (!keyAxis) return; if (mMapData->isEmpty()) return; + const QImage::Format format = QImage::Format_ARGB32_Premultiplied; const int keySize = mMapData->keySize(); const int valueSize = mMapData->valueSize(); int keyOversamplingFactor = mInterpolate ? 1 : (int)(1.0+100.0/(double)keySize); // make mMapImage have at least size 100, factor becomes 1 if size > 200 or interpolation is on @@ -20340,23 +25547,24 @@ void QCPColorMap::updateMapImage() // resize mMapImage to correct dimensions including possible oversampling factors, according to key/value axes orientation: if (keyAxis->orientation() == Qt::Horizontal && (mMapImage.width() != keySize*keyOversamplingFactor || mMapImage.height() != valueSize*valueOversamplingFactor)) - mMapImage = QImage(QSize(keySize*keyOversamplingFactor, valueSize*valueOversamplingFactor), QImage::Format_RGB32); + mMapImage = QImage(QSize(keySize*keyOversamplingFactor, valueSize*valueOversamplingFactor), format); else if (keyAxis->orientation() == Qt::Vertical && (mMapImage.width() != valueSize*valueOversamplingFactor || mMapImage.height() != keySize*keyOversamplingFactor)) - mMapImage = QImage(QSize(valueSize*valueOversamplingFactor, keySize*keyOversamplingFactor), QImage::Format_RGB32); + mMapImage = QImage(QSize(valueSize*valueOversamplingFactor, keySize*keyOversamplingFactor), format); QImage *localMapImage = &mMapImage; // this is the image on which the colorization operates. Either the final mMapImage, or if we need oversampling, mUndersampledMapImage if (keyOversamplingFactor > 1 || valueOversamplingFactor > 1) { // resize undersampled map image to actual key/value cell sizes: if (keyAxis->orientation() == Qt::Horizontal && (mUndersampledMapImage.width() != keySize || mUndersampledMapImage.height() != valueSize)) - mUndersampledMapImage = QImage(QSize(keySize, valueSize), QImage::Format_RGB32); + mUndersampledMapImage = QImage(QSize(keySize, valueSize), format); else if (keyAxis->orientation() == Qt::Vertical && (mUndersampledMapImage.width() != valueSize || mUndersampledMapImage.height() != keySize)) - mUndersampledMapImage = QImage(QSize(valueSize, keySize), QImage::Format_RGB32); + mUndersampledMapImage = QImage(QSize(valueSize, keySize), format); localMapImage = &mUndersampledMapImage; // make the colorization run on the undersampled image } else if (!mUndersampledMapImage.isNull()) mUndersampledMapImage = QImage(); // don't need oversampling mechanism anymore (map size has changed) but mUndersampledMapImage still has nonzero size, free it const double *rawData = mMapData->mData; + const unsigned char *rawAlpha = mMapData->mAlpha; if (keyAxis->orientation() == Qt::Horizontal) { const int lineCount = valueSize; @@ -20364,7 +25572,10 @@ void QCPColorMap::updateMapImage() for (int line=0; line(localMapImage->scanLine(lineCount-1-line)); // invert scanline index because QImage counts scanlines from top, but our vertical index counts from bottom (mathematical coordinate system) - mGradient.colorize(rawData+line*rowCount, mDataRange, pixels, rowCount, 1, mDataScaleType==QCPAxis::stLogarithmic); + if (rawAlpha) + mGradient.colorize(rawData+line*rowCount, rawAlpha+line*rowCount, mDataRange, pixels, rowCount, 1, mDataScaleType==QCPAxis::stLogarithmic); + else + mGradient.colorize(rawData+line*rowCount, mDataRange, pixels, rowCount, 1, mDataScaleType==QCPAxis::stLogarithmic); } } else // keyAxis->orientation() == Qt::Vertical { @@ -20373,7 +25584,10 @@ void QCPColorMap::updateMapImage() for (int line=0; line(localMapImage->scanLine(lineCount-1-line)); // invert scanline index because QImage counts scanlines from top, but our vertical index counts from bottom (mathematical coordinate system) - mGradient.colorize(rawData+line, mDataRange, pixels, rowCount, lineCount, mDataScaleType==QCPAxis::stLogarithmic); + if (rawAlpha) + mGradient.colorize(rawData+line, rawAlpha+line, mDataRange, pixels, rowCount, lineCount, mDataScaleType==QCPAxis::stLogarithmic); + else + mGradient.colorize(rawData+line, mDataRange, pixels, rowCount, lineCount, mDataScaleType==QCPAxis::stLogarithmic); } } @@ -20399,13 +25613,13 @@ void QCPColorMap::draw(QCPPainter *painter) updateMapImage(); // use buffer if painting vectorized (PDF): - bool useBuffer = painter->modes().testFlag(QCPPainter::pmVectorized); + const bool useBuffer = painter->modes().testFlag(QCPPainter::pmVectorized); QCPPainter *localPainter = painter; // will be redirected to paint on mapBuffer if painting vectorized QRectF mapBufferTarget; // the rect in absolute widget coordinates where the visible map portion/buffer will end up in QPixmap mapBuffer; - double mapBufferPixelRatio = 3; // factor by which DPI is increased in embedded bitmaps if (useBuffer) { + const double mapBufferPixelRatio = 3; // factor by which DPI is increased in embedded bitmaps mapBufferTarget = painter->clipRegion().boundingRect(); mapBuffer = QPixmap((mapBufferTarget.size()*mapBufferPixelRatio).toSize()); mapBuffer.fill(Qt::transparent); @@ -20433,9 +25647,9 @@ void QCPColorMap::draw(QCPPainter *painter) halfCellWidth = 0.5*imageRect.width()/(double)(mMapData->valueSize()-1); } imageRect.adjust(-halfCellWidth, -halfCellHeight, halfCellWidth, halfCellHeight); - bool mirrorX = (keyAxis()->orientation() == Qt::Horizontal ? keyAxis() : valueAxis())->rangeReversed(); - bool mirrorY = (valueAxis()->orientation() == Qt::Vertical ? valueAxis() : keyAxis())->rangeReversed(); - bool smoothBackup = localPainter->renderHints().testFlag(QPainter::SmoothPixmapTransform); + const bool mirrorX = (keyAxis()->orientation() == Qt::Horizontal ? keyAxis() : valueAxis())->rangeReversed(); + const bool mirrorY = (valueAxis()->orientation() == Qt::Vertical ? valueAxis() : keyAxis())->rangeReversed(); + const bool smoothBackup = localPainter->renderHints().testFlag(QPainter::SmoothPixmapTransform); localPainter->setRenderHint(QPainter::SmoothPixmapTransform, mInterpolate); QRegion clipBackup; if (mTightBoundary) @@ -20476,51 +25690,11 @@ void QCPColorMap::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const painter->drawRect(rect.adjusted(1, 1, 0, 0)); */ } +/* end of 'src/plottables/plottable-colormap.cpp' */ -/* inherits documentation from base class */ -QCPRange QCPColorMap::getKeyRange(bool &foundRange, SignDomain inSignDomain) const -{ - foundRange = true; - QCPRange result = mMapData->keyRange(); - result.normalize(); - if (inSignDomain == QCPAbstractPlottable::sdPositive) - { - if (result.lower <= 0 && result.upper > 0) - result.lower = result.upper*1e-3; - else if (result.lower <= 0 && result.upper <= 0) - foundRange = false; - } else if (inSignDomain == QCPAbstractPlottable::sdNegative) - { - if (result.upper >= 0 && result.lower < 0) - result.upper = result.lower*1e-3; - else if (result.upper >= 0 && result.lower >= 0) - foundRange = false; - } - return result; -} - -/* inherits documentation from base class */ -QCPRange QCPColorMap::getValueRange(bool &foundRange, SignDomain inSignDomain) const -{ - foundRange = true; - QCPRange result = mMapData->valueRange(); - result.normalize(); - if (inSignDomain == QCPAbstractPlottable::sdPositive) - { - if (result.lower <= 0 && result.upper > 0) - result.lower = result.upper*1e-3; - else if (result.lower <= 0 && result.upper <= 0) - foundRange = false; - } else if (inSignDomain == QCPAbstractPlottable::sdNegative) - { - if (result.upper >= 0 && result.lower < 0) - result.upper = result.lower*1e-3; - else if (result.upper >= 0 && result.lower >= 0) - foundRange = false; - } - return result; -} +/* including file 'src/plottables/plottable-financial.cpp', size 42610 */ +/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */ //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPFinancialData @@ -20529,18 +25703,73 @@ QCPRange QCPColorMap::getValueRange(bool &foundRange, SignDomain inSignDomain) c /*! \class QCPFinancialData \brief Holds the data of one single data point for QCPFinancial. - The container for storing multiple data points is \ref QCPFinancialDataMap. - The stored data is: - \li \a key: coordinate on the key axis of this data point - \li \a open: The opening value at the data point + \li \a key: coordinate on the key axis of this data point (this is the \a mainKey and the \a sortKey) + \li \a open: The opening value at the data point (this is the \a mainValue) \li \a high: The high/maximum value at the data point \li \a low: The low/minimum value at the data point \li \a close: The closing value at the data point - \see QCPFinancialDataMap + The container for storing multiple data points is \ref QCPFinancialDataContainer. It is a typedef + for \ref QCPDataContainer with \ref QCPFinancialData as the DataType template parameter. See the + documentation there for an explanation regarding the data type's generic methods. + + \see QCPFinancialDataContainer */ +/* start documentation of inline functions */ + +/*! \fn double QCPFinancialData::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 QCPFinancialData QCPFinancialData::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 QCPFinancialData::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 QCPFinancialData::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 QCPFinancialData::mainValue() const + + Returns the \a open 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 QCPFinancialData::valueRange() const + + Returns a QCPRange spanning from the \a low to the \a high 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 and all values set to zero. */ @@ -20574,41 +25803,58 @@ QCPFinancialData::QCPFinancialData(double key, double open, double high, double \brief A plottable representing a financial stock chart \image html QCPFinancial.png - + This plottable represents time series data binned to certain intervals, mainly used for stock charts. The two common representations OHLC (Open-High-Low-Close) bars and Candlesticks can be set via \ref setChartStyle. - + The data is passed via \ref setData as a set of open/high/low/close values at certain keys (typically times). This means the data must be already binned appropriately. If data is only available as a series of values (e.g. \a price against \a time), you can use the static convenience function \ref timeSeriesToOhlc to generate binned OHLC-data which can then be passed to \ref setData. - - The width of the OHLC bars/candlesticks can be controlled with \ref setWidth and is given in plot - key coordinates. A typical choice is to set it to (or slightly less than) one bin interval width. - - \section appearance Changing the appearance - + + The width of the OHLC bars/candlesticks can be controlled with \ref setWidth and \ref + setWidthType. A typical choice is to set the width type to \ref wtPlotCoords (the default) and + the width to (or slightly less than) one time bin interval width. + + \section qcpfinancial-appearance Changing the appearance + Charts can be either single- or two-colored (\ref setTwoColored). If set to be single-colored, lines are drawn with the plottable's pen (\ref setPen) and fills with the brush (\ref setBrush). - + If set to two-colored, positive changes of the value during an interval (\a close >= \a open) are represented with a different pen and brush than negative changes (\a close < \a open). These can be configured with \ref setPenPositive, \ref setPenNegative, \ref setBrushPositive, and \ref setBrushNegative. In two-colored mode, the normal plottable pen/brush is ignored. Upon selection - however, the normal selected pen/brush (\ref setSelectedPen, \ref setSelectedBrush) is used, + however, the normal selected pen/brush (provided by the \ref selectionDecorator) is used, irrespective of whether the chart is single- or two-colored. - + + \section qcpfinancial-usage Usage + + Like all data representing objects in QCustomPlot, the QCPFinancial is a plottable + (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies + (QCustomPlot::plottable, QCustomPlot::removePlottable, etc.) + + Usually, you first create an instance: + + \snippet documentation/doc-code-snippets/mainwindow.cpp qcpfinancial-creation-1 + 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 qcpfinancial-creation-2 + Here we have used the static helper method \ref timeSeriesToOhlc, to turn a time-price data + series into a 24-hour binned open-high-low-close data series as QCPFinancial uses. */ /* start of documentation of inline functions */ -/*! \fn QCPFinancialDataMap *QCPFinancial::data() const +/*! \fn QCPFinancialDataContainer *QCPFinancial::data() const - Returns a pointer to the internal data storage of type \ref QCPFinancialDataMap. 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 pointer to the internal data storage of type \ref QCPFinancialDataContainer. 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. */ /* end of documentation of inline functions */ @@ -20619,79 +25865,63 @@ QCPFinancialData::QCPFinancialData(double key, double open, double high, double 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 QCPFinancial can be added to the plot with QCustomPlot::addPlottable, QCustomPlot - then takes ownership of the financial chart. + The created QCPFinancial is automatically registered with the QCustomPlot instance inferred from \a + keyAxis. This QCustomPlot instance takes ownership of the QCPFinancial, so do not delete it manually + but use QCustomPlot::removePlottable() instead. */ QCPFinancial::QCPFinancial(QCPAxis *keyAxis, QCPAxis *valueAxis) : - QCPAbstractPlottable(keyAxis, valueAxis), - mData(0), - mChartStyle(csOhlc), + QCPAbstractPlottable1D(keyAxis, valueAxis), + mChartStyle(csCandlestick), mWidth(0.5), - mTwoColored(false), - mBrushPositive(QBrush(QColor(210, 210, 255))), - mBrushNegative(QBrush(QColor(255, 210, 210))), - mPenPositive(QPen(QColor(10, 40, 180))), - mPenNegative(QPen(QColor(180, 40, 10))) + mWidthType(wtPlotCoords), + mTwoColored(true), + mBrushPositive(QBrush(QColor(50, 160, 0))), + mBrushNegative(QBrush(QColor(180, 0, 15))), + mPenPositive(QPen(QColor(40, 150, 0))), + mPenNegative(QPen(QColor(170, 5, 5))) { - mData = new QCPFinancialDataMap; - - setSelectedPen(QPen(QColor(80, 80, 255), 2.5)); - setSelectedBrush(QBrush(QColor(80, 80, 255))); + mSelectionDecorator->setBrush(QBrush(QColor(160, 160, 255))); } QCPFinancial::~QCPFinancial() { - delete mData; -} - -/*! - Replaces the current data with the provided \a data. - - 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. - - Alternatively, you can also access and modify the plottable's data via the \ref data method, which - returns a pointer to the internal \ref QCPFinancialDataMap. - - \see timeSeriesToOhlc -*/ -void QCPFinancial::setData(QCPFinancialDataMap *data, bool copy) -{ - if (mData == data) - { - qDebug() << Q_FUNC_INFO << "The data pointer is already in (and owned by) this plottable" << reinterpret_cast(data); - return; - } - if (copy) - { - *mData = *data; - } else - { - delete mData; - mData = data; - } } /*! \overload - Replaces the current data with the provided open/high/low/close data. 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 container with the provided \a data container. - \see timeSeriesToOhlc + Since a QSharedPointer is used, multiple QCPFinancials may share the same data container safely. + Modifying the data in the container will then affect all financials 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 qcpfinancial-datasharing-1 + + If you do not wish to share containers, but create a copy from an existing container, rather use + the \ref QCPDataContainer::set method on the financial's data container directly: + \snippet documentation/doc-code-snippets/mainwindow.cpp qcpfinancial-datasharing-2 + + \see addData, timeSeriesToOhlc */ -void QCPFinancial::setData(const QVector &key, const QVector &open, const QVector &high, const QVector &low, const QVector &close) +void QCPFinancial::setData(QSharedPointer data) { - mData->clear(); - int n = key.size(); - n = qMin(n, open.size()); - n = qMin(n, high.size()); - n = qMin(n, low.size()); - n = qMin(n, close.size()); - for (int i=0; iinsertMulti(key[i], QCPFinancialData(key[i], open[i], high[i], low[i], close[i])); - } + mDataContainer = data; +} + +/*! \overload + + Replaces the current data with the provided points in \a keys, \a open, \a high, \a low and \a + close. 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. + + \see addData, timeSeriesToOhlc +*/ +void QCPFinancial::setData(const QVector &keys, const QVector &open, const QVector &high, const QVector &low, const QVector &close, bool alreadySorted) +{ + mDataContainer->clear(); + addData(keys, open, high, low, close, alreadySorted); } /*! @@ -20712,6 +25942,19 @@ void QCPFinancial::setWidth(double width) mWidth = width; } +/*! + Sets how the width of the financial bars is defined. See the documentation of \ref WidthType for + an explanation of the possible values for \a widthType. + + The default value is \ref wtPlotCoords. + + \see setWidth +*/ +void QCPFinancial::setWidthType(QCPFinancial::WidthType widthType) +{ + mWidthType = widthType; +} + /*! Sets whether this chart shall contrast positive from negative trends per data point by using two separate colors to draw the respective bars/candlesticks. @@ -20782,164 +26025,140 @@ void QCPFinancial::setPenNegative(const QPen &pen) mPenNegative = pen; } -/*! - Adds the provided data points in \a dataMap to the current data. +/*! \overload - Alternatively, you can also access and modify the data via the \ref data method, which returns a - pointer to the internal \ref QCPFinancialDataMap. + Adds the provided points in \a keys, \a open, \a high, \a low and \a close 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. - \see removeData + 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. + + \see timeSeriesToOhlc */ -void QCPFinancial::addData(const QCPFinancialDataMap &dataMap) +void QCPFinancial::addData(const QVector &keys, const QVector &open, const QVector &high, const QVector &low, const QVector &close, bool alreadySorted) { - mData->unite(dataMap); + if (keys.size() != open.size() || open.size() != high.size() || high.size() != low.size() || low.size() != close.size() || close.size() != keys.size()) + qDebug() << Q_FUNC_INFO << "keys, open, high, low, close have different sizes:" << keys.size() << open.size() << high.size() << low.size() << close.size(); + const int n = qMin(keys.size(), qMin(open.size(), qMin(high.size(), qMin(low.size(), close.size())))); + QVector tempData(n); + QVector::iterator it = tempData.begin(); + const QVector::iterator itEnd = tempData.end(); + int i = 0; + while (it != itEnd) + { + it->key = keys[i]; + it->open = open[i]; + it->high = high[i]; + it->low = low[i]; + it->close = close[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 in \a data to the current data. + Adds the provided data point as \a key, \a open, \a high, \a low and \a close to the current + data. - Alternatively, you can also access and modify the data via the \ref data method, which returns a - pointer to the internal \ref QCPFinancialData. + Alternatively, you can also access and modify the data directly via the \ref data method, which + returns a pointer to the internal data container. - \see removeData -*/ -void QCPFinancial::addData(const QCPFinancialData &data) -{ - mData->insertMulti(data.key, data); -} - -/*! \overload - - Adds the provided single data point given by \a key, \a open, \a high, \a low, and \a close to - the current data. - - Alternatively, you can also access and modify the data via the \ref data method, which returns a - pointer to the internal \ref QCPFinancialData. - - \see removeData + \see timeSeriesToOhlc */ void QCPFinancial::addData(double key, double open, double high, double low, double close) { - mData->insertMulti(key, QCPFinancialData(key, open, high, low, close)); + mDataContainer->add(QCPFinancialData(key, open, high, low, close)); } -/*! \overload - - Adds the provided open/high/low/close data to the current data. - - Alternatively, you can also access and modify the data via the \ref data method, which returns a - pointer to the internal \ref QCPFinancialData. - - \see removeData +/*! + \copydoc QCPPlottableInterface1D::selectTestRect */ -void QCPFinancial::addData(const QVector &key, const QVector &open, const QVector &high, const QVector &low, const QVector &close) +QCPDataSelection QCPFinancial::selectTestRect(const QRectF &rect, bool onlySelectable) const { - int n = key.size(); - n = qMin(n, open.size()); - n = qMin(n, high.size()); - n = qMin(n, low.size()); - n = qMin(n, close.size()); - for (int i=0; iisEmpty()) + return result; + if (!mKeyAxis || !mValueAxis) + return result; + + QCPFinancialDataContainer::const_iterator visibleBegin, visibleEnd; + getVisibleDataBounds(visibleBegin, visibleEnd); + + for (QCPFinancialDataContainer::const_iterator it=visibleBegin; it!=visibleEnd; ++it) { - mData->insertMulti(key[i], QCPFinancialData(key[i], open[i], high[i], low[i], close[i])); + if (rect.intersects(selectionHitBox(it))) + result.addDataRange(QCPDataRange(it-mDataContainer->constBegin(), it-mDataContainer->constBegin()+1), false); } -} - -/*! - Removes all data points with keys smaller than \a key. - - \see addData, clearData -*/ -void QCPFinancial::removeDataBefore(double key) -{ - QCPFinancialDataMap::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 QCPFinancial::removeDataAfter(double key) -{ - if (mData->isEmpty()) return; - QCPFinancialDataMap::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 QCPFinancial::removeData(double fromKey, double toKey) -{ - if (fromKey >= toKey || mData->isEmpty()) return; - QCPFinancialDataMap::iterator it = mData->upperBound(fromKey); - QCPFinancialDataMap::iterator itEnd = mData->upperBound(toKey); - while (it != itEnd) - it = mData->erase(it); -} - -/*! \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 QCPFinancial::removeData(double key) -{ - mData->remove(key); -} - -/*! - Removes all data points. - - \see removeData, removeDataAfter, removeDataBefore -*/ -void QCPFinancial::clearData() -{ - mData->clear(); + result.simplify(); + return result; } /* inherits documentation from base class */ double QCPFinancial::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) - if (onlySelectable && !mSelectable) + 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())) { // get visible data range: - QCPFinancialDataMap::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 -1; + QCPFinancialDataContainer::const_iterator visibleBegin, visibleEnd; + QCPFinancialDataContainer::const_iterator closestDataPoint = mDataContainer->constEnd(); + getVisibleDataBounds(visibleBegin, visibleEnd); // perform select test according to configured style: + double result = -1; switch (mChartStyle) { case QCPFinancial::csOhlc: - return ohlcSelectTest(pos, lower, upper+1); break; + result = ohlcSelectTest(pos, visibleBegin, visibleEnd, closestDataPoint); break; case QCPFinancial::csCandlestick: - return candlestickSelectTest(pos, lower, upper+1); break; + result = candlestickSelectTest(pos, visibleBegin, visibleEnd, closestDataPoint); break; } + if (details) + { + int pointIndex = closestDataPoint-mDataContainer->constBegin(); + details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1))); + } + return result; } + return -1; } +/* inherits documentation from base class */ +QCPRange QCPFinancial::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const +{ + QCPRange range = mDataContainer->keyRange(foundRange, inSignDomain); + // determine exact range by including width of bars/flags: + if (foundRange) + { + if (inSignDomain != QCP::sdPositive || range.lower-mWidth*0.5 > 0) + range.lower -= mWidth*0.5; + if (inSignDomain != QCP::sdNegative || range.upper+mWidth*0.5 < 0) + range.upper += mWidth*0.5; + } + return range; +} + +/* inherits documentation from base class */ +QCPRange QCPFinancial::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const +{ + return mDataContainer->valueRange(foundRange, inSignDomain, inKeyRange); +} + /*! A convenience function that converts time series data (\a value against \a time) to OHLC binned - data points. The return value can then be passed on to \ref setData. + data points. The return value can then be passed on to \ref QCPFinancialDataContainer::set(const + QCPFinancialDataContainer&). The size of the bins can be controlled with \a timeBinSize in the same units as \a time is given. For example, if the unit of \a time is seconds and single OHLC/Candlesticks should span an hour @@ -20950,12 +26169,12 @@ double QCPFinancial::selectTest(const QPointF &pos, bool onlySelectable, QVarian It merely defines the mathematical offset/phase of the bins that will be used to process the data. */ -QCPFinancialDataMap QCPFinancial::timeSeriesToOhlc(const QVector &time, const QVector &value, double timeBinSize, double timeBinOffset) +QCPFinancialDataContainer QCPFinancial::timeSeriesToOhlc(const QVector &time, const QVector &value, double timeBinSize, double timeBinOffset) { - QCPFinancialDataMap map; + QCPFinancialDataContainer data; int count = qMin(time.size(), value.size()); if (count == 0) - return QCPFinancialDataMap(); + return QCPFinancialDataContainer(); QCPFinancialData currentBinData(0, value.first(), value.first(), value.first(), value.first()); int currentBinIndex = qFloor((time.first()-timeBinOffset)/timeBinSize+0.5); @@ -20970,14 +26189,14 @@ QCPFinancialDataMap QCPFinancial::timeSeriesToOhlc(const QVector &time, { currentBinData.close = value.at(i); currentBinData.key = timeBinOffset+(index)*timeBinSize; - map.insert(currentBinData.key, currentBinData); + data.add(currentBinData); } } else // data point not anymore in current bin, set close of old and open of new bin, and add old to map: { // finalize current bin: currentBinData.close = value.at(i-1); currentBinData.key = timeBinOffset+(index-1)*timeBinSize; - map.insert(currentBinData.key, currentBinData); + data.add(currentBinData); // start next bin: currentBinIndex = index; currentBinData.open = value.at(i); @@ -20986,26 +26205,42 @@ QCPFinancialDataMap QCPFinancial::timeSeriesToOhlc(const QVector &time, } } - return map; + return data; } /* inherits documentation from base class */ void QCPFinancial::draw(QCPPainter *painter) { // get visible data range: - QCPFinancialDataMap::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; + QCPFinancialDataContainer::const_iterator visibleBegin, visibleEnd; + getVisibleDataBounds(visibleBegin, visibleEnd); - // draw visible data range according to configured style: - switch (mChartStyle) + // loop over and draw segments of unselected/selected data: + QList selectedSegments, unselectedSegments, allSegments; + getDataSegments(selectedSegments, unselectedSegments); + allSegments << unselectedSegments << selectedSegments; + for (int i=0; i= unselectedSegments.size(); + QCPFinancialDataContainer::const_iterator begin = visibleBegin; + QCPFinancialDataContainer::const_iterator end = visibleEnd; + mDataContainer->limitIteratorsToDataRange(begin, end, allSegments.at(i)); + if (begin == end) + continue; + + // draw data segment according to configured style: + switch (mChartStyle) + { + case QCPFinancial::csOhlc: + drawOhlcPlot(painter, begin, end, isSelectedSegment); break; + case QCPFinancial::csCandlestick: + drawCandlestickPlot(painter, begin, end, isSelectedSegment); break; + } } + + // draw other selection decoration that isn't just line/scatter pens and brushes: + if (mSelectionDecorator) + mSelectionDecorator->drawDecoration(painter, selection()); } /* inherits documentation from base class */ @@ -21023,7 +26258,7 @@ void QCPFinancial::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const painter->drawLine(QLineF(0, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft())); painter->drawLine(QLineF(rect.width()*0.2, rect.height()*0.3, rect.width()*0.2, rect.height()*0.5).translated(rect.topLeft())); painter->drawLine(QLineF(rect.width()*0.8, rect.height()*0.5, rect.width()*0.8, rect.height()*0.7).translated(rect.topLeft())); - // draw bottom right hald icon with negative color: + // draw bottom right half icon with negative color: painter->setBrush(mBrushNegative); painter->setPen(mPenNegative); painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.bottomRight().toPoint())); @@ -21049,7 +26284,7 @@ void QCPFinancial::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const painter->drawLine(QLineF(0, rect.height()*0.5, rect.width()*0.25, rect.height()*0.5).translated(rect.topLeft())); painter->drawLine(QLineF(rect.width()*0.75, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft())); painter->drawRect(QRectF(rect.width()*0.25, rect.height()*0.25, rect.width()*0.5, rect.height()*0.5).translated(rect.topLeft())); - // draw bottom right hald icon with negative color: + // draw bottom right half icon with negative color: painter->setBrush(mBrushNegative); painter->setPen(mPenNegative); painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.bottomRight().toPoint())); @@ -21067,272 +26302,222 @@ void QCPFinancial::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const } } -/* inherits documentation from base class */ -QCPRange QCPFinancial::getKeyRange(bool &foundRange, QCPAbstractPlottable::SignDomain inSignDomain) const -{ - QCPRange range; - bool haveLower = false; - bool haveUpper = false; - - double current; - QCPFinancialDataMap::const_iterator it = mData->constBegin(); - while (it != mData->constEnd()) - { - current = it.value().key; - if (inSignDomain == sdBoth || (inSignDomain == sdNegative && current < 0) || (inSignDomain == sdPositive && current > 0)) - { - if (current < range.lower || !haveLower) - { - range.lower = current; - haveLower = true; - } - if (current > range.upper || !haveUpper) - { - range.upper = current; - haveUpper = true; - } - } - ++it; - } - // determine exact range by including width of bars/flags: - if (haveLower && mKeyAxis) - range.lower = range.lower-mWidth*0.5; - if (haveUpper && mKeyAxis) - range.upper = range.upper+mWidth*0.5; - foundRange = haveLower && haveUpper; - return range; -} - -/* inherits documentation from base class */ -QCPRange QCPFinancial::getValueRange(bool &foundRange, QCPAbstractPlottable::SignDomain inSignDomain) const -{ - QCPRange range; - bool haveLower = false; - bool haveUpper = false; - - QCPFinancialDataMap::const_iterator it = mData->constBegin(); - while (it != mData->constEnd()) - { - // high: - if (inSignDomain == sdBoth || (inSignDomain == sdNegative && it.value().high < 0) || (inSignDomain == sdPositive && it.value().high > 0)) - { - if (it.value().high < range.lower || !haveLower) - { - range.lower = it.value().high; - haveLower = true; - } - if (it.value().high > range.upper || !haveUpper) - { - range.upper = it.value().high; - haveUpper = true; - } - } - // low: - if (inSignDomain == sdBoth || (inSignDomain == sdNegative && it.value().low < 0) || (inSignDomain == sdPositive && it.value().low > 0)) - { - if (it.value().low < range.lower || !haveLower) - { - range.lower = it.value().low; - haveLower = true; - } - if (it.value().low > range.upper || !haveUpper) - { - range.upper = it.value().low; - haveUpper = true; - } - } - ++it; - } - - foundRange = haveLower && haveUpper; - return range; -} - /*! \internal - Draws the data from \a begin to \a end as OHLC bars with the provided \a painter. + Draws the data from \a begin to \a end-1 as OHLC bars with the provided \a painter. This method is a helper function for \ref draw. It is used when the chart style is \ref csOhlc. */ -void QCPFinancial::drawOhlcPlot(QCPPainter *painter, const QCPFinancialDataMap::const_iterator &begin, const QCPFinancialDataMap::const_iterator &end) +void QCPFinancial::drawOhlcPlot(QCPPainter *painter, const QCPFinancialDataContainer::const_iterator &begin, const QCPFinancialDataContainer::const_iterator &end, bool isSelected) { QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } - QPen linePen; - if (keyAxis->orientation() == Qt::Horizontal) { - for (QCPFinancialDataMap::const_iterator it = begin; it != end; ++it) + for (QCPFinancialDataContainer::const_iterator it = begin; it != end; ++it) { - if (mSelected) - linePen = mSelectedPen; + if (isSelected && mSelectionDecorator) + mSelectionDecorator->applyPen(painter); else if (mTwoColored) - linePen = it.value().close >= it.value().open ? mPenPositive : mPenNegative; + painter->setPen(it->close >= it->open ? mPenPositive : mPenNegative); else - linePen = mPen; - painter->setPen(linePen); - double keyPixel = keyAxis->coordToPixel(it.value().key); - double openPixel = valueAxis->coordToPixel(it.value().open); - double closePixel = valueAxis->coordToPixel(it.value().close); + painter->setPen(mPen); + double keyPixel = keyAxis->coordToPixel(it->key); + double openPixel = valueAxis->coordToPixel(it->open); + double closePixel = valueAxis->coordToPixel(it->close); // draw backbone: - painter->drawLine(QPointF(keyPixel, valueAxis->coordToPixel(it.value().high)), QPointF(keyPixel, valueAxis->coordToPixel(it.value().low))); + painter->drawLine(QPointF(keyPixel, valueAxis->coordToPixel(it->high)), QPointF(keyPixel, valueAxis->coordToPixel(it->low))); // draw open: - double keyWidthPixels = keyPixel-keyAxis->coordToPixel(it.value().key-mWidth*0.5); // sign of this makes sure open/close are on correct sides - painter->drawLine(QPointF(keyPixel-keyWidthPixels, openPixel), QPointF(keyPixel, openPixel)); + double pixelWidth = getPixelWidth(it->key, keyPixel); // sign of this makes sure open/close are on correct sides + painter->drawLine(QPointF(keyPixel-pixelWidth, openPixel), QPointF(keyPixel, openPixel)); // draw close: - painter->drawLine(QPointF(keyPixel, closePixel), QPointF(keyPixel+keyWidthPixels, closePixel)); + painter->drawLine(QPointF(keyPixel, closePixel), QPointF(keyPixel+pixelWidth, closePixel)); } } else { - for (QCPFinancialDataMap::const_iterator it = begin; it != end; ++it) + for (QCPFinancialDataContainer::const_iterator it = begin; it != end; ++it) { - if (mSelected) - linePen = mSelectedPen; + if (isSelected && mSelectionDecorator) + mSelectionDecorator->applyPen(painter); else if (mTwoColored) - linePen = it.value().close >= it.value().open ? mPenPositive : mPenNegative; + painter->setPen(it->close >= it->open ? mPenPositive : mPenNegative); else - linePen = mPen; - painter->setPen(linePen); - double keyPixel = keyAxis->coordToPixel(it.value().key); - double openPixel = valueAxis->coordToPixel(it.value().open); - double closePixel = valueAxis->coordToPixel(it.value().close); + painter->setPen(mPen); + double keyPixel = keyAxis->coordToPixel(it->key); + double openPixel = valueAxis->coordToPixel(it->open); + double closePixel = valueAxis->coordToPixel(it->close); // draw backbone: - painter->drawLine(QPointF(valueAxis->coordToPixel(it.value().high), keyPixel), QPointF(valueAxis->coordToPixel(it.value().low), keyPixel)); + painter->drawLine(QPointF(valueAxis->coordToPixel(it->high), keyPixel), QPointF(valueAxis->coordToPixel(it->low), keyPixel)); // draw open: - double keyWidthPixels = keyPixel-keyAxis->coordToPixel(it.value().key-mWidth*0.5); // sign of this makes sure open/close are on correct sides - painter->drawLine(QPointF(openPixel, keyPixel-keyWidthPixels), QPointF(openPixel, keyPixel)); + double pixelWidth = getPixelWidth(it->key, keyPixel); // sign of this makes sure open/close are on correct sides + painter->drawLine(QPointF(openPixel, keyPixel-pixelWidth), QPointF(openPixel, keyPixel)); // draw close: - painter->drawLine(QPointF(closePixel, keyPixel), QPointF(closePixel, keyPixel+keyWidthPixels)); + painter->drawLine(QPointF(closePixel, keyPixel), QPointF(closePixel, keyPixel+pixelWidth)); } } } /*! \internal - Draws the data from \a begin to \a end as Candlesticks with the provided \a painter. + Draws the data from \a begin to \a end-1 as Candlesticks with the provided \a painter. This method is a helper function for \ref draw. It is used when the chart style is \ref csCandlestick. */ -void QCPFinancial::drawCandlestickPlot(QCPPainter *painter, const QCPFinancialDataMap::const_iterator &begin, const QCPFinancialDataMap::const_iterator &end) +void QCPFinancial::drawCandlestickPlot(QCPPainter *painter, const QCPFinancialDataContainer::const_iterator &begin, const QCPFinancialDataContainer::const_iterator &end, bool isSelected) { QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } - QPen linePen; - QBrush boxBrush; - if (keyAxis->orientation() == Qt::Horizontal) { - for (QCPFinancialDataMap::const_iterator it = begin; it != end; ++it) + for (QCPFinancialDataContainer::const_iterator it = begin; it != end; ++it) { - if (mSelected) + if (isSelected && mSelectionDecorator) { - linePen = mSelectedPen; - boxBrush = mSelectedBrush; + mSelectionDecorator->applyPen(painter); + mSelectionDecorator->applyBrush(painter); } else if (mTwoColored) { - if (it.value().close >= it.value().open) - { - linePen = mPenPositive; - boxBrush = mBrushPositive; - } else - { - linePen = mPenNegative; - boxBrush = mBrushNegative; - } + painter->setPen(it->close >= it->open ? mPenPositive : mPenNegative); + painter->setBrush(it->close >= it->open ? mBrushPositive : mBrushNegative); } else { - linePen = mPen; - boxBrush = mBrush; + painter->setPen(mPen); + painter->setBrush(mBrush); } - painter->setPen(linePen); - painter->setBrush(boxBrush); - double keyPixel = keyAxis->coordToPixel(it.value().key); - double openPixel = valueAxis->coordToPixel(it.value().open); - double closePixel = valueAxis->coordToPixel(it.value().close); + double keyPixel = keyAxis->coordToPixel(it->key); + double openPixel = valueAxis->coordToPixel(it->open); + double closePixel = valueAxis->coordToPixel(it->close); // draw high: - painter->drawLine(QPointF(keyPixel, valueAxis->coordToPixel(it.value().high)), QPointF(keyPixel, valueAxis->coordToPixel(qMax(it.value().open, it.value().close)))); + painter->drawLine(QPointF(keyPixel, valueAxis->coordToPixel(it->high)), QPointF(keyPixel, valueAxis->coordToPixel(qMax(it->open, it->close)))); // draw low: - painter->drawLine(QPointF(keyPixel, valueAxis->coordToPixel(it.value().low)), QPointF(keyPixel, valueAxis->coordToPixel(qMin(it.value().open, it.value().close)))); + painter->drawLine(QPointF(keyPixel, valueAxis->coordToPixel(it->low)), QPointF(keyPixel, valueAxis->coordToPixel(qMin(it->open, it->close)))); // draw open-close box: - double keyWidthPixels = keyPixel-keyAxis->coordToPixel(it.value().key-mWidth*0.5); - painter->drawRect(QRectF(QPointF(keyPixel-keyWidthPixels, closePixel), QPointF(keyPixel+keyWidthPixels, openPixel))); + double pixelWidth = getPixelWidth(it->key, keyPixel); + painter->drawRect(QRectF(QPointF(keyPixel-pixelWidth, closePixel), QPointF(keyPixel+pixelWidth, openPixel))); } } else // keyAxis->orientation() == Qt::Vertical { - for (QCPFinancialDataMap::const_iterator it = begin; it != end; ++it) + for (QCPFinancialDataContainer::const_iterator it = begin; it != end; ++it) { - if (mSelected) + if (isSelected && mSelectionDecorator) { - linePen = mSelectedPen; - boxBrush = mSelectedBrush; + mSelectionDecorator->applyPen(painter); + mSelectionDecorator->applyBrush(painter); } else if (mTwoColored) { - if (it.value().close >= it.value().open) - { - linePen = mPenPositive; - boxBrush = mBrushPositive; - } else - { - linePen = mPenNegative; - boxBrush = mBrushNegative; - } + painter->setPen(it->close >= it->open ? mPenPositive : mPenNegative); + painter->setBrush(it->close >= it->open ? mBrushPositive : mBrushNegative); } else { - linePen = mPen; - boxBrush = mBrush; + painter->setPen(mPen); + painter->setBrush(mBrush); } - painter->setPen(linePen); - painter->setBrush(boxBrush); - double keyPixel = keyAxis->coordToPixel(it.value().key); - double openPixel = valueAxis->coordToPixel(it.value().open); - double closePixel = valueAxis->coordToPixel(it.value().close); + double keyPixel = keyAxis->coordToPixel(it->key); + double openPixel = valueAxis->coordToPixel(it->open); + double closePixel = valueAxis->coordToPixel(it->close); // draw high: - painter->drawLine(QPointF(valueAxis->coordToPixel(it.value().high), keyPixel), QPointF(valueAxis->coordToPixel(qMax(it.value().open, it.value().close)), keyPixel)); + painter->drawLine(QPointF(valueAxis->coordToPixel(it->high), keyPixel), QPointF(valueAxis->coordToPixel(qMax(it->open, it->close)), keyPixel)); // draw low: - painter->drawLine(QPointF(valueAxis->coordToPixel(it.value().low), keyPixel), QPointF(valueAxis->coordToPixel(qMin(it.value().open, it.value().close)), keyPixel)); + painter->drawLine(QPointF(valueAxis->coordToPixel(it->low), keyPixel), QPointF(valueAxis->coordToPixel(qMin(it->open, it->close)), keyPixel)); // draw open-close box: - double keyWidthPixels = keyPixel-keyAxis->coordToPixel(it.value().key-mWidth*0.5); - painter->drawRect(QRectF(QPointF(closePixel, keyPixel-keyWidthPixels), QPointF(openPixel, keyPixel+keyWidthPixels))); + double pixelWidth = getPixelWidth(it->key, keyPixel); + painter->drawRect(QRectF(QPointF(closePixel, keyPixel-pixelWidth), QPointF(openPixel, keyPixel+pixelWidth))); } } } /*! \internal - + + This function is used to determine the width of the bar at coordinate \a key, according to the + specified width (\ref setWidth) and width type (\ref setWidthType). Provide the pixel position of + \a key in \a keyPixel (because usually this was already calculated via \ref QCPAxis::coordToPixel + when this function is called). + + It returns the number of pixels the bar extends to higher keys, relative to the \a key + coordinate. So with a non-reversed horizontal axis, the return value is positive. With a reversed + horizontal axis, the return value is negative. This is important so the open/close flags on the + \ref csOhlc bar are drawn to the correct side. +*/ +double QCPFinancial::getPixelWidth(double key, double keyPixel) const +{ + double result = 0; + switch (mWidthType) + { + case wtAbsolute: + { + if (mKeyAxis) + result = mWidth*0.5*mKeyAxis.data()->pixelOrientation(); + break; + } + case wtAxisRectRatio: + { + if (mKeyAxis && mKeyAxis.data()->axisRect()) + { + if (mKeyAxis.data()->orientation() == Qt::Horizontal) + result = mKeyAxis.data()->axisRect()->width()*mWidth*0.5*mKeyAxis.data()->pixelOrientation(); + else + result = mKeyAxis.data()->axisRect()->height()*mWidth*0.5*mKeyAxis.data()->pixelOrientation(); + } else + qDebug() << Q_FUNC_INFO << "No key axis or axis rect defined"; + break; + } + case wtPlotCoords: + { + if (mKeyAxis) + result = mKeyAxis.data()->coordToPixel(key+mWidth*0.5)-keyPixel; + else + qDebug() << Q_FUNC_INFO << "No key axis defined"; + break; + } + } + return result; +} + +/*! \internal + This method is a helper function for \ref selectTest. It is used to test for selection when the chart style is \ref csOhlc. It only tests against the data points between \a begin and \a end. + + Like \ref selectTest, this method returns the shortest distance of \a pos to the graphical + representation of the plottable, and \a closestDataPoint will point to the respective data point. */ -double QCPFinancial::ohlcSelectTest(const QPointF &pos, const QCPFinancialDataMap::const_iterator &begin, const QCPFinancialDataMap::const_iterator &end) const +double QCPFinancial::ohlcSelectTest(const QPointF &pos, const QCPFinancialDataContainer::const_iterator &begin, const QCPFinancialDataContainer::const_iterator &end, QCPFinancialDataContainer::const_iterator &closestDataPoint) const { + closestDataPoint = mDataContainer->constEnd(); QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; } double minDistSqr = std::numeric_limits::max(); - QCPFinancialDataMap::const_iterator it; if (keyAxis->orientation() == Qt::Horizontal) { - for (it = begin; it != end; ++it) + for (QCPFinancialDataContainer::const_iterator it=begin; it!=end; ++it) { - double keyPixel = keyAxis->coordToPixel(it.value().key); + double keyPixel = keyAxis->coordToPixel(it->key); // calculate distance to backbone: - double currentDistSqr = distSqrToLine(QPointF(keyPixel, valueAxis->coordToPixel(it.value().high)), QPointF(keyPixel, valueAxis->coordToPixel(it.value().low)), pos); + double currentDistSqr = QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(keyPixel, valueAxis->coordToPixel(it->high)), QCPVector2D(keyPixel, valueAxis->coordToPixel(it->low))); if (currentDistSqr < minDistSqr) + { minDistSqr = currentDistSqr; + closestDataPoint = it; + } } } else // keyAxis->orientation() == Qt::Vertical { - for (it = begin; it != end; ++it) + for (QCPFinancialDataContainer::const_iterator it=begin; it!=end; ++it) { - double keyPixel = keyAxis->coordToPixel(it.value().key); + double keyPixel = keyAxis->coordToPixel(it->key); // calculate distance to backbone: - double currentDistSqr = distSqrToLine(QPointF(valueAxis->coordToPixel(it.value().high), keyPixel), QPointF(valueAxis->coordToPixel(it.value().low), keyPixel), pos); + double currentDistSqr = QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(valueAxis->coordToPixel(it->high), keyPixel), QCPVector2D(valueAxis->coordToPixel(it->low), keyPixel)); if (currentDistSqr < minDistSqr) + { minDistSqr = currentDistSqr; + closestDataPoint = it; + } } } return qSqrt(minDistSqr); @@ -21343,23 +26528,26 @@ double QCPFinancial::ohlcSelectTest(const QPointF &pos, const QCPFinancialDataMa This method is a helper function for \ref selectTest. It is used to test for selection when the chart style is \ref csCandlestick. It only tests against the data points between \a begin and \a end. + + Like \ref selectTest, this method returns the shortest distance of \a pos to the graphical + representation of the plottable, and \a closestDataPoint will point to the respective data point. */ -double QCPFinancial::candlestickSelectTest(const QPointF &pos, const QCPFinancialDataMap::const_iterator &begin, const QCPFinancialDataMap::const_iterator &end) const +double QCPFinancial::candlestickSelectTest(const QPointF &pos, const QCPFinancialDataContainer::const_iterator &begin, const QCPFinancialDataContainer::const_iterator &end, QCPFinancialDataContainer::const_iterator &closestDataPoint) const { + closestDataPoint = mDataContainer->constEnd(); QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; } double minDistSqr = std::numeric_limits::max(); - QCPFinancialDataMap::const_iterator it; if (keyAxis->orientation() == Qt::Horizontal) { - for (it = begin; it != end; ++it) + for (QCPFinancialDataContainer::const_iterator it=begin; it!=end; ++it) { double currentDistSqr; // determine whether pos is in open-close-box: - QCPRange boxKeyRange(it.value().key-mWidth*0.5, it.value().key+mWidth*0.5); - QCPRange boxValueRange(it.value().close, it.value().open); + QCPRange boxKeyRange(it->key-mWidth*0.5, it->key+mWidth*0.5); + QCPRange boxValueRange(it->close, it->open); double posKey, posValue; pixelsToCoords(pos, posKey, posValue); if (boxKeyRange.contains(posKey) && boxValueRange.contains(posValue)) // is in open-close-box @@ -21368,22 +26556,25 @@ double QCPFinancial::candlestickSelectTest(const QPointF &pos, const QCPFinancia } else { // calculate distance to high/low lines: - double keyPixel = keyAxis->coordToPixel(it.value().key); - double highLineDistSqr = distSqrToLine(QPointF(keyPixel, valueAxis->coordToPixel(it.value().high)), QPointF(keyPixel, valueAxis->coordToPixel(qMax(it.value().open, it.value().close))), pos); - double lowLineDistSqr = distSqrToLine(QPointF(keyPixel, valueAxis->coordToPixel(it.value().low)), QPointF(keyPixel, valueAxis->coordToPixel(qMin(it.value().open, it.value().close))), pos); + double keyPixel = keyAxis->coordToPixel(it->key); + double highLineDistSqr = QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(keyPixel, valueAxis->coordToPixel(it->high)), QCPVector2D(keyPixel, valueAxis->coordToPixel(qMax(it->open, it->close)))); + double lowLineDistSqr = QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(keyPixel, valueAxis->coordToPixel(it->low)), QCPVector2D(keyPixel, valueAxis->coordToPixel(qMin(it->open, it->close)))); currentDistSqr = qMin(highLineDistSqr, lowLineDistSqr); } if (currentDistSqr < minDistSqr) + { minDistSqr = currentDistSqr; + closestDataPoint = it; + } } } else // keyAxis->orientation() == Qt::Vertical { - for (it = begin; it != end; ++it) + for (QCPFinancialDataContainer::const_iterator it=begin; it!=end; ++it) { double currentDistSqr; // determine whether pos is in open-close-box: - QCPRange boxKeyRange(it.value().key-mWidth*0.5, it.value().key+mWidth*0.5); - QCPRange boxValueRange(it.value().close, it.value().open); + QCPRange boxKeyRange(it->key-mWidth*0.5, it->key+mWidth*0.5); + QCPRange boxValueRange(it->close, it->open); double posKey, posValue; pixelsToCoords(pos, posKey, posValue); if (boxKeyRange.contains(posKey) && boxValueRange.contains(posValue)) // is in open-close-box @@ -21392,54 +26583,1029 @@ double QCPFinancial::candlestickSelectTest(const QPointF &pos, const QCPFinancia } else { // calculate distance to high/low lines: - double keyPixel = keyAxis->coordToPixel(it.value().key); - double highLineDistSqr = distSqrToLine(QPointF(valueAxis->coordToPixel(it.value().high), keyPixel), QPointF(valueAxis->coordToPixel(qMax(it.value().open, it.value().close)), keyPixel), pos); - double lowLineDistSqr = distSqrToLine(QPointF(valueAxis->coordToPixel(it.value().low), keyPixel), QPointF(valueAxis->coordToPixel(qMin(it.value().open, it.value().close)), keyPixel), pos); + double keyPixel = keyAxis->coordToPixel(it->key); + double highLineDistSqr = QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(valueAxis->coordToPixel(it->high), keyPixel), QCPVector2D(valueAxis->coordToPixel(qMax(it->open, it->close)), keyPixel)); + double lowLineDistSqr = QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(valueAxis->coordToPixel(it->low), keyPixel), QCPVector2D(valueAxis->coordToPixel(qMin(it->open, it->close)), keyPixel)); currentDistSqr = qMin(highLineDistSqr, lowLineDistSqr); } if (currentDistSqr < minDistSqr) + { minDistSqr = currentDistSqr; + closestDataPoint = it; + } } } return qSqrt(minDistSqr); } -/*! \internal +/*! \internal called by the drawing methods 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 + \a begin 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. + begin 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. + \a end returns the iterator just above the highest data point that needs to be taken into + account. Same as before, \a end may also lie just outside of the visible range - if the plottable contains no data, both \a lower and \a upper point to constEnd. - - \see QCPGraph::getVisibleDataBounds + if the plottable contains no data, both \a begin and \a end point to \c constEnd. */ -void QCPFinancial::getVisibleDataBounds(QCPFinancialDataMap::const_iterator &lower, QCPFinancialDataMap::const_iterator &upper) const +void QCPFinancial::getVisibleDataBounds(QCPFinancialDataContainer::const_iterator &begin, QCPFinancialDataContainer::const_iterator &end) const { - if (!mKeyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; } - if (mData->isEmpty()) + if (!mKeyAxis) { - lower = mData->constEnd(); - upper = mData->constEnd(); + qDebug() << Q_FUNC_INFO << "invalid key axis"; + begin = mDataContainer->constEnd(); + end = mDataContainer->constEnd(); + return; + } + begin = mDataContainer->findBegin(mKeyAxis.data()->range().lower-mWidth*0.5); // subtract half width of ohlc/candlestick to include partially visible data points + end = mDataContainer->findEnd(mKeyAxis.data()->range().upper+mWidth*0.5); // add half width of ohlc/candlestick to include partially visible data points +} + +/*! \internal + + Returns the hit box in pixel coordinates that will be used for data selection with the selection + rect (\ref selectTestRect), of the data point given by \a it. +*/ +QRectF QCPFinancial::selectionHitBox(QCPFinancialDataContainer::const_iterator it) const +{ + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QRectF(); } + + double keyPixel = keyAxis->coordToPixel(it->key); + double highPixel = valueAxis->coordToPixel(it->high); + double lowPixel = valueAxis->coordToPixel(it->low); + double keyWidthPixels = keyPixel-keyAxis->coordToPixel(it->key-mWidth*0.5); + if (keyAxis->orientation() == Qt::Horizontal) + return QRectF(keyPixel-keyWidthPixels, highPixel, keyWidthPixels*2, lowPixel-highPixel).normalized(); + else + return QRectF(highPixel, keyPixel-keyWidthPixels, lowPixel-highPixel, keyWidthPixels*2).normalized(); +} +/* end of 'src/plottables/plottable-financial.cpp' */ + + +/* including file 'src/plottables/plottable-errorbar.cpp', size 37210 */ +/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */ + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPErrorBarsData +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPErrorBarsData + \brief Holds the data of one single error bar for QCPErrorBars. + + The stored data is: + \li \a errorMinus: how much the error bar extends towards negative coordinates from the data + point position + \li \a errorPlus: how much the error bar extends towards positive coordinates from the data point + position + + The container for storing the error bar information is \ref QCPErrorBarsDataContainer. It is a + typedef for QVector<\ref QCPErrorBarsData>. + + \see QCPErrorBarsDataContainer +*/ + +/*! + Constructs an error bar with errors set to zero. +*/ +QCPErrorBarsData::QCPErrorBarsData() : + errorMinus(0), + errorPlus(0) +{ +} + +/*! + Constructs an error bar with equal \a error in both negative and positive direction. +*/ +QCPErrorBarsData::QCPErrorBarsData(double error) : + errorMinus(error), + errorPlus(error) +{ +} + +/*! + Constructs an error bar with negative and positive errors set to \a errorMinus and \a errorPlus, + respectively. +*/ +QCPErrorBarsData::QCPErrorBarsData(double errorMinus, double errorPlus) : + errorMinus(errorMinus), + errorPlus(errorPlus) +{ +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPErrorBars +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPErrorBars + \brief A plottable that adds a set of error bars to other plottables. + + \image html QCPErrorBars.png + + The \ref QCPErrorBars plottable can be attached to other one-dimensional plottables (e.g. \ref + QCPGraph, \ref QCPCurve, \ref QCPBars, etc.) and equips them with error bars. + + Use \ref setDataPlottable to define for which plottable the \ref QCPErrorBars shall display the + error bars. The orientation of the error bars can be controlled with \ref setErrorType. + + By using \ref setData, you can supply the actual error data, either as symmetric error or + plus/minus asymmetric errors. \ref QCPErrorBars only stores the error data. The absolute + key/value position of each error bar will be adopted from the configured data plottable. The + error data of the \ref QCPErrorBars are associated one-to-one via their index to the data points + of the data plottable. You can directly access and manipulate the error bar data via \ref data. + + Set either of the plus/minus errors to NaN (qQNaN() or + std::numeric_limits::quiet_NaN()) to not show the respective error bar on the data point at + that index. + + \section qcperrorbars-appearance Changing the appearance + + The appearance of the error bars is defined by the pen (\ref setPen), and the width of the + whiskers (\ref setWhiskerWidth). Further, the error bar backbones may leave a gap around the data + point center to prevent that error bars are drawn too close to or even through scatter points. + This gap size can be controlled via \ref setSymbolGap. +*/ + +/* start of documentation of inline functions */ + +/*! \fn QSharedPointer QCPErrorBars::data() const + + Returns a shared pointer to the internal data storage of type \ref QCPErrorBarsDataContainer. You + may use it to directly manipulate the error values, which may be more convenient and faster than + using the regular \ref setData methods. +*/ + +/* end of documentation of inline functions */ + +/*! + Constructs an error bars plottable 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. + + It is also important that the \a keyAxis and \a valueAxis are the same for the error bars + plottable and the data plottable that the error bars shall be drawn on (\ref setDataPlottable). + + The created \ref QCPErrorBars is automatically registered with the QCustomPlot instance inferred + from \a keyAxis. This QCustomPlot instance takes ownership of the \ref QCPErrorBars, so do not + delete it manually but use \ref QCustomPlot::removePlottable() instead. +*/ +QCPErrorBars::QCPErrorBars(QCPAxis *keyAxis, QCPAxis *valueAxis) : + QCPAbstractPlottable(keyAxis, valueAxis), + mDataContainer(new QVector), + mErrorType(etValueError), + mWhiskerWidth(9), + mSymbolGap(10) +{ + setPen(QPen(Qt::black, 0)); + setBrush(Qt::NoBrush); +} + +QCPErrorBars::~QCPErrorBars() +{ +} + +/*! \overload + + Replaces the current data container with the provided \a data container. + + Since a QSharedPointer is used, multiple \ref QCPErrorBars instances may share the same data + container safely. Modifying the data in the container will then affect all \ref QCPErrorBars + instances 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 qcperrorbars-datasharing-1 + + If you do not wish to share containers, but create a copy from an existing container, assign the + data containers directly: + \snippet documentation/doc-code-snippets/mainwindow.cpp qcperrorbars-datasharing-2 + (This uses different notation compared with other plottables, because the \ref QCPErrorBars + uses a \c QVector as its data container, instead of a \ref QCPDataContainer.) + + \see addData +*/ +void QCPErrorBars::setData(QSharedPointer data) +{ + mDataContainer = data; +} + +/*! \overload + + Sets symmetrical error values as specified in \a error. The errors will be associated one-to-one + by the data point index to the associated data plottable (\ref setDataPlottable). + + You can directly access and manipulate the error bar data via \ref data. + + \see addData +*/ +void QCPErrorBars::setData(const QVector &error) +{ + mDataContainer->clear(); + addData(error); +} + +/*! \overload + + Sets asymmetrical errors as specified in \a errorMinus and \a errorPlus. The errors will be + associated one-to-one by the data point index to the associated data plottable (\ref + setDataPlottable). + + You can directly access and manipulate the error bar data via \ref data. + + \see addData +*/ +void QCPErrorBars::setData(const QVector &errorMinus, const QVector &errorPlus) +{ + mDataContainer->clear(); + addData(errorMinus, errorPlus); +} + +/*! + Sets the data plottable to which the error bars will be applied. The error values specified e.g. + via \ref setData will be associated one-to-one by the data point index to the data points of \a + plottable. This means that the error bars will adopt the key/value coordinates of the data point + with the same index. + + The passed \a plottable must be a one-dimensional plottable, i.e. it must implement the \ref + QCPPlottableInterface1D. Further, it must not be a \ref QCPErrorBars instance itself. If either + of these restrictions is violated, a corresponding qDebug output is generated, and the data + plottable of this \ref QCPErrorBars instance is set to zero. + + For proper display, care must also be taken that the key and value axes of the \a plottable match + those configured for this \ref QCPErrorBars instance. +*/ +void QCPErrorBars::setDataPlottable(QCPAbstractPlottable *plottable) +{ + if (plottable && qobject_cast(plottable)) + { + mDataPlottable = 0; + qDebug() << Q_FUNC_INFO << "can't set another QCPErrorBars instance as data plottable"; + return; + } + if (plottable && !plottable->interface1D()) + { + mDataPlottable = 0; + qDebug() << Q_FUNC_INFO << "passed plottable doesn't implement 1d interface, can't associate with QCPErrorBars"; return; } - // get visible data range as QMap iterators - QCPFinancialDataMap::const_iterator lbound = mData->lowerBound(mKeyAxis.data()->range().lower); - QCPFinancialDataMap::const_iterator ubound = 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 + mDataPlottable = plottable; } +/*! + Sets in which orientation the error bars shall appear on the data points. If your data needs both + error dimensions, create two \ref QCPErrorBars with different \a type. +*/ +void QCPErrorBars::setErrorType(ErrorType type) +{ + mErrorType = type; +} + +/*! + Sets the width of the whiskers (the short bars at the end of the actual error bar backbones) to + \a pixels. +*/ +void QCPErrorBars::setWhiskerWidth(double pixels) +{ + mWhiskerWidth = pixels; +} + +/*! + Sets the gap diameter around the data points that will be left out when drawing the error bar + backbones. This gap prevents that error bars are drawn too close to or even through scatter + points. +*/ +void QCPErrorBars::setSymbolGap(double pixels) +{ + mSymbolGap = pixels; +} + +/*! \overload + + Adds symmetrical error values as specified in \a error. The errors will be associated one-to-one + by the data point index to the associated data plottable (\ref setDataPlottable). + + You can directly access and manipulate the error bar data via \ref data. + + \see setData +*/ +void QCPErrorBars::addData(const QVector &error) +{ + addData(error, error); +} + +/*! \overload + + Adds asymmetrical errors as specified in \a errorMinus and \a errorPlus. The errors will be + associated one-to-one by the data point index to the associated data plottable (\ref + setDataPlottable). + + You can directly access and manipulate the error bar data via \ref data. + + \see setData +*/ +void QCPErrorBars::addData(const QVector &errorMinus, const QVector &errorPlus) +{ + if (errorMinus.size() != errorPlus.size()) + qDebug() << Q_FUNC_INFO << "minus and plus error vectors have different sizes:" << errorMinus.size() << errorPlus.size(); + const int n = qMin(errorMinus.size(), errorPlus.size()); + mDataContainer->reserve(n); + for (int i=0; iappend(QCPErrorBarsData(errorMinus.at(i), errorPlus.at(i))); +} + +/*! \overload + + Adds a single symmetrical error bar as specified in \a error. The errors will be associated + one-to-one by the data point index to the associated data plottable (\ref setDataPlottable). + + You can directly access and manipulate the error bar data via \ref data. + + \see setData +*/ +void QCPErrorBars::addData(double error) +{ + mDataContainer->append(QCPErrorBarsData(error)); +} + +/*! \overload + + Adds a single asymmetrical error bar as specified in \a errorMinus and \a errorPlus. The errors + will be associated one-to-one by the data point index to the associated data plottable (\ref + setDataPlottable). + + You can directly access and manipulate the error bar data via \ref data. + + \see setData +*/ +void QCPErrorBars::addData(double errorMinus, double errorPlus) +{ + mDataContainer->append(QCPErrorBarsData(errorMinus, errorPlus)); +} + +/* inherits documentation from base class */ +int QCPErrorBars::dataCount() const +{ + return mDataContainer->size(); +} + +/* inherits documentation from base class */ +double QCPErrorBars::dataMainKey(int index) const +{ + if (mDataPlottable) + return mDataPlottable->interface1D()->dataMainKey(index); + else + qDebug() << Q_FUNC_INFO << "no data plottable set"; + return 0; +} + +/* inherits documentation from base class */ +double QCPErrorBars::dataSortKey(int index) const +{ + if (mDataPlottable) + return mDataPlottable->interface1D()->dataSortKey(index); + else + qDebug() << Q_FUNC_INFO << "no data plottable set"; + return 0; +} + +/* inherits documentation from base class */ +double QCPErrorBars::dataMainValue(int index) const +{ + if (mDataPlottable) + return mDataPlottable->interface1D()->dataMainValue(index); + else + qDebug() << Q_FUNC_INFO << "no data plottable set"; + return 0; +} + +/* inherits documentation from base class */ +QCPRange QCPErrorBars::dataValueRange(int index) const +{ + if (mDataPlottable) + { + const double value = mDataPlottable->interface1D()->dataMainValue(index); + if (index >= 0 && index < mDataContainer->size() && mErrorType == etValueError) + return QCPRange(value-mDataContainer->at(index).errorMinus, value+mDataContainer->at(index).errorPlus); + else + return QCPRange(value, value); + } else + { + qDebug() << Q_FUNC_INFO << "no data plottable set"; + return QCPRange(); + } +} + +/* inherits documentation from base class */ +QPointF QCPErrorBars::dataPixelPosition(int index) const +{ + if (mDataPlottable) + return mDataPlottable->interface1D()->dataPixelPosition(index); + else + qDebug() << Q_FUNC_INFO << "no data plottable set"; + return QPointF(); +} + +/* inherits documentation from base class */ +bool QCPErrorBars::sortKeyIsMainKey() const +{ + if (mDataPlottable) + { + return mDataPlottable->interface1D()->sortKeyIsMainKey(); + } else + { + qDebug() << Q_FUNC_INFO << "no data plottable set"; + return true; + } +} + +/*! + \copydoc QCPPlottableInterface1D::selectTestRect +*/ +QCPDataSelection QCPErrorBars::selectTestRect(const QRectF &rect, bool onlySelectable) const +{ + QCPDataSelection result; + if (!mDataPlottable) + return result; + if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty()) + return result; + if (!mKeyAxis || !mValueAxis) + return result; + + QCPErrorBarsDataContainer::const_iterator visibleBegin, visibleEnd; + getVisibleDataBounds(visibleBegin, visibleEnd, QCPDataRange(0, dataCount())); + + QVector backbones, whiskers; + for (QCPErrorBarsDataContainer::const_iterator it=visibleBegin; it!=visibleEnd; ++it) + { + backbones.clear(); + whiskers.clear(); + getErrorBarLines(it, backbones, whiskers); + for (int i=0; iconstBegin(), it-mDataContainer->constBegin()+1), false); + break; + } + } + } + result.simplify(); + return result; +} + +/* inherits documentation from base class */ +int QCPErrorBars::findBegin(double sortKey, bool expandedRange) const +{ + if (mDataPlottable) + { + if (mDataContainer->isEmpty()) + return 0; + int beginIndex = mDataPlottable->interface1D()->findBegin(sortKey, expandedRange); + if (beginIndex >= mDataContainer->size()) + beginIndex = mDataContainer->size()-1; + return beginIndex; + } else + qDebug() << Q_FUNC_INFO << "no data plottable set"; + return 0; +} + +/* inherits documentation from base class */ +int QCPErrorBars::findEnd(double sortKey, bool expandedRange) const +{ + if (mDataPlottable) + { + if (mDataContainer->isEmpty()) + return 0; + int endIndex = mDataPlottable->interface1D()->findEnd(sortKey, expandedRange); + if (endIndex > mDataContainer->size()) + endIndex = mDataContainer->size(); + return endIndex; + } else + qDebug() << Q_FUNC_INFO << "no data plottable set"; + return 0; +} + +/* inherits documentation from base class */ +double QCPErrorBars::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const +{ + if (!mDataPlottable) return -1; + + if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty()) + return -1; + if (!mKeyAxis || !mValueAxis) + return -1; + + if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint())) + { + QCPErrorBarsDataContainer::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 */ +void QCPErrorBars::draw(QCPPainter *painter) +{ + if (!mDataPlottable) return; + if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } + if (mKeyAxis.data()->range().size() <= 0 || mDataContainer->isEmpty()) return; + + // if the sort key isn't the main key, we must check the visibility for each data point/error bar individually + // (getVisibleDataBounds applies range restriction, but otherwise can only return full data range): + bool checkPointVisibility = !mDataPlottable->interface1D()->sortKeyIsMainKey(); + + // check data validity if flag set: +#ifdef QCUSTOMPLOT_CHECK_DATA + QCPErrorBarsDataContainer::const_iterator it; + for (it = mDataContainer->constBegin(); it != mDataContainer->constEnd(); ++it) + { + if (QCP::isInvalidData(it->errorMinus, it->errorPlus)) + qDebug() << Q_FUNC_INFO << "Data point at index" << it-mDataContainer->constBegin() << "invalid." << "Plottable name:" << name(); + } +#endif + + applyDefaultAntialiasingHint(painter); + painter->setBrush(Qt::NoBrush); + // loop over and draw segments of unselected/selected data: + QList selectedSegments, unselectedSegments, allSegments; + getDataSegments(selectedSegments, unselectedSegments); + allSegments << unselectedSegments << selectedSegments; + QVector backbones, whiskers; + for (int i=0; i= unselectedSegments.size(); + if (isSelectedSegment && mSelectionDecorator) + mSelectionDecorator->applyPen(painter); + else + painter->setPen(mPen); + if (painter->pen().capStyle() == Qt::SquareCap) + { + QPen capFixPen(painter->pen()); + capFixPen.setCapStyle(Qt::FlatCap); + painter->setPen(capFixPen); + } + backbones.clear(); + whiskers.clear(); + for (QCPErrorBarsDataContainer::const_iterator it=begin; it!=end; ++it) + { + if (!checkPointVisibility || errorBarVisible(it-mDataContainer->constBegin())) + getErrorBarLines(it, backbones, whiskers); + } + painter->drawLines(backbones); + painter->drawLines(whiskers); + } + + // draw other selection decoration that isn't just line/scatter pens and brushes: + if (mSelectionDecorator) + mSelectionDecorator->drawDecoration(painter, selection()); +} + +/* inherits documentation from base class */ +void QCPErrorBars::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const +{ + applyDefaultAntialiasingHint(painter); + painter->setPen(mPen); + if (mErrorType == etValueError && mValueAxis && mValueAxis->orientation() == Qt::Vertical) + { + painter->drawLine(QLineF(rect.center().x(), rect.top()+2, rect.center().x(), rect.bottom()-1)); + painter->drawLine(QLineF(rect.center().x()-4, rect.top()+2, rect.center().x()+4, rect.top()+2)); + painter->drawLine(QLineF(rect.center().x()-4, rect.bottom()-1, rect.center().x()+4, rect.bottom()-1)); + } else + { + painter->drawLine(QLineF(rect.left()+2, rect.center().y(), rect.right()-2, rect.center().y())); + painter->drawLine(QLineF(rect.left()+2, rect.center().y()-4, rect.left()+2, rect.center().y()+4)); + painter->drawLine(QLineF(rect.right()-2, rect.center().y()-4, rect.right()-2, rect.center().y()+4)); + } +} + +/* inherits documentation from base class */ +QCPRange QCPErrorBars::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const +{ + if (!mDataPlottable) + { + foundRange = false; + return QCPRange(); + } + + QCPRange range; + bool haveLower = false; + bool haveUpper = false; + QCPErrorBarsDataContainer::const_iterator it; + for (it = mDataContainer->constBegin(); it != mDataContainer->constEnd(); ++it) + { + if (mErrorType == etValueError) + { + // error bar doesn't extend in key dimension (except whisker but we ignore that here), so only use data point center + const double current = mDataPlottable->interface1D()->dataMainKey(it-mDataContainer->constBegin()); + if (qIsNaN(current)) continue; + if (inSignDomain == QCP::sdBoth || (inSignDomain == QCP::sdNegative && current < 0) || (inSignDomain == QCP::sdPositive && current > 0)) + { + if (current < range.lower || !haveLower) + { + range.lower = current; + haveLower = true; + } + if (current > range.upper || !haveUpper) + { + range.upper = current; + haveUpper = true; + } + } + } else // mErrorType == etKeyError + { + const double dataKey = mDataPlottable->interface1D()->dataMainKey(it-mDataContainer->constBegin()); + if (qIsNaN(dataKey)) continue; + // plus error: + double current = dataKey + (qIsNaN(it->errorPlus) ? 0 : it->errorPlus); + if (inSignDomain == QCP::sdBoth || (inSignDomain == QCP::sdNegative && current < 0) || (inSignDomain == QCP::sdPositive && current > 0)) + { + if (current > range.upper || !haveUpper) + { + range.upper = current; + haveUpper = true; + } + } + // minus error: + current = dataKey - (qIsNaN(it->errorMinus) ? 0 : it->errorMinus); + if (inSignDomain == QCP::sdBoth || (inSignDomain == QCP::sdNegative && current < 0) || (inSignDomain == QCP::sdPositive && current > 0)) + { + if (current < range.lower || !haveLower) + { + range.lower = current; + haveLower = true; + } + } + } + } + + if (haveUpper && !haveLower) + { + range.lower = range.upper; + haveLower = true; + } else if (haveLower && !haveUpper) + { + range.upper = range.lower; + haveUpper = true; + } + + foundRange = haveLower && haveUpper; + return range; +} + +/* inherits documentation from base class */ +QCPRange QCPErrorBars::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const +{ + if (!mDataPlottable) + { + foundRange = false; + return QCPRange(); + } + + QCPRange range; + const bool restrictKeyRange = inKeyRange != QCPRange(); + bool haveLower = false; + bool haveUpper = false; + QCPErrorBarsDataContainer::const_iterator itBegin = mDataContainer->constBegin(); + QCPErrorBarsDataContainer::const_iterator itEnd = mDataContainer->constEnd(); + if (mDataPlottable->interface1D()->sortKeyIsMainKey() && restrictKeyRange) + { + itBegin = mDataContainer->constBegin()+findBegin(inKeyRange.lower); + itEnd = mDataContainer->constBegin()+findEnd(inKeyRange.upper); + } + for (QCPErrorBarsDataContainer::const_iterator it = itBegin; it != itEnd; ++it) + { + if (restrictKeyRange) + { + const double dataKey = mDataPlottable->interface1D()->dataMainKey(it-mDataContainer->constBegin()); + if (dataKey < inKeyRange.lower || dataKey > inKeyRange.upper) + continue; + } + if (mErrorType == etValueError) + { + const double dataValue = mDataPlottable->interface1D()->dataMainValue(it-mDataContainer->constBegin()); + if (qIsNaN(dataValue)) continue; + // plus error: + double current = dataValue + (qIsNaN(it->errorPlus) ? 0 : it->errorPlus); + if (inSignDomain == QCP::sdBoth || (inSignDomain == QCP::sdNegative && current < 0) || (inSignDomain == QCP::sdPositive && current > 0)) + { + if (current > range.upper || !haveUpper) + { + range.upper = current; + haveUpper = true; + } + } + // minus error: + current = dataValue - (qIsNaN(it->errorMinus) ? 0 : it->errorMinus); + if (inSignDomain == QCP::sdBoth || (inSignDomain == QCP::sdNegative && current < 0) || (inSignDomain == QCP::sdPositive && current > 0)) + { + if (current < range.lower || !haveLower) + { + range.lower = current; + haveLower = true; + } + } + } else // mErrorType == etKeyError + { + // error bar doesn't extend in value dimension (except whisker but we ignore that here), so only use data point center + const double current = mDataPlottable->interface1D()->dataMainValue(it-mDataContainer->constBegin()); + if (qIsNaN(current)) continue; + if (inSignDomain == QCP::sdBoth || (inSignDomain == QCP::sdNegative && current < 0) || (inSignDomain == QCP::sdPositive && current > 0)) + { + if (current < range.lower || !haveLower) + { + range.lower = current; + haveLower = true; + } + if (current > range.upper || !haveUpper) + { + range.upper = current; + haveUpper = true; + } + } + } + } + + if (haveUpper && !haveLower) + { + range.lower = range.upper; + haveLower = true; + } else if (haveLower && !haveUpper) + { + range.upper = range.lower; + haveUpper = true; + } + + foundRange = haveLower && haveUpper; + return range; +} + +/*! \internal + + Calculates the lines that make up the error bar belonging to the data point \a it. + + The resulting lines are added to \a backbones and \a whiskers. The vectors are not cleared, so + calling this method with different \a it but the same \a backbones and \a whiskers allows to + accumulate lines for multiple data points. + + This method assumes that \a it is a valid iterator within the bounds of this \ref QCPErrorBars + instance and within the bounds of the associated data plottable. +*/ +void QCPErrorBars::getErrorBarLines(QCPErrorBarsDataContainer::const_iterator it, QVector &backbones, QVector &whiskers) const +{ + if (!mDataPlottable) return; + + int index = it-mDataContainer->constBegin(); + QPointF centerPixel = mDataPlottable->interface1D()->dataPixelPosition(index); + if (qIsNaN(centerPixel.x()) || qIsNaN(centerPixel.y())) + return; + QCPAxis *errorAxis = mErrorType == etValueError ? mValueAxis : mKeyAxis; + QCPAxis *orthoAxis = mErrorType == etValueError ? mKeyAxis : mValueAxis; + const double centerErrorAxisPixel = errorAxis->orientation() == Qt::Horizontal ? centerPixel.x() : centerPixel.y(); + const double centerOrthoAxisPixel = orthoAxis->orientation() == Qt::Horizontal ? centerPixel.x() : centerPixel.y(); + const double centerErrorAxisCoord = errorAxis->pixelToCoord(centerErrorAxisPixel); // depending on plottable, this might be different from just mDataPlottable->interface1D()->dataMainKey/Value + const double symbolGap = mSymbolGap*0.5*errorAxis->pixelOrientation(); + // plus error: + double errorStart, errorEnd; + if (!qIsNaN(it->errorPlus)) + { + errorStart = centerErrorAxisPixel+symbolGap; + errorEnd = errorAxis->coordToPixel(centerErrorAxisCoord+it->errorPlus); + if (errorAxis->orientation() == Qt::Vertical) + { + if ((errorStart > errorEnd) != errorAxis->rangeReversed()) + backbones.append(QLineF(centerOrthoAxisPixel, errorStart, centerOrthoAxisPixel, errorEnd)); + whiskers.append(QLineF(centerOrthoAxisPixel-mWhiskerWidth*0.5, errorEnd, centerOrthoAxisPixel+mWhiskerWidth*0.5, errorEnd)); + } else + { + if ((errorStart < errorEnd) != errorAxis->rangeReversed()) + backbones.append(QLineF(errorStart, centerOrthoAxisPixel, errorEnd, centerOrthoAxisPixel)); + whiskers.append(QLineF(errorEnd, centerOrthoAxisPixel-mWhiskerWidth*0.5, errorEnd, centerOrthoAxisPixel+mWhiskerWidth*0.5)); + } + } + // minus error: + if (!qIsNaN(it->errorMinus)) + { + errorStart = centerErrorAxisPixel-symbolGap; + errorEnd = errorAxis->coordToPixel(centerErrorAxisCoord-it->errorMinus); + if (errorAxis->orientation() == Qt::Vertical) + { + if ((errorStart < errorEnd) != errorAxis->rangeReversed()) + backbones.append(QLineF(centerOrthoAxisPixel, errorStart, centerOrthoAxisPixel, errorEnd)); + whiskers.append(QLineF(centerOrthoAxisPixel-mWhiskerWidth*0.5, errorEnd, centerOrthoAxisPixel+mWhiskerWidth*0.5, errorEnd)); + } else + { + if ((errorStart > errorEnd) != errorAxis->rangeReversed()) + backbones.append(QLineF(errorStart, centerOrthoAxisPixel, errorEnd, centerOrthoAxisPixel)); + whiskers.append(QLineF(errorEnd, centerOrthoAxisPixel-mWhiskerWidth*0.5, errorEnd, centerOrthoAxisPixel+mWhiskerWidth*0.5)); + } + } +} + +/*! \internal + + This method outputs the currently visible data range via \a begin and \a end. The returned range + will also never exceed \a rangeRestriction. + + Since error bars with type \ref etKeyError may extend to arbitrarily positive and negative key + coordinates relative to their data point key, this method checks all outer error bars whether + they truly don't reach into the visible portion of the axis rect, by calling \ref + errorBarVisible. On the other hand error bars with type \ref etValueError that are associated + with data plottables whose sort key is equal to the main key (see \ref qcpdatacontainer-datatype + "QCPDataContainer DataType") can be handled very efficiently by finding the visible range of + error bars through binary search (\ref QCPPlottableInterface1D::findBegin and \ref + QCPPlottableInterface1D::findEnd). + + If the plottable's sort key is not equal to the main key, this method returns the full data + range, only restricted by \a rangeRestriction. Drawing optimization then has to be done on a + point-by-point basis in the \ref draw method. +*/ +void QCPErrorBars::getVisibleDataBounds(QCPErrorBarsDataContainer::const_iterator &begin, QCPErrorBarsDataContainer::const_iterator &end, const QCPDataRange &rangeRestriction) const +{ + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) + { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + end = mDataContainer->constEnd(); + begin = end; + return; + } + if (!mDataPlottable || rangeRestriction.isEmpty()) + { + end = mDataContainer->constEnd(); + begin = end; + return; + } + if (!mDataPlottable->interface1D()->sortKeyIsMainKey()) + { + // if the sort key isn't the main key, it's not possible to find a contiguous range of visible + // data points, so this method then only applies the range restriction and otherwise returns + // the full data range. Visibility checks must be done on a per-datapoin-basis during drawing + QCPDataRange dataRange(0, mDataContainer->size()); + dataRange = dataRange.bounded(rangeRestriction); + begin = mDataContainer->constBegin()+dataRange.begin(); + end = mDataContainer->constBegin()+dataRange.end(); + return; + } + + // get visible data range via interface from data plottable, and then restrict to available error data points: + const int n = qMin(mDataContainer->size(), mDataPlottable->interface1D()->dataCount()); + int beginIndex = mDataPlottable->interface1D()->findBegin(keyAxis->range().lower); + int endIndex = mDataPlottable->interface1D()->findEnd(keyAxis->range().upper); + int i = beginIndex; + while (i > 0 && i < n && i > rangeRestriction.begin()) + { + if (errorBarVisible(i)) + beginIndex = i; + --i; + } + i = endIndex; + while (i >= 0 && i < n && i < rangeRestriction.end()) + { + if (errorBarVisible(i)) + endIndex = i+1; + ++i; + } + QCPDataRange dataRange(beginIndex, endIndex); + dataRange = dataRange.bounded(rangeRestriction.bounded(QCPDataRange(0, mDataContainer->size()))); + begin = mDataContainer->constBegin()+dataRange.begin(); + end = mDataContainer->constBegin()+dataRange.end(); +} + +/*! \internal + + Calculates the minimum distance in pixels the error bars' representation has from the given \a + pixelPoint. This is used to determine whether the error bar was clicked or not, e.g. in \ref + selectTest. The closest data point to \a pixelPoint is returned in \a closestData. +*/ +double QCPErrorBars::pointDistance(const QPointF &pixelPoint, QCPErrorBarsDataContainer::const_iterator &closestData) const +{ + closestData = mDataContainer->constEnd(); + if (!mDataPlottable || mDataContainer->isEmpty()) + return -1.0; + + QCPErrorBarsDataContainer::const_iterator begin, end; + getVisibleDataBounds(begin, end, QCPDataRange(0, dataCount())); + + // calculate minimum distances to error backbones (whiskers are ignored for speed) and find closestData iterator: + double minDistSqr = std::numeric_limits::max(); + QVector backbones, whiskers; + for (QCPErrorBarsDataContainer::const_iterator it=begin; it!=end; ++it) + { + getErrorBarLines(it, backbones, whiskers); + for (int i=0; i &selectedSegments, QList &unselectedSegments) const +{ + selectedSegments.clear(); + unselectedSegments.clear(); + if (mSelectable == QCP::stWhole) // stWhole selection type draws the entire plottable with selected style if mSelection isn't empty + { + if (selected()) + selectedSegments << QCPDataRange(0, dataCount()); + else + unselectedSegments << QCPDataRange(0, dataCount()); + } else + { + QCPDataSelection sel(selection()); + sel.simplify(); + selectedSegments = sel.dataRanges(); + unselectedSegments = sel.inverse(QCPDataRange(0, dataCount())).dataRanges(); + } +} + +/*! \internal + + Returns whether the error bar at the specified \a index is visible within the current key axis + range. + + This method assumes for performance reasons without checking that the key axis, the value axis, + and the data plottable (\ref setDataPlottable) are not zero and that \a index is within valid + bounds of this \ref QCPErrorBars instance and the bounds of the data plottable. +*/ +bool QCPErrorBars::errorBarVisible(int index) const +{ + QPointF centerPixel = mDataPlottable->interface1D()->dataPixelPosition(index); + const double centerKeyPixel = mKeyAxis->orientation() == Qt::Horizontal ? centerPixel.x() : centerPixel.y(); + if (qIsNaN(centerKeyPixel)) + return false; + + double keyMin, keyMax; + if (mErrorType == etKeyError) + { + const double centerKey = mKeyAxis->pixelToCoord(centerKeyPixel); + const double errorPlus = mDataContainer->at(index).errorPlus; + const double errorMinus = mDataContainer->at(index).errorMinus; + keyMax = centerKey+(qIsNaN(errorPlus) ? 0 : errorPlus); + keyMin = centerKey-(qIsNaN(errorMinus) ? 0 : errorMinus); + } else // mErrorType == etValueError + { + keyMax = mKeyAxis->pixelToCoord(centerKeyPixel+mWhiskerWidth*0.5*mKeyAxis->pixelOrientation()); + keyMin = mKeyAxis->pixelToCoord(centerKeyPixel-mWhiskerWidth*0.5*mKeyAxis->pixelOrientation()); + } + return ((keyMax > mKeyAxis->range().lower) && (keyMin < mKeyAxis->range().upper)); +} + +/*! \internal + + Returns whether \a line intersects (or is contained in) \a pixelRect. + + \a line is assumed to be either perfectly horizontal or perfectly vertical, as is the case for + error bar lines. +*/ +bool QCPErrorBars::rectIntersectsLine(const QRectF &pixelRect, const QLineF &line) const +{ + if (pixelRect.left() > line.x1() && pixelRect.left() > line.x2()) + return false; + else if (pixelRect.right() < line.x1() && pixelRect.right() < line.x2()) + return false; + else if (pixelRect.top() > line.y1() && pixelRect.top() > line.y2()) + return false; + else if (pixelRect.bottom() < line.y1() && pixelRect.bottom() < line.y2()) + return false; + else + return true; +} +/* end of 'src/plottables/plottable-errorbar.cpp' */ + + +/* including file 'src/items/item-straightline.cpp', size 7592 */ +/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */ //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPItemStraightLine @@ -21456,7 +27622,8 @@ void QCPFinancial::getVisibleDataBounds(QCPFinancialDataMap::const_iterator &low /*! Creates a straight line item and sets default values. - The constructed item can be added to the plot with QCustomPlot::addItem. + The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes + ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead. */ QCPItemStraightLine::QCPItemStraightLine(QCustomPlot *parentPlot) : QCPAbstractItem(parentPlot), @@ -21501,14 +27668,14 @@ double QCPItemStraightLine::selectTest(const QPointF &pos, bool onlySelectable, if (onlySelectable && !mSelectable) return -1; - return distToStraightLine(QVector2D(point1->pixelPoint()), QVector2D(point2->pixelPoint()-point1->pixelPoint()), QVector2D(pos)); + return QCPVector2D(pos).distanceToStraightLine(point1->pixelPosition(), point2->pixelPosition()-point1->pixelPosition()); } /* inherits documentation from base class */ void QCPItemStraightLine::draw(QCPPainter *painter) { - QVector2D start(point1->pixelPoint()); - QVector2D end(point2->pixelPoint()); + QCPVector2D start(point1->pixelPosition()); + QCPVector2D end(point2->pixelPosition()); // get visible segment of straight line inside clipRect: double clipPad = mainPen().widthF(); QLineF line = getRectClippedStraightLine(start, end-start, clipRect().adjusted(-clipPad, -clipPad, clipPad, clipPad)); @@ -21520,18 +27687,6 @@ void QCPItemStraightLine::draw(QCPPainter *painter) } } -/*! \internal - - finds the shortest distance of \a point to the straight line defined by the base point \a - base and the direction vector \a vec. - - This is a helper function for \ref selectTest. -*/ -double QCPItemStraightLine::distToStraightLine(const QVector2D &base, const QVector2D &vec, const QVector2D &point) const -{ - return qAbs((base.y()-point.y())*vec.x()-(base.x()-point.x())*vec.y())/vec.length(); -} - /*! \internal Returns the section of the straight line defined by \a base and direction vector \a @@ -21539,7 +27694,7 @@ double QCPItemStraightLine::distToStraightLine(const QVector2D &base, const QVec This is a helper function for \ref draw. */ -QLineF QCPItemStraightLine::getRectClippedStraightLine(const QVector2D &base, const QVector2D &vec, const QRect &rect) const +QLineF QCPItemStraightLine::getRectClippedStraightLine(const QCPVector2D &base, const QCPVector2D &vec, const QRect &rect) const { double bx, by; double gamma; @@ -21564,31 +27719,31 @@ QLineF QCPItemStraightLine::getRectClippedStraightLine(const QVector2D &base, co result.setLine(rect.left(), by+gamma, rect.right(), by+gamma); // no need to check right because we know line is horizontal } else // line is skewed { - QList pointVectors; + QList pointVectors; // check top of rect: bx = rect.left(); by = rect.top(); gamma = base.x()-bx + (by-base.y())*vec.x()/vec.y(); if (gamma >= 0 && gamma <= rect.width()) - pointVectors.append(QVector2D(bx+gamma, by)); + pointVectors.append(QCPVector2D(bx+gamma, by)); // check bottom of rect: bx = rect.left(); by = rect.bottom(); gamma = base.x()-bx + (by-base.y())*vec.x()/vec.y(); if (gamma >= 0 && gamma <= rect.width()) - pointVectors.append(QVector2D(bx+gamma, by)); + pointVectors.append(QCPVector2D(bx+gamma, by)); // check left of rect: bx = rect.left(); by = rect.top(); gamma = base.y()-by + (bx-base.x())*vec.y()/vec.x(); if (gamma >= 0 && gamma <= rect.height()) - pointVectors.append(QVector2D(bx, by+gamma)); + pointVectors.append(QCPVector2D(bx, by+gamma)); // check right of rect: bx = rect.right(); by = rect.top(); gamma = base.y()-by + (bx-base.x())*vec.y()/vec.x(); if (gamma >= 0 && gamma <= rect.height()) - pointVectors.append(QVector2D(bx, by+gamma)); + pointVectors.append(QCPVector2D(bx, by+gamma)); // evaluate points: if (pointVectors.size() == 2) @@ -21598,7 +27753,7 @@ QLineF QCPItemStraightLine::getRectClippedStraightLine(const QVector2D &base, co { // line probably goes through corner of rect, and we got two points there. single out the point pair with greatest distance: double distSqrMax = 0; - QVector2D pv1, pv2; + QCPVector2D pv1, pv2; for (int i=0; ipixelPoint(), end->pixelPoint(), pos)); + return qSqrt(QCPVector2D(pos).distanceSquaredToLine(start->pixelPosition(), end->pixelPosition())); } /* inherits documentation from base class */ void QCPItemLine::draw(QCPPainter *painter) { - QVector2D startVec(start->pixelPoint()); - QVector2D endVec(end->pixelPoint()); - if (startVec.toPoint() == endVec.toPoint()) + QCPVector2D startVec(start->pixelPosition()); + QCPVector2D endVec(end->pixelPosition()); + if (qFuzzyIsNull((startVec-endVec).lengthSquared())) return; // get visible segment of straight line inside clipRect: double clipPad = qMax(mHead.boundingDistance(), mTail.boundingDistance()); @@ -21751,19 +27911,19 @@ void QCPItemLine::draw(QCPPainter *painter) This is a helper function for \ref draw. */ -QLineF QCPItemLine::getRectClippedLine(const QVector2D &start, const QVector2D &end, const QRect &rect) const +QLineF QCPItemLine::getRectClippedLine(const QCPVector2D &start, const QCPVector2D &end, const QRect &rect) const { bool containsStart = rect.contains(start.x(), start.y()); bool containsEnd = rect.contains(end.x(), end.y()); if (containsStart && containsEnd) return QLineF(start.toPointF(), end.toPointF()); - QVector2D base = start; - QVector2D vec = end-start; + QCPVector2D base = start; + QCPVector2D vec = end-start; double bx, by; double gamma, mu; QLineF result; - QList pointVectors; + QList pointVectors; if (!qFuzzyIsNull(vec.y())) // line is not horizontal { @@ -21775,7 +27935,7 @@ QLineF QCPItemLine::getRectClippedLine(const QVector2D &start, const QVector2D & { gamma = base.x()-bx + mu*vec.x(); if (gamma >= 0 && gamma <= rect.width()) - pointVectors.append(QVector2D(bx+gamma, by)); + pointVectors.append(QCPVector2D(bx+gamma, by)); } // check bottom of rect: bx = rect.left(); @@ -21785,7 +27945,7 @@ QLineF QCPItemLine::getRectClippedLine(const QVector2D &start, const QVector2D & { gamma = base.x()-bx + mu*vec.x(); if (gamma >= 0 && gamma <= rect.width()) - pointVectors.append(QVector2D(bx+gamma, by)); + pointVectors.append(QCPVector2D(bx+gamma, by)); } } if (!qFuzzyIsNull(vec.x())) // line is not vertical @@ -21798,7 +27958,7 @@ QLineF QCPItemLine::getRectClippedLine(const QVector2D &start, const QVector2D & { gamma = base.y()-by + mu*vec.y(); if (gamma >= 0 && gamma <= rect.height()) - pointVectors.append(QVector2D(bx, by+gamma)); + pointVectors.append(QCPVector2D(bx, by+gamma)); } // check right of rect: bx = rect.right(); @@ -21808,7 +27968,7 @@ QLineF QCPItemLine::getRectClippedLine(const QVector2D &start, const QVector2D & { gamma = base.y()-by + mu*vec.y(); if (gamma >= 0 && gamma <= rect.height()) - pointVectors.append(QVector2D(bx, by+gamma)); + pointVectors.append(QCPVector2D(bx, by+gamma)); } } @@ -21825,7 +27985,7 @@ QLineF QCPItemLine::getRectClippedLine(const QVector2D &start, const QVector2D & { // line probably goes through corner of rect, and we got two points there. single out the point pair with greatest distance: double distSqrMax = 0; - QVector2D pv1, pv2; + QCPVector2D pv1, pv2; for (int i=0; ipixelPoint()); - QPointF startDirVec(startDir->pixelPoint()); - QPointF endDirVec(endDir->pixelPoint()); - QPointF endVec(end->pixelPoint()); + QPointF startVec(start->pixelPosition()); + QPointF startDirVec(startDir->pixelPosition()); + QPointF endDirVec(endDir->pixelPosition()); + QPointF endVec(end->pixelPosition()); QPainterPath cubicPath(startVec); cubicPath.cubicTo(startDirVec, endDirVec, endVec); QPolygonF polygon = cubicPath.toSubpathPolygons().first(); + QCPVector2D p(pos); double minDistSqr = std::numeric_limits::max(); for (int i=1; ipixelPoint()); - QPointF startDirVec(startDir->pixelPoint()); - QPointF endDirVec(endDir->pixelPoint()); - QPointF endVec(end->pixelPoint()); - if (QVector2D(endVec-startVec).length() > 1e10f) // too large curves cause crash + QCPVector2D startVec(start->pixelPosition()); + QCPVector2D startDirVec(startDir->pixelPosition()); + QCPVector2D endDirVec(endDir->pixelPosition()); + QCPVector2D endVec(end->pixelPosition()); + if ((endVec-startVec).length() > 1e10) // too large curves cause crash return; - QPainterPath cubicPath(startVec); - cubicPath.cubicTo(startDirVec, endDirVec, endVec); + QPainterPath cubicPath(startVec.toPointF()); + cubicPath.cubicTo(startDirVec.toPointF(), endDirVec.toPointF(), endVec.toPointF()); // paint visible segment, if existent: QRect clip = clipRect().adjusted(-mainPen().widthF(), -mainPen().widthF(), mainPen().widthF(), mainPen().widthF()); @@ -21997,9 +28163,9 @@ void QCPItemCurve::draw(QCPPainter *painter) painter->drawPath(cubicPath); painter->setBrush(Qt::SolidPattern); if (mTail.style() != QCPLineEnding::esNone) - mTail.draw(painter, QVector2D(startVec), M_PI-cubicPath.angleAtPercent(0)/180.0*M_PI); + mTail.draw(painter, startVec, M_PI-cubicPath.angleAtPercent(0)/180.0*M_PI); if (mHead.style() != QCPLineEnding::esNone) - mHead.draw(painter, QVector2D(endVec), -cubicPath.angleAtPercent(1)/180.0*M_PI); + mHead.draw(painter, endVec, -cubicPath.angleAtPercent(1)/180.0*M_PI); } } @@ -22012,8 +28178,12 @@ QPen QCPItemCurve::mainPen() const { return mSelected ? mSelectedPen : mPen; } +/* end of 'src/items/item-curve.cpp' */ +/* including file 'src/items/item-rect.cpp', size 6479 */ +/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */ + //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPItemRect //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -22029,7 +28199,8 @@ QPen QCPItemCurve::mainPen() const /*! Creates a rectangle item and sets default values. - The constructed item can be added to the plot with QCustomPlot::addItem. + The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes + ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead. */ QCPItemRect::QCPItemRect(QCustomPlot *parentPlot) : QCPAbstractItem(parentPlot), @@ -22104,16 +28275,16 @@ double QCPItemRect::selectTest(const QPointF &pos, bool onlySelectable, QVariant if (onlySelectable && !mSelectable) return -1; - QRectF rect = QRectF(topLeft->pixelPoint(), bottomRight->pixelPoint()).normalized(); + QRectF rect = QRectF(topLeft->pixelPosition(), bottomRight->pixelPosition()).normalized(); bool filledRect = mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0; - return rectSelectTest(rect, pos, filledRect); + return rectDistance(rect, pos, filledRect); } /* inherits documentation from base class */ void QCPItemRect::draw(QCPPainter *painter) { - QPointF p1 = topLeft->pixelPoint(); - QPointF p2 = bottomRight->pixelPoint(); + QPointF p1 = topLeft->pixelPosition(); + QPointF p2 = bottomRight->pixelPosition(); if (p1.toPoint() == p2.toPoint()) return; QRectF rect = QRectF(p1, p2).normalized(); @@ -22128,9 +28299,9 @@ void QCPItemRect::draw(QCPPainter *painter) } /* inherits documentation from base class */ -QPointF QCPItemRect::anchorPixelPoint(int anchorId) const +QPointF QCPItemRect::anchorPixelPosition(int anchorId) const { - QRectF rect = QRectF(topLeft->pixelPoint(), bottomRight->pixelPoint()); + QRectF rect = QRectF(topLeft->pixelPosition(), bottomRight->pixelPosition()); switch (anchorId) { case aiTop: return (rect.topLeft()+rect.topRight())*0.5; @@ -22164,8 +28335,12 @@ QBrush QCPItemRect::mainBrush() const { return mSelected ? mSelectedBrush : mBrush; } +/* end of 'src/items/item-rect.cpp' */ +/* including file 'src/items/item-text.cpp', size 13338 */ +/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */ + //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPItemText //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -22187,7 +28362,8 @@ QBrush QCPItemRect::mainBrush() const /*! Creates a text item and sets default values. - The constructed item can be added to the plot with QCustomPlot::addItem. + The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes + ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead. */ QCPItemText::QCPItemText(QCustomPlot *parentPlot) : QCPAbstractItem(parentPlot), @@ -22199,15 +28375,14 @@ QCPItemText::QCPItemText(QCustomPlot *parentPlot) : bottomRight(createAnchor(QLatin1String("bottomRight"), aiBottomRight)), bottom(createAnchor(QLatin1String("bottom"), aiBottom)), bottomLeft(createAnchor(QLatin1String("bottomLeft"), aiBottomLeft)), - left(createAnchor(QLatin1String("left"), aiLeft)) + left(createAnchor(QLatin1String("left"), aiLeft)), + mText(QLatin1String("text")), + mPositionAlignment(Qt::AlignCenter), + mTextAlignment(Qt::AlignTop|Qt::AlignHCenter), + mRotation(0) { position->setCoords(0, 0); - setRotation(0); - setTextAlignment(Qt::AlignTop|Qt::AlignHCenter); - setPositionAlignment(Qt::AlignCenter); - setText(QLatin1String("text")); - setPen(Qt::NoPen); setSelectedPen(Qt::NoPen); setBrush(Qt::NoBrush); @@ -22362,8 +28537,8 @@ double QCPItemText::selectTest(const QPointF &pos, bool onlySelectable, QVariant return -1; // The rect may be rotated, so we transform the actual clicked pos to the rotated - // coordinate system, so we can use the normal rectSelectTest function for non-rotated rects: - QPointF positionPixels(position->pixelPoint()); + // coordinate system, so we can use the normal rectDistance function for non-rotated rects: + QPointF positionPixels(position->pixelPosition()); QTransform inputTransform; inputTransform.translate(positionPixels.x(), positionPixels.y()); inputTransform.rotate(-mRotation); @@ -22375,13 +28550,13 @@ double QCPItemText::selectTest(const QPointF &pos, bool onlySelectable, QVariant QPointF textPos = getTextDrawPoint(positionPixels, textBoxRect, mPositionAlignment); textBoxRect.moveTopLeft(textPos.toPoint()); - return rectSelectTest(textBoxRect, rotatedPos, true); + return rectDistance(textBoxRect, rotatedPos, true); } /* inherits documentation from base class */ void QCPItemText::draw(QCPPainter *painter) { - QPointF pos(position->pixelPoint()); + QPointF pos(position->pixelPosition()); QTransform transform = painter->transform(); transform.translate(pos.x(), pos.y()); if (!qFuzzyIsNull(mRotation)) @@ -22411,10 +28586,10 @@ void QCPItemText::draw(QCPPainter *painter) } /* inherits documentation from base class */ -QPointF QCPItemText::anchorPixelPoint(int anchorId) const +QPointF QCPItemText::anchorPixelPosition(int anchorId) const { // get actual rect points (pretty much copied from draw function): - QPointF pos(position->pixelPoint()); + QPointF pos(position->pixelPosition()); QTransform transform; transform.translate(pos.x(), pos.y()); if (!qFuzzyIsNull(mRotation)) @@ -22508,8 +28683,12 @@ QBrush QCPItemText::mainBrush() const { return mSelected ? mSelectedBrush : mBrush; } +/* end of 'src/items/item-text.cpp' */ +/* including file 'src/items/item-ellipse.cpp', size 7863 */ +/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */ + //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPItemEllipse //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -22525,7 +28704,8 @@ QBrush QCPItemText::mainBrush() const /*! Creates an ellipse item and sets default values. - The constructed item can be added to the plot with QCustomPlot::addItem. + The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes + ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead. */ QCPItemEllipse::QCPItemEllipse(QCustomPlot *parentPlot) : QCPAbstractItem(parentPlot), @@ -22603,9 +28783,8 @@ double QCPItemEllipse::selectTest(const QPointF &pos, bool onlySelectable, QVari if (onlySelectable && !mSelectable) return -1; - double result = -1; - QPointF p1 = topLeft->pixelPoint(); - QPointF p2 = bottomRight->pixelPoint(); + QPointF p1 = topLeft->pixelPosition(); + QPointF p2 = bottomRight->pixelPosition(); QPointF center((p1+p2)/2.0); double a = qAbs(p1.x()-p2.x())/2.0; double b = qAbs(p1.y()-p2.y())/2.0; @@ -22614,7 +28793,7 @@ double QCPItemEllipse::selectTest(const QPointF &pos, bool onlySelectable, QVari // distance to border: double c = 1.0/qSqrt(x*x/(a*a)+y*y/(b*b)); - result = qAbs(c-1)*qSqrt(x*x+y*y); + double result = qAbs(c-1)*qSqrt(x*x+y*y); // filled ellipse, allow click inside to count as hit: if (result > mParentPlot->selectionTolerance()*0.99 && mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0) { @@ -22627,8 +28806,8 @@ double QCPItemEllipse::selectTest(const QPointF &pos, bool onlySelectable, QVari /* inherits documentation from base class */ void QCPItemEllipse::draw(QCPPainter *painter) { - QPointF p1 = topLeft->pixelPoint(); - QPointF p2 = bottomRight->pixelPoint(); + QPointF p1 = topLeft->pixelPosition(); + QPointF p2 = bottomRight->pixelPosition(); if (p1.toPoint() == p2.toPoint()) return; QRectF ellipseRect = QRectF(p1, p2).normalized(); @@ -22653,9 +28832,9 @@ void QCPItemEllipse::draw(QCPPainter *painter) } /* inherits documentation from base class */ -QPointF QCPItemEllipse::anchorPixelPoint(int anchorId) const +QPointF QCPItemEllipse::anchorPixelPosition(int anchorId) const { - QRectF rect = QRectF(topLeft->pixelPoint(), bottomRight->pixelPoint()); + QRectF rect = QRectF(topLeft->pixelPosition(), bottomRight->pixelPosition()); switch (anchorId) { case aiTopLeftRim: return rect.center()+(rect.topLeft()-rect.center())*1/qSqrt(2); @@ -22692,8 +28871,12 @@ QBrush QCPItemEllipse::mainBrush() const { return mSelected ? mSelectedBrush : mBrush; } +/* end of 'src/items/item-ellipse.cpp' */ +/* including file 'src/items/item-pixmap.cpp', size 10615 */ +/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */ + //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPItemPixmap //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -22715,7 +28898,8 @@ QBrush QCPItemEllipse::mainBrush() const /*! Creates a rectangle item and sets default values. - The constructed item can be added to the plot with QCustomPlot::addItem. + The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes + ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead. */ QCPItemPixmap::QCPItemPixmap(QCustomPlot *parentPlot) : QCPAbstractItem(parentPlot), @@ -22726,14 +28910,17 @@ QCPItemPixmap::QCPItemPixmap(QCustomPlot *parentPlot) : right(createAnchor(QLatin1String("right"), aiRight)), bottom(createAnchor(QLatin1String("bottom"), aiBottom)), bottomLeft(createAnchor(QLatin1String("bottomLeft"), aiBottomLeft)), - left(createAnchor(QLatin1String("left"), aiLeft)) + left(createAnchor(QLatin1String("left"), aiLeft)), + mScaled(false), + mScaledPixmapInvalidated(true), + mAspectRatioMode(Qt::KeepAspectRatio), + mTransformationMode(Qt::SmoothTransformation) { topLeft->setCoords(0, 1); bottomRight->setCoords(1, 0); setPen(Qt::NoPen); setSelectedPen(QPen(Qt::blue)); - setScaled(false, Qt::KeepAspectRatio, Qt::SmoothTransformation); } QCPItemPixmap::~QCPItemPixmap() @@ -22746,6 +28933,7 @@ QCPItemPixmap::~QCPItemPixmap() void QCPItemPixmap::setPixmap(const QPixmap &pixmap) { mPixmap = pixmap; + mScaledPixmapInvalidated = true; if (mPixmap.isNull()) qDebug() << Q_FUNC_INFO << "pixmap is null"; } @@ -22759,7 +28947,7 @@ void QCPItemPixmap::setScaled(bool scaled, Qt::AspectRatioMode aspectRatioMode, mScaled = scaled; mAspectRatioMode = aspectRatioMode; mTransformationMode = transformationMode; - updateScaledPixmap(); + mScaledPixmapInvalidated = true; } /*! @@ -22789,7 +28977,7 @@ double QCPItemPixmap::selectTest(const QPointF &pos, bool onlySelectable, QVaria if (onlySelectable && !mSelectable) return -1; - return rectSelectTest(getFinalRect(), pos, true); + return rectDistance(getFinalRect(), pos, true); } /* inherits documentation from base class */ @@ -22815,7 +29003,7 @@ void QCPItemPixmap::draw(QCPPainter *painter) } /* inherits documentation from base class */ -QPointF QCPItemPixmap::anchorPixelPoint(int anchorId) const +QPointF QCPItemPixmap::anchorPixelPosition(int anchorId) const { bool flipHorz; bool flipVert; @@ -22861,16 +29049,25 @@ void QCPItemPixmap::updateScaledPixmap(QRect finalRect, bool flipHorz, bool flip if (mScaled) { +#ifdef QCP_DEVICEPIXELRATIO_SUPPORTED + double devicePixelRatio = mPixmap.devicePixelRatio(); +#else + double devicePixelRatio = 1.0; +#endif if (finalRect.isNull()) finalRect = getFinalRect(&flipHorz, &flipVert); - if (finalRect.size() != mScaledPixmap.size()) + if (mScaledPixmapInvalidated || finalRect.size() != mScaledPixmap.size()/devicePixelRatio) { - mScaledPixmap = mPixmap.scaled(finalRect.size(), mAspectRatioMode, mTransformationMode); + mScaledPixmap = mPixmap.scaled(finalRect.size()*devicePixelRatio, mAspectRatioMode, mTransformationMode); if (flipHorz || flipVert) mScaledPixmap = QPixmap::fromImage(mScaledPixmap.toImage().mirrored(flipHorz, flipVert)); +#ifdef QCP_DEVICEPIXELRATIO_SUPPORTED + mScaledPixmap.setDevicePixelRatio(devicePixelRatio); +#endif } } else if (!mScaledPixmap.isNull()) mScaledPixmap = QPixmap(); + mScaledPixmapInvalidated = false; } /*! \internal @@ -22892,8 +29089,8 @@ QRect QCPItemPixmap::getFinalRect(bool *flippedHorz, bool *flippedVert) const QRect result; bool flipHorz = false; bool flipVert = false; - QPoint p1 = topLeft->pixelPoint().toPoint(); - QPoint p2 = bottomRight->pixelPoint().toPoint(); + QPoint p1 = topLeft->pixelPosition().toPoint(); + QPoint p2 = bottomRight->pixelPosition().toPoint(); if (p1 == p2) return QRect(p1, QSize(0, 0)); if (mScaled) @@ -22913,11 +29110,20 @@ QRect QCPItemPixmap::getFinalRect(bool *flippedHorz, bool *flippedVert) const topLeft.setY(p2.y()); } QSize scaledSize = mPixmap.size(); +#ifdef QCP_DEVICEPIXELRATIO_SUPPORTED + scaledSize /= mPixmap.devicePixelRatio(); + scaledSize.scale(newSize*mPixmap.devicePixelRatio(), mAspectRatioMode); +#else scaledSize.scale(newSize, mAspectRatioMode); +#endif result = QRect(topLeft, scaledSize); } else { +#ifdef QCP_DEVICEPIXELRATIO_SUPPORTED + result = QRect(p1, mPixmap.size()/mPixmap.devicePixelRatio()); +#else result = QRect(p1, mPixmap.size()); +#endif } if (flippedHorz) *flippedHorz = flipHorz; @@ -22935,8 +29141,12 @@ QPen QCPItemPixmap::mainPen() const { return mSelected ? mSelectedPen : mPen; } +/* end of 'src/items/item-pixmap.cpp' */ +/* including file 'src/items/item-tracer.cpp', size 14624 */ +/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */ + //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPItemTracer //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -22966,7 +29176,7 @@ QPen QCPItemPixmap::mainPen() const QCPItemPosition::setParentAnchor. \note The tracer position is only automatically updated upon redraws. So when the data of the - graph changes and immediately afterwards (without a redraw) the a position coordinates of the + graph changes and immediately afterwards (without a redraw) the position coordinates of the tracer are retrieved, they will not reflect the updated data of the graph. In this case \ref updatePosition must be called manually, prior to reading the tracer coordinates. */ @@ -22974,12 +29184,17 @@ QPen QCPItemPixmap::mainPen() const /*! Creates a tracer item and sets default values. - The constructed item can be added to the plot with QCustomPlot::addItem. + The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes + ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead. */ QCPItemTracer::QCPItemTracer(QCustomPlot *parentPlot) : QCPAbstractItem(parentPlot), position(createPosition(QLatin1String("position"))), - mGraph(0) + mSize(6), + mStyle(tsCrosshair), + mGraph(0), + mGraphKey(0), + mInterpolating(false) { position->setCoords(0, 0); @@ -22987,10 +29202,6 @@ QCPItemTracer::QCPItemTracer(QCustomPlot *parentPlot) : setSelectedBrush(Qt::NoBrush); setPen(QPen(Qt::black)); setSelectedPen(QPen(Qt::blue, 2)); - setStyle(tsCrosshair); - setSize(6); - setInterpolating(false); - setGraphKey(0); } QCPItemTracer::~QCPItemTracer() @@ -23122,7 +29333,7 @@ double QCPItemTracer::selectTest(const QPointF &pos, bool onlySelectable, QVaria if (onlySelectable && !mSelectable) return -1; - QPointF center(position->pixelPoint()); + QPointF center(position->pixelPosition()); double w = mSize/2.0; QRect clip = clipRect(); switch (mStyle) @@ -23131,21 +29342,21 @@ double QCPItemTracer::selectTest(const QPointF &pos, bool onlySelectable, QVaria case tsPlus: { if (clipRect().intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect())) - return qSqrt(qMin(distSqrToLine(center+QPointF(-w, 0), center+QPointF(w, 0), pos), - distSqrToLine(center+QPointF(0, -w), center+QPointF(0, w), pos))); + return qSqrt(qMin(QCPVector2D(pos).distanceSquaredToLine(center+QPointF(-w, 0), center+QPointF(w, 0)), + QCPVector2D(pos).distanceSquaredToLine(center+QPointF(0, -w), center+QPointF(0, w)))); break; } case tsCrosshair: { - return qSqrt(qMin(distSqrToLine(QPointF(clip.left(), center.y()), QPointF(clip.right(), center.y()), pos), - distSqrToLine(QPointF(center.x(), clip.top()), QPointF(center.x(), clip.bottom()), pos))); + return qSqrt(qMin(QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(clip.left(), center.y()), QCPVector2D(clip.right(), center.y())), + QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(center.x(), clip.top()), QCPVector2D(center.x(), clip.bottom())))); } case tsCircle: { if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect())) { // distance to border: - double centerDist = QVector2D(center-pos).length(); + double centerDist = QCPVector2D(center-pos).length(); double circleLine = w; double result = qAbs(centerDist-circleLine); // filled ellipse, allow click inside to count as hit: @@ -23164,7 +29375,7 @@ double QCPItemTracer::selectTest(const QPointF &pos, bool onlySelectable, QVaria { QRectF rect = QRectF(center-QPointF(w, w), center+QPointF(w, w)); bool filledRect = mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0; - return rectSelectTest(rect, pos, filledRect); + return rectDistance(rect, pos, filledRect); } break; } @@ -23181,7 +29392,7 @@ void QCPItemTracer::draw(QCPPainter *painter) painter->setPen(mainPen()); painter->setBrush(mainBrush()); - QPointF center(position->pixelPoint()); + QPointF center(position->pixelPosition()); double w = mSize/2.0; QRect clip = clipRect(); switch (mStyle) @@ -23239,39 +29450,41 @@ void QCPItemTracer::updatePosition() { if (mGraph->data()->size() > 1) { - QCPDataMap::const_iterator first = mGraph->data()->constBegin(); - QCPDataMap::const_iterator last = mGraph->data()->constEnd()-1; - if (mGraphKey < first.key()) - position->setCoords(first.key(), first.value().value); - else if (mGraphKey > last.key()) - position->setCoords(last.key(), last.value().value); + QCPGraphDataContainer::const_iterator first = mGraph->data()->constBegin(); + QCPGraphDataContainer::const_iterator last = mGraph->data()->constEnd()-1; + if (mGraphKey <= first->key) + position->setCoords(first->key, first->value); + else if (mGraphKey >= last->key) + position->setCoords(last->key, last->value); else { - QCPDataMap::const_iterator it = mGraph->data()->lowerBound(mGraphKey); - if (it != first) // mGraphKey is somewhere between iterators + QCPGraphDataContainer::const_iterator it = mGraph->data()->findBegin(mGraphKey); + if (it != mGraph->data()->constEnd()) // mGraphKey is not exactly on last iterator, but somewhere between iterators { - QCPDataMap::const_iterator prevIt = it-1; + QCPGraphDataContainer::const_iterator prevIt = it; + ++it; // won't advance to constEnd because we handled that case (mGraphKey >= last->key) before if (mInterpolating) { // interpolate between iterators around mGraphKey: double slope = 0; - if (!qFuzzyCompare((double)it.key(), (double)prevIt.key())) - slope = (it.value().value-prevIt.value().value)/(it.key()-prevIt.key()); - position->setCoords(mGraphKey, (mGraphKey-prevIt.key())*slope+prevIt.value().value); + if (!qFuzzyCompare((double)it->key, (double)prevIt->key)) + slope = (it->value-prevIt->value)/(it->key-prevIt->key); + position->setCoords(mGraphKey, (mGraphKey-prevIt->key)*slope+prevIt->value); } else { // find iterator with key closest to mGraphKey: - if (mGraphKey < (prevIt.key()+it.key())*0.5) - it = prevIt; - position->setCoords(it.key(), it.value().value); + if (mGraphKey < (prevIt->key+it->key)*0.5) + position->setCoords(prevIt->key, prevIt->value); + else + position->setCoords(it->key, it->value); } - } else // mGraphKey is exactly on first iterator - position->setCoords(it.key(), it.value().value); + } else // mGraphKey is exactly on last iterator (should actually be caught when comparing first/last keys, but this is a failsafe for fp uncertainty) + position->setCoords(it->key, it->value); } } else if (mGraph->data()->size() == 1) { - QCPDataMap::const_iterator it = mGraph->data()->constBegin(); - position->setCoords(it.key(), it.value().value); + QCPGraphDataContainer::const_iterator it = mGraph->data()->constBegin(); + position->setCoords(it->key, it->value); } else qDebug() << Q_FUNC_INFO << "graph has no data"; } else @@ -23298,8 +29511,12 @@ QBrush QCPItemTracer::mainBrush() const { return mSelected ? mSelectedBrush : mBrush; } +/* end of 'src/items/item-tracer.cpp' */ +/* including file 'src/items/item-bracket.cpp', size 10687 */ +/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */ + //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPItemBracket //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -23327,21 +29544,22 @@ QBrush QCPItemTracer::mainBrush() const /*! Creates a bracket item and sets default values. - The constructed item can be added to the plot with QCustomPlot::addItem. + The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes + ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead. */ QCPItemBracket::QCPItemBracket(QCustomPlot *parentPlot) : QCPAbstractItem(parentPlot), left(createPosition(QLatin1String("left"))), right(createPosition(QLatin1String("right"))), - center(createAnchor(QLatin1String("center"), aiCenter)) + center(createAnchor(QLatin1String("center"), aiCenter)), + mLength(8), + mStyle(bsCalligraphic) { left->setCoords(0, 0); right->setCoords(1, 1); setPen(QPen(Qt::black)); setSelectedPen(QPen(Qt::blue, 2)); - setLength(8); - setStyle(bsCalligraphic); } QCPItemBracket::~QCPItemBracket() @@ -23402,33 +29620,33 @@ double QCPItemBracket::selectTest(const QPointF &pos, bool onlySelectable, QVari if (onlySelectable && !mSelectable) return -1; - QVector2D leftVec(left->pixelPoint()); - QVector2D rightVec(right->pixelPoint()); + QCPVector2D p(pos); + QCPVector2D leftVec(left->pixelPosition()); + QCPVector2D rightVec(right->pixelPosition()); if (leftVec.toPoint() == rightVec.toPoint()) return -1; - QVector2D widthVec = (rightVec-leftVec)*0.5f; - QVector2D lengthVec(-widthVec.y(), widthVec.x()); - lengthVec = lengthVec.normalized()*mLength; - QVector2D centerVec = (rightVec+leftVec)*0.5f-lengthVec; + QCPVector2D widthVec = (rightVec-leftVec)*0.5; + QCPVector2D lengthVec = widthVec.perpendicular().normalized()*mLength; + QCPVector2D centerVec = (rightVec+leftVec)*0.5-lengthVec; switch (mStyle) { case QCPItemBracket::bsSquare: case QCPItemBracket::bsRound: { - double a = distSqrToLine((centerVec-widthVec).toPointF(), (centerVec+widthVec).toPointF(), pos); - double b = distSqrToLine((centerVec-widthVec+lengthVec).toPointF(), (centerVec-widthVec).toPointF(), pos); - double c = distSqrToLine((centerVec+widthVec+lengthVec).toPointF(), (centerVec+widthVec).toPointF(), pos); + double a = p.distanceSquaredToLine(centerVec-widthVec, centerVec+widthVec); + double b = p.distanceSquaredToLine(centerVec-widthVec+lengthVec, centerVec-widthVec); + double c = p.distanceSquaredToLine(centerVec+widthVec+lengthVec, centerVec+widthVec); return qSqrt(qMin(qMin(a, b), c)); } case QCPItemBracket::bsCurly: case QCPItemBracket::bsCalligraphic: { - double a = distSqrToLine((centerVec-widthVec*0.75f+lengthVec*0.15f).toPointF(), (centerVec+lengthVec*0.3f).toPointF(), pos); - double b = distSqrToLine((centerVec-widthVec+lengthVec*0.7f).toPointF(), (centerVec-widthVec*0.75f+lengthVec*0.15f).toPointF(), pos); - double c = distSqrToLine((centerVec+widthVec*0.75f+lengthVec*0.15f).toPointF(), (centerVec+lengthVec*0.3f).toPointF(), pos); - double d = distSqrToLine((centerVec+widthVec+lengthVec*0.7f).toPointF(), (centerVec+widthVec*0.75f+lengthVec*0.15f).toPointF(), pos); + double a = p.distanceSquaredToLine(centerVec-widthVec*0.75+lengthVec*0.15, centerVec+lengthVec*0.3); + double b = p.distanceSquaredToLine(centerVec-widthVec+lengthVec*0.7, centerVec-widthVec*0.75+lengthVec*0.15); + double c = p.distanceSquaredToLine(centerVec+widthVec*0.75+lengthVec*0.15, centerVec+lengthVec*0.3); + double d = p.distanceSquaredToLine(centerVec+widthVec+lengthVec*0.7, centerVec+widthVec*0.75+lengthVec*0.15); return qSqrt(qMin(qMin(a, b), qMin(c, d))); } } @@ -23438,15 +29656,14 @@ double QCPItemBracket::selectTest(const QPointF &pos, bool onlySelectable, QVari /* inherits documentation from base class */ void QCPItemBracket::draw(QCPPainter *painter) { - QVector2D leftVec(left->pixelPoint()); - QVector2D rightVec(right->pixelPoint()); + QCPVector2D leftVec(left->pixelPosition()); + QCPVector2D rightVec(right->pixelPosition()); if (leftVec.toPoint() == rightVec.toPoint()) return; - QVector2D widthVec = (rightVec-leftVec)*0.5f; - QVector2D lengthVec(-widthVec.y(), widthVec.x()); - lengthVec = lengthVec.normalized()*mLength; - QVector2D centerVec = (rightVec+leftVec)*0.5f-lengthVec; + QCPVector2D widthVec = (rightVec-leftVec)*0.5; + QCPVector2D lengthVec = widthVec.perpendicular().normalized()*mLength; + QCPVector2D centerVec = (rightVec+leftVec)*0.5-lengthVec; QPolygon boundingPoly; boundingPoly << leftVec.toPoint() << rightVec.toPoint() @@ -23479,8 +29696,8 @@ void QCPItemBracket::draw(QCPPainter *painter) painter->setBrush(Qt::NoBrush); QPainterPath path; path.moveTo((centerVec+widthVec+lengthVec).toPointF()); - path.cubicTo((centerVec+widthVec-lengthVec*0.8f).toPointF(), (centerVec+0.4f*widthVec+lengthVec).toPointF(), centerVec.toPointF()); - path.cubicTo((centerVec-0.4f*widthVec+lengthVec).toPointF(), (centerVec-widthVec-lengthVec*0.8f).toPointF(), (centerVec-widthVec+lengthVec).toPointF()); + path.cubicTo((centerVec+widthVec-lengthVec*0.8).toPointF(), (centerVec+0.4*widthVec+lengthVec).toPointF(), centerVec.toPointF()); + path.cubicTo((centerVec-0.4*widthVec+lengthVec).toPointF(), (centerVec-widthVec-lengthVec*0.8).toPointF(), (centerVec-widthVec+lengthVec).toPointF()); painter->drawPath(path); break; } @@ -23491,11 +29708,11 @@ void QCPItemBracket::draw(QCPPainter *painter) QPainterPath path; path.moveTo((centerVec+widthVec+lengthVec).toPointF()); - path.cubicTo((centerVec+widthVec-lengthVec*0.8f).toPointF(), (centerVec+0.4f*widthVec+0.8f*lengthVec).toPointF(), centerVec.toPointF()); - path.cubicTo((centerVec-0.4f*widthVec+0.8f*lengthVec).toPointF(), (centerVec-widthVec-lengthVec*0.8f).toPointF(), (centerVec-widthVec+lengthVec).toPointF()); + path.cubicTo((centerVec+widthVec-lengthVec*0.8).toPointF(), (centerVec+0.4*widthVec+0.8*lengthVec).toPointF(), centerVec.toPointF()); + path.cubicTo((centerVec-0.4*widthVec+0.8*lengthVec).toPointF(), (centerVec-widthVec-lengthVec*0.8).toPointF(), (centerVec-widthVec+lengthVec).toPointF()); - path.cubicTo((centerVec-widthVec-lengthVec*0.5f).toPointF(), (centerVec-0.2f*widthVec+1.2f*lengthVec).toPointF(), (centerVec+lengthVec*0.2f).toPointF()); - path.cubicTo((centerVec+0.2f*widthVec+1.2f*lengthVec).toPointF(), (centerVec+widthVec-lengthVec*0.5f).toPointF(), (centerVec+widthVec+lengthVec).toPointF()); + path.cubicTo((centerVec-widthVec-lengthVec*0.5).toPointF(), (centerVec-0.2*widthVec+1.2*lengthVec).toPointF(), (centerVec+lengthVec*0.2).toPointF()); + path.cubicTo((centerVec+0.2*widthVec+1.2*lengthVec).toPointF(), (centerVec+widthVec-lengthVec*0.5).toPointF(), (centerVec+widthVec+lengthVec).toPointF()); painter->drawPath(path); break; @@ -23505,17 +29722,16 @@ void QCPItemBracket::draw(QCPPainter *painter) } /* inherits documentation from base class */ -QPointF QCPItemBracket::anchorPixelPoint(int anchorId) const +QPointF QCPItemBracket::anchorPixelPosition(int anchorId) const { - QVector2D leftVec(left->pixelPoint()); - QVector2D rightVec(right->pixelPoint()); + QCPVector2D leftVec(left->pixelPosition()); + QCPVector2D rightVec(right->pixelPosition()); if (leftVec.toPoint() == rightVec.toPoint()) return leftVec.toPointF(); - QVector2D widthVec = (rightVec-leftVec)*0.5f; - QVector2D lengthVec(-widthVec.y(), widthVec.x()); - lengthVec = lengthVec.normalized()*mLength; - QVector2D centerVec = (rightVec+leftVec)*0.5f-lengthVec; + QCPVector2D widthVec = (rightVec-leftVec)*0.5; + QCPVector2D lengthVec = widthVec.perpendicular().normalized()*mLength; + QCPVector2D centerVec = (rightVec+leftVec)*0.5-lengthVec; switch (anchorId) { @@ -23535,4 +29751,6 @@ QPen QCPItemBracket::mainPen() const { return mSelected ? mSelectedPen : mPen; } +/* end of 'src/items/item-bracket.cpp' */ + diff --git a/libs/qcustomplot-source/qcustomplot.h b/libs/qcustomplot-source/qcustomplot.h index b3392374..0b1bb274 100644 --- a/libs/qcustomplot-source/qcustomplot.h +++ b/libs/qcustomplot-source/qcustomplot.h @@ -1,7 +1,7 @@ /*************************************************************************** ** ** ** 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 ** @@ -19,39 +19,73 @@ **************************************************************************** ** 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 ** ****************************************************************************/ #ifndef QCUSTOMPLOT_H #define QCUSTOMPLOT_H -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include + +// some Qt version/configuration dependent macros to include or exclude certain code paths: +#ifdef QCUSTOMPLOT_USE_OPENGL +# if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) +# define QCP_OPENGL_PBUFFER +# else +# define QCP_OPENGL_FBO +# endif +# if QT_VERSION >= QT_VERSION_CHECK(5, 3, 0) +# define QCP_OPENGL_OFFSCREENSURFACE +# endif +#endif + +#if QT_VERSION >= QT_VERSION_CHECK(5, 4, 0) + #define QCP_DEVICEPIXELRATIO_SUPPORTED +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include #include +#include +#ifdef QCP_OPENGL_FBO +# include +# include +# ifdef QCP_OPENGL_OFFSCREENSURFACE +# include +# else +# include +# endif +#endif +#ifdef QCP_OPENGL_PBUFFER +# include +#endif #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) # include -# include -# include +# include +# include +# include #else # include -# include +# include +# include #endif class QCPPainter; @@ -65,18 +99,18 @@ class QCPAxisPainterPrivate; class QCPAbstractPlottable; class QCPGraph; class QCPAbstractItem; +class QCPPlottableInterface1D; +class QCPLegend; class QCPItemPosition; class QCPLayer; -class QCPPlotTitle; -class QCPLegend; class QCPAbstractLegendItem; +class QCPSelectionRect; class QCPColorMap; class QCPColorScale; class QCPBars; - -/*! \file */ - +/* including file 'src/global.h', size 16131 */ +/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */ // decl definitions for shared library compilation/usage: #if defined(QCUSTOMPLOT_COMPILE_LIBRARY) @@ -87,11 +121,70 @@ class QCPBars; # define QCP_LIB_DECL #endif +// define empty macro for Q_DECL_OVERRIDE if it doesn't exist (Qt < 5) +#ifndef Q_DECL_OVERRIDE +# define Q_DECL_OVERRIDE +#endif + /*! - The QCP Namespace contains general enums and QFlags used throughout the QCustomPlot library + The QCP Namespace contains general enums, QFlags and functions used throughout the QCustomPlot + library. + + It provides QMetaObject-based reflection of its enums and flags via \a QCP::staticMetaObject. */ -namespace QCP -{ +#ifndef Q_MOC_RUN +namespace QCP { +#else +class QCP { // when in moc-run, make it look like a class, so we get Q_GADGET, Q_ENUMS/Q_FLAGS features in namespace + Q_GADGET + Q_ENUMS(ExportPen) + Q_ENUMS(ResolutionUnit) + Q_ENUMS(SignDomain) + Q_ENUMS(MarginSide) + Q_FLAGS(MarginSides) + Q_ENUMS(AntialiasedElement) + Q_FLAGS(AntialiasedElements) + Q_ENUMS(PlottingHint) + Q_FLAGS(PlottingHints) + Q_ENUMS(Interaction) + Q_FLAGS(Interactions) + Q_ENUMS(SelectionRectMode) + Q_ENUMS(SelectionType) +public: +#endif + +/*! + Defines the different units in which the image resolution can be specified in the export + functions. + + \see QCustomPlot::savePng, QCustomPlot::saveJpg, QCustomPlot::saveBmp, QCustomPlot::saveRastered +*/ +enum ResolutionUnit { ruDotsPerMeter ///< Resolution is given in dots per meter (dpm) + ,ruDotsPerCentimeter ///< Resolution is given in dots per centimeter (dpcm) + ,ruDotsPerInch ///< Resolution is given in dots per inch (DPI/PPI) + }; + +/*! + Defines how cosmetic pens (pens with numerical width 0) are handled during export. + + \see QCustomPlot::savePdf +*/ +enum ExportPen { epNoCosmetic ///< Cosmetic pens are converted to pens with pixel width 1 when exporting + ,epAllowCosmetic ///< Cosmetic pens are exported normally (e.g. in PDF exports, cosmetic pens always appear as 1 pixel on screen, independent of viewer zoom level) + }; + +/*! + Represents negative and positive sign domain, e.g. for passing to \ref + QCPAbstractPlottable::getKeyRange and \ref QCPAbstractPlottable::getValueRange. + + This is primarily needed when working with logarithmic axis scales, since only one of the sign + domains can be visible at a time. +*/ +enum SignDomain { sdNegative ///< The negative sign domain, i.e. numbers smaller than zero + ,sdBoth ///< Both sign domains, including zero, i.e. all numbers + ,sdPositive ///< The positive sign domain, i.e. numbers greater than zero + }; + /*! Defines the sides of a rectangular entity to which margins can be applied. @@ -120,12 +213,12 @@ enum AntialiasedElement { aeAxes = 0x0001 ///< 0x0001 Axis ba ,aeSubGrid = 0x0004 ///< 0x0004 Sub grid lines ,aeLegend = 0x0008 ///< 0x0008 Legend box ,aeLegendItems = 0x0010 ///< 0x0010 Legend items - ,aePlottables = 0x0020 ///< 0x0020 Main lines of plottables (excluding error bars, see element \ref aeErrorBars) + ,aePlottables = 0x0020 ///< 0x0020 Main lines of plottables ,aeItems = 0x0040 ///< 0x0040 Main lines of items ,aeScatters = 0x0080 ///< 0x0080 Scatter symbols of plottables (excluding scatter symbols of type ssPixmap) - ,aeErrorBars = 0x0100 ///< 0x0100 Error bars - ,aeFills = 0x0200 ///< 0x0200 Borders of fills (e.g. under or between graphs) - ,aeZeroLine = 0x0400 ///< 0x0400 Zero-lines, see \ref QCPGrid::setZeroLinePen + ,aeFills = 0x0100 ///< 0x0100 Borders of fills (e.g. under or between graphs) + ,aeZeroLine = 0x0200 ///< 0x0200 Zero-lines, see \ref QCPGrid::setZeroLinePen + ,aeOther = 0x8000 ///< 0x8000 Other elements that don't fit into any of the existing categories ,aeAll = 0xFFFF ///< 0xFFFF All elements ,aeNone = 0x0000 ///< 0x0000 No elements }; @@ -136,12 +229,12 @@ Q_DECLARE_FLAGS(AntialiasedElements, AntialiasedElement) \see QCustomPlot::setPlottingHints */ -enum PlottingHint { phNone = 0x000 ///< 0x000 No hints are set - ,phFastPolylines = 0x001 ///< 0x001 Graph/Curve lines are drawn with a faster method. This reduces the quality - ///< especially of the line segment joins. (Only relevant for solid line pens.) - ,phForceRepaint = 0x002 ///< 0x002 causes an immediate repaint() instead of a soft update() when QCustomPlot::replot() is called with parameter \ref QCustomPlot::rpHint. - ///< This is set by default to prevent the plot from freezing on fast consecutive replots (e.g. user drags ranges with mouse). - ,phCacheLabels = 0x004 ///< 0x004 axis (tick) labels will be cached as pixmaps, increasing replot performance. +enum PlottingHint { phNone = 0x000 ///< 0x000 No hints are set + ,phFastPolylines = 0x001 ///< 0x001 Graph/Curve lines are drawn with a faster method. This reduces the quality especially of the line segment + ///< joins, thus is most effective for pen sizes larger than 1. It is only used for solid line pens. + ,phImmediateRefresh = 0x002 ///< 0x002 causes an immediate repaint() instead of a soft update() when QCustomPlot::replot() is called with parameter \ref QCustomPlot::rpRefreshHint. + ///< This is set by default to prevent the plot from freezing on fast consecutive replots (e.g. user drags ranges with mouse). + ,phCacheLabels = 0x004 ///< 0x004 axis (tick) labels will be cached as pixmaps, increasing replot performance. }; Q_DECLARE_FLAGS(PlottingHints, PlottingHint) @@ -159,10 +252,46 @@ enum Interaction { iRangeDrag = 0x001 ///< 0x001 Axis ranges ar ,iSelectAxes = 0x010 ///< 0x010 Axes are selectable (or parts of them, see QCPAxis::setSelectableParts) ,iSelectLegend = 0x020 ///< 0x020 Legends are selectable (or their child items, see QCPLegend::setSelectableParts) ,iSelectItems = 0x040 ///< 0x040 Items are selectable (Rectangles, Arrows, Textitems, etc. see \ref QCPAbstractItem) - ,iSelectOther = 0x080 ///< 0x080 All other objects are selectable (e.g. your own derived layerables, the plot title,...) + ,iSelectOther = 0x080 ///< 0x080 All other objects are selectable (e.g. your own derived layerables, other layout elements,...) }; Q_DECLARE_FLAGS(Interactions, Interaction) +/*! + Defines the behaviour of the selection rect. + + \see QCustomPlot::setSelectionRectMode, QCustomPlot::selectionRect, QCPSelectionRect +*/ +enum SelectionRectMode { srmNone ///< The selection rect is disabled, and all mouse events are forwarded to the underlying objects, e.g. for axis range dragging + ,srmZoom ///< When dragging the mouse, a selection rect becomes active. Upon releasing, the axes that are currently set as range zoom axes (\ref QCPAxisRect::setRangeZoomAxes) will have their ranges zoomed accordingly. + ,srmSelect ///< When dragging the mouse, a selection rect becomes active. Upon releasing, plottable data points that were within the selection rect are selected, if the plottable's selectability setting permits. (See \ref dataselection "data selection mechanism" for details.) + ,srmCustom ///< When dragging the mouse, a selection rect becomes active. It is the programmer's responsibility to connect according slots to the selection rect's signals (e.g. \ref QCPSelectionRect::accepted) in order to process the user interaction. + }; + +/*! + Defines the different ways a plottable can be selected. These images show the effect of the + different selection types, when the indicated selection rect was dragged: + +
+ + + + + + + + +
\image html selectiontype-none.png stNone\image html selectiontype-whole.png stWhole\image html selectiontype-singledata.png stSingleData\image html selectiontype-datarange.png stDataRange\image html selectiontype-multipledataranges.png stMultipleDataRanges
+
+ + \see QCPAbstractPlottable::setSelectable, QCPDataSelection::enforceType +*/ +enum SelectionType { stNone ///< The plottable is not selectable + ,stWhole ///< Selection behaves like \ref stMultipleDataRanges, but if there are any data points selected, the entire plottable is drawn as selected. + ,stSingleData ///< One individual data point can be selected at a time + ,stDataRange ///< Multiple contiguous data points (a data range) can be selected + ,stMultipleDataRanges ///< Any combination of data points/ranges can be selected + }; + /*! \internal Returns whether the specified \a value is considered an invalid data value for plottables (i.e. @@ -223,91 +352,103 @@ inline int getMarginValue(const QMargins &margins, QCP::MarginSide side) return 0; } -} // end of namespace QCP +extern const QMetaObject staticMetaObject; // in moc-run we create a static meta object for QCP "fake" object. This line is the link to it via QCP::staticMetaObject in normal operation as namespace + +} // end of namespace QCP Q_DECLARE_OPERATORS_FOR_FLAGS(QCP::AntialiasedElements) Q_DECLARE_OPERATORS_FOR_FLAGS(QCP::PlottingHints) Q_DECLARE_OPERATORS_FOR_FLAGS(QCP::MarginSides) Q_DECLARE_OPERATORS_FOR_FLAGS(QCP::Interactions) +Q_DECLARE_METATYPE(QCP::ExportPen) +Q_DECLARE_METATYPE(QCP::ResolutionUnit) +Q_DECLARE_METATYPE(QCP::SignDomain) +Q_DECLARE_METATYPE(QCP::MarginSide) +Q_DECLARE_METATYPE(QCP::AntialiasedElement) +Q_DECLARE_METATYPE(QCP::PlottingHint) +Q_DECLARE_METATYPE(QCP::Interaction) +Q_DECLARE_METATYPE(QCP::SelectionRectMode) +Q_DECLARE_METATYPE(QCP::SelectionType) + +/* end of 'src/global.h' */ -class QCP_LIB_DECL QCPScatterStyle +/* including file 'src/vector2d.h', size 4928 */ +/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */ + +class QCP_LIB_DECL QCPVector2D { - Q_GADGET public: - /*! - Defines the shape used for scatter points. - - On plottables/items that draw scatters, the sizes of these visualizations (with exception of - \ref ssDot and \ref ssPixmap) can be controlled with the \ref setSize function. Scatters are - drawn with the pen and brush specified with \ref setPen and \ref setBrush. - */ - Q_ENUMS(ScatterShape) - enum ScatterShape { ssNone ///< no scatter symbols are drawn (e.g. in QCPGraph, data only represented with lines) - ,ssDot ///< \enumimage{ssDot.png} a single pixel (use \ref ssDisc or \ref ssCircle if you want a round shape with a certain radius) - ,ssCross ///< \enumimage{ssCross.png} a cross - ,ssPlus ///< \enumimage{ssPlus.png} a plus - ,ssCircle ///< \enumimage{ssCircle.png} a circle - ,ssDisc ///< \enumimage{ssDisc.png} a circle which is filled with the pen's color (not the brush as with ssCircle) - ,ssSquare ///< \enumimage{ssSquare.png} a square - ,ssDiamond ///< \enumimage{ssDiamond.png} a diamond - ,ssStar ///< \enumimage{ssStar.png} a star with eight arms, i.e. a combination of cross and plus - ,ssTriangle ///< \enumimage{ssTriangle.png} an equilateral triangle, standing on baseline - ,ssTriangleInverted ///< \enumimage{ssTriangleInverted.png} an equilateral triangle, standing on corner - ,ssCrossSquare ///< \enumimage{ssCrossSquare.png} a square with a cross inside - ,ssPlusSquare ///< \enumimage{ssPlusSquare.png} a square with a plus inside - ,ssCrossCircle ///< \enumimage{ssCrossCircle.png} a circle with a cross inside - ,ssPlusCircle ///< \enumimage{ssPlusCircle.png} a circle with a plus inside - ,ssPeace ///< \enumimage{ssPeace.png} a circle, with one vertical and two downward diagonal lines - ,ssPixmap ///< a custom pixmap specified by \ref setPixmap, centered on the data point coordinates - ,ssCustom ///< custom painter operations are performed per scatter (As QPainterPath, see \ref setCustomPath) - }; - - QCPScatterStyle(); - QCPScatterStyle(ScatterShape shape, double size=6); - QCPScatterStyle(ScatterShape shape, const QColor &color, double size); - QCPScatterStyle(ScatterShape shape, const QColor &color, const QColor &fill, double size); - QCPScatterStyle(ScatterShape shape, const QPen &pen, const QBrush &brush, double size); - QCPScatterStyle(const QPixmap &pixmap); - QCPScatterStyle(const QPainterPath &customPath, const QPen &pen, const QBrush &brush=Qt::NoBrush, double size=6); + QCPVector2D(); + QCPVector2D(double x, double y); + QCPVector2D(const QPoint &point); + QCPVector2D(const QPointF &point); // getters: - double size() const { return mSize; } - ScatterShape shape() const { return mShape; } - QPen pen() const { return mPen; } - QBrush brush() const { return mBrush; } - QPixmap pixmap() const { return mPixmap; } - QPainterPath customPath() const { return mCustomPath; } - - // setters: - void setSize(double size); - void setShape(ScatterShape shape); - void setPen(const QPen &pen); - void setBrush(const QBrush &brush); - void setPixmap(const QPixmap &pixmap); - void setCustomPath(const QPainterPath &customPath); - - // non-property methods: - bool isNone() const { return mShape == ssNone; } - bool isPenDefined() const { return mPenDefined; } - void applyTo(QCPPainter *painter, const QPen &defaultPen) const; - void drawShape(QCPPainter *painter, QPointF pos) const; - void drawShape(QCPPainter *painter, double x, double y) const; - -protected: - // property members: - double mSize; - ScatterShape mShape; - QPen mPen; - QBrush mBrush; - QPixmap mPixmap; - QPainterPath mCustomPath; + double x() const { return mX; } + double y() const { return mY; } + double &rx() { return mX; } + double &ry() { return mY; } - // non-property members: - bool mPenDefined; + // setters: + void setX(double x) { mX = x; } + void setY(double y) { mY = y; } + + // non-virtual methods: + double length() const { return qSqrt(mX*mX+mY*mY); } + double lengthSquared() const { return mX*mX+mY*mY; } + QPoint toPoint() const { return QPoint(mX, mY); } + QPointF toPointF() const { return QPointF(mX, mY); } + + bool isNull() const { return qIsNull(mX) && qIsNull(mY); } + void normalize(); + QCPVector2D normalized() const; + QCPVector2D perpendicular() const { return QCPVector2D(-mY, mX); } + double dot(const QCPVector2D &vec) const { return mX*vec.mX+mY*vec.mY; } + double distanceSquaredToLine(const QCPVector2D &start, const QCPVector2D &end) const; + double distanceSquaredToLine(const QLineF &line) const; + double distanceToStraightLine(const QCPVector2D &base, const QCPVector2D &direction) const; + + QCPVector2D &operator*=(double factor); + QCPVector2D &operator/=(double divisor); + QCPVector2D &operator+=(const QCPVector2D &vector); + QCPVector2D &operator-=(const QCPVector2D &vector); + +private: + // property members: + double mX, mY; + + friend inline const QCPVector2D operator*(double factor, const QCPVector2D &vec); + friend inline const QCPVector2D operator*(const QCPVector2D &vec, double factor); + friend inline const QCPVector2D operator/(const QCPVector2D &vec, double divisor); + friend inline const QCPVector2D operator+(const QCPVector2D &vec1, const QCPVector2D &vec2); + friend inline const QCPVector2D operator-(const QCPVector2D &vec1, const QCPVector2D &vec2); + friend inline const QCPVector2D operator-(const QCPVector2D &vec); }; -Q_DECLARE_TYPEINFO(QCPScatterStyle, Q_MOVABLE_TYPE); +Q_DECLARE_TYPEINFO(QCPVector2D, Q_MOVABLE_TYPE); +inline const QCPVector2D operator*(double factor, const QCPVector2D &vec) { return QCPVector2D(vec.mX*factor, vec.mY*factor); } +inline const QCPVector2D operator*(const QCPVector2D &vec, double factor) { return QCPVector2D(vec.mX*factor, vec.mY*factor); } +inline const QCPVector2D operator/(const QCPVector2D &vec, double divisor) { return QCPVector2D(vec.mX/divisor, vec.mY/divisor); } +inline const QCPVector2D operator+(const QCPVector2D &vec1, const QCPVector2D &vec2) { return QCPVector2D(vec1.mX+vec2.mX, vec1.mY+vec2.mY); } +inline const QCPVector2D operator-(const QCPVector2D &vec1, const QCPVector2D &vec2) { return QCPVector2D(vec1.mX-vec2.mX, vec1.mY-vec2.mY); } +inline const QCPVector2D operator-(const QCPVector2D &vec) { return QCPVector2D(-vec.mX, -vec.mY); } + +/*! \relates QCPVector2D + + Prints \a vec in a human readable format to the qDebug output. +*/ +inline QDebug operator<< (QDebug d, const QCPVector2D &vec) +{ + d.nospace() << "QCPVector2D(" << vec.x() << ", " << vec.y() << ")"; + return d.space(); +} + +/* end of 'src/vector2d.h' */ + + +/* including file 'src/painter.h', size 4035 */ +/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */ class QCP_LIB_DECL QCPPainter : public QPainter { @@ -322,12 +463,12 @@ public: ,pmNoCaching = 0x02 ///< 0x02 Mode for all sorts of exports (e.g. PNG, PDF,...). For example, this prevents using cached pixmap labels ,pmNonCosmetic = 0x04 ///< 0x04 Turns pen widths 0 to 1, i.e. disables cosmetic pens. (A cosmetic pen is always drawn with width 1 pixel in the vector image/pdf viewer, independent of zoom.) }; - Q_FLAGS(PainterMode PainterModes) + Q_ENUMS(PainterMode) + Q_FLAGS(PainterModes) Q_DECLARE_FLAGS(PainterModes, PainterMode) QCPPainter(); - QCPPainter(QPaintDevice *device); - ~QCPPainter(); + explicit QCPPainter(QPaintDevice *device); // getters: bool antialiasing() const { return testRenderHint(QPainter::Antialiasing); } @@ -360,7 +501,121 @@ protected: QStack mAntialiasingStack; }; Q_DECLARE_OPERATORS_FOR_FLAGS(QCPPainter::PainterModes) +Q_DECLARE_METATYPE(QCPPainter::PainterMode) +/* end of 'src/painter.h' */ + + +/* including file 'src/paintbuffer.h', size 4958 */ +/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */ + +class QCP_LIB_DECL QCPAbstractPaintBuffer +{ +public: + explicit QCPAbstractPaintBuffer(const QSize &size, double devicePixelRatio); + virtual ~QCPAbstractPaintBuffer(); + + // getters: + QSize size() const { return mSize; } + bool invalidated() const { return mInvalidated; } + double devicePixelRatio() const { return mDevicePixelRatio; } + + // setters: + void setSize(const QSize &size); + void setInvalidated(bool invalidated=true); + void setDevicePixelRatio(double ratio); + + // introduced virtual methods: + virtual QCPPainter *startPainting() = 0; + virtual void donePainting() {} + virtual void draw(QCPPainter *painter) const = 0; + virtual void clear(const QColor &color) = 0; + +protected: + // property members: + QSize mSize; + double mDevicePixelRatio; + + // non-property members: + bool mInvalidated; + + // introduced virtual methods: + virtual void reallocateBuffer() = 0; +}; + + +class QCP_LIB_DECL QCPPaintBufferPixmap : public QCPAbstractPaintBuffer +{ +public: + explicit QCPPaintBufferPixmap(const QSize &size, double devicePixelRatio); + virtual ~QCPPaintBufferPixmap(); + + // reimplemented virtual methods: + virtual QCPPainter *startPainting() Q_DECL_OVERRIDE; + virtual void draw(QCPPainter *painter) const Q_DECL_OVERRIDE; + void clear(const QColor &color) Q_DECL_OVERRIDE; + +protected: + // non-property members: + QPixmap mBuffer; + + // reimplemented virtual methods: + virtual void reallocateBuffer() Q_DECL_OVERRIDE; +}; + + +#ifdef QCP_OPENGL_PBUFFER +class QCP_LIB_DECL QCPPaintBufferGlPbuffer : public QCPAbstractPaintBuffer +{ +public: + explicit QCPPaintBufferGlPbuffer(const QSize &size, double devicePixelRatio, int multisamples); + virtual ~QCPPaintBufferGlPbuffer(); + + // reimplemented virtual methods: + virtual QCPPainter *startPainting() Q_DECL_OVERRIDE; + virtual void draw(QCPPainter *painter) const Q_DECL_OVERRIDE; + void clear(const QColor &color) Q_DECL_OVERRIDE; + +protected: + // non-property members: + QGLPixelBuffer *mGlPBuffer; + int mMultisamples; + + // reimplemented virtual methods: + virtual void reallocateBuffer() Q_DECL_OVERRIDE; +}; +#endif // QCP_OPENGL_PBUFFER + + +#ifdef QCP_OPENGL_FBO +class QCP_LIB_DECL QCPPaintBufferGlFbo : public QCPAbstractPaintBuffer +{ +public: + explicit QCPPaintBufferGlFbo(const QSize &size, double devicePixelRatio, QWeakPointer glContext, QWeakPointer glPaintDevice); + virtual ~QCPPaintBufferGlFbo(); + + // reimplemented virtual methods: + virtual QCPPainter *startPainting() Q_DECL_OVERRIDE; + virtual void donePainting() Q_DECL_OVERRIDE; + virtual void draw(QCPPainter *painter) const Q_DECL_OVERRIDE; + void clear(const QColor &color) Q_DECL_OVERRIDE; + +protected: + // non-property members: + QWeakPointer mGlContext; + QWeakPointer mGlPaintDevice; + QOpenGLFramebufferObject *mGlFrameBuffer; + + // reimplemented virtual methods: + virtual void reallocateBuffer() Q_DECL_OVERRIDE; +}; +#endif // QCP_OPENGL_FBO + +/* end of 'src/paintbuffer.h' */ + + +/* including file 'src/layer.h', size 6885 */ +/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */ class QCP_LIB_DECL QCPLayer : public QObject { @@ -371,10 +626,24 @@ class QCP_LIB_DECL QCPLayer : public QObject Q_PROPERTY(int index READ index) Q_PROPERTY(QList children READ children) Q_PROPERTY(bool visible READ visible WRITE setVisible) + Q_PROPERTY(LayerMode mode READ mode WRITE setMode) /// \endcond public: + + /*! + Defines the different rendering modes of a layer. Depending on the mode, certain layers can be + replotted individually, without the need to replot (possibly complex) layerables on other + layers. + + \see setMode + */ + enum LayerMode { lmLogical ///< Layer is used only for rendering order, and shares paint buffer with all other adjacent logical layers. + ,lmBuffered ///< Layer has its own paint buffer and may be replotted individually (see \ref replot). + }; + Q_ENUMS(LayerMode) + QCPLayer(QCustomPlot* parentPlot, const QString &layerName); - ~QCPLayer(); + virtual ~QCPLayer(); // getters: QCustomPlot *parentPlot() const { return mParentPlot; } @@ -382,9 +651,14 @@ public: int index() const { return mIndex; } QList children() const { return mChildren; } bool visible() const { return mVisible; } + LayerMode mode() const { return mMode; } // setters: void setVisible(bool visible); + void setMode(LayerMode mode); + + // non-virtual methods: + void replot(); protected: // property members: @@ -393,8 +667,14 @@ protected: int mIndex; QList mChildren; bool mVisible; + LayerMode mMode; + + // non-property members: + QWeakPointer mPaintBuffer; // non-virtual methods: + void draw(QCPPainter *painter); + void drawToPaintBuffer(); void addChild(QCPLayerable *layerable, bool prepend); void removeChild(QCPLayerable *layerable); @@ -404,6 +684,7 @@ private: friend class QCustomPlot; friend class QCPLayerable; }; +Q_DECLARE_METATYPE(QCPLayer::LayerMode) class QCP_LIB_DECL QCPLayerable : public QObject { @@ -417,7 +698,7 @@ class QCP_LIB_DECL QCPLayerable : public QObject /// \endcond public: QCPLayerable(QCustomPlot *plot, QString targetLayer=QString(), QCPLayerable *parentLayerable=0); - ~QCPLayerable(); + virtual ~QCPLayerable(); // getters: bool visible() const { return mVisible; } @@ -434,7 +715,7 @@ public: // introduced virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; - + // non-property methods: bool realVisibility() const; @@ -455,9 +736,15 @@ protected: virtual QRect clipRect() const; virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const = 0; virtual void draw(QCPPainter *painter) = 0; - // events: + // selection events: virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged); virtual void deselectEvent(bool *selectionStateChanged); + // low-level mouse events: + virtual void mousePressEvent(QMouseEvent *event, const QVariant &details); + virtual void mouseMoveEvent(QMouseEvent *event, const QPointF &startPos); + virtual void mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos); + virtual void mouseDoubleClickEvent(QMouseEvent *event, const QVariant &details); + virtual void wheelEvent(QWheelEvent *event); // non-property methods: void initializeParentPlot(QCustomPlot *parentPlot); @@ -469,9 +756,15 @@ private: Q_DISABLE_COPY(QCPLayerable) friend class QCustomPlot; + friend class QCPLayer; friend class QCPAxisRect; }; +/* end of 'src/layer.h' */ + + +/* including file 'src/axis/range.h', size 5280 */ +/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */ class QCP_LIB_DECL QCPRange { @@ -495,46 +788,35 @@ public: friend inline const QCPRange operator*(double value, const QCPRange& range); friend inline const QCPRange operator/(const QCPRange& range, double value); - double size() const; - double center() const; - void normalize(); + double size() const { return upper-lower; } + double center() const { return (upper+lower)*0.5; } + void normalize() { if (lower > upper) qSwap(lower, upper); } void expand(const QCPRange &otherRange); + void expand(double includeCoord); QCPRange expanded(const QCPRange &otherRange) const; + QCPRange expanded(double includeCoord) const; + QCPRange bounded(double lowerBound, double upperBound) const; QCPRange sanitizedForLogScale() const; QCPRange sanitizedForLinScale() const; - bool contains(double value) const; + bool contains(double value) const { return value >= lower && value <= upper; } static bool validRange(double lower, double upper); static bool validRange(const QCPRange &range); - static const double minRange; //1e-280; - static const double maxRange; //1e280; + static const double minRange; + static const double maxRange; }; Q_DECLARE_TYPEINFO(QCPRange, Q_MOVABLE_TYPE); -/* documentation of inline functions */ +/*! \relates QCPRange -/*! \fn QCPRange &QCPRange::operator+=(const double& value) - - Adds \a value to both boundaries of the range. + Prints \a range in a human readable format to the qDebug output. */ - -/*! \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 documentation of inline functions */ +inline QDebug operator<< (QDebug d, const QCPRange &range) +{ + d.nospace() << "QCPRange(" << range.lower << ", " << range.upper << ")"; + return d.space(); +} /*! Adds \a value to both boundaries of the range. @@ -596,13 +878,276 @@ inline const QCPRange operator/(const QCPRange& range, double value) return result; } +/* end of 'src/axis/range.h' */ + + +/* including file 'src/selection.h', size 8579 */ +/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */ + +class QCP_LIB_DECL QCPDataRange +{ +public: + QCPDataRange(); + QCPDataRange(int begin, int end); + + bool operator==(const QCPDataRange& other) const { return mBegin == other.mBegin && mEnd == other.mEnd; } + bool operator!=(const QCPDataRange& other) const { return !(*this == other); } + + // getters: + int begin() const { return mBegin; } + int end() const { return mEnd; } + int size() const { return mEnd-mBegin; } + int length() const { return size(); } + + // setters: + void setBegin(int begin) { mBegin = begin; } + void setEnd(int end) { mEnd = end; } + + // non-property methods: + bool isValid() const { return (mEnd >= mBegin) && (mBegin >= 0); } + bool isEmpty() const { return length() == 0; } + QCPDataRange bounded(const QCPDataRange &other) const; + QCPDataRange expanded(const QCPDataRange &other) const; + QCPDataRange intersection(const QCPDataRange &other) const; + QCPDataRange adjusted(int changeBegin, int changeEnd) const { return QCPDataRange(mBegin+changeBegin, mEnd+changeEnd); } + bool intersects(const QCPDataRange &other) const; + bool contains(const QCPDataRange &other) const; + +private: + // property members: + int mBegin, mEnd; + +}; +Q_DECLARE_TYPEINFO(QCPDataRange, Q_MOVABLE_TYPE); + + +class QCP_LIB_DECL QCPDataSelection +{ +public: + explicit QCPDataSelection(); + explicit QCPDataSelection(const QCPDataRange &range); + + bool operator==(const QCPDataSelection& other) const; + bool operator!=(const QCPDataSelection& other) const { return !(*this == other); } + QCPDataSelection &operator+=(const QCPDataSelection& other); + QCPDataSelection &operator+=(const QCPDataRange& other); + QCPDataSelection &operator-=(const QCPDataSelection& other); + QCPDataSelection &operator-=(const QCPDataRange& other); + friend inline const QCPDataSelection operator+(const QCPDataSelection& a, const QCPDataSelection& b); + friend inline const QCPDataSelection operator+(const QCPDataRange& a, const QCPDataSelection& b); + friend inline const QCPDataSelection operator+(const QCPDataSelection& a, const QCPDataRange& b); + friend inline const QCPDataSelection operator+(const QCPDataRange& a, const QCPDataRange& b); + friend inline const QCPDataSelection operator-(const QCPDataSelection& a, const QCPDataSelection& b); + friend inline const QCPDataSelection operator-(const QCPDataRange& a, const QCPDataSelection& b); + friend inline const QCPDataSelection operator-(const QCPDataSelection& a, const QCPDataRange& b); + friend inline const QCPDataSelection operator-(const QCPDataRange& a, const QCPDataRange& b); + + // getters: + int dataRangeCount() const { return mDataRanges.size(); } + int dataPointCount() const; + QCPDataRange dataRange(int index=0) const; + QList dataRanges() const { return mDataRanges; } + QCPDataRange span() const; + + // non-property methods: + void addDataRange(const QCPDataRange &dataRange, bool simplify=true); + void clear(); + bool isEmpty() const { return mDataRanges.isEmpty(); } + void simplify(); + void enforceType(QCP::SelectionType type); + bool contains(const QCPDataSelection &other) const; + QCPDataSelection intersection(const QCPDataRange &other) const; + QCPDataSelection intersection(const QCPDataSelection &other) const; + QCPDataSelection inverse(const QCPDataRange &outerRange) const; + +private: + // property members: + QList mDataRanges; + + inline static bool lessThanDataRangeBegin(const QCPDataRange &a, const QCPDataRange &b) { return a.begin() < b.begin(); } +}; +Q_DECLARE_METATYPE(QCPDataSelection) + + +/*! + Return a \ref QCPDataSelection with the data points in \a a joined with the data points in \a b. + The resulting data selection is already simplified (see \ref QCPDataSelection::simplify). +*/ +inline const QCPDataSelection operator+(const QCPDataSelection& a, const QCPDataSelection& b) +{ + QCPDataSelection result(a); + result += b; + return result; +} + +/*! + Return a \ref QCPDataSelection with the data points in \a a joined with the data points in \a b. + The resulting data selection is already simplified (see \ref QCPDataSelection::simplify). +*/ +inline const QCPDataSelection operator+(const QCPDataRange& a, const QCPDataSelection& b) +{ + QCPDataSelection result(a); + result += b; + return result; +} + +/*! + Return a \ref QCPDataSelection with the data points in \a a joined with the data points in \a b. + The resulting data selection is already simplified (see \ref QCPDataSelection::simplify). +*/ +inline const QCPDataSelection operator+(const QCPDataSelection& a, const QCPDataRange& b) +{ + QCPDataSelection result(a); + result += b; + return result; +} + +/*! + Return a \ref QCPDataSelection with the data points in \a a joined with the data points in \a b. + The resulting data selection is already simplified (see \ref QCPDataSelection::simplify). +*/ +inline const QCPDataSelection operator+(const QCPDataRange& a, const QCPDataRange& b) +{ + QCPDataSelection result(a); + result += b; + return result; +} + +/*! + Return a \ref QCPDataSelection with the data points which are in \a a but not in \a b. +*/ +inline const QCPDataSelection operator-(const QCPDataSelection& a, const QCPDataSelection& b) +{ + QCPDataSelection result(a); + result -= b; + return result; +} + +/*! + Return a \ref QCPDataSelection with the data points which are in \a a but not in \a b. +*/ +inline const QCPDataSelection operator-(const QCPDataRange& a, const QCPDataSelection& b) +{ + QCPDataSelection result(a); + result -= b; + return result; +} + +/*! + Return a \ref QCPDataSelection with the data points which are in \a a but not in \a b. +*/ +inline const QCPDataSelection operator-(const QCPDataSelection& a, const QCPDataRange& b) +{ + QCPDataSelection result(a); + result -= b; + return result; +} + +/*! + Return a \ref QCPDataSelection with the data points which are in \a a but not in \a b. +*/ +inline const QCPDataSelection operator-(const QCPDataRange& a, const QCPDataRange& b) +{ + QCPDataSelection result(a); + result -= b; + return result; +} + +/*! \relates QCPDataRange + + Prints \a dataRange in a human readable format to the qDebug output. +*/ +inline QDebug operator<< (QDebug d, const QCPDataRange &dataRange) +{ + d.nospace() << "[" << dataRange.begin() << ".." << dataRange.end()-1 << "]"; + return d.space(); +} + +/*! \relates QCPDataSelection + + Prints \a selection in a human readable format to the qDebug output. +*/ +inline QDebug operator<< (QDebug d, const QCPDataSelection &selection) +{ + d.nospace() << "QCPDataSelection("; + for (int i=0; i elements(QCP::MarginSide side) const { return mChildren.value(side); } @@ -614,8 +1159,10 @@ protected: QCustomPlot *mParentPlot; QHash > mChildren; + // introduced virtual methods: + virtual int commonMargin(QCP::MarginSide side) const; + // non-virtual methods: - int commonMargin(QCP::MarginSide side) const; void addChild(QCP::MarginSide side, QCPLayoutElement *element); void removeChild(QCP::MarginSide side, QCPLayoutElement *element); @@ -682,7 +1229,7 @@ public: virtual QList elements(bool recursive) const; // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const Q_DECL_OVERRIDE; protected: // property members: @@ -695,17 +1242,12 @@ protected: // introduced virtual methods: virtual int calculateAutoMargin(QCP::MarginSide side); - // events: - virtual void mousePressEvent(QMouseEvent *event) {Q_UNUSED(event)} - virtual void mouseMoveEvent(QMouseEvent *event) {Q_UNUSED(event)} - virtual void mouseReleaseEvent(QMouseEvent *event) {Q_UNUSED(event)} - virtual void mouseDoubleClickEvent(QMouseEvent *event) {Q_UNUSED(event)} - virtual void wheelEvent(QWheelEvent *event) {Q_UNUSED(event)} + virtual void layoutChanged(); // reimplemented virtual methods: - virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const { Q_UNUSED(painter) } - virtual void draw(QCPPainter *painter) { Q_UNUSED(painter) } - virtual void parentPlotInitialized(QCustomPlot *parentPlot); + virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const Q_DECL_OVERRIDE { Q_UNUSED(painter) } + virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE { Q_UNUSED(painter) } + virtual void parentPlotInitialized(QCustomPlot *parentPlot) Q_DECL_OVERRIDE; private: Q_DISABLE_COPY(QCPLayoutElement) @@ -714,6 +1256,7 @@ private: friend class QCPLayout; friend class QCPMarginGroup; }; +Q_DECLARE_METATYPE(QCPLayoutElement::UpdatePhase) class QCP_LIB_DECL QCPLayout : public QCPLayoutElement @@ -723,8 +1266,8 @@ public: explicit QCPLayout(); // reimplemented virtual methods: - virtual void update(UpdatePhase phase); - virtual QList elements(bool recursive) const; + virtual void update(UpdatePhase phase) Q_DECL_OVERRIDE; + virtual QList elements(bool recursive) const Q_DECL_OVERRIDE; // introduced virtual methods: virtual int elementCount() const = 0; @@ -764,18 +1307,35 @@ class QCP_LIB_DECL QCPLayoutGrid : public QCPLayout Q_PROPERTY(QList rowStretchFactors READ rowStretchFactors WRITE setRowStretchFactors) Q_PROPERTY(int columnSpacing READ columnSpacing WRITE setColumnSpacing) Q_PROPERTY(int rowSpacing READ rowSpacing WRITE setRowSpacing) + Q_PROPERTY(FillOrder fillOrder READ fillOrder WRITE setFillOrder) + Q_PROPERTY(int wrap READ wrap WRITE setWrap) /// \endcond public: + + /*! + Defines in which direction the grid is filled when using \ref addElement(QCPLayoutElement*). + The column/row at which wrapping into the next row/column occurs can be specified with \ref + setWrap. + + \see setFillOrder + */ + enum FillOrder { foRowsFirst ///< Rows are filled first, and a new element is wrapped to the next column if the row count would exceed \ref setWrap. + ,foColumnsFirst ///< Columns are filled first, and a new element is wrapped to the next row if the column count would exceed \ref setWrap. + }; + Q_ENUMS(FillOrder) + explicit QCPLayoutGrid(); virtual ~QCPLayoutGrid(); // getters: - int rowCount() const; - int columnCount() const; + int rowCount() const { return mElements.size(); } + int columnCount() const { return mElements.size() > 0 ? mElements.first().size() : 0; } QList columnStretchFactors() const { return mColumnStretchFactors; } QList rowStretchFactors() const { return mRowStretchFactors; } int columnSpacing() const { return mColumnSpacing; } int rowSpacing() const { return mRowSpacing; } + int wrap() const { return mWrap; } + FillOrder fillOrder() const { return mFillOrder; } // setters: void setColumnStretchFactor(int column, double factor); @@ -784,25 +1344,30 @@ public: void setRowStretchFactors(const QList &factors); void setColumnSpacing(int pixels); void setRowSpacing(int pixels); + void setWrap(int count); + void setFillOrder(FillOrder order, bool rearrange=true); // reimplemented virtual methods: - virtual void updateLayout(); - virtual int elementCount() const; - virtual QCPLayoutElement* elementAt(int index) const; - virtual QCPLayoutElement* takeAt(int index); - virtual bool take(QCPLayoutElement* element); - virtual QList elements(bool recursive) const; - virtual void simplify(); - virtual QSize minimumSizeHint() const; - virtual QSize maximumSizeHint() const; + virtual void updateLayout() Q_DECL_OVERRIDE; + virtual int elementCount() const Q_DECL_OVERRIDE { return rowCount()*columnCount(); } + virtual QCPLayoutElement* elementAt(int index) const Q_DECL_OVERRIDE; + virtual QCPLayoutElement* takeAt(int index) Q_DECL_OVERRIDE; + virtual bool take(QCPLayoutElement* element) Q_DECL_OVERRIDE; + virtual QList elements(bool recursive) const Q_DECL_OVERRIDE; + virtual void simplify() Q_DECL_OVERRIDE; + virtual QSize minimumSizeHint() const Q_DECL_OVERRIDE; + virtual QSize maximumSizeHint() const Q_DECL_OVERRIDE; // non-virtual methods: QCPLayoutElement *element(int row, int column) const; bool addElement(int row, int column, QCPLayoutElement *element); + bool addElement(QCPLayoutElement *element); bool hasElement(int row, int column); void expandTo(int newRowCount, int newColumnCount); void insertRow(int newIndex); void insertColumn(int newIndex); + int rowColToIndex(int row, int column) const; + void indexToRowCol(int index, int &row, int &column) const; protected: // property members: @@ -810,6 +1375,8 @@ protected: QList mColumnStretchFactors; QList mRowStretchFactors; int mColumnSpacing, mRowSpacing; + int mWrap; + FillOrder mFillOrder; // non-virtual methods: void getMinimumRowColSizes(QVector *minColWidths, QVector *minRowHeights) const; @@ -818,6 +1385,7 @@ protected: private: Q_DISABLE_COPY(QCPLayoutGrid) }; +Q_DECLARE_METATYPE(QCPLayoutGrid::FillOrder) class QCP_LIB_DECL QCPLayoutInset : public QCPLayout @@ -830,6 +1398,7 @@ public: enum InsetPlacement { ipFree ///< The element may be positioned/sized arbitrarily, see \ref setInsetRect ,ipBorderAligned ///< The element is aligned to one of the layout sides, see \ref setInsetAlignment }; + Q_ENUMS(InsetPlacement) explicit QCPLayoutInset(); virtual ~QCPLayoutInset(); @@ -845,13 +1414,13 @@ public: void setInsetRect(int index, const QRectF &rect); // reimplemented virtual methods: - virtual void updateLayout(); - virtual int elementCount() const; - virtual QCPLayoutElement* elementAt(int index) const; - virtual QCPLayoutElement* takeAt(int index); - virtual bool take(QCPLayoutElement* element); - virtual void simplify() {} - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; + virtual void updateLayout() Q_DECL_OVERRIDE; + virtual int elementCount() const Q_DECL_OVERRIDE; + virtual QCPLayoutElement* elementAt(int index) const Q_DECL_OVERRIDE; + virtual QCPLayoutElement* takeAt(int index) Q_DECL_OVERRIDE; + virtual bool take(QCPLayoutElement* element) Q_DECL_OVERRIDE; + virtual void simplify() Q_DECL_OVERRIDE {} + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const Q_DECL_OVERRIDE; // non-virtual methods: void addElement(QCPLayoutElement *element, Qt::Alignment alignment); @@ -867,7 +1436,13 @@ protected: private: Q_DISABLE_COPY(QCPLayoutInset) }; +Q_DECLARE_METATYPE(QCPLayoutInset::InsetPlacement) +/* end of 'src/layout.h' */ + + +/* including file 'src/lineending.h', size 4426 */ +/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */ class QCP_LIB_DECL QCPLineEnding { @@ -884,18 +1459,18 @@ public: \see QCPItemLine::setHead, QCPItemLine::setTail, QCPItemCurve::setHead, QCPItemCurve::setTail, QCPAxis::setLowerEnding, QCPAxis::setUpperEnding */ - Q_ENUMS(EndingStyle) enum EndingStyle { esNone ///< No ending decoration ,esFlatArrow ///< A filled arrow head with a straight/flat back (a triangle) ,esSpikeArrow ///< A filled arrow head with an indented back ,esLineArrow ///< A non-filled arrow head with open back ,esDisc ///< A filled circle ,esSquare ///< A filled square - ,esDiamond ///< A filled diamond (45° rotated square) + ,esDiamond ///< A filled diamond (45 degrees rotated square) ,esBar ///< A bar perpendicular to the line ,esHalfBar ///< A bar perpendicular to the line, pointing out to only one side (to which side can be changed with \ref setInverted) ,esSkewedBar ///< A bar that is skewed (skew controllable via \ref setLength) }; + Q_ENUMS(EndingStyle) QCPLineEnding(); QCPLineEnding(EndingStyle style, double width=8, double length=10, bool inverted=false); @@ -915,8 +1490,8 @@ public: // non-property methods: double boundingDistance() const; double realLength() const; - void draw(QCPPainter *painter, const QVector2D &pos, const QVector2D &dir) const; - void draw(QCPPainter *painter, const QVector2D &pos, double angle) const; + void draw(QCPPainter *painter, const QCPVector2D &pos, const QCPVector2D &dir) const; + void draw(QCPPainter *painter, const QCPVector2D &pos, double angle) const; protected: // property members: @@ -925,7 +1500,340 @@ protected: bool mInverted; }; Q_DECLARE_TYPEINFO(QCPLineEnding, Q_MOVABLE_TYPE); +Q_DECLARE_METATYPE(QCPLineEnding::EndingStyle) +/* end of 'src/lineending.h' */ + + +/* including file 'src/axis/axisticker.h', size 4177 */ +/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */ + +class QCP_LIB_DECL QCPAxisTicker +{ + Q_GADGET +public: + /*! + Defines the strategies that the axis ticker may follow when choosing the size of the tick step. + + \see setTickStepStrategy + */ + enum TickStepStrategy + { + tssReadability ///< A nicely readable tick step is prioritized over matching the requested number of ticks (see \ref setTickCount) + ,tssMeetTickCount ///< Less readable tick steps are allowed which in turn facilitates getting closer to the requested tick count + }; + Q_ENUMS(TickStepStrategy) + + QCPAxisTicker(); + virtual ~QCPAxisTicker(); + + // getters: + TickStepStrategy tickStepStrategy() const { return mTickStepStrategy; } + int tickCount() const { return mTickCount; } + double tickOrigin() const { return mTickOrigin; } + + // setters: + void setTickStepStrategy(TickStepStrategy strategy); + void setTickCount(int count); + void setTickOrigin(double origin); + + // introduced virtual methods: + virtual void generate(const QCPRange &range, const QLocale &locale, QChar formatChar, int precision, QVector &ticks, QVector *subTicks, QVector *tickLabels); + +protected: + // property members: + TickStepStrategy mTickStepStrategy; + int mTickCount; + double mTickOrigin; + + // introduced virtual methods: + virtual double getTickStep(const QCPRange &range); + virtual int getSubTickCount(double tickStep); + virtual QString getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision); + virtual QVector createTickVector(double tickStep, const QCPRange &range); + virtual QVector createSubTickVector(int subTickCount, const QVector &ticks); + virtual QVector createLabelVector(const QVector &ticks, const QLocale &locale, QChar formatChar, int precision); + + // non-virtual methods: + void trimTicks(const QCPRange &range, QVector &ticks, bool keepOneOutlier) const; + double pickClosest(double target, const QVector &candidates) const; + double getMantissa(double input, double *magnitude=0) const; + double cleanMantissa(double input) const; +}; +Q_DECLARE_METATYPE(QCPAxisTicker::TickStepStrategy) +Q_DECLARE_METATYPE(QSharedPointer) + +/* end of 'src/axis/axisticker.h' */ + + +/* including file 'src/axis/axistickerdatetime.h', size 3289 */ +/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */ + +class QCP_LIB_DECL QCPAxisTickerDateTime : public QCPAxisTicker +{ +public: + QCPAxisTickerDateTime(); + + // getters: + QString dateTimeFormat() const { return mDateTimeFormat; } + Qt::TimeSpec dateTimeSpec() const { return mDateTimeSpec; } + + // setters: + void setDateTimeFormat(const QString &format); + void setDateTimeSpec(Qt::TimeSpec spec); + void setTickOrigin(double origin); // hides base class method but calls baseclass implementation ("using" throws off IDEs and doxygen) + void setTickOrigin(const QDateTime &origin); + + // static methods: + static QDateTime keyToDateTime(double key); + static double dateTimeToKey(const QDateTime dateTime); + static double dateTimeToKey(const QDate date); + +protected: + // property members: + QString mDateTimeFormat; + Qt::TimeSpec mDateTimeSpec; + + // non-property members: + enum DateStrategy {dsNone, dsUniformTimeInDay, dsUniformDayInMonth} mDateStrategy; + + // reimplemented virtual methods: + virtual double getTickStep(const QCPRange &range) Q_DECL_OVERRIDE; + virtual int getSubTickCount(double tickStep) Q_DECL_OVERRIDE; + virtual QString getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision) Q_DECL_OVERRIDE; + virtual QVector createTickVector(double tickStep, const QCPRange &range) Q_DECL_OVERRIDE; +}; + +/* end of 'src/axis/axistickerdatetime.h' */ + + +/* including file 'src/axis/axistickertime.h', size 3288 */ +/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */ + +class QCP_LIB_DECL QCPAxisTickerTime : public QCPAxisTicker +{ + Q_GADGET +public: + /*! + Defines the logical units in which fractions of time spans can be expressed. + + \see setFieldWidth, setTimeFormat + */ + enum TimeUnit { tuMilliseconds + ,tuSeconds + ,tuMinutes + ,tuHours + ,tuDays + }; + Q_ENUMS(TimeUnit) + + QCPAxisTickerTime(); + + // getters: + QString timeFormat() const { return mTimeFormat; } + int fieldWidth(TimeUnit unit) const { return mFieldWidth.value(unit); } + + // setters: + void setTimeFormat(const QString &format); + void setFieldWidth(TimeUnit unit, int width); + +protected: + // property members: + QString mTimeFormat; + QHash mFieldWidth; + + // non-property members: + TimeUnit mSmallestUnit, mBiggestUnit; + QHash mFormatPattern; + + // reimplemented virtual methods: + virtual double getTickStep(const QCPRange &range) Q_DECL_OVERRIDE; + virtual int getSubTickCount(double tickStep) Q_DECL_OVERRIDE; + virtual QString getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision) Q_DECL_OVERRIDE; + + // non-virtual methods: + void replaceUnit(QString &text, TimeUnit unit, int value) const; +}; +Q_DECLARE_METATYPE(QCPAxisTickerTime::TimeUnit) + +/* end of 'src/axis/axistickertime.h' */ + + +/* including file 'src/axis/axistickerfixed.h', size 3308 */ +/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */ + +class QCP_LIB_DECL QCPAxisTickerFixed : public QCPAxisTicker +{ + Q_GADGET +public: + /*! + Defines how the axis ticker may modify the specified tick step (\ref setTickStep) in order to + control the number of ticks in the axis range. + + \see setScaleStrategy + */ + enum ScaleStrategy { ssNone ///< Modifications are not allowed, the specified tick step is absolutely fixed. This might cause a high tick density and overlapping labels if the axis range is zoomed out. + ,ssMultiples ///< An integer multiple of the specified tick step is allowed. The used factor follows the base class properties of \ref setTickStepStrategy and \ref setTickCount. + ,ssPowers ///< An integer power of the specified tick step is allowed. + }; + Q_ENUMS(ScaleStrategy) + + QCPAxisTickerFixed(); + + // getters: + double tickStep() const { return mTickStep; } + ScaleStrategy scaleStrategy() const { return mScaleStrategy; } + + // setters: + void setTickStep(double step); + void setScaleStrategy(ScaleStrategy strategy); + +protected: + // property members: + double mTickStep; + ScaleStrategy mScaleStrategy; + + // reimplemented virtual methods: + virtual double getTickStep(const QCPRange &range) Q_DECL_OVERRIDE; +}; +Q_DECLARE_METATYPE(QCPAxisTickerFixed::ScaleStrategy) + +/* end of 'src/axis/axistickerfixed.h' */ + + +/* including file 'src/axis/axistickertext.h', size 3085 */ +/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */ + +class QCP_LIB_DECL QCPAxisTickerText : public QCPAxisTicker +{ +public: + QCPAxisTickerText(); + + // getters: + QMap &ticks() { return mTicks; } + int subTickCount() const { return mSubTickCount; } + + // setters: + void setTicks(const QMap &ticks); + void setTicks(const QVector &positions, const QVector labels); + void setSubTickCount(int subTicks); + + // non-virtual methods: + void clear(); + void addTick(double position, QString label); + void addTicks(const QMap &ticks); + void addTicks(const QVector &positions, const QVector &labels); + +protected: + // property members: + QMap mTicks; + int mSubTickCount; + + // reimplemented virtual methods: + virtual double getTickStep(const QCPRange &range) Q_DECL_OVERRIDE; + virtual int getSubTickCount(double tickStep) Q_DECL_OVERRIDE; + virtual QString getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision) Q_DECL_OVERRIDE; + virtual QVector createTickVector(double tickStep, const QCPRange &range) Q_DECL_OVERRIDE; + +}; + +/* end of 'src/axis/axistickertext.h' */ + + +/* including file 'src/axis/axistickerpi.h', size 3911 */ +/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */ + +class QCP_LIB_DECL QCPAxisTickerPi : public QCPAxisTicker +{ + Q_GADGET +public: + /*! + Defines how fractions should be displayed in tick labels. + + \see setFractionStyle + */ + enum FractionStyle { fsFloatingPoint ///< Fractions are displayed as regular decimal floating point numbers, e.g. "0.25" or "0.125". + ,fsAsciiFractions ///< Fractions are written as rationals using ASCII characters only, e.g. "1/4" or "1/8" + ,fsUnicodeFractions ///< Fractions are written using sub- and superscript UTF-8 digits and the fraction symbol. + }; + Q_ENUMS(FractionStyle) + + QCPAxisTickerPi(); + + // getters: + QString piSymbol() const { return mPiSymbol; } + double piValue() const { return mPiValue; } + bool periodicity() const { return mPeriodicity; } + FractionStyle fractionStyle() const { return mFractionStyle; } + + // setters: + void setPiSymbol(QString symbol); + void setPiValue(double pi); + void setPeriodicity(int multiplesOfPi); + void setFractionStyle(FractionStyle style); + +protected: + // property members: + QString mPiSymbol; + double mPiValue; + int mPeriodicity; + FractionStyle mFractionStyle; + + // non-property members: + double mPiTickStep; // size of one tick step in units of mPiValue + + // reimplemented virtual methods: + virtual double getTickStep(const QCPRange &range) Q_DECL_OVERRIDE; + virtual int getSubTickCount(double tickStep) Q_DECL_OVERRIDE; + virtual QString getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision) Q_DECL_OVERRIDE; + + // non-virtual methods: + void simplifyFraction(int &numerator, int &denominator) const; + QString fractionToString(int numerator, int denominator) const; + QString unicodeFraction(int numerator, int denominator) const; + QString unicodeSuperscript(int number) const; + QString unicodeSubscript(int number) const; +}; +Q_DECLARE_METATYPE(QCPAxisTickerPi::FractionStyle) + +/* end of 'src/axis/axistickerpi.h' */ + + +/* including file 'src/axis/axistickerlog.h', size 2663 */ +/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */ + +class QCP_LIB_DECL QCPAxisTickerLog : public QCPAxisTicker +{ +public: + QCPAxisTickerLog(); + + // getters: + double logBase() const { return mLogBase; } + int subTickCount() const { return mSubTickCount; } + + // setters: + void setLogBase(double base); + void setSubTickCount(int subTicks); + +protected: + // property members: + double mLogBase; + int mSubTickCount; + + // non-property members: + double mLogBaseLnInv; + + // reimplemented virtual methods: + virtual double getTickStep(const QCPRange &range) Q_DECL_OVERRIDE; + virtual int getSubTickCount(double tickStep) Q_DECL_OVERRIDE; + virtual QVector createTickVector(double tickStep, const QCPRange &range) Q_DECL_OVERRIDE; +}; + +/* end of 'src/axis/axistickerlog.h' */ + + +/* including file 'src/axis/axis.h', size 20230 */ +/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */ class QCP_LIB_DECL QCPGrid :public QCPLayerable { @@ -939,7 +1847,7 @@ class QCP_LIB_DECL QCPGrid :public QCPLayerable Q_PROPERTY(QPen zeroLinePen READ zeroLinePen WRITE setZeroLinePen) /// \endcond public: - QCPGrid(QCPAxis *parentAxis); + explicit QCPGrid(QCPAxis *parentAxis); // getters: bool subGridVisible() const { return mSubGridVisible; } @@ -962,12 +1870,13 @@ protected: bool mSubGridVisible; bool mAntialiasedSubGrid, mAntialiasedZeroLine; QPen mPen, mSubGridPen, mZeroLinePen; + // non-property members: QCPAxis *mParentAxis; // reimplemented virtual methods: - virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const; - virtual void draw(QCPPainter *painter); + virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const Q_DECL_OVERRIDE; + virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; // non-virtual methods: void drawGridLines(QCPPainter *painter) const; @@ -984,32 +1893,23 @@ class QCP_LIB_DECL QCPAxis : public QCPLayerable Q_PROPERTY(AxisType axisType READ axisType) Q_PROPERTY(QCPAxisRect* axisRect READ axisRect) Q_PROPERTY(ScaleType scaleType READ scaleType WRITE setScaleType NOTIFY scaleTypeChanged) - Q_PROPERTY(double scaleLogBase READ scaleLogBase WRITE setScaleLogBase) Q_PROPERTY(QCPRange range READ range WRITE setRange NOTIFY rangeChanged) Q_PROPERTY(bool rangeReversed READ rangeReversed WRITE setRangeReversed) - Q_PROPERTY(bool autoTicks READ autoTicks WRITE setAutoTicks) - Q_PROPERTY(int autoTickCount READ autoTickCount WRITE setAutoTickCount) - Q_PROPERTY(bool autoTickLabels READ autoTickLabels WRITE setAutoTickLabels) - Q_PROPERTY(bool autoTickStep READ autoTickStep WRITE setAutoTickStep) - Q_PROPERTY(bool autoSubTicks READ autoSubTicks WRITE setAutoSubTicks) + Q_PROPERTY(QSharedPointer ticker READ ticker WRITE setTicker) Q_PROPERTY(bool ticks READ ticks WRITE setTicks) Q_PROPERTY(bool tickLabels READ tickLabels WRITE setTickLabels) Q_PROPERTY(int tickLabelPadding READ tickLabelPadding WRITE setTickLabelPadding) - Q_PROPERTY(LabelType tickLabelType READ tickLabelType WRITE setTickLabelType) Q_PROPERTY(QFont tickLabelFont READ tickLabelFont WRITE setTickLabelFont) Q_PROPERTY(QColor tickLabelColor READ tickLabelColor WRITE setTickLabelColor) Q_PROPERTY(double tickLabelRotation READ tickLabelRotation WRITE setTickLabelRotation) Q_PROPERTY(LabelSide tickLabelSide READ tickLabelSide WRITE setTickLabelSide) - Q_PROPERTY(QString dateTimeFormat READ dateTimeFormat WRITE setDateTimeFormat) - Q_PROPERTY(Qt::TimeSpec dateTimeSpec READ dateTimeSpec WRITE setDateTimeSpec) Q_PROPERTY(QString numberFormat READ numberFormat WRITE setNumberFormat) Q_PROPERTY(int numberPrecision READ numberPrecision WRITE setNumberPrecision) - Q_PROPERTY(double tickStep READ tickStep WRITE setTickStep) - Q_PROPERTY(QVector tickVector READ tickVector WRITE setTickVector) - Q_PROPERTY(QVector tickVectorLabels READ tickVectorLabels WRITE setTickVectorLabels) + Q_PROPERTY(QVector tickVector READ tickVector) + Q_PROPERTY(QVector tickVectorLabels READ tickVectorLabels) Q_PROPERTY(int tickLengthIn READ tickLengthIn WRITE setTickLengthIn) Q_PROPERTY(int tickLengthOut READ tickLengthOut WRITE setTickLengthOut) - Q_PROPERTY(int subTickCount READ subTickCount WRITE setSubTickCount) + Q_PROPERTY(bool subTicks READ subTicks WRITE setSubTicks) Q_PROPERTY(int subTickLengthIn READ subTickLengthIn WRITE setSubTickLengthIn) Q_PROPERTY(int subTickLengthOut READ subTickLengthOut WRITE setSubTickLengthOut) Q_PROPERTY(QPen basePen READ basePen WRITE setBasePen) @@ -1044,18 +1944,9 @@ public: ,atTop = 0x04 ///< 0x04 Axis is horizontal and on the top side of the axis rect ,atBottom = 0x08 ///< 0x08 Axis is horizontal and on the bottom side of the axis rect }; - Q_FLAGS(AxisType AxisTypes) + Q_ENUMS(AxisType) + Q_FLAGS(AxisTypes) Q_DECLARE_FLAGS(AxisTypes, AxisType) - /*! - When automatic tick label generation is enabled (\ref setAutoTickLabels), defines how the - coordinate of the tick is interpreted, i.e. translated into a string. - - \see setTickLabelType - */ - enum LabelType { ltNumber ///< Tick coordinate is regarded as normal number and will be displayed as such. (see \ref setNumberFormat) - ,ltDateTime ///< Tick coordinate is regarded as a date/time (seconds since 1970-01-01T00:00:00 UTC) and will be displayed and formatted as such. (for details, see \ref setDateTimeFormat) - }; - Q_ENUMS(LabelType) /*! Defines on which side of the axis the tick labels (numbers) shall appear. @@ -1070,7 +1961,7 @@ public: \see setScaleType */ enum ScaleType { stLinear ///< Linear scaling - ,stLogarithmic ///< Logarithmic scaling with correspondingly transformed plots and (major) tick marks at every base power (see \ref setScaleLogBase). + ,stLogarithmic ///< Logarithmic scaling with correspondingly transformed axis coordinates (possibly also \ref setTicker to a \ref QCPAxisTickerLog instance). }; Q_ENUMS(ScaleType) /*! @@ -1082,7 +1973,8 @@ public: ,spTickLabels = 0x002 ///< Tick labels (numbers) of this axis (as a whole, not individually) ,spAxisLabel = 0x004 ///< The axis label }; - Q_FLAGS(SelectablePart SelectableParts) + Q_ENUMS(SelectablePart) + Q_FLAGS(SelectableParts) Q_DECLARE_FLAGS(SelectableParts, SelectablePart) explicit QCPAxis(QCPAxisRect *parent, AxisType type); @@ -1092,32 +1984,23 @@ public: AxisType axisType() const { return mAxisType; } QCPAxisRect *axisRect() const { return mAxisRect; } ScaleType scaleType() const { return mScaleType; } - double scaleLogBase() const { return mScaleLogBase; } const QCPRange range() const { return mRange; } bool rangeReversed() const { return mRangeReversed; } - bool autoTicks() const { return mAutoTicks; } - int autoTickCount() const { return mAutoTickCount; } - bool autoTickLabels() const { return mAutoTickLabels; } - bool autoTickStep() const { return mAutoTickStep; } - bool autoSubTicks() const { return mAutoSubTicks; } + QSharedPointer ticker() const { return mTicker; } bool ticks() const { return mTicks; } bool tickLabels() const { return mTickLabels; } int tickLabelPadding() const; - LabelType tickLabelType() const { return mTickLabelType; } QFont tickLabelFont() const { return mTickLabelFont; } QColor tickLabelColor() const { return mTickLabelColor; } double tickLabelRotation() const; LabelSide tickLabelSide() const; - QString dateTimeFormat() const { return mDateTimeFormat; } - Qt::TimeSpec dateTimeSpec() const { return mDateTimeSpec; } QString numberFormat() const; int numberPrecision() const { return mNumberPrecision; } - double tickStep() const { return mTickStep; } QVector tickVector() const { return mTickVector; } QVector tickVectorLabels() const { return mTickVectorLabels; } int tickLengthIn() const; int tickLengthOut() const; - int subTickCount() const { return mSubTickCount; } + bool subTicks() const { return mSubTicks; } int subTickLengthIn() const; int subTickLengthOut() const; QPen basePen() const { return mBasePen; } @@ -1144,37 +2027,26 @@ public: // setters: Q_SLOT void setScaleType(QCPAxis::ScaleType type); - void setScaleLogBase(double base); Q_SLOT void setRange(const QCPRange &range); void setRange(double lower, double upper); void setRange(double position, double size, Qt::AlignmentFlag alignment); void setRangeLower(double lower); void setRangeUpper(double upper); void setRangeReversed(bool reversed); - void setAutoTicks(bool on); - void setAutoTickCount(int approximateCount); - void setAutoTickLabels(bool on); - void setAutoTickStep(bool on); - void setAutoSubTicks(bool on); + void setTicker(QSharedPointer ticker); void setTicks(bool show); void setTickLabels(bool show); void setTickLabelPadding(int padding); - void setTickLabelType(LabelType type); void setTickLabelFont(const QFont &font); void setTickLabelColor(const QColor &color); void setTickLabelRotation(double degrees); void setTickLabelSide(LabelSide side); - void setDateTimeFormat(const QString &format); - void setDateTimeSpec(const Qt::TimeSpec &timeSpec); void setNumberFormat(const QString &formatCode); void setNumberPrecision(int precision); - void setTickStep(double step); - void setTickVector(const QVector &vec); - void setTickVectorLabels(const QVector &vec); void setTickLength(int inside, int outside=0); void setTickLengthIn(int inside); void setTickLengthOut(int outside); - void setSubTickCount(int count); + void setSubTicks(bool show); void setSubTickLength(int inside, int outside=0); void setSubTickLengthIn(int inside); void setSubTickLengthOut(int outside); @@ -1200,11 +2072,13 @@ public: void setUpperEnding(const QCPLineEnding &ending); // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const Q_DECL_OVERRIDE; // non-property methods: Qt::Orientation orientation() const { return mOrientation; } + int pixelOrientation() const { return rangeReversed() != (orientation()==Qt::Vertical) ? -1 : 1; } void moveRange(double diff); + void scaleRange(double factor); void scaleRange(double factor, double center); void setScaleRatio(const QCPAxis *otherAxis, double ratio=1.0); void rescale(bool onlyVisiblePlottables=false); @@ -1220,7 +2094,6 @@ public: static AxisType opposite(AxisType type); signals: - void ticksRequest(); void rangeChanged(const QCPRange &newRange); void rangeChanged(const QCPRange &newRange, const QCPRange &oldRange); void scaleTypeChanged(QCPAxis::ScaleType scaleType); @@ -1245,22 +2118,17 @@ protected: QColor mLabelColor, mSelectedLabelColor; // tick labels: //int mTickLabelPadding; // in QCPAxisPainter - bool mTickLabels, mAutoTickLabels; + bool mTickLabels; //double mTickLabelRotation; // in QCPAxisPainter - LabelType mTickLabelType; QFont mTickLabelFont, mSelectedTickLabelFont; QColor mTickLabelColor, mSelectedTickLabelColor; - QString mDateTimeFormat; - Qt::TimeSpec mDateTimeSpec; int mNumberPrecision; QLatin1Char mNumberFormatChar; bool mNumberBeautifulPowers; //bool mNumberMultiplyCross; // QCPAxisPainter // ticks and subticks: bool mTicks; - double mTickStep; - int mSubTickCount, mAutoTickCount; - bool mAutoTicks, mAutoTickStep, mAutoSubTicks; + bool mSubTicks; //int mTickLengthIn, mTickLengthOut, mSubTickLengthIn, mSubTickLengthOut; // QCPAxisPainter QPen mTickPen, mSelectedTickPen; QPen mSubTickPen, mSelectedSubTickPen; @@ -1268,12 +2136,11 @@ protected: QCPRange mRange; bool mRangeReversed; ScaleType mScaleType; - double mScaleLogBase, mScaleLogBaseLogInv; // non-property members: QCPGrid *mGrid; QCPAxisPainterPrivate *mAxisPainter; - int mLowestVisibleTick, mHighestVisibleTick; + QSharedPointer mTicker; QVector mTickVector; QVector mTickVectorLabels; QVector mSubTickVector; @@ -1281,23 +2148,18 @@ protected: int mCachedMargin; // introduced virtual methods: - virtual void setupTickVectors(); - virtual void generateAutoTicks(); - virtual int calculateAutoSubTickCount(double tickStep) const; virtual int calculateMargin(); // reimplemented virtual methods: - virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const; - virtual void draw(QCPPainter *painter); - virtual QCP::Interaction selectionCategory() const; + virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const Q_DECL_OVERRIDE; + virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; + virtual QCP::Interaction selectionCategory() const Q_DECL_OVERRIDE; // events: - virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged); - virtual void deselectEvent(bool *selectionStateChanged); + virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) Q_DECL_OVERRIDE; + virtual void deselectEvent(bool *selectionStateChanged) Q_DECL_OVERRIDE; // non-virtual methods: - void visibleTickBounds(int &lowIndex, int &highIndex) const; - double baseLog(double value) const; - double basePow(double value) const; + void setupTickVectors(); QPen getBasePen() const; QPen getTickPen() const; QPen getSubTickPen() const; @@ -1315,6 +2177,9 @@ private: }; Q_DECLARE_OPERATORS_FOR_FLAGS(QCPAxis::SelectableParts) Q_DECLARE_OPERATORS_FOR_FLAGS(QCPAxis::AxisTypes) +Q_DECLARE_METATYPE(QCPAxis::AxisType) +Q_DECLARE_METATYPE(QCPAxis::LabelSide) +Q_DECLARE_METATYPE(QCPAxis::ScaleType) Q_DECLARE_METATYPE(QCPAxis::SelectablePart) @@ -1366,8 +2231,8 @@ protected: }; struct TickLabelData { - QString basePart, expPart; - QRect baseBounds, expBounds, totalBounds, rotatedTotalBounds; + QString basePart, expPart, suffixPart; + QRect baseBounds, expBounds, suffixBounds, totalBounds, rotatedTotalBounds; QFont baseFont, expFont; }; QCustomPlot *mParentPlot; @@ -1384,6 +2249,1009 @@ protected: virtual void getMaxTickLabelSize(const QFont &font, const QString &text, QSize *tickLabelsSize) const; }; +/* end of 'src/axis/axis.h' */ + + +/* including file 'src/scatterstyle.h', size 7275 */ +/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */ + +class QCP_LIB_DECL QCPScatterStyle +{ + Q_GADGET +public: + /*! + Represents the various properties of a scatter style instance. For example, this enum is used + to specify which properties of \ref QCPSelectionDecorator::setScatterStyle will be used when + highlighting selected data points. + + Specific scatter properties can be transferred between \ref QCPScatterStyle instances via \ref + setFromOther. + */ + enum ScatterProperty { spNone = 0x00 ///< 0x00 None + ,spPen = 0x01 ///< 0x01 The pen property, see \ref setPen + ,spBrush = 0x02 ///< 0x02 The brush property, see \ref setBrush + ,spSize = 0x04 ///< 0x04 The size property, see \ref setSize + ,spShape = 0x08 ///< 0x08 The shape property, see \ref setShape + ,spAll = 0xFF ///< 0xFF All properties + }; + Q_ENUMS(ScatterProperty) + Q_FLAGS(ScatterProperties) + Q_DECLARE_FLAGS(ScatterProperties, ScatterProperty) + + /*! + Defines the shape used for scatter points. + + On plottables/items that draw scatters, the sizes of these visualizations (with exception of + \ref ssDot and \ref ssPixmap) can be controlled with the \ref setSize function. Scatters are + drawn with the pen and brush specified with \ref setPen and \ref setBrush. + */ + enum ScatterShape { ssNone ///< no scatter symbols are drawn (e.g. in QCPGraph, data only represented with lines) + ,ssDot ///< \enumimage{ssDot.png} a single pixel (use \ref ssDisc or \ref ssCircle if you want a round shape with a certain radius) + ,ssCross ///< \enumimage{ssCross.png} a cross + ,ssPlus ///< \enumimage{ssPlus.png} a plus + ,ssCircle ///< \enumimage{ssCircle.png} a circle + ,ssDisc ///< \enumimage{ssDisc.png} a circle which is filled with the pen's color (not the brush as with ssCircle) + ,ssSquare ///< \enumimage{ssSquare.png} a square + ,ssDiamond ///< \enumimage{ssDiamond.png} a diamond + ,ssStar ///< \enumimage{ssStar.png} a star with eight arms, i.e. a combination of cross and plus + ,ssTriangle ///< \enumimage{ssTriangle.png} an equilateral triangle, standing on baseline + ,ssTriangleInverted ///< \enumimage{ssTriangleInverted.png} an equilateral triangle, standing on corner + ,ssCrossSquare ///< \enumimage{ssCrossSquare.png} a square with a cross inside + ,ssPlusSquare ///< \enumimage{ssPlusSquare.png} a square with a plus inside + ,ssCrossCircle ///< \enumimage{ssCrossCircle.png} a circle with a cross inside + ,ssPlusCircle ///< \enumimage{ssPlusCircle.png} a circle with a plus inside + ,ssPeace ///< \enumimage{ssPeace.png} a circle, with one vertical and two downward diagonal lines + ,ssPixmap ///< a custom pixmap specified by \ref setPixmap, centered on the data point coordinates + ,ssCustom ///< custom painter operations are performed per scatter (As QPainterPath, see \ref setCustomPath) + }; + Q_ENUMS(ScatterShape) + + QCPScatterStyle(); + QCPScatterStyle(ScatterShape shape, double size=6); + QCPScatterStyle(ScatterShape shape, const QColor &color, double size); + QCPScatterStyle(ScatterShape shape, const QColor &color, const QColor &fill, double size); + QCPScatterStyle(ScatterShape shape, const QPen &pen, const QBrush &brush, double size); + QCPScatterStyle(const QPixmap &pixmap); + QCPScatterStyle(const QPainterPath &customPath, const QPen &pen, const QBrush &brush=Qt::NoBrush, double size=6); + + // getters: + double size() const { return mSize; } + ScatterShape shape() const { return mShape; } + QPen pen() const { return mPen; } + QBrush brush() const { return mBrush; } + QPixmap pixmap() const { return mPixmap; } + QPainterPath customPath() const { return mCustomPath; } + + // setters: + void setFromOther(const QCPScatterStyle &other, ScatterProperties properties); + void setSize(double size); + void setShape(ScatterShape shape); + void setPen(const QPen &pen); + void setBrush(const QBrush &brush); + void setPixmap(const QPixmap &pixmap); + void setCustomPath(const QPainterPath &customPath); + + // non-property methods: + bool isNone() const { return mShape == ssNone; } + bool isPenDefined() const { return mPenDefined; } + void undefinePen(); + void applyTo(QCPPainter *painter, const QPen &defaultPen) const; + void drawShape(QCPPainter *painter, const QPointF &pos) const; + void drawShape(QCPPainter *painter, double x, double y) const; + +protected: + // property members: + double mSize; + ScatterShape mShape; + QPen mPen; + QBrush mBrush; + QPixmap mPixmap; + QPainterPath mCustomPath; + + // non-property members: + bool mPenDefined; +}; +Q_DECLARE_TYPEINFO(QCPScatterStyle, Q_MOVABLE_TYPE); +Q_DECLARE_OPERATORS_FOR_FLAGS(QCPScatterStyle::ScatterProperties) +Q_DECLARE_METATYPE(QCPScatterStyle::ScatterProperty) +Q_DECLARE_METATYPE(QCPScatterStyle::ScatterShape) + +/* end of 'src/scatterstyle.h' */ + + +/* including file 'src/datacontainer.h', size 4535 */ +/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */ + +/*! \relates QCPDataContainer + Returns whether the sort key of \a a is less than the sort key of \a b. + + \see QCPDataContainer::sort +*/ +template +inline bool qcpLessThanSortKey(const DataType &a, const DataType &b) { return a.sortKey() < b.sortKey(); } + +template +class QCP_LIB_DECL QCPDataContainer +{ +public: + typedef typename QVector::const_iterator const_iterator; + typedef typename QVector::iterator iterator; + + QCPDataContainer(); + + // getters: + int size() const { return mData.size()-mPreallocSize; } + bool isEmpty() const { return size() == 0; } + bool autoSqueeze() const { return mAutoSqueeze; } + + // setters: + void setAutoSqueeze(bool enabled); + + // non-virtual methods: + void set(const QCPDataContainer &data); + void set(const QVector &data, bool alreadySorted=false); + void add(const QCPDataContainer &data); + void add(const QVector &data, bool alreadySorted=false); + void add(const DataType &data); + void removeBefore(double sortKey); + void removeAfter(double sortKey); + void remove(double sortKeyFrom, double sortKeyTo); + void remove(double sortKey); + void clear(); + void sort(); + void squeeze(bool preAllocation=true, bool postAllocation=true); + + const_iterator constBegin() const { return mData.constBegin()+mPreallocSize; } + const_iterator constEnd() const { return mData.constEnd(); } + iterator begin() { return mData.begin()+mPreallocSize; } + iterator end() { return mData.end(); } + const_iterator findBegin(double sortKey, bool expandedRange=true) const; + const_iterator findEnd(double sortKey, bool expandedRange=true) const; + const_iterator at(int index) const { return constBegin()+qBound(0, index, size()); } + QCPRange keyRange(bool &foundRange, QCP::SignDomain signDomain=QCP::sdBoth); + QCPRange valueRange(bool &foundRange, QCP::SignDomain signDomain=QCP::sdBoth, const QCPRange &inKeyRange=QCPRange()); + QCPDataRange dataRange() const { return QCPDataRange(0, size()); } + void limitIteratorsToDataRange(const_iterator &begin, const_iterator &end, const QCPDataRange &dataRange) const; + +protected: + // property members: + bool mAutoSqueeze; + + // non-property memebers: + QVector mData; + int mPreallocSize; + int mPreallocIteration; + + // non-virtual methods: + void preallocateGrow(int minimumPreallocSize); + void performAutoSqueeze(); +}; + +// include implementation in header since it is a class template: + +/* including file 'src/datacontainer.cpp', size 31224 */ +/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */ + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPDataContainer +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPDataContainer + \brief The generic data container for one-dimensional plottables + + This class template provides a fast container for data storage of one-dimensional data. The data + type is specified as template parameter (called \a DataType in the following) and must provide + some methods as described in the \ref qcpdatacontainer-datatype "next section". + + The data is stored in a sorted fashion, which allows very quick lookups by the sorted key as well + as retrieval of ranges (see \ref findBegin, \ref findEnd, \ref keyRange) using binary search. The + container uses a preallocation and a postallocation scheme, such that appending and prepending + data (with respect to the sort key) is very fast and minimizes reallocations. If data is added + which needs to be inserted between existing keys, the merge usually can be done quickly too, + using the fact that existing data is always sorted. The user can further improve performance by + specifying that added data is already itself sorted by key, if he can guarantee that this is the + case (see for example \ref add(const QVector &data, bool alreadySorted)). + + The data can be accessed with the provided const iterators (\ref constBegin, \ref constEnd). If + it is necessary to alter existing data in-place, the non-const iterators can be used (\ref begin, + \ref end). Changing data members that are not the sort key (for most data types called \a key) is + safe from the container's perspective. + + Great care must be taken however if the sort key is modified through the non-const iterators. For + performance reasons, the iterators don't automatically cause a re-sorting upon their + manipulation. It is thus the responsibility of the user to leave the container in a sorted state + when finished with the data manipulation, before calling any other methods on the container. A + complete re-sort (e.g. after finishing all sort key manipulation) can be done by calling \ref + sort. Failing to do so can not be detected by the container efficiently and will cause both + rendering artifacts and potential data loss. + + Implementing one-dimensional plottables that make use of a \ref QCPDataContainer is usually + done by subclassing from \ref QCPAbstractPlottable1D "QCPAbstractPlottable1D", which + introduces an according \a mDataContainer member and some convenience methods. + + \section qcpdatacontainer-datatype Requirements for the DataType template parameter + + The template parameter DataType is the type of the stored data points. It must be + trivially copyable and have the following public methods, preferably inline: + + \li double sortKey() const\n Returns the member variable of this data point that is the + sort key, defining the ordering in the container. Often this variable is simply called \a key. + + \li static DataType fromSortKey(double sortKey)\n Returns a new instance of the data + type initialized with its sort key set to \a sortKey. + + \li static bool sortKeyIsMainKey()\n Returns true if the sort key is equal to the main + key (see method \c mainKey below). For most plottables this is the case. It is not the case for + example for \ref QCPCurve, which uses \a t as sort key and \a key as main key. This is the reason + why QCPCurve unlike QCPGraph can display parametric curves with loops. + + \li double mainKey() const\n Returns the variable of this data point considered the main + key. This is commonly the variable that is used as the coordinate of this data point on the key + axis of the plottable. This method is used for example when determining the automatic axis + rescaling of key axes (\ref QCPAxis::rescale). + + \li double mainValue() const\n Returns the variable of this data point considered the + main value. This is commonly the variable that is used as the coordinate of this data point on + the value axis of the plottable. + + \li QCPRange valueRange() const\n Returns the range this data point spans in the value + axis coordinate. If the data is single-valued (e.g. QCPGraphData), this is simply a range with + both lower and upper set to the main data point value. However if the data points can represent + multiple values at once (e.g QCPFinancialData with its \a high, \a low, \a open and \a close + values at each \a key) this method should return the range those values span. This method is used + for example when determining the automatic axis rescaling of value axes (\ref + QCPAxis::rescale). +*/ + +/* start documentation of inline functions */ + +/*! \fn int QCPDataContainer::size() const + + Returns the number of data points in the container. +*/ + +/*! \fn bool QCPDataContainer::isEmpty() const + + Returns whether this container holds no data points. +*/ + +/*! \fn QCPDataContainer::const_iterator QCPDataContainer::constBegin() const + + Returns a const iterator to the first data point in this container. +*/ + +/*! \fn QCPDataContainer::const_iterator QCPDataContainer::constEnd() const + + Returns a const iterator to the element past the last data point in this container. +*/ + +/*! \fn QCPDataContainer::iterator QCPDataContainer::begin() const + + Returns a non-const iterator to the first data point in this container. + + You can manipulate the data points in-place through the non-const iterators, but great care must + be taken when manipulating the sort key of a data point, see \ref sort, or the detailed + description of this class. +*/ + +/*! \fn QCPDataContainer::iterator QCPDataContainer::end() const + + Returns a non-const iterator to the element past the last data point in this container. + + You can manipulate the data points in-place through the non-const iterators, but great care must + be taken when manipulating the sort key of a data point, see \ref sort, or the detailed + description of this class. +*/ + +/*! \fn QCPDataContainer::const_iterator QCPDataContainer::at(int index) const + + Returns a const iterator to the element with the specified \a index. If \a index points beyond + the available elements in this container, returns \ref constEnd, i.e. an iterator past the last + valid element. + + You can use this method to easily obtain iterators from a \ref QCPDataRange, see the \ref + dataselection-accessing "data selection page" for an example. +*/ + +/*! \fn QCPDataRange QCPDataContainer::dataRange() const + + Returns a \ref QCPDataRange encompassing the entire data set of this container. This means the + begin index of the returned range is 0, and the end index is \ref size. +*/ + +/* end documentation of inline functions */ + +/*! + Constructs a QCPDataContainer used for plottable classes that represent a series of key-sorted + data +*/ +template +QCPDataContainer::QCPDataContainer() : + mAutoSqueeze(true), + mPreallocSize(0), + mPreallocIteration(0) +{ +} + +/*! + Sets whether the container automatically decides when to release memory from its post- and + preallocation pools when data points are removed. By default this is enabled and for typical + applications shouldn't be changed. + + If auto squeeze is disabled, you can manually decide when to release pre-/postallocation with + \ref squeeze. +*/ +template +void QCPDataContainer::setAutoSqueeze(bool enabled) +{ + if (mAutoSqueeze != enabled) + { + mAutoSqueeze = enabled; + if (mAutoSqueeze) + performAutoSqueeze(); + } +} + +/*! \overload + + Replaces the current data in this container with the provided \a data. + + \see add, remove +*/ +template +void QCPDataContainer::set(const QCPDataContainer &data) +{ + clear(); + add(data); +} + +/*! \overload + + Replaces the current data in this container with the provided \a data + + If you can guarantee that the data points in \a data have ascending order with respect to the + DataType's sort key, set \a alreadySorted to true to avoid an unnecessary sorting run. + + \see add, remove +*/ +template +void QCPDataContainer::set(const QVector &data, bool alreadySorted) +{ + mData = data; + mPreallocSize = 0; + mPreallocIteration = 0; + if (!alreadySorted) + sort(); +} + +/*! \overload + + Adds the provided \a data to the current data in this container. + + \see set, remove +*/ +template +void QCPDataContainer::add(const QCPDataContainer &data) +{ + if (data.isEmpty()) + return; + + const int n = data.size(); + const int oldSize = size(); + + if (oldSize > 0 && !qcpLessThanSortKey(*constBegin(), *(data.constEnd()-1))) // prepend if new data keys are all smaller than or equal to existing ones + { + if (mPreallocSize < n) + preallocateGrow(n); + mPreallocSize -= n; + std::copy(data.constBegin(), data.constEnd(), begin()); + } else // don't need to prepend, so append and merge if necessary + { + mData.resize(mData.size()+n); + std::copy(data.constBegin(), data.constEnd(), end()-n); + if (oldSize > 0 && !qcpLessThanSortKey(*(constEnd()-n-1), *(constEnd()-n))) // if appended range keys aren't all greater than existing ones, merge the two partitions + std::inplace_merge(begin(), end()-n, end(), qcpLessThanSortKey); + } +} + +/*! + Adds the provided data points in \a data to the current data. + + If you can guarantee that the data points in \a data have ascending order with respect to the + DataType's sort key, set \a alreadySorted to true to avoid an unnecessary sorting run. + + \see set, remove +*/ +template +void QCPDataContainer::add(const QVector &data, bool alreadySorted) +{ + if (data.isEmpty()) + return; + if (isEmpty()) + { + set(data, alreadySorted); + return; + } + + const int n = data.size(); + const int oldSize = size(); + + if (alreadySorted && oldSize > 0 && !qcpLessThanSortKey(*constBegin(), *(data.constEnd()-1))) // prepend if new data is sorted and keys are all smaller than or equal to existing ones + { + if (mPreallocSize < n) + preallocateGrow(n); + mPreallocSize -= n; + std::copy(data.constBegin(), data.constEnd(), begin()); + } else // don't need to prepend, so append and then sort and merge if necessary + { + mData.resize(mData.size()+n); + std::copy(data.constBegin(), data.constEnd(), end()-n); + if (!alreadySorted) // sort appended subrange if it wasn't already sorted + std::sort(end()-n, end(), qcpLessThanSortKey); + if (oldSize > 0 && !qcpLessThanSortKey(*(constEnd()-n-1), *(constEnd()-n))) // if appended range keys aren't all greater than existing ones, merge the two partitions + std::inplace_merge(begin(), end()-n, end(), qcpLessThanSortKey); + } +} + +/*! \overload + + Adds the provided single data point to the current data. + + \see remove +*/ +template +void QCPDataContainer::add(const DataType &data) +{ + if (isEmpty() || !qcpLessThanSortKey(data, *(constEnd()-1))) // quickly handle appends if new data key is greater or equal to existing ones + { + mData.append(data); + } else if (qcpLessThanSortKey(data, *constBegin())) // quickly handle prepends using preallocated space + { + if (mPreallocSize < 1) + preallocateGrow(1); + --mPreallocSize; + *begin() = data; + } else // handle inserts, maintaining sorted keys + { + QCPDataContainer::iterator insertionPoint = std::lower_bound(begin(), end(), data, qcpLessThanSortKey); + mData.insert(insertionPoint, data); + } +} + +/*! + Removes all data points with (sort-)keys smaller than or equal to \a sortKey. + + \see removeAfter, remove, clear +*/ +template +void QCPDataContainer::removeBefore(double sortKey) +{ + QCPDataContainer::iterator it = begin(); + QCPDataContainer::iterator itEnd = std::lower_bound(begin(), end(), DataType::fromSortKey(sortKey), qcpLessThanSortKey); + mPreallocSize += itEnd-it; // don't actually delete, just add it to the preallocated block (if it gets too large, squeeze will take care of it) + if (mAutoSqueeze) + performAutoSqueeze(); +} + +/*! + Removes all data points with (sort-)keys greater than or equal to \a sortKey. + + \see removeBefore, remove, clear +*/ +template +void QCPDataContainer::removeAfter(double sortKey) +{ + QCPDataContainer::iterator it = std::upper_bound(begin(), end(), DataType::fromSortKey(sortKey), qcpLessThanSortKey); + QCPDataContainer::iterator itEnd = end(); + mData.erase(it, itEnd); // typically adds it to the postallocated block + if (mAutoSqueeze) + performAutoSqueeze(); +} + +/*! + Removes all data points with (sort-)keys between \a sortKeyFrom and \a sortKeyTo. if \a + sortKeyFrom is greater or equal to \a sortKeyTo, the function does nothing. To remove a single + data point with known (sort-)key, use \ref remove(double sortKey). + + \see removeBefore, removeAfter, clear +*/ +template +void QCPDataContainer::remove(double sortKeyFrom, double sortKeyTo) +{ + if (sortKeyFrom >= sortKeyTo || isEmpty()) + return; + + QCPDataContainer::iterator it = std::lower_bound(begin(), end(), DataType::fromSortKey(sortKeyFrom), qcpLessThanSortKey); + QCPDataContainer::iterator itEnd = std::upper_bound(it, end(), DataType::fromSortKey(sortKeyTo), qcpLessThanSortKey); + mData.erase(it, itEnd); + if (mAutoSqueeze) + performAutoSqueeze(); +} + +/*! \overload + + Removes a single data point at \a sortKey. If the position is not known with absolute (binary) + precision, consider using \ref remove(double sortKeyFrom, double sortKeyTo) with a small + fuzziness interval around the suspected position, depeding on the precision with which the + (sort-)key is known. + + \see removeBefore, removeAfter, clear +*/ +template +void QCPDataContainer::remove(double sortKey) +{ + QCPDataContainer::iterator it = std::lower_bound(begin(), end(), DataType::fromSortKey(sortKey), qcpLessThanSortKey); + if (it != end() && it->sortKey() == sortKey) + { + if (it == begin()) + ++mPreallocSize; // don't actually delete, just add it to the preallocated block (if it gets too large, squeeze will take care of it) + else + mData.erase(it); + } + if (mAutoSqueeze) + performAutoSqueeze(); +} + +/*! + Removes all data points. + + \see remove, removeAfter, removeBefore +*/ +template +void QCPDataContainer::clear() +{ + mData.clear(); + mPreallocIteration = 0; + mPreallocSize = 0; +} + +/*! + Re-sorts all data points in the container by their sort key. + + When setting, adding or removing points using the QCPDataContainer interface (\ref set, \ref add, + \ref remove, etc.), the container makes sure to always stay in a sorted state such that a full + resort is never necessary. However, if you choose to directly manipulate the sort key on data + points by accessing and modifying it through the non-const iterators (\ref begin, \ref end), it + is your responsibility to bring the container back into a sorted state before any other methods + are called on it. This can be achieved by calling this method immediately after finishing the + sort key manipulation. +*/ +template +void QCPDataContainer::sort() +{ + std::sort(begin(), end(), qcpLessThanSortKey); +} + +/*! + Frees all unused memory that is currently in the preallocation and postallocation pools. + + Note that QCPDataContainer automatically decides whether squeezing is necessary, if \ref + setAutoSqueeze is left enabled. It should thus not be necessary to use this method for typical + applications. + + The parameters \a preAllocation and \a postAllocation control whether pre- and/or post allocation + should be freed, respectively. +*/ +template +void QCPDataContainer::squeeze(bool preAllocation, bool postAllocation) +{ + if (preAllocation) + { + if (mPreallocSize > 0) + { + std::copy(begin(), end(), mData.begin()); + mData.resize(size()); + mPreallocSize = 0; + } + mPreallocIteration = 0; + } + if (postAllocation) + mData.squeeze(); +} + +/*! + Returns an iterator to the data point with a (sort-)key that is equal to, just below, or just + above \a sortKey. If \a expandedRange is true, the data point just below \a sortKey will be + considered, otherwise the one just above. + + This can be used in conjunction with \ref findEnd to iterate over data points within a given key + range, including or excluding the bounding data points that are just beyond the specified range. + + If \a expandedRange is true but there are no data points below \a sortKey, \ref constBegin is + returned. + + If the container is empty, returns \ref constEnd. + + \see findEnd, QCPPlottableInterface1D::findBegin +*/ +template +typename QCPDataContainer::const_iterator QCPDataContainer::findBegin(double sortKey, bool expandedRange) const +{ + if (isEmpty()) + return constEnd(); + + QCPDataContainer::const_iterator it = std::lower_bound(constBegin(), constEnd(), DataType::fromSortKey(sortKey), qcpLessThanSortKey); + if (expandedRange && it != constBegin()) // also covers it == constEnd case, and we know --constEnd is valid because mData isn't empty + --it; + return it; +} + +/*! + Returns an iterator to the element after the data point with a (sort-)key that is equal to, just + above or just below \a sortKey. If \a expandedRange is true, the data point just above \a sortKey + will be considered, otherwise the one just below. + + This can be used in conjunction with \ref findBegin to iterate over data points within a given + key range, including the bounding data points that are just below and above the specified range. + + If \a expandedRange is true but there are no data points above \a sortKey, \ref constEnd is + returned. + + If the container is empty, \ref constEnd is returned. + + \see findBegin, QCPPlottableInterface1D::findEnd +*/ +template +typename QCPDataContainer::const_iterator QCPDataContainer::findEnd(double sortKey, bool expandedRange) const +{ + if (isEmpty()) + return constEnd(); + + QCPDataContainer::const_iterator it = std::upper_bound(constBegin(), constEnd(), DataType::fromSortKey(sortKey), qcpLessThanSortKey); + if (expandedRange && it != constEnd()) + ++it; + return it; +} + +/*! + Returns the range encompassed by the (main-)key coordinate of all data points. The output + parameter \a foundRange indicates whether a sensible range was found. If this is false, you + should not use the returned QCPRange (e.g. the data container is empty or all points have the + same key). + + Use \a signDomain to control which sign of the key coordinates should be considered. This is + relevant e.g. for logarithmic plots which can mathematically only display one sign domain at a + time. + + If the DataType reports that its main key is equal to the sort key (\a sortKeyIsMainKey), as is + the case for most plottables, this method uses this fact and finds the range very quickly. + + \see valueRange +*/ +template +QCPRange QCPDataContainer::keyRange(bool &foundRange, QCP::SignDomain signDomain) +{ + if (isEmpty()) + { + foundRange = false; + return QCPRange(); + } + QCPRange range; + bool haveLower = false; + bool haveUpper = false; + double current; + + QCPDataContainer::const_iterator it = constBegin(); + QCPDataContainer::const_iterator itEnd = constEnd(); + if (signDomain == QCP::sdBoth) // range may be anywhere + { + if (DataType::sortKeyIsMainKey()) // if DataType is sorted by main key (e.g. QCPGraph, but not QCPCurve), use faster algorithm by finding just first and last key with non-NaN value + { + while (it != itEnd) // find first non-nan going up from left + { + if (!qIsNaN(it->mainValue())) + { + range.lower = it->mainKey(); + haveLower = true; + break; + } + ++it; + } + it = itEnd; + while (it != constBegin()) // find first non-nan going down from right + { + --it; + if (!qIsNaN(it->mainValue())) + { + range.upper = it->mainKey(); + haveUpper = true; + break; + } + } + } else // DataType is not sorted by main key, go through all data points and accordingly expand range + { + while (it != itEnd) + { + if (!qIsNaN(it->mainValue())) + { + current = it->mainKey(); + if (current < range.lower || !haveLower) + { + range.lower = current; + haveLower = true; + } + if (current > range.upper || !haveUpper) + { + range.upper = current; + haveUpper = true; + } + } + ++it; + } + } + } else if (signDomain == QCP::sdNegative) // range may only be in the negative sign domain + { + while (it != itEnd) + { + if (!qIsNaN(it->mainValue())) + { + current = it->mainKey(); + 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 (signDomain == QCP::sdPositive) // range may only be in the positive sign domain + { + while (it != itEnd) + { + if (!qIsNaN(it->mainValue())) + { + current = it->mainKey(); + 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; + } + } + + foundRange = haveLower && haveUpper; + return range; +} + +/*! + Returns the range encompassed by the value coordinates of the data points in the specified key + range (\a inKeyRange), using the full \a DataType::valueRange reported by the data points. The + output parameter \a foundRange indicates whether a sensible range was found. If this is false, + you should not use the returned QCPRange (e.g. the data container is empty or all points have the + same value). + + If \a inKeyRange has both lower and upper bound set to zero (is equal to QCPRange()), + all data points are considered, without any restriction on the keys. + + Use \a signDomain to control which sign of the value coordinates should be considered. This is + relevant e.g. for logarithmic plots which can mathematically only display one sign domain at a + time. + + \see keyRange +*/ +template +QCPRange QCPDataContainer::valueRange(bool &foundRange, QCP::SignDomain signDomain, const QCPRange &inKeyRange) +{ + if (isEmpty()) + { + foundRange = false; + return QCPRange(); + } + QCPRange range; + const bool restrictKeyRange = inKeyRange != QCPRange(); + bool haveLower = false; + bool haveUpper = false; + QCPRange current; + QCPDataContainer::const_iterator itBegin = constBegin(); + QCPDataContainer::const_iterator itEnd = constEnd(); + if (DataType::sortKeyIsMainKey() && restrictKeyRange) + { + itBegin = findBegin(inKeyRange.lower); + itEnd = findEnd(inKeyRange.upper); + } + if (signDomain == QCP::sdBoth) // range may be anywhere + { + for (QCPDataContainer::const_iterator it = itBegin; it != itEnd; ++it) + { + if (restrictKeyRange && (it->mainKey() < inKeyRange.lower || it->mainKey() > inKeyRange.upper)) + continue; + current = it->valueRange(); + if ((current.lower < range.lower || !haveLower) && !qIsNaN(current.lower)) + { + range.lower = current.lower; + haveLower = true; + } + if ((current.upper > range.upper || !haveUpper) && !qIsNaN(current.upper)) + { + range.upper = current.upper; + haveUpper = true; + } + } + } else if (signDomain == QCP::sdNegative) // range may only be in the negative sign domain + { + for (QCPDataContainer::const_iterator it = itBegin; it != itEnd; ++it) + { + if (restrictKeyRange && (it->mainKey() < inKeyRange.lower || it->mainKey() > inKeyRange.upper)) + continue; + current = it->valueRange(); + if ((current.lower < range.lower || !haveLower) && current.lower < 0 && !qIsNaN(current.lower)) + { + range.lower = current.lower; + haveLower = true; + } + if ((current.upper > range.upper || !haveUpper) && current.upper < 0 && !qIsNaN(current.upper)) + { + range.upper = current.upper; + haveUpper = true; + } + } + } else if (signDomain == QCP::sdPositive) // range may only be in the positive sign domain + { + for (QCPDataContainer::const_iterator it = itBegin; it != itEnd; ++it) + { + if (restrictKeyRange && (it->mainKey() < inKeyRange.lower || it->mainKey() > inKeyRange.upper)) + continue; + current = it->valueRange(); + if ((current.lower < range.lower || !haveLower) && current.lower > 0 && !qIsNaN(current.lower)) + { + range.lower = current.lower; + haveLower = true; + } + if ((current.upper > range.upper || !haveUpper) && current.upper > 0 && !qIsNaN(current.upper)) + { + range.upper = current.upper; + haveUpper = true; + } + } + } + + foundRange = haveLower && haveUpper; + return range; +} + +/*! + Makes sure \a begin and \a end mark a data range that is both within the bounds of this data + container's data, as well as within the specified \a dataRange. + + This function doesn't require for \a dataRange to be within the bounds of this data container's + valid range. +*/ +template +void QCPDataContainer::limitIteratorsToDataRange(const_iterator &begin, const_iterator &end, const QCPDataRange &dataRange) const +{ + QCPDataRange iteratorRange(begin-constBegin(), end-constBegin()); + iteratorRange = iteratorRange.bounded(dataRange.bounded(this->dataRange())); + begin = constBegin()+iteratorRange.begin(); + end = constBegin()+iteratorRange.end(); +} + +/*! \internal + + Increases the preallocation pool to have a size of at least \a minimumPreallocSize. Depending on + the preallocation history, the container will grow by more than requested, to speed up future + consecutive size increases. + + if \a minimumPreallocSize is smaller than or equal to the current preallocation pool size, this + method does nothing. +*/ +template +void QCPDataContainer::preallocateGrow(int minimumPreallocSize) +{ + if (minimumPreallocSize <= mPreallocSize) + return; + + int newPreallocSize = minimumPreallocSize; + newPreallocSize += (1u< +void QCPDataContainer::performAutoSqueeze() +{ + const int totalAlloc = mData.capacity(); + const int postAllocSize = totalAlloc-mData.size(); + const int usedSize = size(); + bool shrinkPostAllocation = false; + bool shrinkPreAllocation = false; + if (totalAlloc > 650000) // if allocation is larger, shrink earlier with respect to total used size + { + shrinkPostAllocation = postAllocSize > usedSize*1.5; // QVector grow strategy is 2^n for static data. Watch out not to oscillate! + shrinkPreAllocation = mPreallocSize*10 > usedSize; + } else if (totalAlloc > 1000) // below 10 MiB raw data be generous with preallocated memory, below 1k points don't even bother + { + shrinkPostAllocation = postAllocSize > usedSize*5; + shrinkPreAllocation = mPreallocSize > usedSize*1.5; // preallocation can grow into postallocation, so can be smaller + } + + if (shrinkPreAllocation || shrinkPostAllocation) + squeeze(shrinkPreAllocation, shrinkPostAllocation); +} +/* end of 'src/datacontainer.cpp' */ + + +/* end of 'src/datacontainer.h' */ + + +/* including file 'src/plottable.h', size 8312 */ +/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */ + +class QCP_LIB_DECL QCPSelectionDecorator +{ + Q_GADGET +public: + QCPSelectionDecorator(); + virtual ~QCPSelectionDecorator(); + + // getters: + QPen pen() const { return mPen; } + QBrush brush() const { return mBrush; } + QCPScatterStyle scatterStyle() const { return mScatterStyle; } + QCPScatterStyle::ScatterProperties usedScatterProperties() const { return mUsedScatterProperties; } + + // setters: + void setPen(const QPen &pen); + void setBrush(const QBrush &brush); + void setScatterStyle(const QCPScatterStyle &scatterStyle, QCPScatterStyle::ScatterProperties usedProperties=QCPScatterStyle::spPen); + void setUsedScatterProperties(const QCPScatterStyle::ScatterProperties &properties); + + // non-virtual methods: + void applyPen(QCPPainter *painter) const; + void applyBrush(QCPPainter *painter) const; + QCPScatterStyle getFinalScatterStyle(const QCPScatterStyle &unselectedStyle) const; + + // introduced virtual methods: + virtual void copyFrom(const QCPSelectionDecorator *other); + virtual void drawDecoration(QCPPainter *painter, QCPDataSelection selection); + +protected: + // property members: + QPen mPen; + QBrush mBrush; + QCPScatterStyle mScatterStyle; + QCPScatterStyle::ScatterProperties mUsedScatterProperties; + // non-property members: + QCPAbstractPlottable *mPlottable; + + // introduced virtual methods: + virtual bool registerWithPlottable(QCPAbstractPlottable *plottable); + +private: + Q_DISABLE_COPY(QCPSelectionDecorator) + friend class QCPAbstractPlottable; +}; +Q_DECLARE_METATYPE(QCPSelectionDecorator*) + class QCP_LIB_DECL QCPAbstractPlottable : public QCPLayerable { @@ -1392,104 +3260,93 @@ class QCP_LIB_DECL QCPAbstractPlottable : public QCPLayerable Q_PROPERTY(QString name READ name WRITE setName) Q_PROPERTY(bool antialiasedFill READ antialiasedFill WRITE setAntialiasedFill) Q_PROPERTY(bool antialiasedScatters READ antialiasedScatters WRITE setAntialiasedScatters) - Q_PROPERTY(bool antialiasedErrorBars READ antialiasedErrorBars WRITE setAntialiasedErrorBars) Q_PROPERTY(QPen pen READ pen WRITE setPen) - Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) Q_PROPERTY(QBrush brush READ brush WRITE setBrush) - Q_PROPERTY(QBrush selectedBrush READ selectedBrush WRITE setSelectedBrush) Q_PROPERTY(QCPAxis* keyAxis READ keyAxis WRITE setKeyAxis) Q_PROPERTY(QCPAxis* valueAxis READ valueAxis WRITE setValueAxis) - Q_PROPERTY(bool selectable READ selectable WRITE setSelectable NOTIFY selectableChanged) - Q_PROPERTY(bool selected READ selected WRITE setSelected NOTIFY selectionChanged) + Q_PROPERTY(QCP::SelectionType selectable READ selectable WRITE setSelectable NOTIFY selectableChanged) + Q_PROPERTY(QCPDataSelection selection READ selection WRITE setSelection NOTIFY selectionChanged) + Q_PROPERTY(QCPSelectionDecorator* selectionDecorator READ selectionDecorator WRITE setSelectionDecorator) /// \endcond public: QCPAbstractPlottable(QCPAxis *keyAxis, QCPAxis *valueAxis); + virtual ~QCPAbstractPlottable(); // getters: QString name() const { return mName; } bool antialiasedFill() const { return mAntialiasedFill; } bool antialiasedScatters() const { return mAntialiasedScatters; } - bool antialiasedErrorBars() const { return mAntialiasedErrorBars; } QPen pen() const { return mPen; } - QPen selectedPen() const { return mSelectedPen; } QBrush brush() const { return mBrush; } - QBrush selectedBrush() const { return mSelectedBrush; } QCPAxis *keyAxis() const { return mKeyAxis.data(); } QCPAxis *valueAxis() const { return mValueAxis.data(); } - bool selectable() const { return mSelectable; } - bool selected() const { return mSelected; } + QCP::SelectionType selectable() const { return mSelectable; } + bool selected() const { return !mSelection.isEmpty(); } + QCPDataSelection selection() const { return mSelection; } + QCPSelectionDecorator *selectionDecorator() const { return mSelectionDecorator; } // setters: void setName(const QString &name); void setAntialiasedFill(bool enabled); void setAntialiasedScatters(bool enabled); - void setAntialiasedErrorBars(bool enabled); void setPen(const QPen &pen); - void setSelectedPen(const QPen &pen); void setBrush(const QBrush &brush); - void setSelectedBrush(const QBrush &brush); void setKeyAxis(QCPAxis *axis); void setValueAxis(QCPAxis *axis); - Q_SLOT void setSelectable(bool selectable); - Q_SLOT void setSelected(bool selected); + Q_SLOT void setSelectable(QCP::SelectionType selectable); + Q_SLOT void setSelection(QCPDataSelection selection); + void setSelectionDecorator(QCPSelectionDecorator *decorator); // introduced virtual methods: - virtual void clearData() = 0; virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const = 0; - virtual bool addToLegend(); - virtual bool removeFromLegend() const; + virtual QCPPlottableInterface1D *interface1D() { return 0; } + virtual QCPRange getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain=QCP::sdBoth) const = 0; + virtual QCPRange getValueRange(bool &foundRange, QCP::SignDomain inSignDomain=QCP::sdBoth, const QCPRange &inKeyRange=QCPRange()) const = 0; // non-property methods: - void rescaleAxes(bool onlyEnlarge=false) const; - void rescaleKeyAxis(bool onlyEnlarge=false) const; - void rescaleValueAxis(bool onlyEnlarge=false) const; - -signals: - void selectionChanged(bool selected); - void selectableChanged(bool selectable); - -protected: - /*! - Represents negative and positive sign domain for passing to \ref getKeyRange and \ref getValueRange. - */ - enum SignDomain { sdNegative ///< The negative sign domain, i.e. numbers smaller than zero - ,sdBoth ///< Both sign domains, including zero, i.e. all (rational) numbers - ,sdPositive ///< The positive sign domain, i.e. numbers greater than zero - }; - - // property members: - QString mName; - bool mAntialiasedFill, mAntialiasedScatters, mAntialiasedErrorBars; - QPen mPen, mSelectedPen; - QBrush mBrush, mSelectedBrush; - QPointer mKeyAxis, mValueAxis; - bool mSelectable, mSelected; - - // reimplemented virtual methods: - virtual QRect clipRect() const; - virtual void draw(QCPPainter *painter) = 0; - virtual QCP::Interaction selectionCategory() const; - void applyDefaultAntialiasingHint(QCPPainter *painter) const; - // events: - virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged); - virtual void deselectEvent(bool *selectionStateChanged); - - // introduced virtual methods: - virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const = 0; - virtual QCPRange getKeyRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const = 0; - virtual QCPRange getValueRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const = 0; - - // non-virtual methods: void coordsToPixels(double key, double value, double &x, double &y) const; const QPointF coordsToPixels(double key, double value) const; void pixelsToCoords(double x, double y, double &key, double &value) const; void pixelsToCoords(const QPointF &pixelPos, double &key, double &value) const; - QPen mainPen() const; - QBrush mainBrush() const; + void rescaleAxes(bool onlyEnlarge=false) const; + void rescaleKeyAxis(bool onlyEnlarge=false) const; + void rescaleValueAxis(bool onlyEnlarge=false, bool inKeyRange=false) const; + bool addToLegend(QCPLegend *legend); + bool addToLegend(); + bool removeFromLegend(QCPLegend *legend) const; + bool removeFromLegend() const; + +signals: + void selectionChanged(bool selected); + void selectionChanged(const QCPDataSelection &selection); + void selectableChanged(QCP::SelectionType selectable); + +protected: + // property members: + QString mName; + bool mAntialiasedFill, mAntialiasedScatters; + QPen mPen; + QBrush mBrush; + QPointer mKeyAxis, mValueAxis; + QCP::SelectionType mSelectable; + QCPDataSelection mSelection; + QCPSelectionDecorator *mSelectionDecorator; + + // reimplemented virtual methods: + virtual QRect clipRect() const Q_DECL_OVERRIDE; + virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE = 0; + virtual QCP::Interaction selectionCategory() const Q_DECL_OVERRIDE; + void applyDefaultAntialiasingHint(QCPPainter *painter) const Q_DECL_OVERRIDE; + // events: + virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) Q_DECL_OVERRIDE; + virtual void deselectEvent(bool *selectionStateChanged) Q_DECL_OVERRIDE; + + // introduced virtual methods: + virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const = 0; + + // non-virtual methods: void applyFillAntialiasingHint(QCPPainter *painter) const; void applyScattersAntialiasingHint(QCPPainter *painter) const; - void applyErrorBarsAntialiasingHint(QCPPainter *painter) const; - double distSqrToLine(const QPointF &start, const QPointF &end, const QPointF &point) const; private: Q_DISABLE_COPY(QCPAbstractPlottable) @@ -1500,15 +3357,22 @@ private: }; +/* end of 'src/plottable.h' */ + + +/* including file 'src/item.h', size 9368 */ +/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */ + class QCP_LIB_DECL QCPItemAnchor { + Q_GADGET public: - QCPItemAnchor(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString name, int anchorId=-1); + QCPItemAnchor(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString &name, int anchorId=-1); virtual ~QCPItemAnchor(); // getters: QString name() const { return mName; } - virtual QPointF pixelPoint() const; + virtual QPointF pixelPosition() const; protected: // property members: @@ -1539,6 +3403,7 @@ private: class QCP_LIB_DECL QCPItemPosition : public QCPItemAnchor { + Q_GADGET public: /*! Defines the ways an item position can be specified. Thus it defines what the numbers passed to @@ -1555,8 +3420,9 @@ public: ///< vertically at the top of the axis rect, etc. You can also go beyond the axis rect by providing negative coordinates or coordinates larger than 1. ,ptPlotCoords ///< Dynamic positioning at a plot coordinate defined by two axes (see \ref setAxes). }; + Q_ENUMS(PositionType) - QCPItemPosition(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString name); + QCPItemPosition(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString &name); virtual ~QCPItemPosition(); // getters: @@ -1572,7 +3438,7 @@ public: QCPAxis *keyAxis() const { return mKeyAxis.data(); } QCPAxis *valueAxis() const { return mValueAxis.data(); } QCPAxisRect *axisRect() const; - virtual QPointF pixelPoint() const; + virtual QPointF pixelPosition() const; // setters: void setType(PositionType type); @@ -1585,7 +3451,7 @@ public: void setCoords(const QPointF &coords); void setAxes(QCPAxis* keyAxis, QCPAxis* valueAxis); void setAxisRect(QCPAxisRect *axisRect); - void setPixelPoint(const QPointF &pixelPoint); + void setPixelPosition(const QPointF &pixelPosition); protected: // property members: @@ -1596,12 +3462,13 @@ protected: QCPItemAnchor *mParentAnchorX, *mParentAnchorY; // reimplemented virtual methods: - virtual QCPItemPosition *toQCPItemPosition() { return this; } + virtual QCPItemPosition *toQCPItemPosition() Q_DECL_OVERRIDE { return this; } private: Q_DISABLE_COPY(QCPItemPosition) }; +Q_DECLARE_METATYPE(QCPItemPosition::PositionType) class QCP_LIB_DECL QCPAbstractItem : public QCPLayerable @@ -1614,7 +3481,7 @@ class QCP_LIB_DECL QCPAbstractItem : public QCPLayerable Q_PROPERTY(bool selected READ selected WRITE setSelected NOTIFY selectionChanged) /// \endcond public: - QCPAbstractItem(QCustomPlot *parentPlot); + explicit QCPAbstractItem(QCustomPlot *parentPlot); virtual ~QCPAbstractItem(); // getters: @@ -1630,7 +3497,7 @@ public: Q_SLOT void setSelected(bool selected); // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const = 0; + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const Q_DECL_OVERRIDE = 0; // non-virtual methods: QList positions() const { return mPositions; } @@ -1652,20 +3519,19 @@ protected: bool mSelectable, mSelected; // reimplemented virtual methods: - virtual QCP::Interaction selectionCategory() const; - virtual QRect clipRect() const; - virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const; - virtual void draw(QCPPainter *painter) = 0; + virtual QCP::Interaction selectionCategory() const Q_DECL_OVERRIDE; + virtual QRect clipRect() const Q_DECL_OVERRIDE; + virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const Q_DECL_OVERRIDE; + virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE = 0; // events: - virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged); - virtual void deselectEvent(bool *selectionStateChanged); + virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) Q_DECL_OVERRIDE; + virtual void deselectEvent(bool *selectionStateChanged) Q_DECL_OVERRIDE; // introduced virtual methods: - virtual QPointF anchorPixelPoint(int anchorId) const; + virtual QPointF anchorPixelPosition(int anchorId) const; // non-virtual methods: - double distSqrToLine(const QPointF &start, const QPointF &end, const QPointF &point) const; - double rectSelectTest(const QRectF &rect, const QPointF &pos, bool filledRect) const; + double rectDistance(const QRectF &rect, const QPointF &pos, bool filledRect) const; QCPItemPosition *createPosition(const QString &name); QCPItemAnchor *createAnchor(const QString &name, int anchorId); @@ -1676,6 +3542,11 @@ private: friend class QCPItemAnchor; }; +/* end of 'src/item.h' */ + + +/* including file 'src/core.h', size 14797 */ +/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */ class QCP_LIB_DECL QCustomPlot : public QWidget { @@ -1690,6 +3561,7 @@ class QCP_LIB_DECL QCustomPlot : public QWidget Q_PROPERTY(int selectionTolerance READ selectionTolerance WRITE setSelectionTolerance) Q_PROPERTY(bool noAntialiasingOnDrag READ noAntialiasingOnDrag WRITE setNoAntialiasingOnDrag) Q_PROPERTY(Qt::KeyboardModifier multiSelectModifier READ multiSelectModifier WRITE setMultiSelectModifier) + Q_PROPERTY(bool openGl READ openGl WRITE setOpenGl) /// \endcond public: /*! @@ -1707,16 +3579,19 @@ public: \see replot */ - enum RefreshPriority { rpImmediate ///< The QCustomPlot surface is immediately refreshed, by calling QWidget::repaint() after the replot - ,rpQueued ///< Queues the refresh such that it is performed at a slightly delayed point in time after the replot, by calling QWidget::update() after the replot - ,rpHint ///< Whether to use immediate repaint or queued update depends on whether the plotting hint \ref QCP::phForceRepaint is set, see \ref setPlottingHints. + enum RefreshPriority { rpImmediateRefresh ///< Replots immediately and repaints the widget immediately by calling QWidget::repaint() after the replot + ,rpQueuedRefresh ///< Replots immediately, but queues the widget repaint, by calling QWidget::update() after the replot. This way multiple redundant widget repaints can be avoided. + ,rpRefreshHint ///< Whether to use immediate or queued refresh depends on whether the plotting hint \ref QCP::phImmediateRefresh is set, see \ref setPlottingHints. + ,rpQueuedReplot ///< Queues the entire replot for the next event loop iteration. This way multiple redundant replots can be avoided. The actual replot is then done with \ref rpRefreshHint priority. }; + Q_ENUMS(RefreshPriority) explicit QCustomPlot(QWidget *parent = 0); virtual ~QCustomPlot(); // getters: QRect viewport() const { return mViewport; } + double bufferDevicePixelRatio() const { return mBufferDevicePixelRatio; } QPixmap background() const { return mBackgroundPixmap; } bool backgroundScaled() const { return mBackgroundScaled; } Qt::AspectRatioMode backgroundScaledMode() const { return mBackgroundScaledMode; } @@ -1729,9 +3604,13 @@ public: bool noAntialiasingOnDrag() const { return mNoAntialiasingOnDrag; } QCP::PlottingHints plottingHints() const { return mPlottingHints; } Qt::KeyboardModifier multiSelectModifier() const { return mMultiSelectModifier; } - + QCP::SelectionRectMode selectionRectMode() const { return mSelectionRectMode; } + QCPSelectionRect *selectionRect() const { return mSelectionRect; } + bool openGl() const { return mOpenGl; } + // setters: void setViewport(const QRect &rect); + void setBufferDevicePixelRatio(double ratio); void setBackground(const QPixmap &pm); void setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode=Qt::KeepAspectRatioByExpanding); void setBackground(const QBrush &brush); @@ -1749,12 +3628,14 @@ public: void setPlottingHints(const QCP::PlottingHints &hints); void setPlottingHint(QCP::PlottingHint hint, bool enabled=true); void setMultiSelectModifier(Qt::KeyboardModifier modifier); + void setSelectionRectMode(QCP::SelectionRectMode mode); + void setSelectionRect(QCPSelectionRect *selectionRect); + void setOpenGl(bool enabled, int multisampling=16); // non-property methods: // plottable interface: QCPAbstractPlottable *plottable(int index); QCPAbstractPlottable *plottable(); - bool addPlottable(QCPAbstractPlottable *plottable); bool removePlottable(QCPAbstractPlottable *plottable); bool removePlottable(int index); int clearPlottables(); @@ -1776,7 +3657,6 @@ public: // item interface: QCPAbstractItem *item(int index) const; QCPAbstractItem *item() const; - bool addItem(QCPAbstractItem* item); bool removeItem(QCPAbstractItem *item); bool removeItem(int index); int clearItems(); @@ -1801,20 +3681,21 @@ public: QCPAxisRect* axisRect(int index=0) const; QList axisRects() const; QCPLayoutElement* layoutElementAt(const QPointF &pos) const; + QCPAxisRect* axisRectAt(const QPointF &pos) const; Q_SLOT void rescaleAxes(bool onlyVisiblePlottables=false); QList selectedAxes() const; QList selectedLegends() const; Q_SLOT void deselectAll(); - bool savePdf(const QString &fileName, bool noCosmeticPen=false, int width=0, int height=0, const QString &pdfCreator=QString(), const QString &pdfTitle=QString()); - bool savePng(const QString &fileName, int width=0, int height=0, double scale=1.0, int quality=-1); - bool saveJpg(const QString &fileName, int width=0, int height=0, double scale=1.0, int quality=-1); - bool saveBmp(const QString &fileName, int width=0, int height=0, double scale=1.0); - bool saveRastered(const QString &fileName, int width, int height, double scale, const char *format, int quality=-1); + bool savePdf(const QString &fileName, int width=0, int height=0, QCP::ExportPen exportPen=QCP::epAllowCosmetic, const QString &pdfCreator=QString(), const QString &pdfTitle=QString()); + bool savePng(const QString &fileName, int width=0, int height=0, double scale=1.0, int quality=-1, int resolution=96, QCP::ResolutionUnit resolutionUnit=QCP::ruDotsPerInch); + bool saveJpg(const QString &fileName, int width=0, int height=0, double scale=1.0, int quality=-1, int resolution=96, QCP::ResolutionUnit resolutionUnit=QCP::ruDotsPerInch); + bool saveBmp(const QString &fileName, int width=0, int height=0, double scale=1.0, int resolution=96, QCP::ResolutionUnit resolutionUnit=QCP::ruDotsPerInch); + bool saveRastered(const QString &fileName, int width, int height, double scale, const char *format, int quality=-1, int resolution=96, QCP::ResolutionUnit resolutionUnit=QCP::ruDotsPerInch); QPixmap toPixmap(int width=0, int height=0, double scale=1.0); void toPainter(QCPPainter *painter, int width=0, int height=0); - Q_SLOT void replot(QCustomPlot::RefreshPriority refreshPriority=QCustomPlot::rpHint); + Q_SLOT void replot(QCustomPlot::RefreshPriority refreshPriority=QCustomPlot::rpRefreshHint); QCPAxis *xAxis, *yAxis, *xAxis2, *yAxis2; QCPLegend *legend; @@ -1826,16 +3707,14 @@ signals: void mouseRelease(QMouseEvent *event); void mouseWheel(QWheelEvent *event); - void plottableClick(QCPAbstractPlottable *plottable, QMouseEvent *event); - void plottableDoubleClick(QCPAbstractPlottable *plottable, QMouseEvent *event); + void plottableClick(QCPAbstractPlottable *plottable, int dataIndex, QMouseEvent *event); + void plottableDoubleClick(QCPAbstractPlottable *plottable, int dataIndex, QMouseEvent *event); void itemClick(QCPAbstractItem *item, QMouseEvent *event); void itemDoubleClick(QCPAbstractItem *item, QMouseEvent *event); void axisClick(QCPAxis *axis, QCPAxis::SelectablePart part, QMouseEvent *event); void axisDoubleClick(QCPAxis *axis, QCPAxis::SelectablePart part, QMouseEvent *event); void legendClick(QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event); void legendDoubleClick(QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event); - void titleClick(QMouseEvent *event, QCPPlotTitle *title); - void titleDoubleClick(QMouseEvent *event, QCPPlotTitle *title); void selectionChangedByUser(); void beforeReplot(); @@ -1844,6 +3723,7 @@ signals: protected: // property members: QRect mViewport; + double mBufferDevicePixelRatio; QCPLayoutGrid *mPlotLayout; bool mAutoAddPlottableToLegend; QList mPlottables; @@ -1862,40 +3742,656 @@ protected: QCPLayer *mCurrentLayer; QCP::PlottingHints mPlottingHints; Qt::KeyboardModifier mMultiSelectModifier; + QCP::SelectionRectMode mSelectionRectMode; + QCPSelectionRect *mSelectionRect; + bool mOpenGl; // non-property members: - QPixmap mPaintBuffer; + QList > mPaintBuffers; QPoint mMousePressPos; - QPointer mMouseEventElement; + bool mMouseHasMoved; + QPointer mMouseEventLayerable; + QVariant mMouseEventLayerableDetails; bool mReplotting; + bool mReplotQueued; + int mOpenGlMultisamples; + QCP::AntialiasedElements mOpenGlAntialiasedElementsBackup; + bool mOpenGlCacheLabelsBackup; +#ifdef QCP_OPENGL_FBO + QSharedPointer mGlContext; + QSharedPointer mGlSurface; + QSharedPointer mGlPaintDevice; +#endif // reimplemented virtual methods: - virtual QSize minimumSizeHint() const; - virtual QSize sizeHint() const; - virtual void paintEvent(QPaintEvent *event); - virtual void resizeEvent(QResizeEvent *event); - virtual void mouseDoubleClickEvent(QMouseEvent *event); - virtual void mousePressEvent(QMouseEvent *event); - virtual void mouseMoveEvent(QMouseEvent *event); - virtual void mouseReleaseEvent(QMouseEvent *event); - virtual void wheelEvent(QWheelEvent *event); + virtual QSize minimumSizeHint() const Q_DECL_OVERRIDE; + virtual QSize sizeHint() const Q_DECL_OVERRIDE; + virtual void paintEvent(QPaintEvent *event) Q_DECL_OVERRIDE; + virtual void resizeEvent(QResizeEvent *event) Q_DECL_OVERRIDE; + virtual void mouseDoubleClickEvent(QMouseEvent *event) Q_DECL_OVERRIDE; + virtual void mousePressEvent(QMouseEvent *event) Q_DECL_OVERRIDE; + virtual void mouseMoveEvent(QMouseEvent *event) Q_DECL_OVERRIDE; + virtual void mouseReleaseEvent(QMouseEvent *event) Q_DECL_OVERRIDE; + virtual void wheelEvent(QWheelEvent *event) Q_DECL_OVERRIDE; // introduced virtual methods: virtual void draw(QCPPainter *painter); + virtual void updateLayout(); virtual void axisRemoved(QCPAxis *axis); virtual void legendRemoved(QCPLegend *legend); + Q_SLOT virtual void processRectSelection(QRect rect, QMouseEvent *event); + Q_SLOT virtual void processRectZoom(QRect rect, QMouseEvent *event); + Q_SLOT virtual void processPointSelection(QMouseEvent *event); // non-virtual methods: + bool registerPlottable(QCPAbstractPlottable *plottable); + bool registerGraph(QCPGraph *graph); + bool registerItem(QCPAbstractItem* item); void updateLayerIndices() const; QCPLayerable *layerableAt(const QPointF &pos, bool onlySelectable, QVariant *selectionDetails=0) const; + QList layerableListAt(const QPointF &pos, bool onlySelectable, QList *selectionDetails=0) const; void drawBackground(QCPPainter *painter); + void setupPaintBuffers(); + QCPAbstractPaintBuffer *createPaintBuffer(); + bool hasInvalidatedPaintBuffers(); + bool setupOpenGl(); + void freeOpenGl(); friend class QCPLegend; friend class QCPAxis; friend class QCPLayer; friend class QCPAxisRect; + friend class QCPAbstractPlottable; + friend class QCPGraph; + friend class QCPAbstractItem; +}; +Q_DECLARE_METATYPE(QCustomPlot::LayerInsertMode) +Q_DECLARE_METATYPE(QCustomPlot::RefreshPriority) + +/* end of 'src/core.h' */ + + +/* including file 'src/plottable1d.h', size 4250 */ +/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */ + +class QCP_LIB_DECL QCPPlottableInterface1D +{ +public: + // introduced pure virtual methods: + virtual int dataCount() const = 0; + virtual double dataMainKey(int index) const = 0; + virtual double dataSortKey(int index) const = 0; + virtual double dataMainValue(int index) const = 0; + virtual QCPRange dataValueRange(int index) const = 0; + virtual QPointF dataPixelPosition(int index) const = 0; + virtual bool sortKeyIsMainKey() const = 0; + virtual QCPDataSelection selectTestRect(const QRectF &rect, bool onlySelectable) const = 0; + virtual int findBegin(double sortKey, bool expandedRange=true) const = 0; + virtual int findEnd(double sortKey, bool expandedRange=true) const = 0; }; +template +class QCP_LIB_DECL QCPAbstractPlottable1D : public QCPAbstractPlottable, public QCPPlottableInterface1D +{ + // No Q_OBJECT macro due to template class + +public: + QCPAbstractPlottable1D(QCPAxis *keyAxis, QCPAxis *valueAxis); + virtual ~QCPAbstractPlottable1D(); + + // virtual methods of 1d plottable interface: + virtual int dataCount() const; + virtual double dataMainKey(int index) const; + virtual double dataSortKey(int index) const; + virtual double dataMainValue(int index) const; + virtual QCPRange dataValueRange(int index) const; + virtual QPointF dataPixelPosition(int index) const; + virtual bool sortKeyIsMainKey() const; + virtual QCPDataSelection selectTestRect(const QRectF &rect, bool onlySelectable) const; + virtual int findBegin(double sortKey, bool expandedRange=true) const; + virtual int findEnd(double sortKey, bool expandedRange=true) const; + + // virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; + virtual QCPPlottableInterface1D *interface1D() { return this; } + +protected: + // property members: + QSharedPointer > mDataContainer; + + // helpers for subclasses: + void getDataSegments(QList &selectedSegments, QList &unselectedSegments) const; + void drawPolyline(QCPPainter *painter, const QVector &lineData) const; + +private: + Q_DISABLE_COPY(QCPAbstractPlottable1D) + +}; + +// include implementation in header since it is a class template: + +/* including file 'src/plottable1d.cpp', size 22240 */ +/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */ + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPPlottableInterface1D +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPPlottableInterface1D + \brief Defines an abstract interface for one-dimensional plottables + + This class contains only pure virtual methods which define a common interface to the data + of one-dimensional plottables. + + For example, it is implemented by the template class \ref QCPAbstractPlottable1D (the preferred + base class for one-dimensional plottables). So if you use that template class as base class of + your one-dimensional plottable, you won't have to care about implementing the 1d interface + yourself. + + If your plottable doesn't derive from \ref QCPAbstractPlottable1D but still wants to provide a 1d + interface (e.g. like \ref QCPErrorBars does), you should inherit from both \ref + QCPAbstractPlottable and \ref QCPPlottableInterface1D and accordingly reimplement the pure + virtual methods of the 1d interface, matching your data container. Also, reimplement \ref + QCPAbstractPlottable::interface1D to return the \c this pointer. + + If you have a \ref QCPAbstractPlottable pointer, you can check whether it implements this + interface by calling \ref QCPAbstractPlottable::interface1D and testing it for a non-zero return + value. If it indeed implements this interface, you may use it to access the plottable's data + without needing to know the exact type of the plottable or its data point type. +*/ + +/* start documentation of pure virtual functions */ + +/*! \fn virtual int QCPPlottableInterface1D::dataCount() const = 0; + + Returns the number of data points of the plottable. +*/ + +/*! \fn virtual QCPDataSelection QCPPlottableInterface1D::selectTestRect(const QRectF &rect, bool onlySelectable) const = 0; + + Returns a data selection containing all the data points of this plottable which are contained (or + hit by) \a rect. This is used mainly in the selection rect interaction for data selection (\ref + dataselection "data selection mechanism"). + + If \a onlySelectable is true, an empty QCPDataSelection is returned if this plottable is not + selectable (i.e. if \ref QCPAbstractPlottable::setSelectable is \ref QCP::stNone). + + \note \a rect must be a normalized rect (positive or zero width and height). This is especially + important when using the rect of \ref QCPSelectionRect::accepted, which is not necessarily + normalized. Use QRect::normalized() when passing a rect which might not be normalized. +*/ + +/*! \fn virtual double QCPPlottableInterface1D::dataMainKey(int index) const = 0 + + Returns the main key of the data point at the given \a index. + + What the main key is, is defined by the plottable's data type. See the \ref + qcpdatacontainer-datatype "QCPDataContainer DataType" documentation for details about this naming + convention. +*/ + +/*! \fn virtual double QCPPlottableInterface1D::dataSortKey(int index) const = 0 + + Returns the sort key of the data point at the given \a index. + + What the sort key is, is defined by the plottable's data type. See the \ref + qcpdatacontainer-datatype "QCPDataContainer DataType" documentation for details about this naming + convention. +*/ + +/*! \fn virtual double QCPPlottableInterface1D::dataMainValue(int index) const = 0 + + Returns the main value of the data point at the given \a index. + + What the main value is, is defined by the plottable's data type. See the \ref + qcpdatacontainer-datatype "QCPDataContainer DataType" documentation for details about this naming + convention. +*/ + +/*! \fn virtual QCPRange QCPPlottableInterface1D::dataValueRange(int index) const = 0 + + Returns the value range of the data point at the given \a index. + + What the value range is, is defined by the plottable's data type. See the \ref + qcpdatacontainer-datatype "QCPDataContainer DataType" documentation for details about this naming + convention. +*/ + +/*! \fn virtual QPointF QCPPlottableInterface1D::dataPixelPosition(int index) const = 0 + + Returns the pixel position on the widget surface at which the data point at the given \a index + appears. + + Usually this corresponds to the point of \ref dataMainKey/\ref dataMainValue, in pixel + coordinates. However, depending on the plottable, this might be a different apparent position + than just a coord-to-pixel transform of those values. For example, \ref QCPBars apparent data + values can be shifted depending on their stacking, bar grouping or configured base value. +*/ + +/*! \fn virtual bool QCPPlottableInterface1D::sortKeyIsMainKey() const = 0 + + Returns whether the sort key (\ref dataSortKey) is identical to the main key (\ref dataMainKey). + + What the sort and main keys are, is defined by the plottable's data type. See the \ref + qcpdatacontainer-datatype "QCPDataContainer DataType" documentation for details about this naming + convention. +*/ + +/*! \fn virtual int QCPPlottableInterface1D::findBegin(double sortKey, bool expandedRange) const = 0 + + Returns the index of the data point with a (sort-)key that is equal to, just below, or just above + \a sortKey. If \a expandedRange is true, the data point just below \a sortKey will be considered, + otherwise the one just above. + + This can be used in conjunction with \ref findEnd to iterate over data points within a given key + range, including or excluding the bounding data points that are just beyond the specified range. + + If \a expandedRange is true but there are no data points below \a sortKey, 0 is returned. + + If the container is empty, returns 0 (in that case, \ref findEnd will also return 0, so a loop + using these methods will not iterate over the index 0). + + \see findEnd, QCPDataContainer::findBegin +*/ + +/*! \fn virtual int QCPPlottableInterface1D::findEnd(double sortKey, bool expandedRange) const = 0 + + Returns the index one after the data point with a (sort-)key that is equal to, just above, or + just below \a sortKey. If \a expandedRange is true, the data point just above \a sortKey will be + considered, otherwise the one just below. + + This can be used in conjunction with \ref findBegin to iterate over data points within a given + key range, including the bounding data points that are just below and above the specified range. + + If \a expandedRange is true but there are no data points above \a sortKey, the index just above the + highest data point is returned. + + If the container is empty, returns 0. + + \see findBegin, QCPDataContainer::findEnd +*/ + +/* end documentation of pure virtual functions */ + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPAbstractPlottable1D +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPAbstractPlottable1D + \brief A template base class for plottables with one-dimensional data + + This template class derives from \ref QCPAbstractPlottable and from the abstract interface \ref + QCPPlottableInterface1D. It serves as a base class for all one-dimensional data (i.e. data with + one key dimension), such as \ref QCPGraph and QCPCurve. + + The template parameter \a DataType is the type of the data points of this plottable (e.g. \ref + QCPGraphData or \ref QCPCurveData). The main purpose of this base class is to provide the member + \a mDataContainer (a shared pointer to a \ref QCPDataContainer "QCPDataContainer") and + implement the according virtual methods of the \ref QCPPlottableInterface1D, such that most + subclassed plottables don't need to worry about this anymore. + + Further, it provides a convenience method for retrieving selected/unselected data segments via + \ref getDataSegments. This is useful when subclasses implement their \ref draw method and need to + draw selected segments with a different pen/brush than unselected segments (also see \ref + QCPSelectionDecorator). + + This class implements basic functionality of \ref QCPAbstractPlottable::selectTest and \ref + QCPPlottableInterface1D::selectTestRect, assuming point-like data points, based on the 1D data + interface. In spite of that, most plottable subclasses will want to reimplement those methods + again, to provide a more accurate hit test based on their specific data visualization geometry. +*/ + +/* start documentation of inline functions */ + +/*! \fn QCPPlottableInterface1D *QCPAbstractPlottable1D::interface1D() + + Returns a \ref QCPPlottableInterface1D pointer to this plottable, providing access to its 1D + interface. + + \seebaseclassmethod +*/ + +/* end documentation of inline functions */ + +/*! + Forwards \a keyAxis and \a valueAxis to the \ref QCPAbstractPlottable::QCPAbstractPlottable + "QCPAbstractPlottable" constructor and allocates the \a mDataContainer. +*/ +template +QCPAbstractPlottable1D::QCPAbstractPlottable1D(QCPAxis *keyAxis, QCPAxis *valueAxis) : + QCPAbstractPlottable(keyAxis, valueAxis), + mDataContainer(new QCPDataContainer) +{ +} + +template +QCPAbstractPlottable1D::~QCPAbstractPlottable1D() +{ +} + +/*! + \copydoc QCPPlottableInterface1D::dataCount +*/ +template +int QCPAbstractPlottable1D::dataCount() const +{ + return mDataContainer->size(); +} + +/*! + \copydoc QCPPlottableInterface1D::dataMainKey +*/ +template +double QCPAbstractPlottable1D::dataMainKey(int index) const +{ + if (index >= 0 && index < mDataContainer->size()) + { + return (mDataContainer->constBegin()+index)->mainKey(); + } else + { + qDebug() << Q_FUNC_INFO << "Index out of bounds" << index; + return 0; + } +} + +/*! + \copydoc QCPPlottableInterface1D::dataSortKey +*/ +template +double QCPAbstractPlottable1D::dataSortKey(int index) const +{ + if (index >= 0 && index < mDataContainer->size()) + { + return (mDataContainer->constBegin()+index)->sortKey(); + } else + { + qDebug() << Q_FUNC_INFO << "Index out of bounds" << index; + return 0; + } +} + +/*! + \copydoc QCPPlottableInterface1D::dataMainValue +*/ +template +double QCPAbstractPlottable1D::dataMainValue(int index) const +{ + if (index >= 0 && index < mDataContainer->size()) + { + return (mDataContainer->constBegin()+index)->mainValue(); + } else + { + qDebug() << Q_FUNC_INFO << "Index out of bounds" << index; + return 0; + } +} + +/*! + \copydoc QCPPlottableInterface1D::dataValueRange +*/ +template +QCPRange QCPAbstractPlottable1D::dataValueRange(int index) const +{ + if (index >= 0 && index < mDataContainer->size()) + { + return (mDataContainer->constBegin()+index)->valueRange(); + } else + { + qDebug() << Q_FUNC_INFO << "Index out of bounds" << index; + return QCPRange(0, 0); + } +} + +/*! + \copydoc QCPPlottableInterface1D::dataPixelPosition +*/ +template +QPointF QCPAbstractPlottable1D::dataPixelPosition(int index) const +{ + if (index >= 0 && index < mDataContainer->size()) + { + const typename QCPDataContainer::const_iterator it = mDataContainer->constBegin()+index; + return coordsToPixels(it->mainKey(), it->mainValue()); + } else + { + qDebug() << Q_FUNC_INFO << "Index out of bounds" << index; + return QPointF(); + } +} + +/*! + \copydoc QCPPlottableInterface1D::sortKeyIsMainKey +*/ +template +bool QCPAbstractPlottable1D::sortKeyIsMainKey() const +{ + return DataType::sortKeyIsMainKey(); +} + +/*! + Implements a rect-selection algorithm assuming the data (accessed via the 1D data interface) is + point-like. Most subclasses will want to reimplement this method again, to provide a more + accurate hit test based on the true data visualization geometry. + + \seebaseclassmethod +*/ +template +QCPDataSelection QCPAbstractPlottable1D::selectTestRect(const QRectF &rect, bool onlySelectable) const +{ + QCPDataSelection result; + if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty()) + return result; + if (!mKeyAxis || !mValueAxis) + return result; + + // convert rect given in pixels to ranges given in plot coordinates: + double key1, value1, key2, value2; + pixelsToCoords(rect.topLeft(), key1, value1); + pixelsToCoords(rect.bottomRight(), key2, value2); + QCPRange keyRange(key1, key2); // QCPRange normalizes internally so we don't have to care about whether key1 < key2 + QCPRange valueRange(value1, value2); + typename QCPDataContainer::const_iterator begin = mDataContainer->constBegin(); + typename QCPDataContainer::const_iterator end = mDataContainer->constEnd(); + if (DataType::sortKeyIsMainKey()) // we can assume that data is sorted by main key, so can reduce the searched key interval: + { + begin = mDataContainer->findBegin(keyRange.lower, false); + end = mDataContainer->findEnd(keyRange.upper, false); + } + if (begin == end) + return result; + + int currentSegmentBegin = -1; // -1 means we're currently not in a segment that's contained in rect + for (typename QCPDataContainer::const_iterator it=begin; it!=end; ++it) + { + if (currentSegmentBegin == -1) + { + if (valueRange.contains(it->mainValue()) && keyRange.contains(it->mainKey())) // start segment + currentSegmentBegin = it-mDataContainer->constBegin(); + } else if (!valueRange.contains(it->mainValue()) || !keyRange.contains(it->mainKey())) // segment just ended + { + result.addDataRange(QCPDataRange(currentSegmentBegin, it-mDataContainer->constBegin()), false); + currentSegmentBegin = -1; + } + } + // process potential last segment: + if (currentSegmentBegin != -1) + result.addDataRange(QCPDataRange(currentSegmentBegin, end-mDataContainer->constBegin()), false); + + result.simplify(); + return result; +} + +/*! + \copydoc QCPPlottableInterface1D::findBegin +*/ +template +int QCPAbstractPlottable1D::findBegin(double sortKey, bool expandedRange) const +{ + return mDataContainer->findBegin(sortKey, expandedRange)-mDataContainer->constBegin(); +} + +/*! + \copydoc QCPPlottableInterface1D::findEnd +*/ +template +int QCPAbstractPlottable1D::findEnd(double sortKey, bool expandedRange) const +{ + return mDataContainer->findEnd(sortKey, expandedRange)-mDataContainer->constBegin(); +} + +/*! + Implements a point-selection algorithm assuming the data (accessed via the 1D data interface) is + point-like. Most subclasses will want to reimplement this method again, to provide a more + accurate hit test based on the true data visualization geometry. + + \seebaseclassmethod +*/ +template +double QCPAbstractPlottable1D::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const +{ + if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty()) + return -1; + if (!mKeyAxis || !mValueAxis) + return -1; + + QCPDataSelection selectionResult; + double minDistSqr = std::numeric_limits::max(); + int minDistIndex = mDataContainer->size(); + + typename QCPDataContainer::const_iterator begin = mDataContainer->constBegin(); + typename QCPDataContainer::const_iterator end = mDataContainer->constEnd(); + if (DataType::sortKeyIsMainKey()) // we can assume that data is sorted by main key, so can reduce the searched key interval: + { + // determine which key range comes into question, taking selection tolerance around pos into account: + double posKeyMin, posKeyMax, dummy; + pixelsToCoords(pos-QPointF(mParentPlot->selectionTolerance(), mParentPlot->selectionTolerance()), posKeyMin, dummy); + pixelsToCoords(pos+QPointF(mParentPlot->selectionTolerance(), mParentPlot->selectionTolerance()), posKeyMax, dummy); + if (posKeyMin > posKeyMax) + qSwap(posKeyMin, posKeyMax); + begin = mDataContainer->findBegin(posKeyMin, true); + end = mDataContainer->findEnd(posKeyMax, true); + } + if (begin == end) + return -1; + QCPRange keyRange(mKeyAxis->range()); + QCPRange valueRange(mValueAxis->range()); + for (typename QCPDataContainer::const_iterator it=begin; it!=end; ++it) + { + const double mainKey = it->mainKey(); + const double mainValue = it->mainValue(); + if (keyRange.contains(mainKey) && valueRange.contains(mainValue)) // make sure data point is inside visible range, for speedup in cases where sort key isn't main key and we iterate over all points + { + const double currentDistSqr = QCPVector2D(coordsToPixels(mainKey, mainValue)-pos).lengthSquared(); + if (currentDistSqr < minDistSqr) + { + minDistSqr = currentDistSqr; + minDistIndex = it-mDataContainer->constBegin(); + } + } + } + if (minDistIndex != mDataContainer->size()) + selectionResult.addDataRange(QCPDataRange(minDistIndex, minDistIndex+1), false); + + selectionResult.simplify(); + if (details) + details->setValue(selectionResult); + return qSqrt(minDistSqr); +} + +/*! + Splits all data into selected and unselected segments and outputs them via \a selectedSegments + and \a unselectedSegments, respectively. + + This is useful when subclasses implement their \ref draw method and need to draw selected + segments with a different pen/brush than unselected segments (also see \ref + QCPSelectionDecorator). + + \see setSelection +*/ +template +void QCPAbstractPlottable1D::getDataSegments(QList &selectedSegments, QList &unselectedSegments) const +{ + selectedSegments.clear(); + unselectedSegments.clear(); + if (mSelectable == QCP::stWhole) // stWhole selection type draws the entire plottable with selected style if mSelection isn't empty + { + if (selected()) + selectedSegments << QCPDataRange(0, dataCount()); + else + unselectedSegments << QCPDataRange(0, dataCount()); + } else + { + QCPDataSelection sel(selection()); + sel.simplify(); + selectedSegments = sel.dataRanges(); + unselectedSegments = sel.inverse(QCPDataRange(0, dataCount())).dataRanges(); + } +} + +/*! + A helper method which draws a line with the passed \a painter, according to the pixel data in \a + lineData. NaN points create gaps in the line, as expected from QCustomPlot's plottables (this is + the main difference to QPainter's regular drawPolyline, which handles NaNs by lagging or + crashing). + + Further it uses a faster line drawing technique based on \ref QCPPainter::drawLine rather than \c + QPainter::drawPolyline if the configured \ref QCustomPlot::setPlottingHints() and \a painter + style allows. +*/ +template +void QCPAbstractPlottable1D::drawPolyline(QCPPainter *painter, const QVector &lineData) const +{ + // 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()) || qIsInf(lineData.at(i).y())) // NaNs create a gap in the line. Also filter Infs which make drawPolyline block + { + 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); + } +} +/* end of 'src/plottable1d.cpp' */ + + +/* end of 'src/plottable1d.h' */ + + +/* including file 'src/colorgradient.h', size 6243 */ +/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */ class QCP_LIB_DECL QCPColorGradient { @@ -1930,7 +4426,8 @@ public: }; Q_ENUMS(GradientPreset) - QCPColorGradient(GradientPreset preset=gpCold); + QCPColorGradient(); + QCPColorGradient(GradientPreset preset); bool operator==(const QCPColorGradient &other) const; bool operator!=(const QCPColorGradient &other) const { return !(*this == other); } @@ -1949,14 +4446,13 @@ public: // non-property methods: void colorize(const double *data, const QCPRange &range, QRgb *scanLine, int n, int dataIndexFactor=1, bool logarithmic=false); + void colorize(const double *data, const unsigned char *alpha, const QCPRange &range, QRgb *scanLine, int n, int dataIndexFactor=1, bool logarithmic=false); QRgb color(double position, const QCPRange &range, bool logarithmic=false); void loadPreset(GradientPreset preset); void clearColorStops(); QCPColorGradient inverted() const; protected: - void updateColorBuffer(); - // property members: int mLevelCount; QMap mColorStops; @@ -1964,10 +4460,90 @@ protected: bool mPeriodic; // non-property members: - QVector mColorBuffer; + QVector mColorBuffer; // have colors premultiplied with alpha (for usage with QImage::Format_ARGB32_Premultiplied) bool mColorBufferInvalidated; + + // non-virtual methods: + bool stopsUseAlpha() const; + void updateColorBuffer(); }; +Q_DECLARE_METATYPE(QCPColorGradient::ColorInterpolation) +Q_DECLARE_METATYPE(QCPColorGradient::GradientPreset) +/* end of 'src/colorgradient.h' */ + + +/* including file 'src/selectiondecorator-bracket.h', size 4426 */ +/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */ + +class QCP_LIB_DECL QCPSelectionDecoratorBracket : public QCPSelectionDecorator +{ + Q_GADGET +public: + + /*! + Defines which shape is drawn at the boundaries of selected data ranges. + + Some of the bracket styles further allow specifying a height and/or width, see \ref + setBracketHeight and \ref setBracketWidth. + */ + enum BracketStyle { bsSquareBracket ///< A square bracket is drawn. + ,bsHalfEllipse ///< A half ellipse is drawn. The size of the ellipse is given by the bracket width/height properties. + ,bsEllipse ///< An ellipse is drawn. The size of the ellipse is given by the bracket width/height properties. + ,bsPlus ///< A plus is drawn. + ,bsUserStyle ///< Start custom bracket styles at this index when subclassing and reimplementing \ref drawBracket. + }; + Q_ENUMS(BracketStyle) + + QCPSelectionDecoratorBracket(); + virtual ~QCPSelectionDecoratorBracket(); + + // getters: + QPen bracketPen() const { return mBracketPen; } + QBrush bracketBrush() const { return mBracketBrush; } + int bracketWidth() const { return mBracketWidth; } + int bracketHeight() const { return mBracketHeight; } + BracketStyle bracketStyle() const { return mBracketStyle; } + bool tangentToData() const { return mTangentToData; } + int tangentAverage() const { return mTangentAverage; } + + // setters: + void setBracketPen(const QPen &pen); + void setBracketBrush(const QBrush &brush); + void setBracketWidth(int width); + void setBracketHeight(int height); + void setBracketStyle(BracketStyle style); + void setTangentToData(bool enabled); + void setTangentAverage(int pointCount); + + // introduced virtual methods: + virtual void drawBracket(QCPPainter *painter, int direction) const; + + // virtual methods: + virtual void drawDecoration(QCPPainter *painter, QCPDataSelection selection); + +protected: + // property members: + QPen mBracketPen; + QBrush mBracketBrush; + int mBracketWidth; + int mBracketHeight; + BracketStyle mBracketStyle; + bool mTangentToData; + int mTangentAverage; + + // non-virtual methods: + double getTangentAngle(const QCPPlottableInterface1D *interface1d, int dataIndex, int direction) const; + QPointF getPixelCoordinates(const QCPPlottableInterface1D *interface1d, int dataIndex) const; + +}; +Q_DECLARE_METATYPE(QCPSelectionDecoratorBracket::BracketStyle) + +/* end of 'src/selectiondecorator-bracket.h' */ + + +/* including file 'src/layoutelements/layoutelement-axisrect.h', size 7528 */ +/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */ class QCP_LIB_DECL QCPAxisRect : public QCPLayoutElement { @@ -1985,12 +4561,15 @@ public: // getters: QPixmap background() const { return mBackgroundPixmap; } + QBrush backgroundBrush() const { return mBackgroundBrush; } bool backgroundScaled() const { return mBackgroundScaled; } Qt::AspectRatioMode backgroundScaledMode() const { return mBackgroundScaledMode; } Qt::Orientations rangeDrag() const { return mRangeDrag; } Qt::Orientations rangeZoom() const { return mRangeZoom; } QCPAxis *rangeDragAxis(Qt::Orientation orientation); QCPAxis *rangeZoomAxis(Qt::Orientation orientation); + QList rangeDragAxes(Qt::Orientation orientation); + QList rangeZoomAxes(Qt::Orientation orientation); double rangeZoomFactor(Qt::Orientation orientation); // setters: @@ -2002,7 +4581,11 @@ public: void setRangeDrag(Qt::Orientations orientations); void setRangeZoom(Qt::Orientations orientations); void setRangeDragAxes(QCPAxis *horizontal, QCPAxis *vertical); + void setRangeDragAxes(QList axes); + void setRangeDragAxes(QList horizontal, QList vertical); void setRangeZoomAxes(QCPAxis *horizontal, QCPAxis *vertical); + void setRangeZoomAxes(QList axes); + void setRangeZoomAxes(QList horizontal, QList vertical); void setRangeZoomFactor(double horizontalFactor, double verticalFactor); void setRangeZoomFactor(double factor); @@ -2016,6 +4599,8 @@ public: bool removeAxis(QCPAxis *axis); QCPLayoutInset *insetLayout() const { return mInsetLayout; } + void zoom(const QRectF &pixelRect); + void zoom(const QRectF &pixelRect, const QList &affectedAxes); void setupFullAxesBox(bool connectRanges=false); QList plottables() const; QList graphs() const; @@ -2036,8 +4621,8 @@ public: QPoint center() const { return mRect.center(); } // reimplemented virtual methods: - virtual void update(UpdatePhase phase); - virtual QList elements(bool recursive) const; + virtual void update(UpdatePhase phase) Q_DECL_OVERRIDE; + virtual QList elements(bool recursive) const Q_DECL_OVERRIDE; protected: // property members: @@ -2048,24 +4633,27 @@ protected: Qt::AspectRatioMode mBackgroundScaledMode; QCPLayoutInset *mInsetLayout; Qt::Orientations mRangeDrag, mRangeZoom; - QPointer mRangeDragHorzAxis, mRangeDragVertAxis, mRangeZoomHorzAxis, mRangeZoomVertAxis; + QList > mRangeDragHorzAxis, mRangeDragVertAxis; + QList > mRangeZoomHorzAxis, mRangeZoomVertAxis; double mRangeZoomFactorHorz, mRangeZoomFactorVert; + // non-property members: - QCPRange mDragStartHorzRange, mDragStartVertRange; + QList mDragStartHorzRange, mDragStartVertRange; QCP::AntialiasedElements mAADragBackup, mNotAADragBackup; QPoint mDragStart; bool mDragging; QHash > mAxes; // reimplemented virtual methods: - virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const; - virtual void draw(QCPPainter *painter); - virtual int calculateAutoMargin(QCP::MarginSide side); + virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const Q_DECL_OVERRIDE; + virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; + virtual int calculateAutoMargin(QCP::MarginSide side) Q_DECL_OVERRIDE; + virtual void layoutChanged() Q_DECL_OVERRIDE; // events: - virtual void mousePressEvent(QMouseEvent *event); - virtual void mouseMoveEvent(QMouseEvent *event); - virtual void mouseReleaseEvent(QMouseEvent *event); - virtual void wheelEvent(QWheelEvent *event); + virtual void mousePressEvent(QMouseEvent *event, const QVariant &details) Q_DECL_OVERRIDE; + virtual void mouseMoveEvent(QMouseEvent *event, const QPointF &startPos) Q_DECL_OVERRIDE; + virtual void mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos) Q_DECL_OVERRIDE; + virtual void wheelEvent(QWheelEvent *event) Q_DECL_OVERRIDE; // non-property methods: void drawBackground(QCPPainter *painter); @@ -2078,6 +4666,12 @@ private: }; +/* end of 'src/layoutelements/layoutelement-axisrect.h' */ + + +/* including file 'src/layoutelements/layoutelement-legend.h', size 10392 */ +/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */ + class QCP_LIB_DECL QCPAbstractLegendItem : public QCPLayoutElement { Q_OBJECT @@ -2111,7 +4705,7 @@ public: Q_SLOT void setSelected(bool selected); // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const Q_DECL_OVERRIDE; signals: void selectionChanged(bool selected); @@ -2127,13 +4721,13 @@ protected: bool mSelectable, mSelected; // reimplemented virtual methods: - virtual QCP::Interaction selectionCategory() const; - virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const; - virtual QRect clipRect() const; - virtual void draw(QCPPainter *painter) = 0; + virtual QCP::Interaction selectionCategory() const Q_DECL_OVERRIDE; + virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const Q_DECL_OVERRIDE; + virtual QRect clipRect() const Q_DECL_OVERRIDE; + virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE = 0; // events: - virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged); - virtual void deselectEvent(bool *selectionStateChanged); + virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) Q_DECL_OVERRIDE; + virtual void deselectEvent(bool *selectionStateChanged) Q_DECL_OVERRIDE; private: Q_DISABLE_COPY(QCPAbstractLegendItem) @@ -2156,8 +4750,8 @@ protected: QCPAbstractPlottable *mPlottable; // reimplemented virtual methods: - virtual void draw(QCPPainter *painter); - virtual QSize minimumSizeHint() const; + virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; + virtual QSize minimumSizeHint() const Q_DECL_OVERRIDE; // non-virtual methods: QPen getIconBorderPen() const; @@ -2191,11 +4785,12 @@ public: \see setSelectedParts, setSelectableParts */ - enum SelectablePart { spNone = 0x000 ///< 0x000 None + enum SelectablePart { spNone = 0x000 ///< 0x000 None ,spLegendBox = 0x001 ///< 0x001 The legend box (frame) ,spItems = 0x002 ///< 0x002 Legend items individually (see \ref selectedItems) }; - Q_FLAGS(SelectablePart SelectableParts) + Q_ENUMS(SelectablePart) + Q_FLAGS(SelectableParts) Q_DECLARE_FLAGS(SelectableParts, SelectablePart) explicit QCPLegend(); @@ -2235,7 +4830,7 @@ public: void setSelectedTextColor(const QColor &color); // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const Q_DECL_OVERRIDE; // non-virtual methods: QCPAbstractLegendItem *item(int index) const; @@ -2268,13 +4863,13 @@ protected: QColor mSelectedTextColor; // reimplemented virtual methods: - virtual void parentPlotInitialized(QCustomPlot *parentPlot); - virtual QCP::Interaction selectionCategory() const; - virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const; - virtual void draw(QCPPainter *painter); + virtual void parentPlotInitialized(QCustomPlot *parentPlot) Q_DECL_OVERRIDE; + virtual QCP::Interaction selectionCategory() const Q_DECL_OVERRIDE; + virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const Q_DECL_OVERRIDE; + virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; // events: - virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged); - virtual void deselectEvent(bool *selectionStateChanged); + virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) Q_DECL_OVERRIDE; + virtual void deselectEvent(bool *selectionStateChanged) Q_DECL_OVERRIDE; // non-virtual methods: QPen getBorderPen() const; @@ -2289,8 +4884,13 @@ private: Q_DECLARE_OPERATORS_FOR_FLAGS(QCPLegend::SelectableParts) Q_DECLARE_METATYPE(QCPLegend::SelectablePart) +/* end of 'src/layoutelements/layoutelement-legend.h' */ -class QCP_LIB_DECL QCPPlotTitle : public QCPLayoutElement + +/* including file 'src/layoutelements/layoutelement-textelement.h', size 5343 */ +/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */ + +class QCP_LIB_DECL QCPTextElement : public QCPLayoutElement { Q_OBJECT /// \cond INCLUDE_QPROPERTIES @@ -2303,11 +4903,15 @@ class QCP_LIB_DECL QCPPlotTitle : public QCPLayoutElement Q_PROPERTY(bool selected READ selected WRITE setSelected NOTIFY selectionChanged) /// \endcond public: - explicit QCPPlotTitle(QCustomPlot *parentPlot); - explicit QCPPlotTitle(QCustomPlot *parentPlot, const QString &text); + explicit QCPTextElement(QCustomPlot *parentPlot); + QCPTextElement(QCustomPlot *parentPlot, const QString &text); + QCPTextElement(QCustomPlot *parentPlot, const QString &text, double pointSize); + QCPTextElement(QCustomPlot *parentPlot, const QString &text, const QString &fontFamily, double pointSize); + QCPTextElement(QCustomPlot *parentPlot, const QString &text, const QFont &font); // getters: QString text() const { return mText; } + int textFlags() const { return mTextFlags; } QFont font() const { return mFont; } QColor textColor() const { return mTextColor; } QFont selectedFont() const { return mSelectedFont; } @@ -2317,6 +4921,7 @@ public: // setters: void setText(const QString &text); + void setTextFlags(int flags); void setFont(const QFont &font); void setTextColor(const QColor &color); void setSelectedFont(const QFont &font); @@ -2325,15 +4930,21 @@ public: Q_SLOT void setSelected(bool selected); // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const Q_DECL_OVERRIDE; + virtual void mousePressEvent(QMouseEvent *event, const QVariant &details) Q_DECL_OVERRIDE; + virtual void mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos) Q_DECL_OVERRIDE; + virtual void mouseDoubleClickEvent(QMouseEvent *event, const QVariant &details) Q_DECL_OVERRIDE; signals: void selectionChanged(bool selected); void selectableChanged(bool selectable); + void clicked(QMouseEvent *event); + void doubleClicked(QMouseEvent *event); protected: // property members: QString mText; + int mTextFlags; QFont mFont; QColor mTextColor; QFont mSelectedFont; @@ -2342,23 +4953,31 @@ protected: bool mSelectable, mSelected; // reimplemented virtual methods: - virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const; - virtual void draw(QCPPainter *painter); - virtual QSize minimumSizeHint() const; - virtual QSize maximumSizeHint() const; + virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const Q_DECL_OVERRIDE; + virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; + virtual QSize minimumSizeHint() const Q_DECL_OVERRIDE; + virtual QSize maximumSizeHint() const Q_DECL_OVERRIDE; // events: - virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged); - virtual void deselectEvent(bool *selectionStateChanged); + virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) Q_DECL_OVERRIDE; + virtual void deselectEvent(bool *selectionStateChanged) Q_DECL_OVERRIDE; // non-virtual methods: QFont mainFont() const; QColor mainTextColor() const; private: - Q_DISABLE_COPY(QCPPlotTitle) + Q_DISABLE_COPY(QCPTextElement) }; + +/* end of 'src/layoutelements/layoutelement-textelement.h' */ + + +/* including file 'src/layoutelements/layoutelement-colorscale.h', size 5907 */ +/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */ + + class QCPColorScaleAxisRectPrivate : public QCPAxisRect { Q_OBJECT @@ -2426,12 +5045,12 @@ public: void rescaleDataRange(bool onlyVisibleMaps); // reimplemented virtual methods: - virtual void update(UpdatePhase phase); + virtual void update(UpdatePhase phase) Q_DECL_OVERRIDE; signals: - void dataRangeChanged(QCPRange newRange); + void dataRangeChanged(const QCPRange &newRange); void dataScaleTypeChanged(QCPAxis::ScaleType scaleType); - void gradientChanged(QCPColorGradient newGradient); + void gradientChanged(const QCPColorGradient &newGradient); protected: // property members: @@ -2446,12 +5065,12 @@ protected: QPointer mColorAxis; // reimplemented virtual methods: - virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const; + virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const Q_DECL_OVERRIDE; // events: - virtual void mousePressEvent(QMouseEvent *event); - virtual void mouseMoveEvent(QMouseEvent *event); - virtual void mouseReleaseEvent(QMouseEvent *event); - virtual void wheelEvent(QWheelEvent *event); + virtual void mousePressEvent(QMouseEvent *event, const QVariant &details) Q_DECL_OVERRIDE; + virtual void mouseMoveEvent(QMouseEvent *event, const QPointF &startPos) Q_DECL_OVERRIDE; + virtual void mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos) Q_DECL_OVERRIDE; + virtual void wheelEvent(QWheelEvent *event) Q_DECL_OVERRIDE; private: Q_DISABLE_COPY(QCPColorScale) @@ -2460,43 +5079,50 @@ private: }; -/*! \file */ +/* end of 'src/layoutelements/layoutelement-colorscale.h' */ +/* including file 'src/plottables/plottable-graph.h', size 8826 */ +/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */ -class QCP_LIB_DECL QCPData +class QCP_LIB_DECL QCPGraphData { public: - QCPData(); - QCPData(double key, double value); - double key, value; - double keyErrorPlus, keyErrorMinus; - double valueErrorPlus, valueErrorMinus; -}; -Q_DECLARE_TYPEINFO(QCPData, Q_MOVABLE_TYPE); - -/*! \typedef QCPDataMap - Container for storing \ref QCPData items in a sorted fashion. The key of the map - is the key member of the QCPData instance. + QCPGraphData(); + QCPGraphData(double key, double value); - This is the container in which QCPGraph holds its data. - \see QCPData, QCPGraph::setData + inline double sortKey() const { return key; } + inline static QCPGraphData fromSortKey(double sortKey) { return QCPGraphData(sortKey, 0); } + inline static bool sortKeyIsMainKey() { return true; } + + inline double mainKey() const { return key; } + inline double mainValue() const { return value; } + + inline QCPRange valueRange() const { return QCPRange(value, value); } + + double key, value; +}; +Q_DECLARE_TYPEINFO(QCPGraphData, Q_PRIMITIVE_TYPE); + + +/*! \typedef QCPGraphDataContainer + + Container for storing \ref QCPGraphData points. The data is stored sorted by \a key. + + This template instantiation is the container in which QCPGraph holds its data. For details about + the generic container, see the documentation of the class template \ref QCPDataContainer. + + \see QCPGraphData, QCPGraph::setData */ -typedef QMap QCPDataMap; -typedef QMapIterator QCPDataMapIterator; -typedef QMutableMapIterator QCPDataMutableMapIterator; +typedef QCPDataContainer QCPGraphDataContainer; - -class QCP_LIB_DECL QCPGraph : public QCPAbstractPlottable +class QCP_LIB_DECL QCPGraph : public QCPAbstractPlottable1D { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(LineStyle lineStyle READ lineStyle WRITE setLineStyle) Q_PROPERTY(QCPScatterStyle scatterStyle READ scatterStyle WRITE setScatterStyle) - Q_PROPERTY(ErrorType errorType READ errorType WRITE setErrorType) - Q_PROPERTY(QPen errorPen READ errorPen WRITE setErrorPen) - Q_PROPERTY(double errorBarSize READ errorBarSize WRITE setErrorBarSize) - Q_PROPERTY(bool errorBarSkipSymbol READ errorBarSkipSymbol WRITE setErrorBarSkipSymbol) + Q_PROPERTY(int scatterSkip READ scatterSkip WRITE setScatterSkip) Q_PROPERTY(QCPGraph* channelFillGraph READ channelFillGraph WRITE setChannelFillGraph) Q_PROPERTY(bool adaptiveSampling READ adaptiveSampling WRITE setAdaptiveSampling) /// \endcond @@ -2515,153 +5141,126 @@ public: ,lsImpulse ///< each data point is represented by a line parallel to the value axis, which reaches from the data point to the zero-value-line }; Q_ENUMS(LineStyle) - /*! - Defines what kind of error bars are drawn for each data point - */ - enum ErrorType { etNone ///< No error bars are shown - ,etKey ///< Error bars for the key dimension of the data point are shown - ,etValue ///< Error bars for the value dimension of the data point are shown - ,etBoth ///< Error bars for both key and value dimensions of the data point are shown - }; - Q_ENUMS(ErrorType) explicit QCPGraph(QCPAxis *keyAxis, QCPAxis *valueAxis); virtual ~QCPGraph(); // getters: - QCPDataMap *data() const { return mData; } + QSharedPointer data() const { return mDataContainer; } LineStyle lineStyle() const { return mLineStyle; } QCPScatterStyle scatterStyle() const { return mScatterStyle; } - ErrorType errorType() const { return mErrorType; } - QPen errorPen() const { return mErrorPen; } - double errorBarSize() const { return mErrorBarSize; } - bool errorBarSkipSymbol() const { return mErrorBarSkipSymbol; } + int scatterSkip() const { return mScatterSkip; } QCPGraph *channelFillGraph() const { return mChannelFillGraph.data(); } bool adaptiveSampling() const { return mAdaptiveSampling; } // setters: - void setData(QCPDataMap *data, bool copy=false); - void setData(const QVector &key, const QVector &value); - void setDataKeyError(const QVector &key, const QVector &value, const QVector &keyError); - void setDataKeyError(const QVector &key, const QVector &value, const QVector &keyErrorMinus, const QVector &keyErrorPlus); - void setDataValueError(const QVector &key, const QVector &value, const QVector &valueError); - void setDataValueError(const QVector &key, const QVector &value, const QVector &valueErrorMinus, const QVector &valueErrorPlus); - void setDataBothError(const QVector &key, const QVector &value, const QVector &keyError, const QVector &valueError); - void setDataBothError(const QVector &key, const QVector &value, const QVector &keyErrorMinus, const QVector &keyErrorPlus, const QVector &valueErrorMinus, const QVector &valueErrorPlus); + void setData(QSharedPointer data); + void setData(const QVector &keys, const QVector &values, bool alreadySorted=false); void setLineStyle(LineStyle ls); void setScatterStyle(const QCPScatterStyle &style); - void setErrorType(ErrorType errorType); - void setErrorPen(const QPen &pen); - void setErrorBarSize(double size); - void setErrorBarSkipSymbol(bool enabled); + void setScatterSkip(int skip); void setChannelFillGraph(QCPGraph *targetGraph); void setAdaptiveSampling(bool enabled); // non-property methods: - void addData(const QCPDataMap &dataMap); - void addData(const QCPData &data); + void addData(const QVector &keys, const QVector &values, bool alreadySorted=false); void addData(double key, double value); - void addData(const QVector &keys, const QVector &values); - void removeDataBefore(double key); - void removeDataAfter(double key); - void removeData(double fromKey, double toKey); - void removeData(double key); // reimplemented virtual methods: - virtual void clearData(); - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; - using QCPAbstractPlottable::rescaleAxes; - using QCPAbstractPlottable::rescaleKeyAxis; - using QCPAbstractPlottable::rescaleValueAxis; - void rescaleAxes(bool onlyEnlarge, bool includeErrorBars) const; // overloads base class interface - void rescaleKeyAxis(bool onlyEnlarge, bool includeErrorBars) const; // overloads base class interface - void rescaleValueAxis(bool onlyEnlarge, bool includeErrorBars) const; // overloads base class interface + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const Q_DECL_OVERRIDE; + virtual QCPRange getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain=QCP::sdBoth) const Q_DECL_OVERRIDE; + virtual QCPRange getValueRange(bool &foundRange, QCP::SignDomain inSignDomain=QCP::sdBoth, const QCPRange &inKeyRange=QCPRange()) const Q_DECL_OVERRIDE; protected: // property members: - QCPDataMap *mData; - QPen mErrorPen; LineStyle mLineStyle; QCPScatterStyle mScatterStyle; - ErrorType mErrorType; - double mErrorBarSize; - bool mErrorBarSkipSymbol; + int mScatterSkip; QPointer mChannelFillGraph; bool mAdaptiveSampling; // reimplemented virtual methods: - virtual void draw(QCPPainter *painter); - virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const; - virtual QCPRange getKeyRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; - virtual QCPRange getValueRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; - virtual QCPRange getKeyRange(bool &foundRange, SignDomain inSignDomain, bool includeErrors) const; // overloads base class interface - virtual QCPRange getValueRange(bool &foundRange, SignDomain inSignDomain, bool includeErrors) const; // overloads base class interface + virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; + virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const Q_DECL_OVERRIDE; // introduced virtual methods: - virtual void drawFill(QCPPainter *painter, QVector *lineData) const; - virtual void drawScatterPlot(QCPPainter *painter, QVector *scatterData) const; - virtual void drawLinePlot(QCPPainter *painter, QVector *lineData) const; - virtual void drawImpulsePlot(QCPPainter *painter, QVector *lineData) const; + virtual void drawFill(QCPPainter *painter, QVector *lines) const; + virtual void drawScatterPlot(QCPPainter *painter, const QVector &scatters, const QCPScatterStyle &style) const; + virtual void drawLinePlot(QCPPainter *painter, const QVector &lines) const; + virtual void drawImpulsePlot(QCPPainter *painter, const QVector &lines) const; + + virtual void getOptimizedLineData(QVector *lineData, const QCPGraphDataContainer::const_iterator &begin, const QCPGraphDataContainer::const_iterator &end) const; + virtual void getOptimizedScatterData(QVector *scatterData, QCPGraphDataContainer::const_iterator begin, QCPGraphDataContainer::const_iterator end) const; // non-virtual methods: - void getPreparedData(QVector *lineData, QVector *scatterData) const; - void getPlotData(QVector *lineData, QVector *scatterData) const; - void getScatterPlotData(QVector *scatterData) const; - void getLinePlotData(QVector *linePixelData, QVector *scatterData) const; - void getStepLeftPlotData(QVector *linePixelData, QVector *scatterData) const; - void getStepRightPlotData(QVector *linePixelData, QVector *scatterData) const; - void getStepCenterPlotData(QVector *linePixelData, QVector *scatterData) const; - void getImpulsePlotData(QVector *linePixelData, QVector *scatterData) const; - void drawError(QCPPainter *painter, double x, double y, const QCPData &data) const; - void getVisibleDataBounds(QCPDataMap::const_iterator &lower, QCPDataMap::const_iterator &upper) const; - int countDataInBounds(const QCPDataMap::const_iterator &lower, const QCPDataMap::const_iterator &upper, int maxCount) const; - void addFillBasePoints(QVector *lineData) const; - void removeFillBasePoints(QVector *lineData) const; + void getVisibleDataBounds(QCPGraphDataContainer::const_iterator &begin, QCPGraphDataContainer::const_iterator &end, const QCPDataRange &rangeRestriction) const; + void getLines(QVector *lines, const QCPDataRange &dataRange) const; + void getScatters(QVector *scatters, const QCPDataRange &dataRange) const; + QVector dataToLines(const QVector &data) const; + QVector dataToStepLeftLines(const QVector &data) const; + QVector dataToStepRightLines(const QVector &data) const; + QVector dataToStepCenterLines(const QVector &data) const; + QVector dataToImpulseLines(const QVector &data) const; + void addFillBasePoints(QVector *lines) const; + void removeFillBasePoints(QVector *lines) const; QPointF lowerFillBasePoint(double lowerKey) const; QPointF upperFillBasePoint(double upperKey) const; - const QPolygonF getChannelFillPolygon(const QVector *lineData) const; + const QPolygonF getChannelFillPolygon(const QVector *lines) const; int findIndexBelowX(const QVector *data, double x) const; int findIndexAboveX(const QVector *data, double x) const; int findIndexBelowY(const QVector *data, double y) const; int findIndexAboveY(const QVector *data, double y) const; - double pointDistance(const QPointF &pixelPoint) const; + double pointDistance(const QPointF &pixelPoint, QCPGraphDataContainer::const_iterator &closestData) const; friend class QCustomPlot; friend class QCPLegend; }; +Q_DECLARE_METATYPE(QCPGraph::LineStyle) + +/* end of 'src/plottables/plottable-graph.h' */ -/*! \file */ - - +/* including file 'src/plottables/plottable-curve.h', size 7409 */ +/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */ class QCP_LIB_DECL QCPCurveData { public: QCPCurveData(); QCPCurveData(double t, double key, double value); + + inline double sortKey() const { return t; } + inline static QCPCurveData fromSortKey(double sortKey) { return QCPCurveData(sortKey, 0, 0); } + inline static bool sortKeyIsMainKey() { return false; } + + inline double mainKey() const { return key; } + inline double mainValue() const { return value; } + + inline QCPRange valueRange() const { return QCPRange(value, value); } + double t, key, value; }; -Q_DECLARE_TYPEINFO(QCPCurveData, Q_MOVABLE_TYPE); +Q_DECLARE_TYPEINFO(QCPCurveData, Q_PRIMITIVE_TYPE); -/*! \typedef QCPCurveDataMap - Container for storing \ref QCPCurveData items in a sorted fashion. The key of the map - is the t member of the QCPCurveData instance. + +/*! \typedef QCPCurveDataContainer + + Container for storing \ref QCPCurveData points. The data is stored sorted by \a t, so the \a + sortKey() (returning \a t) is different from \a mainKey() (returning \a key). + + This template instantiation is the container in which QCPCurve holds its data. For details about + the generic container, see the documentation of the class template \ref QCPDataContainer. - This is the container in which QCPCurve holds its data. \see QCPCurveData, QCPCurve::setData */ +typedef QCPDataContainer QCPCurveDataContainer; -typedef QMap QCPCurveDataMap; -typedef QMapIterator QCPCurveDataMapIterator; -typedef QMutableMapIterator QCPCurveDataMutableMapIterator; - - -class QCP_LIB_DECL QCPCurve : public QCPAbstractPlottable +class QCP_LIB_DECL QCPCurve : public QCPAbstractPlottable1D { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QCPScatterStyle scatterStyle READ scatterStyle WRITE setScatterStyle) + Q_PROPERTY(int scatterSkip READ scatterSkip WRITE setScatterSkip) Q_PROPERTY(LineStyle lineStyle READ lineStyle WRITE setLineStyle) /// \endcond public: @@ -2673,69 +5272,71 @@ public: enum LineStyle { lsNone ///< No line is drawn between data points (e.g. only scatters) ,lsLine ///< Data points are connected with a straight line }; + Q_ENUMS(LineStyle) + explicit QCPCurve(QCPAxis *keyAxis, QCPAxis *valueAxis); virtual ~QCPCurve(); // getters: - QCPCurveDataMap *data() const { return mData; } + QSharedPointer data() const { return mDataContainer; } QCPScatterStyle scatterStyle() const { return mScatterStyle; } + int scatterSkip() const { return mScatterSkip; } LineStyle lineStyle() const { return mLineStyle; } // setters: - void setData(QCPCurveDataMap *data, bool copy=false); - void setData(const QVector &t, const QVector &key, const QVector &value); - void setData(const QVector &key, const QVector &value); + void setData(QSharedPointer data); + void setData(const QVector &t, const QVector &keys, const QVector &values, bool alreadySorted=false); + void setData(const QVector &keys, const QVector &values); void setScatterStyle(const QCPScatterStyle &style); + void setScatterSkip(int skip); void setLineStyle(LineStyle style); // non-property methods: - void addData(const QCPCurveDataMap &dataMap); - void addData(const QCPCurveData &data); + void addData(const QVector &t, const QVector &keys, const QVector &values, bool alreadySorted=false); + void addData(const QVector &keys, const QVector &values); void addData(double t, double key, double value); void addData(double key, double value); - void addData(const QVector &ts, const QVector &keys, const QVector &values); - void removeDataBefore(double t); - void removeDataAfter(double t); - void removeData(double fromt, double tot); - void removeData(double t); // reimplemented virtual methods: - virtual void clearData(); - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const Q_DECL_OVERRIDE; + virtual QCPRange getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain=QCP::sdBoth) const Q_DECL_OVERRIDE; + virtual QCPRange getValueRange(bool &foundRange, QCP::SignDomain inSignDomain=QCP::sdBoth, const QCPRange &inKeyRange=QCPRange()) const Q_DECL_OVERRIDE; protected: // property members: - QCPCurveDataMap *mData; QCPScatterStyle mScatterStyle; + int mScatterSkip; LineStyle mLineStyle; // reimplemented virtual methods: - virtual void draw(QCPPainter *painter); - virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const; - virtual QCPRange getKeyRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; - virtual QCPRange getValueRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; + virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; + virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const Q_DECL_OVERRIDE; // introduced virtual methods: - virtual void drawScatterPlot(QCPPainter *painter, const QVector *pointData) const; + virtual void drawCurveLine(QCPPainter *painter, const QVector &lines) const; + virtual void drawScatterPlot(QCPPainter *painter, const QVector &points, const QCPScatterStyle &style) const; // non-virtual methods: - void getCurveData(QVector *lineData) const; - int getRegion(double x, double y, double rectLeft, double rectTop, double rectRight, double rectBottom) const; - QPointF getOptimizedPoint(int prevRegion, double prevKey, double prevValue, double key, double value, double rectLeft, double rectTop, double rectRight, double rectBottom) const; - QVector getOptimizedCornerPoints(int prevRegion, int currentRegion, double prevKey, double prevValue, double key, double value, double rectLeft, double rectTop, double rectRight, double rectBottom) const; + void getCurveLines(QVector *lines, const QCPDataRange &dataRange, double penWidth) const; + void getScatters(QVector *scatters, const QCPDataRange &dataRange, double scatterWidth) const; + int getRegion(double key, double value, double keyMin, double valueMax, double keyMax, double valueMin) const; + QPointF getOptimizedPoint(int prevRegion, double prevKey, double prevValue, double key, double value, double keyMin, double valueMax, double keyMax, double valueMin) const; + QVector getOptimizedCornerPoints(int prevRegion, int currentRegion, double prevKey, double prevValue, double key, double value, double keyMin, double valueMax, double keyMax, double valueMin) const; bool mayTraverse(int prevRegion, int currentRegion) const; - bool getTraverse(double prevKey, double prevValue, double key, double value, double rectLeft, double rectTop, double rectRight, double rectBottom, QPointF &crossA, QPointF &crossB) const; - void getTraverseCornerPoints(int prevRegion, int currentRegion, double rectLeft, double rectTop, double rectRight, double rectBottom, QVector &beforeTraverse, QVector &afterTraverse) const; - double pointDistance(const QPointF &pixelPoint) const; + bool getTraverse(double prevKey, double prevValue, double key, double value, double keyMin, double valueMax, double keyMax, double valueMin, QPointF &crossA, QPointF &crossB) const; + void getTraverseCornerPoints(int prevRegion, int currentRegion, double keyMin, double valueMax, double keyMax, double valueMin, QVector &beforeTraverse, QVector &afterTraverse) const; + double pointDistance(const QPointF &pixelPoint, QCPCurveDataContainer::const_iterator &closestData) const; friend class QCustomPlot; friend class QCPLegend; }; +Q_DECLARE_METATYPE(QCPCurve::LineStyle) + +/* end of 'src/plottables/plottable-curve.h' */ -/*! \file */ - - +/* including file 'src/plottables/plottable-bars.h', size 8924 */ +/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */ class QCP_LIB_DECL QCPBarsGroup : public QObject { @@ -2754,9 +5355,11 @@ public: enum SpacingType { stAbsolute ///< Bar spacing is in absolute pixels ,stAxisRectRatio ///< Bar spacing is given by a fraction of the axis rect size ,stPlotCoords ///< Bar spacing is in key coordinates and thus scales with the key axis range - }; + }; + Q_ENUMS(SpacingType) + QCPBarsGroup(QCustomPlot *parentPlot); - ~QCPBarsGroup(); + virtual ~QCPBarsGroup(); // getters: SpacingType spacingType() const { return mSpacingType; } @@ -2797,30 +5400,41 @@ private: friend class QCPBars; }; +Q_DECLARE_METATYPE(QCPBarsGroup::SpacingType) -class QCP_LIB_DECL QCPBarData +class QCP_LIB_DECL QCPBarsData { public: - QCPBarData(); - QCPBarData(double key, double value); + QCPBarsData(); + QCPBarsData(double key, double value); + + inline double sortKey() const { return key; } + inline static QCPBarsData fromSortKey(double sortKey) { return QCPBarsData(sortKey, 0); } + inline static bool sortKeyIsMainKey() { return true; } + + inline double mainKey() const { return key; } + inline double mainValue() const { return value; } + + inline QCPRange valueRange() const { return QCPRange(value, value); } // note that bar base value isn't held in each QCPBarsData and thus can't/shouldn't be returned here + double key, value; }; -Q_DECLARE_TYPEINFO(QCPBarData, Q_MOVABLE_TYPE); +Q_DECLARE_TYPEINFO(QCPBarsData, Q_PRIMITIVE_TYPE); -/*! \typedef QCPBarDataMap - Container for storing \ref QCPBarData items in a sorted fashion. The key of the map - is the key member of the QCPBarData instance. + +/*! \typedef QCPBarsDataContainer - This is the container in which QCPBars holds its data. - \see QCPBarData, QCPBars::setData + Container for storing \ref QCPBarsData points. The data is stored sorted by \a key. + + This template instantiation is the container in which QCPBars holds its data. For details about + the generic container, see the documentation of the class template \ref QCPDataContainer. + + \see QCPBarsData, QCPBars::setData */ -typedef QMap QCPBarDataMap; -typedef QMapIterator QCPBarDataMapIterator; -typedef QMutableMapIterator QCPBarDataMutableMapIterator; +typedef QCPDataContainer QCPBarsDataContainer; - -class QCP_LIB_DECL QCPBars : public QCPAbstractPlottable +class QCP_LIB_DECL QCPBars : public QCPAbstractPlottable1D { Q_OBJECT /// \cond INCLUDE_QPROPERTIES @@ -2828,6 +5442,7 @@ class QCP_LIB_DECL QCPBars : public QCPAbstractPlottable Q_PROPERTY(WidthType widthType READ widthType WRITE setWidthType) Q_PROPERTY(QCPBarsGroup* barsGroup READ barsGroup WRITE setBarsGroup) Q_PROPERTY(double baseValue READ baseValue WRITE setBaseValue) + Q_PROPERTY(double stackingGap READ stackingGap WRITE setStackingGap) Q_PROPERTY(QCPBars* barBelow READ barBelow) Q_PROPERTY(QCPBars* barAbove READ barAbove) /// \endcond @@ -2842,7 +5457,7 @@ public: ,wtAxisRectRatio ///< Bar width is given by a fraction of the axis rect size ,wtPlotCoords ///< Bar width is in key coordinates and thus scales with the key axis range }; - Q_ENUMS(WidthType) + Q_ENUMS(WidthType) explicit QCPBars(QCPAxis *keyAxis, QCPAxis *valueAxis); virtual ~QCPBars(); @@ -2852,52 +5467,49 @@ public: WidthType widthType() const { return mWidthType; } QCPBarsGroup *barsGroup() const { return mBarsGroup; } double baseValue() const { return mBaseValue; } + double stackingGap() const { return mStackingGap; } QCPBars *barBelow() const { return mBarBelow.data(); } QCPBars *barAbove() const { return mBarAbove.data(); } - QCPBarDataMap *data() const { return mData; } + QSharedPointer data() const { return mDataContainer; } // setters: + void setData(QSharedPointer data); + void setData(const QVector &keys, const QVector &values, bool alreadySorted=false); void setWidth(double width); void setWidthType(WidthType widthType); void setBarsGroup(QCPBarsGroup *barsGroup); void setBaseValue(double baseValue); - void setData(QCPBarDataMap *data, bool copy=false); - void setData(const QVector &key, const QVector &value); + void setStackingGap(double pixels); // non-property methods: + void addData(const QVector &keys, const QVector &values, bool alreadySorted=false); + void addData(double key, double value); void moveBelow(QCPBars *bars); void moveAbove(QCPBars *bars); - void addData(const QCPBarDataMap &dataMap); - void addData(const QCPBarData &data); - void addData(double key, double value); - void addData(const QVector &keys, const QVector &values); - void removeDataBefore(double key); - void removeDataAfter(double key); - void removeData(double fromKey, double toKey); - void removeData(double key); // reimplemented virtual methods: - virtual void clearData(); - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; + virtual QCPDataSelection selectTestRect(const QRectF &rect, bool onlySelectable) const Q_DECL_OVERRIDE; + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const Q_DECL_OVERRIDE; + virtual QCPRange getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain=QCP::sdBoth) const Q_DECL_OVERRIDE; + virtual QCPRange getValueRange(bool &foundRange, QCP::SignDomain inSignDomain=QCP::sdBoth, const QCPRange &inKeyRange=QCPRange()) const Q_DECL_OVERRIDE; + virtual QPointF dataPixelPosition(int index) const Q_DECL_OVERRIDE; protected: // property members: - QCPBarDataMap *mData; double mWidth; WidthType mWidthType; QCPBarsGroup *mBarsGroup; double mBaseValue; + double mStackingGap; QPointer mBarBelow, mBarAbove; // reimplemented virtual methods: - virtual void draw(QCPPainter *painter); - virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const; - virtual QCPRange getKeyRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; - virtual QCPRange getValueRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; + virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; + virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const Q_DECL_OVERRIDE; // non-virtual methods: - void getVisibleDataBounds(QCPBarDataMap::const_iterator &lower, QCPBarDataMap::const_iterator &upperEnd) const; - QPolygonF getBarPolygon(double key, double value) const; + void getVisibleDataBounds(QCPBarsDataContainer::const_iterator &begin, QCPBarsDataContainer::const_iterator &end) const; + QRectF getBarRect(double key, double value) const; void getPixelWidth(double key, double &lower, double &upper) const; double getStackedBaseValue(double key, bool positive) const; static void connectBars(QCPBars* lower, QCPBars* upper); @@ -2906,27 +5518,62 @@ protected: friend class QCPLegend; friend class QCPBarsGroup; }; +Q_DECLARE_METATYPE(QCPBars::WidthType) + +/* end of 'src/plottables/plottable-bars.h' */ -/*! \file */ +/* including file 'src/plottables/plottable-statisticalbox.h', size 7516 */ +/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */ + +class QCP_LIB_DECL QCPStatisticalBoxData +{ +public: + QCPStatisticalBoxData(); + QCPStatisticalBoxData(double key, double minimum, double lowerQuartile, double median, double upperQuartile, double maximum, const QVector& outliers=QVector()); + + inline double sortKey() const { return key; } + inline static QCPStatisticalBoxData fromSortKey(double sortKey) { return QCPStatisticalBoxData(sortKey, 0, 0, 0, 0, 0); } + inline static bool sortKeyIsMainKey() { return true; } + + inline double mainKey() const { return key; } + inline double mainValue() const { return median; } + + inline QCPRange valueRange() const + { + QCPRange result(minimum, maximum); + for (QVector::const_iterator it = outliers.constBegin(); it != outliers.constEnd(); ++it) + result.expand(*it); + return result; + } + + double key, minimum, lowerQuartile, median, upperQuartile, maximum; + QVector outliers; +}; +Q_DECLARE_TYPEINFO(QCPStatisticalBoxData, Q_MOVABLE_TYPE); +/*! \typedef QCPStatisticalBoxDataContainer + + Container for storing \ref QCPStatisticalBoxData points. The data is stored sorted by \a key. + + This template instantiation is the container in which QCPStatisticalBox holds its data. For + details about the generic container, see the documentation of the class template \ref + QCPDataContainer. + + \see QCPStatisticalBoxData, QCPStatisticalBox::setData +*/ +typedef QCPDataContainer QCPStatisticalBoxDataContainer; -class QCP_LIB_DECL QCPStatisticalBox : public QCPAbstractPlottable +class QCP_LIB_DECL QCPStatisticalBox : public QCPAbstractPlottable1D { Q_OBJECT /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(double key READ key WRITE setKey) - Q_PROPERTY(double minimum READ minimum WRITE setMinimum) - Q_PROPERTY(double lowerQuartile READ lowerQuartile WRITE setLowerQuartile) - Q_PROPERTY(double median READ median WRITE setMedian) - Q_PROPERTY(double upperQuartile READ upperQuartile WRITE setUpperQuartile) - Q_PROPERTY(double maximum READ maximum WRITE setMaximum) - Q_PROPERTY(QVector outliers READ outliers WRITE setOutliers) Q_PROPERTY(double width READ width WRITE setWidth) Q_PROPERTY(double whiskerWidth READ whiskerWidth WRITE setWhiskerWidth) Q_PROPERTY(QPen whiskerPen READ whiskerPen WRITE setWhiskerPen) Q_PROPERTY(QPen whiskerBarPen READ whiskerBarPen WRITE setWhiskerBarPen) + Q_PROPERTY(bool whiskerAntialiased READ whiskerAntialiased WRITE setWhiskerAntialiased) Q_PROPERTY(QPen medianPen READ medianPen WRITE setMedianPen) Q_PROPERTY(QCPScatterStyle outlierStyle READ outlierStyle WRITE setOutlierStyle) /// \endcond @@ -2934,65 +5581,67 @@ public: explicit QCPStatisticalBox(QCPAxis *keyAxis, QCPAxis *valueAxis); // getters: - double key() const { return mKey; } - double minimum() const { return mMinimum; } - double lowerQuartile() const { return mLowerQuartile; } - double median() const { return mMedian; } - double upperQuartile() const { return mUpperQuartile; } - double maximum() const { return mMaximum; } - QVector outliers() const { return mOutliers; } + QSharedPointer data() const { return mDataContainer; } double width() const { return mWidth; } double whiskerWidth() const { return mWhiskerWidth; } QPen whiskerPen() const { return mWhiskerPen; } QPen whiskerBarPen() const { return mWhiskerBarPen; } + bool whiskerAntialiased() const { return mWhiskerAntialiased; } QPen medianPen() const { return mMedianPen; } QCPScatterStyle outlierStyle() const { return mOutlierStyle; } // setters: - void setKey(double key); - void setMinimum(double value); - void setLowerQuartile(double value); - void setMedian(double value); - void setUpperQuartile(double value); - void setMaximum(double value); - void setOutliers(const QVector &values); - void setData(double key, double minimum, double lowerQuartile, double median, double upperQuartile, double maximum); + void setData(QSharedPointer data); + void setData(const QVector &keys, const QVector &minimum, const QVector &lowerQuartile, const QVector &median, const QVector &upperQuartile, const QVector &maximum, bool alreadySorted=false); void setWidth(double width); void setWhiskerWidth(double width); void setWhiskerPen(const QPen &pen); void setWhiskerBarPen(const QPen &pen); + void setWhiskerAntialiased(bool enabled); void setMedianPen(const QPen &pen); void setOutlierStyle(const QCPScatterStyle &style); // non-property methods: - virtual void clearData(); - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; + void addData(const QVector &keys, const QVector &minimum, const QVector &lowerQuartile, const QVector &median, const QVector &upperQuartile, const QVector &maximum, bool alreadySorted=false); + void addData(double key, double minimum, double lowerQuartile, double median, double upperQuartile, double maximum, const QVector &outliers=QVector()); + + // reimplemented virtual methods: + virtual QCPDataSelection selectTestRect(const QRectF &rect, bool onlySelectable) const Q_DECL_OVERRIDE; + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const Q_DECL_OVERRIDE; + virtual QCPRange getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain=QCP::sdBoth) const Q_DECL_OVERRIDE; + virtual QCPRange getValueRange(bool &foundRange, QCP::SignDomain inSignDomain=QCP::sdBoth, const QCPRange &inKeyRange=QCPRange()) const Q_DECL_OVERRIDE; protected: // property members: - QVector mOutliers; - double mKey, mMinimum, mLowerQuartile, mMedian, mUpperQuartile, mMaximum; double mWidth; double mWhiskerWidth; - QPen mWhiskerPen, mWhiskerBarPen, mMedianPen; + QPen mWhiskerPen, mWhiskerBarPen; + bool mWhiskerAntialiased; + QPen mMedianPen; QCPScatterStyle mOutlierStyle; // reimplemented virtual methods: - virtual void draw(QCPPainter *painter); - virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const; - virtual QCPRange getKeyRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; - virtual QCPRange getValueRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; + virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; + virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const Q_DECL_OVERRIDE; // introduced virtual methods: - virtual void drawQuartileBox(QCPPainter *painter, QRectF *quartileBox=0) const; - virtual void drawMedian(QCPPainter *painter) const; - virtual void drawWhiskers(QCPPainter *painter) const; - virtual void drawOutliers(QCPPainter *painter) const; + virtual void drawStatisticalBox(QCPPainter *painter, QCPStatisticalBoxDataContainer::const_iterator it, const QCPScatterStyle &outlierStyle) const; + + // non-virtual methods: + void getVisibleDataBounds(QCPStatisticalBoxDataContainer::const_iterator &begin, QCPStatisticalBoxDataContainer::const_iterator &end) const; + QRectF getQuartileBox(QCPStatisticalBoxDataContainer::const_iterator it) const; + QVector getWhiskerBackboneLines(QCPStatisticalBoxDataContainer::const_iterator it) const; + QVector getWhiskerBarLines(QCPStatisticalBoxDataContainer::const_iterator it) const; friend class QCustomPlot; friend class QCPLegend; }; +/* end of 'src/plottables/plottable-statisticalbox.h' */ + + +/* including file 'src/plottables/plottable-colormap.h', size 7070 */ +/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */ class QCP_LIB_DECL QCPColorMapData { @@ -3010,6 +5659,7 @@ public: QCPRange dataBounds() const { return mDataBounds; } double data(double key, double value); double cell(int keyIndex, int valueIndex); + unsigned char alpha(int keyIndex, int valueIndex); // setters: void setSize(int keySize, int valueSize); @@ -3020,11 +5670,14 @@ public: void setValueRange(const QCPRange &valueRange); void setData(double key, double value, double z); void setCell(int keyIndex, int valueIndex, double z); + void setAlpha(int keyIndex, int valueIndex, unsigned char alpha); // non-property methods: void recalculateDataBounds(); void clear(); + void clearAlpha(); void fill(double z); + void fillAlpha(unsigned char alpha); bool isEmpty() const { return mIsEmpty; } void coordToCell(double key, double value, int *keyIndex, int *valueIndex) const; void cellToCoord(int keyIndex, int valueIndex, double *key, double *value) const; @@ -3034,11 +5687,15 @@ protected: int mKeySize, mValueSize; QCPRange mKeyRange, mValueRange; bool mIsEmpty; + // non-property members: double *mData; + unsigned char *mAlpha; QCPRange mDataBounds; bool mDataModified; + bool createAlpha(bool initializeOpaque=true); + friend class QCPColorMap; }; @@ -3081,13 +5738,14 @@ public: Q_SLOT void updateLegendIcon(Qt::TransformationMode transformMode=Qt::SmoothTransformation, const QSize &thumbSize=QSize(32, 18)); // reimplemented virtual methods: - virtual void clearData(); - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const Q_DECL_OVERRIDE; + virtual QCPRange getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain=QCP::sdBoth) const Q_DECL_OVERRIDE; + virtual QCPRange getValueRange(bool &foundRange, QCP::SignDomain inSignDomain=QCP::sdBoth, const QCPRange &inKeyRange=QCPRange()) const Q_DECL_OVERRIDE; signals: - void dataRangeChanged(QCPRange newRange); + void dataRangeChanged(const QCPRange &newRange); void dataScaleTypeChanged(QCPAxis::ScaleType scaleType); - void gradientChanged(QCPColorGradient newGradient); + void gradientChanged(const QCPColorGradient &newGradient); protected: // property members: @@ -3098,6 +5756,7 @@ protected: bool mInterpolate; bool mTightBoundary; QPointer mColorScale; + // non-property members: QImage mMapImage, mUndersampledMapImage; QPixmap mLegendIcon; @@ -3107,47 +5766,57 @@ protected: virtual void updateMapImage(); // reimplemented virtual methods: - virtual void draw(QCPPainter *painter); - virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const; - virtual QCPRange getKeyRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; - virtual QCPRange getValueRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; + virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; + virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const Q_DECL_OVERRIDE; friend class QCustomPlot; friend class QCPLegend; }; - -/*! \file */ +/* end of 'src/plottables/plottable-colormap.h' */ +/* including file 'src/plottables/plottable-financial.h', size 8622 */ +/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */ class QCP_LIB_DECL QCPFinancialData { public: QCPFinancialData(); QCPFinancialData(double key, double open, double high, double low, double close); + + inline double sortKey() const { return key; } + inline static QCPFinancialData fromSortKey(double sortKey) { return QCPFinancialData(sortKey, 0, 0, 0, 0); } + inline static bool sortKeyIsMainKey() { return true; } + + inline double mainKey() const { return key; } + inline double mainValue() const { return open; } + + inline QCPRange valueRange() const { return QCPRange(low, high); } // open and close must lie between low and high, so we don't need to check them + double key, open, high, low, close; }; -Q_DECLARE_TYPEINFO(QCPFinancialData, Q_MOVABLE_TYPE); +Q_DECLARE_TYPEINFO(QCPFinancialData, Q_PRIMITIVE_TYPE); -/*! \typedef QCPFinancialDataMap - Container for storing \ref QCPFinancialData items in a sorted fashion. The key of the map - is the key member of the QCPFinancialData instance. + +/*! \typedef QCPFinancialDataContainer - This is the container in which QCPFinancial holds its data. - \see QCPFinancial, QCPFinancial::setData + Container for storing \ref QCPFinancialData points. The data is stored sorted by \a key. + + This template instantiation is the container in which QCPFinancial holds its data. For details + about the generic container, see the documentation of the class template \ref QCPDataContainer. + + \see QCPFinancialData, QCPFinancial::setData */ -typedef QMap QCPFinancialDataMap; -typedef QMapIterator QCPFinancialDataMapIterator; -typedef QMutableMapIterator QCPFinancialDataMutableMapIterator; +typedef QCPDataContainer QCPFinancialDataContainer; - -class QCP_LIB_DECL QCPFinancial : public QCPAbstractPlottable +class QCP_LIB_DECL QCPFinancial : public QCPAbstractPlottable1D { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(ChartStyle chartStyle READ chartStyle WRITE setChartStyle) Q_PROPERTY(double width READ width WRITE setWidth) + Q_PROPERTY(WidthType widthType READ widthType WRITE setWidthType) Q_PROPERTY(bool twoColored READ twoColored WRITE setTwoColored) Q_PROPERTY(QBrush brushPositive READ brushPositive WRITE setBrushPositive) Q_PROPERTY(QBrush brushNegative READ brushNegative WRITE setBrushNegative) @@ -3155,6 +5824,18 @@ class QCP_LIB_DECL QCPFinancial : public QCPAbstractPlottable Q_PROPERTY(QPen penNegative READ penNegative WRITE setPenNegative) /// \endcond public: + /*! + Defines the ways the width of the financial bar can be specified. Thus it defines what the + number passed to \ref setWidth actually means. + + \see setWidthType, setWidth + */ + enum WidthType { wtAbsolute ///< width is in absolute pixels + ,wtAxisRectRatio ///< width is given by a fraction of the axis rect size + ,wtPlotCoords ///< width is in key coordinates and thus scales with the key axis range + }; + Q_ENUMS(WidthType) + /*! Defines the possible representations of OHLC data in the plot. @@ -3169,21 +5850,22 @@ public: virtual ~QCPFinancial(); // getters: - QCPFinancialDataMap *data() const { return mData; } + QSharedPointer data() const { return mDataContainer; } ChartStyle chartStyle() const { return mChartStyle; } double width() const { return mWidth; } + WidthType widthType() const { return mWidthType; } bool twoColored() const { return mTwoColored; } QBrush brushPositive() const { return mBrushPositive; } QBrush brushNegative() const { return mBrushNegative; } QPen penPositive() const { return mPenPositive; } QPen penNegative() const { return mPenNegative; } - // setters: - void setData(QCPFinancialDataMap *data, bool copy=false); - void setData(const QVector &key, const QVector &open, const QVector &high, const QVector &low, const QVector &close); + void setData(QSharedPointer data); + void setData(const QVector &keys, const QVector &open, const QVector &high, const QVector &low, const QVector &close, bool alreadySorted=false); void setChartStyle(ChartStyle style); void setWidth(double width); + void setWidthType(WidthType widthType); void setTwoColored(bool twoColored); void setBrushPositive(const QBrush &brush); void setBrushNegative(const QBrush &brush); @@ -3191,48 +5873,175 @@ public: void setPenNegative(const QPen &pen); // non-property methods: - void addData(const QCPFinancialDataMap &dataMap); - void addData(const QCPFinancialData &data); + void addData(const QVector &keys, const QVector &open, const QVector &high, const QVector &low, const QVector &close, bool alreadySorted=false); void addData(double key, double open, double high, double low, double close); - void addData(const QVector &key, const QVector &open, const QVector &high, const QVector &low, const QVector &close); - void removeDataBefore(double key); - void removeDataAfter(double key); - void removeData(double fromKey, double toKey); - void removeData(double key); // reimplemented virtual methods: - virtual void clearData(); - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; + virtual QCPDataSelection selectTestRect(const QRectF &rect, bool onlySelectable) const Q_DECL_OVERRIDE; + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const Q_DECL_OVERRIDE; + virtual QCPRange getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain=QCP::sdBoth) const Q_DECL_OVERRIDE; + virtual QCPRange getValueRange(bool &foundRange, QCP::SignDomain inSignDomain=QCP::sdBoth, const QCPRange &inKeyRange=QCPRange()) const Q_DECL_OVERRIDE; // static methods: - static QCPFinancialDataMap timeSeriesToOhlc(const QVector &time, const QVector &value, double timeBinSize, double timeBinOffset = 0); + static QCPFinancialDataContainer timeSeriesToOhlc(const QVector &time, const QVector &value, double timeBinSize, double timeBinOffset = 0); protected: // property members: - QCPFinancialDataMap *mData; ChartStyle mChartStyle; double mWidth; + WidthType mWidthType; bool mTwoColored; QBrush mBrushPositive, mBrushNegative; QPen mPenPositive, mPenNegative; // reimplemented virtual methods: - virtual void draw(QCPPainter *painter); - virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const; - virtual QCPRange getKeyRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; - virtual QCPRange getValueRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; + virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; + virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const Q_DECL_OVERRIDE; // non-virtual methods: - void drawOhlcPlot(QCPPainter *painter, const QCPFinancialDataMap::const_iterator &begin, const QCPFinancialDataMap::const_iterator &end); - void drawCandlestickPlot(QCPPainter *painter, const QCPFinancialDataMap::const_iterator &begin, const QCPFinancialDataMap::const_iterator &end); - double ohlcSelectTest(const QPointF &pos, const QCPFinancialDataMap::const_iterator &begin, const QCPFinancialDataMap::const_iterator &end) const; - double candlestickSelectTest(const QPointF &pos, const QCPFinancialDataMap::const_iterator &begin, const QCPFinancialDataMap::const_iterator &end) const; - void getVisibleDataBounds(QCPFinancialDataMap::const_iterator &lower, QCPFinancialDataMap::const_iterator &upper) const; + void drawOhlcPlot(QCPPainter *painter, const QCPFinancialDataContainer::const_iterator &begin, const QCPFinancialDataContainer::const_iterator &end, bool isSelected); + void drawCandlestickPlot(QCPPainter *painter, const QCPFinancialDataContainer::const_iterator &begin, const QCPFinancialDataContainer::const_iterator &end, bool isSelected); + double getPixelWidth(double key, double keyPixel) const; + double ohlcSelectTest(const QPointF &pos, const QCPFinancialDataContainer::const_iterator &begin, const QCPFinancialDataContainer::const_iterator &end, QCPFinancialDataContainer::const_iterator &closestDataPoint) const; + double candlestickSelectTest(const QPointF &pos, const QCPFinancialDataContainer::const_iterator &begin, const QCPFinancialDataContainer::const_iterator &end, QCPFinancialDataContainer::const_iterator &closestDataPoint) const; + void getVisibleDataBounds(QCPFinancialDataContainer::const_iterator &begin, QCPFinancialDataContainer::const_iterator &end) const; + QRectF selectionHitBox(QCPFinancialDataContainer::const_iterator it) const; + + friend class QCustomPlot; + friend class QCPLegend; +}; +Q_DECLARE_METATYPE(QCPFinancial::ChartStyle) + +/* end of 'src/plottables/plottable-financial.h' */ + + +/* including file 'src/plottables/plottable-errorbar.h', size 7567 */ +/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */ + +class QCP_LIB_DECL QCPErrorBarsData +{ +public: + QCPErrorBarsData(); + explicit QCPErrorBarsData(double error); + QCPErrorBarsData(double errorMinus, double errorPlus); + + double errorMinus, errorPlus; +}; +Q_DECLARE_TYPEINFO(QCPErrorBarsData, Q_PRIMITIVE_TYPE); + + +/*! \typedef QCPErrorBarsDataContainer + + Container for storing \ref QCPErrorBarsData points. It is a typedef for QVector<\ref + QCPErrorBarsData>. + + This is the container in which \ref QCPErrorBars holds its data. Unlike most other data + containers for plottables, it is not based on \ref QCPDataContainer. This is because the error + bars plottable is special in that it doesn't store its own key and value coordinate per error + bar. It adopts the key and value from the plottable to which the error bars shall be applied + (\ref QCPErrorBars::setDataPlottable). So the stored \ref QCPErrorBarsData doesn't need a + sortable key, but merely an index (as \c QVector provides), which maps one-to-one to the indices + of the other plottable's data. + + \see QCPErrorBarsData, QCPErrorBars::setData +*/ +typedef QVector QCPErrorBarsDataContainer; + +class QCP_LIB_DECL QCPErrorBars : public QCPAbstractPlottable, public QCPPlottableInterface1D +{ + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(QSharedPointer data READ data WRITE setData) + Q_PROPERTY(QCPAbstractPlottable* dataPlottable READ dataPlottable WRITE setDataPlottable) + Q_PROPERTY(ErrorType errorType READ errorType WRITE setErrorType) + Q_PROPERTY(double whiskerWidth READ whiskerWidth WRITE setWhiskerWidth) + Q_PROPERTY(double symbolGap READ symbolGap WRITE setSymbolGap) + /// \endcond +public: + + /*! + Defines in which orientation the error bars shall appear. If your data needs both error + dimensions, create two \ref QCPErrorBars with different \ref ErrorType. + + \see setErrorType + */ + enum ErrorType { etKeyError ///< The errors are for the key dimension (bars appear parallel to the key axis) + ,etValueError ///< The errors are for the value dimension (bars appear parallel to the value axis) + }; + Q_ENUMS(ErrorType) + + explicit QCPErrorBars(QCPAxis *keyAxis, QCPAxis *valueAxis); + virtual ~QCPErrorBars(); + // getters: + QSharedPointer data() const { return mDataContainer; } + QCPAbstractPlottable *dataPlottable() const { return mDataPlottable.data(); } + ErrorType errorType() const { return mErrorType; } + double whiskerWidth() const { return mWhiskerWidth; } + double symbolGap() const { return mSymbolGap; } + + // setters: + void setData(QSharedPointer data); + void setData(const QVector &error); + void setData(const QVector &errorMinus, const QVector &errorPlus); + void setDataPlottable(QCPAbstractPlottable* plottable); + void setErrorType(ErrorType type); + void setWhiskerWidth(double pixels); + void setSymbolGap(double pixels); + + // non-property methods: + void addData(const QVector &error); + void addData(const QVector &errorMinus, const QVector &errorPlus); + void addData(double error); + void addData(double errorMinus, double errorPlus); + + // virtual methods of 1d plottable interface: + virtual int dataCount() const; + virtual double dataMainKey(int index) const; + virtual double dataSortKey(int index) const; + virtual double dataMainValue(int index) const; + virtual QCPRange dataValueRange(int index) const; + virtual QPointF dataPixelPosition(int index) const; + virtual bool sortKeyIsMainKey() const; + virtual QCPDataSelection selectTestRect(const QRectF &rect, bool onlySelectable) const; + virtual int findBegin(double sortKey, bool expandedRange=true) const; + virtual int findEnd(double sortKey, bool expandedRange=true) const; + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const Q_DECL_OVERRIDE; + virtual QCPPlottableInterface1D *interface1D() Q_DECL_OVERRIDE { return this; } + +protected: + // property members: + QSharedPointer mDataContainer; + QPointer mDataPlottable; + ErrorType mErrorType; + double mWhiskerWidth; + double mSymbolGap; + + // reimplemented virtual methods: + virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; + virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const Q_DECL_OVERRIDE; + virtual QCPRange getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain=QCP::sdBoth) const Q_DECL_OVERRIDE; + virtual QCPRange getValueRange(bool &foundRange, QCP::SignDomain inSignDomain=QCP::sdBoth, const QCPRange &inKeyRange=QCPRange()) const Q_DECL_OVERRIDE; + + // non-virtual methods: + void getErrorBarLines(QCPErrorBarsDataContainer::const_iterator it, QVector &backbones, QVector &whiskers) const; + void getVisibleDataBounds(QCPErrorBarsDataContainer::const_iterator &begin, QCPErrorBarsDataContainer::const_iterator &end, const QCPDataRange &rangeRestriction) const; + double pointDistance(const QPointF &pixelPoint, QCPErrorBarsDataContainer::const_iterator &closestData) const; + // helpers: + void getDataSegments(QList &selectedSegments, QList &unselectedSegments) const; + bool errorBarVisible(int index) const; + bool rectIntersectsLine(const QRectF &pixelRect, const QLineF &line) const; friend class QCustomPlot; friend class QCPLegend; }; +/* end of 'src/plottables/plottable-errorbar.h' */ + + +/* including file 'src/items/item-straightline.h', size 3117 */ +/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */ class QCP_LIB_DECL QCPItemStraightLine : public QCPAbstractItem { @@ -3242,7 +6051,7 @@ class QCP_LIB_DECL QCPItemStraightLine : public QCPAbstractItem Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) /// \endcond public: - QCPItemStraightLine(QCustomPlot *parentPlot); + explicit QCPItemStraightLine(QCustomPlot *parentPlot); virtual ~QCPItemStraightLine(); // getters: @@ -3254,7 +6063,7 @@ public: void setSelectedPen(const QPen &pen); // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const Q_DECL_OVERRIDE; QCPItemPosition * const point1; QCPItemPosition * const point2; @@ -3264,14 +6073,18 @@ protected: QPen mPen, mSelectedPen; // reimplemented virtual methods: - virtual void draw(QCPPainter *painter); + virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; // non-virtual methods: - double distToStraightLine(const QVector2D &point1, const QVector2D &vec, const QVector2D &point) const; - QLineF getRectClippedStraightLine(const QVector2D &point1, const QVector2D &vec, const QRect &rect) const; + QLineF getRectClippedStraightLine(const QCPVector2D &point1, const QCPVector2D &vec, const QRect &rect) const; QPen mainPen() const; }; +/* end of 'src/items/item-straightline.h' */ + + +/* including file 'src/items/item-line.h', size 3407 */ +/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */ class QCP_LIB_DECL QCPItemLine : public QCPAbstractItem { @@ -3283,7 +6096,7 @@ class QCP_LIB_DECL QCPItemLine : public QCPAbstractItem Q_PROPERTY(QCPLineEnding tail READ tail WRITE setTail) /// \endcond public: - QCPItemLine(QCustomPlot *parentPlot); + explicit QCPItemLine(QCustomPlot *parentPlot); virtual ~QCPItemLine(); // getters: @@ -3299,7 +6112,7 @@ public: void setTail(const QCPLineEnding &tail); // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const Q_DECL_OVERRIDE; QCPItemPosition * const start; QCPItemPosition * const end; @@ -3310,13 +6123,18 @@ protected: QCPLineEnding mHead, mTail; // reimplemented virtual methods: - virtual void draw(QCPPainter *painter); + virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; // non-virtual methods: - QLineF getRectClippedLine(const QVector2D &start, const QVector2D &end, const QRect &rect) const; + QLineF getRectClippedLine(const QCPVector2D &start, const QCPVector2D &end, const QRect &rect) const; QPen mainPen() const; }; +/* end of 'src/items/item-line.h' */ + + +/* including file 'src/items/item-curve.h', size 3379 */ +/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */ class QCP_LIB_DECL QCPItemCurve : public QCPAbstractItem { @@ -3328,7 +6146,7 @@ class QCP_LIB_DECL QCPItemCurve : public QCPAbstractItem Q_PROPERTY(QCPLineEnding tail READ tail WRITE setTail) /// \endcond public: - QCPItemCurve(QCustomPlot *parentPlot); + explicit QCPItemCurve(QCustomPlot *parentPlot); virtual ~QCPItemCurve(); // getters: @@ -3344,7 +6162,7 @@ public: void setTail(const QCPLineEnding &tail); // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const Q_DECL_OVERRIDE; QCPItemPosition * const start; QCPItemPosition * const startDir; @@ -3357,12 +6175,17 @@ protected: QCPLineEnding mHead, mTail; // reimplemented virtual methods: - virtual void draw(QCPPainter *painter); + virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; // non-virtual methods: QPen mainPen() const; }; +/* end of 'src/items/item-curve.h' */ + + +/* including file 'src/items/item-rect.h', size 3688 */ +/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */ class QCP_LIB_DECL QCPItemRect : public QCPAbstractItem { @@ -3374,7 +6197,7 @@ class QCP_LIB_DECL QCPItemRect : public QCPAbstractItem Q_PROPERTY(QBrush selectedBrush READ selectedBrush WRITE setSelectedBrush) /// \endcond public: - QCPItemRect(QCustomPlot *parentPlot); + explicit QCPItemRect(QCustomPlot *parentPlot); virtual ~QCPItemRect(); // getters: @@ -3390,7 +6213,7 @@ public: void setSelectedBrush(const QBrush &brush); // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const Q_DECL_OVERRIDE; QCPItemPosition * const topLeft; QCPItemPosition * const bottomRight; @@ -3409,14 +6232,19 @@ protected: QBrush mBrush, mSelectedBrush; // reimplemented virtual methods: - virtual void draw(QCPPainter *painter); - virtual QPointF anchorPixelPoint(int anchorId) const; + virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; + virtual QPointF anchorPixelPosition(int anchorId) const Q_DECL_OVERRIDE; // non-virtual methods: QPen mainPen() const; QBrush mainBrush() const; }; +/* end of 'src/items/item-rect.h' */ + + +/* including file 'src/items/item-text.h', size 5554 */ +/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */ class QCP_LIB_DECL QCPItemText : public QCPAbstractItem { @@ -3437,7 +6265,7 @@ class QCP_LIB_DECL QCPItemText : public QCPAbstractItem Q_PROPERTY(QMargins padding READ padding WRITE setPadding) /// \endcond public: - QCPItemText(QCustomPlot *parentPlot); + explicit QCPItemText(QCustomPlot *parentPlot); virtual ~QCPItemText(); // getters: @@ -3471,7 +6299,7 @@ public: void setPadding(const QMargins &padding); // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const Q_DECL_OVERRIDE; QCPItemPosition * const position; QCPItemAnchor * const topLeft; @@ -3498,8 +6326,8 @@ protected: QMargins mPadding; // reimplemented virtual methods: - virtual void draw(QCPPainter *painter); - virtual QPointF anchorPixelPoint(int anchorId) const; + virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; + virtual QPointF anchorPixelPosition(int anchorId) const Q_DECL_OVERRIDE; // non-virtual methods: QPointF getTextDrawPoint(const QPointF &pos, const QRectF &rect, Qt::Alignment positionAlignment) const; @@ -3509,6 +6337,11 @@ protected: QBrush mainBrush() const; }; +/* end of 'src/items/item-text.h' */ + + +/* including file 'src/items/item-ellipse.h', size 3868 */ +/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */ class QCP_LIB_DECL QCPItemEllipse : public QCPAbstractItem { @@ -3520,7 +6353,7 @@ class QCP_LIB_DECL QCPItemEllipse : public QCPAbstractItem Q_PROPERTY(QBrush selectedBrush READ selectedBrush WRITE setSelectedBrush) /// \endcond public: - QCPItemEllipse(QCustomPlot *parentPlot); + explicit QCPItemEllipse(QCustomPlot *parentPlot); virtual ~QCPItemEllipse(); // getters: @@ -3536,7 +6369,7 @@ public: void setSelectedBrush(const QBrush &brush); // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const Q_DECL_OVERRIDE; QCPItemPosition * const topLeft; QCPItemPosition * const bottomRight; @@ -3558,14 +6391,19 @@ protected: QBrush mBrush, mSelectedBrush; // reimplemented virtual methods: - virtual void draw(QCPPainter *painter); - virtual QPointF anchorPixelPoint(int anchorId) const; + virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; + virtual QPointF anchorPixelPosition(int anchorId) const Q_DECL_OVERRIDE; // non-virtual methods: QPen mainPen() const; QBrush mainBrush() const; }; +/* end of 'src/items/item-ellipse.h' */ + + +/* including file 'src/items/item-pixmap.h', size 4373 */ +/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */ class QCP_LIB_DECL QCPItemPixmap : public QCPAbstractItem { @@ -3579,7 +6417,7 @@ class QCP_LIB_DECL QCPItemPixmap : public QCPAbstractItem Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) /// \endcond public: - QCPItemPixmap(QCustomPlot *parentPlot); + explicit QCPItemPixmap(QCustomPlot *parentPlot); virtual ~QCPItemPixmap(); // getters: @@ -3597,7 +6435,7 @@ public: void setSelectedPen(const QPen &pen); // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const Q_DECL_OVERRIDE; QCPItemPosition * const topLeft; QCPItemPosition * const bottomRight; @@ -3615,13 +6453,14 @@ protected: QPixmap mPixmap; QPixmap mScaledPixmap; bool mScaled; + bool mScaledPixmapInvalidated; Qt::AspectRatioMode mAspectRatioMode; Qt::TransformationMode mTransformationMode; QPen mPen, mSelectedPen; // reimplemented virtual methods: - virtual void draw(QCPPainter *painter); - virtual QPointF anchorPixelPoint(int anchorId) const; + virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; + virtual QPointF anchorPixelPosition(int anchorId) const Q_DECL_OVERRIDE; // non-virtual methods: void updateScaledPixmap(QRect finalRect=QRect(), bool flipHorz=false, bool flipVert=false); @@ -3629,6 +6468,11 @@ protected: QPen mainPen() const; }; +/* end of 'src/items/item-pixmap.h' */ + + +/* including file 'src/items/item-tracer.h', size 4762 */ +/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */ class QCP_LIB_DECL QCPItemTracer : public QCPAbstractItem { @@ -3658,7 +6502,7 @@ public: }; Q_ENUMS(TracerStyle) - QCPItemTracer(QCustomPlot *parentPlot); + explicit QCPItemTracer(QCustomPlot *parentPlot); virtual ~QCPItemTracer(); // getters: @@ -3684,7 +6528,7 @@ public: void setInterpolating(bool enabled); // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const Q_DECL_OVERRIDE; // non-virtual methods: void updatePosition(); @@ -3702,13 +6546,19 @@ protected: bool mInterpolating; // reimplemented virtual methods: - virtual void draw(QCPPainter *painter); + virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; // non-virtual methods: QPen mainPen() const; QBrush mainBrush() const; }; +Q_DECLARE_METATYPE(QCPItemTracer::TracerStyle) +/* end of 'src/items/item-tracer.h' */ + + +/* including file 'src/items/item-bracket.h', size 3969 */ +/* commit 633339dadc92cb10c58ef3556b55570685fafb99 2016-09-13 23:54:56 +0200 */ class QCP_LIB_DECL QCPItemBracket : public QCPAbstractItem { @@ -3720,13 +6570,20 @@ class QCP_LIB_DECL QCPItemBracket : public QCPAbstractItem Q_PROPERTY(BracketStyle style READ style WRITE setStyle) /// \endcond public: + /*! + Defines the various visual shapes of the bracket item. The appearance can be further modified + by \ref setLength and \ref setPen. + + \see setStyle + */ enum BracketStyle { bsSquare ///< A brace with angled edges ,bsRound ///< A brace with round edges ,bsCurly ///< A curly brace ,bsCalligraphic ///< A curly brace with varying stroke width giving a calligraphic impression }; + Q_ENUMS(BracketStyle) - QCPItemBracket(QCustomPlot *parentPlot); + explicit QCPItemBracket(QCustomPlot *parentPlot); virtual ~QCPItemBracket(); // getters: @@ -3742,7 +6599,7 @@ public: void setStyle(BracketStyle style); // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const Q_DECL_OVERRIDE; QCPItemPosition * const left; QCPItemPosition * const right; @@ -3756,12 +6613,16 @@ protected: BracketStyle mStyle; // reimplemented virtual methods: - virtual void draw(QCPPainter *painter); - virtual QPointF anchorPixelPoint(int anchorId) const; + virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; + virtual QPointF anchorPixelPosition(int anchorId) const Q_DECL_OVERRIDE; // non-virtual methods: QPen mainPen() const; }; +Q_DECLARE_METATYPE(QCPItemBracket::BracketStyle) + +/* end of 'src/items/item-bracket.h' */ + #endif // QCUSTOMPLOT_H diff --git a/src/PlotDock.cpp b/src/PlotDock.cpp index 0f0faf09..83ee9862 100644 --- a/src/PlotDock.cpp +++ b/src/PlotDock.cpp @@ -170,10 +170,14 @@ void PlotDock::updatePlot(SqliteTableModel* model, BrowseDataTableSettings* sett // check if we have a x axis with datetime data if(xtype == QVariant::DateTime) { - ui->plotWidget->xAxis->setTickLabelType(QCPAxis::ltDateTime); - ui->plotWidget->xAxis->setDateTimeFormat("yyyy-MM-dd"); + QSharedPointer ticker(new QCPAxisTickerDateTime); + ticker->setDateTimeFormat("yyyy-MM-dd"); + ui->plotWidget->xAxis->setTicker(ticker); } else { - ui->plotWidget->xAxis->setTickLabelType(QCPAxis::ltNumber); + QSharedPointer ticker(new QCPAxisTickerFixed); + ticker->setTickStepStrategy(QCPAxisTicker::tssReadability); + ticker->setScaleStrategy(QCPAxisTickerFixed::ssMultiples); + ui->plotWidget->xAxis->setTicker(ticker); } // add graph for each selected y axis