diff --git a/README.md b/README.md index be01ab6..0072b94 100644 --- a/README.md +++ b/README.md @@ -1,14 +1,15 @@ - + ## 0 前言说明 1. **下载说明:由于可执行文件比较大,如有需要请到网盘下载。** 2. **网店地址:https://shop244026315.taobao.com/** 3. **联系方式:QQ(517216493)微信(feiyangqingyun)推荐加微信。** -4. **以下项目已经全部支持Qt4/5/6所有版本以及后续版本** -5. 监控作品体验:[https://pan.baidu.com/s/1d7TH_GEYl5nOecuNlWJJ7g](https://pan.baidu.com/s/1d7TH_GEYl5nOecuNlWJJ7g) 提取码:01jf -6. 其他作品体验:[https://pan.baidu.com/s/1ZxG-oyUKe286LPMPxOrO2A](https://pan.baidu.com/s/1ZxG-oyUKe286LPMPxOrO2A) 提取码:o05q -7. 监控系统在线文档:[https://feiyangqingyun.gitee.io/QWidgetDemo/video_system/](https://feiyangqingyun.gitee.io/QWidgetDemo/video_system/) -8. 大屏系统在线文档:[https://feiyangqingyun.gitee.io/QWidgetDemo/bigscreen/](https://feiyangqingyun.gitee.io/QWidgetDemo/bigscreen/) -9. 物联网系统在线文档:[https://feiyangqingyun.gitee.io/QWidgetDemo/iotsystem/](https://feiyangqingyun.gitee.io/QWidgetDemo/iotsystem/) +4. **以下项目已经全部支持Qt4/5/6所有版本以及后续版本。** +5. 项目作品大全:[https://blog.csdn.net/feiyangqingyun/article/details/97565652](https://blog.csdn.net/feiyangqingyun/article/details/97565652) +6. 监控作品体验:[https://pan.baidu.com/s/1d7TH_GEYl5nOecuNlWJJ7g](https://pan.baidu.com/s/1d7TH_GEYl5nOecuNlWJJ7g) 提取码:01jf +7. 其他作品体验:[https://pan.baidu.com/s/1ZxG-oyUKe286LPMPxOrO2A](https://pan.baidu.com/s/1ZxG-oyUKe286LPMPxOrO2A) 提取码:o05q +8. 监控系统在线文档:[https://feiyangqingyun.gitee.io/QWidgetDemo/video_system/](https://feiyangqingyun.gitee.io/QWidgetDemo/video_system/) +9. 大屏系统在线文档:[https://feiyangqingyun.gitee.io/QWidgetDemo/bigscreen/](https://feiyangqingyun.gitee.io/QWidgetDemo/bigscreen/) +10. 物联网系统在线文档:[https://feiyangqingyun.gitee.io/QWidgetDemo/iotsystem/](https://feiyangqingyun.gitee.io/QWidgetDemo/iotsystem/) ## 1 特别说明 1. 可以选择打开QWidgetDemo.pro一次性编译所有的,也可以到目录下打开pro编译。 diff --git a/third/3rd_qcustomplot/3rd_qcustomplot.pri b/third/3rd_qcustomplot/3rd_qcustomplot.pri index ac9160f..88a1ef5 100644 --- a/third/3rd_qcustomplot/3rd_qcustomplot.pri +++ b/third/3rd_qcustomplot/3rd_qcustomplot.pri @@ -2,6 +2,10 @@ greaterThan(QT_MAJOR_VERSION, 4): QT += printsupport greaterThan(QT_MAJOR_VERSION, 4): CONFIG += c++11 #lessThan(QT_MAJOR_VERSION, 5): QMAKE_CXXFLAGS += -std=c++11 +#引入平滑曲线类 +HEADERS += $$PWD/smoothcurve.h +SOURCES += $$PWD/smoothcurve.cpp + #没有定义任何版本则默认采用2.0 !contains(DEFINES, qcustomplot_v1_3) { !contains(DEFINES, qcustomplot_v2_0) { diff --git a/third/3rd_qcustomplot/smoothcurve.cpp b/third/3rd_qcustomplot/smoothcurve.cpp new file mode 100644 index 0000000..0977868 --- /dev/null +++ b/third/3rd_qcustomplot/smoothcurve.cpp @@ -0,0 +1,120 @@ +#include "smoothcurve.h" +#include "qdebug.h" + +QPainterPath SmoothCurve::createSmoothCurve(const QVector &points) +{ + QPainterPath path; + int len = points.size(); + if (len < 2) { + return path; + } + + QVector firstControlPoints; + QVector secondControlPoints; + calculateControlPoints(points, &firstControlPoints, &secondControlPoints); + path.moveTo(points[0].x(), points[0].y()); + + for (int i = 0; i < len - 1; ++i) { + path.cubicTo(firstControlPoints[i], secondControlPoints[i], points[i + 1]); + } + + return path; +} + +QPainterPath SmoothCurve::createSmoothCurve2(const QVector &points) +{ + //采用Qt原生方法不做任何处理 + int count = points.count(); + if (count == 0) { + return QPainterPath(); + } + + QPainterPath path(points.at(0)); + for (int i = 0; i < count - 1; ++i) { + //控制点的 x 坐标为 sp 与 ep 的 x 坐标和的一半 + //第一个控制点 c1 的 y 坐标为起始点 sp 的 y 坐标 + //第二个控制点 c2 的 y 坐标为结束点 ep 的 y 坐标 + QPointF sp = points.at(i); + QPointF ep = points.at(i + 1); + QPointF c1 = QPointF((sp.x() + ep.x()) / 2, sp.y()); + QPointF c2 = QPointF((sp.x() + ep.x()) / 2, ep.y()); + path.cubicTo(c1, c2, ep); + } + + return path; +} + +void SmoothCurve::calculateFirstControlPoints(double *&result, const double *rhs, int n) +{ + result = new double[n]; + double *tmp = new double[n]; + double b = 2.0; + result[0] = rhs[0] / b; + + for (int i = 1; i < n; ++i) { + tmp[i] = 1 / b; + b = (i < n - 1 ? 4.0 : 3.5) - tmp[i]; + result[i] = (rhs[i] - result[i - 1]) / b; + } + + for (int i = 1; i < n; ++i) { + result[n - i - 1] -= tmp[n - i] * result[n - i]; + } + + delete tmp; +} + +void SmoothCurve::calculateControlPoints(const QVector &datas, + QVector *firstControlPoints, + QVector *secondControlPoints) +{ + int n = datas.size() - 1; + for (int i = 0; i < n; ++i) { + firstControlPoints->append(QPointF()); + secondControlPoints->append(QPointF()); + } + + if (n == 1) { + (*firstControlPoints)[0].rx() = (2 * datas[0].x() + datas[1].x()) / 3; + (*firstControlPoints)[0].ry() = (2 * datas[0].y() + datas[1].y()) / 3; + (*secondControlPoints)[0].rx() = 2 * (*firstControlPoints)[0].x() - datas[0].x(); + (*secondControlPoints)[0].ry() = 2 * (*firstControlPoints)[0].y() - datas[0].y(); + return; + } + + double *xs = 0; + double *ys = 0; + double *rhsx = new double[n]; + double *rhsy = new double[n]; + + for (int i = 1; i < n - 1; ++i) { + rhsx[i] = 4 * datas[i].x() + 2 * datas[i + 1].x(); + rhsy[i] = 4 * datas[i].y() + 2 * datas[i + 1].y(); + } + + rhsx[0] = datas[0].x() + 2 * datas[1].x(); + rhsx[n - 1] = (8 * datas[n - 1].x() + datas[n].x()) / 2.0; + rhsy[0] = datas[0].y() + 2 * datas[1].y(); + rhsy[n - 1] = (8 * datas[n - 1].y() + datas[n].y()) / 2.0; + + calculateFirstControlPoints(xs, rhsx, n); + calculateFirstControlPoints(ys, rhsy, n); + + for (int i = 0; i < n; ++i) { + (*firstControlPoints)[i].rx() = xs[i]; + (*firstControlPoints)[i].ry() = ys[i]; + + if (i < n - 1) { + (*secondControlPoints)[i].rx() = 2 * datas[i + 1].x() - xs[i + 1]; + (*secondControlPoints)[i].ry() = 2 * datas[i + 1].y() - ys[i + 1]; + } else { + (*secondControlPoints)[i].rx() = (datas[n].x() + xs[n - 1]) / 2; + (*secondControlPoints)[i].ry() = (datas[n].y() + ys[n - 1]) / 2; + } + } + + delete xs; + delete ys; + delete rhsx; + delete rhsy; +} diff --git a/third/3rd_qcustomplot/smoothcurve.h b/third/3rd_qcustomplot/smoothcurve.h new file mode 100644 index 0000000..53bb103 --- /dev/null +++ b/third/3rd_qcustomplot/smoothcurve.h @@ -0,0 +1,28 @@ +#ifndef SMOOTHCURVE_H +#define SMOOTHCURVE_H + +#include +#include +#include +#include + +#ifdef quc +class Q_DECL_EXPORT SmoothCurve +#else +class SmoothCurve +#endif + +{ +public: + //创建平滑曲线路径 + static QPainterPath createSmoothCurve(const QVector &points); + static QPainterPath createSmoothCurve2(const QVector &points); + +private: + static void calculateFirstControlPoints(double *&result, const double *rhs, int n); + static void calculateControlPoints(const QVector &datas, + QVector *firstControlPoints, + QVector *secondControlPoints); +}; + +#endif // SMOOTHCURVE_H diff --git a/third/3rd_qcustomplot/v1_3/qcustomplot.cpp b/third/3rd_qcustomplot/v1_3/qcustomplot.cpp index 6c79f15..1dfedc6 100644 --- a/third/3rd_qcustomplot/v1_3/qcustomplot.cpp +++ b/third/3rd_qcustomplot/v1_3/qcustomplot.cpp @@ -24,7 +24,7 @@ ****************************************************************************/ #include "qcustomplot.h" - +#include "smoothcurve.h" //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -33,11 +33,11 @@ /*! \class QCPPainter \brief QPainter subclass used internally - + This QPainter subclass is used to provide some extended functionality e.g. for tweaking position consistency between antialiased and non-antialiased painting. Further it provides workarounds for QPainter quirks. - + \warning This class intentionally hides non-virtual functions of QPainter, e.g. setPen, save and restore. So while it is possible to pass a QCPPainter instance to a function that expects a QPainter pointer, some of the workarounds and tweaks will be unavailable to the function (because @@ -48,28 +48,29 @@ Creates a new QCPPainter instance and sets default values */ QCPPainter::QCPPainter() : - QPainter(), - mModes(pmDefault), - mIsAntialiasing(false) + QPainter(), + mModes(pmDefault), + mIsAntialiasing(false) { - // don't setRenderHint(QPainter::NonCosmeticDefautPen) here, because painter isn't active yet and - // a call to begin() will follow + // don't setRenderHint(QPainter::NonCosmeticDefautPen) here, because painter isn't active yet and + // a call to begin() will follow } /*! Creates a new QCPPainter instance on the specified paint \a device and sets default values. Just like the analogous QPainter constructor, begins painting on \a device immediately. - + Like \ref begin, this method sets QPainter::NonCosmeticDefaultPen in Qt versions before Qt5. */ QCPPainter::QCPPainter(QPaintDevice *device) : - QPainter(device), - mModes(pmDefault), - mIsAntialiasing(false) + QPainter(device), + mModes(pmDefault), + mIsAntialiasing(false) { #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) // before Qt5, default pens used to be cosmetic if NonCosmeticDefaultPen flag isn't set. So we set it to get consistency across Qt versions. - if (isActive()) - setRenderHint(QPainter::NonCosmeticDefaultPen); + if (isActive()) { + setRenderHint(QPainter::NonCosmeticDefaultPen); + } #endif } @@ -80,58 +81,62 @@ QCPPainter::~QCPPainter() /*! Sets the pen of the painter and applies certain fixes to it, depending on the mode of this QCPPainter. - + \note this function hides the non-virtual base class implementation. */ void QCPPainter::setPen(const QPen &pen) { - QPainter::setPen(pen); - if (mModes.testFlag(pmNonCosmetic)) - makeNonCosmetic(); + QPainter::setPen(pen); + if (mModes.testFlag(pmNonCosmetic)) { + makeNonCosmetic(); + } } /*! \overload - + Sets the pen (by color) of the painter and applies certain fixes to it, depending on the mode of this QCPPainter. - + \note this function hides the non-virtual base class implementation. */ void QCPPainter::setPen(const QColor &color) { - QPainter::setPen(color); - if (mModes.testFlag(pmNonCosmetic)) - makeNonCosmetic(); + QPainter::setPen(color); + if (mModes.testFlag(pmNonCosmetic)) { + makeNonCosmetic(); + } } /*! \overload - + Sets the pen (by style) of the painter and applies certain fixes to it, depending on the mode of this QCPPainter. - + \note this function hides the non-virtual base class implementation. */ void QCPPainter::setPen(Qt::PenStyle penStyle) { - QPainter::setPen(penStyle); - if (mModes.testFlag(pmNonCosmetic)) - makeNonCosmetic(); + QPainter::setPen(penStyle); + if (mModes.testFlag(pmNonCosmetic)) { + makeNonCosmetic(); + } } /*! \overload - + Works around a Qt bug introduced with Qt 4.8 which makes drawing QLineF unpredictable when antialiasing is disabled. Thus when antialiasing is disabled, it rounds the \a line to integer coordinates and then passes it to the original drawLine. - + \note this function hides the non-virtual base class implementation. */ void QCPPainter::drawLine(const QLineF &line) { - if (mIsAntialiasing || mModes.testFlag(pmVectorized)) - QPainter::drawLine(line); - else - QPainter::drawLine(line.toLine()); + if (mIsAntialiasing || mModes.testFlag(pmVectorized)) { + QPainter::drawLine(line); + } else { + QPainter::drawLine(line.toLine()); + } } /*! @@ -142,18 +147,17 @@ void QCPPainter::drawLine(const QLineF &line) */ void QCPPainter::setAntialiasing(bool enabled) { - setRenderHint(QPainter::Antialiasing, enabled); - if (mIsAntialiasing != enabled) - { - mIsAntialiasing = enabled; - if (!mModes.testFlag(pmVectorized)) // antialiasing half-pixel shift only needed for rasterized outputs - { - if (mIsAntialiasing) - translate(0.5, 0.5); - else - translate(-0.5, -0.5); + setRenderHint(QPainter::Antialiasing, enabled); + if (mIsAntialiasing != enabled) { + mIsAntialiasing = enabled; + if (!mModes.testFlag(pmVectorized)) { // antialiasing half-pixel shift only needed for rasterized outputs + if (mIsAntialiasing) { + translate(0.5, 0.5); + } else { + translate(-0.5, -0.5); + } + } } - } } /*! @@ -162,7 +166,7 @@ void QCPPainter::setAntialiasing(bool enabled) */ void QCPPainter::setModes(QCPPainter::PainterModes modes) { - mModes = modes; + mModes = modes; } /*! @@ -170,64 +174,67 @@ void QCPPainter::setModes(QCPPainter::PainterModes modes) device. This is necessary to get cosmetic pen consistency across Qt versions, because since Qt5, all pens are non-cosmetic by default, and in Qt4 this render hint must be set to get that behaviour. - + The Constructor \ref QCPPainter(QPaintDevice *device) which directly starts painting also sets the render hint as appropriate. - + \note this function hides the non-virtual base class implementation. */ bool QCPPainter::begin(QPaintDevice *device) { - bool result = QPainter::begin(device); + bool result = QPainter::begin(device); #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) // before Qt5, default pens used to be cosmetic if NonCosmeticDefaultPen flag isn't set. So we set it to get consistency across Qt versions. - if (result) - setRenderHint(QPainter::NonCosmeticDefaultPen); + if (result) { + setRenderHint(QPainter::NonCosmeticDefaultPen); + } #endif - return result; + return result; } /*! \overload - + Sets the mode of the painter. This controls whether the painter shall adjust its fixes/workarounds optimized for certain output devices. */ void QCPPainter::setMode(QCPPainter::PainterMode mode, bool enabled) { - if (!enabled && mModes.testFlag(mode)) - mModes &= ~mode; - else if (enabled && !mModes.testFlag(mode)) - mModes |= mode; + if (!enabled && mModes.testFlag(mode)) { + mModes &= ~mode; + } else if (enabled && !mModes.testFlag(mode)) { + mModes |= mode; + } } /*! Saves the painter (see QPainter::save). Since QCPPainter adds some new internal state to QPainter, the save/restore functions are reimplemented to also save/restore those members. - + \note this function hides the non-virtual base class implementation. - + \see restore */ void QCPPainter::save() { - mAntialiasingStack.push(mIsAntialiasing); - QPainter::save(); + mAntialiasingStack.push(mIsAntialiasing); + QPainter::save(); } /*! Restores the painter (see QPainter::restore). Since QCPPainter adds some new internal state to QPainter, the save/restore functions are reimplemented to also save/restore those members. - + \note this function hides the non-virtual base class implementation. - + \see save */ void QCPPainter::restore() { - if (!mAntialiasingStack.isEmpty()) - mIsAntialiasing = mAntialiasingStack.pop(); - else - qDebug() << Q_FUNC_INFO << "Unbalanced save/restore"; - QPainter::restore(); + if (!mAntialiasingStack.isEmpty()) { + mIsAntialiasing = mAntialiasingStack.pop(); + } else { + qDebug() << Q_FUNC_INFO << "Unbalanced save/restore"; + } + QPainter::restore(); } /*! @@ -236,12 +243,11 @@ void QCPPainter::restore() */ void QCPPainter::makeNonCosmetic() { - if (qFuzzyIsNull(pen().widthF())) - { - QPen p = pen(); - p.setWidth(1); - QPainter::setPen(p); - } + if (qFuzzyIsNull(pen().widthF())) { + QPen p = pen(); + p.setWidth(1); + QPainter::setPen(p); + } } @@ -251,33 +257,33 @@ void QCPPainter::makeNonCosmetic() /*! \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 @@ -285,15 +291,15 @@ void QCPPainter::makeNonCosmetic() 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. @@ -302,21 +308,21 @@ void QCPPainter::makeNonCosmetic() /* 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 left undefined, the scatter color will be inherited from the plottable that uses this scatter style. - + \see setPen */ @@ -324,32 +330,32 @@ void QCPPainter::makeNonCosmetic() /*! 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) + 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) + mSize(size), + mShape(shape), + mPen(Qt::NoPen), + mBrush(Qt::NoBrush), + mPenDefined(false) { } @@ -358,11 +364,11 @@ QCPScatterStyle::QCPScatterStyle(ScatterShape shape, double size) : 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) + mSize(size), + mShape(shape), + mPen(QPen(color)), + mBrush(Qt::NoBrush), + mPenDefined(true) { } @@ -371,18 +377,18 @@ QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QColor &color, double 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) + 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 @@ -395,11 +401,11 @@ QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QColor &color, const 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) + mSize(size), + mShape(shape), + mPen(pen), + mBrush(brush), + mPenDefined(pen.style() != Qt::NoPen) { } @@ -408,132 +414,132 @@ QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QPen &pen, const QBru is set to \ref ssPixmap. */ QCPScatterStyle::QCPScatterStyle(const QPixmap &pixmap) : - mSize(5), - mShape(ssPixmap), - mPen(Qt::NoPen), - mBrush(Qt::NoBrush), - mPixmap(pixmap), - mPenDefined(false) + 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) + 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; + 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; + 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; + 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; + 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; + 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; + 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); + 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()); + drawShape(painter, pos.x(), pos.y()); } /*! \overload @@ -541,126 +547,109 @@ void QCPScatterStyle::drawShape(QCPPainter *painter, QPointF pos) const */ 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; + 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: { + 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; + } } - 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; - } - } } @@ -670,18 +659,18 @@ 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. - + 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 @@ -691,21 +680,21 @@ void QCPScatterStyle::drawShape(QCPPainter *painter, double x, double y) const 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. - + 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. */ @@ -713,16 +702,16 @@ void QCPScatterStyle::drawShape(QCPPainter *painter, double x, double y) const /* start documentation of inline functions */ /*! \fn QList QCPLayer::children() const - + Returns a list of all layerables on this layer. The order corresponds to the rendering order: layerables with higher indices are drawn above layerables with lower indices. */ /*! \fn int QCPLayer::index() const - + Returns the index this layer has in the QCustomPlot. The index is the integer number by which this layer can be accessed via \ref QCustomPlot::layer. - + Layers with higher indices will be drawn above layers with lower indices. */ @@ -730,35 +719,37 @@ void QCPScatterStyle::drawShape(QCPPainter *painter, double x, double y) const /*! Creates a new QCPLayer instance. - + Normally you shouldn't directly instantiate layers, use \ref QCustomPlot::addLayer instead. - + \warning It is not checked that \a layerName is actually a unique layer name in \a parentPlot. This check is only performed by \ref QCustomPlot::addLayer. */ QCPLayer::QCPLayer(QCustomPlot *parentPlot, const QString &layerName) : - QObject(parentPlot), - mParentPlot(parentPlot), - mName(layerName), - mIndex(-1), // will be set to a proper value by the QCustomPlot layer creation function - mVisible(true) + QObject(parentPlot), + mParentPlot(parentPlot), + mName(layerName), + mIndex(-1), // will be set to a proper value by the QCustomPlot layer creation function + mVisible(true) { - // Note: no need to make sure layerName is unique, because layer - // management is done with QCustomPlot functions. + // Note: no need to make sure layerName is unique, because layer + // management is done with QCustomPlot functions. } QCPLayer::~QCPLayer() { - // If child layerables are still on this layer, detach them, so they don't try to reach back to this - // then invalid layer once they get deleted/moved themselves. This only happens when layers are deleted - // directly, like in the QCustomPlot destructor. (The regular layer removal procedure for the user is to - // call QCustomPlot::removeLayer, which moves all layerables off this layer before deleting it.) - - while (!mChildren.isEmpty()) - mChildren.last()->setLayer(0); // removes itself from mChildren via removeChild() - - if (mParentPlot->currentLayer() == this) - qDebug() << Q_FUNC_INFO << "The parent plot's mCurrentLayer will be a dangling pointer. Should have been set to a valid layer or 0 beforehand."; + // If child layerables are still on this layer, detach them, so they don't try to reach back to this + // then invalid layer once they get deleted/moved themselves. This only happens when layers are deleted + // directly, like in the QCustomPlot destructor. (The regular layer removal procedure for the user is to + // call QCustomPlot::removeLayer, which moves all layerables off this layer before deleting it.) + + while (!mChildren.isEmpty()) { + mChildren.last()->setLayer(0); // removes itself from mChildren via removeChild() + } + + if (mParentPlot->currentLayer() == this) { + qDebug() << Q_FUNC_INFO << "The parent plot's mCurrentLayer will be a dangling pointer. Should have been set to a valid layer or 0 beforehand."; + } } /*! @@ -771,44 +762,46 @@ QCPLayer::~QCPLayer() */ void QCPLayer::setVisible(bool visible) { - mVisible = visible; + mVisible = visible; } /*! \internal - + Adds the \a layerable to the list of this layer. If \a prepend is set to true, the layerable will be prepended to the list, i.e. be drawn beneath the other layerables already in the list. - + This function does not change the \a mLayer member of \a layerable to this layer. (Use QCPLayerable::setLayer to change the layer of an object, not this function.) - + \see removeChild */ void QCPLayer::addChild(QCPLayerable *layerable, bool prepend) { - if (!mChildren.contains(layerable)) - { - if (prepend) - mChildren.prepend(layerable); - else - mChildren.append(layerable); - } else - qDebug() << Q_FUNC_INFO << "layerable is already child of this layer" << reinterpret_cast(layerable); + if (!mChildren.contains(layerable)) { + if (prepend) { + mChildren.prepend(layerable); + } else { + mChildren.append(layerable); + } + } else { + qDebug() << Q_FUNC_INFO << "layerable is already child of this layer" << reinterpret_cast(layerable); + } } /*! \internal - + Removes the \a layerable from the list of this layer. - + This function does not change the \a mLayer member of \a layerable. (Use QCPLayerable::setLayer to change the layer of an object, not this function.) - + \see addChild */ void QCPLayer::removeChild(QCPLayerable *layerable) { - if (!mChildren.removeOne(layerable)) - qDebug() << Q_FUNC_INFO << "layerable is not child of this layer" << reinterpret_cast(layerable); + if (!mChildren.removeOne(layerable)) { + qDebug() << Q_FUNC_INFO << "layerable is not child of this layer" << reinterpret_cast(layerable); + } } @@ -818,27 +811,27 @@ void QCPLayer::removeChild(QCPLayerable *layerable) /*! \class QCPLayerable \brief Base class for all drawable objects - + This is the abstract base class most visible objects derive from, e.g. plottables, axes, grid etc. Every layerable is on a layer (QCPLayer) which allows controlling the rendering order by stacking the layers accordingly. - + For details about the layering mechanism, see the QCPLayer documentation. */ /* start documentation of inline functions */ /*! \fn QCPLayerable *QCPLayerable::parentLayerable() const - + Returns the parent layerable of this layerable. The parent layerable is used to provide visibility hierarchies in conjunction with the method \ref realVisibility. This way, layerables only get drawn if their parent layerables are visible, too. - + 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 set manually by the user. */ @@ -848,7 +841,7 @@ void QCPLayer::removeChild(QCPLayerable *layerable) /*! \fn virtual void QCPLayerable::applyDefaultAntialiasingHint(QCPPainter *painter) const = 0 \internal - + This function applies the default antialiasing setting to the specified \a painter, using the function \ref applyAntialiasingHint. It is the antialiasing state the painter is put in, when \ref draw is called on the layerable. If the layerable has multiple entities whose antialiasing @@ -856,7 +849,7 @@ void QCPLayer::removeChild(QCPLayerable *layerable) most prominent entity. In this case however, the \ref draw function usually calls the specialized versions of this function before drawing each entity, effectively overriding the setting of the 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 @@ -864,7 +857,7 @@ void QCPLayer::removeChild(QCPLayerable *layerable) 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. - + Second example: QCPItemLine consists only of a line so there is only one antialiasing setting which can be controlled with QCPItemLine::setAntialiased. (This function is inherited by all layerables. The specialized functions, as seen on QCPGraph, must be added explicitly to the @@ -877,10 +870,10 @@ void QCPLayer::removeChild(QCPLayerable *layerable) /*! \fn virtual void QCPLayerable::draw(QCPPainter *painter) const = 0 \internal - + This function draws the layerable with the specified \a painter. It is only called by QCustomPlot, if the layerable is visible (\ref setVisible). - + Before this function is called, the painter's antialiasing state is set via \ref applyDefaultAntialiasingHint, see the documentation there. Further, the clipping rectangle was set to \ref clipRect. @@ -890,10 +883,10 @@ void QCPLayer::removeChild(QCPLayerable *layerable) /* start documentation of signals */ /*! \fn void QCPLayerable::layerChanged(QCPLayer *newLayer); - + This signal is emitted when the layer of this layerable changes, i.e. this layerable is moved to a different layer. - + \see setLayer */ @@ -901,17 +894,17 @@ void QCPLayer::removeChild(QCPLayerable *layerable) /*! Creates a new QCPLayerable instance. - + Since QCPLayerable is an abstract base class, it can't be instantiated directly. Use one of the derived classes. - + If \a plot is provided, it automatically places itself on the layer named \a targetLayer. If \a targetLayer is an empty string, it places itself on the current layer of the plot (see \ref QCustomPlot::setCurrentLayer). - + 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 @@ -920,29 +913,28 @@ void QCPLayer::removeChild(QCPLayerable *layerable) QCPLayerable subclasses, to guarantee a working destruction hierarchy. */ QCPLayerable::QCPLayerable(QCustomPlot *plot, QString targetLayer, QCPLayerable *parentLayerable) : - QObject(plot), - mVisible(true), - mParentPlot(plot), - mParentLayerable(parentLayerable), - mLayer(0), - mAntialiased(true) + QObject(plot), + mVisible(true), + mParentPlot(plot), + mParentLayerable(parentLayerable), + mLayer(0), + mAntialiased(true) { - if (mParentPlot) - { - if (targetLayer.isEmpty()) - setLayer(mParentPlot->currentLayer()); - else if (!setLayer(targetLayer)) - qDebug() << Q_FUNC_INFO << "setting QCPlayerable initial layer to" << targetLayer << "failed."; - } + if (mParentPlot) { + if (targetLayer.isEmpty()) { + setLayer(mParentPlot->currentLayer()); + } else if (!setLayer(targetLayer)) { + qDebug() << Q_FUNC_INFO << "setting QCPlayerable initial layer to" << targetLayer << "failed."; + } + } } QCPLayerable::~QCPLayerable() { - if (mLayer) - { - mLayer->removeChild(this); - mLayer = 0; - } + if (mLayer) { + mLayer->removeChild(this); + mLayer = 0; + } } /*! @@ -952,72 +944,69 @@ QCPLayerable::~QCPLayerable() */ void QCPLayerable::setVisible(bool on) { - mVisible = on; + mVisible = on; } /*! Sets the \a layer of this layerable object. The object will be placed on top of the other objects already on \a 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) { - return moveToLayer(layer, false); + return moveToLayer(layer, false); } /*! \overload Sets the layer of this layerable object by name - + Returns true on success, i.e. if \a layerName is a valid layer name. */ bool QCPLayerable::setLayer(const QString &layerName) { - if (!mParentPlot) - { - qDebug() << Q_FUNC_INFO << "no parent QCustomPlot set"; - return false; - } - if (QCPLayer *layer = mParentPlot->layer(layerName)) - { - return setLayer(layer); - } else - { - qDebug() << Q_FUNC_INFO << "there is no layer with name" << layerName; - return false; - } + if (!mParentPlot) { + qDebug() << Q_FUNC_INFO << "no parent QCustomPlot set"; + return false; + } + if (QCPLayer *layer = mParentPlot->layer(layerName)) { + return setLayer(layer); + } else { + qDebug() << Q_FUNC_INFO << "there is no layer with name" << layerName; + return false; + } } /*! Sets whether this object will be drawn antialiased or not. - + Note that antialiasing settings may be overridden by QCustomPlot::setAntialiasedElements and QCustomPlot::setNotAntialiasedElements. */ void QCPLayerable::setAntialiased(bool enabled) { - mAntialiased = enabled; + mAntialiased = 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. - + 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 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 { - return mVisible && (!mLayer || mLayer->visible()) && (!mParentLayerable || mParentLayerable.data()->realVisibility()); + return mVisible && (!mLayer || mLayer->visible()) && (!mParentLayerable || mParentLayerable.data()->realVisibility()); } /*! @@ -1032,15 +1021,15 @@ bool QCPLayerable::realVisibility() const bars of a \ref QCPBars plottable, a click inside the area should also be considered a hit. In these cases this function thus returns a constant value greater zero but still below the parent plot's selection tolerance. (typically the selectionTolerance multiplied by 0.99). - + Providing a constant value for area objects allows selecting line objects even when they are obscured by such area objects, by clicking close to the lines (i.e. closer than 0.99*selectionTolerance). - + 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. - + \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 decides on the basis of this selectTest call, that the object was successfully selected. The @@ -1049,97 +1038,98 @@ bool QCPLayerable::realVisibility() const is only done once in \ref selectTest. The result (i.e. the actually clicked part) can then be placed in \a details. So in the subsequent \ref selectEvent, the decision which part was selected doesn't have to be done a second time for a single selection operation. - + You may pass 0 as \a details to indicate that you are not interested in those selection details. - + \see selectEvent, deselectEvent, QCustomPlot::setInteractions */ double QCPLayerable::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { - Q_UNUSED(pos) - Q_UNUSED(onlySelectable) - Q_UNUSED(details) - return -1.0; + Q_UNUSED(pos) + Q_UNUSED(onlySelectable) + Q_UNUSED(details) + return -1.0; } /*! \internal - + Sets the parent plot of this layerable. Use this function once to set the parent plot if you have passed 0 in the constructor. It can not be used to move a layerable from one QCustomPlot to another one. - + Note that, unlike when passing a non-null parent plot in the constructor, this function does not make \a parentPlot the QObject-parent of this layerable. If you want this, call QObject::setParent(\a parentPlot) in addition to this function. - + Further, you will probably want to set a layer (\ref setLayer) after calling this function, to make the layerable appear on the QCustomPlot. - + The parent plot change will be propagated to subclasses via a call to \ref parentPlotInitialized so they can react accordingly (e.g. also initialize the parent plot of child layerables, like QCPLayout does). */ void QCPLayerable::initializeParentPlot(QCustomPlot *parentPlot) { - if (mParentPlot) - { - qDebug() << Q_FUNC_INFO << "called with mParentPlot already initialized"; - return; - } - - if (!parentPlot) - qDebug() << Q_FUNC_INFO << "called with parentPlot zero"; - - mParentPlot = parentPlot; - parentPlotInitialized(mParentPlot); + if (mParentPlot) { + qDebug() << Q_FUNC_INFO << "called with mParentPlot already initialized"; + return; + } + + if (!parentPlot) { + qDebug() << Q_FUNC_INFO << "called with parentPlot zero"; + } + + mParentPlot = parentPlot; + parentPlotInitialized(mParentPlot); } /*! \internal - + Sets the parent layerable of this layerable to \a parentLayerable. Note that \a parentLayerable does not become the QObject-parent (for memory management) of this layerable. - + The parent layerable has influence on the return value of the \ref realVisibility method. Only layerables with a fully visible parent tree will return true for \ref realVisibility, and thus be drawn. - + \see realVisibility */ void QCPLayerable::setParentLayerable(QCPLayerable *parentLayerable) { - mParentLayerable = parentLayerable; + mParentLayerable = parentLayerable; } /*! \internal - + Moves this layerable object to \a layer. If \a prepend is true, this object will be prepended to the new layer's list, i.e. it will be drawn below the objects already on the layer. If it is false, the object will be appended. - + Returns true on success, i.e. if \a layer is a valid layer. */ bool QCPLayerable::moveToLayer(QCPLayer *layer, bool prepend) { - if (layer && !mParentPlot) - { - qDebug() << Q_FUNC_INFO << "no parent QCustomPlot set"; - return false; - } - if (layer && layer->parentPlot() != mParentPlot) - { - qDebug() << Q_FUNC_INFO << "layer" << layer->name() << "is not in same QCustomPlot as this layerable"; - return false; - } - - QCPLayer *oldLayer = mLayer; - if (mLayer) - mLayer->removeChild(this); - mLayer = layer; - if (mLayer) - mLayer->addChild(this, prepend); - if (mLayer != oldLayer) - emit layerChanged(mLayer); - return true; + if (layer && !mParentPlot) { + qDebug() << Q_FUNC_INFO << "no parent QCustomPlot set"; + return false; + } + if (layer && layer->parentPlot() != mParentPlot) { + qDebug() << Q_FUNC_INFO << "layer" << layer->name() << "is not in same QCustomPlot as this layerable"; + return false; + } + + QCPLayer *oldLayer = mLayer; + if (mLayer) { + mLayer->removeChild(this); + } + mLayer = layer; + if (mLayer) { + mLayer->addChild(this, prepend); + } + if (mLayer != oldLayer) { + emit layerChanged(mLayer); + } + return true; } /*! \internal @@ -1151,12 +1141,13 @@ bool QCPLayerable::moveToLayer(QCPLayer *layer, bool prepend) */ void QCPLayerable::applyAntialiasingHint(QCPPainter *painter, bool localAntialiased, QCP::AntialiasedElement overrideElement) const { - if (mParentPlot && mParentPlot->notAntialiasedElements().testFlag(overrideElement)) - painter->setAntialiasing(false); - else if (mParentPlot && mParentPlot->antialiasedElements().testFlag(overrideElement)) - painter->setAntialiasing(true); - else - painter->setAntialiasing(localAntialiased); + if (mParentPlot && mParentPlot->notAntialiasedElements().testFlag(overrideElement)) { + painter->setAntialiasing(false); + } else if (mParentPlot && mParentPlot->antialiasedElements().testFlag(overrideElement)) { + painter->setAntialiasing(true); + } else { + painter->setAntialiasing(localAntialiased); + } } /*! \internal @@ -1164,20 +1155,20 @@ void QCPLayerable::applyAntialiasingHint(QCPPainter *painter, bool localAntialia This function is called by \ref initializeParentPlot, to allow subclasses to react on the setting of a parent plot. This is the case when 0 was passed as parent plot in the constructor, and the parent plot is set at a later time. - + For example, QCPLayoutElement/QCPLayout hierarchies may be created independently of any QCustomPlot at first. When they are then added to a layout inside the QCustomPlot, the top level element of the hierarchy gets its parent plot initialized with \ref initializeParentPlot. To propagate the parent plot to all the children of the hierarchy, the top level element then uses this function to pass the parent plot on to its child elements. - + The default implementation does nothing. - + \see initializeParentPlot */ void QCPLayerable::parentPlotInitialized(QCustomPlot *parentPlot) { - Q_UNUSED(parentPlot) + Q_UNUSED(parentPlot) } /*! \internal @@ -1185,45 +1176,46 @@ void QCPLayerable::parentPlotInitialized(QCustomPlot *parentPlot) Returns the selection category this layerable shall belong to. The selection category is used in conjunction with \ref QCustomPlot::setInteractions to control which objects are selectable and which aren't. - + Subclasses that don't fit any of the normal \ref QCP::Interaction values can use \ref QCP::iSelectOther. This is what the default implementation returns. - + \see QCustomPlot::setInteractions */ QCP::Interaction QCPLayerable::selectionCategory() const { - return QCP::iSelectOther; + return QCP::iSelectOther; } /*! \internal - + Returns the clipping rectangle of this layerable object. By default, this is the viewport of the parent QCustomPlot. Specific subclasses may reimplement this function to provide different clipping rects. - + The returned clipping rect is set on the painter before the draw function of the respective object is called. */ QRect QCPLayerable::clipRect() const { - if (mParentPlot) - return mParentPlot->viewport(); - else - return QRect(); + if (mParentPlot) { + return mParentPlot->viewport(); + } else { + return QRect(); + } } /*! \internal - + This event is called when the layerable shall be selected, as a consequence of a click by the user. Subclasses should react to it by setting their selection state appropriately. The default implementation does nothing. - + \a event is the mouse event that caused the selection. \a additive indicates, whether the user was holding the multi-select-modifier while performing the selection (see \ref QCustomPlot::setMultiSelectModifier). if \a additive is true, the selection state must be toggled (i.e. become selected when unselected and unselected when selected). - + Every selectEvent is preceded by a call to \ref selectTest, which has returned positively (i.e. returned a value greater than 0 and less than the selection tolerance of the parent QCustomPlot). The \a details data you output from \ref selectTest is fed back via \a details here. You may @@ -1231,39 +1223,39 @@ QRect QCPLayerable::clipRect() const selectEvent. Usually \a details is used to transfer which part was clicked, if it is a layerable that has multiple individually selectable parts (like QCPAxis). This way selectEvent doesn't need to do the calculation again to find out which part was actually clicked. - + \a selectionStateChanged is an output parameter. If the pointer is non-null, this function must set the value either to true or false, depending on whether the selection state of this layerable was actually changed. For layerables that only are selectable as a whole and not in parts, this is simple: if \a additive is true, \a selectionStateChanged must also be set to true, because the selection toggles. If \a additive is false, \a selectionStateChanged is only set to true, if the layerable was previously unselected and now is switched to the selected state. - + \see selectTest, deselectEvent */ void QCPLayerable::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) { - Q_UNUSED(event) - Q_UNUSED(additive) - Q_UNUSED(details) - Q_UNUSED(selectionStateChanged) + Q_UNUSED(event) + Q_UNUSED(additive) + Q_UNUSED(details) + Q_UNUSED(selectionStateChanged) } /*! \internal - + This event is called when the layerable shall be deselected, either as consequence of a user interaction or a call to \ref QCustomPlot::deselectAll. Subclasses should react to it by unsetting their selection appropriately. - + just as in \ref selectEvent, the output parameter \a selectionStateChanged (if non-null), must return true or false when the selection state of this layerable has changed or not changed, respectively. - + \see selectTest, selectEvent */ void QCPLayerable::deselectEvent(bool *selectionStateChanged) { - Q_UNUSED(selectionStateChanged) + Q_UNUSED(selectionStateChanged) } @@ -1272,10 +1264,10 @@ void QCPLayerable::deselectEvent(bool *selectionStateChanged) //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPRange \brief Represents the range an axis is encompassing. - + contains a \a lower and \a upper double value and provides convenience input, output and modification functions. - + \see QCPAxis::setRange */ @@ -1301,8 +1293,8 @@ const double QCPRange::maxRange = 1e250; Constructs a range with \a lower and \a upper set to zero. */ QCPRange::QCPRange() : - lower(0), - upper(0) + lower(0), + upper(0) { } @@ -1310,10 +1302,10 @@ QCPRange::QCPRange() : Constructs a range with the specified \a lower and \a upper values. */ QCPRange::QCPRange(double lower, double upper) : - lower(lower), - upper(upper) + lower(lower), + upper(upper) { - normalize(); + normalize(); } /*! @@ -1321,7 +1313,7 @@ QCPRange::QCPRange(double lower, double upper) : */ double QCPRange::size() const { - return upper-lower; + return upper - lower; } /*! @@ -1329,7 +1321,7 @@ double QCPRange::size() const */ double QCPRange::center() const { - return (upper+lower)*0.5; + return (upper + lower) * 0.5; } /*! @@ -1338,45 +1330,48 @@ double QCPRange::center() const */ void QCPRange::normalize() { - if (lower > upper) - qSwap(lower, upper); + 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 \a otherRange is already inside the current range, this function does nothing. - + \see expanded */ void QCPRange::expand(const QCPRange &otherRange) { - if (lower > otherRange.lower) - lower = otherRange.lower; - if (upper < otherRange.upper) - upper = otherRange.upper; + if (lower > otherRange.lower) { + lower = otherRange.lower; + } + if (upper < otherRange.upper) { + upper = otherRange.upper; + } } /*! 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). - + \see expand */ QCPRange QCPRange::expanded(const QCPRange &otherRange) const { - QCPRange result = *this; - result.expand(otherRange); - return result; + QCPRange result = *this; + result.expand(otherRange); + 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 \a lower will always be numerically smaller (or equal) to \a upper. - + If the original range does span positive and negative sign domains or contains zero, the returned range will try to approximate the original range as good as possible. If the positive interval of the original range is wider than the negative interval, the @@ -1386,47 +1381,46 @@ QCPRange QCPRange::expanded(const QCPRange &otherRange) const */ QCPRange QCPRange::sanitizedForLogScale() const { - double rangeFac = 1e-3; - QCPRange sanitizedRange(lower, upper); - sanitizedRange.normalize(); - // can't have range spanning negative and positive values in log plot, so change range to fix it - //if (qFuzzyCompare(sanitizedRange.lower+1, 1) && !qFuzzyCompare(sanitizedRange.upper+1, 1)) - if (sanitizedRange.lower == 0.0 && sanitizedRange.upper != 0.0) - { - // case lower is 0 - if (rangeFac < sanitizedRange.upper*rangeFac) - sanitizedRange.lower = rangeFac; - else - sanitizedRange.lower = sanitizedRange.upper*rangeFac; - } //else if (!qFuzzyCompare(lower+1, 1) && qFuzzyCompare(upper+1, 1)) - else if (sanitizedRange.lower != 0.0 && sanitizedRange.upper == 0.0) - { - // case upper is 0 - if (-rangeFac > sanitizedRange.lower*rangeFac) - sanitizedRange.upper = -rangeFac; - else - sanitizedRange.upper = sanitizedRange.lower*rangeFac; - } else if (sanitizedRange.lower < 0 && sanitizedRange.upper > 0) - { - // find out whether negative or positive interval is wider to decide which sign domain will be chosen - if (-sanitizedRange.lower > sanitizedRange.upper) - { - // negative is wider, do same as in case upper is 0 - if (-rangeFac > sanitizedRange.lower*rangeFac) - sanitizedRange.upper = -rangeFac; - else - sanitizedRange.upper = sanitizedRange.lower*rangeFac; - } else - { - // positive is wider, do same as in case lower is 0 - if (rangeFac < sanitizedRange.upper*rangeFac) - sanitizedRange.lower = rangeFac; - else - sanitizedRange.lower = sanitizedRange.upper*rangeFac; + double rangeFac = 1e-3; + QCPRange sanitizedRange(lower, upper); + sanitizedRange.normalize(); + // can't have range spanning negative and positive values in log plot, so change range to fix it + //if (qFuzzyCompare(sanitizedRange.lower+1, 1) && !qFuzzyCompare(sanitizedRange.upper+1, 1)) + if (sanitizedRange.lower == 0.0 && sanitizedRange.upper != 0.0) { + // case lower is 0 + if (rangeFac < sanitizedRange.upper * rangeFac) { + sanitizedRange.lower = rangeFac; + } else { + sanitizedRange.lower = sanitizedRange.upper * rangeFac; + } + } //else if (!qFuzzyCompare(lower+1, 1) && qFuzzyCompare(upper+1, 1)) + else if (sanitizedRange.lower != 0.0 && sanitizedRange.upper == 0.0) { + // case upper is 0 + if (-rangeFac > sanitizedRange.lower * rangeFac) { + sanitizedRange.upper = -rangeFac; + } else { + sanitizedRange.upper = sanitizedRange.lower * rangeFac; + } + } else if (sanitizedRange.lower < 0 && sanitizedRange.upper > 0) { + // find out whether negative or positive interval is wider to decide which sign domain will be chosen + if (-sanitizedRange.lower > sanitizedRange.upper) { + // negative is wider, do same as in case upper is 0 + if (-rangeFac > sanitizedRange.lower * rangeFac) { + sanitizedRange.upper = -rangeFac; + } else { + sanitizedRange.upper = sanitizedRange.lower * rangeFac; + } + } else { + // positive is wider, do same as in case lower is 0 + if (rangeFac < sanitizedRange.upper * rangeFac) { + sanitizedRange.lower = rangeFac; + } else { + sanitizedRange.lower = sanitizedRange.upper * rangeFac; + } + } } - } - // due to normalization, case lower>0 && upper<0 should never occur, because that implies upper0 && upper<0 should never occur, because that implies upper= lower && value <= upper; + return value >= lower && value <= upper; } /*! @@ -1458,12 +1452,12 @@ bool QCPRange::contains(double value) const */ bool QCPRange::validRange(double lower, double upper) { - return (lower > -maxRange && - upper < maxRange && - qAbs(lower-upper) > minRange && - qAbs(lower-upper) < maxRange && - !(lower > 0 && qIsInf(upper/lower)) && - !(upper < 0 && qIsInf(lower/upper))); + return (lower > -maxRange && + upper < maxRange && + qAbs(lower - upper) > minRange && + qAbs(lower - upper) < maxRange && + !(lower > 0 && qIsInf(upper / lower)) && + !(upper < 0 && qIsInf(lower / upper))); } /*! @@ -1477,12 +1471,12 @@ 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 > 0 && qIsInf(range.upper/range.lower)) && - !(range.upper < 0 && qIsInf(range.lower/range.upper))); + 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))); } @@ -1492,27 +1486,27 @@ bool QCPRange::validRange(const QCPRange &range) /*! \class QCPMarginGroup \brief A margin group allows synchronization of margin sides if working with multiple layout elements. - + QCPMarginGroup allows you to tie a margin side of two or more layout elements together, such that they will all have the same size, based on the largest required margin in the group. - + \n \image html QCPMarginGroup.png "Demonstration of QCPMarginGroup" \n - + In certain situations it is desirable that margins at specific sides are synchronized across layout elements. For example, if one QCPAxisRect is below another one in a grid layout, it will provide a cleaner look to the user if the left and right margins of the two axis rects are of the same size. The left axis of the top axis rect will then be at the same horizontal position as the left axis of the lower axis rect, making them appear aligned. The same applies for the right axes. This is what QCPMarginGroup makes possible. - + To add/remove a specific side of a layout element to/from a margin group, use the \ref QCPLayoutElement::setMarginGroup method. To completely break apart the margin group, either call \ref clear, or just delete the margin group. - + \section QCPMarginGroup-example Example - + First create a margin group: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpmargingroup-creation-1 Then set this group on the layout element sides: @@ -1524,7 +1518,7 @@ bool QCPRange::validRange(const QCPRange &range) /* start documentation of inline functions */ /*! \fn QList QCPMarginGroup::elements(QCP::MarginSide side) const - + Returns a list of all layout elements that have their margin \a side associated with this margin group. */ @@ -1535,18 +1529,18 @@ bool QCPRange::validRange(const QCPRange &range) Creates a new QCPMarginGroup instance in \a parentPlot. */ QCPMarginGroup::QCPMarginGroup(QCustomPlot *parentPlot) : - QObject(parentPlot), - mParentPlot(parentPlot) + QObject(parentPlot), + mParentPlot(parentPlot) { - mChildren.insert(QCP::msLeft, QList()); - mChildren.insert(QCP::msRight, QList()); - mChildren.insert(QCP::msTop, QList()); - mChildren.insert(QCP::msBottom, QList()); + mChildren.insert(QCP::msLeft, QList()); + mChildren.insert(QCP::msRight, QList()); + mChildren.insert(QCP::msTop, QList()); + mChildren.insert(QCP::msBottom, QList()); } QCPMarginGroup::~QCPMarginGroup() { - clear(); + clear(); } /*! @@ -1555,14 +1549,14 @@ QCPMarginGroup::~QCPMarginGroup() */ bool QCPMarginGroup::isEmpty() const { - QHashIterator > it(mChildren); - while (it.hasNext()) - { - it.next(); - if (!it.value().isEmpty()) - return false; - } - return true; + QHashIterator > it(mChildren); + while (it.hasNext()) { + it.next(); + if (!it.value().isEmpty()) { + return false; + } + } + return true; } /*! @@ -1571,22 +1565,22 @@ bool QCPMarginGroup::isEmpty() const */ void QCPMarginGroup::clear() { - // make all children remove themselves from this margin group: - QHashIterator > it(mChildren); - while (it.hasNext()) - { - it.next(); - const QList elements = it.value(); - for (int i=elements.size()-1; i>=0; --i) - elements.at(i)->setMarginGroup(it.key(), 0); // removes itself from mChildren via removeChild - } + // make all children remove themselves from this margin group: + QHashIterator > it(mChildren); + while (it.hasNext()) { + it.next(); + const QList elements = it.value(); + for (int i = elements.size() - 1; i >= 0; --i) { + elements.at(i)->setMarginGroup(it.key(), 0); // removes itself from mChildren via removeChild + } + } } /*! \internal - + Returns the synchronized common margin for \a side. This is the margin value that will be used by the layout element on the respective side, if it is part of this margin group. - + The common margin is calculated by requesting the automatic margin (\ref QCPLayoutElement::calculateAutoMargin) of each element associated with \a side in this margin group, and choosing the largest returned value. (QCPLayoutElement::minimumMargins is taken into @@ -1594,44 +1588,47 @@ void QCPMarginGroup::clear() */ int QCPMarginGroup::commonMargin(QCP::MarginSide side) const { - // query all automatic margins of the layout elements in this margin group side and find maximum: - int result = 0; - const QList elements = mChildren.value(side); - for (int i=0; iautoMargins().testFlag(side)) - continue; - int m = qMax(elements.at(i)->calculateAutoMargin(side), QCP::getMarginValue(elements.at(i)->minimumMargins(), side)); - if (m > result) - result = m; - } - return result; + // query all automatic margins of the layout elements in this margin group side and find maximum: + int result = 0; + const QList elements = mChildren.value(side); + for (int i = 0; i < elements.size(); ++i) { + if (!elements.at(i)->autoMargins().testFlag(side)) { + continue; + } + int m = qMax(elements.at(i)->calculateAutoMargin(side), QCP::getMarginValue(elements.at(i)->minimumMargins(), side)); + if (m > result) { + result = m; + } + } + return result; } /*! \internal - + Adds \a element to the internal list of child elements, for the margin \a side. - + This function does not modify the margin group property of \a element. */ void QCPMarginGroup::addChild(QCP::MarginSide side, QCPLayoutElement *element) { - if (!mChildren[side].contains(element)) - mChildren[side].append(element); - else - qDebug() << Q_FUNC_INFO << "element is already child of this margin group side" << reinterpret_cast(element); + if (!mChildren[side].contains(element)) { + mChildren[side].append(element); + } else { + qDebug() << Q_FUNC_INFO << "element is already child of this margin group side" << reinterpret_cast(element); + } } /*! \internal - + Removes \a element from the internal list of child elements, for the margin \a side. - + This function does not modify the margin group property of \a element. */ void QCPMarginGroup::removeChild(QCP::MarginSide side, QCPLayoutElement *element) { - if (!mChildren[side].removeOne(element)) - qDebug() << Q_FUNC_INFO << "element is not child of this margin group side" << reinterpret_cast(element); + if (!mChildren[side].removeOne(element)) { + qDebug() << Q_FUNC_INFO << "element is not child of this margin group side" << reinterpret_cast(element); + } } @@ -1641,20 +1638,20 @@ void QCPMarginGroup::removeChild(QCP::MarginSide side, QCPLayoutElement *element /*! \class QCPLayoutElement \brief The abstract base class for all objects that form \ref thelayoutsystem "the layout system". - + This is an abstract base class. As such, it can't be instantiated directly, rather use one of its subclasses. - + A Layout element is a rectangular object which can be placed in layouts. It has an outer rect (QCPLayoutElement::outerRect) and an inner rect (\ref QCPLayoutElement::rect). The difference between outer and inner rect is called its margin. The margin can either be set to automatic or manual (\ref setAutoMargins) on a per-side basis. If a side is set to manual, that margin can be set explicitly with \ref setMargins and will stay fixed at that value. If it's set to automatic, the layout element subclass will control the value itself (via \ref calculateAutoMargin). - + Layout elements can be placed in layouts (base class QCPLayout) like QCPLayoutGrid. The top level layout is reachable via \ref QCustomPlot::plotLayout, and is a \ref QCPLayoutGrid. Since \ref QCPLayout itself derives from \ref QCPLayoutElement, layouts can be nested. - + Thus in QCustomPlot one can divide layout elements into two categories: The ones that are 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 @@ -1668,15 +1665,15 @@ void QCPMarginGroup::removeChild(QCP::MarginSide side, QCPLayoutElement *element /* start documentation of inline functions */ /*! \fn QCPLayout *QCPLayoutElement::layout() const - + Returns the parent layout of this layout element. */ /*! \fn QRect QCPLayoutElement::rect() const - + Returns the inner rect of this layout element. The inner rect is the outer rect (\ref setOuterRect) shrinked by the margins (\ref setMargins, \ref setAutoMargins). - + In some cases, the area between outer and inner rect is left blank. In other cases the margin area is used to display peripheral graphics while the main content is in the inner rect. This is where automatic margin calculation becomes interesting because it allows the layout element to @@ -1686,30 +1683,30 @@ void QCPMarginGroup::removeChild(QCP::MarginSide side, QCPLayoutElement *element */ /*! \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. */ @@ -1720,102 +1717,100 @@ void QCPMarginGroup::removeChild(QCP::MarginSide side, QCPLayoutElement *element Creates an instance of QCPLayoutElement and sets default values. */ QCPLayoutElement::QCPLayoutElement(QCustomPlot *parentPlot) : - QCPLayerable(parentPlot), // parenthood is changed as soon as layout element gets inserted into a layout (except for top level layout) - mParentLayout(0), - mMinimumSize(), - mMaximumSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX), - mRect(0, 0, 0, 0), - mOuterRect(0, 0, 0, 0), - mMargins(0, 0, 0, 0), - mMinimumMargins(0, 0, 0, 0), - mAutoMargins(QCP::msAll) + QCPLayerable(parentPlot), // parenthood is changed as soon as layout element gets inserted into a layout (except for top level layout) + mParentLayout(0), + mMinimumSize(), + mMaximumSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX), + mRect(0, 0, 0, 0), + mOuterRect(0, 0, 0, 0), + mMargins(0, 0, 0, 0), + mMinimumMargins(0, 0, 0, 0), + mAutoMargins(QCP::msAll) { } QCPLayoutElement::~QCPLayoutElement() { - setMarginGroup(QCP::msAll, 0); // unregister at margin groups, if there are any - // unregister at layout: - if (qobject_cast(mParentLayout)) // the qobject_cast is just a safeguard in case the layout forgets to call clear() in its dtor and this dtor is called by QObject dtor - mParentLayout->take(this); + setMarginGroup(QCP::msAll, 0); // unregister at margin groups, if there are any + // unregister at layout: + if (qobject_cast(mParentLayout)) { // the qobject_cast is just a safeguard in case the layout forgets to call clear() in its dtor and this dtor is called by QObject dtor + mParentLayout->take(this); + } } /*! Sets the outer rect of this layout element. If the layout element is inside a layout, the layout sets the position and size of this layout element using this function. - + Calling this function externally has no effect, since the layout will overwrite any changes to the outer rect upon the next replot. - + The layout element will adapt its inner \ref rect by applying the margins inward to the outer rect. - + \see rect */ void QCPLayoutElement::setOuterRect(const QRect &rect) { - if (mOuterRect != rect) - { - mOuterRect = rect; - mRect = mOuterRect.adjusted(mMargins.left(), mMargins.top(), -mMargins.right(), -mMargins.bottom()); - } + if (mOuterRect != rect) { + mOuterRect = rect; + mRect = mOuterRect.adjusted(mMargins.left(), mMargins.top(), -mMargins.right(), -mMargins.bottom()); + } } /*! Sets the margins of this layout element. If \ref setAutoMargins is disabled for some or all sides, this function is used to manually set the margin on those sides. Sides that are still set to be handled automatically are ignored and may have any value in \a margins. - + The margin is the distance between the outer rect (controlled by the parent layout via \ref setOuterRect) and the inner \ref rect (which usually contains the main content of this layout element). - + \see setAutoMargins */ void QCPLayoutElement::setMargins(const QMargins &margins) { - if (mMargins != margins) - { - mMargins = margins; - mRect = mOuterRect.adjusted(mMargins.left(), mMargins.top(), -mMargins.right(), -mMargins.bottom()); - } + if (mMargins != margins) { + mMargins = margins; + mRect = mOuterRect.adjusted(mMargins.left(), mMargins.top(), -mMargins.right(), -mMargins.bottom()); + } } /*! If \ref setAutoMargins is enabled on some or all margins, this function is used to provide minimum values for those margins. - + The minimum values are not enforced on margin sides that were set to be under manual control via \ref setAutoMargins. - + \see setAutoMargins */ void QCPLayoutElement::setMinimumMargins(const QMargins &margins) { - if (mMinimumMargins != margins) - { - mMinimumMargins = margins; - } + if (mMinimumMargins != margins) { + mMinimumMargins = margins; + } } /*! Sets on which sides the margin shall be calculated automatically. If a side is calculated automatically, a minimum margin value may be provided with \ref setMinimumMargins. If a side is set to be controlled manually, the value may be specified with \ref setMargins. - + 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 */ void QCPLayoutElement::setAutoMargins(QCP::MarginSides sides) { - mAutoMargins = sides; + mAutoMargins = sides; } /*! Sets the minimum size for the inner \ref rect of this layout element. A parent layout tries to respect the \a size here by changing row/column sizes in the layout accordingly. - + If the parent layout size is not sufficient to satisfy all minimum size constraints of its child layout elements, the layout may set a size that is actually smaller than \a size. QCustomPlot propagates the layout's size constraints to the outside by setting its own minimum QWidget size @@ -1823,21 +1818,21 @@ void QCPLayoutElement::setAutoMargins(QCP::MarginSides sides) */ void QCPLayoutElement::setMinimumSize(const QSize &size) { - if (mMinimumSize != size) - { - mMinimumSize = size; - if (mParentLayout) - mParentLayout->sizeConstraintsChanged(); - } + if (mMinimumSize != size) { + mMinimumSize = size; + if (mParentLayout) { + mParentLayout->sizeConstraintsChanged(); + } + } } /*! \overload - + Sets the minimum size for the inner \ref rect of this layout element. */ void QCPLayoutElement::setMinimumSize(int width, int height) { - setMinimumSize(QSize(width, height)); + setMinimumSize(QSize(width, height)); } /*! @@ -1846,61 +1841,66 @@ void QCPLayoutElement::setMinimumSize(int width, int height) */ void QCPLayoutElement::setMaximumSize(const QSize &size) { - if (mMaximumSize != size) - { - mMaximumSize = size; - if (mParentLayout) - mParentLayout->sizeConstraintsChanged(); - } + if (mMaximumSize != size) { + mMaximumSize = size; + if (mParentLayout) { + mParentLayout->sizeConstraintsChanged(); + } + } } /*! \overload - + Sets the maximum size for the inner \ref rect of this layout element. */ void QCPLayoutElement::setMaximumSize(int width, int height) { - setMaximumSize(QSize(width, height)); + setMaximumSize(QSize(width, height)); } /*! Sets the margin \a group of the specified margin \a sides. - + Margin groups allow synchronizing specified margins across layout elements, see the documentation of \ref QCPMarginGroup. - + To unset the margin group of \a sides, set \a group to 0. - + Note that margin groups only work for margin sides that are set to automatic (\ref setAutoMargins). */ void QCPLayoutElement::setMarginGroup(QCP::MarginSides sides, QCPMarginGroup *group) { - QVector sideVector; - if (sides.testFlag(QCP::msLeft)) sideVector.append(QCP::msLeft); - if (sides.testFlag(QCP::msRight)) sideVector.append(QCP::msRight); - if (sides.testFlag(QCP::msTop)) sideVector.append(QCP::msTop); - if (sides.testFlag(QCP::msBottom)) sideVector.append(QCP::msBottom); - - for (int i=0; iremoveChild(side, this); - - if (!group) // if setting to 0, remove hash entry. Else set hash entry to new group and register there - { - mMarginGroups.remove(side); - } else // setting to a new group - { - mMarginGroups[side] = group; - group->addChild(side, this); - } + QVector sideVector; + if (sides.testFlag(QCP::msLeft)) { + sideVector.append(QCP::msLeft); + } + if (sides.testFlag(QCP::msRight)) { + sideVector.append(QCP::msRight); + } + if (sides.testFlag(QCP::msTop)) { + sideVector.append(QCP::msTop); + } + if (sides.testFlag(QCP::msBottom)) { + sideVector.append(QCP::msBottom); + } + + for (int i = 0; i < sideVector.size(); ++i) { + QCP::MarginSide side = sideVector.at(i); + if (marginGroup(side) != group) { + QCPMarginGroup *oldGroup = marginGroup(side); + if (oldGroup) { // unregister at old group + oldGroup->removeChild(side, this); + } + + if (!group) { // if setting to 0, remove hash entry. Else set hash entry to new group and register there + mMarginGroups.remove(side); + } else { // setting to a new group + mMarginGroups[side] = group; + group->addChild(side, this); + } + } } - } } /*! @@ -1908,75 +1908,73 @@ void QCPLayoutElement::setMarginGroup(QCP::MarginSides sides, QCPMarginGroup *gr replot by the parent layout element. It is called multiple times, once for every \ref UpdatePhase. The phases are run through in the order of the enum values. For details about what happens at the different phases, see the documentation of \ref UpdatePhase. - + Layout elements that have child elements should call the \ref update method of their child elements, and pass the current \a phase unchanged. - + The default implementation executes the automatic margin mechanism in the \ref upMargins phase. Subclasses should make sure to call the base class implementation. */ void QCPLayoutElement::update(UpdatePhase phase) { - if (phase == upMargins) - { - if (mAutoMargins != QCP::msNone) - { - // set the margins of this layout element according to automatic margin calculation, either directly or via a margin group: - QMargins newMargins = mMargins; - QList allMarginSides = QList() << QCP::msLeft << QCP::msRight << QCP::msTop << QCP::msBottom; - foreach (QCP::MarginSide side, allMarginSides) - { - if (mAutoMargins.testFlag(side)) // this side's margin shall be calculated automatically - { - if (mMarginGroups.contains(side)) - QCP::setMarginValue(newMargins, side, mMarginGroups[side]->commonMargin(side)); // this side is part of a margin group, so get the margin value from that group - else - QCP::setMarginValue(newMargins, side, calculateAutoMargin(side)); // this side is not part of a group, so calculate the value directly - // apply minimum margin restrictions: - if (QCP::getMarginValue(newMargins, side) < QCP::getMarginValue(mMinimumMargins, side)) - QCP::setMarginValue(newMargins, side, QCP::getMarginValue(mMinimumMargins, side)); + if (phase == upMargins) { + if (mAutoMargins != QCP::msNone) { + // set the margins of this layout element according to automatic margin calculation, either directly or via a margin group: + QMargins newMargins = mMargins; + QList allMarginSides = QList() << QCP::msLeft << QCP::msRight << QCP::msTop << QCP::msBottom; + foreach (QCP::MarginSide side, allMarginSides) { + if (mAutoMargins.testFlag(side)) { // this side's margin shall be calculated automatically + if (mMarginGroups.contains(side)) { + QCP::setMarginValue(newMargins, side, mMarginGroups[side]->commonMargin(side)); // this side is part of a margin group, so get the margin value from that group + } else { + QCP::setMarginValue(newMargins, side, calculateAutoMargin(side)); // this side is not part of a group, so calculate the value directly + } + // apply minimum margin restrictions: + if (QCP::getMarginValue(newMargins, side) < QCP::getMarginValue(mMinimumMargins, side)) { + QCP::setMarginValue(newMargins, side, QCP::getMarginValue(mMinimumMargins, side)); + } + } + } + setMargins(newMargins); } - } - setMargins(newMargins); } - } } /*! Returns the minimum size this layout element (the inner \ref rect) may be compressed to. - + if a minimum size (\ref setMinimumSize) was not set manually, parent layouts consult this function to determine the minimum allowed size of this layout element. (A manual minimum size is considered set if it is non-zero.) */ QSize QCPLayoutElement::minimumSizeHint() const { - return mMinimumSize; + return mMinimumSize; } /*! Returns the maximum size this layout element (the inner \ref rect) may be expanded to. - + if a maximum size (\ref setMaximumSize) was not set manually, parent layouts consult this function to determine the maximum allowed size of this layout element. (A manual maximum size is considered set if it is smaller than Qt's QWIDGETSIZE_MAX.) */ QSize QCPLayoutElement::maximumSizeHint() const { - return mMaximumSize; + return mMaximumSize; } /*! Returns a list of all child elements in this layout element. If \a recursive is true, all sub-child elements are included in the list, too. - + \warning There may be entries with value 0 in the returned list. (For example, QCPLayoutGrid may have empty cells which yield 0 at the respective index.) */ -QList QCPLayoutElement::elements(bool recursive) const +QList QCPLayoutElement::elements(bool recursive) const { - Q_UNUSED(recursive) - return QList(); + Q_UNUSED(recursive) + return QList(); } /*! @@ -1984,58 +1982,58 @@ QList QCPLayoutElement::elements(bool recursive) const rect, this method returns a value corresponding to 0.99 times the parent plot's selection tolerance. However, layout elements are not selectable by default. So if \a onlySelectable is true, -1.0 is returned. - + See \ref QCPLayerable::selectTest for a general explanation of this virtual method. - + QCPLayoutElement subclasses may reimplement this method to provide more specific selection test behaviour. */ double QCPLayoutElement::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { - Q_UNUSED(details) - - if (onlySelectable) - return -1; - - if (QRectF(mOuterRect).contains(pos)) - { - if (mParentPlot) - return mParentPlot->selectionTolerance()*0.99; - else - { - qDebug() << Q_FUNC_INFO << "parent plot not defined"; - return -1; + Q_UNUSED(details) + + if (onlySelectable) { + return -1; + } + + if (QRectF(mOuterRect).contains(pos)) { + if (mParentPlot) { + return mParentPlot->selectionTolerance() * 0.99; + } else { + qDebug() << Q_FUNC_INFO << "parent plot not defined"; + return -1; + } + } else { + return -1; } - } else - return -1; } /*! \internal - + propagates the parent plot initialization to all child elements, by calling \ref QCPLayerable::initializeParentPlot on them. */ void QCPLayoutElement::parentPlotInitialized(QCustomPlot *parentPlot) { - foreach (QCPLayoutElement* el, elements(false)) - { - if (!el->parentPlot()) - el->initializeParentPlot(parentPlot); - } + foreach (QCPLayoutElement *el, elements(false)) { + if (!el->parentPlot()) { + el->initializeParentPlot(parentPlot); + } + } } /*! \internal - + Returns the margin size for this \a side. It is used if automatic margins is enabled for this \a side (see \ref setAutoMargins). If a minimum margin was set with \ref setMinimumMargins, the returned value will not be smaller than the specified minimum margin. - + The default implementation just returns the respective manual margin (\ref setMargins) or the minimum margin, whichever is larger. */ int QCPLayoutElement::calculateAutoMargin(QCP::MarginSide side) { - return qMax(QCP::getMarginValue(mMargins, side), QCP::getMarginValue(mMinimumMargins, side)); + return qMax(QCP::getMarginValue(mMargins, side), QCP::getMarginValue(mMinimumMargins, side)); } //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -2044,23 +2042,23 @@ int QCPLayoutElement::calculateAutoMargin(QCP::MarginSide side) /*! \class QCPLayout \brief The abstract base class for layouts - + This is an abstract base class for layout elements whose main purpose is to define the position and size of other child layout elements. In most cases, layouts don't draw anything themselves (but there are exceptions to this, e.g. QCPLegend). - + QCPLayout derives from QCPLayoutElement, and thus can itself be nested in other layouts. - + QCPLayout introduces a common interface for accessing and manipulating the child elements. Those functions are most notably \ref elementCount, \ref elementAt, \ref takeAt, \ref take, \ref simplify, \ref removeAt, \ref remove and \ref clear. Individual subclasses may add more functions to this interface which are more specialized to the form of the layout. For example, \ref QCPLayoutGrid adds functions that take row and column indices to access cells of the layout grid more conveniently. - + Since this is an abstract base class, you can't instantiate it directly. Rather use one of its subclasses like QCPLayoutGrid or QCPLayoutInset. - + For a general introduction to the layout system, see the dedicated documentation page \ref thelayoutsystem "The Layout System". */ @@ -2068,44 +2066,44 @@ int QCPLayoutElement::calculateAutoMargin(QCP::MarginSide side) /* start documentation of pure virtual functions */ /*! \fn virtual int QCPLayout::elementCount() const = 0 - + Returns the number of elements/cells in the layout. - + \see elements, elementAt */ /*! \fn virtual QCPLayoutElement* QCPLayout::elementAt(int index) const = 0 - + Returns the element in the cell with the given \a index. If \a index is invalid, returns 0. - + Note that even if \a index is valid, the respective cell may be empty in some layouts (e.g. QCPLayoutGrid), so this function may return 0 in those cases. You may use this function to check whether a cell is empty or not. - + \see elements, elementCount, takeAt */ /*! \fn virtual QCPLayoutElement* QCPLayout::takeAt(int index) = 0 - + Removes the element with the given \a index from the layout and returns it. - + If the \a index is invalid or the cell with that index is empty, returns 0. - + Note that some layouts don't remove the respective cell right away but leave an empty cell after successful removal of the layout element. To collapse empty cells, use \ref simplify. - + \see elementAt, take */ /*! \fn virtual bool QCPLayout::take(QCPLayoutElement* element) = 0 - + Removes the specified \a element from the layout and returns true on success. - + If the \a element isn't in this layout, returns false. - + Note that some layouts don't remove the respective cell right away but leave an empty cell after successful removal of the layout element. To collapse empty cells, use \ref simplify. - + \see takeAt */ @@ -2122,53 +2120,54 @@ QCPLayout::QCPLayout() /*! First calls the QCPLayoutElement::update base class implementation to update the margins on this layout. - + Then calls \ref updateLayout which subclasses reimplement to reposition and resize their cells. - + Finally, \ref update is called on all child elements. */ void QCPLayout::update(UpdatePhase phase) { - QCPLayoutElement::update(phase); - - // set child element rects according to layout: - if (phase == upLayout) - updateLayout(); - - // propagate update call to child elements: - const int elCount = elementCount(); - for (int i=0; iupdate(phase); - } + QCPLayoutElement::update(phase); + + // set child element rects according to layout: + if (phase == upLayout) { + updateLayout(); + } + + // propagate update call to child elements: + const int elCount = elementCount(); + for (int i = 0; i < elCount; ++i) { + if (QCPLayoutElement *el = elementAt(i)) { + el->update(phase); + } + } } /* inherits documentation from base class */ -QList QCPLayout::elements(bool recursive) const +QList QCPLayout::elements(bool recursive) const { - const int c = elementCount(); - QList result; + const int c = elementCount(); + QList result; #if QT_VERSION >= QT_VERSION_CHECK(4, 7, 0) - result.reserve(c); + result.reserve(c); #endif - for (int i=0; ielements(recursive); + for (int i = 0; i < c; ++i) { + result.append(elementAt(i)); } - } - return result; + if (recursive) { + for (int i = 0; i < c; ++i) { + if (result.at(i)) { + result << result.at(i)->elements(recursive); + } + } + } + return result; } /*! Simplifies the layout by collapsing empty cells. The exact behavior depends on subclasses, the default implementation does nothing. - + Not all layouts need simplification. For example, QCPLayoutInset doesn't use explicit simplification while QCPLayoutGrid does. */ @@ -2179,64 +2178,64 @@ void QCPLayout::simplify() /*! Removes and deletes the element at the provided \a index. Returns true on success. If \a index is invalid or points to an empty cell, returns false. - + This function internally uses \ref takeAt to remove the element from the layout and then deletes the returned element. Note that some layouts don't remove the respective cell right away but leave an empty cell after successful removal of the layout element. To collapse empty cells, use \ref simplify. - + \see remove, takeAt */ bool QCPLayout::removeAt(int index) { - if (QCPLayoutElement *el = takeAt(index)) - { - delete el; - return true; - } else - return false; + if (QCPLayoutElement *el = takeAt(index)) { + delete el; + return true; + } else { + return false; + } } /*! Removes and deletes the provided \a element. Returns true on success. If \a element is not in the layout, returns false. - + This function internally uses \ref takeAt to remove the element from the layout and then deletes the element. Note that some layouts don't remove the respective cell right away but leave an empty cell after successful removal of the layout element. To collapse empty cells, use \ref simplify. - + \see removeAt, take */ bool QCPLayout::remove(QCPLayoutElement *element) { - if (take(element)) - { - delete element; - return true; - } else - return false; + if (take(element)) { + delete element; + return true; + } else { + return false; + } } /*! Removes and deletes all layout elements in this layout. Finally calls \ref simplify to make sure all empty cells are collapsed. - + \see remove, removeAt */ void QCPLayout::clear() { - for (int i=elementCount()-1; i>=0; --i) - { - if (elementAt(i)) - removeAt(i); - } - simplify(); + for (int i = elementCount() - 1; i >= 0; --i) { + if (elementAt(i)) { + removeAt(i); + } + } + simplify(); } /*! Subclasses call this method to report changed (minimum/maximum) size constraints. - + If the parent of this layout is again a QCPLayout, forwards the call to the parent's \ref sizeConstraintsChanged. If the parent is a QWidget (i.e. is the \ref QCustomPlot::plotLayout of QCustomPlot), calls QWidget::updateGeometry, so if the QCustomPlot widget is inside a Qt QLayout, @@ -2244,22 +2243,23 @@ void QCPLayout::clear() */ void QCPLayout::sizeConstraintsChanged() const { - if (QWidget *w = qobject_cast(parent())) - w->updateGeometry(); - else if (QCPLayout *l = qobject_cast(parent())) - l->sizeConstraintsChanged(); + if (QWidget *w = qobject_cast(parent())) { + w->updateGeometry(); + } else if (QCPLayout *l = qobject_cast(parent())) { + l->sizeConstraintsChanged(); + } } /*! \internal - + Subclasses reimplement this method to update the position and sizes of the child elements/cells via calling their \ref QCPLayoutElement::setOuterRect. The default implementation does nothing. - + The geometry used as a reference is the inner \ref rect of this layout. Child elements should stay within that rect. - + \ref getSectionSizes may help with the reimplementation of this function. - + \see update */ void QCPLayout::updateLayout() @@ -2268,192 +2268,190 @@ void QCPLayout::updateLayout() /*! \internal - + Associates \a el with this layout. This is done by setting the \ref QCPLayoutElement::layout, the \ref QCPLayerable::parentLayerable and the QObject parent to this layout. - + Further, if \a el didn't previously have a parent plot, calls \ref QCPLayerable::initializeParentPlot on \a el to set the paret plot. - + This method is used by subclass specific methods that add elements to the layout. Note that this method only changes properties in \a el. The removal from the old layout and the insertion into the new layout must be done additionally. */ void QCPLayout::adoptElement(QCPLayoutElement *el) { - if (el) - { - el->mParentLayout = this; - el->setParentLayerable(this); - el->setParent(this); - if (!el->parentPlot()) - el->initializeParentPlot(mParentPlot); - } else - qDebug() << Q_FUNC_INFO << "Null element passed"; + if (el) { + el->mParentLayout = this; + el->setParentLayerable(this); + el->setParent(this); + if (!el->parentPlot()) { + el->initializeParentPlot(mParentPlot); + } + } else { + qDebug() << Q_FUNC_INFO << "Null element passed"; + } } /*! \internal - + Disassociates \a el from this layout. This is done by setting the \ref QCPLayoutElement::layout and the \ref QCPLayerable::parentLayerable to zero. The QObject parent is set to the parent QCustomPlot. - + This method is used by subclass specific methods that remove elements from the layout (e.g. \ref take or \ref takeAt). Note that this method only changes properties in \a el. The removal from the old layout must be done additionally. */ void QCPLayout::releaseElement(QCPLayoutElement *el) { - if (el) - { - el->mParentLayout = 0; - el->setParentLayerable(0); - el->setParent(mParentPlot); - // Note: Don't initializeParentPlot(0) here, because layout element will stay in same parent plot - } else - qDebug() << Q_FUNC_INFO << "Null element passed"; + if (el) { + el->mParentLayout = 0; + el->setParentLayerable(0); + el->setParent(mParentPlot); + // Note: Don't initializeParentPlot(0) here, because layout element will stay in same parent plot + } else { + qDebug() << Q_FUNC_INFO << "Null element passed"; + } } /*! \internal - + This is a helper function for the implementation of \ref updateLayout in subclasses. - + It calculates the sizes of one-dimensional sections with provided constraints on maximum section sizes, minimum section sizes, relative stretch factors and the final total size of all sections. - + The QVector entries refer to the sections. Thus all QVectors must have the same size. - + \a maxSizes gives the maximum allowed size of each section. If there shall be no maximum size imposed, set all vector values to Qt's QWIDGETSIZE_MAX. - + \a minSizes gives the minimum allowed size of each section. If there shall be no minimum size imposed, set all vector values to zero. If the \a minSizes entries add up to a value greater than \a totalSize, sections will be scaled smaller than the proposed minimum sizes. (In other words, not exceeding the allowed total size is taken to be more important than not going below minimum section sizes.) - + \a stretchFactors give the relative proportions of the sections to each other. If all sections shall be scaled equally, set all values equal. If the first section shall be double the size of each individual other section, set the first number of \a stretchFactors to double the value of the other individual values (e.g. {2, 1, 1, 1}). - + \a totalSize is the value that the final section sizes will add up to. Due to rounding, the actual sum may differ slightly. If you want the section sizes to sum up to exactly that value, you could distribute the remaining difference on the sections. - + The return value is a QVector containing the section sizes. */ QVector QCPLayout::getSectionSizes(QVector maxSizes, QVector minSizes, QVector stretchFactors, int totalSize) const { - if (maxSizes.size() != minSizes.size() || minSizes.size() != stretchFactors.size()) - { - qDebug() << Q_FUNC_INFO << "Passed vector sizes aren't equal:" << maxSizes << minSizes << stretchFactors; - return QVector(); - } - if (stretchFactors.isEmpty()) - return QVector(); - int sectionCount = stretchFactors.size(); - QVector sectionSizes(sectionCount); - // if provided total size is forced smaller than total minimum size, ignore minimum sizes (squeeze sections): - int minSizeSum = 0; - for (int i=0; i(); } - } - - QList minimumLockedSections; - QList unfinishedSections; - for (int i=0; i(); + } + int sectionCount = stretchFactors.size(); + QVector sectionSizes(sectionCount); + // if provided total size is forced smaller than total minimum size, ignore minimum sizes (squeeze sections): + int minSizeSum = 0; + for (int i = 0; i < sectionCount; ++i) { + minSizeSum += minSizes.at(i); + } + if (totalSize < minSizeSum) { + // new stretch factors are minimum sizes and minimum sizes are set to zero: + for (int i = 0; i < sectionCount; ++i) { + stretchFactors[i] = minSizes.at(i); + minSizes[i] = 0; } - } - // check if that maximum is actually within the bounds of the total size (i.e. can we stretch all remaining sections so far that the found section - // actually hits its maximum, without exceeding the total size when we add up all sections) - double stretchFactorSum = 0; - for (int i=0; i minimumLockedSections; + QList unfinishedSections; + for (int i = 0; i < sectionCount; ++i) { + unfinishedSections.append(i); + } + double freeSize = totalSize; + + int outerIterations = 0; + while (!unfinishedSections.isEmpty() && outerIterations < sectionCount * 2) { // the iteration check ist just a failsafe in case something really strange happens + ++outerIterations; + int innerIterations = 0; + while (!unfinishedSections.isEmpty() && innerIterations < sectionCount * 2) { // the iteration check ist just a failsafe in case something really strange happens + ++innerIterations; + // find section that hits its maximum next: + int nextId = -1; + double nextMax = 1e12; + for (int i = 0; i < unfinishedSections.size(); ++i) { + int secId = unfinishedSections.at(i); + double hitsMaxAt = (maxSizes.at(secId) - sectionSizes.at(secId)) / stretchFactors.at(secId); + if (hitsMaxAt < nextMax) { + nextMax = hitsMaxAt; + nextId = secId; + } + } + // check if that maximum is actually within the bounds of the total size (i.e. can we stretch all remaining sections so far that the found section + // actually hits its maximum, without exceeding the total size when we add up all sections) + double stretchFactorSum = 0; + for (int i = 0; i < unfinishedSections.size(); ++i) { + stretchFactorSum += stretchFactors.at(unfinishedSections.at(i)); + } + double nextMaxLimit = freeSize / stretchFactorSum; + if (nextMax < nextMaxLimit) { // next maximum is actually hit, move forward to that point and fix the size of that section + for (int i = 0; i < unfinishedSections.size(); ++i) { + sectionSizes[unfinishedSections.at(i)] += nextMax * stretchFactors.at(unfinishedSections.at(i)); // increment all sections + freeSize -= nextMax * stretchFactors.at(unfinishedSections.at(i)); + } + unfinishedSections.removeOne(nextId); // exclude the section that is now at maximum from further changes + } else { // next maximum isn't hit, just distribute rest of free space on remaining sections + for (int i = 0; i < unfinishedSections.size(); ++i) { + sectionSizes[unfinishedSections.at(i)] += nextMaxLimit * stretchFactors.at(unfinishedSections.at(i)); // increment all sections + } + unfinishedSections.clear(); + } + } + if (innerIterations == sectionCount * 2) { + qDebug() << Q_FUNC_INFO << "Exceeded maximum expected inner iteration count, layouting aborted. Input was:" << maxSizes << minSizes << stretchFactors << totalSize; + } + + // now check whether the resulting section sizes violate minimum restrictions: + bool foundMinimumViolation = false; + for (int i = 0; i < sectionSizes.size(); ++i) { + if (minimumLockedSections.contains(i)) { + continue; + } + if (sectionSizes.at(i) < minSizes.at(i)) { // section violates minimum + sectionSizes[i] = minSizes.at(i); // set it to minimum + foundMinimumViolation = true; // make sure we repeat the whole optimization process + minimumLockedSections.append(i); + } + } + if (foundMinimumViolation) { + freeSize = totalSize; + for (int i = 0; i < sectionCount; ++i) { + if (!minimumLockedSections.contains(i)) { // only put sections that haven't hit their minimum back into the pool + unfinishedSections.append(i); + } else { + freeSize -= sectionSizes.at(i); // remove size of minimum locked sections from available space in next round + } + } + // reset all section sizes to zero that are in unfinished sections (all others have been set to their minimum): + for (int i = 0; i < unfinishedSections.size(); ++i) { + sectionSizes[unfinishedSections.at(i)] = 0; + } } - unfinishedSections.removeOne(nextId); // exclude the section that is now at maximum from further changes - } else // next maximum isn't hit, just distribute rest of free space on remaining sections - { - for (int i=0; i result(sectionCount); + for (int i = 0; i < sectionCount; ++i) { + result[i] = qRound(sectionSizes.at(i)); } - } - if (outerIterations == sectionCount*2) - qDebug() << Q_FUNC_INFO << "Exceeded maximum expected outer iteration count, layouting aborted. Input was:" << maxSizes << minSizes << stretchFactors << totalSize; - - QVector result(sectionCount); - for (int i=0; i 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. - + Row and column insertion can be performed with \ref insertRow and \ref insertColumn. */ @@ -2481,418 +2479,419 @@ QVector QCPLayout::getSectionSizes(QVector maxSizes, QVector minS Creates an instance of QCPLayoutGrid and sets default values. */ QCPLayoutGrid::QCPLayoutGrid() : - mColumnSpacing(5), - mRowSpacing(5) + mColumnSpacing(5), + mRowSpacing(5) { } QCPLayoutGrid::~QCPLayoutGrid() { - // clear all child layout elements. This is important because only the specific layouts know how - // to handle removing elements (clear calls virtual removeAt method to do that). - clear(); + // clear all child layout elements. This is important because only the specific layouts know how + // to handle removing elements (clear calls virtual removeAt method to do that). + clear(); } /*! Returns the element in the cell in \a row and \a column. - + Returns 0 if either the row/column is invalid or if the cell is empty. In those cases, a qDebug message is printed. To check whether a cell exists and isn't empty, use \ref hasElement. - + \see addElement, hasElement */ QCPLayoutElement *QCPLayoutGrid::element(int row, int column) const { - if (row >= 0 && row < mElements.size()) - { - if (column >= 0 && column < mElements.first().size()) - { - if (QCPLayoutElement *result = mElements.at(row).at(column)) - return result; - else - qDebug() << Q_FUNC_INFO << "Requested cell is empty. Row:" << row << "Column:" << column; - } else - qDebug() << Q_FUNC_INFO << "Invalid column. Row:" << row << "Column:" << column; - } else - qDebug() << Q_FUNC_INFO << "Invalid row. Row:" << row << "Column:" << column; - return 0; + if (row >= 0 && row < mElements.size()) { + if (column >= 0 && column < mElements.first().size()) { + if (QCPLayoutElement *result = mElements.at(row).at(column)) { + return result; + } else { + qDebug() << Q_FUNC_INFO << "Requested cell is empty. Row:" << row << "Column:" << column; + } + } else { + qDebug() << Q_FUNC_INFO << "Invalid column. Row:" << row << "Column:" << column; + } + } else { + qDebug() << Q_FUNC_INFO << "Invalid row. Row:" << row << "Column:" << column; + } + return 0; } /*! Returns the number of rows in the layout. - + \see columnCount */ int QCPLayoutGrid::rowCount() const { - return mElements.size(); + 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; + if (mElements.size() > 0) { + return mElements.first().size(); + } else { + return 0; + } } /*! 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. - + \see element, hasElement, take, remove */ bool QCPLayoutGrid::addElement(int row, int column, QCPLayoutElement *element) { - if (element) - { - 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; - adoptElement(element); - return true; - } else - qDebug() << Q_FUNC_INFO << "There is already an element in the specified row/column:" << row << column; - } else - qDebug() << Q_FUNC_INFO << "Can't add null element to row/column:" << row << column; - return false; + if (element) { + 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; + adoptElement(element); + return true; + } else { + qDebug() << Q_FUNC_INFO << "There is already an element in the specified row/column:" << row << column; + } + } else { + qDebug() << Q_FUNC_INFO << "Can't add null element to row/column:" << row << column; + } + return false; } /*! Returns whether the cell at \a row and \a column exists and contains a valid element, i.e. isn't empty. - + \see element */ bool QCPLayoutGrid::hasElement(int row, int column) { - if (row >= 0 && row < rowCount() && column >= 0 && column < columnCount()) - return mElements.at(row).at(column); - else - return false; + if (row >= 0 && row < rowCount() && column >= 0 && column < columnCount()) { + return mElements.at(row).at(column); + } else { + return false; + } } /*! Sets the stretch \a factor of \a column. - + Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond their minimum and maximum widths/heights (\ref QCPLayoutElement::setMinimumSize, \ref QCPLayoutElement::setMaximumSize), regardless of the stretch factor. - + The default stretch factor of newly created rows/columns is 1. - + \see setColumnStretchFactors, setRowStretchFactor */ void QCPLayoutGrid::setColumnStretchFactor(int column, double factor) { - if (column >= 0 && column < columnCount()) - { - if (factor > 0) - mColumnStretchFactors[column] = factor; - else - qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << factor; - } else - qDebug() << Q_FUNC_INFO << "Invalid column:" << column; + if (column >= 0 && column < columnCount()) { + if (factor > 0) { + mColumnStretchFactors[column] = factor; + } else { + qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << factor; + } + } else { + qDebug() << Q_FUNC_INFO << "Invalid column:" << column; + } } /*! Sets the stretch \a factors of all columns. \a factors must have the size \ref columnCount. - + Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond their minimum and maximum widths/heights (\ref QCPLayoutElement::setMinimumSize, \ref QCPLayoutElement::setMaximumSize), regardless of the stretch factor. - + The default stretch factor of newly created rows/columns is 1. - + \see setColumnStretchFactor, setRowStretchFactors */ void QCPLayoutGrid::setColumnStretchFactors(const QList &factors) { - if (factors.size() == mColumnStretchFactors.size()) - { - mColumnStretchFactors = factors; - for (int i=0; i= 0 && row < rowCount()) - { - if (factor > 0) - mRowStretchFactors[row] = factor; - else - qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << factor; - } else - qDebug() << Q_FUNC_INFO << "Invalid row:" << row; + if (row >= 0 && row < rowCount()) { + if (factor > 0) { + mRowStretchFactors[row] = factor; + } else { + qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << factor; + } + } else { + qDebug() << Q_FUNC_INFO << "Invalid row:" << row; + } } /*! Sets the stretch \a factors of all rows. \a factors must have the size \ref rowCount. - + Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond their minimum and maximum widths/heights (\ref QCPLayoutElement::setMinimumSize, \ref QCPLayoutElement::setMaximumSize), regardless of the stretch factor. - + The default stretch factor of newly created rows/columns is 1. - + \see setRowStretchFactor, setColumnStretchFactors */ void QCPLayoutGrid::setRowStretchFactors(const QList &factors) { - if (factors.size() == mRowStretchFactors.size()) - { - mRowStretchFactors = factors; - for (int i=0; i()); - mRowStretchFactors.append(1); - } - // go through rows and expand columns as necessary: - int newColCount = qMax(columnCount(), newColumnCount); - for (int i=0; i()); + mRowStretchFactors.append(1); + } + // go through rows and expand columns as necessary: + int newColCount = qMax(columnCount(), newColumnCount); + for (int i = 0; i < rowCount(); ++i) { + while (mElements.at(i).size() < newColCount) { + mElements[i].append(0); + } + } + while (mColumnStretchFactors.size() < newColCount) { + mColumnStretchFactors.append(1); + } } /*! Inserts a new row with empty cells at the row index \a newIndex. Valid values for \a newIndex range from 0 (inserts a row at the top) to \a rowCount (appends a row at the bottom). - + \see insertColumn */ void QCPLayoutGrid::insertRow(int newIndex) { - if (mElements.isEmpty() || mElements.first().isEmpty()) // if grid is completely empty, add first cell - { - expandTo(1, 1); - return; - } - - if (newIndex < 0) - newIndex = 0; - if (newIndex > rowCount()) - newIndex = rowCount(); - - mRowStretchFactors.insert(newIndex, 1); - QList newRow; - for (int col=0; col rowCount()) { + newIndex = rowCount(); + } + + mRowStretchFactors.insert(newIndex, 1); + QList newRow; + for (int col = 0; col < columnCount(); ++col) { + newRow.append((QCPLayoutElement *)0); + } + mElements.insert(newIndex, newRow); } /*! Inserts a new column with empty cells at the column index \a newIndex. Valid values for \a newIndex range from 0 (inserts a row at the left) to \a rowCount (appends a row at the right). - + \see insertRow */ void QCPLayoutGrid::insertColumn(int newIndex) { - if (mElements.isEmpty() || mElements.first().isEmpty()) // if grid is completely empty, add first cell - { - expandTo(1, 1); - return; - } - - if (newIndex < 0) - newIndex = 0; - if (newIndex > columnCount()) - newIndex = columnCount(); - - mColumnStretchFactors.insert(newIndex, 1); - for (int row=0; row columnCount()) { + newIndex = columnCount(); + } + + mColumnStretchFactors.insert(newIndex, 1); + for (int row = 0; row < rowCount(); ++row) { + mElements[row].insert(newIndex, (QCPLayoutElement *)0); + } } /* inherits documentation from base class */ void QCPLayoutGrid::updateLayout() { - QVector minColWidths, minRowHeights, maxColWidths, maxRowHeights; - getMinimumRowColSizes(&minColWidths, &minRowHeights); - getMaximumRowColSizes(&maxColWidths, &maxRowHeights); - - int totalRowSpacing = (rowCount()-1) * mRowSpacing; - int totalColSpacing = (columnCount()-1) * mColumnSpacing; - QVector colWidths = getSectionSizes(maxColWidths, minColWidths, mColumnStretchFactors.toVector(), mRect.width()-totalColSpacing); - QVector rowHeights = getSectionSizes(maxRowHeights, minRowHeights, mRowStretchFactors.toVector(), mRect.height()-totalRowSpacing); - - // go through cells and set rects accordingly: - int yOffset = mRect.top(); - for (int row=0; row 0) - yOffset += rowHeights.at(row-1)+mRowSpacing; - int xOffset = mRect.left(); - for (int col=0; col 0) - xOffset += colWidths.at(col-1)+mColumnSpacing; - if (mElements.at(row).at(col)) - mElements.at(row).at(col)->setOuterRect(QRect(xOffset, yOffset, colWidths.at(col), rowHeights.at(row))); + QVector minColWidths, minRowHeights, maxColWidths, maxRowHeights; + getMinimumRowColSizes(&minColWidths, &minRowHeights); + getMaximumRowColSizes(&maxColWidths, &maxRowHeights); + + int totalRowSpacing = (rowCount() - 1) * mRowSpacing; + int totalColSpacing = (columnCount() - 1) * mColumnSpacing; + QVector colWidths = getSectionSizes(maxColWidths, minColWidths, mColumnStretchFactors.toVector(), mRect.width() - totalColSpacing); + QVector rowHeights = getSectionSizes(maxRowHeights, minRowHeights, mRowStretchFactors.toVector(), mRect.height() - totalRowSpacing); + + // go through cells and set rects accordingly: + int yOffset = mRect.top(); + for (int row = 0; row < rowCount(); ++row) { + if (row > 0) { + yOffset += rowHeights.at(row - 1) + mRowSpacing; + } + int xOffset = mRect.left(); + for (int col = 0; col < columnCount(); ++col) { + if (col > 0) { + xOffset += colWidths.at(col - 1) + mColumnSpacing; + } + if (mElements.at(row).at(col)) { + mElements.at(row).at(col)->setOuterRect(QRect(xOffset, yOffset, colWidths.at(col), rowHeights.at(row))); + } + } } - } } /* inherits documentation from base class */ int QCPLayoutGrid::elementCount() const { - return rowCount()*columnCount(); + return rowCount() * columnCount(); } /* inherits documentation from base class */ QCPLayoutElement *QCPLayoutGrid::elementAt(int index) const { - if (index >= 0 && index < elementCount()) - return mElements.at(index / columnCount()).at(index % columnCount()); - else - return 0; + if (index >= 0 && index < elementCount()) { + return mElements.at(index / columnCount()).at(index % columnCount()); + } else { + return 0; + } } /* inherits documentation from base class */ QCPLayoutElement *QCPLayoutGrid::takeAt(int index) { - if (QCPLayoutElement *el = elementAt(index)) - { - releaseElement(el); - mElements[index / columnCount()][index % columnCount()] = 0; - return el; - } else - { - qDebug() << Q_FUNC_INFO << "Attempt to take invalid index:" << index; - return 0; - } + if (QCPLayoutElement *el = elementAt(index)) { + releaseElement(el); + mElements[index / columnCount()][index % columnCount()] = 0; + return el; + } else { + qDebug() << Q_FUNC_INFO << "Attempt to take invalid index:" << index; + return 0; + } } /* inherits documentation from base class */ bool QCPLayoutGrid::take(QCPLayoutElement *element) { - if (element) - { - for (int i=0; i QCPLayoutGrid::elements(bool recursive) const +QList QCPLayoutGrid::elements(bool recursive) const { - QList result; - int colC = columnCount(); - int rowC = rowCount(); + QList result; + int colC = columnCount(); + int rowC = rowCount(); #if QT_VERSION >= QT_VERSION_CHECK(4, 7, 0) - result.reserve(colC*rowC); + result.reserve(colC * rowC); #endif - for (int row=0; rowelements(recursive); + if (recursive) { + int c = result.size(); + for (int i = 0; i < c; ++i) { + if (result.at(i)) { + result << result.at(i)->elements(recursive); + } + } } - } - return result; + return result; } /*! @@ -2900,145 +2899,141 @@ QList QCPLayoutGrid::elements(bool recursive) const */ void QCPLayoutGrid::simplify() { - // remove rows with only empty cells: - for (int row=rowCount()-1; row>=0; --row) - { - bool hasElements = false; - for (int col=0; col= 0; --row) { + bool hasElements = false; + for (int col = 0; col < columnCount(); ++col) { + if (mElements.at(row).at(col)) { + hasElements = true; + break; + } + } + if (!hasElements) { + mRowStretchFactors.removeAt(row); + mElements.removeAt(row); + if (mElements.isEmpty()) { // removed last element, also remove stretch factor (wouldn't happen below because also columnCount changed to 0 now) + mColumnStretchFactors.clear(); + } + } } - if (!hasElements) - { - mRowStretchFactors.removeAt(row); - mElements.removeAt(row); - if (mElements.isEmpty()) // removed last element, also remove stretch factor (wouldn't happen below because also columnCount changed to 0 now) - mColumnStretchFactors.clear(); + + // remove columns with only empty cells: + for (int col = columnCount() - 1; col >= 0; --col) { + bool hasElements = false; + for (int row = 0; row < rowCount(); ++row) { + if (mElements.at(row).at(col)) { + hasElements = true; + break; + } + } + if (!hasElements) { + mColumnStretchFactors.removeAt(col); + for (int row = 0; row < rowCount(); ++row) { + mElements[row].removeAt(col); + } + } } - } - - // remove columns with only empty cells: - for (int col=columnCount()-1; col>=0; --col) - { - bool hasElements = false; - for (int row=0; row minColWidths, minRowHeights; - getMinimumRowColSizes(&minColWidths, &minRowHeights); - QSize result(0, 0); - for (int i=0; i minColWidths, minRowHeights; + getMinimumRowColSizes(&minColWidths, &minRowHeights); + QSize result(0, 0); + for (int i = 0; i < minColWidths.size(); ++i) { + result.rwidth() += minColWidths.at(i); + } + for (int i = 0; i < minRowHeights.size(); ++i) { + result.rheight() += minRowHeights.at(i); + } + result.rwidth() += qMax(0, columnCount() - 1) * mColumnSpacing + mMargins.left() + mMargins.right(); + result.rheight() += qMax(0, rowCount() - 1) * mRowSpacing + mMargins.top() + mMargins.bottom(); + return result; } /* inherits documentation from base class */ QSize QCPLayoutGrid::maximumSizeHint() const { - QVector maxColWidths, maxRowHeights; - getMaximumRowColSizes(&maxColWidths, &maxRowHeights); - - QSize result(0, 0); - for (int i=0; i maxColWidths, maxRowHeights; + getMaximumRowColSizes(&maxColWidths, &maxRowHeights); + + QSize result(0, 0); + for (int i = 0; i < maxColWidths.size(); ++i) { + result.setWidth(qMin(result.width() + maxColWidths.at(i), QWIDGETSIZE_MAX)); + } + for (int i = 0; i < maxRowHeights.size(); ++i) { + result.setHeight(qMin(result.height() + maxRowHeights.at(i), QWIDGETSIZE_MAX)); + } + result.rwidth() += qMax(0, columnCount() - 1) * mColumnSpacing + mMargins.left() + mMargins.right(); + result.rheight() += qMax(0, rowCount() - 1) * mRowSpacing + mMargins.top() + mMargins.bottom(); + return result; } /*! \internal - + Places the minimum column widths and row heights into \a minColWidths and \a minRowHeights respectively. - + The minimum height of a row is the largest minimum height of any element in that row. The minimum width of a column is the largest minimum width of any element in that column. - + This is a helper function for \ref updateLayout. - + \see getMaximumRowColSizes */ void QCPLayoutGrid::getMinimumRowColSizes(QVector *minColWidths, QVector *minRowHeights) const { - *minColWidths = QVector(columnCount(), 0); - *minRowHeights = QVector(rowCount(), 0); - for (int row=0; rowminimumSizeHint(); - QSize min = mElements.at(row).at(col)->minimumSize(); - QSize final(min.width() > 0 ? min.width() : minHint.width(), min.height() > 0 ? min.height() : minHint.height()); - if (minColWidths->at(col) < final.width()) - (*minColWidths)[col] = final.width(); - if (minRowHeights->at(row) < final.height()) - (*minRowHeights)[row] = final.height(); - } + *minColWidths = QVector(columnCount(), 0); + *minRowHeights = QVector(rowCount(), 0); + for (int row = 0; row < rowCount(); ++row) { + for (int col = 0; col < columnCount(); ++col) { + if (mElements.at(row).at(col)) { + QSize minHint = mElements.at(row).at(col)->minimumSizeHint(); + QSize min = mElements.at(row).at(col)->minimumSize(); + QSize final(min.width() > 0 ? min.width() : minHint.width(), min.height() > 0 ? min.height() : minHint.height()); + if (minColWidths->at(col) < final.width()) { + (*minColWidths)[col] = final.width(); + } + if (minRowHeights->at(row) < final.height()) { + (*minRowHeights)[row] = final.height(); + } + } + } } - } } /*! \internal - + Places the maximum column widths and row heights into \a maxColWidths and \a maxRowHeights respectively. - + The maximum height of a row is the smallest maximum height of any element in that row. The maximum width of a column is the smallest maximum width of any element in that column. - + This is a helper function for \ref updateLayout. - + \see getMinimumRowColSizes */ void QCPLayoutGrid::getMaximumRowColSizes(QVector *maxColWidths, QVector *maxRowHeights) const { - *maxColWidths = QVector(columnCount(), QWIDGETSIZE_MAX); - *maxRowHeights = QVector(rowCount(), QWIDGETSIZE_MAX); - for (int row=0; rowmaximumSizeHint(); - QSize max = mElements.at(row).at(col)->maximumSize(); - QSize final(max.width() < QWIDGETSIZE_MAX ? max.width() : maxHint.width(), max.height() < QWIDGETSIZE_MAX ? max.height() : maxHint.height()); - if (maxColWidths->at(col) > final.width()) - (*maxColWidths)[col] = final.width(); - if (maxRowHeights->at(row) > final.height()) - (*maxRowHeights)[row] = final.height(); - } + *maxColWidths = QVector(columnCount(), QWIDGETSIZE_MAX); + *maxRowHeights = QVector(rowCount(), QWIDGETSIZE_MAX); + for (int row = 0; row < rowCount(); ++row) { + for (int col = 0; col < columnCount(); ++col) { + if (mElements.at(row).at(col)) { + QSize maxHint = mElements.at(row).at(col)->maximumSizeHint(); + QSize max = mElements.at(row).at(col)->maximumSize(); + QSize final(max.width() < QWIDGETSIZE_MAX ? max.width() : maxHint.width(), max.height() < QWIDGETSIZE_MAX ? max.height() : maxHint.height()); + if (maxColWidths->at(col) > final.width()) { + (*maxColWidths)[col] = final.width(); + } + if (maxRowHeights->at(row) > final.height()) { + (*maxRowHeights)[row] = final.height(); + } + } + } } - } } @@ -3047,7 +3042,7 @@ void QCPLayoutGrid::getMaximumRowColSizes(QVector *maxColWidths, QVector *maxColWidths, QVectorminimumSizeHint(); - QSize maxSizeHint = mElements.at(i)->maximumSizeHint(); - finalMinSize.setWidth(mElements.at(i)->minimumSize().width() > 0 ? mElements.at(i)->minimumSize().width() : minSizeHint.width()); - finalMinSize.setHeight(mElements.at(i)->minimumSize().height() > 0 ? mElements.at(i)->minimumSize().height() : minSizeHint.height()); - finalMaxSize.setWidth(mElements.at(i)->maximumSize().width() < QWIDGETSIZE_MAX ? mElements.at(i)->maximumSize().width() : maxSizeHint.width()); - finalMaxSize.setHeight(mElements.at(i)->maximumSize().height() < QWIDGETSIZE_MAX ? mElements.at(i)->maximumSize().height() : maxSizeHint.height()); - if (mInsetPlacement.at(i) == ipFree) - { - insetRect = QRect(rect().x()+rect().width()*mInsetRect.at(i).x(), - rect().y()+rect().height()*mInsetRect.at(i).y(), - rect().width()*mInsetRect.at(i).width(), - rect().height()*mInsetRect.at(i).height()); - if (insetRect.size().width() < finalMinSize.width()) - insetRect.setWidth(finalMinSize.width()); - if (insetRect.size().height() < finalMinSize.height()) - insetRect.setHeight(finalMinSize.height()); - if (insetRect.size().width() > finalMaxSize.width()) - insetRect.setWidth(finalMaxSize.width()); - if (insetRect.size().height() > finalMaxSize.height()) - insetRect.setHeight(finalMaxSize.height()); - } else if (mInsetPlacement.at(i) == ipBorderAligned) - { - insetRect.setSize(finalMinSize); - Qt::Alignment al = mInsetAlignment.at(i); - if (al.testFlag(Qt::AlignLeft)) insetRect.moveLeft(rect().x()); - else if (al.testFlag(Qt::AlignRight)) insetRect.moveRight(rect().x()+rect().width()); - else insetRect.moveLeft(rect().x()+rect().width()*0.5-finalMinSize.width()*0.5); // default to Qt::AlignHCenter - if (al.testFlag(Qt::AlignTop)) insetRect.moveTop(rect().y()); - else if (al.testFlag(Qt::AlignBottom)) insetRect.moveBottom(rect().y()+rect().height()); - else insetRect.moveTop(rect().y()+rect().height()*0.5-finalMinSize.height()*0.5); // default to Qt::AlignVCenter + for (int i = 0; i < mElements.size(); ++i) { + QRect insetRect; + QSize finalMinSize, finalMaxSize; + QSize minSizeHint = mElements.at(i)->minimumSizeHint(); + QSize maxSizeHint = mElements.at(i)->maximumSizeHint(); + finalMinSize.setWidth(mElements.at(i)->minimumSize().width() > 0 ? mElements.at(i)->minimumSize().width() : minSizeHint.width()); + finalMinSize.setHeight(mElements.at(i)->minimumSize().height() > 0 ? mElements.at(i)->minimumSize().height() : minSizeHint.height()); + finalMaxSize.setWidth(mElements.at(i)->maximumSize().width() < QWIDGETSIZE_MAX ? mElements.at(i)->maximumSize().width() : maxSizeHint.width()); + finalMaxSize.setHeight(mElements.at(i)->maximumSize().height() < QWIDGETSIZE_MAX ? mElements.at(i)->maximumSize().height() : maxSizeHint.height()); + if (mInsetPlacement.at(i) == ipFree) { + insetRect = QRect(rect().x() + rect().width() * mInsetRect.at(i).x(), + rect().y() + rect().height() * mInsetRect.at(i).y(), + rect().width() * mInsetRect.at(i).width(), + rect().height() * mInsetRect.at(i).height()); + if (insetRect.size().width() < finalMinSize.width()) { + insetRect.setWidth(finalMinSize.width()); + } + if (insetRect.size().height() < finalMinSize.height()) { + insetRect.setHeight(finalMinSize.height()); + } + if (insetRect.size().width() > finalMaxSize.width()) { + insetRect.setWidth(finalMaxSize.width()); + } + if (insetRect.size().height() > finalMaxSize.height()) { + insetRect.setHeight(finalMaxSize.height()); + } + } else if (mInsetPlacement.at(i) == ipBorderAligned) { + insetRect.setSize(finalMinSize); + Qt::Alignment al = mInsetAlignment.at(i); + if (al.testFlag(Qt::AlignLeft)) { + insetRect.moveLeft(rect().x()); + } else if (al.testFlag(Qt::AlignRight)) { + insetRect.moveRight(rect().x() + rect().width()); + } else { + insetRect.moveLeft(rect().x() + rect().width() * 0.5 - finalMinSize.width() * 0.5); // default to Qt::AlignHCenter + } + if (al.testFlag(Qt::AlignTop)) { + insetRect.moveTop(rect().y()); + } else if (al.testFlag(Qt::AlignBottom)) { + insetRect.moveBottom(rect().y() + rect().height()); + } else { + insetRect.moveTop(rect().y() + rect().height() * 0.5 - finalMinSize.height() * 0.5); // default to Qt::AlignVCenter + } + } + mElements.at(i)->setOuterRect(insetRect); } - mElements.at(i)->setOuterRect(insetRect); - } } /* inherits documentation from base class */ int QCPLayoutInset::elementCount() const { - return mElements.size(); + return mElements.size(); } /* inherits documentation from base class */ QCPLayoutElement *QCPLayoutInset::elementAt(int index) const { - if (index >= 0 && index < mElements.size()) - return mElements.at(index); - else - return 0; + if (index >= 0 && index < mElements.size()) { + return mElements.at(index); + } else { + return 0; + } } /* inherits documentation from base class */ QCPLayoutElement *QCPLayoutInset::takeAt(int index) { - if (QCPLayoutElement *el = elementAt(index)) - { - releaseElement(el); - mElements.removeAt(index); - mInsetPlacement.removeAt(index); - mInsetAlignment.removeAt(index); - mInsetRect.removeAt(index); - return el; - } else - { - qDebug() << Q_FUNC_INFO << "Attempt to take invalid index:" << index; - return 0; - } + if (QCPLayoutElement *el = elementAt(index)) { + releaseElement(el); + mElements.removeAt(index); + mInsetPlacement.removeAt(index); + mInsetAlignment.removeAt(index); + mInsetRect.removeAt(index); + return el; + } else { + qDebug() << Q_FUNC_INFO << "Attempt to take invalid index:" << index; + return 0; + } } /* inherits documentation from base class */ bool QCPLayoutInset::take(QCPLayoutElement *element) { - if (element) - { - for (int i=0; irealVisibility() && mElements.at(i)->selectTest(pos, onlySelectable) >= 0) { + return mParentPlot->selectionTolerance() * 0.99; + } + } return -1; - - for (int i=0; irealVisibility() && mElements.at(i)->selectTest(pos, onlySelectable) >= 0) - return mParentPlot->selectionTolerance()*0.99; - } - return -1; } /*! Adds the specified \a element to the layout as an inset aligned at the border (\ref setInsetAlignment is initialized with \ref ipBorderAligned). The alignment is set to \a alignment. - + \a alignment is an or combination of the following alignment flags: Qt::AlignLeft, Qt::AlignHCenter, Qt::AlighRight, Qt::AlignTop, Qt::AlignVCenter, Qt::AlignBottom. Any other alignment flags will be ignored. - + \see addElement(QCPLayoutElement *element, const QRectF &rect) */ void QCPLayoutInset::addElement(QCPLayoutElement *element, Qt::Alignment alignment) { - if (element) - { - if (element->layout()) // remove from old layout first - element->layout()->take(element); - mElements.append(element); - mInsetPlacement.append(ipBorderAligned); - mInsetAlignment.append(alignment); - mInsetRect.append(QRectF(0.6, 0.6, 0.4, 0.4)); - adoptElement(element); - } else - qDebug() << Q_FUNC_INFO << "Can't add null element"; + if (element) { + if (element->layout()) { // remove from old layout first + element->layout()->take(element); + } + mElements.append(element); + mInsetPlacement.append(ipBorderAligned); + mInsetAlignment.append(alignment); + mInsetRect.append(QRectF(0.6, 0.6, 0.4, 0.4)); + adoptElement(element); + } else { + qDebug() << Q_FUNC_INFO << "Can't add null element"; + } } /*! Adds the specified \a element to the layout as an inset with free positioning/sizing (\ref setInsetAlignment is initialized with \ref ipFree). The position and size is set to \a rect. - + \a rect is given in fractions of the whole inset layout rect. So an inset with rect (0, 0, 1, 1) will span the entire layout. An inset with rect (0.6, 0.1, 0.35, 0.35) will be in the top right corner of the layout, with 35% width and height of the parent layout. - + \see addElement(QCPLayoutElement *element, Qt::Alignment alignment) */ void QCPLayoutInset::addElement(QCPLayoutElement *element, const QRectF &rect) { - if (element) - { - if (element->layout()) // remove from old layout first - element->layout()->take(element); - mElements.append(element); - mInsetPlacement.append(ipFree); - mInsetAlignment.append(Qt::AlignRight|Qt::AlignTop); - mInsetRect.append(rect); - adoptElement(element); - } else - qDebug() << Q_FUNC_INFO << "Can't add null element"; + if (element) { + if (element->layout()) { // remove from old layout first + element->layout()->take(element); + } + mElements.append(element); + mInsetPlacement.append(ipFree); + mInsetAlignment.append(Qt::AlignRight | Qt::AlignTop); + mInsetRect.append(rect); + adoptElement(element); + } else { + qDebug() << Q_FUNC_INFO << "Can't add null element"; + } } @@ -3357,19 +3361,19 @@ void QCPLayoutInset::addElement(QCPLayoutElement *element, const QRectF &rect) /*! \class QCPLineEnding \brief Handles the different ending decorations for line-like items - + \image html QCPLineEnding.png "The various ending styles currently supported" - + For every ending a line-like item has, an instance of this class exists. For example, QCPItemLine has two endings which can be set with QCPItemLine::setHead and QCPItemLine::setTail. - + The styles themselves are defined via the enum QCPLineEnding::EndingStyle. Most decorations can be modified regarding width and length, see \ref setWidth and \ref setLength. The direction of the ending decoration (e.g. direction an arrow is pointing) is controlled by the line-like item. For example, when both endings of a QCPItemLine are set to be arrows, they will point to opposite directions, e.g. "outward". This can be changed by \ref setInverted, which would make the respective arrow point inward. - + Note that due to the overloaded QCPLineEnding constructor, you may directly specify a QCPLineEnding::EndingStyle where actually a QCPLineEnding is expected, e.g. \snippet documentation/doc-code-snippets/mainwindow.cpp qcplineending-sethead @@ -3379,10 +3383,10 @@ void QCPLayoutInset::addElement(QCPLayoutElement *element, const QRectF &rect) Creates a QCPLineEnding instance with default values (style \ref esNone). */ QCPLineEnding::QCPLineEnding() : - mStyle(esNone), - mWidth(8), - mLength(10), - mInverted(false) + mStyle(esNone), + mWidth(8), + mLength(10), + mInverted(false) { } @@ -3390,10 +3394,10 @@ QCPLineEnding::QCPLineEnding() : Creates a QCPLineEnding instance with the specified values. */ QCPLineEnding::QCPLineEnding(QCPLineEnding::EndingStyle style, double width, double length, bool inverted) : - mStyle(style), - mWidth(width), - mLength(length), - mInverted(inverted) + mStyle(style), + mWidth(width), + mLength(length), + mInverted(inverted) { } @@ -3402,29 +3406,29 @@ QCPLineEnding::QCPLineEnding(QCPLineEnding::EndingStyle style, double width, dou */ void QCPLineEnding::setStyle(QCPLineEnding::EndingStyle style) { - mStyle = style; + mStyle = style; } /*! Sets the width of the ending decoration, if the style supports it. On arrows, for example, the width defines the size perpendicular to the arrow's pointing direction. - + \see setLength */ void QCPLineEnding::setWidth(double width) { - mWidth = width; + mWidth = width; } /*! Sets the length of the ending decoration, if the style supports it. On arrows, for example, the length defines the size in pointing direction. - + \see setWidth */ void QCPLineEnding::setLength(double length) { - mLength = length; + mLength = length; } /*! @@ -3437,214 +3441,203 @@ void QCPLineEnding::setLength(double length) */ void QCPLineEnding::setInverted(bool inverted) { - mInverted = inverted; + mInverted = inverted; } /*! \internal - + Returns the maximum pixel radius the ending decoration might cover, starting from the position the decoration is drawn at (typically a line ending/\ref QCPItemPosition of an item). - + This is relevant for clipping. Only omit painting of the decoration when the position where the decoration is supposed to be drawn is farther away from the clipping rect than the returned distance. */ double QCPLineEnding::boundingDistance() const { - switch (mStyle) - { - case esNone: - return 0; - - case esFlatArrow: - case esSpikeArrow: - case esLineArrow: - case esSkewedBar: - return qSqrt(mWidth*mWidth+mLength*mLength); // items that have width and length - - case esDisc: - case esSquare: - case esDiamond: - case esBar: - case esHalfBar: - return mWidth*1.42; // items that only have a width -> width*sqrt(2) + switch (mStyle) { + case esNone: + return 0; - } - return 0; + case esFlatArrow: + case esSpikeArrow: + case esLineArrow: + case esSkewedBar: + return qSqrt(mWidth * mWidth + mLength * mLength); // items that have width and length + + case esDisc: + case esSquare: + case esDiamond: + case esBar: + case esHalfBar: + return mWidth * 1.42; // items that only have a width -> width*sqrt(2) + + } + return 0; } /*! Starting from the origin of this line ending (which is style specific), returns the length covered by the line ending symbol, in backward direction. - + For example, the \ref esSpikeArrow has a shorter real length than a \ref esFlatArrow, even if both have the same \ref setLength value, because the spike arrow has an inward curved back, which reduces the length along its center axis (the drawing origin for arrows is at the tip). - + This function is used for precise, style specific placement of line endings, for example in QCPAxes. */ double QCPLineEnding::realLength() const { - switch (mStyle) - { - case esNone: - case esLineArrow: - case esSkewedBar: - case esBar: - case esHalfBar: - return 0; - - case esFlatArrow: - return mLength; - - case esDisc: - case esSquare: - case esDiamond: - return mWidth*0.5; - - case esSpikeArrow: - return mLength*0.8; - } - return 0; + switch (mStyle) { + case esNone: + case esLineArrow: + case esSkewedBar: + case esBar: + case esHalfBar: + return 0; + + case esFlatArrow: + return mLength; + + case esDisc: + case esSquare: + case esDiamond: + return mWidth * 0.5; + + case esSpikeArrow: + return mLength * 0.8; + } + return 0; } /*! \internal - + 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 { - if (mStyle == esNone) - return; - - QVector2D lengthVec(dir.normalized()); - 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)); - - QPen penBackup = painter->pen(); - QBrush brushBackup = painter->brush(); - QPen miterPen = penBackup; - miterPen.setJoinStyle(Qt::MiterJoin); // to make arrow heads spikey - QBrush brush(painter->pen().color(), Qt::SolidPattern); - switch (mStyle) - { - case esNone: break; - case esFlatArrow: - { - QPointF points[3] = {pos.toPointF(), - (pos-lengthVec+widthVec).toPointF(), - (pos-lengthVec-widthVec).toPointF() - }; - painter->setPen(miterPen); - painter->setBrush(brush); - painter->drawConvexPolygon(points, 3); - painter->setBrush(brushBackup); - painter->setPen(penBackup); - break; + if (mStyle == esNone) { + return; } - case esSpikeArrow: - { - QPointF points[4] = {pos.toPointF(), - (pos-lengthVec+widthVec).toPointF(), - (pos-lengthVec*0.8f).toPointF(), - (pos-lengthVec-widthVec).toPointF() - }; - painter->setPen(miterPen); - painter->setBrush(brush); - painter->drawConvexPolygon(points, 4); - painter->setBrush(brushBackup); - painter->setPen(penBackup); - break; + + QVector2D lengthVec(dir.normalized()); + if (lengthVec.isNull()) { + lengthVec = QVector2D(1, 0); } - case esLineArrow: - { - QPointF points[3] = {(pos-lengthVec+widthVec).toPointF(), - pos.toPointF(), - (pos-lengthVec-widthVec).toPointF() - }; - painter->setPen(miterPen); - painter->drawPolyline(points, 3); - painter->setPen(penBackup); - break; + QVector2D widthVec(-lengthVec.y(), lengthVec.x()); + lengthVec *= (float)(mLength * (mInverted ? -1 : 1)); + widthVec *= (float)(mWidth * 0.5 * (mInverted ? -1 : 1)); + + QPen penBackup = painter->pen(); + QBrush brushBackup = painter->brush(); + QPen miterPen = penBackup; + miterPen.setJoinStyle(Qt::MiterJoin); // to make arrow heads spikey + QBrush brush(painter->pen().color(), Qt::SolidPattern); + switch (mStyle) { + case esNone: + break; + case esFlatArrow: { + QPointF points[3] = {pos.toPointF(), + (pos - lengthVec + widthVec).toPointF(), + (pos - lengthVec - widthVec).toPointF() + }; + painter->setPen(miterPen); + painter->setBrush(brush); + painter->drawConvexPolygon(points, 3); + painter->setBrush(brushBackup); + painter->setPen(penBackup); + break; + } + case esSpikeArrow: { + QPointF points[4] = {pos.toPointF(), + (pos - lengthVec + widthVec).toPointF(), + (pos - lengthVec * 0.8f).toPointF(), + (pos - lengthVec - widthVec).toPointF() + }; + painter->setPen(miterPen); + painter->setBrush(brush); + painter->drawConvexPolygon(points, 4); + painter->setBrush(brushBackup); + painter->setPen(penBackup); + break; + } + case esLineArrow: { + QPointF points[3] = {(pos - lengthVec + widthVec).toPointF(), + pos.toPointF(), + (pos - lengthVec - widthVec).toPointF() + }; + painter->setPen(miterPen); + painter->drawPolyline(points, 3); + painter->setPen(penBackup); + break; + } + case esDisc: { + painter->setBrush(brush); + painter->drawEllipse(pos.toPointF(), mWidth * 0.5, mWidth * 0.5); + painter->setBrush(brushBackup); + break; + } + case esSquare: { + QVector2D widthVecPerp(-widthVec.y(), widthVec.x()); + QPointF points[4] = {(pos - widthVecPerp + widthVec).toPointF(), + (pos - widthVecPerp - widthVec).toPointF(), + (pos + widthVecPerp - widthVec).toPointF(), + (pos + widthVecPerp + widthVec).toPointF() + }; + painter->setPen(miterPen); + painter->setBrush(brush); + painter->drawConvexPolygon(points, 4); + painter->setBrush(brushBackup); + painter->setPen(penBackup); + break; + } + case esDiamond: { + QVector2D widthVecPerp(-widthVec.y(), widthVec.x()); + QPointF points[4] = {(pos - widthVecPerp).toPointF(), + (pos - widthVec).toPointF(), + (pos + widthVecPerp).toPointF(), + (pos + widthVec).toPointF() + }; + painter->setPen(miterPen); + painter->setBrush(brush); + painter->drawConvexPolygon(points, 4); + painter->setBrush(brushBackup); + painter->setPen(penBackup); + break; + } + case esBar: { + painter->drawLine((pos + widthVec).toPointF(), (pos - widthVec).toPointF()); + break; + } + case esHalfBar: { + painter->drawLine((pos + widthVec).toPointF(), pos.toPointF()); + break; + } + case esSkewedBar: { + 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()); + } 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()); + } + break; + } } - case esDisc: - { - painter->setBrush(brush); - painter->drawEllipse(pos.toPointF(), mWidth*0.5, mWidth*0.5); - painter->setBrush(brushBackup); - break; - } - case esSquare: - { - QVector2D widthVecPerp(-widthVec.y(), widthVec.x()); - QPointF points[4] = {(pos-widthVecPerp+widthVec).toPointF(), - (pos-widthVecPerp-widthVec).toPointF(), - (pos+widthVecPerp-widthVec).toPointF(), - (pos+widthVecPerp+widthVec).toPointF() - }; - painter->setPen(miterPen); - painter->setBrush(brush); - painter->drawConvexPolygon(points, 4); - painter->setBrush(brushBackup); - painter->setPen(penBackup); - break; - } - case esDiamond: - { - QVector2D widthVecPerp(-widthVec.y(), widthVec.x()); - QPointF points[4] = {(pos-widthVecPerp).toPointF(), - (pos-widthVec).toPointF(), - (pos+widthVecPerp).toPointF(), - (pos+widthVec).toPointF() - }; - painter->setPen(miterPen); - painter->setBrush(brush); - painter->drawConvexPolygon(points, 4); - painter->setBrush(brushBackup); - painter->setPen(penBackup); - break; - } - case esBar: - { - painter->drawLine((pos+widthVec).toPointF(), (pos-widthVec).toPointF()); - break; - } - case esHalfBar: - { - painter->drawLine((pos+widthVec).toPointF(), pos.toPointF()); - break; - } - case esSkewedBar: - { - 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()); - } 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()); - } - break; - } - } } /*! \internal \overload - + 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 { - draw(painter, pos, QVector2D(qCos(angle), qSin(angle))); + draw(painter, pos, QVector2D(qCos(angle), qSin(angle))); } @@ -3654,11 +3647,11 @@ void QCPLineEnding::draw(QCPPainter *painter, const QVector2D &pos, double angle /*! \class QCPGrid \brief Responsible for drawing the grid of a QCPAxis. - + This class is tightly bound to QCPAxis. Every axis owns a grid instance and uses it to draw the grid lines, sub grid lines and zero-line. You can interact with the grid of an axis via \ref QCPAxis::grid. Normally, you don't need to create an instance of QCPGrid yourself. - + The axis and grid drawing was split into two classes to allow them to be placed on different layers (both QCPAxis and QCPGrid inherit from QCPLayerable). Thus it is possible to have the grid in the background and the axes in the foreground, and any plottables/items in between. This @@ -3667,32 +3660,32 @@ void QCPLineEnding::draw(QCPPainter *painter, const QVector2D &pos, double angle /*! Creates a QCPGrid instance and sets default values. - + You shouldn't instantiate grids on their own, since every QCPAxis brings its own QCPGrid. */ QCPGrid::QCPGrid(QCPAxis *parentAxis) : - QCPLayerable(parentAxis->parentPlot(), QString(), parentAxis), - mParentAxis(parentAxis) + QCPLayerable(parentAxis->parentPlot(), QString(), parentAxis), + mParentAxis(parentAxis) { - // warning: this is called in QCPAxis constructor, so parentAxis members should not be accessed/called - setParent(parentAxis); - setPen(QPen(QColor(200,200,200), 0, Qt::DotLine)); - setSubGridPen(QPen(QColor(220,220,220), 0, Qt::DotLine)); - setZeroLinePen(QPen(QColor(200,200,200), 0, Qt::SolidLine)); - setSubGridVisible(false); - setAntialiased(false); - setAntialiasedSubGrid(false); - setAntialiasedZeroLine(false); + // warning: this is called in QCPAxis constructor, so parentAxis members should not be accessed/called + setParent(parentAxis); + setPen(QPen(QColor(200, 200, 200), 0, Qt::DotLine)); + setSubGridPen(QPen(QColor(220, 220, 220), 0, Qt::DotLine)); + setZeroLinePen(QPen(QColor(200, 200, 200), 0, Qt::SolidLine)); + setSubGridVisible(false); + setAntialiased(false); + setAntialiasedSubGrid(false); + setAntialiasedZeroLine(false); } /*! Sets whether grid lines at sub tick marks are drawn. - + \see setSubGridPen */ void QCPGrid::setSubGridVisible(bool visible) { - mSubGridVisible = visible; + mSubGridVisible = visible; } /*! @@ -3700,7 +3693,7 @@ void QCPGrid::setSubGridVisible(bool visible) */ void QCPGrid::setAntialiasedSubGrid(bool enabled) { - mAntialiasedSubGrid = enabled; + mAntialiasedSubGrid = enabled; } /*! @@ -3708,7 +3701,7 @@ void QCPGrid::setAntialiasedSubGrid(bool enabled) */ void QCPGrid::setAntialiasedZeroLine(bool enabled) { - mAntialiasedZeroLine = enabled; + mAntialiasedZeroLine = enabled; } /*! @@ -3716,7 +3709,7 @@ void QCPGrid::setAntialiasedZeroLine(bool enabled) */ void QCPGrid::setPen(const QPen &pen) { - mPen = pen; + mPen = pen; } /*! @@ -3724,18 +3717,18 @@ void QCPGrid::setPen(const QPen &pen) */ void QCPGrid::setSubGridPen(const QPen &pen) { - mSubGridPen = pen; + mSubGridPen = pen; } /*! Sets the pen with which zero lines are drawn. - + Zero lines are lines at value coordinate 0 which may be drawn with a different pen than other grid lines. To disable zero lines and just draw normal grid lines at zero, set \a pen to Qt::NoPen. */ void QCPGrid::setZeroLinePen(const QPen &pen) { - mZeroLinePen = pen; + mZeroLinePen = pen; } /*! \internal @@ -3744,134 +3737,134 @@ void QCPGrid::setZeroLinePen(const QPen &pen) before drawing the major grid lines. This is the antialiasing state the painter passed to the \ref draw method is in by default. - + 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 */ void QCPGrid::applyDefaultAntialiasingHint(QCPPainter *painter) const { - applyAntialiasingHint(painter, mAntialiased, QCP::aeGrid); + applyAntialiasingHint(painter, mAntialiased, QCP::aeGrid); } /*! \internal - + Draws grid lines and sub grid lines at the positions of (sub) ticks of the parent axis, spanning over the complete axis rect. Also draws the zero line, if appropriate (\ref setZeroLinePen). */ void QCPGrid::draw(QCPPainter *painter) { - if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; } - - if (mSubGridVisible) - drawSubGridLines(painter); - drawGridLines(painter); + if (!mParentAxis) { + qDebug() << Q_FUNC_INFO << "invalid parent axis"; + return; + } + + if (mSubGridVisible) { + drawSubGridLines(painter); + } + drawGridLines(painter); } /*! \internal - + Draws the main grid lines and possibly a zero line with the specified painter. - + This is a helper function called by \ref draw. */ void QCPGrid::drawGridLines(QCPPainter *painter) const { - if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; } - - int lowTick = mParentAxis->mLowestVisibleTick; - int highTick = mParentAxis->mHighestVisibleTick; - double t; // helper variable, result of coordinate-to-pixel transforms - if (mParentAxis->orientation() == Qt::Horizontal) - { - // draw zeroline: - int zeroLineIndex = -1; - if (mZeroLinePen.style() != Qt::NoPen && mParentAxis->mRange.lower < 0 && mParentAxis->mRange.upper > 0) - { - 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) - { - if (qAbs(mParentAxis->mTickVector.at(i)) < epsilon) - { - zeroLineIndex = i; - t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // x - painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top())); - break; + if (!mParentAxis) { + qDebug() << Q_FUNC_INFO << "invalid parent axis"; + return; + } + + int lowTick = mParentAxis->mLowestVisibleTick; + int highTick = mParentAxis->mHighestVisibleTick; + double t; // helper variable, result of coordinate-to-pixel transforms + if (mParentAxis->orientation() == Qt::Horizontal) { + // draw zeroline: + int zeroLineIndex = -1; + if (mZeroLinePen.style() != Qt::NoPen && mParentAxis->mRange.lower < 0 && mParentAxis->mRange.upper > 0) { + 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) { + if (qAbs(mParentAxis->mTickVector.at(i)) < epsilon) { + zeroLineIndex = i; + t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // x + painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top())); + break; + } + } } - } - } - // draw grid lines: - applyDefaultAntialiasingHint(painter); - painter->setPen(mPen); - for (int i=lowTick; i <= highTick; ++i) - { - if (i == zeroLineIndex) continue; // don't draw a gridline on top of the zeroline - t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // x - painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top())); - } - } else - { - // draw zeroline: - int zeroLineIndex = -1; - if (mZeroLinePen.style() != Qt::NoPen && mParentAxis->mRange.lower < 0 && mParentAxis->mRange.upper > 0) - { - 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) - { - if (qAbs(mParentAxis->mTickVector.at(i)) < epsilon) - { - zeroLineIndex = i; - t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // y - painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t)); - break; + // draw grid lines: + applyDefaultAntialiasingHint(painter); + painter->setPen(mPen); + for (int i = lowTick; i <= highTick; ++i) { + if (i == zeroLineIndex) { + continue; // don't draw a gridline on top of the zeroline + } + t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // x + painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top())); + } + } else { + // draw zeroline: + int zeroLineIndex = -1; + if (mZeroLinePen.style() != Qt::NoPen && mParentAxis->mRange.lower < 0 && mParentAxis->mRange.upper > 0) { + 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) { + if (qAbs(mParentAxis->mTickVector.at(i)) < epsilon) { + zeroLineIndex = i; + t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // y + painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t)); + break; + } + } + } + // draw grid lines: + applyDefaultAntialiasingHint(painter); + painter->setPen(mPen); + for (int i = lowTick; i <= highTick; ++i) { + if (i == zeroLineIndex) { + continue; // don't draw a gridline on top of the zeroline + } + t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // y + painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t)); } - } } - // draw grid lines: - applyDefaultAntialiasingHint(painter); - painter->setPen(mPen); - for (int i=lowTick; i <= highTick; ++i) - { - if (i == zeroLineIndex) continue; // don't draw a gridline on top of the zeroline - t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // y - painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t)); - } - } } /*! \internal - + Draws the sub grid lines with the specified painter. - + This is a helper function called by \ref draw. */ void QCPGrid::drawSubGridLines(QCPPainter *painter) const { - if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; } - - applyAntialiasingHint(painter, mAntialiasedSubGrid, QCP::aeSubGrid); - double t; // helper variable, result of coordinate-to-pixel transforms - painter->setPen(mSubGridPen); - if (mParentAxis->orientation() == Qt::Horizontal) - { - for (int i=0; imSubTickVector.size(); ++i) - { - t = mParentAxis->coordToPixel(mParentAxis->mSubTickVector.at(i)); // x - painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top())); + if (!mParentAxis) { + qDebug() << Q_FUNC_INFO << "invalid parent axis"; + return; } - } else - { - for (int i=0; imSubTickVector.size(); ++i) - { - t = mParentAxis->coordToPixel(mParentAxis->mSubTickVector.at(i)); // y - painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t)); + + applyAntialiasingHint(painter, mAntialiasedSubGrid, QCP::aeSubGrid); + double t; // helper variable, result of coordinate-to-pixel transforms + painter->setPen(mSubGridPen); + if (mParentAxis->orientation() == Qt::Horizontal) { + for (int i = 0; i < mParentAxis->mSubTickVector.size(); ++i) { + t = mParentAxis->coordToPixel(mParentAxis->mSubTickVector.at(i)); // x + painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top())); + } + } else { + for (int i = 0; i < mParentAxis->mSubTickVector.size(); ++i) { + t = mParentAxis->coordToPixel(mParentAxis->mSubTickVector.at(i)); // y + painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t)); + } } - } } @@ -3885,12 +3878,12 @@ void QCPGrid::drawSubGridLines(QCPPainter *painter) const Usually doesn't need to be instantiated externally. Access %QCustomPlot's default four axes via QCustomPlot::xAxis (bottom), QCustomPlot::yAxis (left), QCustomPlot::xAxis2 (top) and QCustomPlot::yAxis2 (right). - + Axes are always part of an axis rect, see QCPAxisRect. \image html AxisNamesOverview.png
Naming convention of axis parts
\n - + \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.
@@ -3900,23 +3893,23 @@ void QCPGrid::drawSubGridLines(QCPPainter *painter) const /* 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) */ /*! \fn QCPGrid *QCPAxis::grid() const - + Returns the \ref QCPGrid instance belonging to this axis. Access it to set details about the way the grid is displayed. */ /*! \fn static Qt::Orientation QCPAxis::orientation(AxisType type) - + Returns the orientation of the specified axis type - + \see orientation() */ @@ -3924,14 +3917,14 @@ void QCPGrid::drawSubGridLines(QCPPainter *painter) const /* 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 @@ -3943,7 +3936,7 @@ void QCPGrid::drawSubGridLines(QCPPainter *painter) const This signal is emitted when the range of this axis has changed. You can connect it to the \ref setRange slot of another axis to communicate the new range to the other axis, in order for it to be synchronized. - + 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 @@ -3956,24 +3949,24 @@ void QCPGrid::drawSubGridLines(QCPPainter *painter) const /*! \fn void QCPAxis::rangeChanged(const QCPRange &newRange, const QCPRange &oldRange) \overload - + Additionally to the new range, this signal also provides the previous range held by the axis as \a oldRange. */ /*! \fn void QCPAxis::scaleTypeChanged(QCPAxis::ScaleType scaleType); - + This signal is emitted when the scale type changes, by calls to \ref setScaleType */ /*! \fn void QCPAxis::selectionChanged(QCPAxis::SelectableParts selection) - + This signal is emitted when the selection state of this axis has changed, either by user interaction or by a direct call to \ref setSelectedParts. */ /*! \fn void QCPAxis::selectableChanged(const QCPAxis::SelectableParts &parts); - + This signal is emitted when the selectability changes, by calls to \ref setSelectableParts */ @@ -3981,175 +3974,171 @@ void QCPGrid::drawSubGridLines(QCPPainter *painter) const /*! Constructs an Axis instance of Type \a type for the axis rect \a parent. - + Usually it isn't necessary to instantiate axes directly, because you can let QCustomPlot create them for you with \ref QCPAxisRect::addAxis. If you want to use own QCPAxis-subclasses however, create them manually and then inject them also via \ref QCPAxisRect::addAxis. */ QCPAxis::QCPAxis(QCPAxisRect *parent, AxisType type) : - QCPLayerable(parent->parentPlot(), QString(), parent), - // axis base: - mAxisType(type), - mAxisRect(parent), - mPadding(5), - mOrientation(orientation(type)), - mSelectableParts(spAxis | spTickLabels | spAxisLabel), - mSelectedParts(spNone), - mBasePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), - mSelectedBasePen(QPen(Qt::blue, 2)), - // axis label: - mLabel(), - mLabelFont(mParentPlot->font()), - mSelectedLabelFont(QFont(mLabelFont.family(), mLabelFont.pointSize(), QFont::Bold)), - mLabelColor(Qt::black), - 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), - mTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), - mSelectedTickPen(QPen(Qt::blue, 2)), - mSubTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), - mSelectedSubTickPen(QPen(Qt::blue, 2)), - // scale and range: - 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), - mCachedMarginValid(false), - mCachedMargin(0) + QCPLayerable(parent->parentPlot(), QString(), parent), + // axis base: + mAxisType(type), + mAxisRect(parent), + mPadding(5), + mOrientation(orientation(type)), + mSelectableParts(spAxis | spTickLabels | spAxisLabel), + mSelectedParts(spNone), + mBasePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), + mSelectedBasePen(QPen(Qt::blue, 2)), + // axis label: + mLabel(), + mLabelFont(mParentPlot->font()), + mSelectedLabelFont(QFont(mLabelFont.family(), mLabelFont.pointSize(), QFont::Bold)), + mLabelColor(Qt::black), + 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), + mTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), + mSelectedTickPen(QPen(Qt::blue, 2)), + mSubTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), + mSelectedSubTickPen(QPen(Qt::blue, 2)), + // scale and range: + 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), + 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 - - if (type == atTop) - { - setTickLabelPadding(3); - setLabelPadding(6); - } else if (type == atRight) - { - setTickLabelPadding(7); - setLabelPadding(12); - } else if (type == atBottom) - { - setTickLabelPadding(3); - setLabelPadding(3); - } else if (type == atLeft) - { - setTickLabelPadding(5); - setLabelPadding(10); - } + 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 + + if (type == atTop) { + setTickLabelPadding(3); + setLabelPadding(6); + } else if (type == atRight) { + setTickLabelPadding(7); + setLabelPadding(12); + } else if (type == atBottom) { + setTickLabelPadding(3); + setLabelPadding(3); + } else if (type == atLeft) { + setTickLabelPadding(5); + setLabelPadding(10); + } } QCPAxis::~QCPAxis() { - delete mAxisPainter; - delete mGrid; // delete grid here instead of via parent ~QObject for better defined deletion order + delete mAxisPainter; + delete mGrid; // delete grid here instead of via parent ~QObject for better defined deletion order } /* No documentation as it is a property getter */ int QCPAxis::tickLabelPadding() const { - return mAxisPainter->tickLabelPadding; + return mAxisPainter->tickLabelPadding; } /* No documentation as it is a property getter */ double QCPAxis::tickLabelRotation() const { - return mAxisPainter->tickLabelRotation; + return mAxisPainter->tickLabelRotation; } /* No documentation as it is a property getter */ QCPAxis::LabelSide QCPAxis::tickLabelSide() const { - return mAxisPainter->tickLabelSide; + return mAxisPainter->tickLabelSide; } /* No documentation as it is a property getter */ QString QCPAxis::numberFormat() const { - QString result; - result.append(mNumberFormatChar); - if (mNumberBeautifulPowers) - { - result.append(QLatin1Char('b')); - if (mAxisPainter->numberMultiplyCross) - result.append(QLatin1Char('c')); - } - return result; + QString result; + result.append(mNumberFormatChar); + if (mNumberBeautifulPowers) { + result.append(QLatin1Char('b')); + if (mAxisPainter->numberMultiplyCross) { + result.append(QLatin1Char('c')); + } + } + return result; } /* No documentation as it is a property getter */ int QCPAxis::tickLengthIn() const { - return mAxisPainter->tickLengthIn; + return mAxisPainter->tickLengthIn; } /* No documentation as it is a property getter */ int QCPAxis::tickLengthOut() const { - return mAxisPainter->tickLengthOut; + return mAxisPainter->tickLengthOut; } /* No documentation as it is a property getter */ int QCPAxis::subTickLengthIn() const { - return mAxisPainter->subTickLengthIn; + return mAxisPainter->subTickLengthIn; } /* No documentation as it is a property getter */ int QCPAxis::subTickLengthOut() const { - return mAxisPainter->subTickLengthOut; + return mAxisPainter->subTickLengthOut; } /* No documentation as it is a property getter */ int QCPAxis::labelPadding() const { - return mAxisPainter->labelPadding; + return mAxisPainter->labelPadding; } /* No documentation as it is a property getter */ int QCPAxis::offset() const { - return mAxisPainter->offset; + return mAxisPainter->offset; } /* No documentation as it is a property getter */ QCPLineEnding QCPAxis::lowerEnding() const { - return mAxisPainter->lowerEnding; + return mAxisPainter->lowerEnding; } /* No documentation as it is a property getter */ QCPLineEnding QCPAxis::upperEnding() const { - return mAxisPainter->upperEnding; + return mAxisPainter->upperEnding; } /*! @@ -4158,7 +4147,7 @@ QCPLineEnding QCPAxis::upperEnding() const 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. - + 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]" @@ -4167,139 +4156,139 @@ QCPLineEnding QCPAxis::upperEnding() const */ void QCPAxis::setScaleType(QCPAxis::ScaleType type) { - if (mScaleType != type) - { - mScaleType = type; - if (mScaleType == stLogarithmic) - setRange(mRange.sanitizedForLogScale()); - mCachedMarginValid = false; - emit scaleTypeChanged(mScaleType); - } + if (mScaleType != type) { + mScaleType = type; + if (mScaleType == stLogarithmic) { + setRange(mRange.sanitizedForLogScale()); + } + mCachedMarginValid = false; + emit scaleTypeChanged(mScaleType); + } } /*! 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; + if (base > 1) { + mScaleLogBase = base; + mScaleLogBaseLogInv = 1.0 / qLn(mScaleLogBase); // buffer for faster baseLog() calculation + mCachedMarginValid = false; + } else { + qDebug() << Q_FUNC_INFO << "Invalid logarithmic scale base (must be greater 1):" << base; + } } /*! Sets the range of the axis. - + This slot may be connected with the \ref rangeChanged signal of another axis so this axis is always synchronized with the other axis range, when it changes. - + To invert the direction of an axis, use \ref setRangeReversed. */ void QCPAxis::setRange(const QCPRange &range) { - if (range.lower == mRange.lower && range.upper == mRange.upper) - return; - - if (!QCPRange::validRange(range)) return; - QCPRange oldRange = mRange; - if (mScaleType == stLogarithmic) - { - mRange = range.sanitizedForLogScale(); - } else - { - mRange = range.sanitizedForLinScale(); - } - mCachedMarginValid = false; - emit rangeChanged(mRange); - emit rangeChanged(mRange, oldRange); + if (range.lower == mRange.lower && range.upper == mRange.upper) { + return; + } + + if (!QCPRange::validRange(range)) { + return; + } + QCPRange oldRange = mRange; + if (mScaleType == stLogarithmic) { + mRange = range.sanitizedForLogScale(); + } else { + mRange = range.sanitizedForLinScale(); + } + mCachedMarginValid = false; + emit rangeChanged(mRange); + emit rangeChanged(mRange, oldRange); } /*! Sets whether the user can (de-)select the parts in \a selectable by clicking on the QCustomPlot surface. (When \ref QCustomPlot::setInteractions contains iSelectAxes.) - + However, even when \a selectable is set to a value not allowing the selection of a specific part, it is still possible to set the selection of this part manually, by calling \ref setSelectedParts directly. - + \see SelectablePart, setSelectedParts */ void QCPAxis::setSelectableParts(const SelectableParts &selectable) { - if (mSelectableParts != selectable) - { - mSelectableParts = selectable; - emit selectableChanged(mSelectableParts); - } + if (mSelectableParts != selectable) { + mSelectableParts = selectable; + emit selectableChanged(mSelectableParts); + } } /*! Sets the selected state of the respective axis parts described by \ref SelectablePart. When a part is selected, it uses a different pen/font. - + The entire selection mechanism for axes is handled automatically when \ref QCustomPlot::setInteractions contains iSelectAxes. You only need to call this function when you wish to change the selection state manually. - + This function can change the selection state of a part, independent of the \ref setSelectableParts setting. - + emits the \ref selectionChanged signal when \a selected is different from the previous selection state. - + \see SelectablePart, setSelectableParts, selectTest, setSelectedBasePen, setSelectedTickPen, setSelectedSubTickPen, setSelectedTickLabelFont, setSelectedLabelFont, setSelectedTickLabelColor, setSelectedLabelColor */ void QCPAxis::setSelectedParts(const SelectableParts &selected) { - if (mSelectedParts != selected) - { - mSelectedParts = selected; - emit selectionChanged(mSelectedParts); - } + if (mSelectedParts != selected) { + mSelectedParts = selected; + emit selectionChanged(mSelectedParts); + } } /*! \overload - + Sets the lower and upper bound of the axis range. - + To invert the direction of an axis, use \ref setRangeReversed. - + There is also a slot to set a range, see \ref setRange(const QCPRange &range). */ void QCPAxis::setRange(double lower, double upper) { - if (lower == mRange.lower && upper == mRange.upper) - return; - - if (!QCPRange::validRange(lower, upper)) return; - QCPRange oldRange = mRange; - mRange.lower = lower; - mRange.upper = upper; - if (mScaleType == stLogarithmic) - { - mRange = mRange.sanitizedForLogScale(); - } else - { - mRange = mRange.sanitizedForLinScale(); - } - mCachedMarginValid = false; - emit rangeChanged(mRange); - emit rangeChanged(mRange, oldRange); + if (lower == mRange.lower && upper == mRange.upper) { + return; + } + + if (!QCPRange::validRange(lower, upper)) { + return; + } + QCPRange oldRange = mRange; + mRange.lower = lower; + mRange.upper = upper; + if (mScaleType == stLogarithmic) { + mRange = mRange.sanitizedForLogScale(); + } else { + mRange = mRange.sanitizedForLinScale(); + } + mCachedMarginValid = false; + emit rangeChanged(mRange); + emit rangeChanged(mRange, oldRange); } /*! \overload - + Sets the range of the axis. - + The \a position coordinate indicates together with the \a alignment parameter, where the new range will be positioned. \a size defines the size of the new axis range. \a alignment may be Qt::AlignLeft, Qt::AlignRight or Qt::AlignCenter. This will cause the left border, right border, @@ -4308,12 +4297,13 @@ void QCPAxis::setRange(double lower, double upper) */ void QCPAxis::setRange(double position, double size, Qt::AlignmentFlag alignment) { - if (alignment == Qt::AlignLeft) - setRange(position, position+size); - else if (alignment == Qt::AlignRight) - setRange(position-size, position); - else // alignment == Qt::AlignCenter - setRange(position-size/2.0, position+size/2.0); + if (alignment == Qt::AlignLeft) { + setRange(position, position + size); + } else if (alignment == Qt::AlignRight) { + setRange(position - size, position); + } else { // alignment == Qt::AlignCenter + setRange(position - size / 2.0, position + size / 2.0); + } } /*! @@ -4322,21 +4312,20 @@ void QCPAxis::setRange(double position, double size, Qt::AlignmentFlag alignment */ void QCPAxis::setRangeLower(double lower) { - if (mRange.lower == lower) - return; - - QCPRange oldRange = mRange; - mRange.lower = lower; - if (mScaleType == stLogarithmic) - { - mRange = mRange.sanitizedForLogScale(); - } else - { - mRange = mRange.sanitizedForLinScale(); - } - mCachedMarginValid = false; - emit rangeChanged(mRange); - emit rangeChanged(mRange, oldRange); + if (mRange.lower == lower) { + return; + } + + QCPRange oldRange = mRange; + mRange.lower = lower; + if (mScaleType == stLogarithmic) { + mRange = mRange.sanitizedForLogScale(); + } else { + mRange = mRange.sanitizedForLinScale(); + } + mCachedMarginValid = false; + emit rangeChanged(mRange); + emit rangeChanged(mRange, oldRange); } /*! @@ -4345,21 +4334,20 @@ void QCPAxis::setRangeLower(double lower) */ void QCPAxis::setRangeUpper(double upper) { - if (mRange.upper == upper) - return; - - QCPRange oldRange = mRange; - mRange.upper = upper; - if (mScaleType == stLogarithmic) - { - mRange = mRange.sanitizedForLogScale(); - } else - { - mRange = mRange.sanitizedForLinScale(); - } - mCachedMarginValid = false; - emit rangeChanged(mRange); - emit rangeChanged(mRange, oldRange); + if (mRange.upper == upper) { + return; + } + + QCPRange oldRange = mRange; + mRange.upper = upper; + if (mScaleType == stLogarithmic) { + mRange = mRange.sanitizedForLogScale(); + } else { + mRange = mRange.sanitizedForLinScale(); + } + mCachedMarginValid = false; + emit rangeChanged(mRange); + emit rangeChanged(mRange, oldRange); } /*! @@ -4373,83 +4361,79 @@ void QCPAxis::setRangeUpper(double upper) */ void QCPAxis::setRangeReversed(bool reversed) { - if (mRangeReversed != reversed) - { - mRangeReversed = reversed; - mCachedMarginValid = false; - } + if (mRangeReversed != reversed) { + mRangeReversed = reversed; + mCachedMarginValid = false; + } } /*! 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). - + 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. - + 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 setAutoTickLabels, setAutoSubTicks, setAutoTickCount, setAutoTickStep */ void QCPAxis::setAutoTicks(bool on) { - if (mAutoTicks != on) - { - mAutoTicks = on; - mCachedMarginValid = false; - } + 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; - } + 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; - } + if (mAutoTickLabels != on) { + mAutoTickLabels = on; + mCachedMarginValid = false; + } } /*! @@ -4459,36 +4443,34 @@ void QCPAxis::setAutoTickLabels(bool on) 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; - } + 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 (mAutoSubTicks != on) { + mAutoSubTicks = on; + mCachedMarginValid = false; + } } /*! @@ -4499,11 +4481,10 @@ void QCPAxis::setAutoSubTicks(bool on) */ void QCPAxis::setTicks(bool show) { - if (mTicks != show) - { - mTicks = show; - mCachedMarginValid = false; - } + if (mTicks != show) { + mTicks = show; + mCachedMarginValid = false; + } } /*! @@ -4511,11 +4492,10 @@ void QCPAxis::setTicks(bool show) */ void QCPAxis::setTickLabels(bool show) { - if (mTickLabels != show) - { - mTickLabels = show; - mCachedMarginValid = false; - } + if (mTickLabels != show) { + mTickLabels = show; + mCachedMarginValid = false; + } } /*! @@ -4524,117 +4504,111 @@ void QCPAxis::setTickLabels(bool show) */ void QCPAxis::setTickLabelPadding(int padding) { - if (mAxisPainter->tickLabelPadding != padding) - { - mAxisPainter->tickLabelPadding = padding; - mCachedMarginValid = false; - } + if (mAxisPainter->tickLabelPadding != padding) { + mAxisPainter->tickLabelPadding = padding; + mCachedMarginValid = false; + } } /*! 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; - } + if (mTickLabelType != type) { + mTickLabelType = type; + mCachedMarginValid = false; + } } /*! Sets the font of the tick labels. - + \see setTickLabels, setTickLabelColor */ void QCPAxis::setTickLabelFont(const QFont &font) { - if (font != mTickLabelFont) - { - mTickLabelFont = font; - mCachedMarginValid = false; - } + if (font != mTickLabelFont) { + mTickLabelFont = font; + mCachedMarginValid = false; + } } /*! Sets the color of the tick labels. - + \see setTickLabels, setTickLabelFont */ void QCPAxis::setTickLabelColor(const QColor &color) { - if (color != mTickLabelColor) - { - mTickLabelColor = color; - mCachedMarginValid = false; - } + if (color != mTickLabelColor) { + mTickLabelColor = color; + mCachedMarginValid = false; + } } /*! Sets the rotation of the tick labels. If \a degrees is zero, the labels are drawn normally. Else, the tick labels are drawn rotated by \a degrees clockwise. The specified angle is bound to values from -90 to 90 degrees. - + If \a degrees is exactly -90, 0 or 90, the tick labels are centered on the tick coordinate. For other angles, the label is drawn with an offset such that it seems to point toward or away from the tick mark. */ void QCPAxis::setTickLabelRotation(double degrees) { - if (!qFuzzyIsNull(degrees-mAxisPainter->tickLabelRotation)) - { - mAxisPainter->tickLabelRotation = qBound(-90.0, degrees, 90.0); - mCachedMarginValid = false; - } + if (!qFuzzyIsNull(degrees - mAxisPainter->tickLabelRotation)) { + mAxisPainter->tickLabelRotation = qBound(-90.0, degrees, 90.0); + mCachedMarginValid = false; + } } /*! Sets whether the tick labels (numbers) shall appear inside or outside the axis rect. - + The usual and default setting is \ref lsOutside. Very compact plots sometimes require tick labels to be inside the axis rect, to save space. If \a side is set to \ref lsInside, the tick labels appear on the inside are additionally clipped to the axis rect. */ void QCPAxis::setTickLabelSide(LabelSide side) { - mAxisPainter->tickLabelSide = side; - mCachedMarginValid = false; + mAxisPainter->tickLabelSide = side; + mCachedMarginValid = false; } /*! Sets the format in which dates and times are displayed as tick labels, if \ref setTickLabelType is \ref ltDateTime. for details about the \a format string, see the documentation of QDateTime::toString(). - + Newlines can be inserted with "\n". - + \see setDateTimeSpec */ void QCPAxis::setDateTimeFormat(const QString &format) { - if (mDateTimeFormat != format) - { - mDateTimeFormat = format; - mCachedMarginValid = false; - } + if (mDateTimeFormat != format) { + mDateTimeFormat = format; + mCachedMarginValid = false; + } } /*! @@ -4644,12 +4618,12 @@ void QCPAxis::setDateTimeFormat(const QString &format) 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; + mDateTimeSpec = timeSpec; } /*! @@ -4660,7 +4634,7 @@ void QCPAxis::setDateTimeSpec(const Qt::TimeSpec &timeSpec) 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. "5.5e9", which is ugly in a plot. So when the second char of \a formatCode is set to 'b' (for @@ -4669,13 +4643,13 @@ void QCPAxis::setDateTimeSpec(const Qt::TimeSpec &timeSpec) If instead a cross should be shown (as is usual in the USA), the third char of \a formatCode can 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 @@ -4690,57 +4664,47 @@ void QCPAxis::setDateTimeSpec(const Qt::TimeSpec &timeSpec) */ void QCPAxis::setNumberFormat(const QString &formatCode) { - if (formatCode.isEmpty()) - { - qDebug() << Q_FUNC_INFO << "Passed formatCode is empty"; - return; - } - mCachedMarginValid = false; - - // interpret first char as number format char: - QString allowedFormatChars(QLatin1String("eEfgG")); - if (allowedFormatChars.contains(formatCode.at(0))) - { - mNumberFormatChar = QLatin1Char(formatCode.at(0).toLatin1()); - } else - { - qDebug() << Q_FUNC_INFO << "Invalid number format code (first char not in 'eEfgG'):" << formatCode; - return; - } - if (formatCode.length() < 2) - { - mNumberBeautifulPowers = false; - mAxisPainter->numberMultiplyCross = false; - return; - } - - // interpret second char as indicator for beautiful decimal powers: - if (formatCode.at(1) == QLatin1Char('b') && (mNumberFormatChar == QLatin1Char('e') || mNumberFormatChar == QLatin1Char('g'))) - { - mNumberBeautifulPowers = true; - } else - { - qDebug() << Q_FUNC_INFO << "Invalid number format code (second char not 'b' or first char neither 'e' nor 'g'):" << formatCode; - return; - } - if (formatCode.length() < 3) - { - mAxisPainter->numberMultiplyCross = false; - return; - } - - // interpret third char as indicator for dot or cross multiplication symbol: - if (formatCode.at(2) == QLatin1Char('c')) - { - mAxisPainter->numberMultiplyCross = true; - } else if (formatCode.at(2) == QLatin1Char('d')) - { - mAxisPainter->numberMultiplyCross = false; - } else - { - qDebug() << Q_FUNC_INFO << "Invalid number format code (third char neither 'c' nor 'd'):" << formatCode; - return; - } + if (formatCode.isEmpty()) { + qDebug() << Q_FUNC_INFO << "Passed formatCode is empty"; + return; + } + mCachedMarginValid = false; + + // interpret first char as number format char: + QString allowedFormatChars(QLatin1String("eEfgG")); + if (allowedFormatChars.contains(formatCode.at(0))) { + mNumberFormatChar = QLatin1Char(formatCode.at(0).toLatin1()); + } else { + qDebug() << Q_FUNC_INFO << "Invalid number format code (first char not in 'eEfgG'):" << formatCode; + return; + } + if (formatCode.length() < 2) { + mNumberBeautifulPowers = false; + mAxisPainter->numberMultiplyCross = false; + return; + } + + // interpret second char as indicator for beautiful decimal powers: + if (formatCode.at(1) == QLatin1Char('b') && (mNumberFormatChar == QLatin1Char('e') || mNumberFormatChar == QLatin1Char('g'))) { + mNumberBeautifulPowers = true; + } else { + qDebug() << Q_FUNC_INFO << "Invalid number format code (second char not 'b' or first char neither 'e' nor 'g'):" << formatCode; + return; + } + if (formatCode.length() < 3) { + mAxisPainter->numberMultiplyCross = false; + return; + } + + // interpret third char as indicator for dot or cross multiplication symbol: + if (formatCode.at(2) == QLatin1Char('c')) { + mAxisPainter->numberMultiplyCross = true; + } else if (formatCode.at(2) == QLatin1Char('d')) { + mAxisPainter->numberMultiplyCross = false; + } else { + qDebug() << Q_FUNC_INFO << "Invalid number format code (third char neither 'c' nor 'd'):" << formatCode; + return; + } } /*! @@ -4756,11 +4720,10 @@ void QCPAxis::setNumberFormat(const QString &formatCode) */ void QCPAxis::setNumberPrecision(int precision) { - if (mNumberPrecision != precision) - { - mNumberPrecision = precision; - mCachedMarginValid = false; - } + if (mNumberPrecision != precision) { + mNumberPrecision = precision; + mCachedMarginValid = false; + } } /*! @@ -4770,11 +4733,10 @@ void QCPAxis::setNumberPrecision(int precision) */ void QCPAxis::setTickStep(double step) { - if (mTickStep != step) - { - mTickStep = step; - mCachedMarginValid = false; - } + if (mTickStep != step) { + mTickStep = step; + mCachedMarginValid = false; + } } /*! @@ -4783,18 +4745,18 @@ void QCPAxis::setTickStep(double step) 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; + // don't check whether mTickVector != vec here, because it takes longer than we would save + mTickVector = vec; + mCachedMarginValid = false; } /*! @@ -4802,17 +4764,17 @@ void QCPAxis::setTickVector(const QVector &vec) 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; + // don't check whether mTickVectorLabels != vec here, because it takes longer than we would save + mTickVectorLabels = vec; + mCachedMarginValid = false; } /*! @@ -4820,49 +4782,47 @@ void QCPAxis::setTickVectorLabels(const QVector &vec) plot and \a outside is the length they will reach outside the plot. If \a outside is greater than zero, the tick labels and axis label will increase their distance to the axis accordingly, so they won't collide with the ticks. - + \see setSubTickLength, setTickLengthIn, setTickLengthOut */ void QCPAxis::setTickLength(int inside, int outside) { - setTickLengthIn(inside); - setTickLengthOut(outside); + setTickLengthIn(inside); + setTickLengthOut(outside); } /*! Sets the length of the inward ticks in pixels. \a inside is the length the ticks will reach inside the plot. - + \see setTickLengthOut, setTickLength, setSubTickLength */ void QCPAxis::setTickLengthIn(int inside) { - if (mAxisPainter->tickLengthIn != inside) - { - mAxisPainter->tickLengthIn = inside; - } + if (mAxisPainter->tickLengthIn != inside) { + mAxisPainter->tickLengthIn = inside; + } } /*! Sets the length of the outward ticks in pixels. \a outside is the length the ticks will reach outside the plot. If \a outside is greater than zero, the tick labels and axis label will increase their distance to the axis accordingly, so they won't collide with the ticks. - + \see setTickLengthIn, setTickLength, setSubTickLength */ void QCPAxis::setTickLengthOut(int outside) { - if (mAxisPainter->tickLengthOut != outside) - { - mAxisPainter->tickLengthOut = outside; - mCachedMarginValid = false; // only outside tick length can change margin - } + if (mAxisPainter->tickLengthOut != outside) { + mAxisPainter->tickLengthOut = outside; + mCachedMarginValid = false; // only outside tick length can change margin + } } /*! 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. - + 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. @@ -4872,7 +4832,7 @@ void QCPAxis::setTickLengthOut(int outside) */ void QCPAxis::setSubTickCount(int count) { - mSubTickCount = count; + mSubTickCount = count; } /*! @@ -4880,97 +4840,94 @@ void QCPAxis::setSubTickCount(int count) the plot and \a outside is the length they will reach outside the plot. If \a outside is greater than zero, the tick labels and axis label will increase their distance to the axis accordingly, so they won't collide with the ticks. - + \see setTickLength, setSubTickLengthIn, setSubTickLengthOut */ void QCPAxis::setSubTickLength(int inside, int outside) { - setSubTickLengthIn(inside); - setSubTickLengthOut(outside); + setSubTickLengthIn(inside); + setSubTickLengthOut(outside); } /*! Sets the length of the inward subticks in pixels. \a inside is the length the subticks will reach inside the plot. - + \see setSubTickLengthOut, setSubTickLength, setTickLength */ void QCPAxis::setSubTickLengthIn(int inside) { - if (mAxisPainter->subTickLengthIn != inside) - { - mAxisPainter->subTickLengthIn = inside; - } + if (mAxisPainter->subTickLengthIn != inside) { + mAxisPainter->subTickLengthIn = inside; + } } /*! Sets the length of the outward subticks in pixels. \a outside is the length the subticks will reach outside the plot. If \a outside is greater than zero, the tick labels will increase their distance to the axis accordingly, so they won't collide with the ticks. - + \see setSubTickLengthIn, setSubTickLength, setTickLength */ void QCPAxis::setSubTickLengthOut(int outside) { - if (mAxisPainter->subTickLengthOut != outside) - { - mAxisPainter->subTickLengthOut = outside; - mCachedMarginValid = false; // only outside tick length can change margin - } + if (mAxisPainter->subTickLengthOut != outside) { + mAxisPainter->subTickLengthOut = outside; + mCachedMarginValid = false; // only outside tick length can change margin + } } /*! Sets the pen, the axis base line is drawn with. - + \see setTickPen, setSubTickPen */ void QCPAxis::setBasePen(const QPen &pen) { - mBasePen = pen; + mBasePen = pen; } /*! Sets the pen, tick marks will be drawn with. - + \see setTickLength, setBasePen */ void QCPAxis::setTickPen(const QPen &pen) { - mTickPen = pen; + mTickPen = pen; } /*! Sets the pen, subtick marks will be drawn with. - + \see setSubTickCount, setSubTickLength, setBasePen */ void QCPAxis::setSubTickPen(const QPen &pen) { - mSubTickPen = pen; + mSubTickPen = pen; } /*! Sets the font of the axis label. - + \see setLabelColor */ void QCPAxis::setLabelFont(const QFont &font) { - if (mLabelFont != font) - { - mLabelFont = font; - mCachedMarginValid = false; - } + if (mLabelFont != font) { + mLabelFont = font; + mCachedMarginValid = false; + } } /*! Sets the color of the axis label. - + \see setLabelFont */ void QCPAxis::setLabelColor(const QColor &color) { - mLabelColor = color; + mLabelColor = color; } /*! @@ -4979,25 +4936,23 @@ void QCPAxis::setLabelColor(const QColor &color) */ void QCPAxis::setLabel(const QString &str) { - if (mLabel != str) - { - mLabel = str; - mCachedMarginValid = false; - } + if (mLabel != str) { + mLabel = str; + mCachedMarginValid = false; + } } /*! Sets the distance between the tick labels and the axis label. - + \see setTickLabelPadding, setPadding */ void QCPAxis::setLabelPadding(int padding) { - if (mAxisPainter->labelPadding != padding) - { - mAxisPainter->labelPadding = padding; - mCachedMarginValid = false; - } + if (mAxisPainter->labelPadding != padding) { + mAxisPainter->labelPadding = padding; + mCachedMarginValid = false; + } } /*! @@ -5005,23 +4960,22 @@ void QCPAxis::setLabelPadding(int padding) When \ref QCPAxisRect::setAutoMargins is enabled, the padding is the additional outer most space, that is left blank. - + The axis padding has no meaning if \ref QCPAxisRect::setAutoMargins is disabled. - + \see setLabelPadding, setTickLabelPadding */ void QCPAxis::setPadding(int padding) { - if (mPadding != padding) - { - mPadding = padding; - mCachedMarginValid = false; - } + if (mPadding != padding) { + mPadding = padding; + mCachedMarginValid = false; + } } /*! Sets the offset the axis has to its axis rect side. - + If an axis rect side has multiple axes and automatic margin calculation is enabled for that side, only the offset of the inner most axis has meaning (even if it is set to be invisible). The offset of the other, outer axes is controlled automatically, to place them at appropriate @@ -5029,139 +4983,135 @@ void QCPAxis::setPadding(int padding) */ void QCPAxis::setOffset(int offset) { - mAxisPainter->offset = offset; + mAxisPainter->offset = offset; } /*! Sets the font that is used for tick labels when they are selected. - + \see setTickLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPAxis::setSelectedTickLabelFont(const QFont &font) { - if (font != mSelectedTickLabelFont) - { - mSelectedTickLabelFont = font; - // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts - } + if (font != mSelectedTickLabelFont) { + mSelectedTickLabelFont = font; + // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts + } } /*! Sets the font that is used for the axis label when it is selected. - + \see setLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPAxis::setSelectedLabelFont(const QFont &font) { - mSelectedLabelFont = font; - // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts + mSelectedLabelFont = font; + // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts } /*! Sets the color that is used for tick labels when they are selected. - + \see setTickLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPAxis::setSelectedTickLabelColor(const QColor &color) { - if (color != mSelectedTickLabelColor) - { - mSelectedTickLabelColor = color; - } + if (color != mSelectedTickLabelColor) { + mSelectedTickLabelColor = color; + } } /*! Sets the color that is used for the axis label when it is selected. - + \see setLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPAxis::setSelectedLabelColor(const QColor &color) { - mSelectedLabelColor = color; + mSelectedLabelColor = color; } /*! Sets the pen that is used to draw the axis base line when selected. - + \see setBasePen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPAxis::setSelectedBasePen(const QPen &pen) { - mSelectedBasePen = pen; + mSelectedBasePen = pen; } /*! Sets the pen that is used to draw the (major) ticks when selected. - + \see setTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPAxis::setSelectedTickPen(const QPen &pen) { - mSelectedTickPen = pen; + mSelectedTickPen = pen; } /*! Sets the pen that is used to draw the subticks when selected. - + \see setSubTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPAxis::setSelectedSubTickPen(const QPen &pen) { - mSelectedSubTickPen = pen; + mSelectedSubTickPen = pen; } /*! Sets the style for the lower axis ending. See the documentation of QCPLineEnding for available styles. - + For horizontal axes, this method refers to the left ending, for vertical axes the bottom ending. Note that this meaning does not change when the axis range is reversed with \ref setRangeReversed. - + \see setUpperEnding */ void QCPAxis::setLowerEnding(const QCPLineEnding &ending) { - mAxisPainter->lowerEnding = ending; + mAxisPainter->lowerEnding = ending; } /*! Sets the style for the upper axis ending. See the documentation of QCPLineEnding for available styles. - + For horizontal axes, this method refers to the right ending, for vertical axes the top ending. Note that this meaning does not change when the axis range is reversed with \ref setRangeReversed. - + \see setLowerEnding */ void QCPAxis::setUpperEnding(const QCPLineEnding &ending) { - mAxisPainter->upperEnding = ending; + mAxisPainter->upperEnding = ending; } /*! If the scale type (\ref setScaleType) is \ref stLinear, \a diff is added to the lower and upper bounds of the range. The range is simply moved by \a diff. - + If the scale type is \ref stLogarithmic, the range bounds are multiplied by \a diff. This corresponds to an apparent "linear" move in logarithmic scaling by a distance of log(diff). */ void QCPAxis::moveRange(double diff) { - QCPRange oldRange = mRange; - if (mScaleType == stLinear) - { - mRange.lower += diff; - mRange.upper += diff; - } else // mScaleType == stLogarithmic - { - mRange.lower *= diff; - mRange.upper *= diff; - } - mCachedMarginValid = false; - emit rangeChanged(mRange); - emit rangeChanged(mRange, oldRange); + QCPRange oldRange = mRange; + if (mScaleType == stLinear) { + mRange.lower += diff; + mRange.upper += diff; + } else { // mScaleType == stLogarithmic + mRange.lower *= diff; + mRange.upper *= diff; + } + mCachedMarginValid = false; + emit rangeChanged(mRange); + emit rangeChanged(mRange, oldRange); } /*! @@ -5172,29 +5122,29 @@ void QCPAxis::moveRange(double diff) */ void QCPAxis::scaleRange(double factor, double center) { - QCPRange oldRange = mRange; - if (mScaleType == stLinear) - { - QCPRange newRange; - newRange.lower = (mRange.lower-center)*factor + center; - newRange.upper = (mRange.upper-center)*factor + center; - if (QCPRange::validRange(newRange)) - mRange = newRange.sanitizedForLinScale(); - } else // mScaleType == stLogarithmic - { - if ((mRange.upper < 0 && center < 0) || (mRange.upper > 0 && center > 0)) // make sure center has same sign as range - { - QCPRange newRange; - newRange.lower = qPow(mRange.lower/center, factor)*center; - newRange.upper = qPow(mRange.upper/center, factor)*center; - if (QCPRange::validRange(newRange)) - mRange = newRange.sanitizedForLogScale(); - } 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); + QCPRange oldRange = mRange; + if (mScaleType == stLinear) { + QCPRange newRange; + newRange.lower = (mRange.lower - center) * factor + center; + newRange.upper = (mRange.upper - center) * factor + center; + if (QCPRange::validRange(newRange)) { + mRange = newRange.sanitizedForLinScale(); + } + } else { // mScaleType == stLogarithmic + if ((mRange.upper < 0 && center < 0) || (mRange.upper > 0 && center > 0)) { // make sure center has same sign as range + QCPRange newRange; + newRange.lower = qPow(mRange.lower / center, factor) * center; + newRange.upper = qPow(mRange.upper / center, factor) * center; + if (QCPRange::validRange(newRange)) { + mRange = newRange.sanitizedForLogScale(); + } + } 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); } /*! @@ -5212,72 +5162,72 @@ void QCPAxis::scaleRange(double factor, double center) */ void QCPAxis::setScaleRatio(const QCPAxis *otherAxis, double ratio) { - int otherPixelSize, ownPixelSize; - - if (otherAxis->orientation() == Qt::Horizontal) - otherPixelSize = otherAxis->axisRect()->width(); - else - otherPixelSize = otherAxis->axisRect()->height(); - - if (orientation() == Qt::Horizontal) - ownPixelSize = axisRect()->width(); - else - ownPixelSize = axisRect()->height(); - - double newRangeSize = ratio*otherAxis->range().size()*ownPixelSize/(double)otherPixelSize; - setRange(range().center(), newRangeSize, Qt::AlignCenter); + int otherPixelSize, ownPixelSize; + + if (otherAxis->orientation() == Qt::Horizontal) { + otherPixelSize = otherAxis->axisRect()->width(); + } else { + otherPixelSize = otherAxis->axisRect()->height(); + } + + if (orientation() == Qt::Horizontal) { + ownPixelSize = axisRect()->width(); + } else { + ownPixelSize = axisRect()->height(); + } + + double newRangeSize = ratio * otherAxis->range().size() * ownPixelSize / (double)otherPixelSize; + setRange(range().center(), newRangeSize, Qt::AlignCenter); } /*! Changes the axis range such that all plottables associated with this axis are fully visible in that dimension. - + \see QCPAbstractPlottable::rescaleAxes, QCustomPlot::rescaleAxes */ void QCPAxis::rescale(bool onlyVisiblePlottables) { - QList p = plottables(); - QCPRange newRange; - bool haveRange = false; - for (int i=0; irealVisibility() && onlyVisiblePlottables) - continue; - QCPRange plottableRange; - bool currentFoundRange; - QCPAbstractPlottable::SignDomain signDomain = QCPAbstractPlottable::sdBoth; - if (mScaleType == stLogarithmic) - signDomain = (mRange.upper < 0 ? QCPAbstractPlottable::sdNegative : QCPAbstractPlottable::sdPositive); - if (p.at(i)->keyAxis() == this) - plottableRange = p.at(i)->getKeyRange(currentFoundRange, signDomain); - else - plottableRange = p.at(i)->getValueRange(currentFoundRange, signDomain); - if (currentFoundRange) - { - if (!haveRange) - newRange = plottableRange; - else - newRange.expand(plottableRange); - haveRange = true; + QList p = plottables(); + QCPRange newRange; + bool haveRange = false; + for (int i = 0; i < p.size(); ++i) { + if (!p.at(i)->realVisibility() && onlyVisiblePlottables) { + continue; + } + QCPRange plottableRange; + bool currentFoundRange; + QCPAbstractPlottable::SignDomain signDomain = QCPAbstractPlottable::sdBoth; + if (mScaleType == stLogarithmic) { + signDomain = (mRange.upper < 0 ? QCPAbstractPlottable::sdNegative : QCPAbstractPlottable::sdPositive); + } + if (p.at(i)->keyAxis() == this) { + plottableRange = p.at(i)->getKeyRange(currentFoundRange, signDomain); + } else { + plottableRange = p.at(i)->getValueRange(currentFoundRange, signDomain); + } + if (currentFoundRange) { + if (!haveRange) { + newRange = plottableRange; + } else { + newRange.expand(plottableRange); + } + haveRange = true; + } } - } - if (haveRange) - { - if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable - { - double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason - if (mScaleType == stLinear) - { - newRange.lower = center-mRange.size()/2.0; - newRange.upper = center+mRange.size()/2.0; - } else // mScaleType == stLogarithmic - { - newRange.lower = center/qSqrt(mRange.upper/mRange.lower); - newRange.upper = center*qSqrt(mRange.upper/mRange.lower); - } + if (haveRange) { + if (!QCPRange::validRange(newRange)) { // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable + double center = (newRange.lower + newRange.upper) * 0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason + if (mScaleType == stLinear) { + newRange.lower = center - mRange.size() / 2.0; + newRange.upper = center + mRange.size() / 2.0; + } else { // mScaleType == stLogarithmic + newRange.lower = center / qSqrt(mRange.upper / mRange.lower); + newRange.upper = center * qSqrt(mRange.upper / mRange.lower); + } + } + setRange(newRange); } - setRange(newRange); - } } /*! @@ -5285,37 +5235,35 @@ void QCPAxis::rescale(bool onlyVisiblePlottables) */ double QCPAxis::pixelToCoord(double value) const { - if (orientation() == Qt::Horizontal) - { - if (mScaleType == stLinear) - { - if (!mRangeReversed) - return (value-mAxisRect->left())/(double)mAxisRect->width()*mRange.size()+mRange.lower; - else - return -(value-mAxisRect->left())/(double)mAxisRect->width()*mRange.size()+mRange.upper; - } else // mScaleType == stLogarithmic - { - if (!mRangeReversed) - return qPow(mRange.upper/mRange.lower, (value-mAxisRect->left())/(double)mAxisRect->width())*mRange.lower; - else - return qPow(mRange.upper/mRange.lower, (mAxisRect->left()-value)/(double)mAxisRect->width())*mRange.upper; + if (orientation() == Qt::Horizontal) { + if (mScaleType == stLinear) { + if (!mRangeReversed) { + return (value - mAxisRect->left()) / (double)mAxisRect->width() * mRange.size() + mRange.lower; + } else { + return -(value - mAxisRect->left()) / (double)mAxisRect->width() * mRange.size() + mRange.upper; + } + } else { // mScaleType == stLogarithmic + if (!mRangeReversed) { + return qPow(mRange.upper / mRange.lower, (value - mAxisRect->left()) / (double)mAxisRect->width()) * mRange.lower; + } else { + return qPow(mRange.upper / mRange.lower, (mAxisRect->left() - value) / (double)mAxisRect->width()) * mRange.upper; + } + } + } else { // orientation() == Qt::Vertical + if (mScaleType == stLinear) { + if (!mRangeReversed) { + return (mAxisRect->bottom() - value) / (double)mAxisRect->height() * mRange.size() + mRange.lower; + } else { + return -(mAxisRect->bottom() - value) / (double)mAxisRect->height() * mRange.size() + mRange.upper; + } + } else { // mScaleType == stLogarithmic + if (!mRangeReversed) { + return qPow(mRange.upper / mRange.lower, (mAxisRect->bottom() - value) / (double)mAxisRect->height()) * mRange.lower; + } else { + return qPow(mRange.upper / mRange.lower, (value - mAxisRect->bottom()) / (double)mAxisRect->height()) * mRange.upper; + } + } } - } else // orientation() == Qt::Vertical - { - if (mScaleType == stLinear) - { - if (!mRangeReversed) - return (mAxisRect->bottom()-value)/(double)mAxisRect->height()*mRange.size()+mRange.lower; - else - return -(mAxisRect->bottom()-value)/(double)mAxisRect->height()*mRange.size()+mRange.upper; - } else // mScaleType == stLogarithmic - { - if (!mRangeReversed) - return qPow(mRange.upper/mRange.lower, (mAxisRect->bottom()-value)/(double)mAxisRect->height())*mRange.lower; - else - return qPow(mRange.upper/mRange.lower, (value-mAxisRect->bottom())/(double)mAxisRect->height())*mRange.upper; - } - } } /*! @@ -5323,152 +5271,157 @@ double QCPAxis::pixelToCoord(double value) const */ double QCPAxis::coordToPixel(double value) const { - if (orientation() == Qt::Horizontal) - { - if (mScaleType == stLinear) - { - if (!mRangeReversed) - return (value-mRange.lower)/mRange.size()*mAxisRect->width()+mAxisRect->left(); - else - return (mRange.upper-value)/mRange.size()*mAxisRect->width()+mAxisRect->left(); - } else // mScaleType == stLogarithmic - { - if (value >= 0 && mRange.upper < 0) // invalid value for logarithmic scale, just draw it outside visible range - return !mRangeReversed ? mAxisRect->right()+200 : mAxisRect->left()-200; - else if (value <= 0 && mRange.upper > 0) // invalid value for logarithmic scale, just draw it outside visible range - return !mRangeReversed ? mAxisRect->left()-200 : mAxisRect->right()+200; - else - { - if (!mRangeReversed) - return baseLog(value/mRange.lower)/baseLog(mRange.upper/mRange.lower)*mAxisRect->width()+mAxisRect->left(); - else - return baseLog(mRange.upper/value)/baseLog(mRange.upper/mRange.lower)*mAxisRect->width()+mAxisRect->left(); - } + if (orientation() == Qt::Horizontal) { + if (mScaleType == stLinear) { + if (!mRangeReversed) { + return (value - mRange.lower) / mRange.size() * mAxisRect->width() + mAxisRect->left(); + } else { + return (mRange.upper - value) / mRange.size() * mAxisRect->width() + mAxisRect->left(); + } + } else { // mScaleType == stLogarithmic + if (value >= 0 && mRange.upper < 0) { // invalid value for logarithmic scale, just draw it outside visible range + return !mRangeReversed ? mAxisRect->right() + 200 : mAxisRect->left() - 200; + } else if (value <= 0 && mRange.upper > 0) { // invalid value for logarithmic scale, just draw it outside visible range + return !mRangeReversed ? mAxisRect->left() - 200 : mAxisRect->right() + 200; + } else { + if (!mRangeReversed) { + return baseLog(value / mRange.lower) / baseLog(mRange.upper / mRange.lower) * mAxisRect->width() + mAxisRect->left(); + } else { + return baseLog(mRange.upper / value) / baseLog(mRange.upper / mRange.lower) * mAxisRect->width() + mAxisRect->left(); + } + } + } + } else { // orientation() == Qt::Vertical + if (mScaleType == stLinear) { + if (!mRangeReversed) { + return mAxisRect->bottom() - (value - mRange.lower) / mRange.size() * mAxisRect->height(); + } else { + return mAxisRect->bottom() - (mRange.upper - value) / mRange.size() * mAxisRect->height(); + } + } else { // mScaleType == stLogarithmic + if (value >= 0 && mRange.upper < 0) { // invalid value for logarithmic scale, just draw it outside visible range + return !mRangeReversed ? mAxisRect->top() - 200 : mAxisRect->bottom() + 200; + } else if (value <= 0 && mRange.upper > 0) { // invalid value for logarithmic scale, just draw it outside visible range + return !mRangeReversed ? mAxisRect->bottom() + 200 : mAxisRect->top() - 200; + } else { + if (!mRangeReversed) { + return mAxisRect->bottom() - baseLog(value / mRange.lower) / baseLog(mRange.upper / mRange.lower) * mAxisRect->height(); + } else { + return mAxisRect->bottom() - baseLog(mRange.upper / value) / baseLog(mRange.upper / mRange.lower) * mAxisRect->height(); + } + } + } } - } else // orientation() == Qt::Vertical - { - if (mScaleType == stLinear) - { - if (!mRangeReversed) - return mAxisRect->bottom()-(value-mRange.lower)/mRange.size()*mAxisRect->height(); - else - return mAxisRect->bottom()-(mRange.upper-value)/mRange.size()*mAxisRect->height(); - } else // mScaleType == stLogarithmic - { - if (value >= 0 && mRange.upper < 0) // invalid value for logarithmic scale, just draw it outside visible range - return !mRangeReversed ? mAxisRect->top()-200 : mAxisRect->bottom()+200; - else if (value <= 0 && mRange.upper > 0) // invalid value for logarithmic scale, just draw it outside visible range - return !mRangeReversed ? mAxisRect->bottom()+200 : mAxisRect->top()-200; - else - { - if (!mRangeReversed) - return mAxisRect->bottom()-baseLog(value/mRange.lower)/baseLog(mRange.upper/mRange.lower)*mAxisRect->height(); - else - return mAxisRect->bottom()-baseLog(mRange.upper/value)/baseLog(mRange.upper/mRange.lower)*mAxisRect->height(); - } - } - } } /*! Returns the part of the axis that is hit by \a pos (in pixels). The return value of this function is independent of the user-selectable parts defined with \ref setSelectableParts. Further, this function does not change the current selection state of the axis. - + If the axis is not visible (\ref setVisible), this function always returns \ref spNone. - + \see setSelectedParts, setSelectableParts, QCustomPlot::setInteractions */ QCPAxis::SelectablePart QCPAxis::getPartAt(const QPointF &pos) const { - if (!mVisible) - return spNone; - - if (mAxisPainter->axisSelectionBox().contains(pos.toPoint())) - return spAxis; - else if (mAxisPainter->tickLabelsSelectionBox().contains(pos.toPoint())) - return spTickLabels; - else if (mAxisPainter->labelSelectionBox().contains(pos.toPoint())) - return spAxisLabel; - else - return spNone; + if (!mVisible) { + return spNone; + } + + if (mAxisPainter->axisSelectionBox().contains(pos.toPoint())) { + return spAxis; + } else if (mAxisPainter->tickLabelsSelectionBox().contains(pos.toPoint())) { + return spTickLabels; + } else if (mAxisPainter->labelSelectionBox().contains(pos.toPoint())) { + return spAxisLabel; + } else { + return spNone; + } } /* inherits documentation from base class */ double QCPAxis::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { - if (!mParentPlot) return -1; - SelectablePart part = getPartAt(pos); - if ((onlySelectable && !mSelectableParts.testFlag(part)) || part == spNone) - return -1; - - if (details) - details->setValue(part); - return mParentPlot->selectionTolerance()*0.99; + if (!mParentPlot) { + return -1; + } + SelectablePart part = getPartAt(pos); + if ((onlySelectable && !mSelectableParts.testFlag(part)) || part == spNone) { + return -1; + } + + if (details) { + details->setValue(part); + } + return mParentPlot->selectionTolerance() * 0.99; } /*! Returns a list of all the plottables that have this axis as key or value axis. - + If you are only interested in plottables of type QCPGraph, see \ref graphs. - + \see graphs, items */ -QList QCPAxis::plottables() const +QList QCPAxis::plottables() const { - QList result; - if (!mParentPlot) return result; - - for (int i=0; imPlottables.size(); ++i) - { - if (mParentPlot->mPlottables.at(i)->keyAxis() == this ||mParentPlot->mPlottables.at(i)->valueAxis() == this) - result.append(mParentPlot->mPlottables.at(i)); - } - return result; + QList result; + if (!mParentPlot) { + return result; + } + + for (int i = 0; i < mParentPlot->mPlottables.size(); ++i) { + if (mParentPlot->mPlottables.at(i)->keyAxis() == this || mParentPlot->mPlottables.at(i)->valueAxis() == this) { + result.append(mParentPlot->mPlottables.at(i)); + } + } + return result; } /*! Returns a list of all the graphs that have this axis as key or value axis. - + \see plottables, items */ -QList QCPAxis::graphs() const +QList QCPAxis::graphs() const { - QList result; - if (!mParentPlot) return result; - - for (int i=0; imGraphs.size(); ++i) - { - if (mParentPlot->mGraphs.at(i)->keyAxis() == this || mParentPlot->mGraphs.at(i)->valueAxis() == this) - result.append(mParentPlot->mGraphs.at(i)); - } - return result; + QList result; + if (!mParentPlot) { + return result; + } + + for (int i = 0; i < mParentPlot->mGraphs.size(); ++i) { + if (mParentPlot->mGraphs.at(i)->keyAxis() == this || mParentPlot->mGraphs.at(i)->valueAxis() == this) { + result.append(mParentPlot->mGraphs.at(i)); + } + } + return result; } /*! Returns a list of all the items that are associated with this axis. An item is considered associated with an axis if at least one of its positions uses the axis as key or value axis. - + \see plottables, graphs */ -QList QCPAxis::items() const +QList QCPAxis::items() const { - QList result; - if (!mParentPlot) return result; - - for (int itemId=0; itemIdmItems.size(); ++itemId) - { - QList positions = mParentPlot->mItems.at(itemId)->positions(); - for (int posId=0; posIdkeyAxis() == this || positions.at(posId)->valueAxis() == this) - { - result.append(mParentPlot->mItems.at(itemId)); - break; - } + QList result; + if (!mParentPlot) { + return result; } - } - return result; + + for (int itemId = 0; itemId < mParentPlot->mItems.size(); ++itemId) { + QList positions = mParentPlot->mItems.at(itemId)->positions(); + for (int posId = 0; posId < positions.size(); ++posId) { + if (positions.at(posId)->keyAxis() == this || positions.at(posId)->valueAxis() == this) { + result.append(mParentPlot->mItems.at(itemId)); + break; + } + } + } + return result; } /*! @@ -5477,16 +5430,20 @@ QList QCPAxis::items() const */ QCPAxis::AxisType QCPAxis::marginSideToAxisType(QCP::MarginSide side) { - switch (side) - { - case QCP::msLeft: return atLeft; - case QCP::msRight: return atRight; - case QCP::msTop: return atTop; - case QCP::msBottom: return atBottom; - default: break; - } - qDebug() << Q_FUNC_INFO << "Invalid margin side passed:" << (int)side; - return atLeft; + switch (side) { + case QCP::msLeft: + return atLeft; + case QCP::msRight: + return atRight; + case QCP::msTop: + return atTop; + case QCP::msBottom: + return atBottom; + default: + break; + } + qDebug() << Q_FUNC_INFO << "Invalid margin side passed:" << (int)side; + return atLeft; } /*! @@ -5494,18 +5451,28 @@ QCPAxis::AxisType QCPAxis::marginSideToAxisType(QCP::MarginSide side) */ QCPAxis::AxisType QCPAxis::opposite(QCPAxis::AxisType type) { - switch (type) - { - case atLeft: return atRight; break; - case atRight: return atLeft; break; - case atBottom: return atTop; break; - case atTop: return atBottom; break; - default: qDebug() << Q_FUNC_INFO << "invalid axis type"; return atLeft; break; - } + switch (type) { + case atLeft: + return atRight; + break; + case atRight: + return atLeft; + break; + case atBottom: + return atTop; + break; + case atTop: + return atBottom; + break; + default: + qDebug() << Q_FUNC_INFO << "invalid axis type"; + return atLeft; + break; + } } /*! \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 @@ -5513,168 +5480,158 @@ QCPAxis::AxisType QCPAxis::opposite(QCPAxis::AxisType type) */ 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; + if (!mParentPlot) { + return; + } + if ((!mTicks && !mTickLabels && !mGrid->visible()) || mRange.size() <= 0) { + return; } - 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) - { + // 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); + 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); + 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()); + } } - } 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 (mScaleType == stLinear) { + if (mAutoTickStep) { + // Generate tick positions according to linear scaling: + mTickStep = mRange.size() / (double)(mAutoTickCount + 1e-10); // mAutoTickCount ticks on average, the small addition is to prevent jitter on exact integers + double magnitudeFactor = qPow(10.0, qFloor(qLn(mTickStep) / qLn(10.0))); // get magnitude factor e.g. 0.01, 1, 10, 1000 etc. + double tickStepMantissa = mTickStep / magnitudeFactor; + if (tickStepMantissa < 5) { + // round digit after decimal point to 0.5 + mTickStep = (int)(tickStepMantissa * 2) / 2.0 * magnitudeFactor; + } else { + // round to first digit in multiples of 2 + mTickStep = (int)(tickStepMantissa / 2.0) * 2.0 * magnitudeFactor; + } + } + if (mAutoSubTicks) { + mSubTickCount = calculateAutoSubTickCount(mTickStep); + } + // Generate tick positions according to mTickStep: + qint64 firstStep = floor(mRange.lower / mTickStep); // do not use qFloor here, or we'll lose 64 bit precision + qint64 lastStep = ceil(mRange.upper / mTickStep); // do not use qCeil here, or we'll lose 64 bit precision + int tickcount = lastStep - firstStep + 1; + if (tickcount < 0) { + tickcount = 0; + } + mTickVector.resize(tickcount); + for (int i = 0; i < tickcount; ++i) { + mTickVector[i] = (firstStep + i) * mTickStep; + } + } else { // mScaleType == stLogarithmic + // Generate tick positions according to logbase scaling: + if (mRange.lower > 0 && mRange.upper > 0) { // positive range + double lowerMag = basePow(qFloor(baseLog(mRange.lower))); + double currentMag = lowerMag; + mTickVector.clear(); + mTickVector.append(currentMag); + while (currentMag < mRange.upper && currentMag > 0) { // currentMag might be zero for ranges ~1e-300, just cancel in that case + currentMag *= mScaleLogBase; + mTickVector.append(currentMag); + } + } else if (mRange.lower < 0 && mRange.upper < 0) { // negative range + double lowerMag = -basePow(qCeil(baseLog(-mRange.lower))); + double currentMag = lowerMag; + mTickVector.clear(); + mTickVector.append(currentMag); + while (currentMag < mRange.upper && currentMag < 0) { // currentMag might be zero for ranges ~1e-300, just cancel in that case + currentMag /= mScaleLogBase; + mTickVector.append(currentMag); + } + } else { // invalid range for logarithmic scale, because lower and upper have different sign + mTickVector.clear(); + qDebug() << Q_FUNC_INFO << "Invalid range for logarithmic plot: " << mRange.lower << "-" << mRange.upper; + } } - 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 @@ -5682,81 +5639,114 @@ void QCPAxis::generateAutoTicks() */ 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 + 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 } - } 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; + + return result; } /* inherits documentation from base class */ void QCPAxis::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) { - Q_UNUSED(event) - SelectablePart part = details.value(); - if (mSelectableParts.testFlag(part)) - { - SelectableParts selBefore = mSelectedParts; - setSelectedParts(additive ? mSelectedParts^part : part); - if (selectionStateChanged) - *selectionStateChanged = mSelectedParts != selBefore; - } + Q_UNUSED(event) + SelectablePart part = details.value(); + if (mSelectableParts.testFlag(part)) { + SelectableParts selBefore = mSelectedParts; + setSelectedParts(additive ? mSelectedParts ^part : part); + if (selectionStateChanged) { + *selectionStateChanged = mSelectedParts != selBefore; + } + } } /* inherits documentation from base class */ void QCPAxis::deselectEvent(bool *selectionStateChanged) { - SelectableParts selBefore = mSelectedParts; - setSelectedParts(mSelectedParts & ~mSelectableParts); - if (selectionStateChanged) - *selectionStateChanged = mSelectedParts != selBefore; + SelectableParts selBefore = mSelectedParts; + setSelectedParts(mSelectedParts & ~mSelectableParts); + if (selectionStateChanged) { + *selectionStateChanged = mSelectedParts != selBefore; + } } /*! \internal @@ -5765,82 +5755,81 @@ void QCPAxis::deselectEvent(bool *selectionStateChanged) before drawing axis lines. This is the antialiasing state the painter passed to the \ref draw method is in by default. - + 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 */ void QCPAxis::applyDefaultAntialiasingHint(QCPPainter *painter) const { - applyAntialiasingHint(painter, mAntialiased, QCP::aeAxes); + applyAntialiasingHint(painter, mAntialiased, QCP::aeAxes); } /*! \internal - + Draws the axis with the specified \a painter, using the internal QCPAxisPainterPrivate instance. */ 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); - subTickPositions.reserve(mSubTickVector.size()); - - if (mTicks) - { - for (int i=lowTick; i<=highTick; ++i) - { - tickPositions.append(coordToPixel(mTickVector.at(i))); - if (mTickLabels) - tickLabels.append(mTickVectorLabels.at(i)); + 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); + subTickPositions.reserve(mSubTickVector.size()); + + if (mTicks) { + for (int i = lowTick; i <= highTick; ++i) { + tickPositions.append(coordToPixel(mTickVector.at(i))); + if (mTickLabels) { + tickLabels.append(mTickVectorLabels.at(i)); + } + } + + if (mSubTickCount > 0) { + const int subTickCount = mSubTickVector.size(); + for (int i = 0; i < subTickCount; ++i) { // no need to check bounds because subticks are always only created inside current mRange + subTickPositions.append(coordToPixel(mSubTickVector.at(i))); + } + } } - - if (mSubTickCount > 0) - { - const int subTickCount = mSubTickVector.size(); - for (int i=0; itype = mAxisType; - mAxisPainter->basePen = getBasePen(); - mAxisPainter->labelFont = getLabelFont(); - mAxisPainter->labelColor = getLabelColor(); - mAxisPainter->label = mLabel; - mAxisPainter->substituteExponent = mAutoTickLabels && mNumberBeautifulPowers && mTickLabelType == ltNumber; - mAxisPainter->tickPen = getTickPen(); - mAxisPainter->subTickPen = getSubTickPen(); - mAxisPainter->tickLabelFont = getTickLabelFont(); - mAxisPainter->tickLabelColor = getTickLabelColor(); - mAxisPainter->axisRect = mAxisRect->rect(); - mAxisPainter->viewportRect = mParentPlot->viewport(); - mAxisPainter->abbreviateDecimalPowers = mScaleType == stLogarithmic; - mAxisPainter->reversedEndings = mRangeReversed; - mAxisPainter->tickPositions = tickPositions; - mAxisPainter->tickLabels = tickLabels; - mAxisPainter->subTickPositions = subTickPositions; - mAxisPainter->draw(painter); + // transfer all properties of this axis to QCPAxisPainterPrivate which it needs to draw the axis. + // Note that some axis painter properties are already set by direct feed-through with QCPAxis setters + mAxisPainter->type = mAxisType; + mAxisPainter->basePen = getBasePen(); + mAxisPainter->labelFont = getLabelFont(); + mAxisPainter->labelColor = getLabelColor(); + mAxisPainter->label = mLabel; + mAxisPainter->substituteExponent = mAutoTickLabels && mNumberBeautifulPowers && mTickLabelType == ltNumber; + mAxisPainter->tickPen = getTickPen(); + mAxisPainter->subTickPen = getSubTickPen(); + mAxisPainter->tickLabelFont = getTickLabelFont(); + mAxisPainter->tickLabelColor = getTickLabelColor(); + mAxisPainter->axisRect = mAxisRect->rect(); + mAxisPainter->viewportRect = mParentPlot->viewport(); + mAxisPainter->abbreviateDecimalPowers = mScaleType == stLogarithmic; + mAxisPainter->reversedEndings = mRangeReversed; + mAxisPainter->tickPositions = tickPositions; + mAxisPainter->tickLabels = tickLabels; + mAxisPainter->subTickPositions = subTickPositions; + mAxisPainter->draw(painter); } /*! \internal - + Returns via \a lowIndex and \a highIndex, which ticks in the current tick vector are visible in the current range. The return values are indices of the tick vector, not the positions of the ticks themselves. - + The actual use of this function is when an external tick vector is provided, since it might exceed far beyond the currently displayed range, and would cause unnecessary calculations e.g. of subticks. - + If all ticks are outside the axis range, an inverted range is returned, i.e. highIndex will be smaller than lowIndex. There is one case, where this function returns indices that are not really visible in the current axis range: When the tick spacing is larger than the axis range size and @@ -5849,193 +5838,191 @@ void QCPAxis::draw(QCPPainter *painter) */ void QCPAxis::visibleTickBounds(int &lowIndex, int &highIndex) const { - bool lowFound = false; - bool highFound = false; - lowIndex = 0; - highIndex = -1; - - for (int i=0; i < mTickVector.size(); ++i) - { - if (mTickVector.at(i) >= mRange.lower) - { - lowFound = true; - lowIndex = i; - break; + bool lowFound = false; + bool highFound = false; + lowIndex = 0; + highIndex = -1; + + for (int i = 0; i < mTickVector.size(); ++i) { + if (mTickVector.at(i) >= mRange.lower) { + lowFound = true; + lowIndex = i; + break; + } } - } - for (int i=mTickVector.size()-1; i >= 0; --i) - { - if (mTickVector.at(i) <= mRange.upper) - { - highFound = true; - highIndex = i; - break; + 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; } - } - - 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; + 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); + return qPow(mScaleLogBase, value); } /*! \internal - + Returns the pen that is used to draw the axis base line. Depending on the selection state, this is either mSelectedBasePen or mBasePen. */ QPen QCPAxis::getBasePen() const { - return mSelectedParts.testFlag(spAxis) ? mSelectedBasePen : mBasePen; + return mSelectedParts.testFlag(spAxis) ? mSelectedBasePen : mBasePen; } /*! \internal - + Returns the pen that is used to draw the (major) ticks. Depending on the selection state, this is either mSelectedTickPen or mTickPen. */ QPen QCPAxis::getTickPen() const { - return mSelectedParts.testFlag(spAxis) ? mSelectedTickPen : mTickPen; + return mSelectedParts.testFlag(spAxis) ? mSelectedTickPen : mTickPen; } /*! \internal - + Returns the pen that is used to draw the subticks. Depending on the selection state, this is either mSelectedSubTickPen or mSubTickPen. */ QPen QCPAxis::getSubTickPen() const { - return mSelectedParts.testFlag(spAxis) ? mSelectedSubTickPen : mSubTickPen; + return mSelectedParts.testFlag(spAxis) ? mSelectedSubTickPen : mSubTickPen; } /*! \internal - + Returns the font that is used to draw the tick labels. Depending on the selection state, this is either mSelectedTickLabelFont or mTickLabelFont. */ QFont QCPAxis::getTickLabelFont() const { - return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelFont : mTickLabelFont; + return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelFont : mTickLabelFont; } /*! \internal - + Returns the font that is used to draw the axis label. Depending on the selection state, this is either mSelectedLabelFont or mLabelFont. */ QFont QCPAxis::getLabelFont() const { - return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelFont : mLabelFont; + return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelFont : mLabelFont; } /*! \internal - + Returns the color that is used to draw the tick labels. Depending on the selection state, this is either mSelectedTickLabelColor or mTickLabelColor. */ QColor QCPAxis::getTickLabelColor() const { - return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelColor : mTickLabelColor; + return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelColor : mTickLabelColor; } /*! \internal - + Returns the color that is used to draw the axis label. Depending on the selection state, this is either mSelectedLabelColor or mLabelColor. */ QColor QCPAxis::getLabelColor() const { - return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelColor : mLabelColor; + return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelColor : mLabelColor; } /*! \internal - + Returns the appropriate outward margin for this axis. It is needed if \ref QCPAxisRect::setAutoMargins is set to true on the parent axis rect. An axis with axis type \ref atLeft will return an appropriate left margin, \ref atBottom will return an appropriate bottom margin and so forth. For the calculation, this function goes through similar steps as \ref draw, so changing one function likely requires the modification of the other one as well. - + The margin consists of the outward tick length, tick label padding, tick label size, label padding, label size, and padding. - + The margin is cached internally, so repeated calls while leaving the axis range, fonts, etc. unchanged are very fast. */ int QCPAxis::calculateMargin() { - if (!mVisible) // if not visible, directly return 0, don't cache 0 because we can't react to setVisible in QCPAxis - return 0; - - if (mCachedMarginValid) - return mCachedMargin; - - // run through similar steps as QCPAxis::draw, and caluclate 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); - if (mTicks) - { - for (int i=lowTick; i<=highTick; ++i) - { - tickPositions.append(coordToPixel(mTickVector.at(i))); - if (mTickLabels) - tickLabels.append(mTickVectorLabels.at(i)); + if (!mVisible) { // if not visible, directly return 0, don't cache 0 because we can't react to setVisible in QCPAxis + return 0; } - } - // transfer all properties of this axis to QCPAxisPainterPrivate which it needs to calculate the size. - // Note that some axis painter properties are already set by direct feed-through with QCPAxis setters - mAxisPainter->type = mAxisType; - mAxisPainter->labelFont = getLabelFont(); - mAxisPainter->label = mLabel; - mAxisPainter->tickLabelFont = mTickLabelFont; - mAxisPainter->axisRect = mAxisRect->rect(); - mAxisPainter->viewportRect = mParentPlot->viewport(); - mAxisPainter->tickPositions = tickPositions; - mAxisPainter->tickLabels = tickLabels; - margin += mAxisPainter->size(); - margin += mPadding; - mCachedMargin = margin; - mCachedMarginValid = true; - return margin; + if (mCachedMarginValid) { + return mCachedMargin; + } + + // run through similar steps as QCPAxis::draw, and caluclate 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); + if (mTicks) { + for (int i = lowTick; i <= highTick; ++i) { + tickPositions.append(coordToPixel(mTickVector.at(i))); + if (mTickLabels) { + tickLabels.append(mTickVectorLabels.at(i)); + } + } + } + // transfer all properties of this axis to QCPAxisPainterPrivate which it needs to calculate the size. + // Note that some axis painter properties are already set by direct feed-through with QCPAxis setters + mAxisPainter->type = mAxisType; + mAxisPainter->labelFont = getLabelFont(); + mAxisPainter->label = mLabel; + mAxisPainter->tickLabelFont = mTickLabelFont; + mAxisPainter->axisRect = mAxisRect->rect(); + mAxisPainter->viewportRect = mParentPlot->viewport(); + mAxisPainter->tickPositions = tickPositions; + mAxisPainter->tickLabels = tickLabels; + margin += mAxisPainter->size(); + margin += mPadding; + + mCachedMargin = margin; + mCachedMarginValid = true; + return margin; } /* inherits documentation from base class */ QCP::Interaction QCPAxis::selectionCategory() const { - return QCP::iSelectAxes; + return QCP::iSelectAxes; } @@ -6047,9 +6034,9 @@ QCP::Interaction QCPAxis::selectionCategory() const \internal \brief (Private) - + This is a private class and not part of the public QCustomPlot interface. - + It is used by QCPAxis to do the low-level drawing of axis backbone, tick marks, tick labels and axis label. It also buffers the labels to reduce replot times. The parameters are configured by directly accessing the public member variables. @@ -6060,27 +6047,27 @@ QCP::Interaction QCPAxis::selectionCategory() const redraw, to utilize the caching mechanisms. */ QCPAxisPainterPrivate::QCPAxisPainterPrivate(QCustomPlot *parentPlot) : - type(QCPAxis::atLeft), - basePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), - lowerEnding(QCPLineEnding::esNone), - upperEnding(QCPLineEnding::esNone), - labelPadding(0), - tickLabelPadding(0), - tickLabelRotation(0), - tickLabelSide(QCPAxis::lsOutside), - substituteExponent(true), - numberMultiplyCross(false), - tickLengthIn(5), - tickLengthOut(0), - subTickLengthIn(2), - subTickLengthOut(0), - tickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), - subTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), - offset(0), - abbreviateDecimalPowers(false), - reversedEndings(false), - mParentPlot(parentPlot), - mLabelCache(16) // cache at most 16 (tick) labels + type(QCPAxis::atLeft), + basePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), + lowerEnding(QCPLineEnding::esNone), + upperEnding(QCPLineEnding::esNone), + labelPadding(0), + tickLabelPadding(0), + tickLabelRotation(0), + tickLabelSide(QCPAxis::lsOutside), + substituteExponent(true), + numberMultiplyCross(false), + tickLengthIn(5), + tickLengthOut(0), + subTickLengthIn(2), + subTickLengthOut(0), + tickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), + subTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), + offset(0), + abbreviateDecimalPowers(false), + reversedEndings(false), + mParentPlot(parentPlot), + mLabelCache(16) // cache at most 16 (tick) labels { } @@ -6089,251 +6076,256 @@ QCPAxisPainterPrivate::~QCPAxisPainterPrivate() } /*! \internal - + Draws the axis with the specified \a painter. - + The selection boxes (mAxisSelectionBox, mTickLabelsSelectionBox, mLabelSelectionBox) are set here, too. */ void QCPAxisPainterPrivate::draw(QCPPainter *painter) { - QByteArray newHash = generateLabelParameterHash(); - if (newHash != mLabelParameterHash) - { - mLabelCache.clear(); - mLabelParameterHash = newHash; - } - - QPoint origin; - switch (type) - { - case QCPAxis::atLeft: origin = axisRect.bottomLeft() +QPoint(-offset, 0); break; - case QCPAxis::atRight: origin = axisRect.bottomRight()+QPoint(+offset, 0); break; - case QCPAxis::atTop: origin = axisRect.topLeft() +QPoint(0, -offset); break; - case QCPAxis::atBottom: origin = axisRect.bottomLeft() +QPoint(0, +offset); break; - } + QByteArray newHash = generateLabelParameterHash(); + if (newHash != mLabelParameterHash) { + mLabelCache.clear(); + mLabelParameterHash = newHash; + } - double xCor = 0, yCor = 0; // paint system correction, for pixel exact matches (affects baselines and ticks of top/right axes) - switch (type) - { - case QCPAxis::atTop: yCor = -1; break; - case QCPAxis::atRight: xCor = 1; break; - default: break; - } - int margin = 0; - // draw baseline: - QLineF baseLine; - painter->setPen(basePen); - if (QCPAxis::orientation(type) == Qt::Horizontal) - baseLine.setPoints(origin+QPointF(xCor, yCor), origin+QPointF(axisRect.width()+xCor, yCor)); - else - baseLine.setPoints(origin+QPointF(xCor, yCor), origin+QPointF(xCor, -axisRect.height()+yCor)); - if (reversedEndings) - baseLine = QLineF(baseLine.p2(), baseLine.p1()); // won't make a difference for line itself, but for line endings later - painter->drawLine(baseLine); - - // draw ticks: - if (!tickPositions.isEmpty()) - { - painter->setPen(tickPen); - int tickDir = (type == QCPAxis::atBottom || type == QCPAxis::atRight) ? -1 : 1; // direction of ticks ("inward" is right for left axis and left for right axis) - if (QCPAxis::orientation(type) == Qt::Horizontal) - { - for (int i=0; idrawLine(QLineF(tickPositions.at(i)+xCor, origin.y()-tickLengthOut*tickDir+yCor, tickPositions.at(i)+xCor, origin.y()+tickLengthIn*tickDir+yCor)); - } else - { - for (int i=0; idrawLine(QLineF(origin.x()-tickLengthOut*tickDir+xCor, tickPositions.at(i)+yCor, origin.x()+tickLengthIn*tickDir+xCor, tickPositions.at(i)+yCor)); + QPoint origin; + switch (type) { + case QCPAxis::atLeft: + origin = axisRect.bottomLeft() + QPoint(-offset, 0); + break; + case QCPAxis::atRight: + origin = axisRect.bottomRight() + QPoint(+offset, 0); + break; + case QCPAxis::atTop: + origin = axisRect.topLeft() + QPoint(0, -offset); + break; + case QCPAxis::atBottom: + origin = axisRect.bottomLeft() + QPoint(0, +offset); + break; } - } - - // draw subticks: - if (!subTickPositions.isEmpty()) - { - painter->setPen(subTickPen); - // direction of ticks ("inward" is right for left axis and left for right axis) - int tickDir = (type == QCPAxis::atBottom || type == QCPAxis::atRight) ? -1 : 1; - if (QCPAxis::orientation(type) == Qt::Horizontal) - { - for (int i=0; idrawLine(QLineF(subTickPositions.at(i)+xCor, origin.y()-subTickLengthOut*tickDir+yCor, subTickPositions.at(i)+xCor, origin.y()+subTickLengthIn*tickDir+yCor)); - } else - { - for (int i=0; idrawLine(QLineF(origin.x()-subTickLengthOut*tickDir+xCor, subTickPositions.at(i)+yCor, origin.x()+subTickLengthIn*tickDir+xCor, subTickPositions.at(i)+yCor)); + + double xCor = 0, yCor = 0; // paint system correction, for pixel exact matches (affects baselines and ticks of top/right axes) + switch (type) { + case QCPAxis::atTop: + yCor = -1; + break; + case QCPAxis::atRight: + xCor = 1; + break; + default: + break; } - } - margin += qMax(0, qMax(tickLengthOut, subTickLengthOut)); - - // draw axis base endings: - bool antialiasingBackup = painter->antialiasing(); - painter->setAntialiasing(true); // always want endings to be antialiased, even if base and ticks themselves aren't - painter->setBrush(QBrush(basePen.color())); - QVector2D baseLineVector(baseLine.dx(), baseLine.dy()); - if (lowerEnding.style() != QCPLineEnding::esNone) - lowerEnding.draw(painter, QVector2D(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); - painter->setAntialiasing(antialiasingBackup); - - // tick labels: - QRect oldClipRect; - if (tickLabelSide == QCPAxis::lsInside) // if using inside labels, clip them to the axis rect - { - oldClipRect = painter->clipRegion().boundingRect(); - painter->setClipRect(axisRect); - } - QSize tickLabelsSize(0, 0); // size of largest tick label, for offset calculation of axis label - if (!tickLabels.isEmpty()) - { - if (tickLabelSide == QCPAxis::lsOutside) - margin += tickLabelPadding; - painter->setFont(tickLabelFont); - painter->setPen(QPen(tickLabelColor)); - const int maxLabelIndex = qMin(tickPositions.size(), tickLabels.size()); - int distanceToAxis = margin; - if (tickLabelSide == QCPAxis::lsInside) - distanceToAxis = -(qMax(tickLengthIn, subTickLengthIn)+tickLabelPadding); - for (int i=0; isetClipRect(oldClipRect); - - // axis label: - QRect labelBounds; - if (!label.isEmpty()) - { - margin += labelPadding; - painter->setFont(labelFont); - painter->setPen(QPen(labelColor)); - labelBounds = painter->fontMetrics().boundingRect(0, 0, 0, 0, Qt::TextDontClip, label); - if (type == QCPAxis::atLeft) - { - QTransform oldTransform = painter->transform(); - painter->translate((origin.x()-margin-labelBounds.height()), origin.y()); - painter->rotate(-90); - painter->drawText(0, 0, axisRect.height(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label); - painter->setTransform(oldTransform); + int margin = 0; + // draw baseline: + QLineF baseLine; + painter->setPen(basePen); + if (QCPAxis::orientation(type) == Qt::Horizontal) { + baseLine.setPoints(origin + QPointF(xCor, yCor), origin + QPointF(axisRect.width() + xCor, yCor)); + } else { + baseLine.setPoints(origin + QPointF(xCor, yCor), origin + QPointF(xCor, -axisRect.height() + yCor)); } - else if (type == QCPAxis::atRight) - { - QTransform oldTransform = painter->transform(); - painter->translate((origin.x()+margin+labelBounds.height()), origin.y()-axisRect.height()); - painter->rotate(90); - painter->drawText(0, 0, axisRect.height(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label); - painter->setTransform(oldTransform); + if (reversedEndings) { + baseLine = QLineF(baseLine.p2(), baseLine.p1()); // won't make a difference for line itself, but for line endings later } - else if (type == QCPAxis::atTop) - painter->drawText(origin.x(), origin.y()-margin-labelBounds.height(), axisRect.width(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label); - else if (type == QCPAxis::atBottom) - painter->drawText(origin.x(), origin.y()+margin, axisRect.width(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label); - } - - // set selection boxes: - int selectionTolerance = 0; - if (mParentPlot) - selectionTolerance = mParentPlot->selectionTolerance(); - else - qDebug() << Q_FUNC_INFO << "mParentPlot is null"; - int selAxisOutSize = qMax(qMax(tickLengthOut, subTickLengthOut), selectionTolerance); - int selAxisInSize = selectionTolerance; - int selTickLabelSize; - int selTickLabelOffset; - if (tickLabelSide == QCPAxis::lsOutside) - { - selTickLabelSize = (QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width()); - selTickLabelOffset = qMax(tickLengthOut, subTickLengthOut)+tickLabelPadding; - } else - { - selTickLabelSize = -(QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width()); - selTickLabelOffset = -(qMax(tickLengthIn, subTickLengthIn)+tickLabelPadding); - } - int selLabelSize = labelBounds.height(); - int selLabelOffset = qMax(tickLengthOut, subTickLengthOut)+(!tickLabels.isEmpty() && tickLabelSide == QCPAxis::lsOutside ? tickLabelPadding+selTickLabelSize : 0)+labelPadding; - if (type == QCPAxis::atLeft) - { - mAxisSelectionBox.setCoords(origin.x()-selAxisOutSize, axisRect.top(), origin.x()+selAxisInSize, axisRect.bottom()); - mTickLabelsSelectionBox.setCoords(origin.x()-selTickLabelOffset-selTickLabelSize, axisRect.top(), origin.x()-selTickLabelOffset, axisRect.bottom()); - mLabelSelectionBox.setCoords(origin.x()-selLabelOffset-selLabelSize, axisRect.top(), origin.x()-selLabelOffset, axisRect.bottom()); - } else if (type == QCPAxis::atRight) - { - mAxisSelectionBox.setCoords(origin.x()-selAxisInSize, axisRect.top(), origin.x()+selAxisOutSize, axisRect.bottom()); - mTickLabelsSelectionBox.setCoords(origin.x()+selTickLabelOffset+selTickLabelSize, axisRect.top(), origin.x()+selTickLabelOffset, axisRect.bottom()); - mLabelSelectionBox.setCoords(origin.x()+selLabelOffset+selLabelSize, axisRect.top(), origin.x()+selLabelOffset, axisRect.bottom()); - } else if (type == QCPAxis::atTop) - { - mAxisSelectionBox.setCoords(axisRect.left(), origin.y()-selAxisOutSize, axisRect.right(), origin.y()+selAxisInSize); - mTickLabelsSelectionBox.setCoords(axisRect.left(), origin.y()-selTickLabelOffset-selTickLabelSize, axisRect.right(), origin.y()-selTickLabelOffset); - mLabelSelectionBox.setCoords(axisRect.left(), origin.y()-selLabelOffset-selLabelSize, axisRect.right(), origin.y()-selLabelOffset); - } else if (type == QCPAxis::atBottom) - { - mAxisSelectionBox.setCoords(axisRect.left(), origin.y()-selAxisInSize, axisRect.right(), origin.y()+selAxisOutSize); - mTickLabelsSelectionBox.setCoords(axisRect.left(), origin.y()+selTickLabelOffset+selTickLabelSize, axisRect.right(), origin.y()+selTickLabelOffset); - mLabelSelectionBox.setCoords(axisRect.left(), origin.y()+selLabelOffset+selLabelSize, axisRect.right(), origin.y()+selLabelOffset); - } - mAxisSelectionBox = mAxisSelectionBox.normalized(); - mTickLabelsSelectionBox = mTickLabelsSelectionBox.normalized(); - mLabelSelectionBox = mLabelSelectionBox.normalized(); - // draw hitboxes for debug purposes: - //painter->setBrush(Qt::NoBrush); - //painter->drawRects(QVector() << mAxisSelectionBox << mTickLabelsSelectionBox << mLabelSelectionBox); + painter->drawLine(baseLine); + + // draw ticks: + if (!tickPositions.isEmpty()) { + painter->setPen(tickPen); + int tickDir = (type == QCPAxis::atBottom || type == QCPAxis::atRight) ? -1 : 1; // direction of ticks ("inward" is right for left axis and left for right axis) + if (QCPAxis::orientation(type) == Qt::Horizontal) { + for (int i = 0; i < tickPositions.size(); ++i) { + painter->drawLine(QLineF(tickPositions.at(i) + xCor, origin.y() - tickLengthOut * tickDir + yCor, tickPositions.at(i) + xCor, origin.y() + tickLengthIn * tickDir + yCor)); + } + } else { + for (int i = 0; i < tickPositions.size(); ++i) { + painter->drawLine(QLineF(origin.x() - tickLengthOut * tickDir + xCor, tickPositions.at(i) + yCor, origin.x() + tickLengthIn * tickDir + xCor, tickPositions.at(i) + yCor)); + } + } + } + + // draw subticks: + if (!subTickPositions.isEmpty()) { + painter->setPen(subTickPen); + // direction of ticks ("inward" is right for left axis and left for right axis) + int tickDir = (type == QCPAxis::atBottom || type == QCPAxis::atRight) ? -1 : 1; + if (QCPAxis::orientation(type) == Qt::Horizontal) { + for (int i = 0; i < subTickPositions.size(); ++i) { + painter->drawLine(QLineF(subTickPositions.at(i) + xCor, origin.y() - subTickLengthOut * tickDir + yCor, subTickPositions.at(i) + xCor, origin.y() + subTickLengthIn * tickDir + yCor)); + } + } else { + for (int i = 0; i < subTickPositions.size(); ++i) { + painter->drawLine(QLineF(origin.x() - subTickLengthOut * tickDir + xCor, subTickPositions.at(i) + yCor, origin.x() + subTickLengthIn * tickDir + xCor, subTickPositions.at(i) + yCor)); + } + } + } + margin += qMax(0, qMax(tickLengthOut, subTickLengthOut)); + + // draw axis base endings: + bool antialiasingBackup = painter->antialiasing(); + painter->setAntialiasing(true); // always want endings to be antialiased, even if base and ticks themselves aren't + painter->setBrush(QBrush(basePen.color())); + QVector2D baseLineVector(baseLine.dx(), baseLine.dy()); + if (lowerEnding.style() != QCPLineEnding::esNone) { + lowerEnding.draw(painter, QVector2D(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); + } + painter->setAntialiasing(antialiasingBackup); + + // tick labels: + QRect oldClipRect; + if (tickLabelSide == QCPAxis::lsInside) { // if using inside labels, clip them to the axis rect + oldClipRect = painter->clipRegion().boundingRect(); + painter->setClipRect(axisRect); + } + QSize tickLabelsSize(0, 0); // size of largest tick label, for offset calculation of axis label + if (!tickLabels.isEmpty()) { + if (tickLabelSide == QCPAxis::lsOutside) { + margin += tickLabelPadding; + } + painter->setFont(tickLabelFont); + painter->setPen(QPen(tickLabelColor)); + const int maxLabelIndex = qMin(tickPositions.size(), tickLabels.size()); + int distanceToAxis = margin; + if (tickLabelSide == QCPAxis::lsInside) { + distanceToAxis = -(qMax(tickLengthIn, subTickLengthIn) + tickLabelPadding); + } + for (int i = 0; i < maxLabelIndex; ++i) { + placeTickLabel(painter, tickPositions.at(i), distanceToAxis, tickLabels.at(i), &tickLabelsSize); + } + if (tickLabelSide == QCPAxis::lsOutside) { + margin += (QCPAxis::orientation(type) == Qt::Horizontal) ? tickLabelsSize.height() : tickLabelsSize.width(); + } + } + if (tickLabelSide == QCPAxis::lsInside) { + painter->setClipRect(oldClipRect); + } + + // axis label: + QRect labelBounds; + if (!label.isEmpty()) { + margin += labelPadding; + painter->setFont(labelFont); + painter->setPen(QPen(labelColor)); + labelBounds = painter->fontMetrics().boundingRect(0, 0, 0, 0, Qt::TextDontClip, label); + if (type == QCPAxis::atLeft) { + QTransform oldTransform = painter->transform(); + painter->translate((origin.x() - margin - labelBounds.height()), origin.y()); + painter->rotate(-90); + painter->drawText(0, 0, axisRect.height(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label); + painter->setTransform(oldTransform); + } else if (type == QCPAxis::atRight) { + QTransform oldTransform = painter->transform(); + painter->translate((origin.x() + margin + labelBounds.height()), origin.y() - axisRect.height()); + painter->rotate(90); + painter->drawText(0, 0, axisRect.height(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label); + painter->setTransform(oldTransform); + } else if (type == QCPAxis::atTop) { + painter->drawText(origin.x(), origin.y() - margin - labelBounds.height(), axisRect.width(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label); + } else if (type == QCPAxis::atBottom) { + painter->drawText(origin.x(), origin.y() + margin, axisRect.width(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label); + } + } + + // set selection boxes: + int selectionTolerance = 0; + if (mParentPlot) { + selectionTolerance = mParentPlot->selectionTolerance(); + } else { + qDebug() << Q_FUNC_INFO << "mParentPlot is null"; + } + int selAxisOutSize = qMax(qMax(tickLengthOut, subTickLengthOut), selectionTolerance); + int selAxisInSize = selectionTolerance; + int selTickLabelSize; + int selTickLabelOffset; + if (tickLabelSide == QCPAxis::lsOutside) { + selTickLabelSize = (QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width()); + selTickLabelOffset = qMax(tickLengthOut, subTickLengthOut) + tickLabelPadding; + } else { + selTickLabelSize = -(QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width()); + selTickLabelOffset = -(qMax(tickLengthIn, subTickLengthIn) + tickLabelPadding); + } + int selLabelSize = labelBounds.height(); + int selLabelOffset = qMax(tickLengthOut, subTickLengthOut) + (!tickLabels.isEmpty() && tickLabelSide == QCPAxis::lsOutside ? tickLabelPadding + selTickLabelSize : 0) + labelPadding; + if (type == QCPAxis::atLeft) { + mAxisSelectionBox.setCoords(origin.x() - selAxisOutSize, axisRect.top(), origin.x() + selAxisInSize, axisRect.bottom()); + mTickLabelsSelectionBox.setCoords(origin.x() - selTickLabelOffset - selTickLabelSize, axisRect.top(), origin.x() - selTickLabelOffset, axisRect.bottom()); + mLabelSelectionBox.setCoords(origin.x() - selLabelOffset - selLabelSize, axisRect.top(), origin.x() - selLabelOffset, axisRect.bottom()); + } else if (type == QCPAxis::atRight) { + mAxisSelectionBox.setCoords(origin.x() - selAxisInSize, axisRect.top(), origin.x() + selAxisOutSize, axisRect.bottom()); + mTickLabelsSelectionBox.setCoords(origin.x() + selTickLabelOffset + selTickLabelSize, axisRect.top(), origin.x() + selTickLabelOffset, axisRect.bottom()); + mLabelSelectionBox.setCoords(origin.x() + selLabelOffset + selLabelSize, axisRect.top(), origin.x() + selLabelOffset, axisRect.bottom()); + } else if (type == QCPAxis::atTop) { + mAxisSelectionBox.setCoords(axisRect.left(), origin.y() - selAxisOutSize, axisRect.right(), origin.y() + selAxisInSize); + mTickLabelsSelectionBox.setCoords(axisRect.left(), origin.y() - selTickLabelOffset - selTickLabelSize, axisRect.right(), origin.y() - selTickLabelOffset); + mLabelSelectionBox.setCoords(axisRect.left(), origin.y() - selLabelOffset - selLabelSize, axisRect.right(), origin.y() - selLabelOffset); + } else if (type == QCPAxis::atBottom) { + mAxisSelectionBox.setCoords(axisRect.left(), origin.y() - selAxisInSize, axisRect.right(), origin.y() + selAxisOutSize); + mTickLabelsSelectionBox.setCoords(axisRect.left(), origin.y() + selTickLabelOffset + selTickLabelSize, axisRect.right(), origin.y() + selTickLabelOffset); + mLabelSelectionBox.setCoords(axisRect.left(), origin.y() + selLabelOffset + selLabelSize, axisRect.right(), origin.y() + selLabelOffset); + } + mAxisSelectionBox = mAxisSelectionBox.normalized(); + mTickLabelsSelectionBox = mTickLabelsSelectionBox.normalized(); + mLabelSelectionBox = mLabelSelectionBox.normalized(); + // draw hitboxes for debug purposes: + //painter->setBrush(Qt::NoBrush); + //painter->drawRects(QVector() << mAxisSelectionBox << mTickLabelsSelectionBox << mLabelSelectionBox); } /*! \internal - + Returns the size ("margin" in QCPAxisRect context, so measured perpendicular to the axis backbone direction) needed to fit the axis. */ int QCPAxisPainterPrivate::size() const { - int result = 0; - - // get length of tick marks pointing outwards: - if (!tickPositions.isEmpty()) - result += qMax(0, qMax(tickLengthOut, subTickLengthOut)); - - // calculate size of tick labels: - if (tickLabelSide == QCPAxis::lsOutside) - { - QSize tickLabelsSize(0, 0); - if (!tickLabels.isEmpty()) - { - for (int i=0; iplottingHints().testFlag(QCP::phCacheLabels) && !painter->modes().testFlag(QCPPainter::pmNoCaching)) // label caching enabled - { - CachedLabel *cachedLabel = mLabelCache.take(text); // attempt to get label from cache - if (!cachedLabel) // no cached label existed, create it - { - cachedLabel = new CachedLabel; - TickLabelData labelData = getTickLabelData(painter->font(), text); - cachedLabel->offset = getTickLabelDrawOffset(labelData)+labelData.rotatedTotalBounds.topLeft(); - cachedLabel->pixmap = QPixmap(labelData.rotatedTotalBounds.size()); - cachedLabel->pixmap.fill(Qt::transparent); - QCPPainter cachePainter(&cachedLabel->pixmap); - cachePainter.setPen(painter->pen()); - drawTickLabel(&cachePainter, -labelData.rotatedTotalBounds.topLeft().x(), -labelData.rotatedTotalBounds.topLeft().y(), labelData); + // warning: if you change anything here, also adapt getMaxTickLabelSize() accordingly! + if (text.isEmpty()) { + return; } - // if label would be partly clipped by widget border on sides, don't draw it (only for outside tick labels): - bool labelClippedByBorder = false; - 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(); - else - labelClippedByBorder = labelAnchor.y()+cachedLabel->offset.y()+cachedLabel->pixmap.height() > viewportRect.bottom() || labelAnchor.y()+cachedLabel->offset.y() < viewportRect.top(); + QSize finalSize; + QPointF labelAnchor; + switch (type) { + case QCPAxis::atLeft: + labelAnchor = QPointF(axisRect.left() - distanceToAxis - offset, position); + break; + case QCPAxis::atRight: + labelAnchor = QPointF(axisRect.right() + distanceToAxis + offset, position); + break; + case QCPAxis::atTop: + labelAnchor = QPointF(position, axisRect.top() - distanceToAxis - offset); + break; + case QCPAxis::atBottom: + labelAnchor = QPointF(position, axisRect.bottom() + distanceToAxis + offset); + break; } - if (!labelClippedByBorder) - { - painter->drawPixmap(labelAnchor+cachedLabel->offset, cachedLabel->pixmap); - finalSize = cachedLabel->pixmap.size(); + if (mParentPlot->plottingHints().testFlag(QCP::phCacheLabels) && !painter->modes().testFlag(QCPPainter::pmNoCaching)) { // label caching enabled + CachedLabel *cachedLabel = mLabelCache.take(text); // attempt to get label from cache + if (!cachedLabel) { // no cached label existed, create it + cachedLabel = new CachedLabel; + TickLabelData labelData = getTickLabelData(painter->font(), text); + cachedLabel->offset = getTickLabelDrawOffset(labelData) + labelData.rotatedTotalBounds.topLeft(); + cachedLabel->pixmap = QPixmap(labelData.rotatedTotalBounds.size()); + cachedLabel->pixmap.fill(Qt::transparent); + QCPPainter cachePainter(&cachedLabel->pixmap); + cachePainter.setPen(painter->pen()); + drawTickLabel(&cachePainter, -labelData.rotatedTotalBounds.topLeft().x(), -labelData.rotatedTotalBounds.topLeft().y(), labelData); + } + // if label would be partly clipped by widget border on sides, don't draw it (only for outside tick labels): + bool labelClippedByBorder = false; + 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(); + } else { + labelClippedByBorder = labelAnchor.y() + cachedLabel->offset.y() + cachedLabel->pixmap.height() > viewportRect.bottom() || labelAnchor.y() + cachedLabel->offset.y() < viewportRect.top(); + } + } + if (!labelClippedByBorder) { + painter->drawPixmap(labelAnchor + cachedLabel->offset, cachedLabel->pixmap); + finalSize = cachedLabel->pixmap.size(); + } + 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: + TickLabelData labelData = getTickLabelData(painter->font(), text); + QPointF finalPosition = labelAnchor + getTickLabelDrawOffset(labelData); + // if label would be partly clipped by widget border on sides, don't draw it (only for outside tick labels): + bool labelClippedByBorder = false; + if (tickLabelSide == QCPAxis::lsOutside) { + if (QCPAxis::orientation(type) == Qt::Horizontal) { + labelClippedByBorder = finalPosition.x() + (labelData.rotatedTotalBounds.width() + labelData.rotatedTotalBounds.left()) > viewportRect.right() || finalPosition.x() + labelData.rotatedTotalBounds.left() < viewportRect.left(); + } else { + labelClippedByBorder = finalPosition.y() + (labelData.rotatedTotalBounds.height() + labelData.rotatedTotalBounds.top()) > viewportRect.bottom() || finalPosition.y() + labelData.rotatedTotalBounds.top() < viewportRect.top(); + } + } + if (!labelClippedByBorder) { + drawTickLabel(painter, finalPosition.x(), finalPosition.y(), labelData); + finalSize = labelData.rotatedTotalBounds.size(); + } } - 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: - { - TickLabelData labelData = getTickLabelData(painter->font(), text); - QPointF finalPosition = labelAnchor + getTickLabelDrawOffset(labelData); - // if label would be partly clipped by widget border on sides, don't draw it (only for outside tick labels): - bool labelClippedByBorder = false; - if (tickLabelSide == QCPAxis::lsOutside) - { - if (QCPAxis::orientation(type) == Qt::Horizontal) - labelClippedByBorder = finalPosition.x()+(labelData.rotatedTotalBounds.width()+labelData.rotatedTotalBounds.left()) > viewportRect.right() || finalPosition.x()+labelData.rotatedTotalBounds.left() < viewportRect.left(); - else - labelClippedByBorder = finalPosition.y()+(labelData.rotatedTotalBounds.height()+labelData.rotatedTotalBounds.top()) > viewportRect.bottom() || finalPosition.y()+labelData.rotatedTotalBounds.top() < viewportRect.top(); + + // expand passed tickLabelsSize if current tick label is larger: + if (finalSize.width() > tickLabelsSize->width()) { + tickLabelsSize->setWidth(finalSize.width()); } - if (!labelClippedByBorder) - { - drawTickLabel(painter, finalPosition.x(), finalPosition.y(), labelData); - finalSize = labelData.rotatedTotalBounds.size(); + if (finalSize.height() > tickLabelsSize->height()) { + tickLabelsSize->setHeight(finalSize.height()); } - } - - // expand passed tickLabelsSize if current tick label is larger: - if (finalSize.width() > tickLabelsSize->width()) - tickLabelsSize->setWidth(finalSize.width()); - if (finalSize.height() > tickLabelsSize->height()) - tickLabelsSize->setHeight(finalSize.height()); } /*! \internal - + This is a \ref placeTickLabel helper function. - + Draws the tick label specified in \a labelData with \a painter at the pixel positions \a x and \a y. This function is used by \ref placeTickLabel to create new tick labels for the cache, or to directly draw the labels on the QCustomPlot surface when label caching is disabled, i.e. when @@ -6450,215 +6448,196 @@ void QCPAxisPainterPrivate::placeTickLabel(QCPPainter *painter, double position, */ void QCPAxisPainterPrivate::drawTickLabel(QCPPainter *painter, double x, double y, const TickLabelData &labelData) const { - // backup painter settings that we're about to change: - QTransform oldTransform = painter->transform(); - QFont oldFont = painter->font(); - - // transform painter to position/rotation: - painter->translate(x, y); - if (!qFuzzyIsNull(tickLabelRotation)) - painter->rotate(tickLabelRotation); - - // draw text: - if (!labelData.expPart.isEmpty()) // indicator that beautiful powers must be used - { - painter->setFont(labelData.baseFont); - painter->drawText(0, 0, 0, 0, Qt::TextDontClip, labelData.basePart); - painter->setFont(labelData.expFont); - painter->drawText(labelData.baseBounds.width()+1, 0, labelData.expBounds.width(), labelData.expBounds.height(), Qt::TextDontClip, labelData.expPart); - } else - { - painter->setFont(labelData.baseFont); - painter->drawText(0, 0, labelData.totalBounds.width(), labelData.totalBounds.height(), Qt::TextDontClip | Qt::AlignHCenter, labelData.basePart); - } - - // reset painter settings to what it was before: - painter->setTransform(oldTransform); - painter->setFont(oldFont); + // backup painter settings that we're about to change: + QTransform oldTransform = painter->transform(); + QFont oldFont = painter->font(); + + // transform painter to position/rotation: + painter->translate(x, y); + if (!qFuzzyIsNull(tickLabelRotation)) { + painter->rotate(tickLabelRotation); + } + + // draw text: + if (!labelData.expPart.isEmpty()) { // indicator that beautiful powers must be used + painter->setFont(labelData.baseFont); + painter->drawText(0, 0, 0, 0, Qt::TextDontClip, labelData.basePart); + painter->setFont(labelData.expFont); + painter->drawText(labelData.baseBounds.width() + 1, 0, labelData.expBounds.width(), labelData.expBounds.height(), Qt::TextDontClip, labelData.expPart); + } else { + painter->setFont(labelData.baseFont); + painter->drawText(0, 0, labelData.totalBounds.width(), labelData.totalBounds.height(), Qt::TextDontClip | Qt::AlignHCenter, labelData.basePart); + } + + // reset painter settings to what it was before: + painter->setTransform(oldTransform); + painter->setFont(oldFont); } /*! \internal - + This is a \ref placeTickLabel helper function. - + Transforms the passed \a text and \a font to a tickLabelData structure that can then be further processed by \ref getTickLabelDrawOffset and \ref drawTickLabel. It splits the text into base and exponent if necessary (member substituteExponent) and calculates appropriate bounding boxes. */ QCPAxisPainterPrivate::TickLabelData QCPAxisPainterPrivate::getTickLabelData(const QFont &font, const QString &text) const { - TickLabelData result; - - // determine whether beautiful decimal powers should be used - bool useBeautifulPowers = false; - 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 > 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; + TickLabelData result; + + // determine whether beautiful decimal powers should be used + bool useBeautifulPowers = false; + 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 > 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: - result.baseFont = font; - if (result.baseFont.pointSizeF() > 0) // might return -1 if specified with setPixelSize, in that case we can't do correction in next line - result.baseFont.setPointSizeF(result.baseFont.pointSizeF()+0.05); // QFontMetrics.boundingRect has a bug for exact point sizes that make the results oscillate due to internal rounding - if (useBeautifulPowers) - { - // 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); - // 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); - // 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); - if (!result.expPart.isEmpty() && result.expPart.at(0) == QLatin1Char('+')) - result.expPart.remove(0, 1); - // prepare smaller font for exponent: - result.expFont = font; - if (result.expFont.pointSize() > 0) - 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: - 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 - } else // useBeautifulPowers == false - { - result.basePart = text; - result.totalBounds = QFontMetrics(result.baseFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip | Qt::AlignHCenter, result.basePart); - } - result.totalBounds.moveTopLeft(QPoint(0, 0)); // want bounding box aligned top left at origin, independent of how it was created, to make further processing simpler - - // calculate possibly different bounding rect after rotation: - result.rotatedTotalBounds = result.totalBounds; - if (!qFuzzyIsNull(tickLabelRotation)) - { - QTransform transform; - transform.rotate(tickLabelRotation); - result.rotatedTotalBounds = transform.mapRect(result.rotatedTotalBounds); - } - - return result; + + // calculate text bounding rects and do string preparation for beautiful decimal powers: + result.baseFont = font; + if (result.baseFont.pointSizeF() > 0) { // might return -1 if specified with setPixelSize, in that case we can't do correction in next line + result.baseFont.setPointSizeF(result.baseFont.pointSizeF() + 0.05); // QFontMetrics.boundingRect has a bug for exact point sizes that make the results oscillate due to internal rounding + } + if (useBeautifulPowers) { + // 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); + // 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); + // 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); + } + if (!result.expPart.isEmpty() && result.expPart.at(0) == QLatin1Char('+')) { + result.expPart.remove(0, 1); + } + // prepare smaller font for exponent: + result.expFont = font; + if (result.expFont.pointSize() > 0) { + 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: + 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 + } else { // useBeautifulPowers == false + result.basePart = text; + result.totalBounds = QFontMetrics(result.baseFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip | Qt::AlignHCenter, result.basePart); + } + result.totalBounds.moveTopLeft(QPoint(0, 0)); // want bounding box aligned top left at origin, independent of how it was created, to make further processing simpler + + // calculate possibly different bounding rect after rotation: + result.rotatedTotalBounds = result.totalBounds; + if (!qFuzzyIsNull(tickLabelRotation)) { + QTransform transform; + transform.rotate(tickLabelRotation); + result.rotatedTotalBounds = transform.mapRect(result.rotatedTotalBounds); + } + + return result; } /*! \internal - + This is a \ref placeTickLabel helper function. - + Calculates the offset at which the top left corner of the specified tick label shall be drawn. The offset is relative to a point right next to the tick the label belongs to. - + This function is thus responsible for e.g. centering tick labels under ticks and positioning them appropriately when they are rotated. */ QPointF QCPAxisPainterPrivate::getTickLabelDrawOffset(const TickLabelData &labelData) const { - /* - calculate label offset from base point at tick (non-trivial, for best visual appearance): short - explanation for bottom axis: The anchor, i.e. the point in the label that is placed - horizontally under the corresponding tick is always on the label side that is closer to the - axis (e.g. the left side of the text when we're rotating clockwise). On that side, the height - is halved and the resulting point is defined the anchor. This way, a 90 degree rotated text - will be centered under the tick (i.e. displaced horizontally by half its height). At the same - time, a 45 degree rotated text will "point toward" its tick, as is typical for rotated tick - labels. - */ - bool doRotation = !qFuzzyIsNull(tickLabelRotation); - bool flip = qFuzzyCompare(qAbs(tickLabelRotation), 90.0); // perfect +/-90 degree flip. Indicates vertical label centering on vertical axes. - double radians = tickLabelRotation/180.0*M_PI; - int x=0, y=0; - if ((type == QCPAxis::atLeft && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atRight && tickLabelSide == QCPAxis::lsInside)) // Anchor at right side of tick label - { - if (doRotation) - { - if (tickLabelRotation > 0) - { - x = -qCos(radians)*labelData.totalBounds.width(); - y = flip ? -labelData.totalBounds.width()/2.0 : -qSin(radians)*labelData.totalBounds.width()-qCos(radians)*labelData.totalBounds.height()/2.0; - } else - { - x = -qCos(-radians)*labelData.totalBounds.width()-qSin(-radians)*labelData.totalBounds.height(); - y = flip ? +labelData.totalBounds.width()/2.0 : +qSin(-radians)*labelData.totalBounds.width()-qCos(-radians)*labelData.totalBounds.height()/2.0; - } - } else - { - x = -labelData.totalBounds.width(); - y = -labelData.totalBounds.height()/2.0; + /* + calculate label offset from base point at tick (non-trivial, for best visual appearance): short + explanation for bottom axis: The anchor, i.e. the point in the label that is placed + horizontally under the corresponding tick is always on the label side that is closer to the + axis (e.g. the left side of the text when we're rotating clockwise). On that side, the height + is halved and the resulting point is defined the anchor. This way, a 90 degree rotated text + will be centered under the tick (i.e. displaced horizontally by half its height). At the same + time, a 45 degree rotated text will "point toward" its tick, as is typical for rotated tick + labels. + */ + bool doRotation = !qFuzzyIsNull(tickLabelRotation); + bool flip = qFuzzyCompare(qAbs(tickLabelRotation), 90.0); // perfect +/-90 degree flip. Indicates vertical label centering on vertical axes. + double radians = tickLabelRotation / 180.0 * M_PI; + int x = 0, y = 0; + if ((type == QCPAxis::atLeft && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atRight && tickLabelSide == QCPAxis::lsInside)) { // Anchor at right side of tick label + if (doRotation) { + if (tickLabelRotation > 0) { + x = -qCos(radians) * labelData.totalBounds.width(); + y = flip ? -labelData.totalBounds.width() / 2.0 : -qSin(radians) * labelData.totalBounds.width() - qCos(radians) * labelData.totalBounds.height() / 2.0; + } else { + x = -qCos(-radians) * labelData.totalBounds.width() - qSin(-radians) * labelData.totalBounds.height(); + y = flip ? +labelData.totalBounds.width() / 2.0 : +qSin(-radians) * labelData.totalBounds.width() - qCos(-radians) * labelData.totalBounds.height() / 2.0; + } + } else { + x = -labelData.totalBounds.width(); + y = -labelData.totalBounds.height() / 2.0; + } + } else if ((type == QCPAxis::atRight && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atLeft && tickLabelSide == QCPAxis::lsInside)) { // Anchor at left side of tick label + if (doRotation) { + if (tickLabelRotation > 0) { + x = +qSin(radians) * labelData.totalBounds.height(); + y = flip ? -labelData.totalBounds.width() / 2.0 : -qCos(radians) * labelData.totalBounds.height() / 2.0; + } else { + x = 0; + y = flip ? +labelData.totalBounds.width() / 2.0 : -qCos(-radians) * labelData.totalBounds.height() / 2.0; + } + } else { + x = 0; + y = -labelData.totalBounds.height() / 2.0; + } + } else if ((type == QCPAxis::atTop && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atBottom && tickLabelSide == QCPAxis::lsInside)) { // Anchor at bottom side of tick label + if (doRotation) { + if (tickLabelRotation > 0) { + x = -qCos(radians) * labelData.totalBounds.width() + qSin(radians) * labelData.totalBounds.height() / 2.0; + y = -qSin(radians) * labelData.totalBounds.width() - qCos(radians) * labelData.totalBounds.height(); + } else { + x = -qSin(-radians) * labelData.totalBounds.height() / 2.0; + y = -qCos(-radians) * labelData.totalBounds.height(); + } + } else { + x = -labelData.totalBounds.width() / 2.0; + y = -labelData.totalBounds.height(); + } + } else if ((type == QCPAxis::atBottom && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atTop && tickLabelSide == QCPAxis::lsInside)) { // Anchor at top side of tick label + if (doRotation) { + if (tickLabelRotation > 0) { + x = +qSin(radians) * labelData.totalBounds.height() / 2.0; + y = 0; + } else { + x = -qCos(-radians) * labelData.totalBounds.width() - qSin(-radians) * labelData.totalBounds.height() / 2.0; + y = +qSin(-radians) * labelData.totalBounds.width(); + } + } else { + x = -labelData.totalBounds.width() / 2.0; + y = 0; + } } - } else if ((type == QCPAxis::atRight && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atLeft && tickLabelSide == QCPAxis::lsInside)) // Anchor at left side of tick label - { - if (doRotation) - { - if (tickLabelRotation > 0) - { - x = +qSin(radians)*labelData.totalBounds.height(); - y = flip ? -labelData.totalBounds.width()/2.0 : -qCos(radians)*labelData.totalBounds.height()/2.0; - } else - { - x = 0; - y = flip ? +labelData.totalBounds.width()/2.0 : -qCos(-radians)*labelData.totalBounds.height()/2.0; - } - } else - { - x = 0; - y = -labelData.totalBounds.height()/2.0; - } - } else if ((type == QCPAxis::atTop && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atBottom && tickLabelSide == QCPAxis::lsInside)) // Anchor at bottom side of tick label - { - if (doRotation) - { - if (tickLabelRotation > 0) - { - x = -qCos(radians)*labelData.totalBounds.width()+qSin(radians)*labelData.totalBounds.height()/2.0; - y = -qSin(radians)*labelData.totalBounds.width()-qCos(radians)*labelData.totalBounds.height(); - } else - { - x = -qSin(-radians)*labelData.totalBounds.height()/2.0; - y = -qCos(-radians)*labelData.totalBounds.height(); - } - } else - { - x = -labelData.totalBounds.width()/2.0; - y = -labelData.totalBounds.height(); - } - } else if ((type == QCPAxis::atBottom && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atTop && tickLabelSide == QCPAxis::lsInside)) // Anchor at top side of tick label - { - if (doRotation) - { - if (tickLabelRotation > 0) - { - x = +qSin(radians)*labelData.totalBounds.height()/2.0; - y = 0; - } else - { - x = -qCos(-radians)*labelData.totalBounds.width()-qSin(-radians)*labelData.totalBounds.height()/2.0; - y = +qSin(-radians)*labelData.totalBounds.width(); - } - } else - { - x = -labelData.totalBounds.width()/2.0; - y = 0; - } - } - - return QPointF(x, y); + + return QPointF(x, y); } /*! \internal - + Simulates the steps done by \ref placeTickLabel by calculating bounding boxes of the text label to be drawn, depending on number format etc. Since only the largest tick label is wanted for the margin calculation, the passed \a tickLabelsSize is only expanded, if it's currently set to a @@ -6666,23 +6645,23 @@ QPointF QCPAxisPainterPrivate::getTickLabelDrawOffset(const TickLabelData &label */ void QCPAxisPainterPrivate::getMaxTickLabelSize(const QFont &font, const QString &text, QSize *tickLabelsSize) const { - // note: this function must return the same tick label sizes as the placeTickLabel function. - QSize finalSize; - 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(); - } else // label caching disabled or no label with this text cached: - { - TickLabelData labelData = getTickLabelData(font, text); - finalSize = labelData.rotatedTotalBounds.size(); - } - - // expand passed tickLabelsSize if current tick label is larger: - if (finalSize.width() > tickLabelsSize->width()) - tickLabelsSize->setWidth(finalSize.width()); - if (finalSize.height() > tickLabelsSize->height()) - tickLabelsSize->setHeight(finalSize.height()); + // note: this function must return the same tick label sizes as the placeTickLabel function. + QSize finalSize; + 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(); + } else { // label caching disabled or no label with this text cached: + TickLabelData labelData = getTickLabelData(font, text); + finalSize = labelData.rotatedTotalBounds.size(); + } + + // expand passed tickLabelsSize if current tick label is larger: + if (finalSize.width() > tickLabelsSize->width()) { + tickLabelsSize->setWidth(finalSize.width()); + } + if (finalSize.height() > tickLabelsSize->height()) { + tickLabelsSize->setHeight(finalSize.height()); + } } @@ -6696,7 +6675,7 @@ 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). - + All further specifics are in the subclasses, for example: \li A normal graph with possibly a line, scatter points and error bars: \ref QCPGraph (typically created with \ref QCustomPlot::addGraph) @@ -6705,9 +6684,9 @@ void QCPAxisPainterPrivate::getMaxTickLabelSize(const QFont &font, const QString \li A statistical box plot: \ref QCPStatisticalBox \li A color encoded two-dimensional map: \ref QCPColorMap \li An OHLC/Candlestick chart: \ref QCPFinancial - + \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 @@ -6716,9 +6695,9 @@ void QCPAxisPainterPrivate::getMaxTickLabelSize(const QFont &font, const QString \li \ref drawLegendIcon \li \ref getKeyRange \li \ref getValueRange - + See the documentation of those functions for what they need to do. - + For drawing your plot, you can use the \ref coordsToPixels functions to translate a point in plot coordinates to pixel coordinates. This function is quite convenient, because it takes the orientation of the key and value axes into account for you (x and y are swapped when the key axis @@ -6726,7 +6705,7 @@ void QCPAxisPainterPrivate::getMaxTickLabelSize(const QFont &font, const QString to translate many points in a loop like QCPGraph), you can directly use \ref QCPAxis::coordToPixel. However, you must then take care about the orientation of the axis yourself. - + Here are some important members you inherit from QCPAbstractPlottable: @@ -6766,17 +6745,17 @@ void QCPAxisPainterPrivate::getMaxTickLabelSize(const QFont &font, const QString /*! \fn void QCPAbstractPlottable::drawLegendIcon(QCPPainter *painter, const QRect &rect) const = 0 \internal - + called by QCPLegend::draw (via QCPPlottableLegendItem::draw) to create a graphical representation of this plottable inside \a rect, next to the plottable name. - + The passed \a painter has its cliprect set to \a rect, so painting outside of \a rect won't appear outside the legend icon border. */ /*! \fn QCPRange QCPAbstractPlottable::getKeyRange(bool &foundRange, SignDomain inSignDomain) const = 0 \internal - + 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 @@ -6787,13 +6766,13 @@ void QCPAxisPainterPrivate::getMaxTickLabelSize(const QFont &font, const QString 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. - + \see rescaleAxes, getValueRange */ /*! \fn QCPRange QCPAbstractPlottable::getValueRange(bool &foundRange, SignDomain inSignDomain) const = 0 \internal - + 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 @@ -6804,7 +6783,7 @@ void QCPAxisPainterPrivate::getMaxTickLabelSize(const QFont &font, const QString 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. - + \see rescaleAxes, getKeyRange */ @@ -6812,15 +6791,15 @@ void QCPAxisPainterPrivate::getMaxTickLabelSize(const QFont &font, const QString /* start of documentation of signals */ /*! \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. */ /*! \fn void QCPAbstractPlottable::selectableChanged(bool selectable); - + This signal is emitted when the selectability of this plottable has changed. - + \see setSelectable */ @@ -6831,31 +6810,33 @@ void QCPAxisPainterPrivate::getMaxTickLabelSize(const QFont &font, const QString its value axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and have perpendicular orientations. If either of these restrictions is violated, a corresponding message is printed to the debug output (qDebug), the construction is not aborted, though. - + Since QCPAbstractPlottable is an abstract class that defines the basic interface to plottables, it can't be directly instantiated. - + You probably want one of the subclasses like \ref QCPGraph or \ref QCPCurve instead. */ QCPAbstractPlottable::QCPAbstractPlottable(QCPAxis *keyAxis, QCPAxis *valueAxis) : - QCPLayerable(keyAxis->parentPlot(), QString(), keyAxis->axisRect()), - 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) + QCPLayerable(keyAxis->parentPlot(), QString(), keyAxis->axisRect()), + 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) { - 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."; + 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."; + } } /*! @@ -6864,54 +6845,54 @@ QCPAbstractPlottable::QCPAbstractPlottable(QCPAxis *keyAxis, QCPAxis *valueAxis) */ void QCPAbstractPlottable::setName(const QString &name) { - mName = name; + mName = name; } /*! Sets whether fills 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::setAntialiasedFill(bool enabled) { - mAntialiasedFill = enabled; + mAntialiasedFill = enabled; } /*! Sets whether the scatter symbols 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::setAntialiasedScatters(bool enabled) { - mAntialiasedScatters = 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; + mAntialiasedErrorBars = enabled; } /*! The pen is used to draw basic lines that make up the plottable representation in the plot. - + For example, the \ref QCPGraph subclass draws its graph lines with this pen. \see setBrush */ void QCPAbstractPlottable::setPen(const QPen &pen) { - mPen = pen; + mPen = pen; } /*! @@ -6922,13 +6903,13 @@ void QCPAbstractPlottable::setPen(const QPen &pen) */ void QCPAbstractPlottable::setSelectedPen(const QPen &pen) { - mSelectedPen = 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. - + For example, the \ref QCPGraph subclass draws the fill under the graph with this brush, when it's not set to Qt::NoBrush. @@ -6936,7 +6917,7 @@ void QCPAbstractPlottable::setSelectedPen(const QPen &pen) */ void QCPAbstractPlottable::setBrush(const QBrush &brush) { - mBrush = brush; + mBrush = brush; } /*! @@ -6947,7 +6928,7 @@ void QCPAbstractPlottable::setBrush(const QBrush &brush) */ void QCPAbstractPlottable::setSelectedBrush(const QBrush &brush) { - mSelectedBrush = brush; + mSelectedBrush = brush; } /*! @@ -6955,7 +6936,7 @@ void QCPAbstractPlottable::setSelectedBrush(const QBrush &brush) to the plottable's value axis. This function performs no checks to make sure this is the case. The typical mathematical choice is to use the x-axis (QCustomPlot::xAxis) as key axis and the y-axis (QCustomPlot::yAxis) as value axis. - + Normally, the key and value axes are set in the constructor of the plottable (or \ref QCustomPlot::addGraph when working with QCPGraphs through the dedicated graph interface). @@ -6963,7 +6944,7 @@ void QCPAbstractPlottable::setSelectedBrush(const QBrush &brush) */ void QCPAbstractPlottable::setKeyAxis(QCPAxis *axis) { - mKeyAxis = axis; + mKeyAxis = axis; } /*! @@ -6974,30 +6955,29 @@ void QCPAbstractPlottable::setKeyAxis(QCPAxis *axis) Normally, the key and value axes are set in the constructor of the plottable (or \ref QCustomPlot::addGraph when working with QCPGraphs through the dedicated graph interface). - + \see setKeyAxis */ void QCPAbstractPlottable::setValueAxis(QCPAxis *axis) { - mValueAxis = 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); - } + if (mSelectable != selectable) { + mSelectable = selectable; + emit selectableChanged(mSelectable); + } } /*! @@ -7007,20 +6987,19 @@ void QCPAbstractPlottable::setSelectable(bool selectable) The entire selection mechanism for plottables is handled automatically when \ref QCustomPlot::setInteractions contains iSelectPlottables. You only need to call this function when you wish to change the selection state manually. - + This function can change the selection state even when \ref setSelectable was set to false. - + emits the \ref selectionChanged signal when \a selected is different from the previous selection state. - + \see setSelectable, selectTest */ void QCPAbstractPlottable::setSelected(bool selected) { - if (mSelected != selected) - { - mSelected = selected; - emit selectionChanged(mSelected); - } + if (mSelected != selected) { + mSelected = selected; + emit selectionChanged(mSelected); + } } /*! @@ -7029,226 +7008,238 @@ void QCPAbstractPlottable::setSelected(bool selected) sure not to rescale to an illegal range i.e. a range containing different signs and/or zero. Instead it will stay in the current sign domain and ignore all parts of the plottable that lie outside of that domain. - + \a onlyEnlarge makes sure the ranges are only expanded, never reduced. So it's possible to show multiple plottables in their entirety by multiple calls to rescaleAxes where the first call has \a onlyEnlarge set to false (the default), and all subsequent set to true. - + \see rescaleKeyAxis, rescaleValueAxis, QCustomPlot::rescaleAxes, QCPAxis::rescale */ void QCPAbstractPlottable::rescaleAxes(bool onlyEnlarge) const { - rescaleKeyAxis(onlyEnlarge); - rescaleValueAxis(onlyEnlarge); + rescaleKeyAxis(onlyEnlarge); + rescaleValueAxis(onlyEnlarge); } /*! Rescales the key axis of the plottable so the whole plottable is visible. - + See \ref rescaleAxes for detailed behaviour. */ void QCPAbstractPlottable::rescaleKeyAxis(bool onlyEnlarge) const { - 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); - if (foundRange) - { - if (onlyEnlarge) - newRange.expand(keyAxis->range()); - if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable - { - double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason - if (keyAxis->scaleType() == QCPAxis::stLinear) - { - newRange.lower = center-keyAxis->range().size()/2.0; - newRange.upper = center+keyAxis->range().size()/2.0; - } else // scaleType() == stLogarithmic - { - newRange.lower = center/qSqrt(keyAxis->range().upper/keyAxis->range().lower); - newRange.upper = center*qSqrt(keyAxis->range().upper/keyAxis->range().lower); - } + 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); + if (foundRange) { + if (onlyEnlarge) { + newRange.expand(keyAxis->range()); + } + if (!QCPRange::validRange(newRange)) { // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable + double center = (newRange.lower + newRange.upper) * 0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason + if (keyAxis->scaleType() == QCPAxis::stLinear) { + newRange.lower = center - keyAxis->range().size() / 2.0; + newRange.upper = center + keyAxis->range().size() / 2.0; + } else { // scaleType() == stLogarithmic + newRange.lower = center / qSqrt(keyAxis->range().upper / keyAxis->range().lower); + newRange.upper = center * qSqrt(keyAxis->range().upper / keyAxis->range().lower); + } + } + keyAxis->setRange(newRange); } - keyAxis->setRange(newRange); - } } /*! Rescales the value axis of the plottable so the whole plottable is visible. - + 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 { - 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); - if (foundRange) - { - if (onlyEnlarge) - newRange.expand(valueAxis->range()); - if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable - { - double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason - if (valueAxis->scaleType() == QCPAxis::stLinear) - { - newRange.lower = center-valueAxis->range().size()/2.0; - newRange.upper = center+valueAxis->range().size()/2.0; - } else // scaleType() == stLogarithmic - { - newRange.lower = center/qSqrt(valueAxis->range().upper/valueAxis->range().lower); - newRange.upper = center*qSqrt(valueAxis->range().upper/valueAxis->range().lower); - } + 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); + if (foundRange) { + if (onlyEnlarge) { + newRange.expand(valueAxis->range()); + } + if (!QCPRange::validRange(newRange)) { // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable + double center = (newRange.lower + newRange.upper) * 0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason + if (valueAxis->scaleType() == QCPAxis::stLinear) { + newRange.lower = center - valueAxis->range().size() / 2.0; + newRange.upper = center + valueAxis->range().size() / 2.0; + } else { // scaleType() == stLogarithmic + newRange.lower = center / qSqrt(valueAxis->range().upper / valueAxis->range().lower); + newRange.upper = center * qSqrt(valueAxis->range().upper / valueAxis->range().lower); + } + } + valueAxis->setRange(newRange); } - valueAxis->setRange(newRange); - } } /*! 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. - + \see removeFromLegend, QCPLegend::addItem */ bool QCPAbstractPlottable::addToLegend() { - if (!mParentPlot || !mParentPlot->legend) - return false; - - if (!mParentPlot->legend->hasItemWithPlottable(this)) - { - mParentPlot->legend->addItem(new QCPPlottableLegendItem(mParentPlot->legend, this)); - return true; - } else - return false; + if (!mParentPlot || !mParentPlot->legend) { + return false; + } + + if (!mParentPlot->legend->hasItemWithPlottable(this)) { + mParentPlot->legend->addItem(new QCPPlottableLegendItem(mParentPlot->legend, this)); + return true; + } else { + return false; + } } /*! Removes the plottable from the legend of the parent QCustomPlot. This means the QCPAbstractLegendItem (usually a QCPPlottableLegendItem) that is associated with this plottable is removed. - + Returns true on success, i.e. if the legend exists and a legend item associated with this plottable was found and removed. - + \see addToLegend, QCPLegend::removeItem */ bool QCPAbstractPlottable::removeFromLegend() const { - if (!mParentPlot->legend) - return false; - - if (QCPPlottableLegendItem *lip = mParentPlot->legend->itemWithPlottable(this)) - return mParentPlot->legend->removeItem(lip); - else - return false; + if (!mParentPlot->legend) { + return false; + } + + if (QCPPlottableLegendItem *lip = mParentPlot->legend->itemWithPlottable(this)) { + return mParentPlot->legend->removeItem(lip); + } else { + return false; + } } /* inherits documentation from base class */ QRect QCPAbstractPlottable::clipRect() const { - if (mKeyAxis && mValueAxis) - return mKeyAxis.data()->axisRect()->rect() & mValueAxis.data()->axisRect()->rect(); - else - return QRect(); + if (mKeyAxis && mValueAxis) { + return mKeyAxis.data()->axisRect()->rect() & mValueAxis.data()->axisRect()->rect(); + } else { + return QRect(); + } } /* inherits documentation from base class */ QCP::Interaction QCPAbstractPlottable::selectionCategory() const { - return QCP::iSelectPlottables; + 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); - } + 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)); + 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); - } + 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 @@ -7258,7 +7249,7 @@ void QCPAbstractPlottable::pixelsToCoords(double x, double y, double &key, doubl */ void QCPAbstractPlottable::pixelsToCoords(const QPointF &pixelPos, double &key, double &value) const { - pixelsToCoords(pixelPos.x(), pixelPos.y(), key, value); + pixelsToCoords(pixelPos.x(), pixelPos.y(), key, value); } /*! \internal @@ -7268,7 +7259,7 @@ void QCPAbstractPlottable::pixelsToCoords(const QPointF &pixelPos, double &key, */ QPen QCPAbstractPlottable::mainPen() const { - return mSelected ? mSelectedPen : mPen; + return mSelected ? mSelectedPen : mPen; } /*! \internal @@ -7278,7 +7269,7 @@ QPen QCPAbstractPlottable::mainPen() const */ QBrush QCPAbstractPlottable::mainBrush() const { - return mSelected ? mSelectedBrush : mBrush; + return mSelected ? mSelectedBrush : mBrush; } /*! \internal @@ -7287,121 +7278,122 @@ QBrush QCPAbstractPlottable::mainBrush() const before drawing plottable lines. This is the antialiasing state the painter passed to the \ref draw method is in by default. - + 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, applyErrorBarsAntialiasingHint */ void QCPAbstractPlottable::applyDefaultAntialiasingHint(QCPPainter *painter) const { - applyAntialiasingHint(painter, mAntialiased, QCP::aePlottables); + applyAntialiasingHint(painter, mAntialiased, QCP::aePlottables); } /*! \internal A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter before drawing plottable fills. - + 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, applyDefaultAntialiasingHint, applyScattersAntialiasingHint, applyErrorBarsAntialiasingHint */ void QCPAbstractPlottable::applyFillAntialiasingHint(QCPPainter *painter) const { - applyAntialiasingHint(painter, mAntialiasedFill, QCP::aeFills); + applyAntialiasingHint(painter, mAntialiasedFill, QCP::aeFills); } /*! \internal A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter before drawing plottable scatter points. - + 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, applyDefaultAntialiasingHint, applyErrorBarsAntialiasingHint */ void QCPAbstractPlottable::applyScattersAntialiasingHint(QCPPainter *painter) const { - applyAntialiasingHint(painter, mAntialiasedScatters, QCP::aeScatters); + 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); + 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(); + 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) - { - bool selBefore = mSelected; - setSelected(additive ? !mSelected : true); - if (selectionStateChanged) - *selectionStateChanged = mSelected != selBefore; - } + Q_UNUSED(event) + Q_UNUSED(details) + if (mSelectable) { + bool selBefore = mSelected; + setSelected(additive ? !mSelected : true); + if (selectionStateChanged) { + *selectionStateChanged = mSelected != selBefore; + } + } } /* inherits documentation from base class */ void QCPAbstractPlottable::deselectEvent(bool *selectionStateChanged) { - if (mSelectable) - { - bool selBefore = mSelected; - setSelected(false); - if (selectionStateChanged) - *selectionStateChanged = mSelected != selBefore; - } + if (mSelectable) { + bool selBefore = mSelected; + setSelected(false); + if (selectionStateChanged) { + *selectionStateChanged = mSelected != selBefore; + } + } } @@ -7411,7 +7403,7 @@ void QCPAbstractPlottable::deselectEvent(bool *selectionStateChanged) /*! \class QCPItemAnchor \brief An anchor of an item to which positions can be attached to. - + An item (QCPAbstractItem) may have one or more anchors. Unlike QCPItemPosition, an anchor doesn't control anything on its item, but provides a way to tie other items via their positions to the anchor. @@ -7422,10 +7414,10 @@ void QCPAbstractPlottable::deselectEvent(bool *selectionStateChanged) calling QCPItemPosition::setParentAnchor on \a start, passing the wanted anchor of the QCPItemRect. This way the start of the line will now always follow the respective anchor location on the rect item. - + Note that QCPItemPosition derives from QCPItemAnchor, so every position can also serve as an anchor to other positions. - + To learn how to provide anchors in your own item subclasses, see the subclassing section of the QCPAbstractItem documentation. */ @@ -7433,10 +7425,10 @@ void QCPAbstractPlottable::deselectEvent(bool *selectionStateChanged) /* start documentation of inline functions */ /*! \fn virtual QCPItemPosition *QCPItemAnchor::toQCPItemPosition() - + Returns 0 if this instance is merely a QCPItemAnchor, and a valid pointer of type QCPItemPosition* if it actually is a QCPItemPosition (which is a subclass of QCPItemAnchor). - + This safe downcast functionality could also be achieved with a dynamic_cast. However, QCustomPlot avoids dynamic_cast to work with projects that don't have RTTI support enabled (e.g. -fno-rtti flag with gcc compiler). @@ -7450,51 +7442,47 @@ void QCPAbstractPlottable::deselectEvent(bool *selectionStateChanged) explained in the subclassing section of the QCPAbstractItem documentation. */ QCPItemAnchor::QCPItemAnchor(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString name, int anchorId) : - mName(name), - mParentPlot(parentPlot), - mParentItem(parentItem), - mAnchorId(anchorId) + mName(name), + mParentPlot(parentPlot), + mParentItem(parentItem), + mAnchorId(anchorId) { } QCPItemAnchor::~QCPItemAnchor() { - // unregister as parent at children: - foreach (QCPItemPosition *child, mChildrenX.toList()) - { - if (child->parentAnchorX() == this) - child->setParentAnchorX(0); // this acts back on this anchor and child removes itself from mChildrenX - } - foreach (QCPItemPosition *child, mChildrenY.toList()) - { - if (child->parentAnchorY() == this) - child->setParentAnchorY(0); // this acts back on this anchor and child removes itself from mChildrenY - } + // unregister as parent at children: + foreach (QCPItemPosition *child, mChildrenX.toList()) { + if (child->parentAnchorX() == this) { + child->setParentAnchorX(0); // this acts back on this anchor and child removes itself from mChildrenX + } + } + foreach (QCPItemPosition *child, mChildrenY.toList()) { + if (child->parentAnchorY() == this) { + child->setParentAnchorY(0); // this acts back on this anchor and child removes itself from mChildrenY + } + } } /*! Returns the final absolute pixel position of the QCPItemAnchor on the QCustomPlot surface. - + The pixel information is internally retrieved via QCPAbstractItem::anchorPixelPosition of the parent item, QCPItemAnchor is just an intermediary. */ QPointF QCPItemAnchor::pixelPoint() const { - if (mParentItem) - { - if (mAnchorId > -1) - { - return mParentItem->anchorPixelPoint(mAnchorId); - } else - { - qDebug() << Q_FUNC_INFO << "no valid anchor id set:" << mAnchorId; - return QPointF(); + if (mParentItem) { + if (mAnchorId > -1) { + return mParentItem->anchorPixelPoint(mAnchorId); + } else { + qDebug() << Q_FUNC_INFO << "no valid anchor id set:" << mAnchorId; + return QPointF(); + } + } else { + qDebug() << Q_FUNC_INFO << "no parent item set"; + return QPointF(); } - } else - { - qDebug() << Q_FUNC_INFO << "no parent item set"; - return QPointF(); - } } /*! \internal @@ -7502,27 +7490,29 @@ QPointF QCPItemAnchor::pixelPoint() const Adds \a pos to the childX list of this anchor, which keeps track of which children use this anchor as parent anchor for the respective coordinate. This is necessary to notify the children prior to destruction of the anchor. - + Note that this function does not change the parent setting in \a pos. */ void QCPItemAnchor::addChildX(QCPItemPosition *pos) { - if (!mChildrenX.contains(pos)) - mChildrenX.insert(pos); - else - qDebug() << Q_FUNC_INFO << "provided pos is child already" << reinterpret_cast(pos); + if (!mChildrenX.contains(pos)) { + mChildrenX.insert(pos); + } else { + qDebug() << Q_FUNC_INFO << "provided pos is child already" << reinterpret_cast(pos); + } } /*! \internal Removes \a pos from the childX list of this anchor. - + Note that this function does not change the parent setting in \a pos. */ void QCPItemAnchor::removeChildX(QCPItemPosition *pos) { - if (!mChildrenX.remove(pos)) - qDebug() << Q_FUNC_INFO << "provided pos isn't child" << reinterpret_cast(pos); + if (!mChildrenX.remove(pos)) { + qDebug() << Q_FUNC_INFO << "provided pos isn't child" << reinterpret_cast(pos); + } } /*! \internal @@ -7530,27 +7520,29 @@ void QCPItemAnchor::removeChildX(QCPItemPosition *pos) Adds \a pos to the childY list of this anchor, which keeps track of which children use this anchor as parent anchor for the respective coordinate. This is necessary to notify the children prior to destruction of the anchor. - + Note that this function does not change the parent setting in \a pos. */ void QCPItemAnchor::addChildY(QCPItemPosition *pos) { - if (!mChildrenY.contains(pos)) - mChildrenY.insert(pos); - else - qDebug() << Q_FUNC_INFO << "provided pos is child already" << reinterpret_cast(pos); + if (!mChildrenY.contains(pos)) { + mChildrenY.insert(pos); + } else { + qDebug() << Q_FUNC_INFO << "provided pos is child already" << reinterpret_cast(pos); + } } /*! \internal Removes \a pos from the childY list of this anchor. - + Note that this function does not change the parent setting in \a pos. */ void QCPItemAnchor::removeChildY(QCPItemPosition *pos) { - if (!mChildrenY.remove(pos)) - qDebug() << Q_FUNC_INFO << "provided pos isn't child" << reinterpret_cast(pos); + if (!mChildrenY.remove(pos)) { + qDebug() << Q_FUNC_INFO << "provided pos isn't child" << reinterpret_cast(pos); + } } @@ -7560,7 +7552,7 @@ void QCPItemAnchor::removeChildY(QCPItemPosition *pos) /*! \class QCPItemPosition \brief Manages the position of an item. - + Every item has at least one public QCPItemPosition member pointer which provides ways to position the item on the QCustomPlot surface. Some items have multiple positions, for example QCPItemRect has two: \a topLeft and \a bottomRight. @@ -7595,23 +7587,23 @@ void QCPItemAnchor::removeChildY(QCPItemPosition *pos) /* start documentation of inline functions */ /*! \fn QCPItemPosition::PositionType *QCPItemPosition::type() const - + Returns the current position type. - + If different types were set for X and Y (\ref setTypeX, \ref setTypeY), this method returns the type of the X coordinate. In that case rather use \a typeX() and \a typeY(). - + \see setType */ /*! \fn QCPItemAnchor *QCPItemPosition::parentAnchor() const - + Returns the current parent anchor. - + If different parent anchors were set for X and Y (\ref setParentAnchorX, \ref setParentAnchorY), this method returns the parent anchor of the Y coordinate. In that case rather use \a parentAnchorX() and \a parentAnchorY(). - + \see setParentAnchor */ @@ -7623,133 +7615,141 @@ void QCPItemAnchor::removeChildY(QCPItemPosition *pos) explained in the subclassing section of the QCPAbstractItem documentation. */ QCPItemPosition::QCPItemPosition(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString name) : - QCPItemAnchor(parentPlot, parentItem, name), - mPositionTypeX(ptAbsolute), - mPositionTypeY(ptAbsolute), - mKey(0), - mValue(0), - mParentAnchorX(0), - mParentAnchorY(0) + QCPItemAnchor(parentPlot, parentItem, name), + mPositionTypeX(ptAbsolute), + mPositionTypeY(ptAbsolute), + mKey(0), + mValue(0), + mParentAnchorX(0), + mParentAnchorY(0) { } 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 - foreach (QCPItemPosition *child, mChildrenX.toList()) - { - if (child->parentAnchorX() == this) - child->setParentAnchorX(0); // this acts back on this anchor and child removes itself from mChildrenX - } - foreach (QCPItemPosition *child, mChildrenY.toList()) - { - if (child->parentAnchorY() == this) - child->setParentAnchorY(0); // this acts back on this anchor and child removes itself from mChildrenY - } - // unregister as child in parent: - if (mParentAnchorX) - mParentAnchorX->removeChildX(this); - if (mParentAnchorY) - mParentAnchorY->removeChildY(this); + // 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 + foreach (QCPItemPosition *child, mChildrenX.toList()) { + if (child->parentAnchorX() == this) { + child->setParentAnchorX(0); // this acts back on this anchor and child removes itself from mChildrenX + } + } + foreach (QCPItemPosition *child, mChildrenY.toList()) { + if (child->parentAnchorY() == this) { + child->setParentAnchorY(0); // this acts back on this anchor and child removes itself from mChildrenY + } + } + // unregister as child in parent: + if (mParentAnchorX) { + mParentAnchorX->removeChildX(this); + } + if (mParentAnchorY) { + mParentAnchorY->removeChildY(this); + } } /* can't make this a header inline function, because QPointer breaks with forward declared types, see QTBUG-29588 */ QCPAxisRect *QCPItemPosition::axisRect() const { - return mAxisRect.data(); + return mAxisRect.data(); } /*! Sets the type of the position. The type defines how the coordinates passed to \ref setCoords should be handled and how the QCPItemPosition should behave in the plot. - + The possible values for \a type can be separated in two main categories: \li The position is regarded as a point in plot coordinates. This corresponds to \ref ptPlotCoords and requires two axes that define the plot coordinate system. They can be specified with \ref setAxes. By default, the QCustomPlot's x- and yAxis are used. - + \li The position is fixed on the QCustomPlot surface, i.e. independent of axis ranges. This corresponds to all other types, i.e. \ref ptAbsolute, \ref ptViewportRatio and \ref ptAxisRectRatio. They differ only in the way the absolute position is described, see the documentation of \ref PositionType for details. For \ref ptAxisRectRatio, note that you can specify the axis rect with \ref setAxisRect. By default this is set to the main axis rect. - + Note that the position type \ref ptPlotCoords is only available (and sensible) when the position has no parent anchor (\ref setParentAnchor). - + If the type is changed, the apparent pixel position on the plot is preserved. This means the coordinates as retrieved with coords() and set with \ref setCoords may change in the process. - + This method sets the type for both X and Y directions. It is also possible to set different types for X and Y, see \ref setTypeX, \ref setTypeY. */ void QCPItemPosition::setType(QCPItemPosition::PositionType type) { - setTypeX(type); - setTypeY(type); + setTypeX(type); + setTypeY(type); } /*! This method sets the position type of the X coordinate to \a type. - + For a detailed description of what a position type is, see the documentation of \ref setType. - + \see setType, setTypeY */ 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. - bool retainPixelPosition = true; - if ((mPositionTypeX == ptPlotCoords || type == ptPlotCoords) && (!mKeyAxis || !mValueAxis)) - retainPixelPosition = false; - if ((mPositionTypeX == ptAxisRectRatio || type == ptAxisRectRatio) && (!mAxisRect)) - retainPixelPosition = false; - - QPointF pixel; - if (retainPixelPosition) - pixel = pixelPoint(); - - mPositionTypeX = type; - - if (retainPixelPosition) - setPixelPoint(pixel); - } + 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. + bool retainPixelPosition = true; + if ((mPositionTypeX == ptPlotCoords || type == ptPlotCoords) && (!mKeyAxis || !mValueAxis)) { + retainPixelPosition = false; + } + if ((mPositionTypeX == ptAxisRectRatio || type == ptAxisRectRatio) && (!mAxisRect)) { + retainPixelPosition = false; + } + + QPointF pixel; + if (retainPixelPosition) { + pixel = pixelPoint(); + } + + mPositionTypeX = type; + + if (retainPixelPosition) { + setPixelPoint(pixel); + } + } } /*! This method sets the position type of the Y coordinate to \a type. - + For a detailed description of what a position type is, see the documentation of \ref setType. - + \see setType, setTypeX */ 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. - bool retainPixelPosition = true; - if ((mPositionTypeY == ptPlotCoords || type == ptPlotCoords) && (!mKeyAxis || !mValueAxis)) - retainPixelPosition = false; - if ((mPositionTypeY == ptAxisRectRatio || type == ptAxisRectRatio) && (!mAxisRect)) - retainPixelPosition = false; - - QPointF pixel; - if (retainPixelPosition) - pixel = pixelPoint(); - - mPositionTypeY = type; - - if (retainPixelPosition) - setPixelPoint(pixel); - } + 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. + bool retainPixelPosition = true; + if ((mPositionTypeY == ptPlotCoords || type == ptPlotCoords) && (!mKeyAxis || !mValueAxis)) { + retainPixelPosition = false; + } + if ((mPositionTypeY == ptAxisRectRatio || type == ptAxisRectRatio) && (!mAxisRect)) { + retainPixelPosition = false; + } + + QPointF pixel; + if (retainPixelPosition) { + pixel = pixelPoint(); + } + + mPositionTypeY = type; + + if (retainPixelPosition) { + setPixelPoint(pixel); + } + } } /*! @@ -7757,167 +7757,165 @@ void QCPItemPosition::setTypeY(QCPItemPosition::PositionType type) follow any position changes of the anchor. The local coordinate system of positions with a parent anchor always is absolute pixels, with (0, 0) being exactly on top of the parent anchor. (Hence the type shouldn't be set to \ref ptPlotCoords for positions with parent anchors.) - + if \a keepPixelPosition is true, the current pixel position of the QCPItemPosition is preserved during reparenting. If it's set to false, the coordinates are set to (0, 0), i.e. the position will be exactly on top of the parent anchor. - + To remove this QCPItemPosition from any parent anchor, set \a parentAnchor to 0. - + If the QCPItemPosition previously had no parent and the type is \ref ptPlotCoords, the type is set to \ref ptAbsolute, to keep the position in a valid state. - + This method sets the parent anchor for both X and Y directions. It is also possible to set different parents for X and Y, see \ref setParentAnchorX, \ref setParentAnchorY. */ bool QCPItemPosition::setParentAnchor(QCPItemAnchor *parentAnchor, bool keepPixelPosition) { - bool successX = setParentAnchorX(parentAnchor, keepPixelPosition); - bool successY = setParentAnchorY(parentAnchor, keepPixelPosition); - return successX && successY; + bool successX = setParentAnchorX(parentAnchor, keepPixelPosition); + bool successY = setParentAnchorY(parentAnchor, keepPixelPosition); + return successX && successY; } /*! This method sets the parent anchor of the X coordinate to \a parentAnchor. - + For a detailed description of what a parent anchor is, see the documentation of \ref setParentAnchor. - + \see setParentAnchor, setParentAnchorY */ bool QCPItemPosition::setParentAnchorX(QCPItemAnchor *parentAnchor, bool keepPixelPosition) { - // make sure self is not assigned as parent: - if (parentAnchor == this) - { - qDebug() << Q_FUNC_INFO << "can't set self as parent anchor" << reinterpret_cast(parentAnchor); - return false; - } - // make sure no recursive parent-child-relationships are created: - QCPItemAnchor *currentParent = parentAnchor; - while (currentParent) - { - if (QCPItemPosition *currentParentPos = currentParent->toQCPItemPosition()) - { - // is a QCPItemPosition, might have further parent, so keep iterating - if (currentParentPos == this) - { - qDebug() << Q_FUNC_INFO << "can't create recursive parent-child-relationship" << reinterpret_cast(parentAnchor); + // make sure self is not assigned as parent: + if (parentAnchor == this) { + qDebug() << Q_FUNC_INFO << "can't set self as parent anchor" << reinterpret_cast(parentAnchor); return false; - } - currentParent = currentParentPos->parentAnchorX(); - } else - { - // is a QCPItemAnchor, can't have further parent. Now make sure the parent items aren't the - // same, to prevent a position being child of an anchor which itself depends on the position, - // because they're both on the same item: - if (currentParent->mParentItem == mParentItem) - { - qDebug() << Q_FUNC_INFO << "can't set parent to be an anchor which itself depends on this position" << reinterpret_cast(parentAnchor); - return false; - } - break; } - } - - // if previously no parent set and PosType is still ptPlotCoords, set to ptAbsolute: - if (!mParentAnchorX && mPositionTypeX == ptPlotCoords) - setTypeX(ptAbsolute); - - // save pixel position: - QPointF pixelP; - if (keepPixelPosition) - pixelP = pixelPoint(); - // unregister at current parent anchor: - if (mParentAnchorX) - mParentAnchorX->removeChildX(this); - // register at new parent anchor: - if (parentAnchor) - parentAnchor->addChildX(this); - mParentAnchorX = parentAnchor; - // restore pixel position under new parent: - if (keepPixelPosition) - setPixelPoint(pixelP); - else - setCoords(0, coords().y()); - return true; + // make sure no recursive parent-child-relationships are created: + QCPItemAnchor *currentParent = parentAnchor; + while (currentParent) { + if (QCPItemPosition *currentParentPos = currentParent->toQCPItemPosition()) { + // is a QCPItemPosition, might have further parent, so keep iterating + if (currentParentPos == this) { + qDebug() << Q_FUNC_INFO << "can't create recursive parent-child-relationship" << reinterpret_cast(parentAnchor); + return false; + } + currentParent = currentParentPos->parentAnchorX(); + } else { + // is a QCPItemAnchor, can't have further parent. Now make sure the parent items aren't the + // same, to prevent a position being child of an anchor which itself depends on the position, + // because they're both on the same item: + if (currentParent->mParentItem == mParentItem) { + qDebug() << Q_FUNC_INFO << "can't set parent to be an anchor which itself depends on this position" << reinterpret_cast(parentAnchor); + return false; + } + break; + } + } + + // if previously no parent set and PosType is still ptPlotCoords, set to ptAbsolute: + if (!mParentAnchorX && mPositionTypeX == ptPlotCoords) { + setTypeX(ptAbsolute); + } + + // save pixel position: + QPointF pixelP; + if (keepPixelPosition) { + pixelP = pixelPoint(); + } + // unregister at current parent anchor: + if (mParentAnchorX) { + mParentAnchorX->removeChildX(this); + } + // register at new parent anchor: + if (parentAnchor) { + parentAnchor->addChildX(this); + } + mParentAnchorX = parentAnchor; + // restore pixel position under new parent: + if (keepPixelPosition) { + setPixelPoint(pixelP); + } else { + setCoords(0, coords().y()); + } + return true; } /*! This method sets the parent anchor of the Y coordinate to \a parentAnchor. - + For a detailed description of what a parent anchor is, see the documentation of \ref setParentAnchor. - + \see setParentAnchor, setParentAnchorX */ bool QCPItemPosition::setParentAnchorY(QCPItemAnchor *parentAnchor, bool keepPixelPosition) { - // make sure self is not assigned as parent: - if (parentAnchor == this) - { - qDebug() << Q_FUNC_INFO << "can't set self as parent anchor" << reinterpret_cast(parentAnchor); - return false; - } - // make sure no recursive parent-child-relationships are created: - QCPItemAnchor *currentParent = parentAnchor; - while (currentParent) - { - if (QCPItemPosition *currentParentPos = currentParent->toQCPItemPosition()) - { - // is a QCPItemPosition, might have further parent, so keep iterating - if (currentParentPos == this) - { - qDebug() << Q_FUNC_INFO << "can't create recursive parent-child-relationship" << reinterpret_cast(parentAnchor); + // make sure self is not assigned as parent: + if (parentAnchor == this) { + qDebug() << Q_FUNC_INFO << "can't set self as parent anchor" << reinterpret_cast(parentAnchor); return false; - } - currentParent = currentParentPos->parentAnchorY(); - } else - { - // is a QCPItemAnchor, can't have further parent. Now make sure the parent items aren't the - // same, to prevent a position being child of an anchor which itself depends on the position, - // because they're both on the same item: - if (currentParent->mParentItem == mParentItem) - { - qDebug() << Q_FUNC_INFO << "can't set parent to be an anchor which itself depends on this position" << reinterpret_cast(parentAnchor); - return false; - } - break; } - } - - // if previously no parent set and PosType is still ptPlotCoords, set to ptAbsolute: - if (!mParentAnchorY && mPositionTypeY == ptPlotCoords) - setTypeY(ptAbsolute); - - // save pixel position: - QPointF pixelP; - if (keepPixelPosition) - pixelP = pixelPoint(); - // unregister at current parent anchor: - if (mParentAnchorY) - mParentAnchorY->removeChildY(this); - // register at new parent anchor: - if (parentAnchor) - parentAnchor->addChildY(this); - mParentAnchorY = parentAnchor; - // restore pixel position under new parent: - if (keepPixelPosition) - setPixelPoint(pixelP); - else - setCoords(coords().x(), 0); - return true; + // make sure no recursive parent-child-relationships are created: + QCPItemAnchor *currentParent = parentAnchor; + while (currentParent) { + if (QCPItemPosition *currentParentPos = currentParent->toQCPItemPosition()) { + // is a QCPItemPosition, might have further parent, so keep iterating + if (currentParentPos == this) { + qDebug() << Q_FUNC_INFO << "can't create recursive parent-child-relationship" << reinterpret_cast(parentAnchor); + return false; + } + currentParent = currentParentPos->parentAnchorY(); + } else { + // is a QCPItemAnchor, can't have further parent. Now make sure the parent items aren't the + // same, to prevent a position being child of an anchor which itself depends on the position, + // because they're both on the same item: + if (currentParent->mParentItem == mParentItem) { + qDebug() << Q_FUNC_INFO << "can't set parent to be an anchor which itself depends on this position" << reinterpret_cast(parentAnchor); + return false; + } + break; + } + } + + // if previously no parent set and PosType is still ptPlotCoords, set to ptAbsolute: + if (!mParentAnchorY && mPositionTypeY == ptPlotCoords) { + setTypeY(ptAbsolute); + } + + // save pixel position: + QPointF pixelP; + if (keepPixelPosition) { + pixelP = pixelPoint(); + } + // unregister at current parent anchor: + if (mParentAnchorY) { + mParentAnchorY->removeChildY(this); + } + // register at new parent anchor: + if (parentAnchor) { + parentAnchor->addChildY(this); + } + mParentAnchorY = parentAnchor; + // restore pixel position under new parent: + if (keepPixelPosition) { + setPixelPoint(pixelP); + } else { + setCoords(coords().x(), 0); + } + return true; } /*! Sets the coordinates of this QCPItemPosition. What the coordinates mean, is defined by the type (\ref setType, \ref setTypeX, \ref setTypeY). - + For example, if the type is \ref ptAbsolute, \a key and \a value mean the x and y pixel position on the QCustomPlot surface. In that case the origin (0, 0) is in the top left corner of the QCustomPlot viewport. If the type is \ref ptPlotCoords, \a key and \a value mean a point in the plot coordinate system defined by the axes set by \ref setAxes. By default those are the QCustomPlot's xAxis and yAxis. See the documentation of \ref setType for other available coordinate types and their meaning. - + If different types were configured for X and Y (\ref setTypeX, \ref setTypeY), \a key and \a 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. @@ -7926,8 +7924,8 @@ bool QCPItemPosition::setParentAnchorY(QCPItemAnchor *parentAnchor, bool keepPix */ void QCPItemPosition::setCoords(double key, double value) { - mKey = key; - mValue = value; + mKey = key; + mValue = value; } /*! \overload @@ -7937,7 +7935,7 @@ void QCPItemPosition::setCoords(double key, double value) */ void QCPItemPosition::setCoords(const QPointF &pos) { - setCoords(pos.x(), pos.y()); + setCoords(pos.x(), pos.y()); } /*! @@ -7948,97 +7946,95 @@ void QCPItemPosition::setCoords(const QPointF &pos) */ QPointF QCPItemPosition::pixelPoint() const { - QPointF result; - - // determine X: - switch (mPositionTypeX) - { - case ptAbsolute: - { - result.rx() = mKey; - if (mParentAnchorX) - result.rx() += mParentAnchorX->pixelPoint().x(); - break; + QPointF result; + + // determine X: + switch (mPositionTypeX) { + case ptAbsolute: { + result.rx() = mKey; + if (mParentAnchorX) { + result.rx() += mParentAnchorX->pixelPoint().x(); + } + break; + } + case ptViewportRatio: { + result.rx() = mKey * mParentPlot->viewport().width(); + if (mParentAnchorX) { + result.rx() += mParentAnchorX->pixelPoint().x(); + } else { + result.rx() += mParentPlot->viewport().left(); + } + break; + } + case ptAxisRectRatio: { + if (mAxisRect) { + result.rx() = mKey * mAxisRect.data()->width(); + if (mParentAnchorX) { + result.rx() += mParentAnchorX->pixelPoint().x(); + } else { + result.rx() += mAxisRect.data()->left(); + } + } else { + qDebug() << Q_FUNC_INFO << "Item position type x is ptAxisRectRatio, but no axis rect was defined"; + } + break; + } + case ptPlotCoords: { + if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Horizontal) { + result.rx() = mKeyAxis.data()->coordToPixel(mKey); + } else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Horizontal) { + result.rx() = mValueAxis.data()->coordToPixel(mValue); + } else { + qDebug() << Q_FUNC_INFO << "Item position type x is ptPlotCoords, but no axes were defined"; + } + break; + } } - case ptViewportRatio: - { - result.rx() = mKey*mParentPlot->viewport().width(); - if (mParentAnchorX) - result.rx() += mParentAnchorX->pixelPoint().x(); - else - result.rx() += mParentPlot->viewport().left(); - break; + + // determine Y: + switch (mPositionTypeY) { + case ptAbsolute: { + result.ry() = mValue; + if (mParentAnchorY) { + result.ry() += mParentAnchorY->pixelPoint().y(); + } + break; + } + case ptViewportRatio: { + result.ry() = mValue * mParentPlot->viewport().height(); + if (mParentAnchorY) { + result.ry() += mParentAnchorY->pixelPoint().y(); + } else { + result.ry() += mParentPlot->viewport().top(); + } + break; + } + case ptAxisRectRatio: { + if (mAxisRect) { + result.ry() = mValue * mAxisRect.data()->height(); + if (mParentAnchorY) { + result.ry() += mParentAnchorY->pixelPoint().y(); + } else { + result.ry() += mAxisRect.data()->top(); + } + } else { + qDebug() << Q_FUNC_INFO << "Item position type y is ptAxisRectRatio, but no axis rect was defined"; + } + break; + } + case ptPlotCoords: { + if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Vertical) { + result.ry() = mKeyAxis.data()->coordToPixel(mKey); + } else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Vertical) { + result.ry() = mValueAxis.data()->coordToPixel(mValue); + } else { + qDebug() << Q_FUNC_INFO << "Item position type y is ptPlotCoords, but no axes were defined"; + } + break; + } } - case ptAxisRectRatio: - { - if (mAxisRect) - { - result.rx() = mKey*mAxisRect.data()->width(); - if (mParentAnchorX) - result.rx() += mParentAnchorX->pixelPoint().x(); - else - result.rx() += mAxisRect.data()->left(); - } else - qDebug() << Q_FUNC_INFO << "Item position type x is ptAxisRectRatio, but no axis rect was defined"; - break; - } - case ptPlotCoords: - { - if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Horizontal) - result.rx() = mKeyAxis.data()->coordToPixel(mKey); - else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Horizontal) - result.rx() = mValueAxis.data()->coordToPixel(mValue); - else - qDebug() << Q_FUNC_INFO << "Item position type x is ptPlotCoords, but no axes were defined"; - break; - } - } - - // determine Y: - switch (mPositionTypeY) - { - case ptAbsolute: - { - result.ry() = mValue; - if (mParentAnchorY) - result.ry() += mParentAnchorY->pixelPoint().y(); - break; - } - case ptViewportRatio: - { - result.ry() = mValue*mParentPlot->viewport().height(); - if (mParentAnchorY) - result.ry() += mParentAnchorY->pixelPoint().y(); - else - result.ry() += mParentPlot->viewport().top(); - break; - } - case ptAxisRectRatio: - { - if (mAxisRect) - { - result.ry() = mValue*mAxisRect.data()->height(); - if (mParentAnchorY) - result.ry() += mParentAnchorY->pixelPoint().y(); - else - result.ry() += mAxisRect.data()->top(); - } else - qDebug() << Q_FUNC_INFO << "Item position type y is ptAxisRectRatio, but no axis rect was defined"; - break; - } - case ptPlotCoords: - { - if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Vertical) - result.ry() = mKeyAxis.data()->coordToPixel(mKey); - else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Vertical) - result.ry() = mValueAxis.data()->coordToPixel(mValue); - else - qDebug() << Q_FUNC_INFO << "Item position type y is ptPlotCoords, but no axes were defined"; - break; - } - } - - return result; + + return result; } /*! @@ -8048,8 +8044,8 @@ QPointF QCPItemPosition::pixelPoint() const */ void QCPItemPosition::setAxes(QCPAxis *keyAxis, QCPAxis *valueAxis) { - mKeyAxis = keyAxis; - mValueAxis = valueAxis; + mKeyAxis = keyAxis; + mValueAxis = valueAxis; } /*! @@ -8059,7 +8055,7 @@ void QCPItemPosition::setAxes(QCPAxis *keyAxis, QCPAxis *valueAxis) */ void QCPItemPosition::setAxisRect(QCPAxisRect *axisRect) { - mAxisRect = axisRect; + mAxisRect = axisRect; } /*! @@ -8074,94 +8070,92 @@ void QCPItemPosition::setAxisRect(QCPAxisRect *axisRect) */ void QCPItemPosition::setPixelPoint(const QPointF &pixelPoint) { - double x = pixelPoint.x(); - double y = pixelPoint.y(); - - switch (mPositionTypeX) - { - case ptAbsolute: - { - if (mParentAnchorX) - x -= mParentAnchorX->pixelPoint().x(); - break; + double x = pixelPoint.x(); + double y = pixelPoint.y(); + + switch (mPositionTypeX) { + case ptAbsolute: { + if (mParentAnchorX) { + x -= mParentAnchorX->pixelPoint().x(); + } + break; + } + case ptViewportRatio: { + if (mParentAnchorX) { + x -= mParentAnchorX->pixelPoint().x(); + } else { + x -= mParentPlot->viewport().left(); + } + x /= (double)mParentPlot->viewport().width(); + break; + } + case ptAxisRectRatio: { + if (mAxisRect) { + if (mParentAnchorX) { + x -= mParentAnchorX->pixelPoint().x(); + } else { + x -= mAxisRect.data()->left(); + } + x /= (double)mAxisRect.data()->width(); + } else { + qDebug() << Q_FUNC_INFO << "Item position type x is ptAxisRectRatio, but no axis rect was defined"; + } + break; + } + case ptPlotCoords: { + if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Horizontal) { + x = mKeyAxis.data()->pixelToCoord(x); + } else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Horizontal) { + y = mValueAxis.data()->pixelToCoord(x); + } else { + qDebug() << Q_FUNC_INFO << "Item position type x is ptPlotCoords, but no axes were defined"; + } + break; + } } - case ptViewportRatio: - { - if (mParentAnchorX) - x -= mParentAnchorX->pixelPoint().x(); - else - x -= mParentPlot->viewport().left(); - x /= (double)mParentPlot->viewport().width(); - break; + + switch (mPositionTypeY) { + case ptAbsolute: { + if (mParentAnchorY) { + y -= mParentAnchorY->pixelPoint().y(); + } + break; + } + case ptViewportRatio: { + if (mParentAnchorY) { + y -= mParentAnchorY->pixelPoint().y(); + } else { + y -= mParentPlot->viewport().top(); + } + y /= (double)mParentPlot->viewport().height(); + break; + } + case ptAxisRectRatio: { + if (mAxisRect) { + if (mParentAnchorY) { + y -= mParentAnchorY->pixelPoint().y(); + } else { + y -= mAxisRect.data()->top(); + } + y /= (double)mAxisRect.data()->height(); + } else { + qDebug() << Q_FUNC_INFO << "Item position type y is ptAxisRectRatio, but no axis rect was defined"; + } + break; + } + case ptPlotCoords: { + if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Vertical) { + x = mKeyAxis.data()->pixelToCoord(y); + } else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Vertical) { + y = mValueAxis.data()->pixelToCoord(y); + } else { + qDebug() << Q_FUNC_INFO << "Item position type y is ptPlotCoords, but no axes were defined"; + } + break; + } } - case ptAxisRectRatio: - { - if (mAxisRect) - { - if (mParentAnchorX) - x -= mParentAnchorX->pixelPoint().x(); - else - x -= mAxisRect.data()->left(); - x /= (double)mAxisRect.data()->width(); - } else - qDebug() << Q_FUNC_INFO << "Item position type x is ptAxisRectRatio, but no axis rect was defined"; - break; - } - case ptPlotCoords: - { - if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Horizontal) - x = mKeyAxis.data()->pixelToCoord(x); - else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Horizontal) - y = mValueAxis.data()->pixelToCoord(x); - else - qDebug() << Q_FUNC_INFO << "Item position type x is ptPlotCoords, but no axes were defined"; - break; - } - } - - switch (mPositionTypeY) - { - case ptAbsolute: - { - if (mParentAnchorY) - y -= mParentAnchorY->pixelPoint().y(); - break; - } - case ptViewportRatio: - { - if (mParentAnchorY) - y -= mParentAnchorY->pixelPoint().y(); - else - y -= mParentPlot->viewport().top(); - y /= (double)mParentPlot->viewport().height(); - break; - } - case ptAxisRectRatio: - { - if (mAxisRect) - { - if (mParentAnchorY) - y -= mParentAnchorY->pixelPoint().y(); - else - y -= mAxisRect.data()->top(); - y /= (double)mAxisRect.data()->height(); - } else - qDebug() << Q_FUNC_INFO << "Item position type y is ptAxisRectRatio, but no axis rect was defined"; - break; - } - case ptPlotCoords: - { - if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Vertical) - x = mKeyAxis.data()->pixelToCoord(y); - else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Vertical) - y = mValueAxis.data()->pixelToCoord(y); - else - qDebug() << Q_FUNC_INFO << "Item position type y is ptPlotCoords, but no axes were defined"; - break; - } - } - - setCoords(x, y); + + setCoords(x, y); } @@ -8171,18 +8165,18 @@ void QCPItemPosition::setPixelPoint(const QPointF &pixelPoint) /*! \class QCPAbstractItem \brief The abstract base class for all items in a plot. - + In QCustomPlot, items are supplemental graphical elements that are neither plottables (QCPAbstractPlottable) nor axes (QCPAxis). While plottables are always tied to two axes and thus plot coordinates, items can also be placed in absolute coordinates independent of any axes. Each specific item has at least one QCPItemPosition member which controls the positioning. Some items are defined by more than one coordinate and thus have two or more QCPItemPosition members (For example, QCPItemRect has \a topLeft and \a bottomRight). - + This abstract base class defines a very basic interface like visibility and clipping. Since this class is abstract, it can't be instantiated. Use one of the subclasses or create a subclass yourself to create new items. - + The built-in items are:
@@ -8195,7 +8189,7 @@ void QCPItemPosition::setPixelPoint(const QPointF &pixelPoint)
QCPItemLineA line defined by a start and an end point. May have different ending styles on each side (e.g. arrows).
QCPItemBracketA bracket which may be used to reference/highlight certain parts in the plot.
QCPItemTracerAn item that can be attached to a QCPGraph and sticks to its data points, given a key coordinate.
- + \section items-clipping Clipping Items are by default clipped to the main axis rect (they are only visible inside the axis rect). @@ -8207,9 +8201,9 @@ void QCPItemPosition::setPixelPoint(const QPointF &pixelPoint) in principle is independent of the coordinate axes the item might be tied to via its position members (\ref QCPItemPosition::setAxes). However, it is common that the axis rect for clipping also contains the axes used for the item positions. - + \section items-using Using items - + First you instantiate the item you want to use and add it to the plot: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-1 by default, the positions of the item are bound to the x- and y-Axis of the plot. So we can just @@ -8222,35 +8216,35 @@ void QCPItemPosition::setPixelPoint(const QPointF &pixelPoint) \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-4 and make the line visible on the entire QCustomPlot, by disabling clipping to the axis rect: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-5 - + For more advanced plots, it is even possible to set different types and parent anchors per X/Y coordinate of an item position, using for example \ref QCPItemPosition::setTypeX or \ref QCPItemPosition::setParentAnchorX. For details, see the documentation of \ref QCPItemPosition. - + \section items-subclassing Creating own items - + To create an own item, you implement a subclass of QCPAbstractItem. These are the pure virtual functions, you must implement: \li \ref selectTest \li \ref draw - + See the documentation of those functions for what they need to do. - + \subsection items-positioning Allowing the item to be positioned - + As mentioned, item positions are represented by QCPItemPosition members. Let's assume the new item shall have only one point as its position (as opposed to two like a rect or multiple like a polygon). You then add a public member of type QCPItemPosition like so: - + \code QCPItemPosition * const myPosition;\endcode - + the const makes sure the pointer itself can't be modified from the user of your new item (the QCPItemPosition instance it points to, can be modified, of course). The initialization of this pointer is made easy with the \ref createPosition function. Just assign the return value of this function to each QCPItemPosition in the constructor of your item. \ref createPosition takes a string which is the name of the position, typically this is identical to the variable name. For example, the constructor of QCPItemExample could look like this: - + \code QCPItemExample::QCPItemExample(QCustomPlot *parentPlot) : QCPAbstractItem(parentPlot), @@ -8259,9 +8253,9 @@ void QCPItemPosition::setPixelPoint(const QPointF &pixelPoint) // other constructor code } \endcode - + \subsection items-drawing The draw function - + 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. @@ -8269,19 +8263,19 @@ void QCPItemPosition::setPixelPoint(const QPointF &pixelPoint) 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 if this is the case. - + \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. - + \subsection anchors Providing anchors - + Providing anchors (QCPItemAnchor) starts off like adding a position. First you create a public member, e.g. - + \code QCPItemAnchor * const bottom;\endcode and create it in the constructor with the \ref createAnchor function, assigning it a name and an @@ -8289,7 +8283,7 @@ void QCPItemPosition::setPixelPoint(const QPointF &pixelPoint) 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 anchorId) function. - + In essence the QCPItemAnchor is merely an intermediary that itself asks your item for the pixel position when anything attached to the anchor needs to know the coordinates. */ @@ -8297,17 +8291,17 @@ void QCPItemPosition::setPixelPoint(const QPointF &pixelPoint) /* start of documentation of inline functions */ /*! \fn QList QCPAbstractItem::positions() const - + Returns all positions of the item in a list. - + \see anchors, position */ /*! \fn QList QCPAbstractItem::anchors() const - + Returns all anchors of the item in a list. Note that since a position (QCPItemPosition) is always also an anchor, the list will also contain the positions of this item. - + \see positions, anchor */ @@ -8316,9 +8310,9 @@ void QCPItemPosition::setPixelPoint(const QPointF &pixelPoint) /*! \fn void QCPAbstractItem::draw(QCPPainter *painter) = 0 \internal - + Draws this item with the provided \a painter. - + The cliprect of the provided painter is set to the rect returned by \ref clipRect before this function is called. The clipRect depends on the clipping settings defined by \ref setClipToAxisRect and \ref setClipAxisRect. @@ -8338,73 +8332,73 @@ void QCPItemPosition::setPixelPoint(const QPointF &pixelPoint) Base class constructor which initializes base class members. */ QCPAbstractItem::QCPAbstractItem(QCustomPlot *parentPlot) : - QCPLayerable(parentPlot), - mClipToAxisRect(false), - mSelectable(true), - mSelected(false) + QCPLayerable(parentPlot), + mClipToAxisRect(false), + mSelectable(true), + mSelected(false) { - QList rects = parentPlot->axisRects(); - if (rects.size() > 0) - { - setClipToAxisRect(true); - setClipAxisRect(rects.first()); - } + QList rects = parentPlot->axisRects(); + if (rects.size() > 0) { + setClipToAxisRect(true); + setClipAxisRect(rects.first()); + } } QCPAbstractItem::~QCPAbstractItem() { - // don't delete mPositions because every position is also an anchor and thus in mAnchors - qDeleteAll(mAnchors); + // don't delete mPositions because every position is also an anchor and thus in mAnchors + qDeleteAll(mAnchors); } /* can't make this a header inline function, because QPointer breaks with forward declared types, see QTBUG-29588 */ QCPAxisRect *QCPAbstractItem::clipAxisRect() const { - return mClipAxisRect.data(); + return mClipAxisRect.data(); } /*! Sets whether the item shall be clipped to an axis rect or whether it shall be visible on the entire QCustomPlot. The axis rect can be set with \ref setClipAxisRect. - + \see setClipAxisRect */ void QCPAbstractItem::setClipToAxisRect(bool clip) { - mClipToAxisRect = clip; - if (mClipToAxisRect) - setParentLayerable(mClipAxisRect.data()); + mClipToAxisRect = clip; + if (mClipToAxisRect) { + setParentLayerable(mClipAxisRect.data()); + } } /*! Sets the clip axis rect. It defines the rect that will be used to clip the item when \ref setClipToAxisRect is set to true. - + \see setClipToAxisRect */ void QCPAbstractItem::setClipAxisRect(QCPAxisRect *rect) { - mClipAxisRect = rect; - if (mClipToAxisRect) - setParentLayerable(mClipAxisRect.data()); + mClipAxisRect = rect; + if (mClipToAxisRect) { + setParentLayerable(mClipAxisRect.data()); + } } /*! Sets whether the user can (de-)select this item by clicking on the QCustomPlot surface. (When \ref QCustomPlot::setInteractions contains QCustomPlot::iSelectItems.) - + However, even when \a selectable was set to false, it is possible to set the selection manually, by calling \ref setSelected. - + \see QCustomPlot::setInteractions, setSelected */ void QCPAbstractItem::setSelectable(bool selectable) { - if (mSelectable != selectable) - { - mSelectable = selectable; - emit selectableChanged(mSelectable); - } + if (mSelectable != selectable) { + mSelectable = selectable; + emit selectableChanged(mSelectable); + } } /*! @@ -8414,97 +8408,97 @@ void QCPAbstractItem::setSelectable(bool selectable) The entire selection mechanism for items is handled automatically when \ref QCustomPlot::setInteractions contains QCustomPlot::iSelectItems. You only need to call this function when you wish to change the selection state manually. - + This function can change the selection state even when \ref setSelectable was set to false. - + emits the \ref selectionChanged signal when \a selected is different from the previous selection state. - + \see setSelectable, selectTest */ void QCPAbstractItem::setSelected(bool selected) { - if (mSelected != selected) - { - mSelected = selected; - emit selectionChanged(mSelected); - } + if (mSelected != selected) { + mSelected = selected; + emit selectionChanged(mSelected); + } } /*! Returns the QCPItemPosition with the specified \a name. If this item doesn't have a position by that name, returns 0. - + This function provides an alternative way to access item positions. Normally, you access positions direcly by their member pointers (which typically have the same variable name as \a name). - + \see positions, anchor */ QCPItemPosition *QCPAbstractItem::position(const QString &name) const { - for (int i=0; iname() == name) - return mPositions.at(i); - } - qDebug() << Q_FUNC_INFO << "position with name not found:" << name; - return 0; + for (int i = 0; i < mPositions.size(); ++i) { + if (mPositions.at(i)->name() == name) { + return mPositions.at(i); + } + } + qDebug() << Q_FUNC_INFO << "position with name not found:" << name; + return 0; } /*! Returns the QCPItemAnchor with the specified \a name. If this item doesn't have an anchor by that name, returns 0. - + This function provides an alternative way to access item anchors. Normally, you access anchors direcly by their member pointers (which typically have the same variable name as \a name). - + \see anchors, position */ QCPItemAnchor *QCPAbstractItem::anchor(const QString &name) const { - for (int i=0; iname() == name) - return mAnchors.at(i); - } - qDebug() << Q_FUNC_INFO << "anchor with name not found:" << name; - return 0; + for (int i = 0; i < mAnchors.size(); ++i) { + if (mAnchors.at(i)->name() == name) { + return mAnchors.at(i); + } + } + qDebug() << Q_FUNC_INFO << "anchor with name not found:" << name; + return 0; } /*! Returns whether this item has an anchor with the specified \a name. - + Note that you can check for positions with this function, too. This is because every position is also an anchor (QCPItemPosition inherits from QCPItemAnchor). - + \see anchor, position */ bool QCPAbstractItem::hasAnchor(const QString &name) const { - for (int i=0; iname() == name) - return true; - } - return false; + for (int i = 0; i < mAnchors.size(); ++i) { + if (mAnchors.at(i)->name() == name) { + return true; + } + } + return false; } /*! \internal - + 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. - + \see draw */ QRect QCPAbstractItem::clipRect() const { - if (mClipToAxisRect && mClipAxisRect) - return mClipAxisRect.data()->rect(); - else - return mParentPlot->viewport(); + if (mClipToAxisRect && mClipAxisRect) { + return mClipAxisRect.data()->rect(); + } else { + return mParentPlot->viewport(); + } } /*! \internal @@ -8513,49 +8507,50 @@ QRect QCPAbstractItem::clipRect() const before drawing item lines. This is the antialiasing state the painter passed to the \ref draw method is in by default. - + 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 */ void QCPAbstractItem::applyDefaultAntialiasingHint(QCPPainter *painter) const { - applyAntialiasingHint(painter, mAntialiased, QCP::aeItems); + 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(); + 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 @@ -8563,56 +8558,56 @@ double QCPAbstractItem::distSqrToLine(const QPointF &start, const QPointF &end, A convenience function which returns the selectTest value for a specified \a rect and a specified click position \a pos. \a filledRect defines whether a click inside the rect should also be considered a hit or whether only the rect border is sensitive to hits. - + This function may be used to help with the implementation of the \ref selectTest function for 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 */ double QCPAbstractItem::rectSelectTest(const QRectF &rect, const QPointF &pos, bool filledRect) const { - double result = -1; + double result = -1; - // distance to border: - QList lines; - lines << QLineF(rect.topLeft(), rect.topRight()) << QLineF(rect.bottomLeft(), rect.bottomRight()) - << QLineF(rect.topLeft(), rect.bottomLeft()) << QLineF(rect.topRight(), rect.bottomRight()); - double minDistSqr = std::numeric_limits::max(); - for (int i=0; i mParentPlot->selectionTolerance()*0.99) - { - if (rect.contains(pos)) - result = mParentPlot->selectionTolerance()*0.99; - } - return result; + // distance to border: + QList lines; + lines << QLineF(rect.topLeft(), rect.topRight()) << QLineF(rect.bottomLeft(), rect.bottomRight()) + << QLineF(rect.topLeft(), rect.bottomLeft()) << QLineF(rect.topRight(), rect.bottomRight()); + double minDistSqr = std::numeric_limits::max(); + for (int i = 0; i < lines.size(); ++i) { + double distSqr = distSqrToLine(lines.at(i).p1(), lines.at(i).p2(), pos); + if (distSqr < minDistSqr) { + minDistSqr = distSqr; + } + } + result = qSqrt(minDistSqr); + + // filled rect, allow click inside to count as hit: + if (filledRect && result > mParentPlot->selectionTolerance() * 0.99) { + if (rect.contains(pos)) { + result = mParentPlot->selectionTolerance() * 0.99; + } + } + return result; } /*! \internal Returns the pixel position of the anchor with Id \a anchorId. This function must be reimplemented in item subclasses if they want to provide anchors (QCPItemAnchor). - + For example, if the item has two anchors with id 0 and 1, this function takes one of these anchor ids and returns the respective pixel points of the specified anchor. - + \see createAnchor */ QPointF QCPAbstractItem::anchorPixelPoint(int anchorId) const { - qDebug() << Q_FUNC_INFO << "called on item which shouldn't have any anchors (this method not reimplemented). anchorId" << anchorId; - return QPointF(); + qDebug() << Q_FUNC_INFO << "called on item which shouldn't have any anchors (this method not reimplemented). anchorId" << anchorId; + return QPointF(); } /*! \internal @@ -8620,28 +8615,30 @@ QPointF QCPAbstractItem::anchorPixelPoint(int anchorId) const Creates a QCPItemPosition, registers it with this item and returns a pointer to it. The specified \a name must be a unique string that is usually identical to the variable name of the position member (This is needed to provide the name-based \ref position access to positions). - + Don't delete positions created by this function manually, as the item will take care of it. - + Use this function in the constructor (initialization list) of the specific item subclass to create each position member. Don't create QCPItemPositions with \b new yourself, because they won't be registered with the item properly. - + \see createAnchor */ QCPItemPosition *QCPAbstractItem::createPosition(const QString &name) { - if (hasAnchor(name)) - qDebug() << Q_FUNC_INFO << "anchor/position with name exists already:" << name; - QCPItemPosition *newPosition = new QCPItemPosition(mParentPlot, this, name); - mPositions.append(newPosition); - mAnchors.append(newPosition); // every position is also an anchor - newPosition->setAxes(mParentPlot->xAxis, mParentPlot->yAxis); - newPosition->setType(QCPItemPosition::ptPlotCoords); - if (mParentPlot->axisRect()) - newPosition->setAxisRect(mParentPlot->axisRect()); - newPosition->setCoords(0, 0); - return newPosition; + if (hasAnchor(name)) { + qDebug() << Q_FUNC_INFO << "anchor/position with name exists already:" << name; + } + QCPItemPosition *newPosition = new QCPItemPosition(mParentPlot, this, name); + mPositions.append(newPosition); + mAnchors.append(newPosition); // every position is also an anchor + newPosition->setAxes(mParentPlot->xAxis, mParentPlot->yAxis); + newPosition->setType(QCPItemPosition::ptPlotCoords); + if (mParentPlot->axisRect()) { + newPosition->setAxisRect(mParentPlot->axisRect()); + } + newPosition->setCoords(0, 0); + return newPosition; } /*! \internal @@ -8649,59 +8646,60 @@ QCPItemPosition *QCPAbstractItem::createPosition(const QString &name) Creates a QCPItemAnchor, registers it with this item and returns a pointer to it. The specified \a name must be a unique string that is usually identical to the variable name of the anchor member (This is needed to provide the name based \ref anchor access to anchors). - + The \a anchorId must be a number identifying the created anchor. It is recommended to create an enum (e.g. "AnchorIndex") for this on each item that uses anchors. This id is used by the anchor to identify itself when it calls QCPAbstractItem::anchorPixelPoint. That function then returns the correct pixel coordinates for the passed anchor id. - + Don't delete anchors created by this function manually, as the item will take care of it. - + Use this function in the constructor (initialization list) of the specific item subclass to create each anchor member. Don't create QCPItemAnchors with \b new yourself, because then they won't be registered with the item properly. - + \see createPosition */ QCPItemAnchor *QCPAbstractItem::createAnchor(const QString &name, int anchorId) { - if (hasAnchor(name)) - qDebug() << Q_FUNC_INFO << "anchor/position with name exists already:" << name; - QCPItemAnchor *newAnchor = new QCPItemAnchor(mParentPlot, this, name, anchorId); - mAnchors.append(newAnchor); - return newAnchor; + if (hasAnchor(name)) { + qDebug() << Q_FUNC_INFO << "anchor/position with name exists already:" << name; + } + QCPItemAnchor *newAnchor = new QCPItemAnchor(mParentPlot, this, name, anchorId); + mAnchors.append(newAnchor); + return newAnchor; } /* inherits documentation from base class */ void QCPAbstractItem::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) { - Q_UNUSED(event) - Q_UNUSED(details) - if (mSelectable) - { - bool selBefore = mSelected; - setSelected(additive ? !mSelected : true); - if (selectionStateChanged) - *selectionStateChanged = mSelected != selBefore; - } + Q_UNUSED(event) + Q_UNUSED(details) + if (mSelectable) { + bool selBefore = mSelected; + setSelected(additive ? !mSelected : true); + if (selectionStateChanged) { + *selectionStateChanged = mSelected != selBefore; + } + } } /* inherits documentation from base class */ void QCPAbstractItem::deselectEvent(bool *selectionStateChanged) { - if (mSelectable) - { - bool selBefore = mSelected; - setSelected(false); - if (selectionStateChanged) - *selectionStateChanged = mSelected != selBefore; - } + if (mSelectable) { + bool selBefore = mSelected; + setSelected(false); + if (selectionStateChanged) { + *selectionStateChanged = mSelected != selBefore; + } + } } /* inherits documentation from base class */ QCP::Interaction QCPAbstractItem::selectionCategory() const { - return QCP::iSelectItems; + return QCP::iSelectItems; } @@ -8714,10 +8712,10 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCustomPlot - + \brief The central class of the library. This is the QWidget which displays the plot and interacts with the user. - + For tutorials on how to use QCustomPlot, see the website\n http://www.qcustomplot.com/ */ @@ -8725,22 +8723,22 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const /* start of documentation of inline functions */ /*! \fn QRect QCustomPlot::viewport() const - + Returns the viewport rect of this QCustomPlot instance. The viewport is the area the plot is drawn in, all mechanisms, e.g. margin caluclation take the viewport to be the outer border of the plot. The viewport normally is the rect() of the QCustomPlot widget, i.e. a rect with top left (0, 0) and size of the QCustomPlot widget. - + Don't confuse the viewport with the axis rect (QCustomPlot::axisRect). An axis rect is typically an area enclosed by four axes, where the graphs/plottables are drawn in. The viewport is larger and contains also the axes themselves, their tick numbers, their labels, the plot title etc. - + Only when saving to a file (see \ref savePng, \ref savePdf etc.) the viewport is temporarily modified to allow saving plots with sizes independent of the current widget size. */ /*! \fn QCPLayoutGrid *QCustomPlot::plotLayout() const - + Returns the top level layout of this QCustomPlot instance. It is a \ref QCPLayoutGrid, initially containing just one cell with the main QCPAxisRect inside. */ @@ -8756,7 +8754,7 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const /*! \fn void QCustomPlot::mousePress(QMouseEvent *event) This signal is emitted when the QCustomPlot receives a mouse press event. - + It is emitted before QCustomPlot handles any other mechanism like range dragging. So a slot connected to this signal can still influence the behaviour e.g. with \ref QCPAxisRect::setRangeDrag or \ref QCPAxisRect::setRangeDragAxes. @@ -8765,11 +8763,11 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const /*! \fn void QCustomPlot::mouseMove(QMouseEvent *event) This signal is emitted when the QCustomPlot receives a mouse move event. - + It is emitted before QCustomPlot handles any other mechanism like range dragging. So a slot connected to this signal can still influence the behaviour e.g. with \ref QCPAxisRect::setRangeDrag or \ref QCPAxisRect::setRangeDragAxes. - + \warning It is discouraged to change the drag-axes with \ref QCPAxisRect::setRangeDragAxes here, because the dragging starting point was saved the moment the mouse was pressed. Thus it only has a meaning for the range drag axes that were set at that moment. If you want to change the drag @@ -8779,7 +8777,7 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const /*! \fn void QCustomPlot::mouseRelease(QMouseEvent *event) This signal is emitted when the QCustomPlot receives a mouse release event. - + It is emitted before QCustomPlot handles any other mechanisms like object selection. So a slot connected to this signal can still influence the behaviour e.g. with \ref setInteractions or \ref QCPAbstractPlottable::setSelectable. @@ -8788,150 +8786,150 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const /*! \fn void QCustomPlot::mouseWheel(QMouseEvent *event) This signal is emitted when the QCustomPlot receives a mouse wheel event. - + It is emitted before QCustomPlot handles any other mechanisms like range zooming. So a slot connected to this signal can still influence the behaviour e.g. with \ref QCPAxisRect::setRangeZoom, \ref QCPAxisRect::setRangeZoomAxes or \ref QCPAxisRect::setRangeZoomFactor. */ /*! \fn void QCustomPlot::plottableClick(QCPAbstractPlottable *plottable, QMouseEvent *event) - + This signal is emitted when a plottable is clicked. \a event is the mouse event that caused the click and \a plottable is the plottable that received the click. - + \see plottableDoubleClick */ /*! \fn void QCustomPlot::plottableDoubleClick(QCPAbstractPlottable *plottable, QMouseEvent *event) - + This signal is emitted when a plottable is double clicked. - + \a event is the mouse event that caused the click and \a plottable is the plottable that received the click. - + \see plottableClick */ /*! \fn void QCustomPlot::itemClick(QCPAbstractItem *item, QMouseEvent *event) - + This signal is emitted when an item is clicked. \a event is the mouse event that caused the click and \a item is the item that received the click. - + \see itemDoubleClick */ /*! \fn void QCustomPlot::itemDoubleClick(QCPAbstractItem *item, QMouseEvent *event) - + This signal is emitted when an item is double clicked. - + \a event is the mouse event that caused the click and \a item is the item that received the click. - + \see itemClick */ /*! \fn void QCustomPlot::axisClick(QCPAxis *axis, QCPAxis::SelectablePart part, QMouseEvent *event) - + This signal is emitted when an axis is clicked. - + \a event is the mouse event that caused the click, \a axis is the axis that received the click and \a part indicates the part of the axis that was clicked. - + \see axisDoubleClick */ /*! \fn void QCustomPlot::axisDoubleClick(QCPAxis *axis, QCPAxis::SelectablePart part, QMouseEvent *event) This signal is emitted when an axis is double clicked. - + \a event is the mouse event that caused the click, \a axis is the axis that received the click and \a part indicates the part of the axis that was clicked. - + \see axisClick */ /*! \fn void QCustomPlot::legendClick(QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event) This signal is emitted when a legend (item) is clicked. - + \a event is the mouse event that caused the click, \a legend is the legend that received the click and \a item is the legend item that received the click. If only the legend and no item is clicked, \a item is 0. This happens for a click inside the legend padding or the space between two items. - + \see legendDoubleClick */ /*! \fn void QCustomPlot::legendDoubleClick(QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event) This signal is emitted when a legend (item) is double clicked. - + \a event is the mouse event that caused the click, \a legend is the legend that received the click and \a item is the legend item that received the click. If only the legend and no item is clicked, \a item is 0. This happens for a click inside the legend padding or the space between two items. - + \see legendClick */ /*! \fn void QCustomPlot:: titleClick(QMouseEvent *event, QCPPlotTitle *title) This signal is emitted when a plot title is clicked. - + \a event is the mouse event that caused the click and \a title is the plot title that received the click. - + \see titleDoubleClick */ /*! \fn void QCustomPlot::titleDoubleClick(QMouseEvent *event, QCPPlotTitle *title) This signal is emitted when a plot title is double clicked. - + \a event is the mouse event that caused the click and \a title is the plot title that received the click. - + \see titleClick */ /*! \fn void QCustomPlot::selectionChangedByUser() - + This signal is emitted after the user has changed the selection in the QCustomPlot, e.g. by clicking. It is not emitted when the selection state of an object has changed programmatically by a direct call to setSelected() on an object or by calling \ref deselectAll. - + 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. - + See the documentation of \ref setInteractions for details about the selection mechanism. - + \see selectedPlottables, selectedGraphs, selectedItems, selectedAxes, selectedLegends */ /*! \fn void QCustomPlot::beforeReplot() - + This signal is emitted immediately before a replot takes place (caused by a call to the slot \ref replot). - + It is safe to mutually connect the replot slot with this signal on two QCustomPlots to make them replot synchronously, it won't cause an infinite recursion. - + \see replot, afterReplot */ /*! \fn void QCustomPlot::afterReplot() - + This signal is emitted immediately after a replot has taken place (caused by a call to the slot \ref replot). - + It is safe to mutually connect the replot slot with this signal on two QCustomPlots to make them replot synchronously, it won't cause an infinite recursion. - + \see replot, beforeReplot */ @@ -8941,7 +8939,7 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const /*! \var QCPAxis *QCustomPlot::xAxis A pointer to the primary x Axis (bottom) of the main axis rect of the plot. - + QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref yAxis2) and the \ref legend. They make it very easy working with plots that only have a single axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the @@ -8954,7 +8952,7 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const /*! \var QCPAxis *QCustomPlot::yAxis A pointer to the primary y Axis (left) of the main axis rect of the plot. - + QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref yAxis2) and the \ref legend. They make it very easy working with plots that only have a single axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the @@ -8969,7 +8967,7 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const A pointer to the secondary x Axis (top) of the main axis rect of the plot. Secondary axes are invisible by default. Use QCPAxis::setVisible to change this (or use \ref QCPAxisRect::setupFullAxesBox). - + QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref yAxis2) and the \ref legend. They make it very easy working with plots that only have a single axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the @@ -8984,7 +8982,7 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const A pointer to the secondary y Axis (right) of the main axis rect of the plot. Secondary axes are invisible by default. Use QCPAxis::setVisible to change this (or use \ref QCPAxisRect::setupFullAxesBox). - + QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref yAxis2) and the \ref legend. They make it very easy working with plots that only have a single axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the @@ -8998,7 +8996,7 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const A pointer to the default legend of the main axis rect. The legend is invisible by default. Use QCPLegend::setVisible to change this. - + QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref yAxis2) and the \ref legend. They make it very easy working with plots that only have a single axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the @@ -9015,205 +9013,210 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const Constructs a QCustomPlot and sets reasonable default values. */ QCustomPlot::QCustomPlot(QWidget *parent) : - QWidget(parent), - xAxis(0), - yAxis(0), - xAxis2(0), - yAxis2(0), - legend(0), - mPlotLayout(0), - mAutoAddPlottableToLegend(true), - mAntialiasedElements(QCP::aeNone), - mNotAntialiasedElements(QCP::aeNone), - mInteractions(0), - mSelectionTolerance(8), - mNoAntialiasingOnDrag(false), - mBackgroundBrush(Qt::white, Qt::SolidPattern), - mBackgroundScaled(true), - mBackgroundScaledMode(Qt::KeepAspectRatioByExpanding), - mCurrentLayer(0), - mPlottingHints(QCP::phCacheLabels|QCP::phForceRepaint), - mMultiSelectModifier(Qt::ControlModifier), - mPaintBuffer(size()), - mMouseEventElement(0), - mReplotting(false) + QWidget(parent), + xAxis(0), + yAxis(0), + xAxis2(0), + yAxis2(0), + legend(0), + mPlotLayout(0), + mAutoAddPlottableToLegend(true), + mAntialiasedElements(QCP::aeNone), + mNotAntialiasedElements(QCP::aeNone), + mInteractions(0), + mSelectionTolerance(8), + mNoAntialiasingOnDrag(false), + mBackgroundBrush(Qt::white, Qt::SolidPattern), + mBackgroundScaled(true), + mBackgroundScaledMode(Qt::KeepAspectRatioByExpanding), + mCurrentLayer(0), + mPlottingHints(QCP::phCacheLabels | QCP::phForceRepaint), + mMultiSelectModifier(Qt::ControlModifier), + mPaintBuffer(size()), + mMouseEventElement(0), + mReplotting(false) { - setAttribute(Qt::WA_NoMousePropagation); - setAttribute(Qt::WA_OpaquePaintEvent); - setMouseTracking(true); - QLocale currentLocale = locale(); - currentLocale.setNumberOptions(QLocale::OmitGroupSeparator); - setLocale(currentLocale); - - // 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"))); - updateLayerIndices(); - setCurrentLayer(QLatin1String("main")); - - // create initial layout, axis rect and legend: - mPlotLayout = new QCPLayoutGrid; - mPlotLayout->initializeParentPlot(this); - mPlotLayout->setParent(this); // important because if parent is QWidget, QCPLayout::sizeConstraintsChanged will call QWidget::updateGeometry - mPlotLayout->setLayer(QLatin1String("main")); - QCPAxisRect *defaultAxisRect = new QCPAxisRect(this, true); - mPlotLayout->addElement(0, 0, defaultAxisRect); - xAxis = defaultAxisRect->axis(QCPAxis::atBottom); - yAxis = defaultAxisRect->axis(QCPAxis::atLeft); - xAxis2 = defaultAxisRect->axis(QCPAxis::atTop); - yAxis2 = defaultAxisRect->axis(QCPAxis::atRight); - legend = new QCPLegend; - legend->setVisible(false); - defaultAxisRect->insetLayout()->addElement(legend, Qt::AlignRight|Qt::AlignTop); - defaultAxisRect->insetLayout()->setMargins(QMargins(12, 12, 12, 12)); - - defaultAxisRect->setLayer(QLatin1String("background")); - xAxis->setLayer(QLatin1String("axes")); - yAxis->setLayer(QLatin1String("axes")); - xAxis2->setLayer(QLatin1String("axes")); - yAxis2->setLayer(QLatin1String("axes")); - xAxis->grid()->setLayer(QLatin1String("grid")); - yAxis->grid()->setLayer(QLatin1String("grid")); - xAxis2->grid()->setLayer(QLatin1String("grid")); - yAxis2->grid()->setLayer(QLatin1String("grid")); - legend->setLayer(QLatin1String("legend")); - - setViewport(rect()); // needs to be called after mPlotLayout has been created - - replot(); + setAttribute(Qt::WA_NoMousePropagation); + setAttribute(Qt::WA_OpaquePaintEvent); + setMouseTracking(true); + QLocale currentLocale = locale(); + currentLocale.setNumberOptions(QLocale::OmitGroupSeparator); + setLocale(currentLocale); + + // 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"))); + updateLayerIndices(); + setCurrentLayer(QLatin1String("main")); + + // create initial layout, axis rect and legend: + mPlotLayout = new QCPLayoutGrid; + mPlotLayout->initializeParentPlot(this); + mPlotLayout->setParent(this); // important because if parent is QWidget, QCPLayout::sizeConstraintsChanged will call QWidget::updateGeometry + mPlotLayout->setLayer(QLatin1String("main")); + QCPAxisRect *defaultAxisRect = new QCPAxisRect(this, true); + mPlotLayout->addElement(0, 0, defaultAxisRect); + xAxis = defaultAxisRect->axis(QCPAxis::atBottom); + yAxis = defaultAxisRect->axis(QCPAxis::atLeft); + xAxis2 = defaultAxisRect->axis(QCPAxis::atTop); + yAxis2 = defaultAxisRect->axis(QCPAxis::atRight); + legend = new QCPLegend; + legend->setVisible(false); + defaultAxisRect->insetLayout()->addElement(legend, Qt::AlignRight | Qt::AlignTop); + defaultAxisRect->insetLayout()->setMargins(QMargins(12, 12, 12, 12)); + + defaultAxisRect->setLayer(QLatin1String("background")); + xAxis->setLayer(QLatin1String("axes")); + yAxis->setLayer(QLatin1String("axes")); + xAxis2->setLayer(QLatin1String("axes")); + yAxis2->setLayer(QLatin1String("axes")); + xAxis->grid()->setLayer(QLatin1String("grid")); + yAxis->grid()->setLayer(QLatin1String("grid")); + xAxis2->grid()->setLayer(QLatin1String("grid")); + yAxis2->grid()->setLayer(QLatin1String("grid")); + legend->setLayer(QLatin1String("legend")); + + setViewport(rect()); // needs to be called after mPlotLayout has been created + + replot(); } QCustomPlot::~QCustomPlot() { - clearPlottables(); - clearItems(); + clearPlottables(); + clearItems(); - if (mPlotLayout) - { - delete mPlotLayout; - mPlotLayout = 0; - } - - mCurrentLayer = 0; - qDeleteAll(mLayers); // don't use removeLayer, because it would prevent the last layer to be removed - mLayers.clear(); + if (mPlotLayout) { + delete mPlotLayout; + mPlotLayout = 0; + } + + mCurrentLayer = 0; + qDeleteAll(mLayers); // don't use removeLayer, because it would prevent the last layer to be removed + mLayers.clear(); } /*! Sets which elements are forcibly drawn antialiased as an \a or combination of QCP::AntialiasedElement. - + This overrides the antialiasing settings for whole element groups, normally controlled with the \a setAntialiasing function on the individual elements. If an element is neither specified in \ref setAntialiasedElements nor in \ref setNotAntialiasedElements, the antialiasing setting on each individual element instance is used. - + For example, if \a antialiasedElements contains \ref QCP::aePlottables, all plottables will be drawn antialiased, no matter what the specific QCPAbstractPlottable::setAntialiased value was set to. - + if an element in \a antialiasedElements is already set in \ref setNotAntialiasedElements, it is removed from there. - + \see setNotAntialiasedElements */ void QCustomPlot::setAntialiasedElements(const QCP::AntialiasedElements &antialiasedElements) { - mAntialiasedElements = antialiasedElements; - - // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously: - if ((mNotAntialiasedElements & mAntialiasedElements) != 0) - mNotAntialiasedElements |= ~mAntialiasedElements; + mAntialiasedElements = antialiasedElements; + + // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously: + if ((mNotAntialiasedElements & mAntialiasedElements) != 0) { + mNotAntialiasedElements |= ~mAntialiasedElements; + } } /*! Sets whether the specified \a antialiasedElement is forcibly drawn antialiased. - + See \ref setAntialiasedElements for details. - + \see setNotAntialiasedElement */ void QCustomPlot::setAntialiasedElement(QCP::AntialiasedElement antialiasedElement, bool enabled) { - if (!enabled && mAntialiasedElements.testFlag(antialiasedElement)) - mAntialiasedElements &= ~antialiasedElement; - else if (enabled && !mAntialiasedElements.testFlag(antialiasedElement)) - mAntialiasedElements |= antialiasedElement; - - // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously: - if ((mNotAntialiasedElements & mAntialiasedElements) != 0) - mNotAntialiasedElements |= ~mAntialiasedElements; + if (!enabled && mAntialiasedElements.testFlag(antialiasedElement)) { + mAntialiasedElements &= ~antialiasedElement; + } else if (enabled && !mAntialiasedElements.testFlag(antialiasedElement)) { + mAntialiasedElements |= antialiasedElement; + } + + // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously: + if ((mNotAntialiasedElements & mAntialiasedElements) != 0) { + mNotAntialiasedElements |= ~mAntialiasedElements; + } } /*! Sets which elements are forcibly drawn not antialiased as an \a or combination of QCP::AntialiasedElement. - + This overrides the antialiasing settings for whole element groups, normally controlled with the \a setAntialiasing function on the individual elements. If an element is neither specified in \ref setAntialiasedElements nor in \ref setNotAntialiasedElements, the antialiasing setting on each individual element instance is used. - + For example, if \a notAntialiasedElements contains \ref QCP::aePlottables, no plottables will be drawn antialiased, no matter what the specific QCPAbstractPlottable::setAntialiased value was set to. - + if an element in \a notAntialiasedElements is already set in \ref setAntialiasedElements, it is removed from there. - + \see setAntialiasedElements */ void QCustomPlot::setNotAntialiasedElements(const QCP::AntialiasedElements ¬AntialiasedElements) { - mNotAntialiasedElements = notAntialiasedElements; - - // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously: - if ((mNotAntialiasedElements & mAntialiasedElements) != 0) - mAntialiasedElements |= ~mNotAntialiasedElements; + mNotAntialiasedElements = notAntialiasedElements; + + // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously: + if ((mNotAntialiasedElements & mAntialiasedElements) != 0) { + mAntialiasedElements |= ~mNotAntialiasedElements; + } } /*! Sets whether the specified \a notAntialiasedElement is forcibly drawn not antialiased. - + See \ref setNotAntialiasedElements for details. - + \see setAntialiasedElement */ void QCustomPlot::setNotAntialiasedElement(QCP::AntialiasedElement notAntialiasedElement, bool enabled) { - if (!enabled && mNotAntialiasedElements.testFlag(notAntialiasedElement)) - mNotAntialiasedElements &= ~notAntialiasedElement; - else if (enabled && !mNotAntialiasedElements.testFlag(notAntialiasedElement)) - mNotAntialiasedElements |= notAntialiasedElement; - - // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously: - if ((mNotAntialiasedElements & mAntialiasedElements) != 0) - mAntialiasedElements |= ~mNotAntialiasedElements; + if (!enabled && mNotAntialiasedElements.testFlag(notAntialiasedElement)) { + mNotAntialiasedElements &= ~notAntialiasedElement; + } else if (enabled && !mNotAntialiasedElements.testFlag(notAntialiasedElement)) { + mNotAntialiasedElements |= notAntialiasedElement; + } + + // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously: + if ((mNotAntialiasedElements & mAntialiasedElements) != 0) { + mAntialiasedElements |= ~mNotAntialiasedElements; + } } /*! 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 */ void QCustomPlot::setAutoAddPlottableToLegend(bool on) { - mAutoAddPlottableToLegend = on; + mAutoAddPlottableToLegend = on; } /*! Sets the possible interactions of this QCustomPlot as an or-combination of \ref QCP::Interaction enums. There are the following types of interactions: - + Axis range manipulation is controlled via \ref QCP::iRangeDrag and \ref QCP::iRangeZoom. When the respective interaction is enabled, the user may drag axes ranges and zoom with the mouse wheel. For details how to control which axes the user may drag/zoom and in what orientations, see \ref 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 @@ -9222,78 +9225,79 @@ void QCustomPlot::setAutoAddPlottableToLegend(bool on) 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. - + 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 out whether a specific item is selected, call QCPAbstractItem::selected(). To retrieve a list of all currently selected items, call \ref selectedItems. - + Axis selection is controlled with \ref QCP::iSelectAxes. If \ref QCP::iSelectAxes is set, the user may select parts of the axes by clicking on them. What parts exactly (e.g. Axis base line, tick labels, axis label) are selectable can be controlled via \ref QCPAxis::setSelectableParts for each axis. To retrieve a list of all axes that currently contain selected parts, call \ref selectedAxes. Which parts of an axis are selected, can be retrieved with QCPAxis::selectedParts(). - + Legend selection is controlled with \ref QCP::iSelectLegend. If this is set, the user may select the legend itself or individual items by clicking on them. What parts exactly are selectable can be controlled via \ref QCPLegend::setSelectableParts. To find out whether the legend or any of its child items are selected, check the value of QCPLegend::selectedParts. To 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 user may select those objects by clicking on them. To find out which are currently selected, you need to check their selected state explicitly. - + If the selection state has changed by user interaction, the \ref selectionChangedByUser signal is emitted. Each selectable object additionally emits an individual selectionChanged signal whenever their selection state has changed, i.e. not only by user interaction. - + To allow multiple objects to be selected by holding the selection modifier (\ref setMultiSelectModifier), set the flag \ref QCP::iMultiSelect. - + \note In addition to the selection mechanism presented here, QCustomPlot always emits corresponding signals, when an object is clicked or double clicked. see \ref plottableClick and \ref plottableDoubleClick for example. - + \see setInteraction, setSelectionTolerance */ void QCustomPlot::setInteractions(const QCP::Interactions &interactions) { - mInteractions = interactions; + mInteractions = interactions; } /*! Sets the single \a interaction of this QCustomPlot to \a enabled. - + For details about the interaction system, see \ref setInteractions. - + \see setInteractions */ void QCustomPlot::setInteraction(const QCP::Interaction &interaction, bool enabled) { - if (!enabled && mInteractions.testFlag(interaction)) - mInteractions &= ~interaction; - else if (enabled && !mInteractions.testFlag(interaction)) - mInteractions |= interaction; + if (!enabled && mInteractions.testFlag(interaction)) { + mInteractions &= ~interaction; + } else if (enabled && !mInteractions.testFlag(interaction)) { + mInteractions |= interaction; + } } /*! Sets the tolerance that is used to decide whether a click selects an object (e.g. a plottable) or not. - + If the user clicks in the vicinity of the line of e.g. a QCPGraph, it's only regarded as a potential selection when the minimum distance between the click position and the graph line is smaller than \a pixels. Objects that are defined by an area (e.g. QCPBars) only react to clicks directly inside the area and ignore this selection tolerance. In other words, it only has meaning for parts of objects that are too thin to exactly hit with a click and thus need such a tolerance. - + \see setInteractions, QCPLayerable::selectTest */ void QCustomPlot::setSelectionTolerance(int pixels) { - mSelectionTolerance = pixels; + mSelectionTolerance = pixels; } /*! @@ -9302,68 +9306,71 @@ void QCustomPlot::setSelectionTolerance(int pixels) performance during dragging. Thus it creates a more responsive user experience. As soon as the user stops dragging, the last replot is done with normal antialiasing, to restore high image quality. - + \see setAntialiasedElements, setNotAntialiasedElements */ void QCustomPlot::setNoAntialiasingOnDrag(bool enabled) { - mNoAntialiasingOnDrag = enabled; + mNoAntialiasingOnDrag = enabled; } /*! Sets the plotting hints for this QCustomPlot instance as an \a or combination of QCP::PlottingHint. - + \see setPlottingHint */ void QCustomPlot::setPlottingHints(const QCP::PlottingHints &hints) { - mPlottingHints = hints; + mPlottingHints = hints; } /*! Sets the specified plotting \a hint to \a enabled. - + \see setPlottingHints */ void QCustomPlot::setPlottingHint(QCP::PlottingHint hint, bool enabled) { - QCP::PlottingHints newHints = mPlottingHints; - if (!enabled) - newHints &= ~hint; - else - newHints |= hint; - - if (newHints != mPlottingHints) - setPlottingHints(newHints); + QCP::PlottingHints newHints = mPlottingHints; + if (!enabled) { + newHints &= ~hint; + } else { + newHints |= hint; + } + + if (newHints != mPlottingHints) { + setPlottingHints(newHints); + } } /*! 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. - + By default the multi-select-modifier is set to Qt::ControlModifier. - + \see setInteractions */ void QCustomPlot::setMultiSelectModifier(Qt::KeyboardModifier modifier) { - mMultiSelectModifier = modifier; + mMultiSelectModifier = 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. - + This function is used to allow arbitrary size exports with \ref toPixmap, \ref savePng, \ref savePdf, etc. by temporarily changing the viewport size. */ void QCustomPlot::setViewport(const QRect &rect) { - mViewport = rect; - if (mPlotLayout) - mPlotLayout->setOuterRect(mViewport); + mViewport = rect; + if (mPlotLayout) { + mPlotLayout->setOuterRect(mViewport); + } } /*! @@ -9374,7 +9381,7 @@ void QCustomPlot::setViewport(const QRect &rect) enabled with \ref setBackgroundScaled and the scaling mode (whether and how the aspect ratio is preserved) can be set with \ref setBackgroundScaledMode. To set all these options in one call, consider using the overloaded version of this function. - + If a background brush was set with \ref setBackground(const QBrush &brush), the viewport will first be filled with that brush, before drawing the background pixmap. This can be useful for background pixmaps with translucent areas. @@ -9383,8 +9390,8 @@ void QCustomPlot::setViewport(const QRect &rect) */ void QCustomPlot::setBackground(const QPixmap &pm) { - mBackgroundPixmap = pm; - mScaledBackgroundPixmap = QPixmap(); + mBackgroundPixmap = pm; + mScaledBackgroundPixmap = QPixmap(); } /*! @@ -9394,7 +9401,7 @@ void QCustomPlot::setBackground(const QPixmap &pm) was set with \ref setBackground(const QPixmap &pm), this brush will be used to fill the viewport before the background pixmap is drawn. This can be useful for background pixmaps with translucent areas. - + Set \a brush to Qt::NoBrush or Qt::Transparent to leave background transparent. This can be useful for exporting to image formats which support transparency, e.g. \ref savePng. @@ -9402,11 +9409,11 @@ void QCustomPlot::setBackground(const QPixmap &pm) */ void QCustomPlot::setBackground(const QBrush &brush) { - mBackgroundBrush = brush; + mBackgroundBrush = brush; } /*! \overload - + Allows setting the background pixmap of the viewport, whether it shall be scaled and how it shall be scaled in one call. @@ -9414,515 +9421,506 @@ void QCustomPlot::setBackground(const QBrush &brush) */ void QCustomPlot::setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode) { - mBackgroundPixmap = pm; - mScaledBackgroundPixmap = QPixmap(); - mBackgroundScaled = scaled; - mBackgroundScaledMode = mode; + mBackgroundPixmap = pm; + mScaledBackgroundPixmap = QPixmap(); + mBackgroundScaled = scaled; + mBackgroundScaledMode = mode; } /*! Sets whether the viewport background pixmap shall be scaled to fit the viewport. If \a scaled is set to true, control whether and how the aspect ratio of the original pixmap is preserved with \ref setBackgroundScaledMode. - + Note that the scaled version of the original pixmap is buffered, so there is no performance penalty on replots. (Except when the viewport dimensions are changed continuously.) - + \see setBackground, setBackgroundScaledMode */ void QCustomPlot::setBackgroundScaled(bool scaled) { - mBackgroundScaled = scaled; + mBackgroundScaled = scaled; } /*! If scaling of the viewport background pixmap is enabled (\ref setBackgroundScaled), use this function to define whether and how the aspect ratio of the original pixmap is preserved. - + \see setBackground, setBackgroundScaled */ void QCustomPlot::setBackgroundScaledMode(Qt::AspectRatioMode mode) { - mBackgroundScaledMode = mode; + mBackgroundScaledMode = mode; } /*! Returns the plottable with \a index. If the index is invalid, returns 0. - + There is an overloaded version of this function with no parameter which returns the last added plottable, see QCustomPlot::plottable() - + \see plottableCount, addPlottable */ QCPAbstractPlottable *QCustomPlot::plottable(int index) { - if (index >= 0 && index < mPlottables.size()) - { - return mPlottables.at(index); - } else - { - qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; - return 0; - } + if (index >= 0 && index < mPlottables.size()) { + return mPlottables.at(index); + } else { + qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; + return 0; + } } /*! \overload - + Returns the last plottable that was added with \ref addPlottable. If there are no plottables in the plot, returns 0. - + \see plottableCount, addPlottable */ QCPAbstractPlottable *QCustomPlot::plottable() { - if (!mPlottables.isEmpty()) - { - return mPlottables.last(); - } else - return 0; + if (!mPlottables.isEmpty()) { + return mPlottables.last(); + } else { + return 0; + } } /*! 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; + 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). - + Returns true on success. - + \see addPlottable, clearPlottables */ bool QCustomPlot::removePlottable(QCPAbstractPlottable *plottable) { - if (!mPlottables.contains(plottable)) - { - qDebug() << Q_FUNC_INFO << "plottable not in list:" << reinterpret_cast(plottable); - return false; - } - - // remove plottable from legend: - plottable->removeFromLegend(); - // special handling for QCPGraphs to maintain the simple graph interface: - if (QCPGraph *graph = qobject_cast(plottable)) - mGraphs.removeOne(graph); - // remove plottable: - delete plottable; - mPlottables.removeOne(plottable); - return true; + if (!mPlottables.contains(plottable)) { + qDebug() << Q_FUNC_INFO << "plottable not in list:" << reinterpret_cast(plottable); + return false; + } + + // remove plottable from legend: + plottable->removeFromLegend(); + // special handling for QCPGraphs to maintain the simple graph interface: + if (QCPGraph *graph = qobject_cast(plottable)) { + mGraphs.removeOne(graph); + } + // remove plottable: + delete plottable; + mPlottables.removeOne(plottable); + return true; } /*! \overload - + Removes the plottable by its \a index. */ bool QCustomPlot::removePlottable(int index) { - if (index >= 0 && index < mPlottables.size()) - return removePlottable(mPlottables[index]); - else - { - qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; - return false; - } + if (index >= 0 && index < mPlottables.size()) { + return removePlottable(mPlottables[index]); + } else { + qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; + return false; + } } /*! Removes all plottables from the plot (and the QCustomPlot::legend, if necessary). - + Returns the number of plottables removed. - + \see removePlottable */ int QCustomPlot::clearPlottables() { - int c = mPlottables.size(); - for (int i=c-1; i >= 0; --i) - removePlottable(mPlottables[i]); - return c; + int c = mPlottables.size(); + for (int i = c - 1; i >= 0; --i) { + removePlottable(mPlottables[i]); + } + return c; } /*! Returns the number of currently existing plottables in the plot - + \see plottable, addPlottable */ int QCustomPlot::plottableCount() const { - return mPlottables.size(); + return mPlottables.size(); } /*! Returns a list of the selected plottables. If no plottables are currently selected, the list is empty. - + There is a convenience function if you're only interested in selected graphs, see \ref selectedGraphs. - + \see setInteractions, QCPAbstractPlottable::setSelectable, QCPAbstractPlottable::setSelected */ -QList QCustomPlot::selectedPlottables() const +QList QCustomPlot::selectedPlottables() const { - QList result; - foreach (QCPAbstractPlottable *plottable, mPlottables) - { - if (plottable->selected()) - result.append(plottable); - } - return result; + QList result; + foreach (QCPAbstractPlottable *plottable, mPlottables) { + if (plottable->selected()) { + result.append(plottable); + } + } + return result; } /*! Returns the plottable at the pixel position \a pos. Plottables that only consist of single lines (like graphs) have a tolerance band around them, see \ref setSelectionTolerance. If multiple plottables come into consideration, the one closest to \a pos is returned. - + If \a onlySelectable is true, only plottables that are selectable (QCPAbstractPlottable::setSelectable) are considered. - + If there is no plottable at \a pos, the return value is 0. - + \see itemAt, layoutElementAt */ QCPAbstractPlottable *QCustomPlot::plottableAt(const QPointF &pos, bool onlySelectable) const { - QCPAbstractPlottable *resultPlottable = 0; - double resultDistance = mSelectionTolerance; // only regard clicks with distances smaller than mSelectionTolerance as selections, so initialize with that value - - foreach (QCPAbstractPlottable *plottable, mPlottables) - { - if (onlySelectable && !plottable->selectable()) // we could have also passed onlySelectable to the selectTest function, but checking here is faster, because we have access to QCPabstractPlottable::selectable - continue; - if ((plottable->keyAxis()->axisRect()->rect() & plottable->valueAxis()->axisRect()->rect()).contains(pos.toPoint())) // only consider clicks inside the rect that is spanned by the plottable's key/value axes - { - double currentDistance = plottable->selectTest(pos, false); - if (currentDistance >= 0 && currentDistance < resultDistance) - { - resultPlottable = plottable; - resultDistance = currentDistance; - } + QCPAbstractPlottable *resultPlottable = 0; + double resultDistance = mSelectionTolerance; // only regard clicks with distances smaller than mSelectionTolerance as selections, so initialize with that value + + foreach (QCPAbstractPlottable *plottable, mPlottables) { + if (onlySelectable && !plottable->selectable()) { // we could have also passed onlySelectable to the selectTest function, but checking here is faster, because we have access to QCPabstractPlottable::selectable + continue; + } + if ((plottable->keyAxis()->axisRect()->rect() & plottable->valueAxis()->axisRect()->rect()).contains(pos.toPoint())) { // only consider clicks inside the rect that is spanned by the plottable's key/value axes + double currentDistance = plottable->selectTest(pos, false); + if (currentDistance >= 0 && currentDistance < resultDistance) { + resultPlottable = plottable; + resultDistance = currentDistance; + } + } } - } - - return resultPlottable; + + return resultPlottable; } /*! Returns whether this QCustomPlot instance contains the \a plottable. - + \see addPlottable */ bool QCustomPlot::hasPlottable(QCPAbstractPlottable *plottable) const { - return mPlottables.contains(plottable); + return mPlottables.contains(plottable); } /*! Returns the graph with \a index. If the index is invalid, returns 0. - + There is an overloaded version of this function with no parameter which returns the last created graph, see QCustomPlot::graph() - + \see graphCount, addGraph */ QCPGraph *QCustomPlot::graph(int index) const { - if (index >= 0 && index < mGraphs.size()) - { - return mGraphs.at(index); - } else - { - qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; - return 0; - } + if (index >= 0 && index < mGraphs.size()) { + return mGraphs.at(index); + } else { + qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; + return 0; + } } /*! \overload - + Returns the last graph, that was created with \ref addGraph. If there are no graphs in the plot, returns 0. - + \see graphCount, addGraph */ QCPGraph *QCustomPlot::graph() const { - if (!mGraphs.isEmpty()) - { - return mGraphs.last(); - } else - return 0; + if (!mGraphs.isEmpty()) { + return mGraphs.last(); + } else { + return 0; + } } /*! Creates a new graph inside the plot. If \a keyAxis and \a valueAxis are left unspecified (0), the bottom (xAxis) is used as key and the left (yAxis) is used as value axis. If specified, \a keyAxis and \a valueAxis must reside in this QCustomPlot. - + \a keyAxis will be used as key axis (typically "x") and \a valueAxis as value axis (typically "y") for the graph. - + Returns a pointer to the newly created graph, or 0 if adding the graph failed. - + \see graph, graphCount, removeGraph, clearGraphs */ QCPGraph *QCustomPlot::addGraph(QCPAxis *keyAxis, QCPAxis *valueAxis) { - if (!keyAxis) keyAxis = xAxis; - if (!valueAxis) valueAxis = yAxis; - if (!keyAxis || !valueAxis) - { - qDebug() << Q_FUNC_INFO << "can't use default QCustomPlot xAxis or yAxis, because at least one is invalid (has been deleted)"; - return 0; - } - if (keyAxis->parentPlot() != this || valueAxis->parentPlot() != this) - { - qDebug() << Q_FUNC_INFO << "passed keyAxis or valueAxis doesn't have this QCustomPlot as parent"; - return 0; - } - - QCPGraph *newGraph = new QCPGraph(keyAxis, valueAxis); - if (addPlottable(newGraph)) - { - newGraph->setName(QLatin1String("Graph ")+QString::number(mGraphs.size())); - return newGraph; - } else - { - delete newGraph; - return 0; - } + if (!keyAxis) { + keyAxis = xAxis; + } + if (!valueAxis) { + valueAxis = yAxis; + } + if (!keyAxis || !valueAxis) { + qDebug() << Q_FUNC_INFO << "can't use default QCustomPlot xAxis or yAxis, because at least one is invalid (has been deleted)"; + return 0; + } + if (keyAxis->parentPlot() != this || valueAxis->parentPlot() != this) { + qDebug() << Q_FUNC_INFO << "passed keyAxis or valueAxis doesn't have this QCustomPlot as parent"; + return 0; + } + + QCPGraph *newGraph = new QCPGraph(keyAxis, valueAxis); + if (addPlottable(newGraph)) { + newGraph->setName(QLatin1String("Graph ") + QString::number(mGraphs.size())); + return newGraph; + } else { + delete newGraph; + return 0; + } } /*! 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). - + Returns true on success. - + \see clearGraphs */ bool QCustomPlot::removeGraph(QCPGraph *graph) { - return removePlottable(graph); + return removePlottable(graph); } /*! \overload - + Removes the graph by its \a index. */ bool QCustomPlot::removeGraph(int index) { - if (index >= 0 && index < mGraphs.size()) - return removeGraph(mGraphs[index]); - else - return false; + if (index >= 0 && index < mGraphs.size()) { + return removeGraph(mGraphs[index]); + } else { + return false; + } } /*! Removes all graphs from the plot (and the QCustomPlot::legend, if necessary). Returns the number of graphs removed. - + \see removeGraph */ int QCustomPlot::clearGraphs() { - int c = mGraphs.size(); - for (int i=c-1; i >= 0; --i) - removeGraph(mGraphs[i]); - return c; + int c = mGraphs.size(); + for (int i = c - 1; i >= 0; --i) { + removeGraph(mGraphs[i]); + } + return c; } /*! Returns the number of currently existing graphs in the plot - + \see graph, addGraph */ int QCustomPlot::graphCount() const { - return mGraphs.size(); + return mGraphs.size(); } /*! Returns a list of the selected graphs. If no graphs are currently selected, the list is empty. - + 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 */ -QList QCustomPlot::selectedGraphs() const +QList QCustomPlot::selectedGraphs() const { - QList result; - foreach (QCPGraph *graph, mGraphs) - { - if (graph->selected()) - result.append(graph); - } - return result; + QList result; + foreach (QCPGraph *graph, mGraphs) { + if (graph->selected()) { + result.append(graph); + } + } + return result; } /*! Returns the item with \a index. If the index is invalid, returns 0. - + There is an overloaded version of this function with no parameter which returns the last added item, see QCustomPlot::item() - + \see itemCount, addItem */ QCPAbstractItem *QCustomPlot::item(int index) const { - if (index >= 0 && index < mItems.size()) - { - return mItems.at(index); - } else - { - qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; - return 0; - } + if (index >= 0 && index < mItems.size()) { + return mItems.at(index); + } else { + qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; + return 0; + } } /*! \overload - + Returns the last item, that was added with \ref addItem. If there are no items in the plot, returns 0. - + \see itemCount, addItem */ QCPAbstractItem *QCustomPlot::item() const { - if (!mItems.isEmpty()) - { - return mItems.last(); - } else - return 0; + if (!mItems.isEmpty()) { + return mItems.last(); + } else { + return 0; + } } /*! 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; - } + 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. - + Returns true on success. - + \see addItem, clearItems */ bool QCustomPlot::removeItem(QCPAbstractItem *item) { - if (mItems.contains(item)) - { - delete item; - mItems.removeOne(item); - return true; - } else - { - qDebug() << Q_FUNC_INFO << "item not in list:" << reinterpret_cast(item); - return false; - } + if (mItems.contains(item)) { + delete item; + mItems.removeOne(item); + return true; + } else { + qDebug() << Q_FUNC_INFO << "item not in list:" << reinterpret_cast(item); + return false; + } } /*! \overload - + Removes the item by its \a index. */ bool QCustomPlot::removeItem(int index) { - if (index >= 0 && index < mItems.size()) - return removeItem(mItems[index]); - else - { - qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; - return false; - } + if (index >= 0 && index < mItems.size()) { + return removeItem(mItems[index]); + } else { + qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; + return false; + } } /*! Removes all items from the plot. - + Returns the number of items removed. - + \see removeItem */ int QCustomPlot::clearItems() { - int c = mItems.size(); - for (int i=c-1; i >= 0; --i) - removeItem(mItems[i]); - return c; + int c = mItems.size(); + for (int i = c - 1; i >= 0; --i) { + removeItem(mItems[i]); + } + return c; } /*! Returns the number of currently existing items in the plot - + \see item, addItem */ int QCustomPlot::itemCount() const { - return mItems.size(); + return mItems.size(); } /*! Returns a list of the selected items. If no items are currently selected, the list is empty. - + \see setInteractions, QCPAbstractItem::setSelectable, QCPAbstractItem::setSelected */ -QList QCustomPlot::selectedItems() const +QList QCustomPlot::selectedItems() const { - QList result; - foreach (QCPAbstractItem *item, mItems) - { - if (item->selected()) - result.append(item); - } - return result; + QList result; + foreach (QCPAbstractItem *item, mItems) { + if (item->selected()) { + result.append(item); + } + } + return result; } /*! @@ -9930,81 +9928,77 @@ QList QCustomPlot::selectedItems() const QCPItemLine or \ref QCPItemCurve) have a tolerance band around them, see \ref setSelectionTolerance. If multiple items come into consideration, the one closest to \a pos is returned. - + If \a onlySelectable is true, only items that are selectable (QCPAbstractItem::setSelectable) are considered. - + If there is no item at \a pos, the return value is 0. - + \see plottableAt, layoutElementAt */ QCPAbstractItem *QCustomPlot::itemAt(const QPointF &pos, bool onlySelectable) const { - QCPAbstractItem *resultItem = 0; - double resultDistance = mSelectionTolerance; // only regard clicks with distances smaller than mSelectionTolerance as selections, so initialize with that value - - foreach (QCPAbstractItem *item, mItems) - { - if (onlySelectable && !item->selectable()) // we could have also passed onlySelectable to the selectTest function, but checking here is faster, because we have access to QCPAbstractItem::selectable - continue; - if (!item->clipToAxisRect() || item->clipRect().contains(pos.toPoint())) // only consider clicks inside axis cliprect of the item if actually clipped to it - { - double currentDistance = item->selectTest(pos, false); - if (currentDistance >= 0 && currentDistance < resultDistance) - { - resultItem = item; - resultDistance = currentDistance; - } + QCPAbstractItem *resultItem = 0; + double resultDistance = mSelectionTolerance; // only regard clicks with distances smaller than mSelectionTolerance as selections, so initialize with that value + + foreach (QCPAbstractItem *item, mItems) { + if (onlySelectable && !item->selectable()) { // we could have also passed onlySelectable to the selectTest function, but checking here is faster, because we have access to QCPAbstractItem::selectable + continue; + } + if (!item->clipToAxisRect() || item->clipRect().contains(pos.toPoint())) { // only consider clicks inside axis cliprect of the item if actually clipped to it + double currentDistance = item->selectTest(pos, false); + if (currentDistance >= 0 && currentDistance < resultDistance) { + resultItem = item; + resultDistance = currentDistance; + } + } } - } - - return resultItem; + + return resultItem; } /*! Returns whether this QCustomPlot contains the \a item. - + \see addItem */ bool QCustomPlot::hasItem(QCPAbstractItem *item) const { - return mItems.contains(item); + return mItems.contains(item); } /*! Returns the layer with the specified \a name. If there is no layer with the specified name, 0 is returned. - + Layer names are case-sensitive. - + \see addLayer, moveLayer, removeLayer */ QCPLayer *QCustomPlot::layer(const QString &name) const { - foreach (QCPLayer *layer, mLayers) - { - if (layer->name() == name) - return layer; - } - return 0; + foreach (QCPLayer *layer, mLayers) { + if (layer->name() == name) { + return layer; + } + } + return 0; } /*! \overload - + Returns the layer by \a index. If the index is invalid, 0 is returned. - + \see addLayer, moveLayer, removeLayer */ QCPLayer *QCustomPlot::layer(int index) const { - if (index >= 0 && index < mLayers.size()) - { - return mLayers.at(index); - } else - { - qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; - return 0; - } + if (index >= 0 && index < mLayers.size()) { + return mLayers.at(index); + } else { + qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; + return 0; + } } /*! @@ -10012,352 +10006,339 @@ QCPLayer *QCustomPlot::layer(int index) const */ QCPLayer *QCustomPlot::currentLayer() const { - return mCurrentLayer; + return mCurrentLayer; } /*! Sets the layer with the specified \a name to be the current layer. All layerables (\ref QCPLayerable), e.g. plottables and items, are created on the current layer. - + Returns true on success, i.e. if there is a layer with the specified \a name in the QCustomPlot. - + Layer names are case-sensitive. - + \see addLayer, moveLayer, removeLayer, QCPLayerable::setLayer */ bool QCustomPlot::setCurrentLayer(const QString &name) { - if (QCPLayer *newCurrentLayer = layer(name)) - { - return setCurrentLayer(newCurrentLayer); - } else - { - qDebug() << Q_FUNC_INFO << "layer with name doesn't exist:" << name; - return false; - } + if (QCPLayer *newCurrentLayer = layer(name)) { + return setCurrentLayer(newCurrentLayer); + } else { + qDebug() << Q_FUNC_INFO << "layer with name doesn't exist:" << name; + return false; + } } /*! \overload - + Sets the provided \a layer to be the current layer. - + Returns true on success, i.e. when \a layer is a valid layer in the QCustomPlot. - + \see addLayer, moveLayer, removeLayer */ bool QCustomPlot::setCurrentLayer(QCPLayer *layer) { - if (!mLayers.contains(layer)) - { - qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast(layer); - return false; - } - - mCurrentLayer = layer; - return true; + if (!mLayers.contains(layer)) { + qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast(layer); + return false; + } + + mCurrentLayer = layer; + return true; } /*! Returns the number of currently existing layers in the plot - + \see layer, addLayer */ int QCustomPlot::layerCount() const { - return mLayers.size(); + return mLayers.size(); } /*! Adds a new layer to this QCustomPlot instance. The new layer will have the name \a name, which must be unique. Depending on \a insertMode, it is positioned either below or above \a otherLayer. - + Returns true on success, i.e. if there is no other layer named \a name and \a otherLayer is a valid layer inside this QCustomPlot. - + If \a otherLayer is 0, the highest layer in the QCustomPlot will be used. - + For an explanation of what layers are in QCustomPlot, see the documentation of \ref QCPLayer. - + \see layer, moveLayer, removeLayer */ bool QCustomPlot::addLayer(const QString &name, QCPLayer *otherLayer, QCustomPlot::LayerInsertMode insertMode) { - if (!otherLayer) - otherLayer = mLayers.last(); - if (!mLayers.contains(otherLayer)) - { - qDebug() << Q_FUNC_INFO << "otherLayer not a layer of this QCustomPlot:" << reinterpret_cast(otherLayer); - return false; - } - if (layer(name)) - { - qDebug() << Q_FUNC_INFO << "A layer exists already with the name" << name; - return false; - } - - QCPLayer *newLayer = new QCPLayer(this, name); - mLayers.insert(otherLayer->index() + (insertMode==limAbove ? 1:0), newLayer); - updateLayerIndices(); - return true; + if (!otherLayer) { + otherLayer = mLayers.last(); + } + if (!mLayers.contains(otherLayer)) { + qDebug() << Q_FUNC_INFO << "otherLayer not a layer of this QCustomPlot:" << reinterpret_cast(otherLayer); + return false; + } + if (layer(name)) { + qDebug() << Q_FUNC_INFO << "A layer exists already with the name" << name; + return false; + } + + QCPLayer *newLayer = new QCPLayer(this, name); + mLayers.insert(otherLayer->index() + (insertMode == limAbove ? 1 : 0), newLayer); + updateLayerIndices(); + return true; } /*! Removes the specified \a layer and returns true on success. - + All layerables (e.g. plottables and items) on the removed layer will be moved to the layer below \a layer. If \a layer is the bottom layer, the layerables are moved to the layer above. In both cases, the total rendering order of all layerables in the QCustomPlot is preserved. - + If \a layer is the current layer (\ref setCurrentLayer), the layer below (or above, if bottom layer) becomes the new current layer. - + It is not possible to remove the last layer of the plot. - + \see layer, addLayer, moveLayer */ bool QCustomPlot::removeLayer(QCPLayer *layer) { - if (!mLayers.contains(layer)) - { - qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast(layer); - return false; - } - if (mLayers.size() < 2) - { - qDebug() << Q_FUNC_INFO << "can't remove last layer"; - return false; - } - - // append all children of this layer to layer below (if this is lowest layer, prepend to layer above) - int removedIndex = layer->index(); - bool isFirstLayer = removedIndex==0; - QCPLayer *targetLayer = isFirstLayer ? mLayers.at(removedIndex+1) : mLayers.at(removedIndex-1); - QList children = layer->children(); - if (isFirstLayer) // prepend in reverse order (so order relative to each other stays the same) - { - for (int i=children.size()-1; i>=0; --i) - children.at(i)->moveToLayer(targetLayer, true); - } else // append normally - { - for (int i=0; imoveToLayer(targetLayer, false); - } - // if removed layer is current layer, change current layer to layer below/above: - if (layer == mCurrentLayer) - setCurrentLayer(targetLayer); - // remove layer: - delete layer; - mLayers.removeOne(layer); - updateLayerIndices(); - return true; + if (!mLayers.contains(layer)) { + qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast(layer); + return false; + } + if (mLayers.size() < 2) { + qDebug() << Q_FUNC_INFO << "can't remove last layer"; + return false; + } + + // append all children of this layer to layer below (if this is lowest layer, prepend to layer above) + int removedIndex = layer->index(); + bool isFirstLayer = removedIndex == 0; + QCPLayer *targetLayer = isFirstLayer ? mLayers.at(removedIndex + 1) : mLayers.at(removedIndex - 1); + QList children = layer->children(); + if (isFirstLayer) { // prepend in reverse order (so order relative to each other stays the same) + for (int i = children.size() - 1; i >= 0; --i) { + children.at(i)->moveToLayer(targetLayer, true); + } + } else { // append normally + for (int i = 0; i < children.size(); ++i) { + children.at(i)->moveToLayer(targetLayer, false); + } + } + // if removed layer is current layer, change current layer to layer below/above: + if (layer == mCurrentLayer) { + setCurrentLayer(targetLayer); + } + // remove layer: + delete layer; + mLayers.removeOne(layer); + updateLayerIndices(); + return true; } /*! Moves the specified \a layer either above or below \a otherLayer. Whether it's placed above or below is controlled with \a insertMode. - + Returns true on success, i.e. when both \a layer and \a otherLayer are valid layers in the QCustomPlot. - + \see layer, addLayer, moveLayer */ bool QCustomPlot::moveLayer(QCPLayer *layer, QCPLayer *otherLayer, QCustomPlot::LayerInsertMode insertMode) { - if (!mLayers.contains(layer)) - { - qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast(layer); - return false; - } - if (!mLayers.contains(otherLayer)) - { - qDebug() << Q_FUNC_INFO << "otherLayer not a layer of this QCustomPlot:" << reinterpret_cast(otherLayer); - return false; - } - - 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)); - - updateLayerIndices(); - return true; + if (!mLayers.contains(layer)) { + qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast(layer); + return false; + } + if (!mLayers.contains(otherLayer)) { + qDebug() << Q_FUNC_INFO << "otherLayer not a layer of this QCustomPlot:" << reinterpret_cast(otherLayer); + return false; + } + + 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)); + } + + updateLayerIndices(); + return true; } /*! Returns the number of axis rects in the plot. - + All axis rects can be accessed via QCustomPlot::axisRect(). - + Initially, only one axis rect exists in the plot. - + \see axisRect, axisRects */ int QCustomPlot::axisRectCount() const { - return axisRects().size(); + return axisRects().size(); } /*! Returns the axis rect with \a index. - + Initially, only one axis rect (with index 0) exists in the plot. If multiple axis rects were added, all of them may be accessed with this function in a linear fashion (even when they are nested in a layout hierarchy or inside other axis rects via QCPAxisRect::insetLayout). - + \see axisRectCount, axisRects */ QCPAxisRect *QCustomPlot::axisRect(int index) const { - const QList rectList = axisRects(); - if (index >= 0 && index < rectList.size()) - { - return rectList.at(index); - } else - { - qDebug() << Q_FUNC_INFO << "invalid axis rect index" << index; - return 0; - } + const QList rectList = axisRects(); + if (index >= 0 && index < rectList.size()) { + return rectList.at(index); + } else { + qDebug() << Q_FUNC_INFO << "invalid axis rect index" << index; + return 0; + } } /*! Returns all axis rects in the plot. - + \see axisRectCount, axisRect */ -QList QCustomPlot::axisRects() const +QList QCustomPlot::axisRects() const { - QList result; - QStack elementStack; - if (mPlotLayout) - elementStack.push(mPlotLayout); - - while (!elementStack.isEmpty()) - { - foreach (QCPLayoutElement *element, elementStack.pop()->elements(false)) - { - if (element) - { - elementStack.push(element); - if (QCPAxisRect *ar = qobject_cast(element)) - result.append(ar); - } + QList result; + QStack elementStack; + if (mPlotLayout) { + elementStack.push(mPlotLayout); } - } - - return result; + + while (!elementStack.isEmpty()) { + foreach (QCPLayoutElement *element, elementStack.pop()->elements(false)) { + if (element) { + elementStack.push(element); + if (QCPAxisRect *ar = qobject_cast(element)) { + result.append(ar); + } + } + } + } + + return result; } /*! Returns the layout element at pixel position \a pos. If there is no element at that position, returns 0. - + Only visible elements are used. If \ref QCPLayoutElement::setVisible on the element itself or on any of its parent elements is set to false, it will not be considered. - + \see itemAt, plottableAt */ QCPLayoutElement *QCustomPlot::layoutElementAt(const QPointF &pos) const { - 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; - break; - } + 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; + break; + } + } } - } - return currentElement; + return currentElement; } /*! Returns the axes that currently have selected parts, i.e. whose selection state is not \ref QCPAxis::spNone. - + \see selectedPlottables, selectedLegends, setInteractions, QCPAxis::setSelectedParts, QCPAxis::setSelectableParts */ -QList QCustomPlot::selectedAxes() const +QList QCustomPlot::selectedAxes() const { - QList result, allAxes; - foreach (QCPAxisRect *rect, axisRects()) - allAxes << rect->axes(); - - foreach (QCPAxis *axis, allAxes) - { - if (axis->selectedParts() != QCPAxis::spNone) - result.append(axis); - } - - return result; + QList result, allAxes; + foreach (QCPAxisRect *rect, axisRects()) { + allAxes << rect->axes(); + } + + foreach (QCPAxis *axis, allAxes) { + if (axis->selectedParts() != QCPAxis::spNone) { + result.append(axis); + } + } + + return result; } /*! Returns the legends that currently have selected parts, i.e. whose selection state is not \ref QCPLegend::spNone. - + \see selectedPlottables, selectedAxes, setInteractions, QCPLegend::setSelectedParts, QCPLegend::setSelectableParts, QCPLegend::selectedItems */ -QList QCustomPlot::selectedLegends() const +QList QCustomPlot::selectedLegends() const { - QList result; - - QStack elementStack; - if (mPlotLayout) - elementStack.push(mPlotLayout); - - while (!elementStack.isEmpty()) - { - foreach (QCPLayoutElement *subElement, elementStack.pop()->elements(false)) - { - if (subElement) - { - elementStack.push(subElement); - if (QCPLegend *leg = qobject_cast(subElement)) - { - if (leg->selectedParts() != QCPLegend::spNone) - result.append(leg); - } - } + QList result; + + QStack elementStack; + if (mPlotLayout) { + elementStack.push(mPlotLayout); } - } - - return result; + + while (!elementStack.isEmpty()) { + foreach (QCPLayoutElement *subElement, elementStack.pop()->elements(false)) { + if (subElement) { + elementStack.push(subElement); + if (QCPLegend *leg = qobject_cast(subElement)) { + if (leg->selectedParts() != QCPLegend::spNone) { + result.append(leg); + } + } + } + } + } + + return result; } /*! Deselects all layerables (plottables, items, axes, legends,...) of the QCustomPlot. - + Since calling this function is not a user interaction, this does not emit the \ref selectionChangedByUser signal. The individual selectionChanged signals are emitted though, if the objects were previously selected. - + \see setInteractions, selectedPlottables, selectedItems, selectedAxes, selectedLegends */ void QCustomPlot::deselectAll() { - foreach (QCPLayer *layer, mLayers) - { - foreach (QCPLayerable *layerable, layer->children()) - layerable->deselectEvent(0); - } + foreach (QCPLayer *layer, mLayers) { + foreach (QCPLayerable *layerable, layer->children()) { + layerable->deselectEvent(0); + } + } } /*! 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. - + 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 @@ -10365,48 +10346,53 @@ void QCustomPlot::deselectAll() */ void QCustomPlot::replot(QCustomPlot::RefreshPriority refreshPriority) { - if (mReplotting) // incase signals loop back to replot slot - return; - mReplotting = true; - 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."; - - emit afterReplot(); - mReplotting = false; + if (mReplotting) { // incase signals loop back to replot slot + return; + } + mReplotting = true; + 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."; + } + + emit afterReplot(); + mReplotting = false; } /*! Rescales the axes such that all plottables (like graphs) in the plot are fully visible. - + if \a onlyVisiblePlottables is set to true, only the plottables that have their visibility set to true (QCPLayerable::setVisible), will be used to rescale the axes. - + \see QCPAbstractPlottable::rescaleAxes, QCPAxis::rescale */ void QCustomPlot::rescaleAxes(bool onlyVisiblePlottables) { - QList allAxes; - foreach (QCPAxisRect *rect, axisRects()) - allAxes << rect->axes(); - - foreach (QCPAxis *axis, allAxes) - axis->rescale(onlyVisiblePlottables); + QList allAxes; + foreach (QCPAxisRect *rect, axisRects()) { + allAxes << rect->axes(); + } + + foreach (QCPAxis *axis, allAxes) { + axis->rescale(onlyVisiblePlottables); + } } /*! @@ -10420,13 +10406,13 @@ void QCustomPlot::rescaleAxes(bool onlyVisiblePlottables) 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 @@ -10437,76 +10423,74 @@ 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. - + \see savePng, saveBmp, saveJpg, saveRastered */ bool QCustomPlot::savePdf(const QString &fileName, bool noCosmeticPen, int width, int height, const QString &pdfCreator, const QString &pdfTitle) { - bool success = false; + bool success = false; #ifdef QT_NO_PRINTER - Q_UNUSED(fileName) - Q_UNUSED(noCosmeticPen) - Q_UNUSED(width) - Q_UNUSED(height) - Q_UNUSED(pdfCreator) - Q_UNUSED(pdfTitle) - qDebug() << Q_FUNC_INFO << "Qt was built without printer support (QT_NO_PRINTER). PDF not created."; + Q_UNUSED(fileName) + Q_UNUSED(noCosmeticPen) + Q_UNUSED(width) + Q_UNUSED(height) + Q_UNUSED(pdfCreator) + Q_UNUSED(pdfTitle) + qDebug() << Q_FUNC_INFO << "Qt was built without printer support (QT_NO_PRINTER). PDF not created."; #else - int newWidth, newHeight; - if (width == 0 || height == 0) - { - newWidth = this->width(); - newHeight = this->height(); - } else - { - newWidth = width; - newHeight = height; - } - - QPrinter printer(QPrinter::ScreenResolution); - printer.setOutputFileName(fileName); - printer.setOutputFormat(QPrinter::PdfFormat); - printer.setColorMode(QPrinter::Color); - printer.printEngine()->setProperty(QPrintEngine::PPK_Creator, pdfCreator); - printer.printEngine()->setProperty(QPrintEngine::PPK_DocumentName, pdfTitle); - QRect oldViewport = viewport(); - setViewport(QRect(0, 0, newWidth, newHeight)); + int newWidth, newHeight; + if (width == 0 || height == 0) { + newWidth = this->width(); + newHeight = this->height(); + } else { + newWidth = width; + newHeight = height; + } + + QPrinter printer(QPrinter::ScreenResolution); + printer.setOutputFileName(fileName); + printer.setOutputFormat(QPrinter::PdfFormat); + printer.setColorMode(QPrinter::Color); + printer.printEngine()->setProperty(QPrintEngine::PPK_Creator, pdfCreator); + printer.printEngine()->setProperty(QPrintEngine::PPK_DocumentName, pdfTitle); + QRect oldViewport = viewport(); + setViewport(QRect(0, 0, newWidth, newHeight)); #if QT_VERSION < QT_VERSION_CHECK(5, 3, 0) - printer.setFullPage(true); - printer.setPaperSize(viewport().size(), QPrinter::DevicePixel); + printer.setFullPage(true); + printer.setPaperSize(viewport().size(), QPrinter::DevicePixel); #else - QPageLayout pageLayout; - pageLayout.setMode(QPageLayout::FullPageMode); - pageLayout.setOrientation(QPageLayout::Portrait); - pageLayout.setMargins(QMarginsF(0, 0, 0, 0)); - pageLayout.setPageSize(QPageSize(viewport().size(), QPageSize::Point, QString(), QPageSize::ExactMatch)); - printer.setPageLayout(pageLayout); + QPageLayout pageLayout; + pageLayout.setMode(QPageLayout::FullPageMode); + pageLayout.setOrientation(QPageLayout::Portrait); + pageLayout.setMargins(QMarginsF(0, 0, 0, 0)); + pageLayout.setPageSize(QPageSize(viewport().size(), QPageSize::Point, QString(), QPageSize::ExactMatch)); + printer.setPageLayout(pageLayout); #endif - QCPPainter printpainter; - if (printpainter.begin(&printer)) - { - printpainter.setMode(QCPPainter::pmVectorized); - printpainter.setMode(QCPPainter::pmNoCaching); - printpainter.setMode(QCPPainter::pmNonCosmetic, noCosmeticPen); - printpainter.setWindow(mViewport); - if (mBackgroundBrush.style() != Qt::NoBrush && - mBackgroundBrush.color() != Qt::white && - mBackgroundBrush.color() != Qt::transparent && - mBackgroundBrush.color().alpha() > 0) // draw pdf background color if not white/transparent - printpainter.fillRect(viewport(), mBackgroundBrush); - draw(&printpainter); - printpainter.end(); - success = true; - } - setViewport(oldViewport); + QCPPainter printpainter; + if (printpainter.begin(&printer)) { + printpainter.setMode(QCPPainter::pmVectorized); + printpainter.setMode(QCPPainter::pmNoCaching); + printpainter.setMode(QCPPainter::pmNonCosmetic, noCosmeticPen); + printpainter.setWindow(mViewport); + if (mBackgroundBrush.style() != Qt::NoBrush && + mBackgroundBrush.color() != Qt::white && + mBackgroundBrush.color() != Qt::transparent && + mBackgroundBrush.color().alpha() > 0) { // draw pdf background color if not white/transparent + printpainter.fillRect(viewport(), mBackgroundBrush); + } + draw(&printpainter); + printpainter.end(); + success = true; + } + setViewport(oldViewport); #endif // QT_NO_PRINTER - return success; + return success; } /*! @@ -10519,7 +10503,7 @@ bool QCustomPlot::savePdf(const QString &fileName, bool noCosmeticPen, int width 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. @@ -10530,7 +10514,7 @@ bool QCustomPlot::savePdf(const QString &fileName, bool noCosmeticPen, int width 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. @@ -10540,7 +10524,7 @@ bool QCustomPlot::savePdf(const QString &fileName, bool noCosmeticPen, int width 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(). @@ -10548,7 +10532,7 @@ bool QCustomPlot::savePdf(const QString &fileName, bool noCosmeticPen, int width */ bool QCustomPlot::savePng(const QString &fileName, int width, int height, double scale, int quality) { - return saveRastered(fileName, width, height, scale, "PNG", quality); + return saveRastered(fileName, width, height, scale, "PNG", quality); } /*! @@ -10561,7 +10545,7 @@ bool QCustomPlot::savePng(const QString &fileName, int width, int height, double 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. @@ -10579,7 +10563,7 @@ bool QCustomPlot::savePng(const QString &fileName, int width, int height, double 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(). @@ -10587,7 +10571,7 @@ bool QCustomPlot::savePng(const QString &fileName, int width, int height, double */ bool QCustomPlot::saveJpg(const QString &fileName, int width, int height, double scale, int quality) { - return saveRastered(fileName, width, height, scale, "JPG", quality); + return saveRastered(fileName, width, height, scale, "JPG", quality); } /*! @@ -10600,7 +10584,7 @@ bool QCustomPlot::saveJpg(const QString &fileName, int width, int height, double 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. @@ -10615,7 +10599,7 @@ bool QCustomPlot::saveJpg(const QString &fileName, int width, int height, double 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(). @@ -10623,11 +10607,11 @@ bool QCustomPlot::saveJpg(const QString &fileName, int width, int height, double */ bool QCustomPlot::saveBmp(const QString &fileName, int width, int height, double scale) { - return saveRastered(fileName, width, height, scale, "BMP"); + return saveRastered(fileName, width, height, scale, "BMP"); } /*! \internal - + Returns a minimum size hint that corresponds to the minimum size of the top level layout (\ref plotLayout). To prevent QCustomPlot from being collapsed to size/width zero, set a minimum size (setMinimumSize) either on the whole QCustomPlot or on any layout elements inside the plot. @@ -10636,236 +10620,233 @@ bool QCustomPlot::saveBmp(const QString &fileName, int width, int height, double */ QSize QCustomPlot::minimumSizeHint() const { - return mPlotLayout->minimumSizeHint(); + return mPlotLayout->minimumSizeHint(); } /*! \internal - + Returns a size hint that is the same as \ref minimumSizeHint. - + */ QSize QCustomPlot::sizeHint() const { - return mPlotLayout->minimumSizeHint(); + return mPlotLayout->minimumSizeHint(); } /*! \internal - + Event handler for when the QCustomPlot widget needs repainting. This does not cause a \ref replot, but draws the internal buffer on the widget surface. */ void QCustomPlot::paintEvent(QPaintEvent *event) { - Q_UNUSED(event); - QPainter painter(this); - painter.drawPixmap(0, 0, mPaintBuffer); + Q_UNUSED(event); + QPainter painter(this); + painter.drawPixmap(0, 0, mPaintBuffer); } /*! \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. */ void QCustomPlot::resizeEvent(QResizeEvent *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 + // 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 } /*! \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. - + \see mousePressEvent, mouseReleaseEvent */ void QCustomPlot::mouseDoubleClickEvent(QMouseEvent *event) { - emit mouseDoubleClick(event); - - 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) - { - mMouseEventElement->mouseReleaseEvent(event); - mMouseEventElement = 0; - } - - //QWidget::mouseDoubleClickEvent(event); don't call base class implementation because it would just cause a mousePress/ReleaseEvent, which we don't want. + emit mouseDoubleClick(event); + + 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) { + mMouseEventElement->mouseReleaseEvent(event); + mMouseEventElement = 0; + } + + //QWidget::mouseDoubleClickEvent(event); don't call base class implementation because it would just cause a mousePress/ReleaseEvent, which we don't want. } /*! \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. - + \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) - - // call event of affected layout element: - mMouseEventElement = layoutElementAt(event->pos()); - if (mMouseEventElement) - mMouseEventElement->mousePressEvent(event); - - QWidget::mousePressEvent(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) + + // call event of affected layout element: + mMouseEventElement = layoutElementAt(event->pos()); + if (mMouseEventElement) { + mMouseEventElement->mousePressEvent(event); + } + + QWidget::mousePressEvent(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. - + \see mousePressEvent, mouseReleaseEvent */ void QCustomPlot::mouseMoveEvent(QMouseEvent *event) { - emit mouseMove(event); + emit mouseMove(event); - // call event of affected layout element: - if (mMouseEventElement) - mMouseEventElement->mouseMoveEvent(event); - - QWidget::mouseMoveEvent(event); + // call event of affected layout element: + if (mMouseEventElement) { + mMouseEventElement->mouseMoveEvent(event); + } + + QWidget::mouseMoveEvent(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. - + \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 (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; + emit mouseRelease(event); + bool doReplot = false; + + if ((mMousePressPos - event->pos()).manhattanLength() < 5) { // determine whether it was a click operation + 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(); } - } } - } - 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(); - } + + // 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 itemClick(ai, event); + } else if (QCPLegend *lg = qobject_cast(clickedLayerable)) { + emit legendClick(lg, 0, event); + } else if (QCPAbstractLegendItem *li = qobject_cast(clickedLayerable)) { + emit legendClick(li->parentLegend(), li, event); + } else if (QCPPlotTitle *pt = qobject_cast(clickedLayerable)) { + emit titleClick(event, pt); + } } - - // 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 itemClick(ai, event); - else if (QCPLegend *lg = qobject_cast(clickedLayerable)) - emit legendClick(lg, 0, event); - else if (QCPAbstractLegendItem *li = qobject_cast(clickedLayerable)) - 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) - { - mMouseEventElement->mouseReleaseEvent(event); - mMouseEventElement = 0; - } - - if (doReplot || noAntialiasingOnDrag()) - replot(); - - QWidget::mouseReleaseEvent(event); + + // call event of affected layout element: + if (mMouseEventElement) { + mMouseEventElement->mouseReleaseEvent(event); + mMouseEventElement = 0; + } + + if (doReplot || noAntialiasingOnDrag()) { + replot(); + } + + QWidget::mouseReleaseEvent(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. - + */ 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); + emit mouseWheel(event); + + // call event of affected layout element: + if (QCPLayoutElement *el = layoutElementAt(event->pos())) { + el->wheelEvent(event); + } + + QWidget::wheelEvent(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 @@ -10873,46 +10854,43 @@ void QCustomPlot::wheelEvent(QWheelEvent *event) */ void QCustomPlot::draw(QCPPainter *painter) { - // run through layout phases: - mPlotLayout->update(QCPLayoutElement::upPreparation); - mPlotLayout->update(QCPLayoutElement::upMargins); - mPlotLayout->update(QCPLayoutElement::upLayout); - - // draw viewport background pixmap: - drawBackground(painter); + // run through layout phases: + mPlotLayout->update(QCPLayoutElement::upPreparation); + mPlotLayout->update(QCPLayoutElement::upMargins); + mPlotLayout->update(QCPLayoutElement::upLayout); - // 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(); - } + // 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(); + } + } } - } - - /* Debug code to draw all layout element rects - foreach (QCPLayoutElement* el, findChildren()) - { - painter->setBrush(Qt::NoBrush); - painter->setPen(QPen(QColor(0, 0, 0, 100), 0, Qt::DashLine)); - painter->drawRect(el->rect()); - painter->setPen(QPen(QColor(255, 0, 0, 100), 0, Qt::DashLine)); - painter->drawRect(el->outerRect()); - } - */ + + /* Debug code to draw all layout element rects + foreach (QCPLayoutElement* el, findChildren()) + { + painter->setBrush(Qt::NoBrush); + painter->setPen(QPen(QColor(0, 0, 0, 100), 0, Qt::DashLine)); + painter->drawRect(el->rect()); + painter->setPen(QPen(QColor(255, 0, 0, 100), 0, Qt::DashLine)); + painter->drawRect(el->outerRect()); + } + */ } /*! \internal - + Draws the viewport background pixmap of the plot. - + If a pixmap was provided via \ref setBackground, this function buffers the scaled version depending on \ref setBackgroundScaled and \ref setBackgroundScaledMode and then draws it inside the viewport with the provided \a painter. The scaled version is buffered in @@ -10920,79 +10898,83 @@ void QCustomPlot::draw(QCPPainter *painter) the axis rect has changed in a way that requires a rescale of the background pixmap (this is 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. - + \see setBackground, setBackgroundScaled, setBackgroundScaledMode */ void QCustomPlot::drawBackground(QCPPainter *painter) { - // Note: background color is handled in individual replot/save functions + // Note: background color is handled in individual replot/save functions - // draw background pixmap (on top of fill, if brush specified): - if (!mBackgroundPixmap.isNull()) - { - if (mBackgroundScaled) - { - // check whether mScaledBackground needs to be updated: - QSize scaledSize(mBackgroundPixmap.size()); - scaledSize.scale(mViewport.size(), mBackgroundScaledMode); - if (mScaledBackgroundPixmap.size() != scaledSize) - mScaledBackgroundPixmap = mBackgroundPixmap.scaled(mViewport.size(), mBackgroundScaledMode, Qt::SmoothTransformation); - painter->drawPixmap(mViewport.topLeft(), mScaledBackgroundPixmap, QRect(0, 0, mViewport.width(), mViewport.height()) & mScaledBackgroundPixmap.rect()); - } else - { - painter->drawPixmap(mViewport.topLeft(), mBackgroundPixmap, QRect(0, 0, mViewport.width(), mViewport.height())); + // draw background pixmap (on top of fill, if brush specified): + if (!mBackgroundPixmap.isNull()) { + if (mBackgroundScaled) { + // check whether mScaledBackground needs to be updated: + QSize scaledSize(mBackgroundPixmap.size()); + scaledSize.scale(mViewport.size(), mBackgroundScaledMode); + if (mScaledBackgroundPixmap.size() != scaledSize) { + mScaledBackgroundPixmap = mBackgroundPixmap.scaled(mViewport.size(), mBackgroundScaledMode, Qt::SmoothTransformation); + } + painter->drawPixmap(mViewport.topLeft(), mScaledBackgroundPixmap, QRect(0, 0, mViewport.width(), mViewport.height()) & mScaledBackgroundPixmap.rect()); + } else { + painter->drawPixmap(mViewport.topLeft(), mBackgroundPixmap, QRect(0, 0, mViewport.width(), mViewport.height())); + } } - } } /*! \internal - + This method is used by \ref QCPAxisRect::removeAxis to report removed axes to the QCustomPlot so it may clear its QCustomPlot::xAxis, yAxis, xAxis2 and yAxis2 members accordingly. */ void QCustomPlot::axisRemoved(QCPAxis *axis) { - if (xAxis == axis) - xAxis = 0; - if (xAxis2 == axis) - xAxis2 = 0; - if (yAxis == axis) - yAxis = 0; - if (yAxis2 == axis) - yAxis2 = 0; - - // Note: No need to take care of range drag axes and range zoom axes, because they are stored in smart pointers + if (xAxis == axis) { + xAxis = 0; + } + if (xAxis2 == axis) { + xAxis2 = 0; + } + if (yAxis == axis) { + yAxis = 0; + } + if (yAxis2 == axis) { + yAxis2 = 0; + } + + // Note: No need to take care of range drag axes and range zoom axes, because they are stored in smart pointers } /*! \internal - + This method is used by the QCPLegend destructor to report legend removal to the QCustomPlot so it may clear its QCustomPlot::legend member accordingly. */ void QCustomPlot::legendRemoved(QCPLegend *legend) { - if (this->legend == legend) - this->legend = 0; + if (this->legend == legend) { + this->legend = 0; + } } /*! \internal - + Assigns all layers their index (QCPLayer::mIndex) in the mLayers list. This method is thus called after every operation that changes the layer indices, like layer removal, layer creation, layer moving. */ void QCustomPlot::updateLayerIndices() const { - for (int i=0; imIndex = i; + for (int i = 0; i < mLayers.size(); ++i) { + mLayers.at(i)->mIndex = i; + } } /*! \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.) @@ -11005,28 +10987,29 @@ void QCustomPlot::updateLayerIndices() const */ QCPLayerable *QCustomPlot::layerableAt(const QPointF &pos, bool onlySelectable, QVariant *selectionDetails) const { - 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) - { - minimumDistance = dist; - minimumDistanceLayerable = layerables.at(i); - if (selectionDetails) *selectionDetails = details; - } + 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) { + minimumDistance = dist; + minimumDistanceLayerable = layerables.at(i); + if (selectionDetails) { + *selectionDetails = details; + } + } + } + if (minimumDistance < selectionTolerance()) { + return minimumDistanceLayerable; + } } - if (minimumDistance < selectionTolerance()) - return minimumDistanceLayerable; - } - return 0; + return 0; } /*! @@ -11034,110 +11017,107 @@ 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(). - + \see saveBmp, saveJpg, savePng, savePdf */ bool QCustomPlot::saveRastered(const QString &fileName, int width, int height, double scale, const char *format, int quality) { - QPixmap buffer = toPixmap(width, height, scale); - if (!buffer.isNull()) - return buffer.save(fileName, format, quality); - else - return false; + QPixmap buffer = toPixmap(width, height, scale); + if (!buffer.isNull()) { + return buffer.save(fileName, format, quality); + } else { + return false; + } } /*! Renders the plot to a pixmap and returns it. - + The plot is 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 pixmap with width 200.) - + \see toPainter, saveRastered, saveBmp, savePng, saveJpg, savePdf */ QPixmap QCustomPlot::toPixmap(int width, int height, double scale) { - // this method is somewhat similar to toPainter. Change something here, and a change in toPainter might be necessary, too. - int newWidth, newHeight; - if (width == 0 || height == 0) - { - newWidth = this->width(); - newHeight = this->height(); - } else - { - newWidth = width; - newHeight = height; - } - int scaledWidth = qRound(scale*newWidth); - int scaledHeight = qRound(scale*newHeight); - - QPixmap result(scaledWidth, scaledHeight); - result.fill(mBackgroundBrush.style() == Qt::SolidPattern ? mBackgroundBrush.color() : Qt::transparent); // if using non-solid pattern, make transparent now and draw brush pattern later - QCPPainter painter; - painter.begin(&result); - if (painter.isActive()) - { - QRect oldViewport = viewport(); - setViewport(QRect(0, 0, newWidth, newHeight)); - painter.setMode(QCPPainter::pmNoCaching); - if (!qFuzzyCompare(scale, 1.0)) - { - if (scale > 1.0) // for scale < 1 we always want cosmetic pens where possible, because else lines might disappear for very small scales - painter.setMode(QCPPainter::pmNonCosmetic); - painter.scale(scale, scale); + // this method is somewhat similar to toPainter. Change something here, and a change in toPainter might be necessary, too. + int newWidth, newHeight; + if (width == 0 || height == 0) { + newWidth = this->width(); + newHeight = this->height(); + } else { + newWidth = width; + newHeight = height; } - if (mBackgroundBrush.style() != Qt::SolidPattern && mBackgroundBrush.style() != Qt::NoBrush) // solid fills were done a few lines above with QPixmap::fill - painter.fillRect(mViewport, mBackgroundBrush); - draw(&painter); - setViewport(oldViewport); - painter.end(); - } else // might happen if pixmap has width or height zero - { - qDebug() << Q_FUNC_INFO << "Couldn't activate painter on pixmap"; - return QPixmap(); - } - return result; + int scaledWidth = qRound(scale * newWidth); + int scaledHeight = qRound(scale * newHeight); + + QPixmap result(scaledWidth, scaledHeight); + result.fill(mBackgroundBrush.style() == Qt::SolidPattern ? mBackgroundBrush.color() : Qt::transparent); // if using non-solid pattern, make transparent now and draw brush pattern later + QCPPainter painter; + painter.begin(&result); + if (painter.isActive()) { + QRect oldViewport = viewport(); + setViewport(QRect(0, 0, newWidth, newHeight)); + painter.setMode(QCPPainter::pmNoCaching); + if (!qFuzzyCompare(scale, 1.0)) { + if (scale > 1.0) { // for scale < 1 we always want cosmetic pens where possible, because else lines might disappear for very small scales + painter.setMode(QCPPainter::pmNonCosmetic); + } + painter.scale(scale, scale); + } + if (mBackgroundBrush.style() != Qt::SolidPattern && mBackgroundBrush.style() != Qt::NoBrush) { // solid fills were done a few lines above with QPixmap::fill + painter.fillRect(mViewport, mBackgroundBrush); + } + draw(&painter); + setViewport(oldViewport); + painter.end(); + } else { // might happen if pixmap has width or height zero + qDebug() << Q_FUNC_INFO << "Couldn't activate painter on pixmap"; + return QPixmap(); + } + return result; } /*! Renders the plot using the passed \a painter. - + The plot is sized to \a width and \a height in pixels. If the \a painter's scale is not 1.0, the resulting plot will appear scaled accordingly. - + \note If you are restricted to using a QPainter (instead of QCPPainter), create a temporary QPicture and open a QCPPainter on it. Then call \ref toPainter with this QCPPainter. After ending the paint operation on the picture, draw it with the QPainter. This will reproduce the painter actions the QCPPainter took, with a QPainter. - + \see toPixmap */ void QCustomPlot::toPainter(QCPPainter *painter, int width, int height) { - // this method is somewhat similar to toPixmap. Change something here, and a change in toPixmap might be necessary, too. - int newWidth, newHeight; - if (width == 0 || height == 0) - { - newWidth = this->width(); - newHeight = this->height(); - } else - { - newWidth = width; - newHeight = height; - } + // this method is somewhat similar to toPixmap. Change something here, and a change in toPixmap might be necessary, too. + int newWidth, newHeight; + if (width == 0 || height == 0) { + newWidth = this->width(); + newHeight = this->height(); + } else { + newWidth = width; + newHeight = height; + } - if (painter->isActive()) - { - QRect oldViewport = viewport(); - setViewport(QRect(0, 0, newWidth, newHeight)); - painter->setMode(QCPPainter::pmNoCaching); - if (mBackgroundBrush.style() != Qt::NoBrush) // unlike in toPixmap, we can't do QPixmap::fill for Qt::SolidPattern brush style, so we also draw solid fills with fillRect here - painter->fillRect(mViewport, mBackgroundBrush); - draw(painter); - setViewport(oldViewport); - } else - qDebug() << Q_FUNC_INFO << "Passed painter is not active"; + if (painter->isActive()) { + QRect oldViewport = viewport(); + setViewport(QRect(0, 0, newWidth, newHeight)); + painter->setMode(QCPPainter::pmNoCaching); + if (mBackgroundBrush.style() != Qt::NoBrush) { // unlike in toPixmap, we can't do QPixmap::fill for Qt::SolidPattern brush style, so we also draw solid fills with fillRect here + painter->fillRect(mViewport, mBackgroundBrush); + } + draw(painter); + setViewport(oldViewport); + } else { + qDebug() << Q_FUNC_INFO << "Passed painter is not active"; + } } @@ -11147,7 +11127,7 @@ void QCustomPlot::toPainter(QCPPainter *painter, int width, int height) /*! \class QCPColorGradient \brief Defines a color gradient for use with e.g. \ref QCPColorMap - + This class describes a color gradient which can be used to encode data with color. For example, QCPColorMap and QCPColorScale have \ref QCPColorMap::setGradient "setGradient" methods which take an instance of this class. Colors are set with \ref setColorStopAt(double position, const QColor &color) @@ -11156,14 +11136,14 @@ 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. - + \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.: \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 color gradient shall be applied periodically (wrapping around) to data values that lie outside the data range specified on the plottable instance can be controlled with \ref setPeriodic. @@ -11172,110 +11152,107 @@ void QCustomPlot::toPainter(QCPPainter *painter, int width, int height) /*! 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) : - mLevelCount(350), - mColorInterpolation(ciRGB), - mPeriodic(false), - mColorBufferInvalidated(true) + mLevelCount(350), + mColorInterpolation(ciRGB), + mPeriodic(false), + mColorBufferInvalidated(true) { - mColorBuffer.fill(qRgb(0, 0, 0), mLevelCount); - loadPreset(preset); + mColorBuffer.fill(qRgb(0, 0, 0), mLevelCount); + loadPreset(preset); } /* undocumented operator */ bool QCPColorGradient::operator==(const QCPColorGradient &other) const { - return ((other.mLevelCount == this->mLevelCount) && - (other.mColorInterpolation == this->mColorInterpolation) && - (other.mPeriodic == this->mPeriodic) && - (other.mColorStops == this->mColorStops)); + return ((other.mLevelCount == this->mLevelCount) && + (other.mColorInterpolation == this->mColorInterpolation) && + (other.mPeriodic == this->mPeriodic) && + (other.mColorStops == this->mColorStops)); } /*! 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. - + \image html QCPColorGradient-levelcount.png */ void QCPColorGradient::setLevelCount(int n) { - if (n < 2) - { - qDebug() << Q_FUNC_INFO << "n must be greater or equal 2 but was" << n; - n = 2; - } - if (n != mLevelCount) - { - mLevelCount = n; - mColorBufferInvalidated = true; - } + if (n < 2) { + qDebug() << Q_FUNC_INFO << "n must be greater or equal 2 but was" << n; + n = 2; + } + if (n != mLevelCount) { + mLevelCount = n; + mColorBufferInvalidated = true; + } } /*! Sets at which positions from 0 to 1 which color shall occur. The positions are the keys, the colors are the values of the passed QMap \a colorStops. In between these color stops, the color 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. - + \see clearColorStops */ void QCPColorGradient::setColorStops(const QMap &colorStops) { - mColorStops = colorStops; - mColorBufferInvalidated = true; + mColorStops = colorStops; + mColorBufferInvalidated = true; } /*! Sets the \a color the gradient will have at the specified \a position (from 0 to 1). In between these color stops, the color is interpolated according to \ref setColorInterpolation. - + \see setColorStops, clearColorStops */ void QCPColorGradient::setColorStopAt(double position, const QColor &color) { - mColorStops.insert(position, color); - mColorBufferInvalidated = true; + mColorStops.insert(position, color); + mColorBufferInvalidated = true; } /*! Sets whether the colors in between the configured color stops (see \ref setColorStopAt) shall be interpolated linearly in RGB or in HSV color space. - + For example, a sweep in RGB space from red to green will have a muddy brown intermediate color, whereas in HSV space the intermediate color is yellow. */ void QCPColorGradient::setColorInterpolation(QCPColorGradient::ColorInterpolation interpolation) { - if (interpolation != mColorInterpolation) - { - mColorInterpolation = interpolation; - mColorBufferInvalidated = true; - } + if (interpolation != mColorInterpolation) { + mColorInterpolation = interpolation; + mColorBufferInvalidated = true; + } } /*! Sets whether data points that are outside the configured data range (e.g. \ref QCPColorMap::setDataRange) are colored by periodically repeating the color gradient or whether they all have the same color, corresponding to the respective gradient boundary color. - + \image html QCPColorGradient-periodic.png - + As shown in the image above, gradients that have the same start and end color are especially suitable for a periodic gradient mapping, since they produce smooth color transitions throughout the color map. A preset that has this property is \ref gpHues. - + In practice, using periodic color gradients makes sense when the data corresponds to a periodic dimension, such as an angle or a phase. If this is not the case, the color encoding might become ambiguous, because multiple different data values are shown as the same color. */ void QCPColorGradient::setPeriodic(bool enabled) { - mPeriodic = enabled; + mPeriodic = enabled; } /*! @@ -11284,7 +11261,7 @@ void QCPColorGradient::setPeriodic(bool enabled) 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 @@ -11292,305 +11269,295 @@ void QCPColorGradient::setPeriodic(bool enabled) */ 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 (!data) - { - qDebug() << Q_FUNC_INFO << "null pointer given as data"; - 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; - scanLine[i] = mColorBuffer.at(index); - } + // If you change something here, make sure to also adapt ::color() + if (!data) { + qDebug() << Q_FUNC_INFO << "null pointer given as data"; + return; } - } else // logarithmic == true - { - if (mPeriodic) - { - for (int i=0; i= mLevelCount) - index = mLevelCount-1; - scanLine[i] = mColorBuffer.at(index); - } + if (!scanLine) { + qDebug() << Q_FUNC_INFO << "null pointer given as scanLine"; + return; + } + if (mColorBufferInvalidated) { + updateColorBuffer(); + } + + if (!logarithmic) { + const double posToIndexFactor = (mLevelCount - 1) / range.size(); + if (mPeriodic) { + for (int i = 0; i < n; ++i) { + int index = (int)((data[dataIndexFactor * i] - range.lower) * posToIndexFactor) % mLevelCount; + if (index < 0) { + index += mLevelCount; + } + scanLine[i] = mColorBuffer.at(index); + } + } else { + for (int i = 0; i < n; ++i) { + int index = (data[dataIndexFactor * i] - range.lower) * posToIndexFactor; + if (index < 0) { + index = 0; + } else if (index >= mLevelCount) { + index = mLevelCount - 1; + } + scanLine[i] = mColorBuffer.at(index); + } + } + } else { // logarithmic == true + if (mPeriodic) { + for (int i = 0; i < n; ++i) { + int index = (int)(qLn(data[dataIndexFactor * i] / range.lower) / qLn(range.upper / range.lower) * (mLevelCount - 1)) % mLevelCount; + if (index < 0) { + index += mLevelCount; + } + scanLine[i] = mColorBuffer.at(index); + } + } else { + for (int i = 0; i < n; ++i) { + int index = qLn(data[dataIndexFactor * i] / range.lower) / qLn(range.upper / range.lower) * (mLevelCount - 1); + if (index < 0) { + index = 0; + } else if (index >= mLevelCount) { + index = mLevelCount - 1; + } + scanLine[i] = mColorBuffer.at(index); + } + } } - } } /*! \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. */ QRgb QCPColorGradient::color(double position, const QCPRange &range, bool logarithmic) { - // If you change something here, make sure to also adapt ::colorize() - if (mColorBufferInvalidated) - updateColorBuffer(); - int index = 0; - if (!logarithmic) - index = (position-range.lower)*(mLevelCount-1)/range.size(); - else - index = qLn(position/range.lower)/qLn(range.upper/range.lower)*(mLevelCount-1); - if (mPeriodic) - { - index = index % mLevelCount; - if (index < 0) - index += mLevelCount; - } else - { - if (index < 0) - index = 0; - else if (index >= mLevelCount) - index = mLevelCount-1; - } - return mColorBuffer.at(index); + // If you change something here, make sure to also adapt ::colorize() + if (mColorBufferInvalidated) { + updateColorBuffer(); + } + int index = 0; + if (!logarithmic) { + index = (position - range.lower) * (mLevelCount - 1) / range.size(); + } else { + index = qLn(position / range.lower) / qLn(range.upper / range.lower) * (mLevelCount - 1); + } + if (mPeriodic) { + index = index % mLevelCount; + if (index < 0) { + index += mLevelCount; + } + } else { + if (index < 0) { + index = 0; + } else if (index >= mLevelCount) { + index = mLevelCount - 1; + } + } + return mColorBuffer.at(index); } /*! Clears the current color stops and loads the specified \a preset. A preset consists of predefined color stops and the corresponding color interpolation method. - + The available presets are: \image html QCPColorGradient.png */ void QCPColorGradient::loadPreset(GradientPreset preset) { - clearColorStops(); - switch (preset) - { - case gpGrayscale: - setColorInterpolation(ciRGB); - setColorStopAt(0, Qt::black); - setColorStopAt(1, Qt::white); - break; - case gpHot: - setColorInterpolation(ciRGB); - setColorStopAt(0, QColor(50, 0, 0)); - setColorStopAt(0.2, QColor(180, 10, 0)); - setColorStopAt(0.4, QColor(245, 50, 0)); - setColorStopAt(0.6, QColor(255, 150, 10)); - setColorStopAt(0.8, QColor(255, 255, 50)); - setColorStopAt(1, QColor(255, 255, 255)); - break; - case gpCold: - setColorInterpolation(ciRGB); - setColorStopAt(0, QColor(0, 0, 50)); - setColorStopAt(0.2, QColor(0, 10, 180)); - setColorStopAt(0.4, QColor(0, 50, 245)); - setColorStopAt(0.6, QColor(10, 150, 255)); - setColorStopAt(0.8, QColor(50, 255, 255)); - setColorStopAt(1, QColor(255, 255, 255)); - break; - case gpNight: - setColorInterpolation(ciHSV); - setColorStopAt(0, QColor(10, 20, 30)); - setColorStopAt(1, QColor(250, 255, 250)); - break; - case gpCandy: - setColorInterpolation(ciHSV); - setColorStopAt(0, QColor(0, 0, 255)); - setColorStopAt(1, QColor(255, 250, 250)); - break; - case gpGeography: - setColorInterpolation(ciRGB); - setColorStopAt(0, QColor(70, 170, 210)); - setColorStopAt(0.20, QColor(90, 160, 180)); - setColorStopAt(0.25, QColor(45, 130, 175)); - setColorStopAt(0.30, QColor(100, 140, 125)); - setColorStopAt(0.5, QColor(100, 140, 100)); - setColorStopAt(0.6, QColor(130, 145, 120)); - setColorStopAt(0.7, QColor(140, 130, 120)); - setColorStopAt(0.9, QColor(180, 190, 190)); - setColorStopAt(1, QColor(210, 210, 230)); - break; - case gpIon: - setColorInterpolation(ciHSV); - setColorStopAt(0, QColor(50, 10, 10)); - setColorStopAt(0.45, QColor(0, 0, 255)); - setColorStopAt(0.8, QColor(0, 255, 255)); - setColorStopAt(1, QColor(0, 255, 0)); - break; - case gpThermal: - setColorInterpolation(ciRGB); - setColorStopAt(0, QColor(0, 0, 50)); - setColorStopAt(0.15, QColor(20, 0, 120)); - setColorStopAt(0.33, QColor(200, 30, 140)); - setColorStopAt(0.6, QColor(255, 100, 0)); - setColorStopAt(0.85, QColor(255, 255, 40)); - setColorStopAt(1, QColor(255, 255, 255)); - break; - case gpPolar: - setColorInterpolation(ciRGB); - setColorStopAt(0, QColor(50, 255, 255)); - setColorStopAt(0.18, QColor(10, 70, 255)); - setColorStopAt(0.28, QColor(10, 10, 190)); - setColorStopAt(0.5, QColor(0, 0, 0)); - setColorStopAt(0.72, QColor(190, 10, 10)); - setColorStopAt(0.82, QColor(255, 70, 10)); - setColorStopAt(1, QColor(255, 255, 50)); - break; - case gpSpectrum: - setColorInterpolation(ciHSV); - setColorStopAt(0, QColor(50, 0, 50)); - setColorStopAt(0.15, QColor(0, 0, 255)); - setColorStopAt(0.35, QColor(0, 255, 255)); - setColorStopAt(0.6, QColor(255, 255, 0)); - setColorStopAt(0.75, QColor(255, 30, 0)); - setColorStopAt(1, QColor(50, 0, 0)); - break; - case gpJet: - setColorInterpolation(ciRGB); - setColorStopAt(0, QColor(0, 0, 100)); - setColorStopAt(0.15, QColor(0, 50, 255)); - setColorStopAt(0.35, QColor(0, 255, 255)); - setColorStopAt(0.65, QColor(255, 255, 0)); - setColorStopAt(0.85, QColor(255, 30, 0)); - setColorStopAt(1, QColor(100, 0, 0)); - break; - case gpHues: - setColorInterpolation(ciHSV); - setColorStopAt(0, QColor(255, 0, 0)); - setColorStopAt(1.0/3.0, QColor(0, 0, 255)); - setColorStopAt(2.0/3.0, QColor(0, 255, 0)); - setColorStopAt(1, QColor(255, 0, 0)); - break; - } + clearColorStops(); + switch (preset) { + case gpGrayscale: + setColorInterpolation(ciRGB); + setColorStopAt(0, Qt::black); + setColorStopAt(1, Qt::white); + break; + case gpHot: + setColorInterpolation(ciRGB); + setColorStopAt(0, QColor(50, 0, 0)); + setColorStopAt(0.2, QColor(180, 10, 0)); + setColorStopAt(0.4, QColor(245, 50, 0)); + setColorStopAt(0.6, QColor(255, 150, 10)); + setColorStopAt(0.8, QColor(255, 255, 50)); + setColorStopAt(1, QColor(255, 255, 255)); + break; + case gpCold: + setColorInterpolation(ciRGB); + setColorStopAt(0, QColor(0, 0, 50)); + setColorStopAt(0.2, QColor(0, 10, 180)); + setColorStopAt(0.4, QColor(0, 50, 245)); + setColorStopAt(0.6, QColor(10, 150, 255)); + setColorStopAt(0.8, QColor(50, 255, 255)); + setColorStopAt(1, QColor(255, 255, 255)); + break; + case gpNight: + setColorInterpolation(ciHSV); + setColorStopAt(0, QColor(10, 20, 30)); + setColorStopAt(1, QColor(250, 255, 250)); + break; + case gpCandy: + setColorInterpolation(ciHSV); + setColorStopAt(0, QColor(0, 0, 255)); + setColorStopAt(1, QColor(255, 250, 250)); + break; + case gpGeography: + setColorInterpolation(ciRGB); + setColorStopAt(0, QColor(70, 170, 210)); + setColorStopAt(0.20, QColor(90, 160, 180)); + setColorStopAt(0.25, QColor(45, 130, 175)); + setColorStopAt(0.30, QColor(100, 140, 125)); + setColorStopAt(0.5, QColor(100, 140, 100)); + setColorStopAt(0.6, QColor(130, 145, 120)); + setColorStopAt(0.7, QColor(140, 130, 120)); + setColorStopAt(0.9, QColor(180, 190, 190)); + setColorStopAt(1, QColor(210, 210, 230)); + break; + case gpIon: + setColorInterpolation(ciHSV); + setColorStopAt(0, QColor(50, 10, 10)); + setColorStopAt(0.45, QColor(0, 0, 255)); + setColorStopAt(0.8, QColor(0, 255, 255)); + setColorStopAt(1, QColor(0, 255, 0)); + break; + case gpThermal: + setColorInterpolation(ciRGB); + setColorStopAt(0, QColor(0, 0, 50)); + setColorStopAt(0.15, QColor(20, 0, 120)); + setColorStopAt(0.33, QColor(200, 30, 140)); + setColorStopAt(0.6, QColor(255, 100, 0)); + setColorStopAt(0.85, QColor(255, 255, 40)); + setColorStopAt(1, QColor(255, 255, 255)); + break; + case gpPolar: + setColorInterpolation(ciRGB); + setColorStopAt(0, QColor(50, 255, 255)); + setColorStopAt(0.18, QColor(10, 70, 255)); + setColorStopAt(0.28, QColor(10, 10, 190)); + setColorStopAt(0.5, QColor(0, 0, 0)); + setColorStopAt(0.72, QColor(190, 10, 10)); + setColorStopAt(0.82, QColor(255, 70, 10)); + setColorStopAt(1, QColor(255, 255, 50)); + break; + case gpSpectrum: + setColorInterpolation(ciHSV); + setColorStopAt(0, QColor(50, 0, 50)); + setColorStopAt(0.15, QColor(0, 0, 255)); + setColorStopAt(0.35, QColor(0, 255, 255)); + setColorStopAt(0.6, QColor(255, 255, 0)); + setColorStopAt(0.75, QColor(255, 30, 0)); + setColorStopAt(1, QColor(50, 0, 0)); + break; + case gpJet: + setColorInterpolation(ciRGB); + setColorStopAt(0, QColor(0, 0, 100)); + setColorStopAt(0.15, QColor(0, 50, 255)); + setColorStopAt(0.35, QColor(0, 255, 255)); + setColorStopAt(0.65, QColor(255, 255, 0)); + setColorStopAt(0.85, QColor(255, 30, 0)); + setColorStopAt(1, QColor(100, 0, 0)); + break; + case gpHues: + setColorInterpolation(ciHSV); + setColorStopAt(0, QColor(255, 0, 0)); + setColorStopAt(1.0 / 3.0, QColor(0, 0, 255)); + setColorStopAt(2.0 / 3.0, QColor(0, 255, 0)); + setColorStopAt(1, QColor(255, 0, 0)); + break; + } } /*! Clears all color stops. - + \see setColorStops, setColorStopAt */ void QCPColorGradient::clearColorStops() { - mColorStops.clear(); - mColorBufferInvalidated = true; + mColorStops.clear(); + mColorBufferInvalidated = true; } /*! Returns an inverted gradient. The inverted gradient has all properties as this \ref QCPColorGradient, but the order of the color stops is inverted. - + \see setColorStops, setColorStopAt */ QCPColorGradient QCPColorGradient::inverted() const { - QCPColorGradient result(*this); - result.clearColorStops(); - for (QMap::const_iterator it=mColorStops.constBegin(); it!=mColorStops.constEnd(); ++it) - result.setColorStopAt(1.0-it.key(), it.value()); - return result; + QCPColorGradient result(*this); + result.clearColorStops(); + for (QMap::const_iterator it = mColorStops.constBegin(); it != mColorStops.constEnd(); ++it) { + result.setColorStopAt(1.0 - it.key(), it.value()); + } + return result; } /*! \internal - + Updates the internal color buffer which will be used by \ref colorize and \ref color, to quickly convert positions to colors. This is where the interpolation between color stops is calculated. */ void QCPColorGradient::updateColorBuffer() { - if (mColorBuffer.size() != mLevelCount) - mColorBuffer.resize(mLevelCount); - if (mColorStops.size() > 1) - { - double indexToPosFactor = 1.0/(double)(mLevelCount-1); - 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(); - } else if (it == mColorStops.constBegin()) // position is on or before first stop, use color of first stop - { - mColorBuffer[i] = it.value().rgb(); - } else // position is in between stops (or on an intermediate stop), interpolate color - { - QMap::const_iterator high = it; - QMap::const_iterator low = it-1; - double t = (position-low.key())/(high.key()-low.key()); // interpolation factor 0..1 - switch (mColorInterpolation) - { - 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()); - break; - } - case ciHSV: - { - QColor lowHsv = low.value().toHsv(); - QColor highHsv = high.value().toHsv(); - double hue = 0; - double hueDiff = highHsv.hueF()-lowHsv.hueF(); - if (hueDiff > 0.5) - hue = lowHsv.hueF() - t*(1.0-hueDiff); - else if (hueDiff < -0.5) - hue = lowHsv.hueF() + t*(1.0+hueDiff); - else - 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(); - break; - } - } - } + if (mColorBuffer.size() != mLevelCount) { + mColorBuffer.resize(mLevelCount); } - } else if (mColorStops.size() == 1) - { - mColorBuffer.fill(mColorStops.constBegin().value().rgb()); - } else // mColorStops is empty, fill color buffer with black - { - mColorBuffer.fill(qRgb(0, 0, 0)); - } - mColorBufferInvalidated = false; + if (mColorStops.size() > 1) { + double indexToPosFactor = 1.0 / (double)(mLevelCount - 1); + for (int i = 0; i < mLevelCount; ++i) { + double position = i * indexToPosFactor; + QMap::const_iterator it = mColorStops.lowerBound(position); + if (it == mColorStops.constEnd()) { // position is on or after last stop, use color of last stop + mColorBuffer[i] = (it - 1).value().rgb(); + } else if (it == mColorStops.constBegin()) { // position is on or before first stop, use color of first stop + mColorBuffer[i] = it.value().rgb(); + } else { // position is in between stops (or on an intermediate stop), interpolate color + QMap::const_iterator high = it; + QMap::const_iterator low = it - 1; + double t = (position - low.key()) / (high.key() - low.key()); // interpolation factor 0..1 + switch (mColorInterpolation) { + 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()); + break; + } + case ciHSV: { + QColor lowHsv = low.value().toHsv(); + QColor highHsv = high.value().toHsv(); + double hue = 0; + double hueDiff = highHsv.hueF() - lowHsv.hueF(); + if (hueDiff > 0.5) { + hue = lowHsv.hueF() - t * (1.0 - hueDiff); + } else if (hueDiff < -0.5) { + hue = lowHsv.hueF() + t * (1.0 + hueDiff); + } else { + 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(); + break; + } + } + } + } + } else if (mColorStops.size() == 1) { + mColorBuffer.fill(mColorStops.constBegin().value().rgb()); + } else { // mColorStops is empty, fill color buffer with black + mColorBuffer.fill(qRgb(0, 0, 0)); + } + mColorBufferInvalidated = false; } @@ -11600,36 +11567,36 @@ void QCPColorGradient::updateColorBuffer() /*! \class QCPAxisRect \brief Holds multiple axes and arranges them in a rectangular shape. - + This class represents an axis rect, a rectangular area that is bounded on all sides with an arbitrary number of axes. - + Initially QCustomPlot has one axis rect, accessible via QCustomPlot::axisRect(). However, the layout system allows to have multiple axis rects, e.g. arranged in a grid layout (QCustomPlot::plotLayout). - + By default, QCPAxisRect comes with four axes, at bottom, top, left and right. They can be accessed via \ref axis by providing the respective axis type (\ref QCPAxis::AxisType) and index. If you need all axes in the axis rect, use \ref axes. The top and right axes are set to be invisible initially (QCPAxis::setVisible). To add more axes to a side, use \ref addAxis or \ref addAxes. To remove an axis, use \ref removeAxis. - + The axis rect layerable itself only draws a background pixmap or color, if specified (\ref setBackground). It is placed on the "background" layer initially (see \ref QCPLayer for an explanation of the QCustomPlot layer system). The axes that are held by the axis rect can be placed on other layers, independently of the axis rect. - + Every axis rect has a child layout of type \ref QCPLayoutInset. It is accessible via \ref insetLayout and can be used to have other layout elements (or even other layouts with multiple elements) hovering inside the axis rect. - + If an axis rect is clicked and dragged, it processes this by moving certain axis ranges. The behaviour can be controlled with \ref setRangeDrag and \ref setRangeDragAxes. If the mouse wheel is scrolled while the cursor is on the axis rect, certain axes are scaled. This is controllable via \ref setRangeZoom, \ref setRangeZoomAxes and \ref setRangeZoomFactor. These interactions are only enabled if \ref QCustomPlot::setInteractions contains \ref QCP::iRangeDrag and \ref QCP::iRangeZoom. - + \image html AxisRectSpacingOverview.png
Overview of the spacings and paddings that define the geometry of an axis. The dashed line on the far left indicates the viewport/widget border.
@@ -11638,81 +11605,81 @@ void QCPColorGradient::updateColorBuffer() /* start documentation of inline functions */ /*! \fn QCPLayoutInset *QCPAxisRect::insetLayout() const - + Returns the inset layout of this axis rect. It can be used to place other layout elements (or even layouts with multiple other elements) inside/on top of an axis rect. - + \see QCPLayoutInset */ /*! \fn int QCPAxisRect::left() const - + Returns the pixel position of the left border of this axis rect. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn int QCPAxisRect::right() const - + Returns the pixel position of the right border of this axis rect. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn int QCPAxisRect::top() const - + Returns the pixel position of the top border of this axis rect. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn int QCPAxisRect::bottom() const - + Returns the pixel position of the bottom border of this axis rect. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn int QCPAxisRect::width() const - + Returns the pixel width of this axis rect. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn int QCPAxisRect::height() const - + Returns the pixel height of this axis rect. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn QSize QCPAxisRect::size() const - + Returns the pixel size of this axis rect. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn QPoint QCPAxisRect::topLeft() const - + Returns the top left corner of this axis rect in pixels. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn QPoint QCPAxisRect::topRight() const - + Returns the top right corner of this axis rect in pixels. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn QPoint QCPAxisRect::bottomLeft() const - + Returns the bottom left corner of this axis rect in pixels. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn QPoint QCPAxisRect::bottomRight() const - + Returns the bottom right corner of this axis rect in pixels. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn QPoint QCPAxisRect::center() const - + Returns the center of this axis rect in pixels. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ @@ -11724,123 +11691,124 @@ void QCPColorGradient::updateColorBuffer() sides, the top and right axes are set invisible initially. */ QCPAxisRect::QCPAxisRect(QCustomPlot *parentPlot, bool setupDefaultAxes) : - QCPLayoutElement(parentPlot), - mBackgroundBrush(Qt::NoBrush), - mBackgroundScaled(true), - mBackgroundScaledMode(Qt::KeepAspectRatioByExpanding), - mInsetLayout(new QCPLayoutInset), - mRangeDrag(Qt::Horizontal|Qt::Vertical), - mRangeZoom(Qt::Horizontal|Qt::Vertical), - mRangeZoomFactorHorz(0.85), - mRangeZoomFactorVert(0.85), - mDragging(false) + QCPLayoutElement(parentPlot), + mBackgroundBrush(Qt::NoBrush), + mBackgroundScaled(true), + mBackgroundScaledMode(Qt::KeepAspectRatioByExpanding), + mInsetLayout(new QCPLayoutInset), + mRangeDrag(Qt::Horizontal | Qt::Vertical), + mRangeZoom(Qt::Horizontal | Qt::Vertical), + mRangeZoomFactorHorz(0.85), + mRangeZoomFactorVert(0.85), + mDragging(false) { - mInsetLayout->initializeParentPlot(mParentPlot); - mInsetLayout->setParentLayerable(this); - mInsetLayout->setParent(this); - - setMinimumSize(50, 50); - setMinimumMargins(QMargins(15, 15, 15, 15)); - mAxes.insert(QCPAxis::atLeft, QList()); - mAxes.insert(QCPAxis::atRight, QList()); - mAxes.insert(QCPAxis::atTop, QList()); - mAxes.insert(QCPAxis::atBottom, QList()); - - if (setupDefaultAxes) - { - QCPAxis *xAxis = addAxis(QCPAxis::atBottom); - QCPAxis *yAxis = addAxis(QCPAxis::atLeft); - QCPAxis *xAxis2 = addAxis(QCPAxis::atTop); - QCPAxis *yAxis2 = addAxis(QCPAxis::atRight); - setRangeDragAxes(xAxis, yAxis); - setRangeZoomAxes(xAxis, yAxis); - xAxis2->setVisible(false); - yAxis2->setVisible(false); - xAxis->grid()->setVisible(true); - yAxis->grid()->setVisible(true); - xAxis2->grid()->setVisible(false); - yAxis2->grid()->setVisible(false); - xAxis2->grid()->setZeroLinePen(Qt::NoPen); - yAxis2->grid()->setZeroLinePen(Qt::NoPen); - xAxis2->grid()->setVisible(false); - yAxis2->grid()->setVisible(false); - } + mInsetLayout->initializeParentPlot(mParentPlot); + mInsetLayout->setParentLayerable(this); + mInsetLayout->setParent(this); + + setMinimumSize(50, 50); + setMinimumMargins(QMargins(15, 15, 15, 15)); + mAxes.insert(QCPAxis::atLeft, QList()); + mAxes.insert(QCPAxis::atRight, QList()); + mAxes.insert(QCPAxis::atTop, QList()); + mAxes.insert(QCPAxis::atBottom, QList()); + + if (setupDefaultAxes) { + QCPAxis *xAxis = addAxis(QCPAxis::atBottom); + QCPAxis *yAxis = addAxis(QCPAxis::atLeft); + QCPAxis *xAxis2 = addAxis(QCPAxis::atTop); + QCPAxis *yAxis2 = addAxis(QCPAxis::atRight); + setRangeDragAxes(xAxis, yAxis); + setRangeZoomAxes(xAxis, yAxis); + xAxis2->setVisible(false); + yAxis2->setVisible(false); + xAxis->grid()->setVisible(true); + yAxis->grid()->setVisible(true); + xAxis2->grid()->setVisible(false); + yAxis2->grid()->setVisible(false); + xAxis2->grid()->setZeroLinePen(Qt::NoPen); + yAxis2->grid()->setZeroLinePen(Qt::NoPen); + xAxis2->grid()->setVisible(false); + yAxis2->grid()->setVisible(false); + } } QCPAxisRect::~QCPAxisRect() { - delete mInsetLayout; - mInsetLayout = 0; - - QList axesList = axes(); - for (int i=0; i axesList = axes(); + for (int i = 0; i < axesList.size(); ++i) { + removeAxis(axesList.at(i)); + } } /*! Returns the number of axes on the axis rect side specified with \a type. - + \see axis */ int QCPAxisRect::axisCount(QCPAxis::AxisType type) const { - return mAxes.value(type).size(); + return mAxes.value(type).size(); } /*! Returns the axis with the given \a index on the axis rect side specified with \a type. - + \see axisCount, axes */ QCPAxis *QCPAxisRect::axis(QCPAxis::AxisType type, int index) const { - QList ax(mAxes.value(type)); - if (index >= 0 && index < ax.size()) - { - return ax.at(index); - } else - { - qDebug() << Q_FUNC_INFO << "Axis index out of bounds:" << index; - return 0; - } + QList ax(mAxes.value(type)); + if (index >= 0 && index < ax.size()) { + return ax.at(index); + } else { + qDebug() << Q_FUNC_INFO << "Axis index out of bounds:" << index; + return 0; + } } /*! Returns all axes on the axis rect sides specified with \a types. - + \a types may be a single \ref QCPAxis::AxisType or an or-combination, to get the axes of multiple sides. - + \see axis */ -QList QCPAxisRect::axes(QCPAxis::AxisTypes types) const +QList QCPAxisRect::axes(QCPAxis::AxisTypes types) const { - QList result; - if (types.testFlag(QCPAxis::atLeft)) - result << mAxes.value(QCPAxis::atLeft); - if (types.testFlag(QCPAxis::atRight)) - result << mAxes.value(QCPAxis::atRight); - if (types.testFlag(QCPAxis::atTop)) - result << mAxes.value(QCPAxis::atTop); - if (types.testFlag(QCPAxis::atBottom)) - result << mAxes.value(QCPAxis::atBottom); - return result; + QList result; + if (types.testFlag(QCPAxis::atLeft)) { + result << mAxes.value(QCPAxis::atLeft); + } + if (types.testFlag(QCPAxis::atRight)) { + result << mAxes.value(QCPAxis::atRight); + } + if (types.testFlag(QCPAxis::atTop)) { + result << mAxes.value(QCPAxis::atTop); + } + if (types.testFlag(QCPAxis::atBottom)) { + result << mAxes.value(QCPAxis::atBottom); + } + return result; } /*! \overload - + Returns all axes of this axis rect. */ -QList QCPAxisRect::axes() const +QList QCPAxisRect::axes() const { - QList result; - QHashIterator > it(mAxes); - while (it.hasNext()) - { - it.next(); - result << it.value(); - } - return result; + QList result; + QHashIterator > it(mAxes); + while (it.hasNext()) { + it.next(); + result << it.value(); + } + return result; } /*! @@ -11852,104 +11820,101 @@ QList QCPAxisRect::axes() const 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) { - QCPAxis *newAxis = axis; - if (!newAxis) - { - newAxis = new QCPAxis(this, type); - } else // user provided existing axis instance, do some sanity checks - { - if (newAxis->axisType() != type) - { - qDebug() << Q_FUNC_INFO << "passed axis has different axis type than specified in type parameter"; - return 0; + QCPAxis *newAxis = axis; + if (!newAxis) { + newAxis = new QCPAxis(this, type); + } else { // user provided existing axis instance, do some sanity checks + if (newAxis->axisType() != type) { + qDebug() << Q_FUNC_INFO << "passed axis has different axis type than specified in type parameter"; + return 0; + } + if (newAxis->axisRect() != this) { + qDebug() << Q_FUNC_INFO << "passed axis doesn't have this axis rect as parent axis rect"; + return 0; + } + if (axes().contains(newAxis)) { + qDebug() << Q_FUNC_INFO << "passed axis is already owned by this axis rect"; + return 0; + } } - if (newAxis->axisRect() != this) - { - qDebug() << Q_FUNC_INFO << "passed axis doesn't have this axis rect as parent axis rect"; - return 0; + if (mAxes[type].size() > 0) { // multiple axes on one side, add half-bar axis ending to additional axes with offset + bool invert = (type == QCPAxis::atRight) || (type == QCPAxis::atBottom); + newAxis->setLowerEnding(QCPLineEnding(QCPLineEnding::esHalfBar, 6, 10, !invert)); + newAxis->setUpperEnding(QCPLineEnding(QCPLineEnding::esHalfBar, 6, 10, invert)); } - if (axes().contains(newAxis)) - { - qDebug() << Q_FUNC_INFO << "passed axis is already owned by this axis rect"; - return 0; - } - } - if (mAxes[type].size() > 0) // multiple axes on one side, add half-bar axis ending to additional axes with offset - { - bool invert = (type == QCPAxis::atRight) || (type == QCPAxis::atBottom); - newAxis->setLowerEnding(QCPLineEnding(QCPLineEnding::esHalfBar, 6, 10, !invert)); - newAxis->setUpperEnding(QCPLineEnding(QCPLineEnding::esHalfBar, 6, 10, invert)); - } - mAxes[type].append(newAxis); - return newAxis; + mAxes[type].append(newAxis); + return newAxis; } /*! Adds a new axis with \ref addAxis to each axis rect side specified in \a types. This may be an or-combination of QCPAxis::AxisType, so axes can be added to multiple sides at once. - + Returns a list of the added axes. - + \see addAxis, setupFullAxesBox */ -QList QCPAxisRect::addAxes(QCPAxis::AxisTypes types) +QList QCPAxisRect::addAxes(QCPAxis::AxisTypes types) { - QList result; - if (types.testFlag(QCPAxis::atLeft)) - result << addAxis(QCPAxis::atLeft); - if (types.testFlag(QCPAxis::atRight)) - result << addAxis(QCPAxis::atRight); - if (types.testFlag(QCPAxis::atTop)) - result << addAxis(QCPAxis::atTop); - if (types.testFlag(QCPAxis::atBottom)) - result << addAxis(QCPAxis::atBottom); - return result; + QList result; + if (types.testFlag(QCPAxis::atLeft)) { + result << addAxis(QCPAxis::atLeft); + } + if (types.testFlag(QCPAxis::atRight)) { + result << addAxis(QCPAxis::atRight); + } + if (types.testFlag(QCPAxis::atTop)) { + result << addAxis(QCPAxis::atTop); + } + if (types.testFlag(QCPAxis::atBottom)) { + result << addAxis(QCPAxis::atBottom); + } + return result; } /*! Removes the specified \a axis from the axis rect and deletes it. - + Returns true on success, i.e. if \a axis was a valid axis in this axis rect. - + \see addAxis */ bool QCPAxisRect::removeAxis(QCPAxis *axis) { - // don't access axis->axisType() to provide safety when axis is an invalid pointer, rather go through all axis containers: - QHashIterator > it(mAxes); - while (it.hasNext()) - { - it.next(); - if (it.value().contains(axis)) - { - mAxes[it.key()].removeOne(axis); - if (qobject_cast(parentPlot())) // make sure this isn't called from QObject dtor when QCustomPlot is already destructed (happens when the axis rect is not in any layout and thus QObject-child of QCustomPlot) - parentPlot()->axisRemoved(axis); - delete axis; - return true; + // don't access axis->axisType() to provide safety when axis is an invalid pointer, rather go through all axis containers: + QHashIterator > it(mAxes); + while (it.hasNext()) { + it.next(); + if (it.value().contains(axis)) { + mAxes[it.key()].removeOne(axis); + if (qobject_cast(parentPlot())) { // make sure this isn't called from QObject dtor when QCustomPlot is already destructed (happens when the axis rect is not in any layout and thus QObject-child of QCustomPlot) + parentPlot()->axisRemoved(axis); + } + delete axis; + return true; + } } - } - qDebug() << Q_FUNC_INFO << "Axis isn't in axis rect:" << reinterpret_cast(axis); - return false; + qDebug() << Q_FUNC_INFO << "Axis isn't in axis rect:" << reinterpret_cast(axis); + return false; } /*! 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) @@ -11965,7 +11930,7 @@ bool QCPAxisRect::removeAxis(QCPAxis *axis) \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. If \a connectRanges is true, the \ref QCPAxis::rangeChanged "rangeChanged" signals of the bottom @@ -11973,206 +11938,204 @@ bool QCPAxisRect::removeAxis(QCPAxis *axis) */ void QCPAxisRect::setupFullAxesBox(bool connectRanges) { - QCPAxis *xAxis, *yAxis, *xAxis2, *yAxis2; - if (axisCount(QCPAxis::atBottom) == 0) - xAxis = addAxis(QCPAxis::atBottom); - else - xAxis = axis(QCPAxis::atBottom); - - if (axisCount(QCPAxis::atLeft) == 0) - yAxis = addAxis(QCPAxis::atLeft); - else - yAxis = axis(QCPAxis::atLeft); - - if (axisCount(QCPAxis::atTop) == 0) - xAxis2 = addAxis(QCPAxis::atTop); - else - xAxis2 = axis(QCPAxis::atTop); - - if (axisCount(QCPAxis::atRight) == 0) - yAxis2 = addAxis(QCPAxis::atRight); - else - yAxis2 = axis(QCPAxis::atRight); - - xAxis->setVisible(true); - yAxis->setVisible(true); - xAxis2->setVisible(true); - yAxis2->setVisible(true); - xAxis2->setTickLabels(false); - yAxis2->setTickLabels(false); - - 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()); + QCPAxis *xAxis, *yAxis, *xAxis2, *yAxis2; + if (axisCount(QCPAxis::atBottom) == 0) { + xAxis = addAxis(QCPAxis::atBottom); + } else { + xAxis = axis(QCPAxis::atBottom); + } - 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()); - - if (connectRanges) - { - connect(xAxis, SIGNAL(rangeChanged(QCPRange)), xAxis2, SLOT(setRange(QCPRange))); - connect(yAxis, SIGNAL(rangeChanged(QCPRange)), yAxis2, SLOT(setRange(QCPRange))); - } + if (axisCount(QCPAxis::atLeft) == 0) { + yAxis = addAxis(QCPAxis::atLeft); + } else { + yAxis = axis(QCPAxis::atLeft); + } + + if (axisCount(QCPAxis::atTop) == 0) { + xAxis2 = addAxis(QCPAxis::atTop); + } else { + xAxis2 = axis(QCPAxis::atTop); + } + + if (axisCount(QCPAxis::atRight) == 0) { + yAxis2 = addAxis(QCPAxis::atRight); + } else { + yAxis2 = axis(QCPAxis::atRight); + } + + xAxis->setVisible(true); + yAxis->setVisible(true); + xAxis2->setVisible(true); + yAxis2->setVisible(true); + xAxis2->setTickLabels(false); + yAxis2->setTickLabels(false); + + 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()); + + 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()); + + if (connectRanges) { + connect(xAxis, SIGNAL(rangeChanged(QCPRange)), xAxis2, SLOT(setRange(QCPRange))); + connect(yAxis, SIGNAL(rangeChanged(QCPRange)), yAxis2, SLOT(setRange(QCPRange))); + } } /*! Returns a list of all the plottables that are associated with this axis rect. - + A plottable is considered associated with an axis rect if its key or value axis (or both) is in this axis rect. - + \see graphs, items */ -QList QCPAxisRect::plottables() const +QList QCPAxisRect::plottables() const { - // Note: don't append all QCPAxis::plottables() into a list, because we might get duplicate entries - QList result; - for (int i=0; imPlottables.size(); ++i) - { - if (mParentPlot->mPlottables.at(i)->keyAxis()->axisRect() == this ||mParentPlot->mPlottables.at(i)->valueAxis()->axisRect() == this) - result.append(mParentPlot->mPlottables.at(i)); - } - return result; + // Note: don't append all QCPAxis::plottables() into a list, because we might get duplicate entries + QList result; + for (int i = 0; i < mParentPlot->mPlottables.size(); ++i) { + if (mParentPlot->mPlottables.at(i)->keyAxis()->axisRect() == this || mParentPlot->mPlottables.at(i)->valueAxis()->axisRect() == this) { + result.append(mParentPlot->mPlottables.at(i)); + } + } + return result; } /*! Returns a list of all the graphs that are associated with this axis rect. - + A graph is considered associated with an axis rect if its key or value axis (or both) is in this axis rect. - + \see plottables, items */ -QList QCPAxisRect::graphs() const +QList QCPAxisRect::graphs() const { - // Note: don't append all QCPAxis::graphs() into a list, because we might get duplicate entries - QList result; - for (int i=0; imGraphs.size(); ++i) - { - if (mParentPlot->mGraphs.at(i)->keyAxis()->axisRect() == this || mParentPlot->mGraphs.at(i)->valueAxis()->axisRect() == this) - result.append(mParentPlot->mGraphs.at(i)); - } - return result; + // Note: don't append all QCPAxis::graphs() into a list, because we might get duplicate entries + QList result; + for (int i = 0; i < mParentPlot->mGraphs.size(); ++i) { + if (mParentPlot->mGraphs.at(i)->keyAxis()->axisRect() == this || mParentPlot->mGraphs.at(i)->valueAxis()->axisRect() == this) { + result.append(mParentPlot->mGraphs.at(i)); + } + } + return result; } /*! Returns a list of all the items that are associated with this axis rect. - + An item is considered associated with an axis rect if any of its positions has key or value axis set to an axis that is in this axis rect, or if any of its positions has \ref QCPItemPosition::setAxisRect set to the axis rect, or if the clip axis rect (\ref QCPAbstractItem::setClipAxisRect) is set to this axis rect. - + \see plottables, graphs */ QList QCPAxisRect::items() const { - // Note: don't just append all QCPAxis::items() into a list, because we might get duplicate entries - // and miss those items that have this axis rect as clipAxisRect. - QList result; - for (int itemId=0; itemIdmItems.size(); ++itemId) - { - if (mParentPlot->mItems.at(itemId)->clipAxisRect() == this) - { - result.append(mParentPlot->mItems.at(itemId)); - continue; + // Note: don't just append all QCPAxis::items() into a list, because we might get duplicate entries + // and miss those items that have this axis rect as clipAxisRect. + QList result; + for (int itemId = 0; itemId < mParentPlot->mItems.size(); ++itemId) { + if (mParentPlot->mItems.at(itemId)->clipAxisRect() == this) { + result.append(mParentPlot->mItems.at(itemId)); + continue; + } + QList positions = mParentPlot->mItems.at(itemId)->positions(); + for (int posId = 0; posId < positions.size(); ++posId) { + if (positions.at(posId)->axisRect() == this || + positions.at(posId)->keyAxis()->axisRect() == this || + positions.at(posId)->valueAxis()->axisRect() == this) { + result.append(mParentPlot->mItems.at(itemId)); + break; + } + } } - QList positions = mParentPlot->mItems.at(itemId)->positions(); - for (int posId=0; posIdaxisRect() == this || - positions.at(posId)->keyAxis()->axisRect() == this || - positions.at(posId)->valueAxis()->axisRect() == this) - { - result.append(mParentPlot->mItems.at(itemId)); - break; - } - } - } - return result; + return result; } /*! This method is called automatically upon replot and doesn't need to be called by users of QCPAxisRect. - + 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. */ void QCPAxisRect::update(UpdatePhase phase) { - QCPLayoutElement::update(phase); - - switch (phase) - { - case upPreparation: - { - QList allAxes = axes(); - for (int i=0; isetupTickVectors(); - break; + QCPLayoutElement::update(phase); + + switch (phase) { + case upPreparation: { + QList allAxes = axes(); + for (int i = 0; i < allAxes.size(); ++i) { + allAxes.at(i)->setupTickVectors(); + } + break; + } + case upLayout: { + mInsetLayout->setOuterRect(rect()); + break; + } + default: + break; } - case upLayout: - { - mInsetLayout->setOuterRect(rect()); - break; - } - default: break; - } - - // pass update call on to inset layout (doesn't happen automatically, because QCPAxisRect doesn't derive from QCPLayout): - mInsetLayout->update(phase); + + // pass update call on to inset layout (doesn't happen automatically, because QCPAxisRect doesn't derive from QCPLayout): + mInsetLayout->update(phase); } /* inherits documentation from base class */ -QList QCPAxisRect::elements(bool recursive) const +QList QCPAxisRect::elements(bool recursive) const { - QList result; - if (mInsetLayout) - { - result << mInsetLayout; - if (recursive) - result << mInsetLayout->elements(recursive); - } - return result; + QList result; + if (mInsetLayout) { + result << mInsetLayout; + if (recursive) { + result << mInsetLayout->elements(recursive); + } + } + return result; } /* inherits documentation from base class */ void QCPAxisRect::applyDefaultAntialiasingHint(QCPPainter *painter) const { - painter->setAntialiasing(false); + painter->setAntialiasing(false); } /* inherits documentation from base class */ void QCPAxisRect::draw(QCPPainter *painter) { - drawBackground(painter); + drawBackground(painter); } /*! @@ -12187,17 +12150,17 @@ void QCPAxisRect::draw(QCPPainter *painter) Below the pixmap, the axis rect may be optionally filled with a brush, if specified with \ref setBackground(const QBrush &brush). - + \see setBackgroundScaled, setBackgroundScaledMode, setBackground(const QBrush &brush) */ void QCPAxisRect::setBackground(const QPixmap &pm) { - mBackgroundPixmap = pm; - mScaledBackgroundPixmap = QPixmap(); + mBackgroundPixmap = pm; + mScaledBackgroundPixmap = QPixmap(); } /*! \overload - + Sets \a brush as the background brush. The axis rect background will be filled with this brush. Since axis rects place themselves on the "background" layer by default, the axis rect backgrounds are usually drawn below everything else. @@ -12206,16 +12169,16 @@ void QCPAxisRect::setBackground(const QPixmap &pm) setBackground(const QPixmap &pm). To disable drawing of a background brush, set \a brush to Qt::NoBrush. - + \see setBackground(const QPixmap &pm) */ void QCPAxisRect::setBackground(const QBrush &brush) { - mBackgroundBrush = brush; + mBackgroundBrush = brush; } /*! \overload - + Allows setting the background pixmap of the axis rect, whether it shall be scaled and how it shall be scaled in one call. @@ -12223,25 +12186,25 @@ void QCPAxisRect::setBackground(const QBrush &brush) */ void QCPAxisRect::setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode) { - mBackgroundPixmap = pm; - mScaledBackgroundPixmap = QPixmap(); - mBackgroundScaled = scaled; - mBackgroundScaledMode = mode; + mBackgroundPixmap = pm; + mScaledBackgroundPixmap = QPixmap(); + mBackgroundScaled = scaled; + mBackgroundScaledMode = mode; } /*! Sets whether the axis background pixmap shall be scaled to fit the axis rect or not. If \a scaled is set to true, you may control whether and how the aspect ratio of the original pixmap is preserved with \ref setBackgroundScaledMode. - + Note that the scaled version of the original pixmap is buffered, so there is no performance penalty on replots. (Except when the axis rect dimensions are changed continuously.) - + \see setBackground, setBackgroundScaledMode */ void QCPAxisRect::setBackgroundScaled(bool scaled) { - mBackgroundScaled = scaled; + mBackgroundScaled = scaled; } /*! @@ -12251,37 +12214,37 @@ void QCPAxisRect::setBackgroundScaled(bool scaled) */ void QCPAxisRect::setBackgroundScaledMode(Qt::AspectRatioMode mode) { - mBackgroundScaledMode = mode; + mBackgroundScaledMode = mode; } /*! Returns the range drag axis of the \a orientation provided. - + \see setRangeDragAxes */ QCPAxis *QCPAxisRect::rangeDragAxis(Qt::Orientation orientation) { - return (orientation == Qt::Horizontal ? mRangeDragHorzAxis.data() : mRangeDragVertAxis.data()); + return (orientation == Qt::Horizontal ? mRangeDragHorzAxis.data() : mRangeDragVertAxis.data()); } /*! Returns the range zoom axis of the \a orientation provided. - + \see setRangeZoomAxes */ QCPAxis *QCPAxisRect::rangeZoomAxis(Qt::Orientation orientation) { - return (orientation == Qt::Horizontal ? mRangeZoomHorzAxis.data() : mRangeZoomVertAxis.data()); + return (orientation == Qt::Horizontal ? mRangeZoomHorzAxis.data() : mRangeZoomVertAxis.data()); } /*! Returns the range zoom factor of the \a orientation provided. - + \see setRangeZoomFactor */ double QCPAxisRect::rangeZoomFactor(Qt::Orientation orientation) { - return (orientation == Qt::Horizontal ? mRangeZoomFactorHorz : mRangeZoomFactorVert); + return (orientation == Qt::Horizontal ? mRangeZoomFactorHorz : mRangeZoomFactorVert); } /*! @@ -12290,19 +12253,19 @@ double QCPAxisRect::rangeZoomFactor(Qt::Orientation orientation) \ref setRangeDragAxes(QCPAxis *horizontal, QCPAxis *vertical). By default, the horizontal axis is the bottom axis (xAxis) and the vertical axis is the left axis (yAxis). - + To disable range dragging entirely, pass 0 as \a orientations or remove \ref QCP::iRangeDrag from \ref QCustomPlot::setInteractions. To enable range dragging for both directions, pass Qt::Horizontal | Qt::Vertical as \a orientations. - + In addition to setting \a orientations to a non-zero value, make sure \ref QCustomPlot::setInteractions contains \ref QCP::iRangeDrag to enable the range dragging interaction. - + \see setRangeZoom, setRangeDragAxes, QCustomPlot::setNoAntialiasingOnDrag */ void QCPAxisRect::setRangeDrag(Qt::Orientations orientations) { - mRangeDrag = orientations; + mRangeDrag = orientations; } /*! @@ -12314,40 +12277,40 @@ void QCPAxisRect::setRangeDrag(Qt::Orientations orientations) To disable range zooming entirely, pass 0 as \a orientations or remove \ref QCP::iRangeZoom from \ref QCustomPlot::setInteractions. To enable range zooming for both directions, pass Qt::Horizontal | Qt::Vertical as \a orientations. - + In addition to setting \a orientations to a non-zero value, make sure \ref QCustomPlot::setInteractions contains \ref QCP::iRangeZoom to enable the range zooming interaction. - + \see setRangeZoomFactor, setRangeZoomAxes, setRangeDrag */ void QCPAxisRect::setRangeZoom(Qt::Orientations orientations) { - mRangeZoom = orientations; + mRangeZoom = orientations; } /*! Sets the axes whose range will be dragged when \ref setRangeDrag enables mouse range dragging on the QCustomPlot widget. - + \see setRangeZoomAxes */ void QCPAxisRect::setRangeDragAxes(QCPAxis *horizontal, QCPAxis *vertical) { - mRangeDragHorzAxis = horizontal; - mRangeDragVertAxis = vertical; + mRangeDragHorzAxis = horizontal; + mRangeDragVertAxis = vertical; } /*! 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). - + \see setRangeDragAxes */ void QCPAxisRect::setRangeZoomAxes(QCPAxis *horizontal, QCPAxis *vertical) { - mRangeZoomHorzAxis = horizontal; - mRangeZoomVertAxis = vertical; + mRangeZoomHorzAxis = horizontal; + mRangeZoomVertAxis = vertical; } /*! @@ -12362,28 +12325,28 @@ void QCPAxisRect::setRangeZoomAxes(QCPAxis *horizontal, QCPAxis *vertical) */ void QCPAxisRect::setRangeZoomFactor(double horizontalFactor, double verticalFactor) { - mRangeZoomFactorHorz = horizontalFactor; - mRangeZoomFactorVert = verticalFactor; + mRangeZoomFactorHorz = horizontalFactor; + mRangeZoomFactorVert = verticalFactor; } /*! \overload - + Sets both the horizontal and vertical zoom \a factor. */ void QCPAxisRect::setRangeZoomFactor(double factor) { - mRangeZoomFactorHorz = factor; - mRangeZoomFactorVert = factor; + mRangeZoomFactorHorz = factor; + mRangeZoomFactorVert = factor; } /*! \internal - + Draws the background of this axis rect. It may consist of a background fill (a QBrush) and a pixmap. - + If a brush was given via \ref setBackground(const QBrush &brush), this function first draws an according filling inside the axis rect with the provided \a painter. - + Then, if a pixmap was provided via \ref setBackground, this function buffers the scaled version depending on \ref setBackgroundScaled and \ref setBackgroundScaledMode and then draws it inside the axis rect with the provided \a painter. The scaled version is buffered in @@ -12391,184 +12354,174 @@ void QCPAxisRect::setRangeZoomFactor(double factor) 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 set. - + \see setBackground, setBackgroundScaled, setBackgroundScaledMode */ void QCPAxisRect::drawBackground(QCPPainter *painter) { - // draw background fill: - if (mBackgroundBrush != Qt::NoBrush) - painter->fillRect(mRect, mBackgroundBrush); - - // draw background pixmap (on top of fill, if brush specified): - if (!mBackgroundPixmap.isNull()) - { - if (mBackgroundScaled) - { - // check whether mScaledBackground needs to be updated: - QSize scaledSize(mBackgroundPixmap.size()); - scaledSize.scale(mRect.size(), mBackgroundScaledMode); - if (mScaledBackgroundPixmap.size() != scaledSize) - mScaledBackgroundPixmap = mBackgroundPixmap.scaled(mRect.size(), mBackgroundScaledMode, Qt::SmoothTransformation); - painter->drawPixmap(mRect.topLeft()+QPoint(0, -1), mScaledBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height()) & mScaledBackgroundPixmap.rect()); - } else - { - painter->drawPixmap(mRect.topLeft()+QPoint(0, -1), mBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height())); + // draw background fill: + if (mBackgroundBrush != Qt::NoBrush) { + painter->fillRect(mRect, mBackgroundBrush); + } + + // draw background pixmap (on top of fill, if brush specified): + if (!mBackgroundPixmap.isNull()) { + if (mBackgroundScaled) { + // check whether mScaledBackground needs to be updated: + QSize scaledSize(mBackgroundPixmap.size()); + scaledSize.scale(mRect.size(), mBackgroundScaledMode); + if (mScaledBackgroundPixmap.size() != scaledSize) { + mScaledBackgroundPixmap = mBackgroundPixmap.scaled(mRect.size(), mBackgroundScaledMode, Qt::SmoothTransformation); + } + painter->drawPixmap(mRect.topLeft() + QPoint(0, -1), mScaledBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height()) & mScaledBackgroundPixmap.rect()); + } else { + painter->drawPixmap(mRect.topLeft() + QPoint(0, -1), mBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height())); + } } - } } /*! \internal - + This function makes sure multiple axes on the side specified with \a type don't collide, but are distributed according to their respective space requirement (QCPAxis::calculateMargin). - + It does this by setting an appropriate offset (\ref QCPAxis::setOffset) on all axes except the one with index zero. - + This function is called by \ref calculateAutoMargin. */ void QCPAxisRect::updateAxesOffset(QCPAxis::AxisType type) { - const QList axesList = mAxes.value(type); - if (axesList.isEmpty()) - return; - - bool isFirstVisible = !axesList.first()->visible(); // if the first axis is visible, the second axis (which is where the loop starts) isn't the first visible axis, so initialize with false - for (int i=1; ioffset() + axesList.at(i-1)->calculateMargin(); - if (axesList.at(i)->visible()) // only add inner tick length to offset if this axis is visible and it's not the first visible one (might happen if true first axis is invisible) - { - if (!isFirstVisible) - offset += axesList.at(i)->tickLengthIn(); - isFirstVisible = false; + const QList axesList = mAxes.value(type); + if (axesList.isEmpty()) { + return; + } + + bool isFirstVisible = !axesList.first()->visible(); // if the first axis is visible, the second axis (which is where the loop starts) isn't the first visible axis, so initialize with false + for (int i = 1; i < axesList.size(); ++i) { + int offset = axesList.at(i - 1)->offset() + axesList.at(i - 1)->calculateMargin(); + if (axesList.at(i)->visible()) { // only add inner tick length to offset if this axis is visible and it's not the first visible one (might happen if true first axis is invisible) + if (!isFirstVisible) { + offset += axesList.at(i)->tickLengthIn(); + } + isFirstVisible = false; + } + axesList.at(i)->setOffset(offset); } - axesList.at(i)->setOffset(offset); - } } /* inherits documentation from base class */ int QCPAxisRect::calculateAutoMargin(QCP::MarginSide side) { - if (!mAutoMargins.testFlag(side)) - qDebug() << Q_FUNC_INFO << "Called with side that isn't specified as auto margin"; - - updateAxesOffset(QCPAxis::marginSideToAxisType(side)); - - // note: only need to look at the last (outer most) axis to determine the total margin, due to updateAxisOffset call - const QList axesList = mAxes.value(QCPAxis::marginSideToAxisType(side)); - if (axesList.size() > 0) - return axesList.last()->offset() + axesList.last()->calculateMargin(); - else - return 0; + if (!mAutoMargins.testFlag(side)) { + qDebug() << Q_FUNC_INFO << "Called with side that isn't specified as auto margin"; + } + + updateAxesOffset(QCPAxis::marginSideToAxisType(side)); + + // note: only need to look at the last (outer most) axis to determine the total margin, due to updateAxisOffset call + const QList axesList = mAxes.value(QCPAxis::marginSideToAxisType(side)); + if (axesList.size() > 0) { + return axesList.last()->offset() + axesList.last()->calculateMargin(); + } else { + return 0; + } } /*! \internal - + Event handler for when a mouse button is pressed on the axis rect. If the left mouse button is pressed, the range dragging interaction is initialized (the actual range manipulation happens in the \ref mouseMoveEvent). The mDragging flag is set to true and some anchor points are set that are needed to determine the distance the mouse was dragged in the mouse move/release events later. - + \see mouseMoveEvent, mouseReleaseEvent */ void QCPAxisRect::mousePressEvent(QMouseEvent *event) { - 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) - { - mDragging = true; - // initialize antialiasing backup in case we start dragging: - if (mParentPlot->noAntialiasingOnDrag()) - { - mAADragBackup = mParentPlot->antialiasedElements(); - mNotAADragBackup = mParentPlot->notAntialiasedElements(); + 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) { + mDragging = true; + // initialize antialiasing backup in case we start dragging: + if (mParentPlot->noAntialiasingOnDrag()) { + mAADragBackup = mParentPlot->antialiasedElements(); + mNotAADragBackup = mParentPlot->notAntialiasedElements(); + } + // Mouse range dragging interaction: + if (mParentPlot->interactions().testFlag(QCP::iRangeDrag)) { + if (mRangeDragHorzAxis) { + mDragStartHorzRange = mRangeDragHorzAxis.data()->range(); + } + if (mRangeDragVertAxis) { + mDragStartVertRange = mRangeDragVertAxis.data()->range(); + } + } } - // Mouse range dragging interaction: - if (mParentPlot->interactions().testFlag(QCP::iRangeDrag)) - { - if (mRangeDragHorzAxis) - mDragStartHorzRange = mRangeDragHorzAxis.data()->range(); - if (mRangeDragVertAxis) - mDragStartVertRange = mRangeDragVertAxis.data()->range(); - } - } } /*! \internal - + Event handler for when the mouse is moved on the axis rect. If range dragging was activated in a preceding \ref mousePressEvent, the range is moved accordingly. - + \see mousePressEvent, mouseReleaseEvent */ void QCPAxisRect::mouseMoveEvent(QMouseEvent *event) { - // Mouse range dragging interaction: - if (mDragging && mParentPlot->interactions().testFlag(QCP::iRangeDrag)) - { - if (mRangeDrag.testFlag(Qt::Horizontal)) - { - if (QCPAxis *rangeDragHorzAxis = mRangeDragHorzAxis.data()) - { - if (rangeDragHorzAxis->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 = rangeDragHorzAxis->pixelToCoord(mDragStart.x()) / rangeDragHorzAxis->pixelToCoord(event->pos().x()); - rangeDragHorzAxis->setRange(mDragStartHorzRange.lower*diff, mDragStartHorzRange.upper*diff); + // Mouse range dragging interaction: + if (mDragging && mParentPlot->interactions().testFlag(QCP::iRangeDrag)) { + if (mRangeDrag.testFlag(Qt::Horizontal)) { + if (QCPAxis *rangeDragHorzAxis = mRangeDragHorzAxis.data()) { + if (rangeDragHorzAxis->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 = rangeDragHorzAxis->pixelToCoord(mDragStart.x()) / rangeDragHorzAxis->pixelToCoord(event->pos().x()); + rangeDragHorzAxis->setRange(mDragStartHorzRange.lower * diff, mDragStartHorzRange.upper * diff); + } + } } - } - } - if (mRangeDrag.testFlag(Qt::Vertical)) - { - if (QCPAxis *rangeDragVertAxis = mRangeDragVertAxis.data()) - { - if (rangeDragVertAxis->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 = rangeDragVertAxis->pixelToCoord(mDragStart.y()) / rangeDragVertAxis->pixelToCoord(event->pos().y()); - rangeDragVertAxis->setRange(mDragStartVertRange.lower*diff, mDragStartVertRange.upper*diff); + if (mRangeDrag.testFlag(Qt::Vertical)) { + if (QCPAxis *rangeDragVertAxis = mRangeDragVertAxis.data()) { + if (rangeDragVertAxis->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 = rangeDragVertAxis->pixelToCoord(mDragStart.y()) / rangeDragVertAxis->pixelToCoord(event->pos().y()); + rangeDragVertAxis->setRange(mDragStartVertRange.lower * diff, mDragStartVertRange.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(); } - } } - 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) { - Q_UNUSED(event) - mDragging = false; - if (mParentPlot->noAntialiasingOnDrag()) - { - mParentPlot->setAntialiasedElements(mAADragBackup); - mParentPlot->setNotAntialiasedElements(mNotAADragBackup); - } + Q_UNUSED(event) + mDragging = false; + if (mParentPlot->noAntialiasingOnDrag()) { + mParentPlot->setAntialiasedElements(mAADragBackup); + mParentPlot->setNotAntialiasedElements(mNotAADragBackup); + } } /*! \internal - + 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 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 wheel is turned rapidly, many steps may bunch up to one event, so the event->delta() may then be multiples of 120. This is taken into account here, by calculating \a wheelSteps and using it as @@ -12577,28 +12530,26 @@ void QCPAxisRect::mouseReleaseEvent(QMouseEvent *event) */ void QCPAxisRect::wheelEvent(QWheelEvent *event) { - // Mouse range zooming interaction: - if (mParentPlot->interactions().testFlag(QCP::iRangeZoom)) - { - if (mRangeZoom != 0) - { - double factor; - double wheelSteps = event->delta()/120.0; // a single step delta is +/-120 usually - if (mRangeZoom.testFlag(Qt::Horizontal)) - { - factor = qPow(mRangeZoomFactorHorz, wheelSteps); - if (mRangeZoomHorzAxis.data()) - mRangeZoomHorzAxis.data()->scaleRange(factor, mRangeZoomHorzAxis.data()->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())); - } - mParentPlot->replot(); + // Mouse range zooming interaction: + if (mParentPlot->interactions().testFlag(QCP::iRangeZoom)) { + if (mRangeZoom != 0) { + double factor; + double wheelSteps = event->delta() / 120.0; // a single step delta is +/-120 usually + if (mRangeZoom.testFlag(Qt::Horizontal)) { + factor = qPow(mRangeZoomFactorHorz, wheelSteps); + if (mRangeZoomHorzAxis.data()) { + mRangeZoomHorzAxis.data()->scaleRange(factor, mRangeZoomHorzAxis.data()->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())); + } + } + mParentPlot->replot(); + } } - } } @@ -12608,16 +12559,16 @@ void QCPAxisRect::wheelEvent(QWheelEvent *event) /*! \class QCPAbstractLegendItem \brief The abstract base class for all entries in a QCPLegend. - + It defines a very basic interface for entries in a QCPLegend. For representing plottables in the legend, the subclass \ref QCPPlottableLegendItem is more suitable. - + Only derive directly from this class when you need absolute freedom (e.g. a custom legend entry that's not even associated with a plottable). You must implement the following pure virtual functions: \li \ref draw (from QCPLayerable) - + You inherit the following members you may use: @@ -12633,7 +12584,7 @@ void QCPAxisRect::wheelEvent(QWheelEvent *event) /* start of documentation of signals */ /*! \fn void QCPAbstractLegendItem::selectionChanged(bool selected) - + This signal is emitted when the selection state of this legend item has changed, either by user interaction or by a direct call to \ref setSelected. */ @@ -12645,142 +12596,144 @@ void QCPAxisRect::wheelEvent(QWheelEvent *event) cause the item to be added to \a parent, so \ref QCPLegend::addItem must be called separately. */ QCPAbstractLegendItem::QCPAbstractLegendItem(QCPLegend *parent) : - QCPLayoutElement(parent->parentPlot()), - mParentLegend(parent), - mFont(parent->font()), - mTextColor(parent->textColor()), - mSelectedFont(parent->selectedFont()), - mSelectedTextColor(parent->selectedTextColor()), - mSelectable(true), - mSelected(false) + QCPLayoutElement(parent->parentPlot()), + mParentLegend(parent), + mFont(parent->font()), + mTextColor(parent->textColor()), + mSelectedFont(parent->selectedFont()), + mSelectedTextColor(parent->selectedTextColor()), + mSelectable(true), + mSelected(false) { - setLayer(QLatin1String("legend")); - setMargins(QMargins(8, 2, 8, 2)); + setLayer(QLatin1String("legend")); + setMargins(QMargins(8, 2, 8, 2)); } /*! Sets the default font of this specific legend item to \a font. - + \see setTextColor, QCPLegend::setFont */ void QCPAbstractLegendItem::setFont(const QFont &font) { - mFont = font; + mFont = font; } /*! Sets the default text color of this specific legend item to \a color. - + \see setFont, QCPLegend::setTextColor */ void QCPAbstractLegendItem::setTextColor(const QColor &color) { - mTextColor = color; + mTextColor = color; } /*! When this legend item is selected, \a font is used to draw generic text, instead of the normal font set with \ref setFont. - + \see setFont, QCPLegend::setSelectedFont */ void QCPAbstractLegendItem::setSelectedFont(const QFont &font) { - mSelectedFont = font; + mSelectedFont = font; } /*! When this legend item is selected, \a color is used to draw generic text, instead of the normal color set with \ref setTextColor. - + \see setTextColor, QCPLegend::setSelectedTextColor */ void QCPAbstractLegendItem::setSelectedTextColor(const QColor &color) { - mSelectedTextColor = color; + mSelectedTextColor = color; } /*! Sets whether this specific legend item is selectable. - + \see setSelectedParts, QCustomPlot::setInteractions */ void QCPAbstractLegendItem::setSelectable(bool selectable) { - if (mSelectable != selectable) - { - mSelectable = selectable; - emit selectableChanged(mSelectable); - } + if (mSelectable != selectable) { + mSelectable = selectable; + emit selectableChanged(mSelectable); + } } /*! Sets whether this specific legend item is selected. - + It is possible to set the selection state of this item by calling this function directly, even if setSelectable is set to false. - + \see setSelectableParts, QCustomPlot::setInteractions */ void QCPAbstractLegendItem::setSelected(bool selected) { - if (mSelected != selected) - { - mSelected = selected; - emit selectionChanged(mSelected); - } + if (mSelected != selected) { + mSelected = selected; + emit selectionChanged(mSelected); + } } /* inherits documentation from base class */ double QCPAbstractLegendItem::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { - Q_UNUSED(details) - if (!mParentPlot) return -1; - if (onlySelectable && (!mSelectable || !mParentLegend->selectableParts().testFlag(QCPLegend::spItems))) - return -1; - - if (mRect.contains(pos.toPoint())) - return mParentPlot->selectionTolerance()*0.99; - else - return -1; + Q_UNUSED(details) + if (!mParentPlot) { + return -1; + } + if (onlySelectable && (!mSelectable || !mParentLegend->selectableParts().testFlag(QCPLegend::spItems))) { + return -1; + } + + if (mRect.contains(pos.toPoint())) { + return mParentPlot->selectionTolerance() * 0.99; + } else { + return -1; + } } /* inherits documentation from base class */ void QCPAbstractLegendItem::applyDefaultAntialiasingHint(QCPPainter *painter) const { - applyAntialiasingHint(painter, mAntialiased, QCP::aeLegendItems); + applyAntialiasingHint(painter, mAntialiased, QCP::aeLegendItems); } /* inherits documentation from base class */ QRect QCPAbstractLegendItem::clipRect() const { - return mOuterRect; + return mOuterRect; } /* inherits documentation from base class */ void QCPAbstractLegendItem::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) { - Q_UNUSED(event) - Q_UNUSED(details) - if (mSelectable && mParentLegend->selectableParts().testFlag(QCPLegend::spItems)) - { - bool selBefore = mSelected; - setSelected(additive ? !mSelected : true); - if (selectionStateChanged) - *selectionStateChanged = mSelected != selBefore; - } + Q_UNUSED(event) + Q_UNUSED(details) + if (mSelectable && mParentLegend->selectableParts().testFlag(QCPLegend::spItems)) { + bool selBefore = mSelected; + setSelected(additive ? !mSelected : true); + if (selectionStateChanged) { + *selectionStateChanged = mSelected != selBefore; + } + } } /* inherits documentation from base class */ void QCPAbstractLegendItem::deselectEvent(bool *selectionStateChanged) { - if (mSelectable && mParentLegend->selectableParts().testFlag(QCPLegend::spItems)) - { - bool selBefore = mSelected; - setSelected(false); - if (selectionStateChanged) - *selectionStateChanged = mSelected != selBefore; - } + if (mSelectable && mParentLegend->selectableParts().testFlag(QCPLegend::spItems)) { + bool selBefore = mSelected; + setSelected(false); + if (selectionStateChanged) { + *selectionStateChanged = mSelected != selBefore; + } + } } //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -12789,13 +12742,13 @@ void QCPAbstractLegendItem::deselectEvent(bool *selectionStateChanged) /*! \class QCPPlottableLegendItem \brief A legend item representing a plottable with an icon and the plottable name. - + This is the standard legend item for plottables. It displays an icon of the plottable next to the plottable name. The icon is drawn by the respective plottable itself (\ref QCPAbstractPlottable::drawLegendIcon), and tries to give an intuitive symbol for the plottable. For example, the QCPGraph draws a centered horizontal line and/or a single scatter point in the middle. - + Legend items of this type are always associated with one plottable (retrievable via the plottable() function and settable with the constructor). You may change the font of the plottable name with \ref setFont. Icon padding and border pen is taken from the parent QCPLegend, see \ref @@ -12805,7 +12758,7 @@ void QCPAbstractLegendItem::deselectEvent(bool *selectionStateChanged) creates/removes legend items of this type in the default implementation. However, these functions may be reimplemented such that a different kind of legend item (e.g a direct subclass of QCPAbstractLegendItem) is used for that plottable. - + Since QCPLegend is based on QCPLayoutGrid, a legend item itself is just a subclass of QCPLayoutElement. While it could be added to a legend (or any other layout) via the normal layout interface, QCPLegend has specialized functions for handling legend items conveniently, see the @@ -12814,94 +12767,97 @@ void QCPAbstractLegendItem::deselectEvent(bool *selectionStateChanged) /*! Creates a new legend item associated with \a plottable. - + Once it's created, it can be added to the legend via \ref QCPLegend::addItem. - + A more convenient way of adding/removing a plottable to/from the legend is via the functions \ref QCPAbstractPlottable::addToLegend and \ref QCPAbstractPlottable::removeFromLegend. */ QCPPlottableLegendItem::QCPPlottableLegendItem(QCPLegend *parent, QCPAbstractPlottable *plottable) : - QCPAbstractLegendItem(parent), - mPlottable(plottable) + QCPAbstractLegendItem(parent), + mPlottable(plottable) { } /*! \internal - + Returns the pen that shall be used to draw the icon border, taking into account the selection state of this item. */ QPen QCPPlottableLegendItem::getIconBorderPen() const { - return mSelected ? mParentLegend->selectedIconBorderPen() : mParentLegend->iconBorderPen(); + return mSelected ? mParentLegend->selectedIconBorderPen() : mParentLegend->iconBorderPen(); } /*! \internal - + Returns the text color that shall be used to draw text, taking into account the selection state of this item. */ QColor QCPPlottableLegendItem::getTextColor() const { - return mSelected ? mSelectedTextColor : mTextColor; + return mSelected ? mSelectedTextColor : mTextColor; } /*! \internal - + Returns the font that shall be used to draw text, taking into account the selection state of this item. */ QFont QCPPlottableLegendItem::getFont() const { - return mSelected ? mSelectedFont : mFont; + return mSelected ? mSelectedFont : mFont; } /*! \internal - + Draws the item with \a painter. The size and position of the drawn legend item is defined by the parent layout (typically a \ref QCPLegend) and the \ref minimumSizeHint and \ref maximumSizeHint of this legend item. */ void QCPPlottableLegendItem::draw(QCPPainter *painter) { - if (!mPlottable) return; - painter->setFont(getFont()); - painter->setPen(QPen(getTextColor())); - QSizeF iconSize = mParentLegend->iconSize(); - QRectF textRect = painter->fontMetrics().boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPlottable->name()); - QRectF iconRect(mRect.topLeft(), iconSize); - int textHeight = qMax(textRect.height(), iconSize.height()); // if text has smaller height than icon, center text vertically in icon height, else align tops - painter->drawText(mRect.x()+iconSize.width()+mParentLegend->iconTextPadding(), mRect.y(), textRect.width(), textHeight, Qt::TextDontClip, mPlottable->name()); - // draw icon: - painter->save(); - painter->setClipRect(iconRect, Qt::IntersectClip); - mPlottable->drawLegendIcon(painter, iconRect); - painter->restore(); - // draw icon border: - if (getIconBorderPen().style() != Qt::NoPen) - { - painter->setPen(getIconBorderPen()); - painter->setBrush(Qt::NoBrush); - painter->drawRect(iconRect); - } + if (!mPlottable) { + return; + } + painter->setFont(getFont()); + painter->setPen(QPen(getTextColor())); + QSizeF iconSize = mParentLegend->iconSize(); + QRectF textRect = painter->fontMetrics().boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPlottable->name()); + QRectF iconRect(mRect.topLeft(), iconSize); + int textHeight = qMax(textRect.height(), iconSize.height()); // if text has smaller height than icon, center text vertically in icon height, else align tops + painter->drawText(mRect.x() + iconSize.width() + mParentLegend->iconTextPadding(), mRect.y(), textRect.width(), textHeight, Qt::TextDontClip, mPlottable->name()); + // draw icon: + painter->save(); + painter->setClipRect(iconRect, Qt::IntersectClip); + mPlottable->drawLegendIcon(painter, iconRect); + painter->restore(); + // draw icon border: + if (getIconBorderPen().style() != Qt::NoPen) { + painter->setPen(getIconBorderPen()); + painter->setBrush(Qt::NoBrush); + painter->drawRect(iconRect); + } } /*! \internal - + Calculates and returns the size of this item. This includes the icon, the text and the padding in between. */ QSize QCPPlottableLegendItem::minimumSizeHint() const { - if (!mPlottable) return QSize(); - QSize result(0, 0); - QRect textRect; - QFontMetrics fontMetrics(getFont()); - QSize iconSize = mParentLegend->iconSize(); - textRect = fontMetrics.boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPlottable->name()); - result.setWidth(iconSize.width() + mParentLegend->iconTextPadding() + textRect.width() + mMargins.left() + mMargins.right()); - result.setHeight(qMax(textRect.height(), iconSize.height()) + mMargins.top() + mMargins.bottom()); - return result; + if (!mPlottable) { + return QSize(); + } + QSize result(0, 0); + QRect textRect; + QFontMetrics fontMetrics(getFont()); + QSize iconSize = mParentLegend->iconSize(); + textRect = fontMetrics.boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPlottable->name()); + result.setWidth(iconSize.width() + mParentLegend->iconTextPadding() + textRect.width() + mMargins.left() + mMargins.right()); + result.setHeight(qMax(textRect.height(), iconSize.height()) + mMargins.top() + mMargins.bottom()); + return result; } @@ -12913,12 +12869,12 @@ 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 @@ -12938,7 +12894,7 @@ QSize QCPPlottableLegendItem::minimumSizeHint() const /*! \fn void QCPLegend::selectionChanged(QCPLegend::SelectableParts selection); This signal is emitted when the selection state of this legend has changed. - + \see setSelectedParts, setSelectableParts */ @@ -12946,57 +12902,57 @@ QSize QCPPlottableLegendItem::minimumSizeHint() const /*! Constructs a new QCPLegend instance with \a parentPlot as the containing plot and default values. - + Note that by default, QCustomPlot already contains a legend ready to be used as QCustomPlot::legend */ QCPLegend::QCPLegend() { - setRowSpacing(0); - setColumnSpacing(10); - setMargins(QMargins(2, 3, 2, 2)); - setAntialiased(false); - setIconSize(32, 18); - - setIconTextPadding(7); - - setSelectableParts(spLegendBox | spItems); - setSelectedParts(spNone); - - setBorderPen(QPen(Qt::black)); - setSelectedBorderPen(QPen(Qt::blue, 2)); - setIconBorderPen(Qt::NoPen); - setSelectedIconBorderPen(QPen(Qt::blue, 2)); - setBrush(Qt::white); - setSelectedBrush(Qt::white); - setTextColor(Qt::black); - setSelectedTextColor(Qt::blue); + setRowSpacing(0); + setColumnSpacing(10); + setMargins(QMargins(2, 3, 2, 2)); + setAntialiased(false); + setIconSize(32, 18); + + setIconTextPadding(7); + + setSelectableParts(spLegendBox | spItems); + setSelectedParts(spNone); + + setBorderPen(QPen(Qt::black)); + setSelectedBorderPen(QPen(Qt::blue, 2)); + setIconBorderPen(Qt::NoPen); + setSelectedIconBorderPen(QPen(Qt::blue, 2)); + setBrush(Qt::white); + setSelectedBrush(Qt::white); + setTextColor(Qt::black); + setSelectedTextColor(Qt::blue); } QCPLegend::~QCPLegend() { - clearItems(); - if (qobject_cast(mParentPlot)) // make sure this isn't called from QObject dtor when QCustomPlot is already destructed (happens when the legend is not in any layout and thus QObject-child of QCustomPlot) - mParentPlot->legendRemoved(this); + clearItems(); + if (qobject_cast(mParentPlot)) { // make sure this isn't called from QObject dtor when QCustomPlot is already destructed (happens when the legend is not in any layout and thus QObject-child of QCustomPlot) + mParentPlot->legendRemoved(this); + } } /* no doc for getter, see setSelectedParts */ QCPLegend::SelectableParts QCPLegend::selectedParts() const { - // check whether any legend elements selected, if yes, add spItems to return value - bool hasSelectedItems = false; - for (int i=0; iselected()) - { - hasSelectedItems = true; - break; + // check whether any legend elements selected, if yes, add spItems to return value + bool hasSelectedItems = false; + for (int i = 0; i < itemCount(); ++i) { + if (item(i) && item(i)->selected()) { + hasSelectedItems = true; + break; + } + } + if (hasSelectedItems) { + return mSelectedParts | spItems; + } else { + return mSelectedParts & ~spItems; } - } - if (hasSelectedItems) - return mSelectedParts | spItems; - else - return mSelectedParts & ~spItems; } /*! @@ -13004,7 +12960,7 @@ QCPLegend::SelectableParts QCPLegend::selectedParts() const */ void QCPLegend::setBorderPen(const QPen &pen) { - mBorderPen = pen; + mBorderPen = pen; } /*! @@ -13012,45 +12968,45 @@ void QCPLegend::setBorderPen(const QPen &pen) */ void QCPLegend::setBrush(const QBrush &brush) { - mBrush = brush; + mBrush = brush; } /*! Sets the default font of legend text. Legend items that draw text (e.g. the name of a graph) will use this font by default. However, a different font can be specified on a per-item-basis by accessing the specific legend item. - + This function will also set \a font on all already existing legend items. - + \see QCPAbstractLegendItem::setFont */ void QCPLegend::setFont(const QFont &font) { - mFont = font; - for (int i=0; isetFont(mFont); - } + mFont = font; + for (int i = 0; i < itemCount(); ++i) { + if (item(i)) { + item(i)->setFont(mFont); + } + } } /*! Sets the default color of legend text. Legend items that draw text (e.g. the name of a graph) will use this color by default. However, a different colors can be specified on a per-item-basis by accessing the specific legend item. - + This function will also set \a color on all already existing legend items. - + \see QCPAbstractLegendItem::setTextColor */ void QCPLegend::setTextColor(const QColor &color) { - mTextColor = color; - for (int i=0; isetTextColor(color); - } + mTextColor = color; + for (int i = 0; i < itemCount(); ++i) { + if (item(i)) { + item(i)->setTextColor(color); + } + } } /*! @@ -13059,15 +13015,15 @@ void QCPLegend::setTextColor(const QColor &color) */ void QCPLegend::setIconSize(const QSize &size) { - mIconSize = size; + mIconSize = size; } /*! \overload */ void QCPLegend::setIconSize(int width, int height) { - mIconSize.setWidth(width); - mIconSize.setHeight(height); + mIconSize.setWidth(width); + mIconSize.setHeight(height); } /*! @@ -13077,83 +13033,79 @@ void QCPLegend::setIconSize(int width, int height) */ void QCPLegend::setIconTextPadding(int padding) { - mIconTextPadding = padding; + mIconTextPadding = padding; } /*! Sets the pen used to draw a border around each legend icon. Legend items that draw an icon (e.g. a visual representation of the graph) will use this pen by default. - + If no border is wanted, set this to \a Qt::NoPen. */ void QCPLegend::setIconBorderPen(const QPen &pen) { - mIconBorderPen = pen; + mIconBorderPen = pen; } /*! Sets whether the user can (de-)select the parts in \a selectable by clicking on the QCustomPlot surface. (When \ref QCustomPlot::setInteractions contains \ref QCP::iSelectLegend.) - + However, even when \a selectable is set to a value not allowing the selection of a specific part, it is still possible to set the selection of this part manually, by calling \ref setSelectedParts directly. - + \see SelectablePart, setSelectedParts */ void QCPLegend::setSelectableParts(const SelectableParts &selectable) { - if (mSelectableParts != selectable) - { - mSelectableParts = selectable; - emit selectableChanged(mSelectableParts); - } + if (mSelectableParts != selectable) { + mSelectableParts = selectable; + emit selectableChanged(mSelectableParts); + } } /*! Sets the selected state of the respective legend parts described by \ref SelectablePart. When a part is selected, it uses a different pen/font and brush. If some legend items are selected and \a selected doesn't contain \ref spItems, those items become deselected. - + The entire selection mechanism is handled automatically when \ref QCustomPlot::setInteractions contains iSelectLegend. You only need to call this function when you wish to change the selection state manually. - + This function can change the selection state of a part even when \ref setSelectableParts was set to a value that actually excludes the part. - + emits the \ref selectionChanged signal when \a selected is different from the previous selection state. - + Note that it doesn't make sense to set the selected state \ref spItems here when it wasn't set before, because there's no way to specify which exact items to newly select. Do this by calling \ref QCPAbstractLegendItem::setSelected directly on the legend item you wish to select. - + \see SelectablePart, setSelectableParts, selectTest, setSelectedBorderPen, setSelectedIconBorderPen, setSelectedBrush, setSelectedFont */ void QCPLegend::setSelectedParts(const SelectableParts &selected) { - SelectableParts newSelected = selected; - mSelectedParts = this->selectedParts(); // update mSelectedParts in case item selection changed + SelectableParts newSelected = selected; + mSelectedParts = this->selectedParts(); // update mSelectedParts in case item selection changed - if (mSelectedParts != newSelected) - { - if (!mSelectedParts.testFlag(spItems) && newSelected.testFlag(spItems)) // attempt to set spItems flag (can't do that) - { - qDebug() << Q_FUNC_INFO << "spItems flag can not be set, it can only be unset with this function"; - newSelected &= ~spItems; + if (mSelectedParts != newSelected) { + if (!mSelectedParts.testFlag(spItems) && newSelected.testFlag(spItems)) { // attempt to set spItems flag (can't do that) + qDebug() << Q_FUNC_INFO << "spItems flag can not be set, it can only be unset with this function"; + newSelected &= ~spItems; + } + if (mSelectedParts.testFlag(spItems) && !newSelected.testFlag(spItems)) { // spItems flag was unset, so clear item selection + for (int i = 0; i < itemCount(); ++i) { + if (item(i)) { + item(i)->setSelected(false); + } + } + } + mSelectedParts = newSelected; + emit selectionChanged(mSelectedParts); } - if (mSelectedParts.testFlag(spItems) && !newSelected.testFlag(spItems)) // spItems flag was unset, so clear item selection - { - for (int i=0; isetSelected(false); - } - } - mSelectedParts = newSelected; - emit selectionChanged(mSelectedParts); - } } /*! @@ -13164,7 +13116,7 @@ void QCPLegend::setSelectedParts(const SelectableParts &selected) */ void QCPLegend::setSelectedBorderPen(const QPen &pen) { - mSelectedBorderPen = pen; + mSelectedBorderPen = pen; } /*! @@ -13174,7 +13126,7 @@ void QCPLegend::setSelectedBorderPen(const QPen &pen) */ void QCPLegend::setSelectedIconBorderPen(const QPen &pen) { - mSelectedIconBorderPen = pen; + mSelectedIconBorderPen = pen; } /*! @@ -13185,70 +13137,69 @@ void QCPLegend::setSelectedIconBorderPen(const QPen &pen) */ void QCPLegend::setSelectedBrush(const QBrush &brush) { - mSelectedBrush = brush; + mSelectedBrush = brush; } /*! Sets the default font that is used by legend items when they are selected. - + This function will also set \a font on all already existing legend items. \see setFont, QCPAbstractLegendItem::setSelectedFont */ void QCPLegend::setSelectedFont(const QFont &font) { - mSelectedFont = font; - for (int i=0; isetSelectedFont(font); - } + mSelectedFont = font; + for (int i = 0; i < itemCount(); ++i) { + if (item(i)) { + item(i)->setSelectedFont(font); + } + } } /*! Sets the default text color that is used by legend items when they are selected. - + This function will also set \a color on all already existing legend items. \see setTextColor, QCPAbstractLegendItem::setSelectedTextColor */ void QCPLegend::setSelectedTextColor(const QColor &color) { - mSelectedTextColor = color; - for (int i=0; isetSelectedTextColor(color); - } + mSelectedTextColor = color; + for (int i = 0; i < itemCount(); ++i) { + if (item(i)) { + item(i)->setSelectedTextColor(color); + } + } } /*! Returns the item with index \a i. - + \see itemCount */ QCPAbstractLegendItem *QCPLegend::item(int index) const { - return qobject_cast(elementAt(index)); + return qobject_cast(elementAt(index)); } /*! Returns the QCPPlottableLegendItem which is associated with \a plottable (e.g. a \ref QCPGraph*). If such an item isn't in the legend, returns 0. - + \see hasItemWithPlottable */ QCPPlottableLegendItem *QCPLegend::itemWithPlottable(const QCPAbstractPlottable *plottable) const { - for (int i=0; i(item(i))) - { - if (pli->plottable() == plottable) - return pli; + for (int i = 0; i < itemCount(); ++i) { + if (QCPPlottableLegendItem *pli = qobject_cast(item(i))) { + if (pli->plottable() == plottable) { + return pli; + } + } } - } - return 0; + return 0; } /*! @@ -13257,7 +13208,7 @@ QCPPlottableLegendItem *QCPLegend::itemWithPlottable(const QCPAbstractPlottable */ int QCPLegend::itemCount() const { - return elementCount(); + return elementCount(); } /*! @@ -13265,72 +13216,72 @@ int QCPLegend::itemCount() const */ bool QCPLegend::hasItem(QCPAbstractLegendItem *item) const { - for (int i=0; iitem(i)) - return true; - } - return false; + for (int i = 0; i < itemCount(); ++i) { + if (item == this->item(i)) { + return true; + } + } + return false; } /*! Returns whether the legend contains a QCPPlottableLegendItem which is associated with \a plottable (e.g. a \ref QCPGraph*). If such an item isn't in the legend, returns false. - + \see itemWithPlottable */ bool QCPLegend::hasItemWithPlottable(const QCPAbstractPlottable *plottable) const { - return itemWithPlottable(plottable); + return itemWithPlottable(plottable); } /*! Adds \a item to the legend, if it's not present already. - + 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. */ bool QCPLegend::addItem(QCPAbstractLegendItem *item) { - if (!hasItem(item)) - { - return addElement(rowCount(), 0, item); - } else - return false; + if (!hasItem(item)) { + return addElement(rowCount(), 0, item); + } else { + return false; + } } /*! Removes the item with index \a index from the legend. Returns true, if successful. - + \see itemCount, clearItems */ bool QCPLegend::removeItem(int index) { - if (QCPAbstractLegendItem *ali = item(index)) - { - bool success = remove(ali); - simplify(); - return success; - } else - return false; + if (QCPAbstractLegendItem *ali = item(index)) { + bool success = remove(ali); + simplify(); + return success; + } else { + return false; + } } /*! \overload - + Removes \a item from the legend. Returns true, if successful. - + \see clearItems */ bool QCPLegend::removeItem(QCPAbstractLegendItem *item) { - bool success = remove(item); - simplify(); - return success; + bool success = remove(item); + simplify(); + return success; } /*! @@ -13338,28 +13289,28 @@ bool QCPLegend::removeItem(QCPAbstractLegendItem *item) */ void QCPLegend::clearItems() { - for (int i=itemCount()-1; i>=0; --i) - removeItem(i); + for (int i = itemCount() - 1; i >= 0; --i) { + removeItem(i); + } } /*! Returns the legend items that are currently selected. If no items are selected, the list is empty. - + \see QCPAbstractLegendItem::setSelected, setSelectable */ QList QCPLegend::selectedItems() const { - QList result; - for (int i=0; iselected()) - result.append(ali); + QList result; + for (int i = 0; i < itemCount(); ++i) { + if (QCPAbstractLegendItem *ali = item(i)) { + if (ali->selected()) { + result.append(ali); + } + } } - } - return result; + return result; } /*! \internal @@ -13368,109 +13319,113 @@ QList QCPLegend::selectedItems() const before drawing main legend elements. This is the antialiasing state the painter passed to the \ref draw method is in by default. - + 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 */ void QCPLegend::applyDefaultAntialiasingHint(QCPPainter *painter) const { - applyAntialiasingHint(painter, mAntialiased, QCP::aeLegend); + applyAntialiasingHint(painter, mAntialiased, QCP::aeLegend); } /*! \internal - + Returns the pen used to paint the border of the legend, taking into account the selection state of the legend box. */ QPen QCPLegend::getBorderPen() const { - return mSelectedParts.testFlag(spLegendBox) ? mSelectedBorderPen : mBorderPen; + return mSelectedParts.testFlag(spLegendBox) ? mSelectedBorderPen : mBorderPen; } /*! \internal - + Returns the brush used to paint the background of the legend, taking into account the selection state of the legend box. */ QBrush QCPLegend::getBrush() const { - return mSelectedParts.testFlag(spLegendBox) ? mSelectedBrush : mBrush; + return mSelectedParts.testFlag(spLegendBox) ? mSelectedBrush : mBrush; } /*! \internal - + Draws the legend box with the provided \a painter. The individual legend items are layerables themselves, thus are drawn independently. */ void QCPLegend::draw(QCPPainter *painter) { - // draw background rect: - painter->setBrush(getBrush()); - painter->setPen(getBorderPen()); - painter->drawRect(mOuterRect); + // draw background rect: + painter->setBrush(getBrush()); + painter->setPen(getBorderPen()); + painter->drawRect(mOuterRect); } /* inherits documentation from base class */ double QCPLegend::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { - if (!mParentPlot) return -1; - if (onlySelectable && !mSelectableParts.testFlag(spLegendBox)) + if (!mParentPlot) { + return -1; + } + if (onlySelectable && !mSelectableParts.testFlag(spLegendBox)) { + return -1; + } + + if (mOuterRect.contains(pos.toPoint())) { + if (details) { + details->setValue(spLegendBox); + } + return mParentPlot->selectionTolerance() * 0.99; + } return -1; - - if (mOuterRect.contains(pos.toPoint())) - { - if (details) details->setValue(spLegendBox); - return mParentPlot->selectionTolerance()*0.99; - } - return -1; } /* inherits documentation from base class */ void QCPLegend::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) { - Q_UNUSED(event) - mSelectedParts = selectedParts(); // in case item selection has changed - if (details.value() == spLegendBox && mSelectableParts.testFlag(spLegendBox)) - { - SelectableParts selBefore = mSelectedParts; - setSelectedParts(additive ? mSelectedParts^spLegendBox : mSelectedParts|spLegendBox); // no need to unset spItems in !additive case, because they will be deselected by QCustomPlot (they're normal QCPLayerables with own deselectEvent) - if (selectionStateChanged) - *selectionStateChanged = mSelectedParts != selBefore; - } + Q_UNUSED(event) + mSelectedParts = selectedParts(); // in case item selection has changed + if (details.value() == spLegendBox && mSelectableParts.testFlag(spLegendBox)) { + SelectableParts selBefore = mSelectedParts; + setSelectedParts(additive ? mSelectedParts ^spLegendBox : mSelectedParts | spLegendBox); // no need to unset spItems in !additive case, because they will be deselected by QCustomPlot (they're normal QCPLayerables with own deselectEvent) + if (selectionStateChanged) { + *selectionStateChanged = mSelectedParts != selBefore; + } + } } /* inherits documentation from base class */ void QCPLegend::deselectEvent(bool *selectionStateChanged) { - mSelectedParts = selectedParts(); // in case item selection has changed - if (mSelectableParts.testFlag(spLegendBox)) - { - SelectableParts selBefore = mSelectedParts; - setSelectedParts(selectedParts() & ~spLegendBox); - if (selectionStateChanged) - *selectionStateChanged = mSelectedParts != selBefore; - } + mSelectedParts = selectedParts(); // in case item selection has changed + if (mSelectableParts.testFlag(spLegendBox)) { + SelectableParts selBefore = mSelectedParts; + setSelectedParts(selectedParts() & ~spLegendBox); + if (selectionStateChanged) { + *selectionStateChanged = mSelectedParts != selBefore; + } + } } /* inherits documentation from base class */ QCP::Interaction QCPLegend::selectionCategory() const { - return QCP::iSelectLegend; + return QCP::iSelectLegend; } /* inherits documentation from base class */ QCP::Interaction QCPAbstractLegendItem::selectionCategory() const { - return QCP::iSelectLegend; + return QCP::iSelectLegend; } /* inherits documentation from base class */ void QCPLegend::parentPlotInitialized(QCustomPlot *parentPlot) { - Q_UNUSED(parentPlot) + Q_UNUSED(parentPlot) } @@ -13480,13 +13435,13 @@ void QCPLegend::parentPlotInitialized(QCustomPlot *parentPlot) /*! \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 @@ -13496,10 +13451,10 @@ void QCPLegend::parentPlotInitialized(QCustomPlot *parentPlot) /* start documentation of signals */ /*! \fn void QCPPlotTitle::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. - + \see setSelected, setSelectable */ @@ -13507,93 +13462,92 @@ void QCPLegend::parentPlotInitialized(QCustomPlot *parentPlot) /*! Creates a new QCPPlotTitle instance and sets default values. The initial text is empty (\ref setText). - + To set the title text in the constructor, rather use \ref QCPPlotTitle(QCustomPlot *parentPlot, const QString &text). */ QCPPlotTitle::QCPPlotTitle(QCustomPlot *parentPlot) : - QCPLayoutElement(parentPlot), - mFont(QFont(QLatin1String("sans serif"), 13*1.5, QFont::Bold)), - mTextColor(Qt::black), - mSelectedFont(QFont(QLatin1String("sans serif"), 13*1.6, QFont::Bold)), - mSelectedTextColor(Qt::blue), - mSelectable(false), - mSelected(false) + QCPLayoutElement(parentPlot), + mFont(QFont(QLatin1String("sans serif"), 13 * 1.5, QFont::Bold)), + mTextColor(Qt::black), + mSelectedFont(QFont(QLatin1String("sans serif"), 13 * 1.6, QFont::Bold)), + 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); - } - setMargins(QMargins(5, 5, 5, 0)); + 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); + } + setMargins(QMargins(5, 5, 5, 0)); } /*! \overload - + Creates a new QCPPlotTitle instance and sets default values. The initial text is set to \a text. */ QCPPlotTitle::QCPPlotTitle(QCustomPlot *parentPlot, const QString &text) : - QCPLayoutElement(parentPlot), - mText(text), - mFont(QFont(parentPlot->font().family(), parentPlot->font().pointSize()*1.5, QFont::Bold)), - mTextColor(Qt::black), - mSelectedFont(QFont(parentPlot->font().family(), parentPlot->font().pointSize()*1.6, QFont::Bold)), - mSelectedTextColor(Qt::blue), - mSelectable(false), - mSelected(false) + QCPLayoutElement(parentPlot), + mText(text), + mFont(QFont(parentPlot->font().family(), parentPlot->font().pointSize() * 1.5, QFont::Bold)), + mTextColor(Qt::black), + mSelectedFont(QFont(parentPlot->font().family(), parentPlot->font().pointSize() * 1.6, QFont::Bold)), + mSelectedTextColor(Qt::blue), + mSelectable(false), + mSelected(false) { - setLayer(QLatin1String("axes")); - setMargins(QMargins(5, 5, 5, 0)); + setLayer(QLatin1String("axes")); + setMargins(QMargins(5, 5, 5, 0)); } /*! Sets the text that will be displayed to \a text. Multiple lines can be created by insertion of "\n". - + \see setFont, setTextColor */ void QCPPlotTitle::setText(const QString &text) { - mText = text; + mText = text; } /*! Sets the \a font of the title text. - + \see setTextColor, setSelectedFont */ void QCPPlotTitle::setFont(const QFont &font) { - mFont = font; + mFont = font; } /*! Sets the \a color of the title text. - + \see setFont, setSelectedTextColor */ void QCPPlotTitle::setTextColor(const QColor &color) { - mTextColor = color; + mTextColor = color; } /*! Sets the \a font of the title text that will be used if the plot title is selected (\ref setSelected). - + \see setFont */ void QCPPlotTitle::setSelectedFont(const QFont &font) { - mSelectedFont = font; + mSelectedFont = font; } /*! Sets the \a color of the title text that will be used if the plot title is selected (\ref setSelected). - + \see setTextColor */ void QCPPlotTitle::setSelectedTextColor(const QColor &color) { - mSelectedTextColor = color; + mSelectedTextColor = color; } /*! @@ -13604,120 +13558,120 @@ void QCPPlotTitle::setSelectedTextColor(const QColor &color) */ void QCPPlotTitle::setSelectable(bool selectable) { - if (mSelectable != selectable) - { - mSelectable = selectable; - emit selectableChanged(mSelectable); - } + if (mSelectable != selectable) { + mSelectable = selectable; + emit selectableChanged(mSelectable); + } } /*! Sets the selection state of this plot title 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) { - if (mSelected != selected) - { - mSelected = selected; - emit selectionChanged(mSelected); - } + if (mSelected != selected) { + mSelected = selected; + emit selectionChanged(mSelected); + } } /* inherits documentation from base class */ void QCPPlotTitle::applyDefaultAntialiasingHint(QCPPainter *painter) const { - applyAntialiasingHint(painter, mAntialiased, QCP::aeNone); + applyAntialiasingHint(painter, mAntialiased, QCP::aeNone); } /* inherits documentation from base class */ void QCPPlotTitle::draw(QCPPainter *painter) { - painter->setFont(mainFont()); - painter->setPen(QPen(mainTextColor())); - painter->drawText(mRect, Qt::AlignCenter, mText, &mTextBoundingRect); + painter->setFont(mainFont()); + painter->setPen(QPen(mainTextColor())); + painter->drawText(mRect, Qt::AlignCenter, mText, &mTextBoundingRect); } /* inherits documentation from base class */ QSize QCPPlotTitle::minimumSizeHint() const { - QFontMetrics metrics(mFont); - QSize result = metrics.boundingRect(0, 0, 0, 0, Qt::AlignCenter, mText).size(); - result.rwidth() += mMargins.left() + mMargins.right(); - result.rheight() += mMargins.top() + mMargins.bottom(); - return result; + QFontMetrics metrics(mFont); + QSize result = metrics.boundingRect(0, 0, 0, 0, Qt::AlignCenter, mText).size(); + result.rwidth() += mMargins.left() + mMargins.right(); + result.rheight() += mMargins.top() + mMargins.bottom(); + return result; } /* inherits documentation from base class */ QSize QCPPlotTitle::maximumSizeHint() const { - QFontMetrics metrics(mFont); - QSize result = metrics.boundingRect(0, 0, 0, 0, Qt::AlignCenter, mText).size(); - result.rheight() += mMargins.top() + mMargins.bottom(); - result.setWidth(QWIDGETSIZE_MAX); - return result; + QFontMetrics metrics(mFont); + QSize result = metrics.boundingRect(0, 0, 0, 0, Qt::AlignCenter, mText).size(); + result.rheight() += mMargins.top() + mMargins.bottom(); + result.setWidth(QWIDGETSIZE_MAX); + return result; } /* inherits documentation from base class */ void QCPPlotTitle::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) { - Q_UNUSED(event) - Q_UNUSED(details) - if (mSelectable) - { - bool selBefore = mSelected; - setSelected(additive ? !mSelected : true); - if (selectionStateChanged) - *selectionStateChanged = mSelected != selBefore; - } + Q_UNUSED(event) + Q_UNUSED(details) + if (mSelectable) { + bool selBefore = mSelected; + setSelected(additive ? !mSelected : true); + if (selectionStateChanged) { + *selectionStateChanged = mSelected != selBefore; + } + } } /* inherits documentation from base class */ void QCPPlotTitle::deselectEvent(bool *selectionStateChanged) { - if (mSelectable) - { - bool selBefore = mSelected; - setSelected(false); - if (selectionStateChanged) - *selectionStateChanged = mSelected != selBefore; - } + if (mSelectable) { + bool selBefore = mSelected; + setSelected(false); + if (selectionStateChanged) { + *selectionStateChanged = mSelected != selBefore; + } + } } /* inherits documentation from base class */ double QCPPlotTitle::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { - Q_UNUSED(details) - if (onlySelectable && !mSelectable) - return -1; - - if (mTextBoundingRect.contains(pos.toPoint())) - return mParentPlot->selectionTolerance()*0.99; - else - return -1; + Q_UNUSED(details) + if (onlySelectable && !mSelectable) { + return -1; + } + + if (mTextBoundingRect.contains(pos.toPoint())) { + return mParentPlot->selectionTolerance() * 0.99; + } else { + return -1; + } } /*! \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 { - return mSelected ? mSelectedFont : mFont; + return mSelected ? mSelectedFont : mFont; } /*! \internal - + 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 { - return mSelected ? mSelectedTextColor : mTextColor; + return mSelected ? mSelectedTextColor : mTextColor; } @@ -13727,35 +13681,35 @@ QColor QCPPlotTitle::mainTextColor() const /*! \class QCPColorScale \brief A color scale for use with color coding data such as QCPColorMap - + This layout element can be placed on the plot to correlate a color gradient with data values. It is usually used in combination with one or multiple \ref QCPColorMap "QCPColorMaps". \image html QCPColorScale.png - + The color scale can be either horizontal or vertical, as shown in the image above. The orientation and the side where the numbers appear is controlled with \ref setType. - + Use \ref QCPColorMap::setColorScale to connect a color map with a color scale. Once they are connected, they share their gradient, data range and data scale type (\ref setGradient, \ref setDataRange, \ref setDataScaleType). Multiple color maps may be associated with a single color scale, to make them all synchronize these properties. - + 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 - + 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 In this case we have placed it to the right of the default axis rect, so it wasn't necessary to call \ref setType, since \ref QCPAxis::atRight is already the default. The text next to the color scale can be set with \ref setLabel. - + For optimum appearance (like in the image above), it may be desirable to line up the axis rect and the borders of the color scale. Use a \ref QCPMarginGroup to achieve this: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolorscale-margingroup - + Color scales are initialized with a non-zero minimum top and bottom margin (\ref setMinimumMargins), because vertical color scales are most common and the minimum top/bottom margin makes sure it keeps some distance to the top/bottom widget border. So if you change to a @@ -13766,14 +13720,14 @@ QColor QCPPlotTitle::mainTextColor() const /* start documentation of inline functions */ /*! \fn QCPAxis *QCPColorScale::axis() const - + Returns the internal \ref QCPAxis instance of this color scale. You can access it to alter the appearance and behaviour of the axis. \ref QCPColorScale duplicates some properties in its interface for convenience. Those are \ref setDataRange (\ref QCPAxis::setRange), \ref setDataScaleType (\ref QCPAxis::setScaleType), and the method \ref setLabel (\ref QCPAxis::setLabel). As they each are connected, it does not matter whether you use the method on the QCPColorScale or on its QCPAxis. - + If the type of the color scale is changed with \ref setType, the axis returned by this method will change, too, to either the left, right, bottom or top axis, depending on which type was set. */ @@ -13782,23 +13736,23 @@ QColor QCPPlotTitle::mainTextColor() const /* start documentation of signals */ /*! \fn void QCPColorScale::dataRangeChanged(QCPRange newRange); - + This signal is emitted when the data range changes. - + \see setDataRange */ /*! \fn void QCPColorScale::dataScaleTypeChanged(QCPAxis::ScaleType scaleType); - + This signal is emitted when the data scale type changes. - + \see setDataScaleType */ /*! \fn void QCPColorScale::gradientChanged(QCPColorGradient newGradient); - + This signal is emitted when the gradient changes. - + \see setGradient */ @@ -13808,170 +13762,164 @@ QColor QCPPlotTitle::mainTextColor() const Constructs a new QCPColorScale. */ QCPColorScale::QCPColorScale(QCustomPlot *parentPlot) : - QCPLayoutElement(parentPlot), - mType(QCPAxis::atTop), // set to atTop such that setType(QCPAxis::atRight) below doesn't skip work because it thinks it's already atRight - mDataScaleType(QCPAxis::stLinear), - mBarWidth(20), - mAxisRect(new QCPColorScaleAxisRectPrivate(this)) + QCPLayoutElement(parentPlot), + mType(QCPAxis::atTop), // set to atTop such that setType(QCPAxis::atRight) below doesn't skip work because it thinks it's already atRight + mDataScaleType(QCPAxis::stLinear), + mBarWidth(20), + mAxisRect(new QCPColorScaleAxisRectPrivate(this)) { - setMinimumMargins(QMargins(0, 6, 0, 6)); // for default right color scale types, keep some room at bottom and top (important if no margin group is used) - setType(QCPAxis::atRight); - setDataRange(QCPRange(0, 6)); + setMinimumMargins(QMargins(0, 6, 0, 6)); // for default right color scale types, keep some room at bottom and top (important if no margin group is used) + setType(QCPAxis::atRight); + setDataRange(QCPRange(0, 6)); } QCPColorScale::~QCPColorScale() { - delete mAxisRect; + delete mAxisRect; } /* undocumented getter */ QString QCPColorScale::label() const { - if (!mColorAxis) - { - qDebug() << Q_FUNC_INFO << "internal color axis undefined"; - return QString(); - } - - return mColorAxis.data()->label(); + if (!mColorAxis) { + qDebug() << Q_FUNC_INFO << "internal color axis undefined"; + return QString(); + } + + return mColorAxis.data()->label(); } /* undocumented getter */ bool QCPColorScale::rangeDrag() const { - if (!mAxisRect) - { - qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; - return false; - } - - return mAxisRect.data()->rangeDrag().testFlag(QCPAxis::orientation(mType)) && - mAxisRect.data()->rangeDragAxis(QCPAxis::orientation(mType)) && - mAxisRect.data()->rangeDragAxis(QCPAxis::orientation(mType))->orientation() == QCPAxis::orientation(mType); + if (!mAxisRect) { + qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; + return false; + } + + return mAxisRect.data()->rangeDrag().testFlag(QCPAxis::orientation(mType)) && + mAxisRect.data()->rangeDragAxis(QCPAxis::orientation(mType)) && + mAxisRect.data()->rangeDragAxis(QCPAxis::orientation(mType))->orientation() == QCPAxis::orientation(mType); } /* undocumented getter */ bool QCPColorScale::rangeZoom() const { - if (!mAxisRect) - { - qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; - return false; - } - - return mAxisRect.data()->rangeZoom().testFlag(QCPAxis::orientation(mType)) && - mAxisRect.data()->rangeZoomAxis(QCPAxis::orientation(mType)) && - mAxisRect.data()->rangeZoomAxis(QCPAxis::orientation(mType))->orientation() == QCPAxis::orientation(mType); + if (!mAxisRect) { + qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; + return false; + } + + return mAxisRect.data()->rangeZoom().testFlag(QCPAxis::orientation(mType)) && + mAxisRect.data()->rangeZoomAxis(QCPAxis::orientation(mType)) && + mAxisRect.data()->rangeZoomAxis(QCPAxis::orientation(mType))->orientation() == QCPAxis::orientation(mType); } /*! Sets at which side of the color scale the axis is placed, and thus also its orientation. - + 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. */ void QCPColorScale::setType(QCPAxis::AxisType type) { - if (!mAxisRect) - { - qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; - return; - } - if (mType != type) - { - mType = type; - QCPRange rangeTransfer(0, 6); - double logBaseTransfer = 10; - QString labelTransfer; - // revert some settings on old axis: - if (mColorAxis) - { - rangeTransfer = mColorAxis.data()->range(); - labelTransfer = mColorAxis.data()->label(); - logBaseTransfer = mColorAxis.data()->scaleLogBase(); - 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))); + if (!mAxisRect) { + qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; + return; } - QList allAxisTypes = QList() << QCPAxis::atLeft << QCPAxis::atRight << QCPAxis::atBottom << QCPAxis::atTop; - foreach (QCPAxis::AxisType atype, allAxisTypes) - { - mAxisRect.data()->axis(atype)->setTicks(atype == mType); - mAxisRect.data()->axis(atype)->setTickLabels(atype== mType); + if (mType != type) { + mType = type; + QCPRange rangeTransfer(0, 6); + double logBaseTransfer = 10; + QString labelTransfer; + // revert some settings on old axis: + if (mColorAxis) { + rangeTransfer = mColorAxis.data()->range(); + labelTransfer = mColorAxis.data()->label(); + logBaseTransfer = mColorAxis.data()->scaleLogBase(); + 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))); + } + QList allAxisTypes = QList() << QCPAxis::atLeft << QCPAxis::atRight << QCPAxis::atBottom << QCPAxis::atTop; + foreach (QCPAxis::AxisType atype, allAxisTypes) { + mAxisRect.data()->axis(atype)->setTicks(atype == mType); + mAxisRect.data()->axis(atype)->setTickLabels(atype == mType); + } + // 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 + 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); } - // 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 - 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); - } } /*! Sets the range spanned by the color gradient and that is shown by the axis in the color scale. - + It is equivalent to calling QCPColorMap::setDataRange on any of the connected color maps. It is also equivalent to directly accessing the \ref axis and setting its range with \ref QCPAxis::setRange. - + \see setDataScaleType, setGradient, rescaleDataRange */ void QCPColorScale::setDataRange(const QCPRange &dataRange) { - if (mDataRange.lower != dataRange.lower || mDataRange.upper != dataRange.upper) - { - mDataRange = dataRange; - if (mColorAxis) - mColorAxis.data()->setRange(mDataRange); - emit dataRangeChanged(mDataRange); - } + if (mDataRange.lower != dataRange.lower || mDataRange.upper != dataRange.upper) { + mDataRange = dataRange; + if (mColorAxis) { + mColorAxis.data()->setRange(mDataRange); + } + emit dataRangeChanged(mDataRange); + } } /*! Sets the scale type of the color scale, i.e. whether values are linearly associated with colors or logarithmically. - + It is equivalent to calling QCPColorMap::setDataScaleType on any of the connected color maps. It is also equivalent to directly accessing the \ref axis and setting its scale type with \ref QCPAxis::setScaleType. - + \see setDataRange, setGradient */ void QCPColorScale::setDataScaleType(QCPAxis::ScaleType scaleType) { - if (mDataScaleType != scaleType) - { - mDataScaleType = scaleType; - if (mColorAxis) - mColorAxis.data()->setScaleType(mDataScaleType); - if (mDataScaleType == QCPAxis::stLogarithmic) - setDataRange(mDataRange.sanitizedForLogScale()); - emit dataScaleTypeChanged(mDataScaleType); - } + if (mDataScaleType != scaleType) { + mDataScaleType = scaleType; + if (mColorAxis) { + mColorAxis.data()->setScaleType(mDataScaleType); + } + if (mDataScaleType == QCPAxis::stLogarithmic) { + setDataRange(mDataRange.sanitizedForLogScale()); + } + emit dataScaleTypeChanged(mDataScaleType); + } } /*! Sets the color gradient that will be used to represent data values. - + It is equivalent to calling QCPColorMap::setGradient on any of the connected color maps. - + \see setDataRange, setDataScaleType */ void QCPColorScale::setGradient(const QCPColorGradient &gradient) { - if (mGradient != gradient) - { - mGradient = gradient; - if (mAxisRect) - mAxisRect.data()->mGradientImageInvalidated = true; - emit gradientChanged(mGradient); - } + if (mGradient != gradient) { + mGradient = gradient; + if (mAxisRect) { + mAxisRect.data()->mGradientImageInvalidated = true; + } + emit gradientChanged(mGradient); + } } /*! @@ -13980,13 +13928,12 @@ void QCPColorScale::setGradient(const QCPColorGradient &gradient) */ void QCPColorScale::setLabel(const QString &str) { - if (!mColorAxis) - { - qDebug() << Q_FUNC_INFO << "internal color axis undefined"; - return; - } - - mColorAxis.data()->setLabel(str); + if (!mColorAxis) { + qDebug() << Q_FUNC_INFO << "internal color axis undefined"; + return; + } + + mColorAxis.data()->setLabel(str); } /*! @@ -13995,213 +13942,200 @@ void QCPColorScale::setLabel(const QString &str) */ void QCPColorScale::setBarWidth(int width) { - mBarWidth = width; + mBarWidth = width; } /*! Sets whether the user can drag the data range (\ref setDataRange). - + Note that \ref QCP::iRangeDrag must be in the QCustomPlot's interactions (\ref QCustomPlot::setInteractions) to allow range dragging. */ void QCPColorScale::setRangeDrag(bool enabled) { - if (!mAxisRect) - { - qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; - return; - } - - if (enabled) - mAxisRect.data()->setRangeDrag(QCPAxis::orientation(mType)); - else - mAxisRect.data()->setRangeDrag(0); + if (!mAxisRect) { + qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; + return; + } + + if (enabled) { + mAxisRect.data()->setRangeDrag(QCPAxis::orientation(mType)); + } else { + mAxisRect.data()->setRangeDrag(0); + } } /*! Sets whether the user can zoom the data range (\ref setDataRange) by scrolling the mouse wheel. - + Note that \ref QCP::iRangeZoom must be in the QCustomPlot's interactions (\ref QCustomPlot::setInteractions) to allow range dragging. */ void QCPColorScale::setRangeZoom(bool enabled) { - if (!mAxisRect) - { - qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; - return; - } - - if (enabled) - mAxisRect.data()->setRangeZoom(QCPAxis::orientation(mType)); - else - mAxisRect.data()->setRangeZoom(0); + if (!mAxisRect) { + qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; + return; + } + + if (enabled) { + mAxisRect.data()->setRangeZoom(QCPAxis::orientation(mType)); + } else { + mAxisRect.data()->setRangeZoom(0); + } } /*! Returns a list of all the color maps associated with this color scale. */ -QList QCPColorScale::colorMaps() const +QList QCPColorScale::colorMaps() const { - QList result; - for (int i=0; iplottableCount(); ++i) - { - if (QCPColorMap *cm = qobject_cast(mParentPlot->plottable(i))) - if (cm->colorScale() == this) - result.append(cm); - } - return result; + QList result; + for (int i = 0; i < mParentPlot->plottableCount(); ++i) { + if (QCPColorMap *cm = qobject_cast(mParentPlot->plottable(i))) + if (cm->colorScale() == this) { + result.append(cm); + } + } + return result; } /*! Changes the data range such that all color maps associated with this color scale are fully mapped to the gradient in the data dimension. - + \see setDataRange */ 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) - if (mDataScaleType == QCPAxis::stLogarithmic) - sign = (mDataRange.upper < 0 ? -1 : 1); - for (int i=0; irealVisibility() && onlyVisibleMaps) - continue; - QCPRange mapRange; - if (maps.at(i)->colorScale() == this) - { - bool currentFoundRange = true; - mapRange = maps.at(i)->data()->dataBounds(); - if (sign == 1) - { - 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) - { - if (mapRange.upper >= 0 && mapRange.lower < 0) - mapRange.upper = mapRange.lower*1e-3; - else if (mapRange.upper >= 0 && mapRange.lower >= 0) - currentFoundRange = false; - } - if (currentFoundRange) - { - if (!haveRange) - newRange = mapRange; - else - newRange.expand(mapRange); - haveRange = true; - } + 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) + if (mDataScaleType == QCPAxis::stLogarithmic) { + sign = (mDataRange.upper < 0 ? -1 : 1); } - } - if (haveRange) - { - if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this dimension), shift current range to at least center the data - { - double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason - if (mDataScaleType == QCPAxis::stLinear) - { - newRange.lower = center-mDataRange.size()/2.0; - newRange.upper = center+mDataRange.size()/2.0; - } else // mScaleType == stLogarithmic - { - newRange.lower = center/qSqrt(mDataRange.upper/mDataRange.lower); - newRange.upper = center*qSqrt(mDataRange.upper/mDataRange.lower); - } + for (int i = 0; i < maps.size(); ++i) { + if (!maps.at(i)->realVisibility() && onlyVisibleMaps) { + continue; + } + QCPRange mapRange; + if (maps.at(i)->colorScale() == this) { + bool currentFoundRange = true; + mapRange = maps.at(i)->data()->dataBounds(); + if (sign == 1) { + 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) { + if (mapRange.upper >= 0 && mapRange.lower < 0) { + mapRange.upper = mapRange.lower * 1e-3; + } else if (mapRange.upper >= 0 && mapRange.lower >= 0) { + currentFoundRange = false; + } + } + if (currentFoundRange) { + if (!haveRange) { + newRange = mapRange; + } else { + newRange.expand(mapRange); + } + haveRange = true; + } + } + } + if (haveRange) { + if (!QCPRange::validRange(newRange)) { // likely due to range being zero (plottable has only constant data in this dimension), shift current range to at least center the data + double center = (newRange.lower + newRange.upper) * 0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason + if (mDataScaleType == QCPAxis::stLinear) { + newRange.lower = center - mDataRange.size() / 2.0; + newRange.upper = center + mDataRange.size() / 2.0; + } else { // mScaleType == stLogarithmic + newRange.lower = center / qSqrt(mDataRange.upper / mDataRange.lower); + newRange.upper = center * qSqrt(mDataRange.upper / mDataRange.lower); + } + } + setDataRange(newRange); } - setDataRange(newRange); - } } /* inherits documentation from base class */ void QCPColorScale::update(UpdatePhase phase) { - QCPLayoutElement::update(phase); - if (!mAxisRect) - { - qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; - return; - } - - mAxisRect.data()->update(phase); - - switch (phase) - { - case upMargins: - { - if (mType == QCPAxis::atBottom || mType == QCPAxis::atTop) - { - setMaximumSize(QWIDGETSIZE_MAX, mBarWidth+mAxisRect.data()->margins().top()+mAxisRect.data()->margins().bottom()+margins().top()+margins().bottom()); - setMinimumSize(0, mBarWidth+mAxisRect.data()->margins().top()+mAxisRect.data()->margins().bottom()+margins().top()+margins().bottom()); - } else - { - setMaximumSize(mBarWidth+mAxisRect.data()->margins().left()+mAxisRect.data()->margins().right()+margins().left()+margins().right(), QWIDGETSIZE_MAX); - setMinimumSize(mBarWidth+mAxisRect.data()->margins().left()+mAxisRect.data()->margins().right()+margins().left()+margins().right(), 0); - } - break; + QCPLayoutElement::update(phase); + if (!mAxisRect) { + qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; + return; } - case upLayout: - { - mAxisRect.data()->setOuterRect(rect()); - break; + + mAxisRect.data()->update(phase); + + switch (phase) { + case upMargins: { + if (mType == QCPAxis::atBottom || mType == QCPAxis::atTop) { + setMaximumSize(QWIDGETSIZE_MAX, mBarWidth + mAxisRect.data()->margins().top() + mAxisRect.data()->margins().bottom() + margins().top() + margins().bottom()); + setMinimumSize(0, mBarWidth + mAxisRect.data()->margins().top() + mAxisRect.data()->margins().bottom() + margins().top() + margins().bottom()); + } else { + setMaximumSize(mBarWidth + mAxisRect.data()->margins().left() + mAxisRect.data()->margins().right() + margins().left() + margins().right(), QWIDGETSIZE_MAX); + setMinimumSize(mBarWidth + mAxisRect.data()->margins().left() + mAxisRect.data()->margins().right() + margins().left() + margins().right(), 0); + } + break; + } + case upLayout: { + mAxisRect.data()->setOuterRect(rect()); + break; + } + default: + break; } - default: break; - } } /* inherits documentation from base class */ void QCPColorScale::applyDefaultAntialiasingHint(QCPPainter *painter) const { - painter->setAntialiasing(false); + painter->setAntialiasing(false); } /* inherits documentation from base class */ void QCPColorScale::mousePressEvent(QMouseEvent *event) { - if (!mAxisRect) - { - qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; - return; - } - mAxisRect.data()->mousePressEvent(event); + if (!mAxisRect) { + qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; + return; + } + mAxisRect.data()->mousePressEvent(event); } /* inherits documentation from base class */ void QCPColorScale::mouseMoveEvent(QMouseEvent *event) { - if (!mAxisRect) - { - qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; - return; - } - mAxisRect.data()->mouseMoveEvent(event); + if (!mAxisRect) { + qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; + return; + } + mAxisRect.data()->mouseMoveEvent(event); } /* inherits documentation from base class */ void QCPColorScale::mouseReleaseEvent(QMouseEvent *event) { - if (!mAxisRect) - { - qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; - return; - } - mAxisRect.data()->mouseReleaseEvent(event); + if (!mAxisRect) { + qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; + return; + } + mAxisRect.data()->mouseReleaseEvent(event); } /* inherits documentation from base class */ void QCPColorScale::wheelEvent(QWheelEvent *event) { - if (!mAxisRect) - { - qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; - return; - } - mAxisRect.data()->wheelEvent(event); + if (!mAxisRect) { + qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; + return; + } + mAxisRect.data()->wheelEvent(event); } //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -14212,9 +14146,9 @@ void QCPColorScale::wheelEvent(QWheelEvent *event) \internal \brief An axis rect subclass for use in a QCPColorScale - + This is a private class and not part of the public QCustomPlot interface. - + It provides the axis rect functionality for the QCPColorScale class. */ @@ -14223,36 +14157,36 @@ void QCPColorScale::wheelEvent(QWheelEvent *event) Creates a new instance, as a child of \a parentColorScale. */ QCPColorScaleAxisRectPrivate::QCPColorScaleAxisRectPrivate(QCPColorScale *parentColorScale) : - QCPAxisRect(parentColorScale->parentPlot(), true), - mParentColorScale(parentColorScale), - mGradientImageInvalidated(true) + QCPAxisRect(parentColorScale->parentPlot(), true), + mParentColorScale(parentColorScale), + mGradientImageInvalidated(true) { - setParentLayerable(parentColorScale); - setMinimumMargins(QMargins(0, 0, 0, 0)); - QList allAxisTypes = QList() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight; - foreach (QCPAxis::AxisType type, allAxisTypes) - { - axis(type)->setVisible(true); - axis(type)->grid()->setVisible(false); - axis(type)->setPadding(0); - connect(axis(type), SIGNAL(selectionChanged(QCPAxis::SelectableParts)), this, SLOT(axisSelectionChanged(QCPAxis::SelectableParts))); - connect(axis(type), SIGNAL(selectableChanged(QCPAxis::SelectableParts)), this, SLOT(axisSelectableChanged(QCPAxis::SelectableParts))); - } + setParentLayerable(parentColorScale); + setMinimumMargins(QMargins(0, 0, 0, 0)); + QList allAxisTypes = QList() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight; + foreach (QCPAxis::AxisType type, allAxisTypes) { + axis(type)->setVisible(true); + axis(type)->grid()->setVisible(false); + axis(type)->setPadding(0); + connect(axis(type), SIGNAL(selectionChanged(QCPAxis::SelectableParts)), this, SLOT(axisSelectionChanged(QCPAxis::SelectableParts))); + connect(axis(type), SIGNAL(selectableChanged(QCPAxis::SelectableParts)), this, SLOT(axisSelectableChanged(QCPAxis::SelectableParts))); + } - connect(axis(QCPAxis::atLeft), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atRight), SLOT(setRange(QCPRange))); - connect(axis(QCPAxis::atRight), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atLeft), SLOT(setRange(QCPRange))); - connect(axis(QCPAxis::atBottom), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atTop), SLOT(setRange(QCPRange))); - connect(axis(QCPAxis::atTop), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atBottom), SLOT(setRange(QCPRange))); - connect(axis(QCPAxis::atLeft), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atRight), SLOT(setScaleType(QCPAxis::ScaleType))); - connect(axis(QCPAxis::atRight), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atLeft), SLOT(setScaleType(QCPAxis::ScaleType))); - connect(axis(QCPAxis::atBottom), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atTop), SLOT(setScaleType(QCPAxis::ScaleType))); - connect(axis(QCPAxis::atTop), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atBottom), SLOT(setScaleType(QCPAxis::ScaleType))); - - // make layer transfers of color scale transfer to axis rect and axes - // the axes must be set after axis rect, such that they appear above color gradient drawn by axis rect: - connect(parentColorScale, SIGNAL(layerChanged(QCPLayer*)), this, SLOT(setLayer(QCPLayer*))); - foreach (QCPAxis::AxisType type, allAxisTypes) - connect(parentColorScale, SIGNAL(layerChanged(QCPLayer*)), axis(type), SLOT(setLayer(QCPLayer*))); + connect(axis(QCPAxis::atLeft), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atRight), SLOT(setRange(QCPRange))); + connect(axis(QCPAxis::atRight), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atLeft), SLOT(setRange(QCPRange))); + connect(axis(QCPAxis::atBottom), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atTop), SLOT(setRange(QCPRange))); + connect(axis(QCPAxis::atTop), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atBottom), SLOT(setRange(QCPRange))); + connect(axis(QCPAxis::atLeft), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atRight), SLOT(setScaleType(QCPAxis::ScaleType))); + connect(axis(QCPAxis::atRight), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atLeft), SLOT(setScaleType(QCPAxis::ScaleType))); + connect(axis(QCPAxis::atBottom), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atTop), SLOT(setScaleType(QCPAxis::ScaleType))); + connect(axis(QCPAxis::atTop), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atBottom), SLOT(setScaleType(QCPAxis::ScaleType))); + + // make layer transfers of color scale transfer to axis rect and axes + // the axes must be set after axis rect, such that they appear above color gradient drawn by axis rect: + connect(parentColorScale, SIGNAL(layerChanged(QCPLayer *)), this, SLOT(setLayer(QCPLayer *))); + foreach (QCPAxis::AxisType type, allAxisTypes) { + connect(parentColorScale, SIGNAL(layerChanged(QCPLayer *)), axis(type), SLOT(setLayer(QCPLayer *))); + } } /*! \internal @@ -14261,19 +14195,19 @@ QCPColorScaleAxisRectPrivate::QCPColorScaleAxisRectPrivate(QCPColorScale *parent */ void QCPColorScaleAxisRectPrivate::draw(QCPPainter *painter) { - if (mGradientImageInvalidated) - updateGradientImage(); - - bool mirrorHorz = false; - bool mirrorVert = false; - if (mParentColorScale->mColorAxis) - { - mirrorHorz = mParentColorScale->mColorAxis.data()->rangeReversed() && (mParentColorScale->type() == QCPAxis::atBottom || mParentColorScale->type() == QCPAxis::atTop); - mirrorVert = mParentColorScale->mColorAxis.data()->rangeReversed() && (mParentColorScale->type() == QCPAxis::atLeft || mParentColorScale->type() == QCPAxis::atRight); - } - - painter->drawImage(rect().adjusted(0, -1, 0, -1), mGradientImage.mirrored(mirrorHorz, mirrorVert)); - QCPAxisRect::draw(painter); + if (mGradientImageInvalidated) { + updateGradientImage(); + } + + bool mirrorHorz = false; + bool mirrorVert = false; + if (mParentColorScale->mColorAxis) { + mirrorHorz = mParentColorScale->mColorAxis.data()->rangeReversed() && (mParentColorScale->type() == QCPAxis::atBottom || mParentColorScale->type() == QCPAxis::atTop); + mirrorVert = mParentColorScale->mColorAxis.data()->rangeReversed() && (mParentColorScale->type() == QCPAxis::atLeft || mParentColorScale->type() == QCPAxis::atRight); + } + + painter->drawImage(rect().adjusted(0, -1, 0, -1), mGradientImage.mirrored(mirrorHorz, mirrorVert)); + QCPAxisRect::draw(painter); } /*! \internal @@ -14283,39 +14217,41 @@ void QCPColorScaleAxisRectPrivate::draw(QCPPainter *painter) */ void QCPColorScaleAxisRectPrivate::updateGradientImage() { - if (rect().isEmpty()) - return; - - int n = mParentColorScale->mGradient.levelCount(); - int w, h; - QVector data(n); - for (int i=0; imType == QCPAxis::atBottom || mParentColorScale->mType == QCPAxis::atTop) - { - w = n; - h = rect().height(); - mGradientImage = QImage(w, h, QImage::Format_RGB32); - QVector pixels; - for (int y=0; y(mGradientImage.scanLine(y))); - mParentColorScale->mGradient.colorize(data.constData(), QCPRange(0, n-1), pixels.first(), n); - for (int y=1; y(mGradientImage.scanLine(y)); - const QRgb lineColor = mParentColorScale->mGradient.color(data[h-1-y], QCPRange(0, n-1)); - for (int x=0; xmGradient.levelCount(); + int w, h; + QVector data(n); + for (int i = 0; i < n; ++i) { + data[i] = i; + } + if (mParentColorScale->mType == QCPAxis::atBottom || mParentColorScale->mType == QCPAxis::atTop) { + w = n; + h = rect().height(); + mGradientImage = QImage(w, h, QImage::Format_RGB32); + QVector pixels; + for (int y = 0; y < h; ++y) { + pixels.append(reinterpret_cast(mGradientImage.scanLine(y))); + } + mParentColorScale->mGradient.colorize(data.constData(), QCPRange(0, n - 1), pixels.first(), n); + for (int y = 1; y < h; ++y) { + memcpy(pixels.at(y), pixels.first(), n * sizeof(QRgb)); + } + } else { + w = rect().width(); + h = n; + mGradientImage = QImage(w, h, QImage::Format_RGB32); + for (int y = 0; y < h; ++y) { + QRgb *pixels = reinterpret_cast(mGradientImage.scanLine(y)); + const QRgb lineColor = mParentColorScale->mGradient.color(data[h - 1 - y], QCPRange(0, n - 1)); + for (int x = 0; x < w; ++x) { + pixels[x] = lineColor; + } + } + } + mGradientImageInvalidated = false; } /*! \internal @@ -14325,22 +14261,22 @@ void QCPColorScaleAxisRectPrivate::updateGradientImage() */ void QCPColorScaleAxisRectPrivate::axisSelectionChanged(QCPAxis::SelectableParts selectedParts) { - // axis bases of four axes shall always (de-)selected synchronously: - QList allAxisTypes = QList() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight; - foreach (QCPAxis::AxisType type, allAxisTypes) - { - if (QCPAxis *senderAxis = qobject_cast(sender())) - if (senderAxis->axisType() == type) - continue; - - if (axis(type)->selectableParts().testFlag(QCPAxis::spAxis)) - { - if (selectedParts.testFlag(QCPAxis::spAxis)) - axis(type)->setSelectedParts(axis(type)->selectedParts() | QCPAxis::spAxis); - else - axis(type)->setSelectedParts(axis(type)->selectedParts() & ~QCPAxis::spAxis); + // axis bases of four axes shall always (de-)selected synchronously: + QList allAxisTypes = QList() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight; + foreach (QCPAxis::AxisType type, allAxisTypes) { + if (QCPAxis *senderAxis = qobject_cast(sender())) + if (senderAxis->axisType() == type) { + continue; + } + + if (axis(type)->selectableParts().testFlag(QCPAxis::spAxis)) { + if (selectedParts.testFlag(QCPAxis::spAxis)) { + axis(type)->setSelectedParts(axis(type)->selectedParts() | QCPAxis::spAxis); + } else { + axis(type)->setSelectedParts(axis(type)->selectedParts() & ~QCPAxis::spAxis); + } + } } - } } /*! \internal @@ -14350,22 +14286,22 @@ void QCPColorScaleAxisRectPrivate::axisSelectionChanged(QCPAxis::SelectableParts */ void QCPColorScaleAxisRectPrivate::axisSelectableChanged(QCPAxis::SelectableParts selectableParts) { - // synchronize axis base selectability: - QList allAxisTypes = QList() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight; - foreach (QCPAxis::AxisType type, allAxisTypes) - { - if (QCPAxis *senderAxis = qobject_cast(sender())) - if (senderAxis->axisType() == type) - continue; - - if (axis(type)->selectableParts().testFlag(QCPAxis::spAxis)) - { - if (selectableParts.testFlag(QCPAxis::spAxis)) - axis(type)->setSelectableParts(axis(type)->selectableParts() | QCPAxis::spAxis); - else - axis(type)->setSelectableParts(axis(type)->selectableParts() & ~QCPAxis::spAxis); + // synchronize axis base selectability: + QList allAxisTypes = QList() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight; + foreach (QCPAxis::AxisType type, allAxisTypes) { + if (QCPAxis *senderAxis = qobject_cast(sender())) + if (senderAxis->axisType() == type) { + continue; + } + + if (axis(type)->selectableParts().testFlag(QCPAxis::spAxis)) { + if (selectableParts.testFlag(QCPAxis::spAxis)) { + axis(type)->setSelectableParts(axis(type)->selectableParts() | QCPAxis::spAxis); + } else { + axis(type)->setSelectableParts(axis(type)->selectableParts() & ~QCPAxis::spAxis); + } + } } - } } @@ -14375,9 +14311,9 @@ void QCPColorScaleAxisRectPrivate::axisSelectableChanged(QCPAxis::SelectablePart /*! \class QCPData \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 @@ -14385,7 +14321,7 @@ void QCPColorScaleAxisRectPrivate::axisSelectableChanged(QCPAxis::SelectablePart \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) - + \see QCPDataMap */ @@ -14393,12 +14329,12 @@ void QCPColorScaleAxisRectPrivate::axisSelectableChanged(QCPAxis::SelectablePart Constructs a data point with key, value and all errors set to zero. */ QCPData::QCPData() : - key(0), - value(0), - keyErrorPlus(0), - keyErrorMinus(0), - valueErrorPlus(0), - valueErrorMinus(0) + key(0), + value(0), + keyErrorPlus(0), + keyErrorMinus(0), + valueErrorPlus(0), + valueErrorMinus(0) { } @@ -14406,12 +14342,12 @@ QCPData::QCPData() : Constructs a data point with the specified \a key and \a value. All errors are set to zero. */ QCPData::QCPData(double key, double value) : - key(key), - value(value), - keyErrorPlus(0), - keyErrorMinus(0), - valueErrorPlus(0), - valueErrorMinus(0) + key(key), + value(value), + keyErrorPlus(0), + keyErrorMinus(0), + valueErrorPlus(0), + valueErrorMinus(0) { } @@ -14424,33 +14360,33 @@ QCPData::QCPData(double key, double value) : \brief A plottable representing a graph in a plot. \image html QCPGraph.png - + 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. - + 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 want to plot non-single-valued curves, rather use the QCPCurve plottable. - + Gaps in the graph line can be created by adding data points with NaN as value (qQNaN() or std::numeric_limits::quiet_NaN()) in between the two data points that shall be separated. - + \section 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). - + \subsection filling Filling under or between graphs - + QCPGraph knows two types of fills: Normal graph fills towards the zero-value-line parallel to the key axis of the graph, and fills between two graphs, called channel fills. To enable a fill, just set a brush with \ref setBrush which is neither Qt::NoBrush nor fully transparent. - + By default, a normal fill towards the zero-value-line will be drawn. To set up a channel fill between this graph and another one, call \ref setChannelFillGraph with the other graph as parameter. @@ -14461,7 +14397,7 @@ QCPData::QCPData(double key, double value) : /* start of documentation of inline functions */ /*! \fn QCPDataMap *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. @@ -14474,81 +14410,77 @@ QCPData::QCPData(double key, double 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 QCPGraph can be added to the plot with QCustomPlot::addPlottable, QCustomPlot then takes ownership of the graph. - + 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) + QCPAbstractPlottable(keyAxis, valueAxis) { - mData = new QCPDataMap; - - 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); - setChannelFillGraph(0); - setAdaptiveSampling(true); + mData = new QCPDataMap; + + 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); + setChannelFillGraph(0); + setAdaptiveSampling(true); } QCPGraph::~QCPGraph() { - delete mData; + 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; - } + 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 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); - } + mData->clear(); + int n = key.size(); + n = qMin(n, value.size()); + QCPData newData; + for (int i = 0; i < n; ++i) { + newData.key = key[i]; + newData.value = value[i]; + mData->insertMulti(newData.key, newData); + } } /*! @@ -14557,24 +14489,23 @@ void QCPGraph::setData(const QVector &key, const QVector &value) 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); - } + mData->clear(); + int n = key.size(); + n = qMin(n, value.size()); + n = qMin(n, valueError.size()); + QCPData newData; + for (int i = 0; i < n; ++i) { + newData.key = key[i]; + newData.value = value[i]; + newData.valueErrorMinus = valueError[i]; + newData.valueErrorPlus = valueError[i]; + mData->insertMulti(key[i], newData); + } } /*! @@ -14588,20 +14519,19 @@ void QCPGraph::setDataValueError(const QVector &key, 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); - } + mData->clear(); + int n = key.size(); + n = qMin(n, value.size()); + n = qMin(n, valueErrorMinus.size()); + n = qMin(n, valueErrorPlus.size()); + QCPData newData; + for (int i = 0; i < n; ++i) { + newData.key = key[i]; + newData.value = value[i]; + newData.valueErrorMinus = valueErrorMinus[i]; + newData.valueErrorPlus = valueErrorPlus[i]; + mData->insertMulti(key[i], newData); + } } /*! @@ -14610,24 +14540,23 @@ void QCPGraph::setDataValueError(const QVector &key, const QVector &key, const QVector &value, const QVector &keyError) { - 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); - } + mData->clear(); + int n = key.size(); + n = qMin(n, value.size()); + n = qMin(n, keyError.size()); + QCPData newData; + for (int i = 0; i < n; ++i) { + newData.key = key[i]; + newData.value = value[i]; + newData.keyErrorMinus = keyError[i]; + newData.keyErrorPlus = keyError[i]; + mData->insertMulti(key[i], newData); + } } /*! @@ -14641,20 +14570,19 @@ void QCPGraph::setDataKeyError(const QVector &key, const QVector */ 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); - } + mData->clear(); + int n = key.size(); + n = qMin(n, value.size()); + n = qMin(n, keyErrorMinus.size()); + n = qMin(n, keyErrorPlus.size()); + QCPData newData; + for (int i = 0; i < n; ++i) { + newData.key = key[i]; + newData.value = value[i]; + newData.keyErrorMinus = keyErrorMinus[i]; + newData.keyErrorPlus = keyErrorPlus[i]; + mData->insertMulti(key[i], newData); + } } /*! @@ -14663,27 +14591,26 @@ void QCPGraph::setDataKeyError(const QVector &key, const QVector 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); - } + mData->clear(); + int n = key.size(); + n = qMin(n, value.size()); + n = qMin(n, valueError.size()); + n = qMin(n, keyError.size()); + QCPData newData; + for (int i = 0; i < n; ++i) { + newData.key = key[i]; + newData.value = value[i]; + newData.keyErrorMinus = keyError[i]; + newData.keyErrorPlus = keyError[i]; + newData.valueErrorMinus = valueError[i]; + newData.valueErrorPlus = valueError[i]; + mData->insertMulti(key[i], newData); + } } /*! @@ -14697,47 +14624,46 @@ void QCPGraph::setDataBothError(const QVector &key, 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); - } + mData->clear(); + int n = key.size(); + n = qMin(n, value.size()); + n = qMin(n, valueErrorMinus.size()); + n = qMin(n, valueErrorPlus.size()); + n = qMin(n, keyErrorMinus.size()); + n = qMin(n, keyErrorPlus.size()); + QCPData newData; + for (int i = 0; i < n; ++i) { + newData.key = key[i]; + newData.value = value[i]; + newData.keyErrorMinus = keyErrorMinus[i]; + newData.keyErrorPlus = keyErrorPlus[i]; + newData.valueErrorMinus = valueErrorMinus[i]; + newData.valueErrorPlus = valueErrorPlus[i]; + mData->insertMulti(key[i], newData); + } } /*! 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. - + \see setScatterStyle */ void QCPGraph::setLineStyle(LineStyle ls) { - mLineStyle = ls; + mLineStyle = ls; } /*! Sets the visual appearance of single data points in the plot. If set to \ref QCPScatterStyle::ssNone, no scatter points are drawn (e.g. for line-only-plots with appropriate line style). - + \see QCPScatterStyle, setLineStyle */ void QCPGraph::setScatterStyle(const QCPScatterStyle &style) { - mScatterStyle = style; + mScatterStyle = style; } /*! @@ -14750,7 +14676,7 @@ void QCPGraph::setScatterStyle(const QCPScatterStyle &style) */ void QCPGraph::setErrorType(ErrorType errorType) { - mErrorType = errorType; + mErrorType = errorType; } /*! @@ -14759,7 +14685,7 @@ void QCPGraph::setErrorType(ErrorType errorType) */ void QCPGraph::setErrorPen(const QPen &pen) { - mErrorPen = pen; + mErrorPen = pen; } /*! @@ -14767,29 +14693,29 @@ void QCPGraph::setErrorPen(const QPen &pen) */ void QCPGraph::setErrorBarSize(double size) { - mErrorBarSize = size; + 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; + mErrorBarSkipSymbol = enabled; } /*! Sets the target graph for filling the area between this graph and \a targetGraph with the current brush (\ref setBrush). - + When \a targetGraph is set to 0, a normal graph fill to the zero-value-line will be shown. To disable any filling, set the brush to Qt::NoBrush. @@ -14797,41 +14723,39 @@ void QCPGraph::setErrorBarSkipSymbol(bool enabled) */ void QCPGraph::setChannelFillGraph(QCPGraph *targetGraph) { - // prevent setting channel target to this graph itself: - if (targetGraph == this) - { - qDebug() << Q_FUNC_INFO << "targetGraph is this graph itself"; - mChannelFillGraph = 0; - return; - } - // prevent setting channel target to a graph not in the plot: - if (targetGraph && targetGraph->mParentPlot != mParentPlot) - { - qDebug() << Q_FUNC_INFO << "targetGraph not in same plot"; - mChannelFillGraph = 0; - return; - } - - mChannelFillGraph = targetGraph; + // prevent setting channel target to this graph itself: + if (targetGraph == this) { + qDebug() << Q_FUNC_INFO << "targetGraph is this graph itself"; + mChannelFillGraph = 0; + return; + } + // prevent setting channel target to a graph not in the plot: + if (targetGraph && targetGraph->mParentPlot != mParentPlot) { + qDebug() << Q_FUNC_INFO << "targetGraph not in same plot"; + mChannelFillGraph = 0; + return; + } + + mChannelFillGraph = targetGraph; } /*! Sets whether adaptive sampling shall be used when plotting this graph. QCustomPlot's adaptive sampling technique can drastically improve the replot performance for graphs with a larger number of points (e.g. above 10,000), without notably changing the appearance of the graph. - + By default, adaptive sampling is enabled. Even if enabled, QCustomPlot decides whether adaptive sampling shall actually be used on a per-graph basis. So leaving adaptive sampling enabled has no disadvantage in almost all cases. - + \image html adaptive-sampling-line.png "A line plot of 500,000 points without and with adaptive sampling" - + As can be seen, line plots experience no visual degradation from adaptive sampling. Outliers are reproduced reliably, as well as the overall shape of the data set. The replot time reduces dramatically though. This allows QCustomPlot to display large amounts of data in realtime. - + \image html adaptive-sampling-scatter.png "A scatter plot of 100,000 points without and with adaptive sampling" - + Care must be taken when using high-density scatter plots in combination with adaptive sampling. The adaptive sampling algorithm treats scatter plots more carefully than line plots which still gives a significant reduction of replot times, but not quite as much as for line plots. This is @@ -14840,7 +14764,7 @@ void QCPGraph::setChannelFillGraph(QCPGraph *targetGraph) identical, as banding occurs for the outer data points. This is in fact intentional, such that the boundaries of the data cloud stay visible to the viewer. How strong the banding appears, depends on the point density, i.e. the number of points in the plot. - + For some situations with scatter plots it might thus be desirable to manually turn adaptive sampling off. For example, when saving the plot to disk. This can be achieved by setting \a enabled to false before issuing a command like \ref QCustomPlot::savePng, and setting \a enabled @@ -14848,69 +14772,68 @@ void QCPGraph::setChannelFillGraph(QCPGraph *targetGraph) */ void QCPGraph::setAdaptiveSampling(bool enabled) { - mAdaptiveSampling = enabled; + mAdaptiveSampling = enabled; } /*! Adds the provided data points in \a dataMap to the current data. - + Alternatively, you can also access and modify the graph's data via the \ref data method, which returns a pointer to the internal \ref QCPDataMap. - + \see removeData */ void QCPGraph::addData(const QCPDataMap &dataMap) { - mData->unite(dataMap); + mData->unite(dataMap); } /*! \overload Adds the provided single data point in \a data to the current data. - + Alternatively, you can also access and modify the graph's data via the \ref data method, which returns a pointer to the internal \ref QCPDataMap. - + \see removeData */ void QCPGraph::addData(const QCPData &data) { - mData->insertMulti(data.key, data); + mData->insertMulti(data.key, data); } /*! \overload Adds the provided single data point as \a key and \a value pair to the current data. - + Alternatively, you can also access and modify the graph's data via the \ref data method, which returns a pointer to the internal \ref QCPDataMap. - + \see removeData */ void QCPGraph::addData(double key, double value) { - QCPData newData; - newData.key = key; - newData.value = value; - mData->insertMulti(newData.key, newData); + 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); - } + int n = qMin(keys.size(), values.size()); + QCPData newData; + for (int i = 0; i < n; ++i) { + newData.key = keys[i]; + newData.value = values[i]; + mData->insertMulti(newData.key, newData); + } } /*! @@ -14919,9 +14842,10 @@ void QCPGraph::addData(const QVector &keys, const QVector &value */ void QCPGraph::removeDataBefore(double key) { - QCPDataMap::iterator it = mData->begin(); - while (it != mData->end() && it.key() < key) - it = mData->erase(it); + QCPDataMap::iterator it = mData->begin(); + while (it != mData->end() && it.key() < key) { + it = mData->erase(it); + } } /*! @@ -14930,30 +14854,36 @@ void QCPGraph::removeDataBefore(double key) */ void QCPGraph::removeDataAfter(double key) { - if (mData->isEmpty()) return; - QCPDataMap::iterator it = mData->upperBound(key); - while (it != mData->end()) - it = mData->erase(it); + 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); + 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. @@ -14962,7 +14892,7 @@ void QCPGraph::removeData(double fromKey, double toKey) */ void QCPGraph::removeData(double key) { - mData->remove(key); + mData->remove(key); } /*! @@ -14971,277 +14901,314 @@ void QCPGraph::removeData(double key) */ void QCPGraph::clearData() { - mData->clear(); + mData->clear(); } /* inherits documentation from base class */ double QCPGraph::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { - Q_UNUSED(details) - if ((onlySelectable && !mSelectable) || mData->isEmpty()) - return -1; - if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; } - - if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint())) - return pointDistance(pos); - else - return -1; + Q_UNUSED(details) + if ((onlySelectable && !mSelectable) || mData->isEmpty()) { + return -1; + } + if (!mKeyAxis || !mValueAxis) { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + return -1; + } + + if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint())) { + return pointDistance(pos); + } else { + return -1; + } } /*! \overload - + Allows to define whether error bars are taken into consideration when determining the new axis range. - + \see rescaleKeyAxis, rescaleValueAxis, QCPAbstractPlottable::rescaleAxes, QCustomPlot::rescaleAxes */ void QCPGraph::rescaleAxes(bool onlyEnlarge, bool includeErrorBars) const { - rescaleKeyAxis(onlyEnlarge, includeErrorBars); - rescaleValueAxis(onlyEnlarge, includeErrorBars); + rescaleKeyAxis(onlyEnlarge, includeErrorBars); + rescaleValueAxis(onlyEnlarge, includeErrorBars); } /*! \overload - + Allows to define whether error bars (of kind \ref QCPGraph::etKey) are taken into consideration when determining the new axis range. - + \see rescaleAxes, QCPAbstractPlottable::rescaleKeyAxis */ void QCPGraph::rescaleKeyAxis(bool onlyEnlarge, bool includeErrorBars) const { - // this code is a copy of QCPAbstractPlottable::rescaleKeyAxis with the only change - // that getKeyRange is passed the includeErrorBars value. - if (mData->isEmpty()) return; - - QCPAxis *keyAxis = mKeyAxis.data(); - if (!keyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; } - - SignDomain signDomain = sdBoth; - if (keyAxis->scaleType() == QCPAxis::stLogarithmic) - signDomain = (keyAxis->range().upper < 0 ? sdNegative : sdPositive); - - bool foundRange; - QCPRange newRange = getKeyRange(foundRange, signDomain, includeErrorBars); - - if (foundRange) - { - if (onlyEnlarge) - { - if (keyAxis->range().lower < newRange.lower) - newRange.lower = keyAxis->range().lower; - if (keyAxis->range().upper > newRange.upper) - newRange.upper = keyAxis->range().upper; + // 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); } - 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; + // 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); } - valueAxis->setRange(newRange); - } } /* 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 (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; - - // fill vectors with data appropriate to plot style: - getPlotData(lineData, scatterData); - - // check data validity if flag set: + if (!mKeyAxis || !mValueAxis) { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + return; + } + if (mKeyAxis.data()->range().size() <= 0 || mData->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; + } + + // 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) - { - if (QCP::isInvalidData(it.value().key, it.value().value) || - QCP::isInvalidData(it.value().keyErrorPlus, it.value().keyErrorMinus) || - QCP::isInvalidData(it.value().valueErrorPlus, it.value().valueErrorPlus)) - qDebug() << Q_FUNC_INFO << "Data point at" << it.key() << "invalid." << "Plottable name:" << name(); - } + QCPDataMap::const_iterator it; + for (it = mData->constBegin(); it != mData->constEnd(); ++it) { + if (QCP::isInvalidData(it.value().key, it.value().value) || + QCP::isInvalidData(it.value().keyErrorPlus, it.value().keyErrorMinus) || + QCP::isInvalidData(it.value().valueErrorPlus, it.value().valueErrorPlus)) { + qDebug() << Q_FUNC_INFO << "Data point at" << it.key() << "invalid." << "Plottable name:" << name(); + } + } #endif - // draw fill of graph: - if (mLineStyle != lsNone) - drawFill(painter, lineData); - - // draw line: - if (mLineStyle == lsImpulse) - drawImpulsePlot(painter, lineData); - else if (mLineStyle != lsNone) - drawLinePlot(painter, lineData); // also step plots can be drawn as a line plot - - // draw scatters: - if (scatterData) - drawScatterPlot(painter, scatterData); - - // free allocated line and point vectors: - delete lineData; - if (scatterData) - delete scatterData; + // draw fill of graph: + if (mLineStyle != lsNone) { + drawFill(painter, lineData); + } + + // draw line: + if (mLineStyle == lsImpulse) { + drawImpulsePlot(painter, lineData); + } else if (mLineStyle != lsNone) { + drawLinePlot(painter, lineData); // also step plots can be drawn as a line plot + } + + // draw scatters: + if (scatterData) { + drawScatterPlot(painter, scatterData); + } + + // free allocated line and point vectors: + delete lineData; + if (scatterData) { + delete scatterData; + } } /* inherits documentation from base class */ void QCPGraph::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const { - // draw fill: - if (mBrush.style() != Qt::NoBrush) - { - applyFillAntialiasingHint(painter); - painter->fillRect(QRectF(rect.left(), rect.top()+rect.height()/2.0, rect.width(), rect.height()/3.0), mBrush); - } - // draw line vertically centered: - if (mLineStyle != lsNone) - { - applyDefaultAntialiasingHint(painter); - painter->setPen(mPen); - painter->drawLine(QLineF(rect.left(), rect.top()+rect.height()/2.0, rect.right()+5, rect.top()+rect.height()/2.0)); // +5 on x2 else last segment is missing from dashed/dotted pens - } - // draw scatter symbol: - if (!mScatterStyle.isNone()) - { - applyScattersAntialiasingHint(painter); - // scale scatter pixmap if it's too large to fit in legend icon rect: - if (mScatterStyle.shape() == QCPScatterStyle::ssPixmap && (mScatterStyle.pixmap().size().width() > rect.width() || mScatterStyle.pixmap().size().height() > rect.height())) - { - QCPScatterStyle scaledStyle(mScatterStyle); - scaledStyle.setPixmap(scaledStyle.pixmap().scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation)); - scaledStyle.applyTo(painter, mPen); - scaledStyle.drawShape(painter, QRectF(rect).center()); - } else - { - mScatterStyle.applyTo(painter, mPen); - mScatterStyle.drawShape(painter, QRectF(rect).center()); + // draw fill: + if (mBrush.style() != Qt::NoBrush) { + applyFillAntialiasingHint(painter); + painter->fillRect(QRectF(rect.left(), rect.top() + rect.height() / 2.0, rect.width(), rect.height() / 3.0), mBrush); + } + // draw line vertically centered: + if (mLineStyle != lsNone) { + applyDefaultAntialiasingHint(painter); + painter->setPen(mPen); + painter->drawLine(QLineF(rect.left(), rect.top() + rect.height() / 2.0, rect.right() + 5, rect.top() + rect.height() / 2.0)); // +5 on x2 else last segment is missing from dashed/dotted pens + } + // draw scatter symbol: + if (!mScatterStyle.isNone()) { + applyScattersAntialiasingHint(painter); + // scale scatter pixmap if it's too large to fit in legend icon rect: + if (mScatterStyle.shape() == QCPScatterStyle::ssPixmap && (mScatterStyle.pixmap().size().width() > rect.width() || mScatterStyle.pixmap().size().height() > rect.height())) { + QCPScatterStyle scaledStyle(mScatterStyle); + scaledStyle.setPixmap(scaledStyle.pixmap().scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation)); + scaledStyle.applyTo(painter, mPen); + scaledStyle.drawShape(painter, QRectF(rect).center()); + } else { + mScatterStyle.applyTo(painter, mPen); + mScatterStyle.drawShape(painter, QRectF(rect).center()); + } } - } } /*! \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 */ void QCPGraph::getPlotData(QVector *lineData, QVector *scatterData) const { - switch(mLineStyle) - { - case lsNone: getScatterPlotData(scatterData); break; - case lsLine: getLinePlotData(lineData, scatterData); break; - case lsStepLeft: getStepLeftPlotData(lineData, scatterData); break; - case lsStepRight: getStepRightPlotData(lineData, scatterData); break; - case lsStepCenter: getStepCenterPlotData(lineData, scatterData); break; - case lsImpulse: getImpulsePlotData(lineData, scatterData); break; - } + switch (mLineStyle) { + case lsNone: + getScatterPlotData(scatterData); + break; + case lsLine: + getLinePlotData(lineData, scatterData); + break; + case lsStepLeft: + getStepLeftPlotData(lineData, scatterData); + break; + case lsStepRight: + getStepRightPlotData(lineData, scatterData); + break; + case lsStepCenter: + getStepCenterPlotData(lineData, scatterData); + break; + case lsImpulse: + getImpulsePlotData(lineData, scatterData); + break; + } } /*! \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); + getPreparedData(0, scatterData); } /*! \internal - + Places the raw data points needed for a normal linearly connected graph in \a linePixelData. As for all plot data retrieval functions, \a scatterData just contains all unaltered data (scatter) points that are visible for drawing scatter points, if necessary. If drawing scatter points is disabled (i.e. the scatter style's shape is \ref QCPScatterStyle::ssNone), pass 0 as \a scatterData, and the function will skip filling the vector. - + \see drawLinePlot */ void QCPGraph::getLinePlotData(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->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) - { - for (int i=0; icoordToPixel(lineData.at(i).value)); - (*linePixelData)[i].setY(keyAxis->coordToPixel(lineData.at(i).key)); + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + return; } - } else // key axis is horizontal - { - for (int i=0; icoordToPixel(lineData.at(i).key)); - (*linePixelData)[i].setY(valueAxis->coordToPixel(lineData.at(i).value)); + if (!linePixelData) { + qDebug() << Q_FUNC_INFO << "null pointer passed as linePixelData"; + 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) { + for (int i = 0; i < lineData.size(); ++i) { + (*linePixelData)[i].setX(valueAxis->coordToPixel(lineData.at(i).value)); + (*linePixelData)[i].setY(keyAxis->coordToPixel(lineData.at(i).key)); + } + } else { // key axis is horizontal + for (int i = 0; i < lineData.size(); ++i) { + (*linePixelData)[i].setX(keyAxis->coordToPixel(lineData.at(i).key)); + (*linePixelData)[i].setY(valueAxis->coordToPixel(lineData.at(i).value)); + } } - } } /*! @@ -15252,49 +15219,51 @@ void QCPGraph::getLinePlotData(QVector *linePixelData, QVector 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: - 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); + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + return; } - } else // key axis is horizontal - { - 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); + 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 lastValue = valueAxis->coordToPixel(lineData.first().value); + double key; + for (int i = 0; i < lineData.size(); ++i) { + key = keyAxis->coordToPixel(lineData.at(i).key); + (*linePixelData)[i * 2 + 0].setX(lastValue); + (*linePixelData)[i * 2 + 0].setY(key); + lastValue = valueAxis->coordToPixel(lineData.at(i).value); + (*linePixelData)[i * 2 + 1].setX(lastValue); + (*linePixelData)[i * 2 + 1].setY(key); + } + } else { // key axis is horizontal + double lastValue = valueAxis->coordToPixel(lineData.first().value); + double key; + for (int i = 0; i < lineData.size(); ++i) { + key = keyAxis->coordToPixel(lineData.at(i).key); + (*linePixelData)[i * 2 + 0].setX(key); + (*linePixelData)[i * 2 + 0].setY(lastValue); + lastValue = valueAxis->coordToPixel(lineData.at(i).value); + (*linePixelData)[i * 2 + 1].setX(key); + (*linePixelData)[i * 2 + 1].setY(lastValue); + } } - } } /*! @@ -15305,49 +15274,51 @@ void QCPGraph::getStepLeftPlotData(QVector *linePixelData, 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); + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + return; } - } 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); + 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; i < lineData.size(); ++i) { + value = valueAxis->coordToPixel(lineData.at(i).value); + (*linePixelData)[i * 2 + 0].setX(value); + (*linePixelData)[i * 2 + 0].setY(lastKey); + lastKey = keyAxis->coordToPixel(lineData.at(i).key); + (*linePixelData)[i * 2 + 1].setX(value); + (*linePixelData)[i * 2 + 1].setY(lastKey); + } + } else { // key axis is horizontal + double lastKey = keyAxis->coordToPixel(lineData.first().key); + double value; + for (int i = 0; i < lineData.size(); ++i) { + value = valueAxis->coordToPixel(lineData.at(i).value); + (*linePixelData)[i * 2 + 0].setX(lastKey); + (*linePixelData)[i * 2 + 0].setY(value); + lastKey = keyAxis->coordToPixel(lineData.at(i).key); + (*linePixelData)[i * 2 + 1].setX(lastKey); + (*linePixelData)[i * 2 + 1].setY(value); + } } - } } /*! @@ -15358,60 +15329,62 @@ void QCPGraph::getStepRightPlotData(QVector *linePixelData, 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); + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + return; } - (*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); + 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; i < lineData.size(); ++i) { + key = (keyAxis->coordToPixel(lineData.at(i).key) + lastKey) * 0.5; + (*linePixelData)[i * 2 - 1].setX(lastValue); + (*linePixelData)[i * 2 - 1].setY(key); + lastValue = valueAxis->coordToPixel(lineData.at(i).value); + lastKey = keyAxis->coordToPixel(lineData.at(i).key); + (*linePixelData)[i * 2 + 0].setX(lastValue); + (*linePixelData)[i * 2 + 0].setY(key); + } + (*linePixelData)[lineData.size() * 2 - 1].setX(lastValue); + (*linePixelData)[lineData.size() * 2 - 1].setY(lastKey); + } else { // key axis is horizontal + double lastKey = keyAxis->coordToPixel(lineData.first().key); + double lastValue = valueAxis->coordToPixel(lineData.first().value); + double key; + (*linePixelData)[0].setX(lastKey); + (*linePixelData)[0].setY(lastValue); + for (int i = 1; i < lineData.size(); ++i) { + key = (keyAxis->coordToPixel(lineData.at(i).key) + lastKey) * 0.5; + (*linePixelData)[i * 2 - 1].setX(key); + (*linePixelData)[i * 2 - 1].setY(lastValue); + lastValue = valueAxis->coordToPixel(lineData.at(i).value); + lastKey = keyAxis->coordToPixel(lineData.at(i).key); + (*linePixelData)[i * 2 + 0].setX(key); + (*linePixelData)[i * 2 + 0].setY(lastValue); + } + (*linePixelData)[lineData.size() * 2 - 1].setX(lastKey); + (*linePixelData)[lineData.size() * 2 - 1].setY(lastValue); } - (*linePixelData)[lineData.size()*2-1].setX(lastKey); - (*linePixelData)[lineData.size()*2-1].setY(lastValue); - } } @@ -15423,424 +15396,446 @@ void QCPGraph::getStepCenterPlotData(QVector *linePixelData, 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); + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + return; } - } 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 (!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; i < lineData.size(); ++i) { + key = keyAxis->coordToPixel(lineData.at(i).key); + (*linePixelData)[i * 2 + 0].setX(zeroPointX); + (*linePixelData)[i * 2 + 0].setY(key); + (*linePixelData)[i * 2 + 1].setX(valueAxis->coordToPixel(lineData.at(i).value)); + (*linePixelData)[i * 2 + 1].setY(key); + } + } else { // key axis is horizontal + double zeroPointY = valueAxis->coordToPixel(0); + double key; + for (int i = 0; i < lineData.size(); ++i) { + key = keyAxis->coordToPixel(lineData.at(i).key); + (*linePixelData)[i * 2 + 0].setX(key); + (*linePixelData)[i * 2 + 0].setY(zeroPointY); + (*linePixelData)[i * 2 + 1].setX(key); + (*linePixelData)[i * 2 + 1].setY(valueAxis->coordToPixel(lineData.at(i).value)); + } + } +} + +void QCPGraph::setSmooth(int smooth) +{ + this->smooth = smooth; } /*! \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). - + 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 */ void QCPGraph::drawFill(QCPPainter *painter, QVector *lineData) const { - if (mLineStyle == lsImpulse) return; // fill doesn't make sense for impulse plot - if (mainBrush().style() == Qt::NoBrush || mainBrush().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); - } else - { - // draw channel fill between this graph and mChannelFillGraph: - painter->setPen(Qt::NoPen); - painter->setBrush(mainBrush()); - painter->drawPolygon(getChannelFillPolygon(lineData)); - } + if (mLineStyle == lsImpulse) { + return; // fill doesn't make sense for impulse plot + } + if (mainBrush().style() == Qt::NoBrush || mainBrush().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()); + + if (smooth == 1) { + painter->drawPath(SmoothCurve::createSmoothCurve(*lineData)); + } else if (smooth == 2) { + painter->drawPath(SmoothCurve::createSmoothCurve2(*lineData)); + } else { + painter->drawPolygon(QPolygonF(*lineData)); + } + + removeFillBasePoints(lineData); + } else { + // draw channel fill between this graph and mChannelFillGraph: + painter->setPen(Qt::NoPen); + painter->setBrush(mainBrush()); + painter->drawPolygon(getChannelFillPolygon(lineData)); + } } /*! \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. - + \see drawLinePlot, drawImpulsePlot */ void QCPGraph::drawScatterPlot(QCPPainter *painter, QVector *scatterData) 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)); + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + return; + } + + // draw error bars: + if (mErrorType != etNone) { + applyErrorBarsAntialiasingHint(painter); + painter->setPen(mErrorPen); + if (keyAxis->orientation() == Qt::Vertical) { + for (int i = 0; i < scatterData->size(); ++i) { + drawError(painter, valueAxis->coordToPixel(scatterData->at(i).value), keyAxis->coordToPixel(scatterData->at(i).key), scatterData->at(i)); + } + } else { + for (int i = 0; i < scatterData->size(); ++i) { + drawError(painter, keyAxis->coordToPixel(scatterData->at(i).key), valueAxis->coordToPixel(scatterData->at(i).value), scatterData->at(i)); + } + } + } + + // draw scatter point symbols: + applyScattersAntialiasingHint(painter); + mScatterStyle.applyTo(painter, mPen); + if (keyAxis->orientation() == Qt::Vertical) { + for (int i = 0; i < scatterData->size(); ++i) + if (!qIsNaN(scatterData->at(i).value)) { + mScatterStyle.drawShape(painter, valueAxis->coordToPixel(scatterData->at(i).value), keyAxis->coordToPixel(scatterData->at(i).key)); + } + } else { + for (int i = 0; i < scatterData->size(); ++i) + if (!qIsNaN(scatterData->at(i).value)) { + mScatterStyle.drawShape(painter, keyAxis->coordToPixel(scatterData->at(i).key), valueAxis->coordToPixel(scatterData->at(i).value)); + } } - } - - // 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)); - } } /*! \internal - + Draws line graphs from the provided data. It connects all points in \a lineData, which was created by one of the "get(...)PlotData" functions for line styles that require simple line connections between the point vector they create. These are for example \ref getLinePlotData, \ref getStepLeftPlotData, \ref getStepRightPlotData and \ref getStepCenterPlotData. - + \see drawScatterPlot, drawImpulsePlot */ void QCPGraph::drawLinePlot(QCPPainter *painter, QVector *lineData) const { - // draw line of graph: - if (mainPen().style() != Qt::NoPen && mainPen().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()) || 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; + // draw line of graph: + if (mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0) { + applyDefaultAntialiasingHint(painter); + //开启了平滑曲线则应用对应算法绘制平滑路径 + if (mLineStyle == lsLine) { + if (smooth == 1) { + painter->drawPath(SmoothCurve::createSmoothCurve(*lineData)); + return; + } else if (smooth == 2) { + painter->drawPath(SmoothCurve::createSmoothCurve2(*lineData)); + return; + } + } + + 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()) || 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); } - ++i; - } - // draw last segment: - painter->drawPolyline(lineData->constData()+segmentStart, lineDataSize-segmentStart); } - } } /*! \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 */ void QCPGraph::drawImpulsePlot(QCPPainter *painter, QVector *lineData) const { - // draw impulses: - if (mainPen().style() != Qt::NoPen && mainPen().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); - } + // draw impulses: + if (mainPen().style() != Qt::NoPen && mainPen().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); + } } /*! \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. */ void QCPGraph::getPreparedData(QVector *lineData, QVector *scatterData) const { - 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; - - // count points in visible range, taking into account that we only need to count to the limit maxCount if using adaptive sampling: - int maxCount = std::numeric_limits::max(); - if (mAdaptiveSampling) - { - int keyPixelSpan = qAbs(keyAxis->coordToPixel(lower.key())-keyAxis->coordToPixel(upper.key())); - maxCount = 2*keyPixelSpan+2; - } - int dataCount = countDataInBounds(lower, upper, maxCount); - - if (mAdaptiveSampling && dataCount >= maxCount) // use adaptive sampling only if there are at least two points per pixel on average - { - if (lineData) - { - QCPDataMap::const_iterator it = lower; - QCPDataMap::const_iterator upperEnd = upper+1; - double minValue = it.value().value; - double maxValue = it.value().value; - QCPDataMap::const_iterator currentIntervalFirstPoint = it; - int reversedFactor = keyAxis->rangeReversed() != (keyAxis->orientation()==Qt::Vertical) ? -1 : 1; // is used to calculate keyEpsilon pixel into the correct direction - int reversedRound = keyAxis->rangeReversed() != (keyAxis->orientation()==Qt::Vertical) ? 1 : 0; // is used to switch between floor (normal) and ceil (reversed) rounding of currentIntervalStartKey - double currentIntervalStartKey = keyAxis->pixelToCoord((int)(keyAxis->coordToPixel(lower.key())+reversedRound)); - double lastIntervalEndKey = currentIntervalStartKey; - double keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor)); // interval of one pixel on screen when mapped to plot key coordinates - bool keyEpsilonVariable = keyAxis->scaleType() == QCPAxis::stLogarithmic; // indicates whether keyEpsilon needs to be updated after every interval (for log axes) - int intervalDataCount = 1; - ++it; // advance iterator to second data point because adaptive sampling works in 1 point retrospect - while (it != upperEnd) - { - if (it.key() < currentIntervalStartKey+keyEpsilon) // data point is still within same pixel, so skip it and expand value span of this cluster if necessary - { - if (it.value().value < minValue) - minValue = it.value().value; - else if (it.value().value > maxValue) - maxValue = it.value().value; - ++intervalDataCount; - } else // new pixel interval started - { - if (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; - } - // 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)); + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + return; } - - 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; + // 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; + } + + // count points in visible range, taking into account that we only need to count to the limit maxCount if using adaptive sampling: + int maxCount = std::numeric_limits::max(); + if (mAdaptiveSampling) { + int keyPixelSpan = qAbs(keyAxis->coordToPixel(lower.key()) - keyAxis->coordToPixel(upper.key())); + maxCount = 2 * keyPixelSpan + 2; + } + int dataCount = countDataInBounds(lower, upper, maxCount); + + if (mAdaptiveSampling && dataCount >= maxCount) { // use adaptive sampling only if there are at least two points per pixel on average + if (lineData) { + QCPDataMap::const_iterator it = lower; + QCPDataMap::const_iterator upperEnd = upper + 1; + double minValue = it.value().value; + double maxValue = it.value().value; + QCPDataMap::const_iterator currentIntervalFirstPoint = it; + int reversedFactor = keyAxis->rangeReversed() != (keyAxis->orientation() == Qt::Vertical) ? -1 : 1; // is used to calculate keyEpsilon pixel into the correct direction + int reversedRound = keyAxis->rangeReversed() != (keyAxis->orientation() == Qt::Vertical) ? 1 : 0; // is used to switch between floor (normal) and ceil (reversed) rounding of currentIntervalStartKey + double currentIntervalStartKey = keyAxis->pixelToCoord((int)(keyAxis->coordToPixel(lower.key()) + reversedRound)); + double lastIntervalEndKey = currentIntervalStartKey; + double keyEpsilon = qAbs(currentIntervalStartKey - keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey) + 1.0 * reversedFactor)); // interval of one pixel on screen when mapped to plot key coordinates + bool keyEpsilonVariable = keyAxis->scaleType() == QCPAxis::stLogarithmic; // indicates whether keyEpsilon needs to be updated after every interval (for log axes) + int intervalDataCount = 1; + ++it; // advance iterator to second data point because adaptive sampling works in 1 point retrospect + while (it != upperEnd) { + if (it.key() < currentIntervalStartKey + keyEpsilon) { // data point is still within same pixel, so skip it and expand value span of this cluster if necessary + if (it.value().value < minValue) { + minValue = it.value().value; + } else if (it.value().value > maxValue) { + maxValue = it.value().value; + } + ++intervalDataCount; + } else { // new pixel interval started + if (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; + } + // 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)); } - } 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; + + if (scatterData) { + double valueMaxRange = valueAxis->range().upper; + double valueMinRange = valueAxis->range().lower; + QCPDataMap::const_iterator it = lower; + QCPDataMap::const_iterator upperEnd = upper + 1; + double minValue = it.value().value; + double maxValue = it.value().value; + QCPDataMap::const_iterator minValueIt = it; + QCPDataMap::const_iterator maxValueIt = it; + QCPDataMap::const_iterator currentIntervalStart = it; + int reversedFactor = keyAxis->rangeReversed() ? -1 : 1; // is used to calculate keyEpsilon pixel into the correct direction + int reversedRound = keyAxis->rangeReversed() ? 1 : 0; // is used to switch between floor (normal) and ceil (reversed) rounding of currentIntervalStartKey + double currentIntervalStartKey = keyAxis->pixelToCoord((int)(keyAxis->coordToPixel(lower.key()) + reversedRound)); + double keyEpsilon = qAbs(currentIntervalStartKey - keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey) + 1.0 * reversedFactor)); // interval of one pixel on screen when mapped to plot key coordinates + bool keyEpsilonVariable = keyAxis->scaleType() == QCPAxis::stLogarithmic; // indicates whether keyEpsilon needs to be updated after every interval (for log axes) + int intervalDataCount = 1; + ++it; // advance iterator to second data point because adaptive sampling works in 1 point retrospect + while (it != upperEnd) { + if (it.key() < currentIntervalStartKey + keyEpsilon) { // data point is still within same pixel, so skip it and expand value span of this pixel if necessary + if (it.value().value < minValue && it.value().value > valueMinRange && it.value().value < valueMaxRange) { + minValue = it.value().value; + minValueIt = it; + } else if (it.value().value > maxValue && it.value().value > valueMinRange && it.value().value < valueMaxRange) { + maxValue = it.value().value; + maxValueIt = it; + } + ++intervalDataCount; + } else { // new pixel started + if (intervalDataCount >= 2) { // last pixel had multiple data points, consolidate them + // determine value pixel span and add as many points in interval to maintain certain vertical data density (this is specific to scatter plot): + double valuePixelSpan = qAbs(valueAxis->coordToPixel(minValue) - valueAxis->coordToPixel(maxValue)); + int dataModulo = qMax(1, qRound(intervalDataCount / (valuePixelSpan / 4.0))); // approximately every 4 value pixels one data point on average + QCPDataMap::const_iterator intervalIt = currentIntervalStart; + int c = 0; + while (intervalIt != it) { + if ((c % dataModulo == 0 || intervalIt == minValueIt || intervalIt == maxValueIt) && intervalIt.value().value > valueMinRange && intervalIt.value().value < valueMaxRange) { + scatterData->append(intervalIt.value()); + } + ++c; + ++intervalIt; + } + } else if (currentIntervalStart.value().value > valueMinRange && currentIntervalStart.value().value < valueMaxRange) { + scatterData->append(currentIntervalStart.value()); + } + minValue = it.value().value; + maxValue = it.value().value; + currentIntervalStart = it; + currentIntervalStartKey = keyAxis->pixelToCoord((int)(keyAxis->coordToPixel(it.key()) + reversedRound)); + if (keyEpsilonVariable) { + keyEpsilon = qAbs(currentIntervalStartKey - keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey) + 1.0 * reversedFactor)); + } + intervalDataCount = 1; + } + ++it; + } + // handle last interval: + if (intervalDataCount >= 2) { // last pixel had multiple data points, consolidate them + // determine value pixel span and add as many points in interval to maintain certain vertical data density (this is specific to scatter plot): + double valuePixelSpan = qAbs(valueAxis->coordToPixel(minValue) - valueAxis->coordToPixel(maxValue)); + int dataModulo = qMax(1, qRound(intervalDataCount / (valuePixelSpan / 4.0))); // approximately every 4 value pixels one data point on average + QCPDataMap::const_iterator intervalIt = currentIntervalStart; + int c = 0; + while (intervalIt != it) { + if ((c % dataModulo == 0 || intervalIt == minValueIt || intervalIt == maxValueIt) && intervalIt.value().value > valueMinRange && intervalIt.value().value < valueMaxRange) { + scatterData->append(intervalIt.value()); + } + ++c; + ++intervalIt; + } + } else if (currentIntervalStart.value().value > valueMinRange && currentIntervalStart.value().value < valueMaxRange) { + scatterData->append(currentIntervalStart.value()); + } + } + } else { // don't use adaptive sampling algorithm, transfer points one-to-one from the map into the output parameters + QVector *dataVector = 0; + if (lineData) { + dataVector = lineData; + } else if (scatterData) { + dataVector = scatterData; + } + if (dataVector) { + QCPDataMap::const_iterator it = lower; + QCPDataMap::const_iterator upperEnd = upper + 1; + dataVector->reserve(dataCount + 2); // +2 for possible fill end points + while (it != upperEnd) { + dataVector->append(it.value()); + ++it; + } + } + if (lineData && scatterData) { + *scatterData = *dataVector; } - } else if (currentIntervalStart.value().value > valueMinRange && currentIntervalStart.value().value < valueMaxRange) - scatterData->append(currentIntervalStart.value()); } - } else // don't use adaptive sampling algorithm, transfer points one-to-one from the map into the output parameters - { - QVector *dataVector = 0; - if (lineData) - dataVector = lineData; - else if (scatterData) - dataVector = scatterData; - if (dataVector) - { - QCPDataMap::const_iterator it = lower; - QCPDataMap::const_iterator upperEnd = upper+1; - dataVector->reserve(dataCount+2); // +2 for possible fill end points - while (it != upperEnd) - { - dataVector->append(it.value()); - ++it; - } - } - 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 @@ -15848,140 +15843,152 @@ void QCPGraph::getPreparedData(QVector *lineData, QVector *sca */ void QCPGraph::drawError(QCPPainter *painter, double x, double y, const QCPData &data) const { - if (qIsNaN(data.value)) - 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 (qIsNaN(data.value)) { + return; + } + 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::Vertical) - { - // 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)); + 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) { + // 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 + // draw value error vertically and key error horizontally + if (mErrorType == etKey || mErrorType == etBoth) { + a = keyAxis->coordToPixel(data.key - data.keyErrorMinus); + b = keyAxis->coordToPixel(data.key + data.keyErrorPlus); + if (keyAxis->rangeReversed()) { + qSwap(a, b); + } + // draw spine: + if (mErrorBarSkipSymbol) { + if (x - a > skipSymbolMargin) { // don't draw spine if error is so small it's within skipSymbolmargin + painter->drawLine(QLineF(a, y, x - skipSymbolMargin, y)); + } + if (b - x > skipSymbolMargin) { + painter->drawLine(QLineF(x + skipSymbolMargin, y, b, y)); + } + } else { + painter->drawLine(QLineF(a, y, b, y)); + } + // draw handles: + painter->drawLine(QLineF(a, y - barWidthHalf, a, y + barWidthHalf)); + painter->drawLine(QLineF(b, y - barWidthHalf, b, y + barWidthHalf)); + } + if (mErrorType == etValue || mErrorType == etBoth) { + a = valueAxis->coordToPixel(data.value - data.valueErrorMinus); + b = valueAxis->coordToPixel(data.value + data.valueErrorPlus); + if (valueAxis->rangeReversed()) { + qSwap(a, b); + } + // draw spine: + if (mErrorBarSkipSymbol) { + if (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 - { - // draw value error vertically and key error horizontally - if (mErrorType == etKey || mErrorType == etBoth) - { - a = keyAxis->coordToPixel(data.key-data.keyErrorMinus); - b = keyAxis->coordToPixel(data.key+data.keyErrorPlus); - if (keyAxis->rangeReversed()) - qSwap(a,b); - // draw spine: - if (mErrorBarSkipSymbol) - { - if (x-a > skipSymbolMargin) // don't draw spine if error is so small it's within skipSymbolmargin - painter->drawLine(QLineF(a, y, x-skipSymbolMargin, y)); - if (b-x > skipSymbolMargin) - painter->drawLine(QLineF(x+skipSymbolMargin, y, b, y)); - } else - painter->drawLine(QLineF(a, y, b, y)); - // draw handles: - painter->drawLine(QLineF(a, y-barWidthHalf, a, y+barWidthHalf)); - painter->drawLine(QLineF(b, y-barWidthHalf, b, y+barWidthHalf)); - } - if (mErrorType == etValue || mErrorType == etBoth) - { - a = valueAxis->coordToPixel(data.value-data.valueErrorMinus); - b = valueAxis->coordToPixel(data.value+data.valueErrorPlus); - if (valueAxis->rangeReversed()) - qSwap(a,b); - // draw spine: - if (mErrorBarSkipSymbol) - { - if (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)); - } - } } /*! \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 + 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 } /*! \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 @@ -15989,132 +15996,140 @@ void QCPGraph::getVisibleDataBounds(QCPDataMap::const_iterator &lower, QCPDataMa */ int QCPGraph::countDataInBounds(const QCPDataMap::const_iterator &lower, const QCPDataMap::const_iterator &upper, int maxCount) const { - if (upper == mData->constEnd() && lower == mData->constEnd()) - return 0; - QCPDataMap::const_iterator it = lower; - int count = 1; - while (it != upper && count < maxCount) - { - ++it; - ++count; - } - return count; + if (upper == mData->constEnd() && lower == mData->constEnd()) { + return 0; + } + QCPDataMap::const_iterator it = lower; + int count = 1; + while (it != upper && count < maxCount) { + ++it; + ++count; + } + 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 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. - + \see removeFillBasePoints, lowerFillBasePoint, upperFillBasePoint */ void QCPGraph::addFillBasePoints(QVector *lineData) const { - if (!mKeyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; } - if (!lineData) { qDebug() << Q_FUNC_INFO << "passed null as lineData"; return; } - if (lineData->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()); - } else - { - *lineData << upperFillBasePoint(lineData->last().x()); - *lineData << lowerFillBasePoint(lineData->first().x()); - } + if (!mKeyAxis) { + qDebug() << Q_FUNC_INFO << "invalid key axis"; + return; + } + if (!lineData) { + qDebug() << Q_FUNC_INFO << "passed null as lineData"; + return; + } + if (lineData->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()); + } else { + *lineData << upperFillBasePoint(lineData->last().x()); + *lineData << lowerFillBasePoint(lineData->first().x()); + } } /*! \internal - + removes the two points from \a lineData that were added by \ref addFillBasePoints. - + \see addFillBasePoints, lowerFillBasePoint, upperFillBasePoint */ void QCPGraph::removeFillBasePoints(QVector *lineData) const { - if (!lineData) { qDebug() << Q_FUNC_INFO << "passed null as lineData"; return; } - if (lineData->isEmpty()) return; - - lineData->remove(lineData->size()-2, 2); + if (!lineData) { + qDebug() << Q_FUNC_INFO << "passed null as lineData"; + return; + } + if (lineData->isEmpty()) { + return; + } + + lineData->remove(lineData->size() - 2, 2); } /*! \internal - + called by \ref addFillBasePoints to conveniently assign the point which closes the fill polygon on the lower side of the zero-value-line parallel to the key axis. The logarithmic axis scale case is a bit special, since the zero-value-line in pixel coordinates is in positive or negative infinity. So this case is handled separately by just closing the fill polygon on the axis which lies in the direction towards the zero value. - + \a lowerKey will be the the key (in pixels) of the returned point. Depending on whether the key axis is horizontal or vertical, \a lowerKey will end up as the x or y value of the returned point, respectively. - + \see upperFillBasePoint, addFillBasePoints */ QPointF QCPGraph::lowerFillBasePoint(double lowerKey) const { - QCPAxis *keyAxis = mKeyAxis.data(); - QCPAxis *valueAxis = mValueAxis.data(); - if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPointF(); } - - QPointF point; - if (valueAxis->scaleType() == QCPAxis::stLinear) - { - if (keyAxis->axisType() == QCPAxis::atLeft) - { - point.setX(valueAxis->coordToPixel(0)); - point.setY(lowerKey); - } else if (keyAxis->axisType() == QCPAxis::atRight) - { - point.setX(valueAxis->coordToPixel(0)); - point.setY(lowerKey); - } else if (keyAxis->axisType() == QCPAxis::atTop) - { - point.setX(lowerKey); - point.setY(valueAxis->coordToPixel(0)); - } else if (keyAxis->axisType() == QCPAxis::atBottom) - { - point.setX(lowerKey); - point.setY(valueAxis->coordToPixel(0)); + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + return QPointF(); } - } else // valueAxis->mScaleType == QCPAxis::stLogarithmic - { - // In logarithmic scaling we can't just draw to value zero so we just fill all the way - // to the axis which is in the direction towards zero - if (keyAxis->orientation() == Qt::Vertical) - { - if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) || - (valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis - point.setX(keyAxis->axisRect()->right()); - else - point.setX(keyAxis->axisRect()->left()); - point.setY(lowerKey); - } else if (keyAxis->axisType() == QCPAxis::atTop || keyAxis->axisType() == QCPAxis::atBottom) - { - point.setX(lowerKey); - if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) || - (valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis - point.setY(keyAxis->axisRect()->top()); - else - point.setY(keyAxis->axisRect()->bottom()); + + QPointF point; + if (valueAxis->scaleType() == QCPAxis::stLinear) { + if (keyAxis->axisType() == QCPAxis::atLeft) { + point.setX(valueAxis->coordToPixel(0)); + point.setY(lowerKey); + } else if (keyAxis->axisType() == QCPAxis::atRight) { + point.setX(valueAxis->coordToPixel(0)); + point.setY(lowerKey); + } else if (keyAxis->axisType() == QCPAxis::atTop) { + point.setX(lowerKey); + point.setY(valueAxis->coordToPixel(0)); + } else if (keyAxis->axisType() == QCPAxis::atBottom) { + point.setX(lowerKey); + point.setY(valueAxis->coordToPixel(0)); + } + } else { // valueAxis->mScaleType == QCPAxis::stLogarithmic + // In logarithmic scaling we can't just draw to value zero so we just fill all the way + // to the axis which is in the direction towards zero + if (keyAxis->orientation() == Qt::Vertical) { + if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) || + (valueAxis->range().upper > 0 && valueAxis->rangeReversed())) { // if range is negative, zero is on opposite side of key axis + point.setX(keyAxis->axisRect()->right()); + } else { + point.setX(keyAxis->axisRect()->left()); + } + point.setY(lowerKey); + } else if (keyAxis->axisType() == QCPAxis::atTop || keyAxis->axisType() == QCPAxis::atBottom) { + point.setX(lowerKey); + if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) || + (valueAxis->range().upper > 0 && valueAxis->rangeReversed())) { // if range is negative, zero is on opposite side of key axis + point.setY(keyAxis->axisRect()->top()); + } else { + point.setY(keyAxis->axisRect()->bottom()); + } + } } - } - return point; + return point; } /*! \internal - + called by \ref addFillBasePoints to conveniently assign the point which closes the fill polygon on the upper side of the zero-value-line parallel to the key axis. The logarithmic axis scale case is a bit special, since the zero-value-line in pixel coordinates is in positive or @@ -16124,62 +16139,59 @@ QPointF QCPGraph::lowerFillBasePoint(double lowerKey) const \a upperKey will be the the key (in pixels) of the returned point. Depending on whether the key axis is horizontal or vertical, \a upperKey will end up as the x or y value of the returned point, respectively. - + \see lowerFillBasePoint, addFillBasePoints */ QPointF QCPGraph::upperFillBasePoint(double upperKey) const { - QCPAxis *keyAxis = mKeyAxis.data(); - QCPAxis *valueAxis = mValueAxis.data(); - if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPointF(); } - - QPointF point; - if (valueAxis->scaleType() == QCPAxis::stLinear) - { - if (keyAxis->axisType() == QCPAxis::atLeft) - { - point.setX(valueAxis->coordToPixel(0)); - point.setY(upperKey); - } else if (keyAxis->axisType() == QCPAxis::atRight) - { - point.setX(valueAxis->coordToPixel(0)); - point.setY(upperKey); - } else if (keyAxis->axisType() == QCPAxis::atTop) - { - point.setX(upperKey); - point.setY(valueAxis->coordToPixel(0)); - } else if (keyAxis->axisType() == QCPAxis::atBottom) - { - point.setX(upperKey); - point.setY(valueAxis->coordToPixel(0)); + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + return QPointF(); } - } else // valueAxis->mScaleType == QCPAxis::stLogarithmic - { - // In logarithmic scaling we can't just draw to value 0 so we just fill all the way - // to the axis which is in the direction towards 0 - if (keyAxis->orientation() == Qt::Vertical) - { - if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) || - (valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis - point.setX(keyAxis->axisRect()->right()); - else - point.setX(keyAxis->axisRect()->left()); - point.setY(upperKey); - } else if (keyAxis->axisType() == QCPAxis::atTop || keyAxis->axisType() == QCPAxis::atBottom) - { - point.setX(upperKey); - if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) || - (valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis - point.setY(keyAxis->axisRect()->top()); - else - point.setY(keyAxis->axisRect()->bottom()); + + QPointF point; + if (valueAxis->scaleType() == QCPAxis::stLinear) { + if (keyAxis->axisType() == QCPAxis::atLeft) { + point.setX(valueAxis->coordToPixel(0)); + point.setY(upperKey); + } else if (keyAxis->axisType() == QCPAxis::atRight) { + point.setX(valueAxis->coordToPixel(0)); + point.setY(upperKey); + } else if (keyAxis->axisType() == QCPAxis::atTop) { + point.setX(upperKey); + point.setY(valueAxis->coordToPixel(0)); + } else if (keyAxis->axisType() == QCPAxis::atBottom) { + point.setX(upperKey); + point.setY(valueAxis->coordToPixel(0)); + } + } else { // valueAxis->mScaleType == QCPAxis::stLogarithmic + // In logarithmic scaling we can't just draw to value 0 so we just fill all the way + // to the axis which is in the direction towards 0 + if (keyAxis->orientation() == Qt::Vertical) { + if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) || + (valueAxis->range().upper > 0 && valueAxis->rangeReversed())) { // if range is negative, zero is on opposite side of key axis + point.setX(keyAxis->axisRect()->right()); + } else { + point.setX(keyAxis->axisRect()->left()); + } + point.setY(upperKey); + } else if (keyAxis->axisType() == QCPAxis::atTop || keyAxis->axisType() == QCPAxis::atBottom) { + point.setX(upperKey); + if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) || + (valueAxis->range().upper > 0 && valueAxis->rangeReversed())) { // if range is negative, zero is on opposite side of key axis + point.setY(keyAxis->axisRect()->top()); + } else { + point.setY(keyAxis->axisRect()->bottom()); + } + } } - } - return point; + return point; } /*! \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 @@ -16189,141 +16201,177 @@ QPointF QCPGraph::upperFillBasePoint(double upperKey) const */ const QPolygonF QCPGraph::getChannelFillPolygon(const QVector *lineData) const { - if (!mChannelFillGraph) - return QPolygonF(); - - QCPAxis *keyAxis = mKeyAxis.data(); - QCPAxis *valueAxis = mValueAxis.data(); - if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPolygonF(); } - if (!mChannelFillGraph.data()->mKeyAxis) { qDebug() << Q_FUNC_INFO << "channel fill target key axis invalid"; return QPolygonF(); } - - 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(); - QVector otherData; - mChannelFillGraph.data()->getPlotData(&otherData, 0); - 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); - - // pointers to be able to swap them, depending which data range needs cropping: - QVector *staticData = &thisData; - QVector *croppedData = &otherData; - - // crop both vectors to ranges in which the keys overlap (which coord is key, depends on axisType): - if (keyAxis->orientation() == Qt::Horizontal) - { - // x is key - // if an axis range is reversed, the data point keys will be descending. Reverse them, since following algorithm assumes ascending keys: - if (staticData->first().x() > staticData->last().x()) - { - int size = staticData->size(); - for (int i=0; ifirst().x() > croppedData->last().x()) - { - int size = croppedData->size(); - for (int i=0; ifirst().x() < croppedData->first().x()) // other one must be cropped - qSwap(staticData, croppedData); - int lowBound = findIndexBelowX(croppedData, staticData->first().x()); - if (lowBound == -1) return QPolygonF(); // key ranges have no overlap - croppedData->remove(0, lowBound); - // set lowest point of cropped data to fit exactly key position of first static data - // point via linear interpolation: - if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation - double slope; - if (croppedData->at(1).x()-croppedData->at(0).x() != 0) - slope = (croppedData->at(1).y()-croppedData->at(0).y())/(croppedData->at(1).x()-croppedData->at(0).x()); - else - slope = 0; - (*croppedData)[0].setY(croppedData->at(0).y()+slope*(staticData->first().x()-croppedData->at(0).x())); - (*croppedData)[0].setX(staticData->first().x()); - - // crop upper bound: - if (staticData->last().x() > croppedData->last().x()) // other one must be cropped - qSwap(staticData, croppedData); - int highBound = findIndexAboveX(croppedData, staticData->last().x()); - if (highBound == -1) return QPolygonF(); // key ranges have no overlap - croppedData->remove(highBound+1, croppedData->size()-(highBound+1)); - // set highest point of cropped data to fit exactly key position of last static data - // point via linear interpolation: - if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation - int li = croppedData->size()-1; // last index - if (croppedData->at(li).x()-croppedData->at(li-1).x() != 0) - slope = (croppedData->at(li).y()-croppedData->at(li-1).y())/(croppedData->at(li).x()-croppedData->at(li-1).x()); - else - slope = 0; - (*croppedData)[li].setY(croppedData->at(li-1).y()+slope*(staticData->last().x()-croppedData->at(li-1).x())); - (*croppedData)[li].setX(staticData->last().x()); - } else // mKeyAxis->orientation() == Qt::Vertical - { - // y is key - // similar to "x is key" but switched x,y. Further, lower/upper meaning is inverted compared to x, - // because in pixel coordinates, y increases from top to bottom, not bottom to top like data coordinate. - // if an axis range is reversed, the data point keys will be descending. Reverse them, since following algorithm assumes ascending keys: - if (staticData->first().y() < staticData->last().y()) - { - int size = staticData->size(); - for (int i=0; imKeyAxis) { + qDebug() << Q_FUNC_INFO << "channel fill target key axis invalid"; + return QPolygonF(); } - if (croppedData->first().y() < croppedData->last().y()) - { - int size = croppedData->size(); - for (int i=0; imKeyAxis.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) } - // crop lower bound: - if (staticData->first().y() > croppedData->first().y()) // other one must be cropped - qSwap(staticData, croppedData); - int lowBound = findIndexAboveY(croppedData, staticData->first().y()); - if (lowBound == -1) return QPolygonF(); // key ranges have no overlap - croppedData->remove(0, lowBound); - // set lowest point of cropped data to fit exactly key position of first static data - // point via linear interpolation: - if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation - double slope; - if (croppedData->at(1).y()-croppedData->at(0).y() != 0) // avoid division by zero in step plots - slope = (croppedData->at(1).x()-croppedData->at(0).x())/(croppedData->at(1).y()-croppedData->at(0).y()); - else - slope = 0; - (*croppedData)[0].setX(croppedData->at(0).x()+slope*(staticData->first().y()-croppedData->at(0).y())); - (*croppedData)[0].setY(staticData->first().y()); - - // crop upper bound: - if (staticData->last().y() < croppedData->last().y()) // other one must be cropped - qSwap(staticData, croppedData); - int highBound = findIndexBelowY(croppedData, staticData->last().y()); - if (highBound == -1) return QPolygonF(); // key ranges have no overlap - croppedData->remove(highBound+1, croppedData->size()-(highBound+1)); - // set highest point of cropped data to fit exactly key position of last static data - // point via linear interpolation: - if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation - int li = croppedData->size()-1; // last index - if (croppedData->at(li).y()-croppedData->at(li-1).y() != 0) // avoid division by zero in step plots - slope = (croppedData->at(li).x()-croppedData->at(li-1).x())/(croppedData->at(li).y()-croppedData->at(li-1).y()); - else - slope = 0; - (*croppedData)[li].setX(croppedData->at(li-1).x()+slope*(staticData->last().y()-croppedData->at(li-1).y())); - (*croppedData)[li].setY(staticData->last().y()); - } - - // return joined: - for (int i=otherData.size()-1; i>=0; --i) // insert reversed, otherwise the polygon will be twisted - thisData << otherData.at(i); - return QPolygonF(thisData); + + if (lineData->isEmpty()) { + return QPolygonF(); + } + QVector otherData; + mChannelFillGraph.data()->getPlotData(&otherData, 0); + 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; i < lineData->size(); ++i) { // don't use the vector<<(vector), it squeezes internally, which ruins the performance tuning with reserve() + thisData << lineData->at(i); + } + + // pointers to be able to swap them, depending which data range needs cropping: + QVector *staticData = &thisData; + QVector *croppedData = &otherData; + + // crop both vectors to ranges in which the keys overlap (which coord is key, depends on axisType): + if (keyAxis->orientation() == Qt::Horizontal) { + // x is key + // if an axis range is reversed, the data point keys will be descending. Reverse them, since following algorithm assumes ascending keys: + if (staticData->first().x() > staticData->last().x()) { + int size = staticData->size(); + for (int i = 0; i < size / 2; ++i) { + qSwap((*staticData)[i], (*staticData)[size - 1 - i]); + } + } + if (croppedData->first().x() > croppedData->last().x()) { + int size = croppedData->size(); + for (int i = 0; i < size / 2; ++i) { + qSwap((*croppedData)[i], (*croppedData)[size - 1 - i]); + } + } + // crop lower bound: + if (staticData->first().x() < croppedData->first().x()) { // other one must be cropped + qSwap(staticData, croppedData); + } + int lowBound = findIndexBelowX(croppedData, staticData->first().x()); + if (lowBound == -1) { + return QPolygonF(); // key ranges have no overlap + } + croppedData->remove(0, lowBound); + // set lowest point of cropped data to fit exactly key position of first static data + // point via linear interpolation: + if (croppedData->size() < 2) { + return QPolygonF(); // need at least two points for interpolation + } + double slope; + if (croppedData->at(1).x() - croppedData->at(0).x() != 0) { + slope = (croppedData->at(1).y() - croppedData->at(0).y()) / (croppedData->at(1).x() - croppedData->at(0).x()); + } else { + slope = 0; + } + (*croppedData)[0].setY(croppedData->at(0).y() + slope * (staticData->first().x() - croppedData->at(0).x())); + (*croppedData)[0].setX(staticData->first().x()); + + // crop upper bound: + if (staticData->last().x() > croppedData->last().x()) { // other one must be cropped + qSwap(staticData, croppedData); + } + int highBound = findIndexAboveX(croppedData, staticData->last().x()); + if (highBound == -1) { + return QPolygonF(); // key ranges have no overlap + } + croppedData->remove(highBound + 1, croppedData->size() - (highBound + 1)); + // set highest point of cropped data to fit exactly key position of last static data + // point via linear interpolation: + if (croppedData->size() < 2) { + return QPolygonF(); // need at least two points for interpolation + } + int li = croppedData->size() - 1; // last index + if (croppedData->at(li).x() - croppedData->at(li - 1).x() != 0) { + slope = (croppedData->at(li).y() - croppedData->at(li - 1).y()) / (croppedData->at(li).x() - croppedData->at(li - 1).x()); + } else { + slope = 0; + } + (*croppedData)[li].setY(croppedData->at(li - 1).y() + slope * (staticData->last().x() - croppedData->at(li - 1).x())); + (*croppedData)[li].setX(staticData->last().x()); + } else { // mKeyAxis->orientation() == Qt::Vertical + // y is key + // similar to "x is key" but switched x,y. Further, lower/upper meaning is inverted compared to x, + // because in pixel coordinates, y increases from top to bottom, not bottom to top like data coordinate. + // if an axis range is reversed, the data point keys will be descending. Reverse them, since following algorithm assumes ascending keys: + if (staticData->first().y() < staticData->last().y()) { + int size = staticData->size(); + for (int i = 0; i < size / 2; ++i) { + qSwap((*staticData)[i], (*staticData)[size - 1 - i]); + } + } + if (croppedData->first().y() < croppedData->last().y()) { + int size = croppedData->size(); + for (int i = 0; i < size / 2; ++i) { + qSwap((*croppedData)[i], (*croppedData)[size - 1 - i]); + } + } + // crop lower bound: + if (staticData->first().y() > croppedData->first().y()) { // other one must be cropped + qSwap(staticData, croppedData); + } + int lowBound = findIndexAboveY(croppedData, staticData->first().y()); + if (lowBound == -1) { + return QPolygonF(); // key ranges have no overlap + } + croppedData->remove(0, lowBound); + // set lowest point of cropped data to fit exactly key position of first static data + // point via linear interpolation: + if (croppedData->size() < 2) { + return QPolygonF(); // need at least two points for interpolation + } + double slope; + if (croppedData->at(1).y() - croppedData->at(0).y() != 0) { // avoid division by zero in step plots + slope = (croppedData->at(1).x() - croppedData->at(0).x()) / (croppedData->at(1).y() - croppedData->at(0).y()); + } else { + slope = 0; + } + (*croppedData)[0].setX(croppedData->at(0).x() + slope * (staticData->first().y() - croppedData->at(0).y())); + (*croppedData)[0].setY(staticData->first().y()); + + // crop upper bound: + if (staticData->last().y() < croppedData->last().y()) { // other one must be cropped + qSwap(staticData, croppedData); + } + int highBound = findIndexBelowY(croppedData, staticData->last().y()); + if (highBound == -1) { + return QPolygonF(); // key ranges have no overlap + } + croppedData->remove(highBound + 1, croppedData->size() - (highBound + 1)); + // set highest point of cropped data to fit exactly key position of last static data + // point via linear interpolation: + if (croppedData->size() < 2) { + return QPolygonF(); // need at least two points for interpolation + } + int li = croppedData->size() - 1; // last index + if (croppedData->at(li).y() - croppedData->at(li - 1).y() != 0) { // avoid division by zero in step plots + slope = (croppedData->at(li).x() - croppedData->at(li - 1).x()) / (croppedData->at(li).y() - croppedData->at(li - 1).y()); + } else { + slope = 0; + } + (*croppedData)[li].setX(croppedData->at(li - 1).x() + slope * (staticData->last().y() - croppedData->at(li - 1).y())); + (*croppedData)[li].setY(staticData->last().y()); + } + + // return joined: + for (int i = otherData.size() - 1; i >= 0; --i) { // insert reversed, otherwise the polygon will be twisted + thisData << otherData.at(i); + } + return QPolygonF(thisData); } /*! \internal - + Finds the smallest index of \a data, whose points x value is just above \a x. Assumes x values in \a data points are ordered ascending, as is the case when plotting with horizontal key axis. @@ -16331,135 +16379,129 @@ const QPolygonF QCPGraph::getChannelFillPolygon(const QVector *lineData */ int QCPGraph::findIndexAboveX(const QVector *data, double x) const { - for (int i=data->size()-1; i>=0; --i) - { - if (data->at(i).x() < x) - { - if (isize()-1) - return i+1; - else - return data->size()-1; + for (int i = data->size() - 1; i >= 0; --i) { + if (data->at(i).x() < x) { + if (i < data->size() - 1) { + return i + 1; + } else { + return data->size() - 1; + } + } } - } - return -1; + return -1; } /*! \internal - + Finds the highest index of \a data, whose points x value is just below \a x. Assumes x values in \a data points are ordered ascending, as is the case when plotting with horizontal key axis. - + Used to calculate the channel fill polygon, see \ref getChannelFillPolygon. */ int QCPGraph::findIndexBelowX(const QVector *data, double x) const { - for (int i=0; isize(); ++i) - { - if (data->at(i).x() > x) - { - if (i>0) - return i-1; - else - return 0; + for (int i = 0; i < data->size(); ++i) { + if (data->at(i).x() > x) { + if (i > 0) { + return i - 1; + } else { + return 0; + } + } } - } - return -1; + return -1; } /*! \internal - + Finds the smallest index of \a data, whose points y value is just above \a y. Assumes y values in \a data points are ordered descending, as is the case when plotting with vertical key axis. - + Used to calculate the channel fill polygon, see \ref getChannelFillPolygon. */ int QCPGraph::findIndexAboveY(const QVector *data, double y) const { - for (int i=0; isize(); ++i) - { - if (data->at(i).y() < y) - { - if (i>0) - return i-1; - else - return 0; + for (int i = 0; i < data->size(); ++i) { + if (data->at(i).y() < y) { + if (i > 0) { + return i - 1; + } else { + return 0; + } + } } - } - return -1; + return -1; } /*! \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. - + 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 { - if (mData->isEmpty()) - return -1.0; - if (mLineStyle == lsNone && mScatterStyle.isNone()) - return -1.0; - - // calculate minimum distances to graph representation: - if (mLineStyle == lsNone) - { - // no line displayed, only calculate distance to scatter points: - QVector scatterData; - getScatterPlotData(&scatterData); - if (scatterData.size() > 0) - { - 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 - { - double minDistSqr = std::numeric_limits::max(); - if (mLineStyle == lsImpulse) - { - // impulse plot differs from other line styles in that the lineData points are only pairwise connected: - for (int i=0; iisEmpty()) { + return -1.0; + } + if (mLineStyle == lsNone && mScatterStyle.isNone()) { + return -1.0; + } + + // calculate minimum distances to graph representation: + if (mLineStyle == lsNone) { + // no line displayed, only calculate distance to scatter points: + QVector scatterData; + getScatterPlotData(&scatterData); + if (scatterData.size() > 0) { + double minDistSqr = std::numeric_limits::max(); + for (int i = 0; i < scatterData.size(); ++i) { + double currentDistSqr = QVector2D(coordsToPixels(scatterData.at(i).key, scatterData.at(i).value) - pixelPoint).lengthSquared(); + if (currentDistSqr < minDistSqr) { + minDistSqr = currentDistSqr; + } + } + return qSqrt(minDistSqr); + } else { // no data available in view to calculate distance to + return -1.0; } - } else - { - // all other line plots (line and step) connect points directly: - 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 + double minDistSqr = std::numeric_limits::max(); + if (mLineStyle == lsImpulse) { + // impulse plot differs from other line styles in that the lineData points are only pairwise connected: + for (int i = 0; i < lineData.size() - 1; i += 2) { // iterate pairs + double currentDistSqr = distSqrToLine(lineData.at(i), lineData.at(i + 1), pixelPoint); + if (currentDistSqr < minDistSqr) { + minDistSqr = currentDistSqr; + } + } + } else { + // all other line plots (line and step) connect points directly: + for (int i = 0; i < lineData.size() - 1; ++i) { + double currentDistSqr = distSqrToLine(lineData.at(i), lineData.at(i + 1), pixelPoint); + if (currentDistSqr < minDistSqr) { + minDistSqr = currentDistSqr; + } + } + } + return qSqrt(minDistSqr); + } else if (lineData.size() > 0) { // only single data point, calculate distance to that point + return QVector2D(lineData.at(0) - pixelPoint).length(); + } else { // no data available in view to calculate distance to + return -1.0; } - } - return qSqrt(minDistSqr); - } else if (lineData.size() > 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; - } + } } /*! \internal - + Finds the highest index of \a data, whose points y value is just below \a y. Assumes y values in \a data points are ordered descending, as is the case when plotting with vertical key axis (since keys are ordered ascending). @@ -16468,263 +16510,220 @@ double QCPGraph::pointDistance(const QPointF &pixelPoint) const */ int QCPGraph::findIndexBelowY(const QVector *data, double y) const { - for (int i=data->size()-1; i>=0; --i) - { - if (data->at(i).y() > y) - { - if (isize()-1) - return i+1; - else - return data->size()-1; + for (int i = data->size() - 1; i >= 0; --i) { + if (data->at(i).y() > y) { + if (i < data->size() - 1) { + return i + 1; + } else { + return data->size() - 1; + } + } } - } - return -1; + return -1; } /* 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); + // 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); + // 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; + 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; } - if (current+currentErrorPlus > range.upper || !haveUpper) - { - range.upper = current+currentErrorPlus; - haveUpper = true; + } 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; } - } - ++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; + + 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; + 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; } - if (current+currentErrorPlus > range.upper || !haveUpper) - { - range.upper = current+currentErrorPlus; - haveUpper = true; + } 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; } - } - ++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; + + foundRange = haveLower && haveUpper; + return range; } @@ -16734,14 +16733,14 @@ 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 - + \see QCPCurveDataMap */ @@ -16749,9 +16748,9 @@ QCPRange QCPGraph::getValueRange(bool &foundRange, SignDomain inSignDomain, bool Constructs a curve data point with t, key and value set to zero. */ QCPCurveData::QCPCurveData() : - t(0), - key(0), - value(0) + t(0), + key(0), + value(0) { } @@ -16759,9 +16758,9 @@ QCPCurveData::QCPCurveData() : Constructs a curve data point with the specified \a t, \a key and \a value. */ QCPCurveData::QCPCurveData(double t, double key, double value) : - t(t), - key(key), - value(value) + t(t), + key(key), + value(value) { } @@ -16772,28 +16771,28 @@ QCPCurveData::QCPCurveData(double t, double key, double value) : /*! \class QCPCurve \brief A plottable representing a parametric curve in a plot. - + \image html QCPCurve.png - + Unlike QCPGraph, plottables of this type may have multiple points with the same key coordinate, so their visual representation can have \a loops. This is realized by introducing a third 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. - + 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 - + 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.) - + Usually, you first create an instance and add it to the customPlot: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcurve-creation-1 and then modify the properties of the newly created plottable, e.g.: @@ -16805,120 +16804,115 @@ QCPCurveData::QCPCurveData(double t, double key, double 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. */ QCPCurve::QCPCurve(QCPAxis *keyAxis, QCPAxis *valueAxis) : - QCPAbstractPlottable(keyAxis, valueAxis) + QCPAbstractPlottable(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; - - setScatterStyle(QCPScatterStyle()); - setLineStyle(lsLine); + 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; + + setScatterStyle(QCPScatterStyle()); + setLineStyle(lsLine); } QCPCurve::~QCPCurve() { - delete mData; + 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; - } + 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. */ void QCPCurve::setData(const QVector &t, const QVector &key, const QVector &value) { - 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); - } + mData->clear(); + int n = t.size(); + n = qMin(n, key.size()); + n = qMin(n, value.size()); + QCPCurveData newData; + for (int i = 0; i < n; ++i) { + newData.t = t[i]; + newData.key = key[i]; + newData.value = value[i]; + mData->insertMulti(newData.t, newData); + } } /*! \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. */ void QCPCurve::setData(const QVector &key, const QVector &value) { - mData->clear(); - int n = key.size(); - n = qMin(n, value.size()); - QCPCurveData newData; - for (int i=0; iinsertMulti(newData.t, newData); - } + mData->clear(); + int n = key.size(); + n = qMin(n, value.size()); + QCPCurveData newData; + for (int i = 0; i < n; ++i) { + newData.t = i; // no t vector given, so we assign t the index of the key/value pair + newData.key = key[i]; + newData.value = value[i]; + mData->insertMulti(newData.t, newData); + } } /*! Sets the visual appearance of single data points in the plot. If set to \ref QCPScatterStyle::ssNone, no scatter points are drawn (e.g. for line-only plots with appropriate line style). - + \see QCPScatterStyle, setLineStyle */ void QCPCurve::setScatterStyle(const QCPScatterStyle &style) { - mScatterStyle = style; + mScatterStyle = style; } /*! Sets how the single data points are connected in the plot or how they are represented visually apart from the scatter symbol. For scatter-only plots, set \a style to \ref lsNone and \ref setScatterStyle to the desired scatter style. - + \see setScatterStyle */ void QCPCurve::setLineStyle(QCPCurve::LineStyle style) { - mLineStyle = style; + mLineStyle = style; } /*! @@ -16927,7 +16921,7 @@ void QCPCurve::setLineStyle(QCPCurve::LineStyle style) */ void QCPCurve::addData(const QCPCurveDataMap &dataMap) { - mData->unite(dataMap); + mData->unite(dataMap); } /*! \overload @@ -16936,7 +16930,7 @@ void QCPCurve::addData(const QCPCurveDataMap &dataMap) */ void QCPCurve::addData(const QCPCurveData &data) { - mData->insertMulti(data.t, data); + mData->insertMulti(data.t, data); } /*! \overload @@ -16945,31 +16939,32 @@ void QCPCurve::addData(const QCPCurveData &data) */ 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); + QCPCurveData newData; + newData.t = t; + newData.key = key; + newData.value = value; + mData->insertMulti(newData.t, newData); } /*! \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. - + \see removeData */ void QCPCurve::addData(double key, double value) { - QCPCurveData newData; - if (!mData->isEmpty()) - newData.t = (mData->constEnd()-1).key()+1; - else - newData.t = 0; - newData.key = key; - newData.value = value; - mData->insertMulti(newData.t, newData); + QCPCurveData newData; + if (!mData->isEmpty()) { + newData.t = (mData->constEnd() - 1).key() + 1; + } else { + newData.t = 0; + } + newData.key = key; + newData.value = value; + mData->insertMulti(newData.t, newData); } /*! \overload @@ -16978,17 +16973,16 @@ void QCPCurve::addData(double key, double value) */ 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); - } + int n = ts.size(); + n = qMin(n, keys.size()); + n = qMin(n, values.size()); + QCPCurveData newData; + for (int i = 0; i < n; ++i) { + newData.t = ts[i]; + newData.key = keys[i]; + newData.value = values[i]; + mData->insertMulti(newData.t, newData); + } } /*! @@ -16997,9 +16991,10 @@ void QCPCurve::addData(const QVector &ts, const QVector &keys, c */ void QCPCurve::removeDataBefore(double t) { - QCPCurveDataMap::iterator it = mData->begin(); - while (it != mData->end() && it.key() < t) - it = mData->erase(it); + QCPCurveDataMap::iterator it = mData->begin(); + while (it != mData->end() && it.key() < t) { + it = mData->erase(it); + } } /*! @@ -17008,40 +17003,46 @@ void QCPCurve::removeDataBefore(double t) */ void QCPCurve::removeDataAfter(double t) { - if (mData->isEmpty()) return; - QCPCurveDataMap::iterator it = mData->upperBound(t); - while (it != mData->end()) - it = mData->erase(it); + 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); + 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); + mData->remove(t); } /*! @@ -17050,163 +17051,162 @@ void QCPCurve::removeData(double t) */ void QCPCurve::clearData() { - mData->clear(); + mData->clear(); } /* inherits documentation from base class */ double QCPCurve::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { - Q_UNUSED(details) - if ((onlySelectable && !mSelectable) || mData->isEmpty()) - return -1; - if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; } - - if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint())) - return pointDistance(pos); - else - return -1; + Q_UNUSED(details) + if ((onlySelectable && !mSelectable) || mData->isEmpty()) { + return -1; + } + if (!mKeyAxis || !mValueAxis) { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + return -1; + } + + if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint())) { + return pointDistance(pos); + } else { + return -1; + } } /* inherits documentation from base class */ void QCPCurve::draw(QCPPainter *painter) { - if (mData->isEmpty()) return; - - // allocate line vector: - QVector *lineData = new QVector; - - // 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) - { - applyFillAntialiasingHint(painter); - painter->setPen(Qt::NoPen); - painter->setBrush(mainBrush()); - painter->drawPolygon(QPolygonF(*lineData)); - } - - // draw curve line: - if (mLineStyle != lsNone && mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0) - { - applyDefaultAntialiasingHint(painter); - painter->setPen(mainPen()); - painter->setBrush(Qt::NoBrush); - // if drawing solid line and not in PDF, use much faster line drawing instead of polyline: - if (mParentPlot->plottingHints().testFlag(QCP::phFastPolylines) && - painter->pen().style() == Qt::SolidLine && - !painter->modes().testFlag(QCPPainter::pmVectorized) && - !painter->modes().testFlag(QCPPainter::pmNoCaching)) - { - int i = 0; - bool lastIsNan = false; - const int lineDataSize = lineData->size(); - while (i < lineDataSize && (qIsNaN(lineData->at(i).y()) || qIsNaN(lineData->at(i).x()))) // make sure first point is not NaN - ++i; - ++i; // because drawing works in 1 point retrospect - while (i < lineDataSize) - { - if (!qIsNaN(lineData->at(i).y()) && !qIsNaN(lineData->at(i).x())) // NaNs create a gap in the line - { - if (!lastIsNan) - painter->drawLine(lineData->at(i-1), lineData->at(i)); - else - lastIsNan = false; - } else - lastIsNan = true; - ++i; - } - } else - { - 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); + if (mData->isEmpty()) { + return; } - } - - // draw scatters: - if (!mScatterStyle.isNone()) - drawScatterPlot(painter, lineData); - - // free allocated line data: - delete lineData; + + // allocate line vector: + QVector *lineData = new QVector; + + // 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) { + applyFillAntialiasingHint(painter); + painter->setPen(Qt::NoPen); + painter->setBrush(mainBrush()); + painter->drawPolygon(QPolygonF(*lineData)); + } + + // draw curve line: + if (mLineStyle != lsNone && mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0) { + applyDefaultAntialiasingHint(painter); + painter->setPen(mainPen()); + painter->setBrush(Qt::NoBrush); + // if drawing solid line and not in PDF, use much faster line drawing instead of polyline: + if (mParentPlot->plottingHints().testFlag(QCP::phFastPolylines) && + painter->pen().style() == Qt::SolidLine && + !painter->modes().testFlag(QCPPainter::pmVectorized) && + !painter->modes().testFlag(QCPPainter::pmNoCaching)) { + int i = 0; + bool lastIsNan = false; + const int lineDataSize = lineData->size(); + while (i < lineDataSize && (qIsNaN(lineData->at(i).y()) || qIsNaN(lineData->at(i).x()))) { // make sure first point is not NaN + ++i; + } + ++i; // because drawing works in 1 point retrospect + while (i < lineDataSize) { + if (!qIsNaN(lineData->at(i).y()) && !qIsNaN(lineData->at(i).x())) { // NaNs create a gap in the line + if (!lastIsNan) { + painter->drawLine(lineData->at(i - 1), lineData->at(i)); + } else { + lastIsNan = false; + } + } else { + lastIsNan = true; + } + ++i; + } + } else { + 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); + } + } + + // draw scatters: + if (!mScatterStyle.isNone()) { + drawScatterPlot(painter, lineData); + } + + // free allocated line data: + delete lineData; } /* inherits documentation from base class */ void QCPCurve::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const { - // draw fill: - if (mBrush.style() != Qt::NoBrush) - { - applyFillAntialiasingHint(painter); - painter->fillRect(QRectF(rect.left(), rect.top()+rect.height()/2.0, rect.width(), rect.height()/3.0), mBrush); - } - // draw line vertically centered: - if (mLineStyle != lsNone) - { - applyDefaultAntialiasingHint(painter); - painter->setPen(mPen); - painter->drawLine(QLineF(rect.left(), rect.top()+rect.height()/2.0, rect.right()+5, rect.top()+rect.height()/2.0)); // +5 on x2 else last segment is missing from dashed/dotted pens - } - // draw scatter symbol: - if (!mScatterStyle.isNone()) - { - applyScattersAntialiasingHint(painter); - // scale scatter pixmap if it's too large to fit in legend icon rect: - if (mScatterStyle.shape() == QCPScatterStyle::ssPixmap && (mScatterStyle.pixmap().size().width() > rect.width() || mScatterStyle.pixmap().size().height() > rect.height())) - { - QCPScatterStyle scaledStyle(mScatterStyle); - scaledStyle.setPixmap(scaledStyle.pixmap().scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation)); - scaledStyle.applyTo(painter, mPen); - scaledStyle.drawShape(painter, QRectF(rect).center()); - } else - { - mScatterStyle.applyTo(painter, mPen); - mScatterStyle.drawShape(painter, QRectF(rect).center()); + // draw fill: + if (mBrush.style() != Qt::NoBrush) { + applyFillAntialiasingHint(painter); + painter->fillRect(QRectF(rect.left(), rect.top() + rect.height() / 2.0, rect.width(), rect.height() / 3.0), mBrush); + } + // draw line vertically centered: + if (mLineStyle != lsNone) { + applyDefaultAntialiasingHint(painter); + painter->setPen(mPen); + painter->drawLine(QLineF(rect.left(), rect.top() + rect.height() / 2.0, rect.right() + 5, rect.top() + rect.height() / 2.0)); // +5 on x2 else last segment is missing from dashed/dotted pens + } + // draw scatter symbol: + if (!mScatterStyle.isNone()) { + applyScattersAntialiasingHint(painter); + // scale scatter pixmap if it's too large to fit in legend icon rect: + if (mScatterStyle.shape() == QCPScatterStyle::ssPixmap && (mScatterStyle.pixmap().size().width() > rect.width() || mScatterStyle.pixmap().size().height() > rect.height())) { + QCPScatterStyle scaledStyle(mScatterStyle); + scaledStyle.setPixmap(scaledStyle.pixmap().scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation)); + scaledStyle.applyTo(painter, mPen); + scaledStyle.drawShape(painter, QRectF(rect).center()); + } else { + mScatterStyle.applyTo(painter, mPen); + mScatterStyle.drawShape(painter, QRectF(rect).center()); + } } - } } /*! \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. */ void QCPCurve::drawScatterPlot(QCPPainter *painter, const QVector *pointData) 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)); + // draw scatter point symbols: + applyScattersAntialiasingHint(painter); + mScatterStyle.applyTo(painter, mPen); + for (int i = 0; i < pointData->size(); ++i) + if (!qIsNaN(pointData->at(i).x()) && !qIsNaN(pointData->at(i).y())) { + mScatterStyle.drawShape(painter, pointData->at(i)); + } } /*! \internal - + called by QCPCurve::draw to generate a point vector (in pixel coordinates) which represents the line of the curve. @@ -17214,146 +17214,139 @@ void QCPCurve::drawScatterPlot(QCPPainter *painter, const QVector *poin are projected onto a rectangle slightly larger than the visible axis rect and simplified regarding point count. The algorithm makes sure to preserve appearance of lines and fills inside the visible axis rect by generating new temporary points on the outer rect if necessary. - + Methods that are also involved in the algorithm are: \ref getRegion, \ref getOptimizedPoint, \ref getOptimizedCornerPoints \ref mayTraverse, \ref getTraverse, \ref getTraverseCornerPoints. */ void QCPCurve::getCurveData(QVector *lineData) const { - 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); - 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()) - { - currentRegion = getRegion(it.value().key, it.value().value, rectLeft, rectTop, rectRight, rectBottom); - 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 - { - 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)); - // 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); - } else if (mayTraverse(prevRegion, currentRegion) && - getTraverse(prevIt.value().key, prevIt.value().value, it.value().key, it.value().value, rectLeft, rectTop, rectRight, rectBottom, 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()) - { - *lineData << beforeTraverseCornerPoints; - lineData->append(crossA); - lineData->append(crossB); - *lineData << afterTraverseCornerPoints; - } else - { - lineData->append(crossB); - *lineData << 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); - } - } 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); - 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)); - } - } else // region didn't change - { - if (currentRegion == 5) // still in R, keep adding original points - { - lineData->append(coordsToPixels(it.value().key, it.value().value)); - } else // still outside R, no need to add anything - { - // see how this is not doing anything? That's the main optimization... - } + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + return; } - prevIt = it; - prevRegion = currentRegion; - ++it; - } - *lineData << trailingPoints; + + // 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); + 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()) { + currentRegion = getRegion(it.value().key, it.value().value, rectLeft, rectTop, rectRight, rectBottom); + 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 + 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)); + // 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); + } else if (mayTraverse(prevRegion, currentRegion) && + getTraverse(prevIt.value().key, prevIt.value().value, it.value().key, it.value().value, rectLeft, rectTop, rectRight, rectBottom, 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()) { + *lineData << beforeTraverseCornerPoints; + lineData->append(crossA); + lineData->append(crossB); + *lineData << afterTraverseCornerPoints; + } else { + lineData->append(crossB); + *lineData << 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); + } + } 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); + } 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)); + } + } else { // region didn't change + if (currentRegion == 5) { // still in R, keep adding original points + lineData->append(coordsToPixels(it.value().key, it.value().value)); + } else { // still outside R, no need to add anything + // see how this is not doing anything? That's the main optimization... + } + } + prevIt = it; + prevRegion = currentRegion; + ++it; + } + *lineData << trailingPoints; } /*! \internal - + This function is part of the curve optimization algorithm of \ref getCurveData. - + 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: - +
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 { - if (x < rectLeft) // region 123 - { - if (y > rectTop) - return 1; - else if (y < rectBottom) - return 3; - else - return 2; - } else if (x > rectRight) // region 789 - { - if (y > rectTop) - return 7; - else if (y < rectBottom) - return 9; - else - return 8; - } else // region 456 - { - if (y > rectTop) - return 4; - else if (y < rectBottom) - return 6; - else - return 5; - } + if (x < rectLeft) { // region 123 + if (y > rectTop) { + return 1; + } else if (y < rectBottom) { + return 3; + } else { + return 2; + } + } else if (x > rectRight) { // region 789 + if (y > rectTop) { + return 7; + } else if (y < rectBottom) { + return 9; + } else { + return 8; + } + } else { // region 456 + if (y > rectTop) { + return 4; + } else if (y < rectBottom) { + return 6; + } else { + return 5; + } + } } /*! \internal - + This function is part of the curve optimization algorithm of \ref getCurveData. - + 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 the line connecting (\a key, \a value) with (\a otherKey, \a otherValue). - + It returns the intersection point of the segment with the border of region 5. - + For this function it doesn't matter whether (\a key, \a value) is the point inside region 5 or whether it's (\a otherKey, \a otherValue), i.e. whether the segment is coming from region 5 or leaving it. It is important though that \a otherRegion correctly identifies the other region not @@ -17361,97 +17354,83 @@ int QCPCurve::getRegion(double x, double y, double rectLeft, double rectTop, dou */ QPointF QCPCurve::getOptimizedPoint(int otherRegion, double otherKey, double otherValue, double key, double value, double rectLeft, double rectTop, double rectRight, double rectBottom) const { - double intersectKey = rectLeft; // initial value is just fail-safe - double intersectValue = rectTop; // initial value is just fail-safe - switch (otherRegion) - { - case 1: // top and left edge - { - intersectValue = rectTop; - intersectKey = otherKey + (key-otherKey)/(value-otherValue)*(intersectValue-otherValue); - if (intersectKey < rectLeft || intersectKey > rectRight) // doesn't intersect, so must intersect other: - { - intersectKey = rectLeft; - intersectValue = otherValue + (value-otherValue)/(key-otherKey)*(intersectKey-otherKey); - } - break; + double intersectKey = rectLeft; // initial value is just fail-safe + double intersectValue = rectTop; // initial value is just fail-safe + switch (otherRegion) { + case 1: { // top and left edge + intersectValue = rectTop; + intersectKey = otherKey + (key - otherKey) / (value - otherValue) * (intersectValue - otherValue); + if (intersectKey < rectLeft || intersectKey > rectRight) { // doesn't intersect, so must intersect other: + intersectKey = rectLeft; + intersectValue = otherValue + (value - otherValue) / (key - otherKey) * (intersectKey - otherKey); + } + break; + } + case 2: { // left edge + intersectKey = rectLeft; + intersectValue = otherValue + (value - otherValue) / (key - otherKey) * (intersectKey - otherKey); + break; + } + case 3: { // bottom and left edge + intersectValue = rectBottom; + intersectKey = otherKey + (key - otherKey) / (value - otherValue) * (intersectValue - otherValue); + if (intersectKey < rectLeft || intersectKey > rectRight) { // doesn't intersect, so must intersect other: + intersectKey = rectLeft; + intersectValue = otherValue + (value - otherValue) / (key - otherKey) * (intersectKey - otherKey); + } + break; + } + case 4: { // top edge + intersectValue = rectTop; + intersectKey = otherKey + (key - otherKey) / (value - otherValue) * (intersectValue - otherValue); + break; + } + case 5: { + break; // case 5 shouldn't happen for this function but we add it anyway to prevent potential discontinuity in branch table + } + case 6: { // bottom edge + intersectValue = rectBottom; + intersectKey = otherKey + (key - otherKey) / (value - otherValue) * (intersectValue - otherValue); + break; + } + case 7: { // top and right edge + intersectValue = rectTop; + intersectKey = otherKey + (key - otherKey) / (value - otherValue) * (intersectValue - otherValue); + if (intersectKey < rectLeft || intersectKey > rectRight) { // doesn't intersect, so must intersect other: + intersectKey = rectRight; + intersectValue = otherValue + (value - otherValue) / (key - otherKey) * (intersectKey - otherKey); + } + break; + } + case 8: { // right edge + intersectKey = rectRight; + intersectValue = otherValue + (value - otherValue) / (key - otherKey) * (intersectKey - otherKey); + break; + } + case 9: { // bottom and right edge + intersectValue = rectBottom; + intersectKey = otherKey + (key - otherKey) / (value - otherValue) * (intersectValue - otherValue); + if (intersectKey < rectLeft || intersectKey > rectRight) { // doesn't intersect, so must intersect other: + intersectKey = rectRight; + intersectValue = otherValue + (value - otherValue) / (key - otherKey) * (intersectKey - otherKey); + } + break; + } } - case 2: // left edge - { - intersectKey = rectLeft; - intersectValue = otherValue + (value-otherValue)/(key-otherKey)*(intersectKey-otherKey); - break; - } - case 3: // bottom and left edge - { - intersectValue = rectBottom; - intersectKey = otherKey + (key-otherKey)/(value-otherValue)*(intersectValue-otherValue); - if (intersectKey < rectLeft || intersectKey > rectRight) // doesn't intersect, so must intersect other: - { - intersectKey = rectLeft; - intersectValue = otherValue + (value-otherValue)/(key-otherKey)*(intersectKey-otherKey); - } - break; - } - case 4: // top edge - { - intersectValue = rectTop; - intersectKey = otherKey + (key-otherKey)/(value-otherValue)*(intersectValue-otherValue); - break; - } - case 5: - { - break; // case 5 shouldn't happen for this function but we add it anyway to prevent potential discontinuity in branch table - } - case 6: // bottom edge - { - intersectValue = rectBottom; - intersectKey = otherKey + (key-otherKey)/(value-otherValue)*(intersectValue-otherValue); - break; - } - case 7: // top and right edge - { - intersectValue = rectTop; - intersectKey = otherKey + (key-otherKey)/(value-otherValue)*(intersectValue-otherValue); - if (intersectKey < rectLeft || intersectKey > rectRight) // doesn't intersect, so must intersect other: - { - intersectKey = rectRight; - intersectValue = otherValue + (value-otherValue)/(key-otherKey)*(intersectKey-otherKey); - } - break; - } - case 8: // right edge - { - intersectKey = rectRight; - intersectValue = otherValue + (value-otherValue)/(key-otherKey)*(intersectKey-otherKey); - break; - } - case 9: // bottom and right edge - { - intersectValue = rectBottom; - intersectKey = otherKey + (key-otherKey)/(value-otherValue)*(intersectValue-otherValue); - if (intersectKey < rectLeft || intersectKey > rectRight) // doesn't intersect, so must intersect other: - { - intersectKey = rectRight; - intersectValue = otherValue + (value-otherValue)/(key-otherKey)*(intersectKey-otherKey); - } - break; - } - } - return coordsToPixels(intersectKey, intersectValue); + return coordsToPixels(intersectKey, intersectValue); } /*! \internal - + This function is part of the curve optimization algorithm of \ref getCurveData. - + 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 doesn't unintentionally cut through the visible area of the axis rect and create plot artifacts. This method provides these points that must be added, assuming the original segment doesn't start, end, or traverse region 5. (Corner points where region 5 is traversed are calculated by \ref getTraverseCornerPoints.) - + For example, consider a segment which directly goes from region 4 to 2 but originally is far out to the top left such that it doesn't cross region 5. Naively optimizing these points by projecting them on the top and left borders of region 5 will create a segment that surely crosses @@ -17461,554 +17440,778 @@ QPointF QCPCurve::getOptimizedPoint(int otherRegion, double otherKey, double oth */ 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 result; - switch (prevRegion) - { - case 1: - { - 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 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); } - else - { result << coordsToPixels(rectLeft, rectTop) << coordsToPixels(rectRight, rectTop); result.append(result.last()); result << coordsToPixels(rectRight, rectBottom); } - break; + QVector result; + switch (prevRegion) { + case 1: { + 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 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); + } else { + result << coordsToPixels(rectLeft, rectTop) << coordsToPixels(rectRight, rectTop); + result.append(result.last()); + result << coordsToPixels(rectRight, rectBottom); + } + break; + } + } + break; } - } - break; - } - case 2: - { - 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; } - } - break; - } - case 3: - { - 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 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); } - else - { result << coordsToPixels(rectLeft, rectBottom) << coordsToPixels(rectLeft, rectTop); result.append(result.last()); result << coordsToPixels(rectRight, rectTop); } - break; + case 2: { + 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; + } + } + break; } - } - break; - } - case 4: - { - 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; } - } - break; - } - case 5: - { - 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; } - } - break; - } - case 6: - { - 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; } - } - break; - } - case 7: - { - 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 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); } - else - { result << coordsToPixels(rectRight, rectTop) << coordsToPixels(rectLeft, rectTop); result.append(result.last()); result << coordsToPixels(rectLeft, rectBottom); } - break; + case 3: { + 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 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); + } else { + result << coordsToPixels(rectLeft, rectBottom) << coordsToPixels(rectLeft, rectTop); + result.append(result.last()); + result << coordsToPixels(rectRight, rectTop); + } + break; + } + } + break; } - } - break; - } - case 8: - { - 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; } - } - break; - } - case 9: - { - 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 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); } - else - { result << coordsToPixels(rectRight, rectBottom) << coordsToPixels(rectRight, rectTop); result.append(result.last()); result << coordsToPixels(rectLeft, rectTop); } - break; + case 4: { + 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; + } + } + break; + } + case 5: { + 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; + } + } + break; + } + case 6: { + 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; + } + } + break; + } + case 7: { + 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 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); + } else { + result << coordsToPixels(rectRight, rectTop) << coordsToPixels(rectLeft, rectTop); + result.append(result.last()); + result << coordsToPixels(rectLeft, rectBottom); + } + break; + } + } + break; + } + case 8: { + 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; + } + } + break; + } + case 9: { + 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 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); + } else { + result << coordsToPixels(rectRight, rectBottom) << coordsToPixels(rectRight, rectTop); + result.append(result.last()); + result << coordsToPixels(rectLeft, rectTop); + } + break; + } + } + break; } - } - break; } - } - return result; + return result; } /*! \internal - + This function is part of the curve optimization algorithm of \ref getCurveData. - + 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 nor \a currentRegion is 5 itself. - + If this method returns false, the segment for sure doesn't pass region 5. If it returns true, the segment may or may not pass region 5 and a more fine-grained calculation must be used (\ref getTraverse). */ bool QCPCurve::mayTraverse(int prevRegion, int currentRegion) const { - switch (prevRegion) - { - case 1: - { - switch (currentRegion) - { - case 4: - case 7: - case 2: - case 3: return false; - default: return true; - } + switch (prevRegion) { + case 1: { + switch (currentRegion) { + case 4: + case 7: + case 2: + case 3: + return false; + default: + return true; + } + } + case 2: { + switch (currentRegion) { + case 1: + case 3: + return false; + default: + return true; + } + } + case 3: { + switch (currentRegion) { + case 1: + case 2: + case 6: + case 9: + return false; + default: + return true; + } + } + case 4: { + switch (currentRegion) { + case 1: + case 7: + return false; + default: + return true; + } + } + case 5: + return false; // should never occur + case 6: { + switch (currentRegion) { + case 3: + case 9: + return false; + default: + return true; + } + } + case 7: { + switch (currentRegion) { + case 1: + case 4: + case 8: + case 9: + return false; + default: + return true; + } + } + case 8: { + switch (currentRegion) { + case 7: + case 9: + return false; + default: + return true; + } + } + case 9: { + switch (currentRegion) { + case 3: + case 6: + case 8: + case 7: + return false; + default: + return true; + } + } + default: + return true; } - case 2: - { - switch (currentRegion) - { - case 1: - case 3: return false; - default: return true; - } - } - case 3: - { - switch (currentRegion) - { - case 1: - case 2: - case 6: - case 9: return false; - default: return true; - } - } - case 4: - { - switch (currentRegion) - { - case 1: - case 7: return false; - default: return true; - } - } - case 5: return false; // should never occur - case 6: - { - switch (currentRegion) - { - case 3: - case 9: return false; - default: return true; - } - } - case 7: - { - switch (currentRegion) - { - case 1: - case 4: - case 8: - case 9: return false; - default: return true; - } - } - case 8: - { - switch (currentRegion) - { - case 7: - case 9: return false; - default: return true; - } - } - case 9: - { - switch (currentRegion) - { - case 3: - case 6: - case 8: - case 7: return false; - default: return true; - } - } - default: return true; - } } /*! \internal - + This function is part of the curve optimization algorithm of \ref getCurveData. - + 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 region 5. - + The return value of this method indicates whether the segment actually traverses region 5 or not. - + 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 { - 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)); - } 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)); - } 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)); - // check bottom of rect: - gamma = prevKey + (rectBottom-prevValue)*keyPerValue; - if (gamma >= rectLeft && gamma <= rectRight) - intersections.append(QPointF(gamma, rectBottom)); - double valuePerKey = 1.0/keyPerValue; - // check left of rect: - gamma = prevValue + (rectLeft-prevKey)*valuePerKey; - if (gamma >= rectBottom && gamma <= rectTop) - intersections.append(QPointF(rectLeft, gamma)); - // check right of rect: - gamma = prevValue + (rectRight-prevKey)*valuePerKey; - if (gamma >= rectBottom && gamma <= rectTop) - intersections.append(QPointF(rectRight, gamma)); - } - - // handle cases where found points isn't exactly 2: - if (intersections.size() > 2) - { - // line probably goes through corner of rect, and we got duplicate points there. single out the point pair with greatest distance in between: - double distSqrMax = 0; - QPointF pv1, pv2; - for (int i=0; i distSqrMax) - { - pv1 = intersections.at(i); - pv2 = intersections.at(k); - distSqrMax = distSqr; + 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)); + } 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)); + } 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)); + } + // check bottom of rect: + gamma = prevKey + (rectBottom - prevValue) * keyPerValue; + if (gamma >= rectLeft && gamma <= rectRight) { + intersections.append(QPointF(gamma, rectBottom)); + } + double valuePerKey = 1.0 / keyPerValue; + // check left of rect: + gamma = prevValue + (rectLeft - prevKey) * valuePerKey; + if (gamma >= rectBottom && gamma <= rectTop) { + intersections.append(QPointF(rectLeft, gamma)); + } + // check right of rect: + gamma = prevValue + (rectRight - prevKey) * valuePerKey; + if (gamma >= rectBottom && gamma <= rectTop) { + intersections.append(QPointF(rectRight, gamma)); } - } } - intersections = QList() << pv1 << pv2; - } else if (intersections.size() != 2) - { - // one or even zero points found (shouldn't happen unless line perfectly tangent to corner), no need to draw segment - return false; - } - - // possibly re-sort points so optimized point segment has same direction as original segment: - if ((key-prevKey)*(intersections.at(1).x()-intersections.at(0).x()) + (value-prevValue)*(intersections.at(1).y()-intersections.at(0).y()) < 0) // scalar product of both segments < 0 -> opposite direction - intersections.move(0, 1); - crossA = coordsToPixels(intersections.at(0).x(), intersections.at(0).y()); - crossB = coordsToPixels(intersections.at(1).x(), intersections.at(1).y()); - return true; + + // handle cases where found points isn't exactly 2: + if (intersections.size() > 2) { + // line probably goes through corner of rect, and we got duplicate points there. single out the point pair with greatest distance in between: + double distSqrMax = 0; + QPointF pv1, pv2; + for (int i = 0; i < intersections.size() - 1; ++i) { + for (int k = i + 1; k < intersections.size(); ++k) { + QPointF distPoint = intersections.at(i) - intersections.at(k); + double distSqr = distPoint.x() * distPoint.x() + distPoint.y() + distPoint.y(); + if (distSqr > distSqrMax) { + pv1 = intersections.at(i); + pv2 = intersections.at(k); + distSqrMax = distSqr; + } + } + } + intersections = QList() << pv1 << pv2; + } else if (intersections.size() != 2) { + // one or even zero points found (shouldn't happen unless line perfectly tangent to corner), no need to draw segment + return false; + } + + // possibly re-sort points so optimized point segment has same direction as original segment: + if ((key - prevKey) * (intersections.at(1).x() - intersections.at(0).x()) + (value - prevValue) * (intersections.at(1).y() - intersections.at(0).y()) < 0) { // scalar product of both segments < 0 -> opposite direction + intersections.move(0, 1); + } + crossA = coordsToPixels(intersections.at(0).x(), intersections.at(0).y()); + crossB = coordsToPixels(intersections.at(1).x(), intersections.at(1).y()); + return true; } /*! \internal - + This function is part of the curve optimization algorithm of \ref getCurveData. - + 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. - + In certain situations it is not sufficient to merely generate the entry and exit points of the segment into/out of region 5, as \ref getTraverse provides. It may happen that a single segment, in addition to traversing region 5, skips another region outside of region 5, which makes it necessary to add an optimized corner point there (very similar to the job \ref getOptimizedCornerPoints does for segments that are completely in outside regions and don't traverse 5). - + As an example, consider a segment going from region 1 to region 6, traversing the lower left corner of region 5. In this configuration, the segment additionally crosses the border between region 1 and 2 before entering region 5. This makes it necessary to add an additional point in the top left corner, before adding the optimized traverse points. So in this case, the output parameter \a beforeTraverse will contain the top left corner point, and \a afterTraverse will be empty. - + In some cases, such as when going from region 1 to 9, it may even be necessary to add additional 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 { - switch (prevRegion) - { - case 1: - { - 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; } - } - break; + switch (prevRegion) { + case 1: { + 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; + } + } + break; + } + case 2: { + switch (currentRegion) { + case 7: { + afterTraverse << coordsToPixels(rectRight, rectTop); + break; + } + case 9: { + afterTraverse << coordsToPixels(rectRight, rectBottom); + break; + } + } + break; + } + case 3: { + 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; + } + } + break; + } + case 4: { + switch (currentRegion) { + case 3: { + afterTraverse << coordsToPixels(rectLeft, rectBottom); + break; + } + case 9: { + afterTraverse << coordsToPixels(rectRight, rectBottom); + break; + } + } + break; + } + case 5: { + break; // shouldn't happen because this method only handles full traverses + } + case 6: { + switch (currentRegion) { + case 1: { + afterTraverse << coordsToPixels(rectLeft, rectTop); + break; + } + case 7: { + afterTraverse << coordsToPixels(rectRight, rectTop); + break; + } + } + break; + } + case 7: { + 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; + } + } + break; + } + case 8: { + switch (currentRegion) { + case 1: { + afterTraverse << coordsToPixels(rectLeft, rectTop); + break; + } + case 3: { + afterTraverse << coordsToPixels(rectLeft, rectBottom); + break; + } + } + break; + } + case 9: { + 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; + } + } + break; + } } - case 2: - { - switch (currentRegion) - { - case 7: { afterTraverse << coordsToPixels(rectRight, rectTop); break; } - case 9: { afterTraverse << coordsToPixels(rectRight, rectBottom); break; } - } - break; - } - case 3: - { - 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; } - } - break; - } - case 4: - { - switch (currentRegion) - { - case 3: { afterTraverse << coordsToPixels(rectLeft, rectBottom); break; } - case 9: { afterTraverse << coordsToPixels(rectRight, rectBottom); break; } - } - break; - } - case 5: { break; } // shouldn't happen because this method only handles full traverses - case 6: - { - switch (currentRegion) - { - case 1: { afterTraverse << coordsToPixels(rectLeft, rectTop); break; } - case 7: { afterTraverse << coordsToPixels(rectRight, rectTop); break; } - } - break; - } - case 7: - { - 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; } - } - break; - } - case 8: - { - switch (currentRegion) - { - case 1: { afterTraverse << coordsToPixels(rectLeft, rectTop); break; } - case 3: { afterTraverse << coordsToPixels(rectLeft, rectBottom); break; } - } - break; - } - case 9: - { - 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; } - } - break; - } - } } /*! \internal - + 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. */ double QCPCurve::pointDistance(const QPointF &pixelPoint) const { - if (mData->isEmpty()) - { - 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(); - } - - // calculate minimum distance to line segments: - QVector *lineData = new QVector; - getCurveData(lineData); - double minDistSqr = std::numeric_limits::max(); - for (int i=0; isize()-1; ++i) - { - double currentDistSqr = distSqrToLine(lineData->at(i), lineData->at(i+1), pixelPoint); - if (currentDistSqr < minDistSqr) - minDistSqr = currentDistSqr; - } - delete lineData; - return qSqrt(minDistSqr); + if (mData->isEmpty()) { + 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(); + } + + // calculate minimum distance to line segments: + QVector *lineData = new QVector; + getCurveData(lineData); + double minDistSqr = std::numeric_limits::max(); + for (int i = 0; i < lineData->size() - 1; ++i) { + double currentDistSqr = distSqrToLine(lineData->at(i), lineData->at(i + 1), pixelPoint); + if (currentDistSqr < minDistSqr) { + minDistSqr = currentDistSqr; + } + } + delete lineData; + return qSqrt(minDistSqr); } /* inherits documentation from base class */ QCPRange QCPCurve::getKeyRange(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().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; + QCPRange range; + bool haveLower = false; + bool haveUpper = false; + + double current; + + QCPCurveDataMap::const_iterator it = mData->constBegin(); + 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; + } + } } - if (current > range.upper || !haveUpper) - { - range.upper = current; - haveUpper = true; - } - } + ++it; } - ++it; - } - - foundRange = haveLower && haveUpper; - return range; + + 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; + 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; + } + } } - if (current > range.upper || !haveUpper) - { - range.upper = current; - haveUpper = true; - } - } + ++it; } - ++it; - } - - foundRange = haveLower && haveUpper; - return range; + + foundRange = haveLower && haveUpper; + return range; } @@ -18018,34 +18221,34 @@ QCPRange QCPCurve::getValueRange(bool &foundRange, SignDomain inSignDomain) cons /*! \class QCPBarsGroup \brief Groups multiple QCPBars together so they appear side by side - + \image html QCPBarsGroup.png - + When showing multiple QCPBars in one plot which have bars at identical keys, it may be desirable to have them appearing next to each other at each key. This is what adding the respective QCPBars plottables to a QCPBarsGroup achieves. (An alternative approach is to stack them on top of each other, see \ref QCPBars::moveAbove.) - + \section qcpbarsgroup-usage Usage - + To add a QCPBars plottable to the group, create a new group and then add the respective bars intances: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpbarsgroup-creation Alternatively to appending to the group like shown above, you can also set the group on the QCPBars plottable via \ref QCPBars::setBarsGroup. - + The spacing between the bars can be configured via \ref setSpacingType and \ref setSpacing. The bars in this group appear in the plot in the order they were appended. To insert a bars plottable at a certain index position, or to reposition a bars plottable which is already in the group, use \ref insert. - + To remove specific bars from the group, use either \ref remove or call \ref QCPBars::setBarsGroup "QCPBars::setBarsGroup(0)" on the respective bars plottable. - + To clear the entire group, call \ref clear, or simply delete the group. - + \section qcpbarsgroup-example Example - + The image above is generated with the following code: \snippet documentation/doc-image-generator/mainwindow.cpp qcpbarsgroup-example */ @@ -18053,29 +18256,29 @@ QCPRange QCPCurve::getValueRange(bool &foundRange, SignDomain inSignDomain) cons /* start of documentation of inline functions */ /*! \fn QList QCPBarsGroup::bars() const - + Returns all bars currently in this group. - + \see bars(int index) */ /*! \fn int QCPBarsGroup::size() const - + Returns the number of QCPBars plottables that are part of this group. - + */ /*! \fn bool QCPBarsGroup::isEmpty() const - + Returns whether this bars group is empty. - + \see size */ /*! \fn bool QCPBarsGroup::contains(QCPBars *bars) - + Returns whether the specified \a bars plottable is part of this group. - + */ /* end of documentation of inline functions */ @@ -18084,28 +18287,28 @@ QCPRange QCPCurve::getValueRange(bool &foundRange, SignDomain inSignDomain) cons Constructs a new bars group for the specified QCustomPlot instance. */ QCPBarsGroup::QCPBarsGroup(QCustomPlot *parentPlot) : - QObject(parentPlot), - mParentPlot(parentPlot), - mSpacingType(stAbsolute), - mSpacing(4) + QObject(parentPlot), + mParentPlot(parentPlot), + mSpacingType(stAbsolute), + mSpacing(4) { } QCPBarsGroup::~QCPBarsGroup() { - clear(); + clear(); } /*! Sets how the spacing between adjacent bars is interpreted. See \ref SpacingType. - + The actual spacing can then be specified with \ref setSpacing. \see setSpacing */ void QCPBarsGroup::setSpacingType(SpacingType spacingType) { - mSpacingType = spacingType; + mSpacingType = spacingType; } /*! @@ -18116,7 +18319,7 @@ void QCPBarsGroup::setSpacingType(SpacingType spacingType) */ void QCPBarsGroup::setSpacing(double spacing) { - mSpacing = spacing; + mSpacing = spacing; } /*! @@ -18127,14 +18330,12 @@ void QCPBarsGroup::setSpacing(double spacing) */ QCPBars *QCPBarsGroup::bars(int index) const { - if (index >= 0 && index < mBars.size()) - { - return mBars.at(index); - } else - { - qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; - return 0; - } + if (index >= 0 && index < mBars.size()) { + return mBars.at(index); + } else { + qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; + return 0; + } } /*! @@ -18144,8 +18345,9 @@ QCPBars *QCPBarsGroup::bars(int index) const */ void QCPBarsGroup::clear() { - foreach (QCPBars *bars, mBars) // since foreach takes a copy, removing bars in the loop is okay - bars->setBarsGroup(0); // removes itself via removeBars + foreach (QCPBars *bars, mBars) { // since foreach takes a copy, removing bars in the loop is okay + bars->setBarsGroup(0); // removes itself via removeBars + } } /*! @@ -18156,22 +18358,22 @@ void QCPBarsGroup::clear() */ void QCPBarsGroup::append(QCPBars *bars) { - if (!bars) - { - qDebug() << Q_FUNC_INFO << "bars is 0"; - return; - } - - if (!mBars.contains(bars)) - bars->setBarsGroup(this); - else - qDebug() << Q_FUNC_INFO << "bars plottable is already in this bars group:" << reinterpret_cast(bars); + if (!bars) { + qDebug() << Q_FUNC_INFO << "bars is 0"; + return; + } + + if (!mBars.contains(bars)) { + bars->setBarsGroup(this); + } else { + qDebug() << Q_FUNC_INFO << "bars plottable is already in this bars group:" << reinterpret_cast(bars); + } } /*! Inserts the specified \a bars plottable into this group at the specified index position \a i. This gives you full control over the ordering of the bars. - + \a bars may already be part of this group. In that case, \a bars is just moved to the new index position. @@ -18179,149 +18381,142 @@ void QCPBarsGroup::append(QCPBars *bars) */ void QCPBarsGroup::insert(int i, QCPBars *bars) { - if (!bars) - { - qDebug() << Q_FUNC_INFO << "bars is 0"; - return; - } - - // first append to bars list normally: - if (!mBars.contains(bars)) - bars->setBarsGroup(this); - // then move to according position: - mBars.move(mBars.indexOf(bars), qBound(0, i, mBars.size()-1)); + if (!bars) { + qDebug() << Q_FUNC_INFO << "bars is 0"; + return; + } + + // first append to bars list normally: + if (!mBars.contains(bars)) { + bars->setBarsGroup(this); + } + // then move to according position: + mBars.move(mBars.indexOf(bars), qBound(0, i, mBars.size() - 1)); } /*! Removes the specified \a bars plottable from this group. - + \see contains, clear */ void QCPBarsGroup::remove(QCPBars *bars) { - if (!bars) - { - qDebug() << Q_FUNC_INFO << "bars is 0"; - return; - } - - if (mBars.contains(bars)) - bars->setBarsGroup(0); - else - qDebug() << Q_FUNC_INFO << "bars plottable is not in this bars group:" << reinterpret_cast(bars); + if (!bars) { + qDebug() << Q_FUNC_INFO << "bars is 0"; + return; + } + + if (mBars.contains(bars)) { + bars->setBarsGroup(0); + } else { + qDebug() << Q_FUNC_INFO << "bars plottable is not in this bars group:" << reinterpret_cast(bars); + } } /*! \internal - + Adds the specified \a bars to the internal mBars list of bars. This method does not change the barsGroup property on \a bars. - + \see unregisterBars */ void QCPBarsGroup::registerBars(QCPBars *bars) { - if (!mBars.contains(bars)) - mBars.append(bars); + if (!mBars.contains(bars)) { + mBars.append(bars); + } } /*! \internal - + Removes the specified \a bars from the internal mBars list of bars. This method does not change the barsGroup property on \a bars. - + \see registerBars */ void QCPBarsGroup::unregisterBars(QCPBars *bars) { - mBars.removeOne(bars); + mBars.removeOne(bars); } /*! \internal - + Returns the pixel offset in the key dimension the specified \a bars plottable should have at the given key coordinate \a keyCoord. The offset is relative to the pixel position of the key coordinate \a keyCoord. */ double QCPBarsGroup::keyPixelOffset(const QCPBars *bars, double keyCoord) { - // find list of all base bars in case some mBars are stacked: - QList baseBars; - foreach (const QCPBars *b, mBars) - { - while (b->barBelow()) - b = b->barBelow(); - if (!baseBars.contains(b)) - baseBars.append(b); - } - // find base bar this "bars" is stacked on: - const QCPBars *thisBase = bars; - while (thisBase->barBelow()) - thisBase = thisBase->barBelow(); - - // determine key pixel offset of this base bars considering all other base bars in this barsgroup: - double result = 0; - 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 - { - 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; - 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; igetPixelWidth(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; + // find list of all base bars in case some mBars are stacked: + QList baseBars; + foreach (const QCPBars *b, mBars) { + while (b->barBelow()) { + b = b->barBelow(); + } + if (!baseBars.contains(b)) { + baseBars.append(b); + } } - } - return result; + // find base bar this "bars" is stacked on: + const QCPBars *thisBase = bars; + while (thisBase->barBelow()) { + thisBase = thisBase->barBelow(); + } + + // determine key pixel offset of this base bars considering all other base bars in this barsgroup: + double result = 0; + 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 + 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; + 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; + } + } + return result; } /*! \internal - + Returns the spacing in pixels which is between this \a bars and the following one, both at the 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 stAxisRectRatio and \ref stPlotCoords. The \a keyCoord is only relevant for spacings given in @@ -18329,26 +18524,23 @@ double QCPBarsGroup::keyPixelOffset(const QCPBars *bars, double keyCoord) */ double QCPBarsGroup::getPixelSpacing(const QCPBars *bars, double keyCoord) { - switch (mSpacingType) - { - case stAbsolute: - { - return mSpacing; + switch (mSpacingType) { + case stAbsolute: { + return mSpacing; + } + case stAxisRectRatio: { + if (bars->keyAxis()->orientation() == Qt::Horizontal) { + return bars->keyAxis()->axisRect()->width() * mSpacing; + } else { + return bars->keyAxis()->axisRect()->height() * mSpacing; + } + } + case stPlotCoords: { + double keyPixel = bars->keyAxis()->coordToPixel(keyCoord); + return bars->keyAxis()->coordToPixel(keyCoord + mSpacing) - keyPixel; + } } - case stAxisRectRatio: - { - if (bars->keyAxis()->orientation() == Qt::Horizontal) - return bars->keyAxis()->axisRect()->width()*mSpacing; - else - return bars->keyAxis()->axisRect()->height()*mSpacing; - } - case stPlotCoords: - { - double keyPixel = bars->keyAxis()->coordToPixel(keyCoord); - return bars->keyAxis()->coordToPixel(keyCoord+mSpacing)-keyPixel; - } - } - return 0; + return 0; } @@ -18358,13 +18550,13 @@ double QCPBarsGroup::getPixelSpacing(const QCPBars *bars, double keyCoord) /*! \class QCPBarData \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 - + \see QCPBarDataaMap */ @@ -18372,8 +18564,8 @@ double QCPBarsGroup::getPixelSpacing(const QCPBars *bars, double keyCoord) Constructs a bar data point with key and value set to zero. */ QCPBarData::QCPBarData() : - key(0), - value(0) + key(0), + value(0) { } @@ -18381,8 +18573,8 @@ QCPBarData::QCPBarData() : Constructs a bar data point with the specified \a key and \a value. */ QCPBarData::QCPBarData(double key, double value) : - key(key), - value(value) + key(key), + value(value) { } @@ -18395,29 +18587,29 @@ QCPBarData::QCPBarData(double key, double value) : \brief A plottable representing a bar chart in a plot. \image html QCPBars.png - + To plot data, assign it with the \ref setData or \ref addData functions. - + \section 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. - + Bar charts are stackable. This means, two QCPBars plottables can be placed on top of each other (see \ref QCPBars::moveAbove). So when two bars are at the same key position, they will appear stacked. - + If you would like to group multiple QCPBars plottables together so they appear side by side as shown below, use QCPBarsGroup. - + \image html QCPBarsGroup.png - + \section 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.) - + Usually, you first create an instance: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpbars-creation-1 add it to the customPlot with QCustomPlot::addPlottable: @@ -18431,14 +18623,14 @@ QCPBarData::QCPBarData(double key, double value) : /*! \fn QCPBars *QCPBars::barBelow() const Returns the bars plottable that is directly below this bars plottable. If there is no such plottable, returns 0. - + \see barAbove, moveBelow, moveAbove */ /*! \fn QCPBars *QCPBars::barAbove() const Returns the bars plottable that is directly above this bars plottable. If there is no such plottable, returns 0. - + \see barBelow, moveBelow, moveAbove */ @@ -18449,35 +18641,36 @@ QCPBarData::QCPBarData(double key, double 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 QCPBars can be added to the plot with QCustomPlot::addPlottable, QCustomPlot then takes ownership of the bar chart. */ QCPBars::QCPBars(QCPAxis *keyAxis, QCPAxis *valueAxis) : - QCPAbstractPlottable(keyAxis, valueAxis), - mData(new QCPBarDataMap), - mWidth(0.75), - mWidthType(wtPlotCoords), - mBarsGroup(0), - mBaseValue(0) + QCPAbstractPlottable(keyAxis, valueAxis), + mData(new QCPBarDataMap), + mWidth(0.75), + mWidthType(wtPlotCoords), + mBarsGroup(0), + mBaseValue(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; + // 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; } QCPBars::~QCPBars() { - setBarsGroup(0); - if (mBarBelow || mBarAbove) - connectBars(mBarBelow.data(), mBarAbove.data()); // take this bar out of any stacking - delete mData; + setBarsGroup(0); + if (mBarBelow || mBarAbove) { + connectBars(mBarBelow.data(), mBarAbove.data()); // take this bar out of any stacking + } + delete mData; } /*! @@ -18488,37 +18681,39 @@ QCPBars::~QCPBars() */ void QCPBars::setWidth(double width) { - mWidth = width; + mWidth = width; } /*! Sets how the width of the 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 QCPBars::setWidthType(QCPBars::WidthType widthType) { - mWidthType = widthType; + mWidthType = widthType; } /*! Sets to which QCPBarsGroup this QCPBars instance belongs to. Alternatively, you can also use \ref QCPBarsGroup::append. - + To remove this QCPBars from any group, set \a barsGroup to 0. */ void QCPBars::setBarsGroup(QCPBarsGroup *barsGroup) { - // deregister at old group: - if (mBarsGroup) - mBarsGroup->unregisterBars(this); - mBarsGroup = barsGroup; - // register at new group: - if (mBarsGroup) - mBarsGroup->registerBars(this); + // deregister at old group: + if (mBarsGroup) { + mBarsGroup->unregisterBars(this); + } + mBarsGroup = barsGroup; + // register at new group: + if (mBarsGroup) { + mBarsGroup->registerBars(this); + } } /*! @@ -18528,124 +18723,122 @@ void QCPBars::setBarsGroup(QCPBarsGroup *barsGroup) the base value is given by their individual value data. For example, if the base value is set to 1, a bar with data value 2 will have its lowest point at value coordinate 1 and highest point at 3. - + For stacked bars, only the base value of the bottom-most QCPBars has meaning. - + The default base value is 0. */ void QCPBars::setBaseValue(double baseValue) { - mBaseValue = baseValue; + mBaseValue = 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. */ void QCPBars::setData(QCPBarDataMap *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; - } + 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 tuples. The provided vectors should have equal length. Else, the number of added points will be the size of the smallest vector. */ void QCPBars::setData(const QVector &key, const QVector &value) { - mData->clear(); - int n = key.size(); - n = qMin(n, value.size()); - QCPBarData newData; - for (int i=0; iinsertMulti(newData.key, newData); - } + mData->clear(); + int n = key.size(); + n = qMin(n, value.size()); + QCPBarData newData; + for (int i = 0; i < n; ++i) { + newData.key = key[i]; + newData.value = value[i]; + mData->insertMulti(newData.key, newData); + } } /*! Moves this bars plottable below \a bars. In other words, the bars of this plottable will appear below the bars of \a bars. The move target \a bars must use the same key and value axis as this 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 is already between two other bars, the two other bars will be stacked on top of each other after the operation. - + To remove this bars plottable from any stacking, set \a bars to 0. - + \see moveBelow, barAbove, barBelow */ void QCPBars::moveBelow(QCPBars *bars) { - if (bars == this) return; - if (bars && (bars->keyAxis() != mKeyAxis.data() || bars->valueAxis() != mValueAxis.data())) - { - qDebug() << Q_FUNC_INFO << "passed QCPBars* doesn't have same key and value axis as this QCPBars"; - return; - } - // remove from stacking: - connectBars(mBarBelow.data(), mBarAbove.data()); // Note: also works if one (or both) of them is 0 - // if new bar given, insert this bar below it: - if (bars) - { - if (bars->mBarBelow) - connectBars(bars->mBarBelow.data(), this); - connectBars(this, bars); - } + if (bars == this) { + return; + } + if (bars && (bars->keyAxis() != mKeyAxis.data() || bars->valueAxis() != mValueAxis.data())) { + qDebug() << Q_FUNC_INFO << "passed QCPBars* doesn't have same key and value axis as this QCPBars"; + return; + } + // remove from stacking: + connectBars(mBarBelow.data(), mBarAbove.data()); // Note: also works if one (or both) of them is 0 + // if new bar given, insert this bar below it: + if (bars) { + if (bars->mBarBelow) { + connectBars(bars->mBarBelow.data(), this); + } + connectBars(this, bars); + } } /*! Moves this bars plottable above \a bars. In other words, the bars of this plottable will appear above the bars of \a bars. The move target \a bars must use the same key and value axis as this plottable. - + Inserting into and removing from existing bar stacking is handled gracefully. If \a bars already 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. - + To remove this bars plottable from any stacking, set \a bars to 0. - + \see moveBelow, barBelow, barAbove */ void QCPBars::moveAbove(QCPBars *bars) { - if (bars == this) return; - if (bars && (bars->keyAxis() != mKeyAxis.data() || bars->valueAxis() != mValueAxis.data())) - { - qDebug() << Q_FUNC_INFO << "passed QCPBars* doesn't have same key and value axis as this QCPBars"; - return; - } - // remove from stacking: - connectBars(mBarBelow.data(), mBarAbove.data()); // Note: also works if one (or both) of them is 0 - // if new bar given, insert this bar above it: - if (bars) - { - if (bars->mBarAbove) - connectBars(this, bars->mBarAbove.data()); - connectBars(bars, this); - } + if (bars == this) { + return; + } + if (bars && (bars->keyAxis() != mKeyAxis.data() || bars->valueAxis() != mValueAxis.data())) { + qDebug() << Q_FUNC_INFO << "passed QCPBars* doesn't have same key and value axis as this QCPBars"; + return; + } + // remove from stacking: + connectBars(mBarBelow.data(), mBarAbove.data()); // Note: also works if one (or both) of them is 0 + // if new bar given, insert this bar above it: + if (bars) { + if (bars->mBarAbove) { + connectBars(this, bars->mBarAbove.data()); + } + connectBars(bars, this); + } } /*! @@ -18654,7 +18847,7 @@ void QCPBars::moveAbove(QCPBars *bars) */ void QCPBars::addData(const QCPBarDataMap &dataMap) { - mData->unite(dataMap); + mData->unite(dataMap); } /*! \overload @@ -18663,7 +18856,7 @@ void QCPBars::addData(const QCPBarDataMap &dataMap) */ void QCPBars::addData(const QCPBarData &data) { - mData->insertMulti(data.key, data); + mData->insertMulti(data.key, data); } /*! \overload @@ -18672,10 +18865,10 @@ void QCPBars::addData(const QCPBarData &data) */ void QCPBars::addData(double key, double value) { - QCPBarData newData; - newData.key = key; - newData.value = value; - mData->insertMulti(newData.key, newData); + QCPBarData newData; + newData.key = key; + newData.value = value; + mData->insertMulti(newData.key, newData); } /*! \overload @@ -18684,15 +18877,14 @@ void QCPBars::addData(double key, double value) */ void QCPBars::addData(const QVector &keys, const QVector &values) { - int n = keys.size(); - n = qMin(n, values.size()); - QCPBarData newData; - for (int i=0; iinsertMulti(newData.key, newData); - } + int n = keys.size(); + n = qMin(n, values.size()); + QCPBarData newData; + for (int i = 0; i < n; ++i) { + newData.key = keys[i]; + newData.value = values[i]; + mData->insertMulti(newData.key, newData); + } } /*! @@ -18701,9 +18893,10 @@ void QCPBars::addData(const QVector &keys, const QVector &values */ void QCPBars::removeDataBefore(double key) { - QCPBarDataMap::iterator it = mData->begin(); - while (it != mData->end() && it.key() < key) - it = mData->erase(it); + QCPBarDataMap::iterator it = mData->begin(); + while (it != mData->end() && it.key() < key) { + it = mData->erase(it); + } } /*! @@ -18712,39 +18905,45 @@ void QCPBars::removeDataBefore(double key) */ void QCPBars::removeDataAfter(double key) { - if (mData->isEmpty()) return; - QCPBarDataMap::iterator it = mData->upperBound(key); - while (it != mData->end()) - it = mData->erase(it); + 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); + 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); + mData->remove(key); } /*! @@ -18753,379 +18952,386 @@ void QCPBars::removeData(double key) */ void QCPBars::clearData() { - mData->clear(); + mData->clear(); } /* inherits documentation from base class */ double QCPBars::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { - Q_UNUSED(details) - if (onlySelectable && !mSelectable) - 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) - { - if (getBarPolygon(it.value().key, it.value().value).boundingRect().contains(pos)) - return mParentPlot->selectionTolerance()*0.99; + Q_UNUSED(details) + if (onlySelectable && !mSelectable) { + return -1; } - } - 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) { + if (getBarPolygon(it.value().key, it.value().value).boundingRect().contains(pos)) { + return mParentPlot->selectionTolerance() * 0.99; + } + } + } + return -1; } /* 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; - - QCPBarDataMap::const_iterator it, lower, upperEnd; - getVisibleDataBounds(lower, upperEnd); - for (it = lower; it != upperEnd; ++it) - { - // check data validity if flag set: + if (!mKeyAxis || !mValueAxis) { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + return; + } + if (mData->isEmpty()) { + return; + } + + QCPBarDataMap::const_iterator it, lower, upperEnd; + getVisibleDataBounds(lower, upperEnd); + for (it = lower; it != upperEnd; ++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.value().key, it.value().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); + 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) { + applyDefaultAntialiasingHint(painter); + painter->setPen(mainPen()); + painter->setBrush(Qt::NoBrush); + painter->drawPolyline(barPolygon); + } } - // draw bar line: - if (mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0) - { - applyDefaultAntialiasingHint(painter); - painter->setPen(mainPen()); - painter->setBrush(Qt::NoBrush); - painter->drawPolyline(barPolygon); - } - } } /* inherits documentation from base class */ void QCPBars::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const { - // draw filled rect: - applyDefaultAntialiasingHint(painter); - painter->setBrush(mBrush); - painter->setPen(mPen); - QRectF r = QRectF(0, 0, rect.width()*0.67, rect.height()*0.67); - r.moveCenter(rect.center()); - painter->drawRect(r); + // draw filled rect: + applyDefaultAntialiasingHint(painter); + painter->setBrush(mBrush); + painter->setPen(mPen); + QRectF r = QRectF(0, 0, rect.width() * 0.67, rect.height() * 0.67); + r.moveCenter(rect.center()); + painter->drawRect(r); } /*! \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 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 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. - + if the bars plottable contains no data, both \a lower and \a upperEnd point to constEnd. */ void QCPBars::getVisibleDataBounds(QCPBarDataMap::const_iterator &lower, QCPBarDataMap::const_iterator &upperEnd) const { - if (!mKeyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; } - if (mData->isEmpty()) - { - lower = mData->constEnd(); - upperEnd = mData->constEnd(); - return; - } - - // get visible data range as QMap iterators - lower = mData->lowerBound(mKeyAxis.data()->range().lower); - upperEnd = mData->upperBound(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()) - { - --it; - QRectF barBounds = getBarPolygon(it.value().key, it.value().value).boundingRect(); - if (mKeyAxis.data()->orientation() == Qt::Horizontal) - isVisible = ((!mKeyAxis.data()->rangeReversed() && barBounds.right() >= lowerPixelBound) || (mKeyAxis.data()->rangeReversed() && barBounds.left() <= lowerPixelBound)); - else // keyaxis is vertical - isVisible = ((!mKeyAxis.data()->rangeReversed() && barBounds.top() <= lowerPixelBound) || (mKeyAxis.data()->rangeReversed() && barBounds.bottom() >= lowerPixelBound)); - if (isVisible) - lower = 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()) - { - QRectF barBounds = getBarPolygon(upperEnd.value().key, upperEnd.value().value).boundingRect(); - if (mKeyAxis.data()->orientation() == Qt::Horizontal) - isVisible = ((!mKeyAxis.data()->rangeReversed() && barBounds.left() <= upperPixelBound) || (mKeyAxis.data()->rangeReversed() && barBounds.right() >= upperPixelBound)); - else // keyaxis is vertical - isVisible = ((!mKeyAxis.data()->rangeReversed() && barBounds.bottom() >= upperPixelBound) || (mKeyAxis.data()->rangeReversed() && barBounds.top() <= upperPixelBound)); - if (isVisible) - upperEnd = it+1; - else - break; - ++it; - } + if (!mKeyAxis) { + qDebug() << Q_FUNC_INFO << "invalid key axis"; + return; + } + if (mData->isEmpty()) { + lower = mData->constEnd(); + upperEnd = mData->constEnd(); + return; + } + + // get visible data range as QMap iterators + lower = mData->lowerBound(mKeyAxis.data()->range().lower); + upperEnd = mData->upperBound(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()) { + --it; + QRectF barBounds = getBarPolygon(it.value().key, it.value().value).boundingRect(); + if (mKeyAxis.data()->orientation() == Qt::Horizontal) { + isVisible = ((!mKeyAxis.data()->rangeReversed() && barBounds.right() >= lowerPixelBound) || (mKeyAxis.data()->rangeReversed() && barBounds.left() <= lowerPixelBound)); + } else { // keyaxis is vertical + isVisible = ((!mKeyAxis.data()->rangeReversed() && barBounds.top() <= lowerPixelBound) || (mKeyAxis.data()->rangeReversed() && barBounds.bottom() >= lowerPixelBound)); + } + if (isVisible) { + lower = 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()) { + QRectF barBounds = getBarPolygon(upperEnd.value().key, upperEnd.value().value).boundingRect(); + if (mKeyAxis.data()->orientation() == Qt::Horizontal) { + isVisible = ((!mKeyAxis.data()->rangeReversed() && barBounds.left() <= upperPixelBound) || (mKeyAxis.data()->rangeReversed() && barBounds.right() >= upperPixelBound)); + } else { // keyaxis is vertical + isVisible = ((!mKeyAxis.data()->rangeReversed() && barBounds.bottom() >= upperPixelBound) || (mKeyAxis.data()->rangeReversed() && barBounds.top() <= upperPixelBound)); + } + if (isVisible) { + upperEnd = it + 1; + } else { + break; + } + ++it; + } } /*! \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). */ QPolygonF QCPBars::getBarPolygon(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(); } - - QPolygonF result; - double lowerPixelWidth, upperPixelWidth; - getPixelWidth(key, lowerPixelWidth, upperPixelWidth); - double base = getStackedBaseValue(key, value >= 0); - double basePixel = valueAxis->coordToPixel(base); - double valuePixel = valueAxis->coordToPixel(base+value); - double keyPixel = keyAxis->coordToPixel(key); - if (mBarsGroup) - keyPixel += mBarsGroup->keyPixelOffset(this, key); - 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); - } else - { - result << QPointF(basePixel, keyPixel+lowerPixelWidth); - result << QPointF(valuePixel, keyPixel+lowerPixelWidth); - result << QPointF(valuePixel, keyPixel+upperPixelWidth); - result << QPointF(basePixel, keyPixel+upperPixelWidth); - } - return result; + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + return QPolygonF(); + } + + QPolygonF result; + double lowerPixelWidth, upperPixelWidth; + getPixelWidth(key, lowerPixelWidth, upperPixelWidth); + double base = getStackedBaseValue(key, value >= 0); + double basePixel = valueAxis->coordToPixel(base); + double valuePixel = valueAxis->coordToPixel(base + value); + double keyPixel = keyAxis->coordToPixel(key); + if (mBarsGroup) { + keyPixel += mBarsGroup->keyPixelOffset(this, key); + } + 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); + } else { + result << QPointF(basePixel, keyPixel + lowerPixelWidth); + result << QPointF(valuePixel, keyPixel + lowerPixelWidth); + result << QPointF(valuePixel, keyPixel + upperPixelWidth); + result << QPointF(basePixel, keyPixel + upperPixelWidth); + } + return result; } /*! \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). - + The output parameters \a lower and \a upper return the number of pixels the bar extends to lower and higher keys, relative to the \a key coordinate (so with a non-reversed horizontal axis, \a lower is negative and \a upper positive). */ void QCPBars::getPixelWidth(double key, double &lower, double &upper) const { - switch (mWidthType) - { - case wtAbsolute: - { - upper = mWidth*0.5; - lower = -upper; - if (mKeyAxis && (mKeyAxis.data()->rangeReversed() ^ (mKeyAxis.data()->orientation() == Qt::Vertical))) - qSwap(lower, upper); - break; + switch (mWidthType) { + case wtAbsolute: { + upper = mWidth * 0.5; + lower = -upper; + if (mKeyAxis && (mKeyAxis.data()->rangeReversed() ^ (mKeyAxis.data()->orientation() == Qt::Vertical))) { + qSwap(lower, upper); + } + break; + } + case wtAxisRectRatio: { + if (mKeyAxis && mKeyAxis.data()->axisRect()) { + if (mKeyAxis.data()->orientation() == Qt::Horizontal) { + upper = mKeyAxis.data()->axisRect()->width() * mWidth * 0.5; + } else { + upper = mKeyAxis.data()->axisRect()->height() * mWidth * 0.5; + } + 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; + } + case wtPlotCoords: { + if (mKeyAxis) { + double keyPixel = mKeyAxis.data()->coordToPixel(key); + upper = mKeyAxis.data()->coordToPixel(key + mWidth * 0.5) - keyPixel; + lower = mKeyAxis.data()->coordToPixel(key - mWidth * 0.5) - keyPixel; + // no need to qSwap(lower, higher) when range reversed, because higher/lower are gained by + // coordinate transform which includes range direction + } else { + qDebug() << Q_FUNC_INFO << "No key axis defined"; + } + break; + } } - case wtAxisRectRatio: - { - if (mKeyAxis && mKeyAxis.data()->axisRect()) - { - if (mKeyAxis.data()->orientation() == Qt::Horizontal) - upper = mKeyAxis.data()->axisRect()->width()*mWidth*0.5; - else - upper = mKeyAxis.data()->axisRect()->height()*mWidth*0.5; - 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; - } - case wtPlotCoords: - { - if (mKeyAxis) - { - double keyPixel = mKeyAxis.data()->coordToPixel(key); - upper = mKeyAxis.data()->coordToPixel(key+mWidth*0.5)-keyPixel; - lower = mKeyAxis.data()->coordToPixel(key-mWidth*0.5)-keyPixel; - // no need to qSwap(lower, higher) when range reversed, because higher/lower are gained by - // coordinate transform which includes range direction - } else - qDebug() << Q_FUNC_INFO << "No key axis defined"; - break; - } - } } /*! \internal - + This function is called to find at which value to start drawing the base of a bar at \a key, when it is stacked on top of another QCPBars (e.g. with \ref moveAbove). - + positive and negative bars are separated per stack (positive are stacked above baseValue upwards, negative are stacked below baseValue downwards). This can be indicated with \a positive. So if the bar for which we need the base value is negative, set \a positive to false. */ 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 - // 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 - 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); - while (it != itEnd) - { - if ((positive && it.value().value > max) || - (!positive && it.value().value < max)) - max = it.value().value; - ++it; + if (mBarBelow) { + double max = 0; // don't use 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 + 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); + while (it != itEnd) { + if ((positive && it.value().value > max) || + (!positive && it.value().value < max)) { + max = it.value().value; + } + ++it; + } + // recurse down the bar-stack to find the total height: + return max + mBarBelow.data()->getStackedBaseValue(key, positive); + } else { + return mBaseValue; } - // recurse down the bar-stack to find the total height: - return max + mBarBelow.data()->getStackedBaseValue(key, positive); - } else - return mBaseValue; } /*! \internal Connects \a below and \a above to each other via their mBarAbove/mBarBelow properties. The bar(s) currently above lower and below upper will become disconnected to lower/upper. - + If lower is zero, upper will be disconnected at the bottom. If upper is zero, lower will be disconnected at the top. */ void QCPBars::connectBars(QCPBars *lower, QCPBars *upper) { - if (!lower && !upper) return; - - if (!lower) // disconnect upper at bottom - { - // disconnect old bar below upper: - if (upper->mBarBelow && upper->mBarBelow.data()->mBarAbove.data() == upper) - upper->mBarBelow.data()->mBarAbove = 0; - upper->mBarBelow = 0; - } else if (!upper) // disconnect lower at top - { - // disconnect old bar above lower: - if (lower->mBarAbove && lower->mBarAbove.data()->mBarBelow.data() == lower) - lower->mBarAbove.data()->mBarBelow = 0; - lower->mBarAbove = 0; - } else // connect lower and upper - { - // disconnect old bar above lower: - if (lower->mBarAbove && lower->mBarAbove.data()->mBarBelow.data() == lower) - lower->mBarAbove.data()->mBarBelow = 0; - // disconnect old bar below upper: - if (upper->mBarBelow && upper->mBarBelow.data()->mBarAbove.data() == upper) - upper->mBarBelow.data()->mBarAbove = 0; - lower->mBarAbove = upper; - upper->mBarBelow = lower; - } + if (!lower && !upper) { + return; + } + + if (!lower) { // disconnect upper at bottom + // disconnect old bar below upper: + if (upper->mBarBelow && upper->mBarBelow.data()->mBarAbove.data() == upper) { + upper->mBarBelow.data()->mBarAbove = 0; + } + upper->mBarBelow = 0; + } else if (!upper) { // disconnect lower at top + // disconnect old bar above lower: + if (lower->mBarAbove && lower->mBarAbove.data()->mBarBelow.data() == lower) { + lower->mBarAbove.data()->mBarBelow = 0; + } + lower->mBarAbove = 0; + } else { // connect lower and upper + // disconnect old bar above lower: + if (lower->mBarAbove && lower->mBarAbove.data()->mBarBelow.data() == lower) { + lower->mBarAbove.data()->mBarBelow = 0; + } + // disconnect old bar below upper: + if (upper->mBarBelow && upper->mBarBelow.data()->mBarAbove.data() == upper) { + upper->mBarBelow.data()->mBarAbove = 0; + } + lower->mBarAbove = upper; + upper->mBarBelow = lower; + } } /* inherits documentation from base class */ QCPRange QCPBars::getKeyRange(bool &foundRange, SignDomain inSignDomain) const { - QCPRange range; - bool haveLower = false; - bool haveUpper = false; - - 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; - } + QCPRange range; + bool haveLower = false; + bool haveUpper = false; + + 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; } - ++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; + // 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; } /* inherits documentation from base class */ QCPRange QCPBars::getValueRange(bool &foundRange, SignDomain inSignDomain) const { - 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; - } + 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; } - ++it; - } - - foundRange = true; // return true because bar charts always have the 0-line visible - return range; + + foundRange = true; // return true because bar charts always have the 0-line visible + return range; } @@ -19137,7 +19343,7 @@ QCPRange QCPBars::getValueRange(bool &foundRange, SignDomain inSignDomain) const \brief A plottable representing a single statistical box in a plot. \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 @@ -19145,30 +19351,30 @@ QCPRange QCPBars::getValueRange(bool &foundRange, SignDomain inSignDomain) const \li \ref setMedian \li \ref setUpperQuartile \li \ref setMaximum - + Additionally you can define a list of outliers, drawn as scatter datapoints: \li \ref setOutliers - + \section 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). 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). - + The median indicator line 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 \ref setOutlierStyle - + \section 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: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpstatisticalbox-creation-1 @@ -19181,30 +19387,30 @@ QCPRange QCPBars::getValueRange(bool &foundRange, SignDomain inSignDomain) const 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. */ QCPStatisticalBox::QCPStatisticalBox(QCPAxis *keyAxis, QCPAxis *valueAxis) : - QCPAbstractPlottable(keyAxis, valueAxis), - mKey(0), - mMinimum(0), - mLowerQuartile(0), - mMedian(0), - mUpperQuartile(0), - mMaximum(0) + QCPAbstractPlottable(keyAxis, valueAxis), + mKey(0), + mMinimum(0), + mLowerQuartile(0), + mMedian(0), + mUpperQuartile(0), + mMaximum(0) { - 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); + 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); } /*! @@ -19212,136 +19418,136 @@ QCPStatisticalBox::QCPStatisticalBox(QCPAxis *keyAxis, QCPAxis *valueAxis) : */ void QCPStatisticalBox::setKey(double key) { - mKey = 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. - + \see setMaximum, setWhiskerPen, setWhiskerBarPen, setWhiskerWidth */ void QCPStatisticalBox::setMinimum(double value) { - mMinimum = 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. - + \see setUpperQuartile, setPen, setBrush, setWidth */ void QCPStatisticalBox::setLowerQuartile(double value) { - mLowerQuartile = 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). - + \see setMedianPen */ void QCPStatisticalBox::setMedian(double value) { - mMedian = 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. - + \see setLowerQuartile, setPen, setBrush, setWidth */ void QCPStatisticalBox::setUpperQuartile(double value) { - mUpperQuartile = value; + mUpperQuartile = value; } /*! 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. - + \see setMinimum, setWhiskerPen, setWhiskerBarPen, setWhiskerWidth */ void QCPStatisticalBox::setMaximum(double value) { - mMaximum = 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. - + \see setOutlierStyle */ void QCPStatisticalBox::setOutliers(const QVector &values) { - mOutliers = values; + mOutliers = values; } /*! Sets all parameters of the statistical box plot at once. - + \see setKey, setMinimum, setLowerQuartile, setMedian, setUpperQuartile, setMaximum */ void QCPStatisticalBox::setData(double key, double minimum, double lowerQuartile, double median, double upperQuartile, double maximum) { - setKey(key); - setMinimum(minimum); - setLowerQuartile(lowerQuartile); - setMedian(median); - setUpperQuartile(upperQuartile); - setMaximum(maximum); + setKey(key); + setMinimum(minimum); + setLowerQuartile(lowerQuartile); + setMedian(median); + setUpperQuartile(upperQuartile); + setMaximum(maximum); } /*! Sets the width of the box in key coordinates. - + \see setWhiskerWidth */ void QCPStatisticalBox::setWidth(double width) { - mWidth = width; + mWidth = width; } /*! Sets the width of the whiskers (\ref setMinimum, \ref setMaximum) in key coordinates. - + \see setWidth */ void QCPStatisticalBox::setWhiskerWidth(double width) { - mWhiskerWidth = width; + mWhiskerWidth = width; } /*! Sets the pen used for drawing the whisker backbone (That's the line parallel to the value axis). - + 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. - + \see setWhiskerBarPen */ void QCPStatisticalBox::setWhiskerPen(const QPen &pen) { - mWhiskerPen = pen; + mWhiskerPen = 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). - + \see setWhiskerPen */ void QCPStatisticalBox::setWhiskerBarPen(const QPen &pen) { - mWhiskerBarPen = pen; + mWhiskerBarPen = pen; } /*! @@ -19349,235 +19555,236 @@ void QCPStatisticalBox::setWhiskerBarPen(const QPen &pen) */ void QCPStatisticalBox::setMedianPen(const QPen &pen) { - mMedianPen = pen; + mMedianPen = pen; } /*! Sets the appearance of the outlier data points. - + \see setOutliers */ void QCPStatisticalBox::setOutlierStyle(const QCPScatterStyle &style) { - mOutlierStyle = style; + mOutlierStyle = style; } /* inherits documentation from base class */ void QCPStatisticalBox::clearData() { - setOutliers(QVector()); - setKey(0); - setMinimum(0); - setLowerQuartile(0); - setMedian(0); - setUpperQuartile(0); - setMaximum(0); + setOutliers(QVector()); + setKey(0); + setMinimum(0); + setLowerQuartile(0); + setMedian(0); + setUpperQuartile(0); + setMaximum(0); } /* inherits documentation from base class */ double QCPStatisticalBox::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { - Q_UNUSED(details) - if (onlySelectable && !mSelectable) + Q_UNUSED(details) + if (onlySelectable && !mSelectable) { + 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); + // 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)); + } + } 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); - // 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)); - } - return -1; } /* inherits documentation from base class */ void QCPStatisticalBox::draw(QCPPainter *painter) { - if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } + if (!mKeyAxis || !mValueAxis) { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + return; + } - // check data validity if flag set: + // 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; isave(); - painter->setClipRect(quartileBox, Qt::IntersectClip); - drawMedian(painter); - painter->restore(); - - drawWhiskers(painter); - drawOutliers(painter); + + QRectF quartileBox; + drawQuartileBox(painter, &quartileBox); + + painter->save(); + painter->setClipRect(quartileBox, Qt::IntersectClip); + drawMedian(painter); + painter->restore(); + + drawWhiskers(painter); + drawOutliers(painter); } /* inherits documentation from base class */ void QCPStatisticalBox::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const { - // draw filled rect: - applyDefaultAntialiasingHint(painter); - painter->setPen(mPen); - painter->setBrush(mBrush); - QRectF r = QRectF(0, 0, rect.width()*0.67, rect.height()*0.67); - r.moveCenter(rect.center()); - painter->drawRect(r); + // draw filled rect: + applyDefaultAntialiasingHint(painter); + painter->setPen(mPen); + painter->setBrush(mBrush); + QRectF r = QRectF(0, 0, rect.width() * 0.67, rect.height() * 0.67); + r.moveCenter(rect.center()); + 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; + 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; + } } /*! \internal - + Draws the median line inside the quartile box. */ void QCPStatisticalBox::drawMedian(QCPPainter *painter) const { - QLineF medianLine; - medianLine.setP1(coordsToPixels(mKey-mWidth*0.5, mMedian)); - medianLine.setP2(coordsToPixels(mKey+mWidth*0.5, mMedian)); - applyDefaultAntialiasingHint(painter); - painter->setPen(mMedianPen); - painter->drawLine(medianLine); + QLineF medianLine; + medianLine.setP1(coordsToPixels(mKey - mWidth * 0.5, mMedian)); + medianLine.setP2(coordsToPixels(mKey + mWidth * 0.5, mMedian)); + applyDefaultAntialiasingHint(painter); + 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->setPen(mWhiskerPen); - painter->drawLine(backboneMin); - painter->drawLine(backboneMax); - painter->setPen(mWhiskerBarPen); - painter->drawLine(barMin); - painter->drawLine(barMax); + 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->setPen(mWhiskerPen); + painter->drawLine(backboneMin); + painter->drawLine(backboneMax); + painter->setPen(mWhiskerBarPen); + painter->drawLine(barMin); + painter->drawLine(barMax); } /*! \internal - + Draws the outlier scatter points. */ void QCPStatisticalBox::drawOutliers(QCPPainter *painter) const { - applyScattersAntialiasingHint(painter); - mOutlierStyle.applyTo(painter, mPen); - for (int i=0; i 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(); + } } - } 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(); - } - } - foundRange = false; - return QCPRange(); + foundRange = false; + return QCPRange(); } /* inherits documentation from base class */ QCPRange QCPStatisticalBox::getValueRange(bool &foundRange, SignDomain inSignDomain) 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; - } + 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 < values.size(); ++i) { + if ((inSignDomain == sdNegative && values.at(i) < 0) || + (inSignDomain == sdPositive && values.at(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(); } - } - // 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(); - } } @@ -19587,20 +19794,20 @@ QCPRange QCPStatisticalBox::getValueRange(bool &foundRange, SignDomain inSignDom /*! \class QCPColorMapData \brief Holds the two-dimensional data of a QCPColorMap plottable. - + This class is a data storage for \ref QCPColorMap. It holds a two-dimensional array, which \ref QCPColorMap then displays as a 2D image in the plot, where the array values are represented by a color, depending on the value. - + The size of the array can be controlled via \ref setSize (or \ref setKeySize, \ref setValueSize). Which plot coordinates these cells correspond to can be configured with \ref setRange (or \ref setKeyRange, \ref setValueRange). - + The data cells can be accessed in two ways: They can be directly addressed by an integer index with \ref setCell. This is the fastest method. Alternatively, they can be addressed by their plot coordinate with \ref setData. plot coordinate to cell index transformations and vice versa are provided by the functions \ref coordToCell and \ref cellToCoord. - + 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, @@ -19616,7 +19823,7 @@ QCPRange QCPStatisticalBox::getValueRange(bool &foundRange, SignDomain inSignDom /* start of documentation of inline functions */ /*! \fn bool QCPColorMapData::isEmpty() const - + Returns whether this instance carries no data. This is equivalent to having a size where at least one of the dimensions is 0 (see \ref setSize). */ @@ -19627,39 +19834,40 @@ QCPRange QCPStatisticalBox::getValueRange(bool &foundRange, SignDomain inSignDom Constructs a new QCPColorMapData instance. The instance has \a keySize cells in the key direction and \a valueSize cells in the value direction. These cells will be displayed by the \ref QCPColorMap at the coordinates \a keyRange and \a valueRange. - + \see setSize, setKeySize, setValueSize, setRange, setKeyRange, setValueRange */ QCPColorMapData::QCPColorMapData(int keySize, int valueSize, const QCPRange &keyRange, const QCPRange &valueRange) : - mKeySize(0), - mValueSize(0), - mKeyRange(keyRange), - mValueRange(valueRange), - mIsEmpty(true), - mData(0), - mDataModified(true) + mKeySize(0), + mValueSize(0), + mKeyRange(keyRange), + mValueRange(valueRange), + mIsEmpty(true), + mData(0), + mDataModified(true) { - setSize(keySize, valueSize); - fill(0); + setSize(keySize, valueSize); + fill(0); } QCPColorMapData::~QCPColorMapData() { - if (mData) - delete[] mData; + if (mData) { + delete[] mData; + } } /*! Constructs a new QCPColorMapData instance copying the data and range of \a other. */ QCPColorMapData::QCPColorMapData(const QCPColorMapData &other) : - mKeySize(0), - mValueSize(0), - mIsEmpty(true), - mData(0), - mDataModified(true) + mKeySize(0), + mValueSize(0), + mIsEmpty(true), + mData(0), + mDataModified(true) { - *this = other; + *this = other; } /*! @@ -19667,38 +19875,40 @@ QCPColorMapData::QCPColorMapData(const QCPColorMapData &other) : */ QCPColorMapData &QCPColorMapData::operator=(const QCPColorMapData &other) { - if (&other != this) - { - const int keySize = other.keySize(); - const int valueSize = other.valueSize(); - setSize(keySize, valueSize); - setRange(other.keyRange(), other.valueRange()); - if (!mIsEmpty) - memcpy(mData, other.mData, sizeof(mData[0])*keySize*valueSize); - mDataBounds = other.mDataBounds; - mDataModified = true; - } - return *this; + if (&other != this) { + const int keySize = other.keySize(); + const int valueSize = other.valueSize(); + setSize(keySize, valueSize); + setRange(other.keyRange(), other.valueRange()); + if (!mIsEmpty) { + memcpy(mData, other.mData, sizeof(mData[0])*keySize * valueSize); + } + mDataBounds = other.mDataBounds; + mDataModified = true; + } + return *this; } /* undocumented getter */ double QCPColorMapData::data(double key, double value) { - int keyCell = (key-mKeyRange.lower)/(mKeyRange.upper-mKeyRange.lower)*(mKeySize-1)+0.5; - int valueCell = (value-mValueRange.lower)/(mValueRange.upper-mValueRange.lower)*(mValueSize-1)+0.5; - if (keyCell >= 0 && keyCell < mKeySize && valueCell >= 0 && valueCell < mValueSize) - return mData[valueCell*mKeySize + keyCell]; - else - return 0; + int keyCell = (key - mKeyRange.lower) / (mKeyRange.upper - mKeyRange.lower) * (mKeySize - 1) + 0.5; + int valueCell = (value - mValueRange.lower) / (mValueRange.upper - mValueRange.lower) * (mValueSize - 1) + 0.5; + if (keyCell >= 0 && keyCell < mKeySize && valueCell >= 0 && valueCell < mValueSize) { + return mData[valueCell * mKeySize + keyCell]; + } else { + return 0; + } } /* undocumented getter */ double QCPColorMapData::cell(int keyIndex, int valueIndex) { - if (keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize) - return mData[valueIndex*mKeySize + keyIndex]; - else - return 0; + if (keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize) { + return mData[valueIndex * mKeySize + keyIndex]; + } else { + return 0; + } } /*! @@ -19707,7 +19917,7 @@ double QCPColorMapData::cell(int keyIndex, int valueIndex) The current data is discarded and the map cells are set to 0, unless the map had already the requested size. - + Setting at least one of \a keySize or \a valueSize to zero frees the internal data array and \ref isEmpty returns true. @@ -19715,30 +19925,33 @@ double QCPColorMapData::cell(int keyIndex, int valueIndex) */ void QCPColorMapData::setSize(int keySize, int valueSize) { - if (keySize != mKeySize || valueSize != mValueSize) - { - mKeySize = keySize; - mValueSize = valueSize; - if (mData) - delete[] mData; - mIsEmpty = mKeySize == 0 || mValueSize == 0; - if (!mIsEmpty) - { + if (keySize != mKeySize || valueSize != mValueSize) { + mKeySize = keySize; + mValueSize = valueSize; + if (mData) { + delete[] mData; + } + mIsEmpty = mKeySize == 0 || mValueSize == 0; + if (!mIsEmpty) { #ifdef __EXCEPTIONS - try { // 2D arrays get memory intensive fast. So if the allocation fails, at least output debug message + try { // 2D arrays get memory intensive fast. So if the allocation fails, at least output debug message #endif - mData = new double[mKeySize*mValueSize]; + mData = new double[mKeySize * mValueSize]; #ifdef __EXCEPTIONS - } catch (...) { mData = 0; } + } catch (...) { + mData = 0; + } #endif - if (mData) - fill(0); - else - qDebug() << Q_FUNC_INFO << "out of memory for data dimensions "<< mKeySize << "*" << mValueSize; - } else - mData = 0; - mDataModified = true; - } + if (mData) { + fill(0); + } else { + qDebug() << Q_FUNC_INFO << "out of memory for data dimensions " << mKeySize << "*" << mValueSize; + } + } else { + mData = 0; + } + mDataModified = true; + } } /*! @@ -19746,14 +19959,14 @@ void QCPColorMapData::setSize(int keySize, int valueSize) The current data is discarded and the map cells are set to 0, unless the map had already the requested size. - + Setting \a keySize to zero frees the internal data array and \ref isEmpty returns true. \see setKeyRange, setSize, setValueSize */ void QCPColorMapData::setKeySize(int keySize) { - setSize(keySize, mValueSize); + setSize(keySize, mValueSize); } /*! @@ -19761,153 +19974,155 @@ void QCPColorMapData::setKeySize(int keySize) The current data is discarded and the map cells are set to 0, unless the map had already the requested size. - + Setting \a valueSize to zero frees the internal data array and \ref isEmpty returns true. \see setValueRange, setSize, setKeySize */ void QCPColorMapData::setValueSize(int valueSize) { - setSize(mKeySize, valueSize); + setSize(mKeySize, valueSize); } /*! Sets the coordinate ranges the data shall be distributed over. This defines the rectangular area covered by the color map in plot coordinates. - + The outer cells will be centered on the range boundaries given to this function. For example, if the key size (\ref setKeySize) is 3 and \a keyRange is set to QCPRange(2, 3) there will be cells centered on the key coordinates 2, 2.5 and 3. - + \see setSize */ void QCPColorMapData::setRange(const QCPRange &keyRange, const QCPRange &valueRange) { - setKeyRange(keyRange); - setValueRange(valueRange); + setKeyRange(keyRange); + setValueRange(valueRange); } /*! Sets the coordinate range the data shall be distributed over in the key dimension. Together with the value range, This defines the rectangular area covered by the color map in plot coordinates. - + The outer cells will be centered on the range boundaries given to this function. For example, if the key size (\ref setKeySize) is 3 and \a keyRange is set to QCPRange(2, 3) there will be cells centered on the key coordinates 2, 2.5 and 3. - + \see setRange, setValueRange, setSize */ void QCPColorMapData::setKeyRange(const QCPRange &keyRange) { - mKeyRange = keyRange; + mKeyRange = keyRange; } /*! Sets the coordinate range the data shall be distributed over in the value dimension. Together with the key range, This defines the rectangular area covered by the color map in plot coordinates. - + The outer cells will be centered on the range boundaries given to this function. For example, if the value size (\ref setValueSize) is 3 and \a valueRange is set to QCPRange(2, 3) there will be cells centered on the value coordinates 2, 2.5 and 3. - + \see setRange, setKeyRange, setSize */ void QCPColorMapData::setValueRange(const QCPRange &valueRange) { - mValueRange = valueRange; + mValueRange = valueRange; } /*! Sets the data of the cell, which lies at the plot coordinates given by \a key and \a value, to \a z. - + \note The QCPColorMap always displays the data at equal key/value intervals, even if the key or value axis is set to a logarithmic scaling. If you want to use QCPColorMap with logarithmic axes, you shouldn't use the \ref QCPColorMapData::setData method as it uses a linear transformation to determine the cell index. Rather directly access the cell index with \ref QCPColorMapData::setCell. - + \see setCell, setRange */ void QCPColorMapData::setData(double key, double value, double z) { - int keyCell = (key-mKeyRange.lower)/(mKeyRange.upper-mKeyRange.lower)*(mKeySize-1)+0.5; - int valueCell = (value-mValueRange.lower)/(mValueRange.upper-mValueRange.lower)*(mValueSize-1)+0.5; - if (keyCell >= 0 && keyCell < mKeySize && valueCell >= 0 && valueCell < mValueSize) - { - mData[valueCell*mKeySize + keyCell] = z; - if (z < mDataBounds.lower) - mDataBounds.lower = z; - if (z > mDataBounds.upper) - mDataBounds.upper = z; - mDataModified = true; - } + int keyCell = (key - mKeyRange.lower) / (mKeyRange.upper - mKeyRange.lower) * (mKeySize - 1) + 0.5; + int valueCell = (value - mValueRange.lower) / (mValueRange.upper - mValueRange.lower) * (mValueSize - 1) + 0.5; + if (keyCell >= 0 && keyCell < mKeySize && valueCell >= 0 && valueCell < mValueSize) { + mData[valueCell * mKeySize + keyCell] = z; + if (z < mDataBounds.lower) { + mDataBounds.lower = z; + } + if (z > mDataBounds.upper) { + mDataBounds.upper = z; + } + mDataModified = true; + } } /*! Sets the data of the cell with indices \a keyIndex and \a valueIndex to \a z. The indices enumerate the cells starting from zero, up to the map's size-1 in the respective dimension (see \ref setSize). - + In the standard plot configuration (horizontal key axis and vertical value axis, both not range-reversed), the cell with indices (0, 0) is in the bottom left corner and the cell with indices (keySize-1, valueSize-1) is in the top right corner of the color map. - + \see setData, setSize */ void QCPColorMapData::setCell(int keyIndex, int valueIndex, double z) { - if (keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize) - { - mData[valueIndex*mKeySize + keyIndex] = z; - if (z < mDataBounds.lower) - mDataBounds.lower = z; - if (z > mDataBounds.upper) - mDataBounds.upper = z; - mDataModified = true; - } + if (keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize) { + mData[valueIndex * mKeySize + keyIndex] = z; + if (z < mDataBounds.lower) { + mDataBounds.lower = z; + } + if (z > mDataBounds.upper) { + mDataBounds.upper = z; + } + mDataModified = true; + } } /*! Goes through the data and updates the buffered minimum and maximum data values. - + Calling this method is only advised if you are about to call \ref QCPColorMap::rescaleDataRange and can not guarantee that the cells holding the maximum or minimum data haven't been overwritten with a smaller or larger value respectively, since the buffered maximum/minimum values have been updated the last time. Why this is the case is explained in the class description (\ref QCPColorMapData). - + Note that the method \ref QCPColorMap::rescaleDataRange provides a parameter \a recalculateDataBounds for convenience. Setting this to true will call this method for you, before doing the rescale. */ void QCPColorMapData::recalculateDataBounds() { - if (mKeySize > 0 && mValueSize > 0) - { - double minHeight = mData[0]; - double maxHeight = mData[0]; - const int dataCount = mValueSize*mKeySize; - for (int i=0; i maxHeight) - maxHeight = mData[i]; - if (mData[i] < minHeight) - minHeight = mData[i]; + if (mKeySize > 0 && mValueSize > 0) { + double minHeight = mData[0]; + double maxHeight = mData[0]; + const int dataCount = mValueSize * mKeySize; + for (int i = 0; i < dataCount; ++i) { + if (mData[i] > maxHeight) { + maxHeight = mData[i]; + } + if (mData[i] < minHeight) { + minHeight = mData[i]; + } + } + mDataBounds.lower = minHeight; + mDataBounds.upper = maxHeight; } - mDataBounds.lower = minHeight; - mDataBounds.upper = maxHeight; - } } /*! Frees the internal data memory. - + This is equivalent to calling \ref setSize "setSize(0, 0)". */ void QCPColorMapData::clear() { - setSize(0, 0); + setSize(0, 0); } /*! @@ -19915,59 +20130,64 @@ void QCPColorMapData::clear() */ void QCPColorMapData::fill(double z) { - const int dataCount = mValueSize*mKeySize; - for (int i=0; i(data); - return; - } - if (copy) - { - *mMapData = *data; - } else - { - delete mMapData; - mMapData = data; - } - mMapImageInvalidated = true; + if (mMapData == data) { + qDebug() << Q_FUNC_INFO << "The data pointer is already in (and owned by) this plottable" << reinterpret_cast(data); + return; + } + if (copy) { + *mMapData = *data; + } else { + delete mMapData; + mMapData = data; + } + mMapImageInvalidated = true; } /*! Sets the data range of this color map to \a dataRange. The data range defines which data values are mapped to the color gradient. - + To make the data range span the full range of the data set, use \ref rescaleDataRange. - + \see QCPColorScale::setDataRange */ void QCPColorMap::setDataRange(const QCPRange &dataRange) { - if (!QCPRange::validRange(dataRange)) return; - if (mDataRange.lower != dataRange.lower || mDataRange.upper != dataRange.upper) - { - if (mDataScaleType == QCPAxis::stLogarithmic) - mDataRange = dataRange.sanitizedForLogScale(); - else - mDataRange = dataRange.sanitizedForLinScale(); - mMapImageInvalidated = true; - emit dataRangeChanged(mDataRange); - } + if (!QCPRange::validRange(dataRange)) { + return; + } + if (mDataRange.lower != dataRange.lower || mDataRange.upper != dataRange.upper) { + if (mDataScaleType == QCPAxis::stLogarithmic) { + mDataRange = dataRange.sanitizedForLogScale(); + } else { + mDataRange = dataRange.sanitizedForLinScale(); + } + mMapImageInvalidated = true; + emit dataRangeChanged(mDataRange); + } } /*! Sets whether the data is correlated with the color gradient linearly or logarithmically. - + \see QCPColorScale::setDataScaleType */ void QCPColorMap::setDataScaleType(QCPAxis::ScaleType scaleType) { - if (mDataScaleType != scaleType) - { - mDataScaleType = scaleType; - mMapImageInvalidated = true; - emit dataScaleTypeChanged(mDataScaleType); - if (mDataScaleType == QCPAxis::stLogarithmic) - setDataRange(mDataRange.sanitizedForLogScale()); - } + if (mDataScaleType != scaleType) { + mDataScaleType = scaleType; + mMapImageInvalidated = true; + emit dataScaleTypeChanged(mDataScaleType); + if (mDataScaleType == QCPAxis::stLogarithmic) { + setDataRange(mDataRange.sanitizedForLogScale()); + } + } } /*! Sets the color gradient that is used to represent the data. For more details on how to create an own gradient or use one of the preset gradients, see \ref QCPColorGradient. - + The colors defined by the gradient will be used to represent data values in the currently set data range, see \ref setDataRange. Data points that are outside this data range will either be colored uniformly with the respective gradient boundary color, or the gradient will repeat, depending on \ref QCPColorGradient::setPeriodic. - + \see QCPColorScale::setGradient */ void QCPColorMap::setGradient(const QCPColorGradient &gradient) { - if (mGradient != gradient) - { - mGradient = gradient; - mMapImageInvalidated = true; - emit gradientChanged(mGradient); - } + if (mGradient != gradient) { + mGradient = gradient; + mMapImageInvalidated = true; + emit gradientChanged(mGradient); + } } /*! Sets whether the color map image shall use bicubic interpolation when displaying the color map shrinked or expanded, and not at a 1:1 pixel-to-data scale. - + \image html QCPColorMap-interpolate.png "A 10*10 color map, with interpolation and without interpolation enabled" */ void QCPColorMap::setInterpolate(bool enabled) { - mInterpolate = enabled; - mMapImageInvalidated = true; // because oversampling factors might need to change + mInterpolate = enabled; + mMapImageInvalidated = true; // because oversampling factors might need to change } /*! Sets whether the outer most data rows and columns are clipped to the specified key and value range (see \ref QCPColorMapData::setKeyRange, \ref QCPColorMapData::setValueRange). - + if \a enabled is set to false, the data points at the border of the color map are drawn with the same width and height as all other data points. Since the data points are represented by rectangles of one color centered on the data coordinate, this means that the shown color map extends by half a data point over the specified key/value range in each direction. - + \image html QCPColorMap-tightboundary.png "A color map, with tight boundary enabled and disabled" */ void QCPColorMap::setTightBoundary(bool enabled) { - mTightBoundary = enabled; + mTightBoundary = enabled; } /*! Associates the color scale \a colorScale with this color map. - + This means that both the color scale and the color map synchronize their gradient, data range and data scale type (\ref setGradient, \ref setDataRange, \ref setDataScaleType). Multiple color maps can be associated with one single color scale. This causes the color maps to also synchronize those properties, via the mutual color scale. - + This function causes the color map to adopt the current color gradient, data range and data scale type of \a colorScale. After this call, you may change these properties at either the color map or the color scale, and the setting will be applied to both. - + Pass 0 as \a colorScale to disconnect the color scale from this color map again. */ void QCPColorMap::setColorScale(QCPColorScale *colorScale) { - if (mColorScale) // unconnect signals from old color scale - { - disconnect(this, SIGNAL(dataRangeChanged(QCPRange)), mColorScale.data(), SLOT(setDataRange(QCPRange))); - disconnect(this, SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), mColorScale.data(), SLOT(setDataScaleType(QCPAxis::ScaleType))); - disconnect(this, SIGNAL(gradientChanged(QCPColorGradient)), mColorScale.data(), SLOT(setGradient(QCPColorGradient))); - disconnect(mColorScale.data(), SIGNAL(dataRangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange))); - disconnect(mColorScale.data(), SIGNAL(gradientChanged(QCPColorGradient)), this, SLOT(setGradient(QCPColorGradient))); - disconnect(mColorScale.data(), SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType))); - } - mColorScale = colorScale; - if (mColorScale) // connect signals to new color scale - { - setGradient(mColorScale.data()->gradient()); - setDataRange(mColorScale.data()->dataRange()); - setDataScaleType(mColorScale.data()->dataScaleType()); - connect(this, SIGNAL(dataRangeChanged(QCPRange)), mColorScale.data(), SLOT(setDataRange(QCPRange))); - connect(this, SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), mColorScale.data(), SLOT(setDataScaleType(QCPAxis::ScaleType))); - connect(this, SIGNAL(gradientChanged(QCPColorGradient)), mColorScale.data(), SLOT(setGradient(QCPColorGradient))); - connect(mColorScale.data(), SIGNAL(dataRangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange))); - connect(mColorScale.data(), SIGNAL(gradientChanged(QCPColorGradient)), this, SLOT(setGradient(QCPColorGradient))); - connect(mColorScale.data(), SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType))); - } + if (mColorScale) { // unconnect signals from old color scale + disconnect(this, SIGNAL(dataRangeChanged(QCPRange)), mColorScale.data(), SLOT(setDataRange(QCPRange))); + disconnect(this, SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), mColorScale.data(), SLOT(setDataScaleType(QCPAxis::ScaleType))); + disconnect(this, SIGNAL(gradientChanged(QCPColorGradient)), mColorScale.data(), SLOT(setGradient(QCPColorGradient))); + disconnect(mColorScale.data(), SIGNAL(dataRangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange))); + disconnect(mColorScale.data(), SIGNAL(gradientChanged(QCPColorGradient)), this, SLOT(setGradient(QCPColorGradient))); + disconnect(mColorScale.data(), SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType))); + } + mColorScale = colorScale; + if (mColorScale) { // connect signals to new color scale + setGradient(mColorScale.data()->gradient()); + setDataRange(mColorScale.data()->dataRange()); + setDataScaleType(mColorScale.data()->dataScaleType()); + connect(this, SIGNAL(dataRangeChanged(QCPRange)), mColorScale.data(), SLOT(setDataRange(QCPRange))); + connect(this, SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), mColorScale.data(), SLOT(setDataScaleType(QCPAxis::ScaleType))); + connect(this, SIGNAL(gradientChanged(QCPColorGradient)), mColorScale.data(), SLOT(setGradient(QCPColorGradient))); + connect(mColorScale.data(), SIGNAL(dataRangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange))); + connect(mColorScale.data(), SIGNAL(gradientChanged(QCPColorGradient)), this, SLOT(setGradient(QCPColorGradient))); + connect(mColorScale.data(), SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType))); + } } /*! Sets the data range (\ref setDataRange) to span the minimum and maximum values that occur in the current data set. This corresponds to the \ref rescaleKeyAxis or \ref rescaleValueAxis methods, only for the third data dimension of the color map. - + The minimum and maximum values of the data set are buffered in the internal QCPColorMapData instance (\ref data). As data is updated via its \ref QCPColorMapData::setCell or \ref QCPColorMapData::setData, the buffered minimum and maximum values are updated, too. For @@ -20261,41 +20477,42 @@ void QCPColorMap::setColorScale(QCPColorScale *colorScale) QCPColorMapData::recalculateDataBounds can be used. For convenience, setting the parameter \a recalculateDataBounds calls this method before setting the data range to the buffered minimum and maximum. - + \see setDataRange */ void QCPColorMap::rescaleDataRange(bool recalculateDataBounds) { - if (recalculateDataBounds) - mMapData->recalculateDataBounds(); - setDataRange(mMapData->dataBounds()); + if (recalculateDataBounds) { + mMapData->recalculateDataBounds(); + } + setDataRange(mMapData->dataBounds()); } /*! Takes the current appearance of the color map and updates the legend icon, which is used to represent this color map in the legend (see \ref QCPLegend). - + The \a transformMode specifies whether the rescaling is done by a faster, low quality image scaling algorithm (Qt::FastTransformation) or by a slower, higher quality algorithm (Qt::SmoothTransformation). - + The current color map appearance is scaled down to \a thumbSize. Ideally, this should be equal to the size of the legend icon (see \ref QCPLegend::setIconSize). If it isn't exactly the configured legend icon size, the thumb will be rescaled during drawing of the legend item. - + \see setDataRange */ void QCPColorMap::updateLegendIcon(Qt::TransformationMode transformMode, const QSize &thumbSize) { - if (mMapImage.isNull() && !data()->isEmpty()) - updateMapImage(); // try to update map image if it's null (happens if no draw has happened yet) - - if (!mMapImage.isNull()) // might still be null, e.g. if data is empty, so check here again - { - bool mirrorX = (keyAxis()->orientation() == Qt::Horizontal ? keyAxis() : valueAxis())->rangeReversed(); - bool mirrorY = (valueAxis()->orientation() == Qt::Vertical ? valueAxis() : keyAxis())->rangeReversed(); - mLegendIcon = QPixmap::fromImage(mMapImage.mirrored(mirrorX, mirrorY)).scaled(thumbSize, Qt::KeepAspectRatio, transformMode); - } + if (mMapImage.isNull() && !data()->isEmpty()) { + updateMapImage(); // try to update map image if it's null (happens if no draw has happened yet) + } + + if (!mMapImage.isNull()) { // might still be null, e.g. if data is empty, so check here again + bool mirrorX = (keyAxis()->orientation() == Qt::Horizontal ? keyAxis() : valueAxis())->rangeReversed(); + bool mirrorY = (valueAxis()->orientation() == Qt::Vertical ? valueAxis() : keyAxis())->rangeReversed(); + mLegendIcon = QPixmap::fromImage(mMapImage.mirrored(mirrorX, mirrorY)).scaled(thumbSize, Qt::KeepAspectRatio, transformMode); + } } /*! @@ -20304,36 +20521,40 @@ void QCPColorMap::updateLegendIcon(Qt::TransformationMode transformMode, const Q */ void QCPColorMap::clearData() { - mMapData->clear(); + mMapData->clear(); } /* inherits documentation from base class */ double QCPColorMap::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { - Q_UNUSED(details) - if (onlySelectable && !mSelectable) + Q_UNUSED(details) + if (onlySelectable && !mSelectable) { + 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)) { + return mParentPlot->selectionTolerance() * 0.99; + } + } 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)) - return mParentPlot->selectionTolerance()*0.99; - } - return -1; } /*! \internal - + Updates the internal map image buffer by going through the internal \ref QCPColorMapData and turning the data values into color pixels with \ref QCPColorGradient::colorize. - + This method is called by \ref QCPColorMap::draw if either the data has been modified or the map image has been invalidated for a different reason (e.g. a change of the data range with \ref setDataRange). - + If the map cell count is low, the image created will be oversampled in order to avoid a QPainter::drawImage bug which makes inner pixel boundaries jitter when stretch-drawing images without smooth transform enabled. Accordingly, oversampling isn't performed if \ref @@ -20341,196 +20562,202 @@ double QCPColorMap::selectTest(const QPointF &pos, bool onlySelectable, QVariant */ void QCPColorMap::updateMapImage() { - QCPAxis *keyAxis = mKeyAxis.data(); - if (!keyAxis) return; - if (mMapData->isEmpty()) return; - - 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 - int valueOversamplingFactor = mInterpolate ? 1 : (int)(1.0+100.0/(double)valueSize); // make mMapImage have at least size 100, factor becomes 1 if size > 200 or interpolation is on - - // 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); - else if (keyAxis->orientation() == Qt::Vertical && (mMapImage.width() != valueSize*valueOversamplingFactor || mMapImage.height() != keySize*keyOversamplingFactor)) - mMapImage = QImage(QSize(valueSize*valueOversamplingFactor, keySize*keyOversamplingFactor), QImage::Format_RGB32); - - 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); - else if (keyAxis->orientation() == Qt::Vertical && (mUndersampledMapImage.width() != valueSize || mUndersampledMapImage.height() != keySize)) - mUndersampledMapImage = QImage(QSize(valueSize, keySize), QImage::Format_RGB32); - 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; - if (keyAxis->orientation() == Qt::Horizontal) - { - const int lineCount = valueSize; - const int rowCount = keySize; - 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); + QCPAxis *keyAxis = mKeyAxis.data(); + if (!keyAxis) { + return; } - } else // keyAxis->orientation() == Qt::Vertical - { - const int lineCount = keySize; - const int rowCount = valueSize; - 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 (mMapData->isEmpty()) { + return; } - } - - if (keyOversamplingFactor > 1 || valueOversamplingFactor > 1) - { - if (keyAxis->orientation() == Qt::Horizontal) - mMapImage = mUndersampledMapImage.scaled(keySize*keyOversamplingFactor, valueSize*valueOversamplingFactor, Qt::IgnoreAspectRatio, Qt::FastTransformation); - else - mMapImage = mUndersampledMapImage.scaled(valueSize*valueOversamplingFactor, keySize*keyOversamplingFactor, Qt::IgnoreAspectRatio, Qt::FastTransformation); - } - mMapData->mDataModified = false; - mMapImageInvalidated = false; + + 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 + int valueOversamplingFactor = mInterpolate ? 1 : (int)(1.0 + 100.0 / (double)valueSize); // make mMapImage have at least size 100, factor becomes 1 if size > 200 or interpolation is on + + // 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); + } else if (keyAxis->orientation() == Qt::Vertical && (mMapImage.width() != valueSize * valueOversamplingFactor || mMapImage.height() != keySize * keyOversamplingFactor)) { + mMapImage = QImage(QSize(valueSize * valueOversamplingFactor, keySize * keyOversamplingFactor), QImage::Format_RGB32); + } + + 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); + } else if (keyAxis->orientation() == Qt::Vertical && (mUndersampledMapImage.width() != valueSize || mUndersampledMapImage.height() != keySize)) { + mUndersampledMapImage = QImage(QSize(valueSize, keySize), QImage::Format_RGB32); + } + 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; + if (keyAxis->orientation() == Qt::Horizontal) { + const int lineCount = valueSize; + const int rowCount = keySize; + for (int line = 0; line < lineCount; ++line) { + QRgb *pixels = reinterpret_cast(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); + } + } else { // keyAxis->orientation() == Qt::Vertical + const int lineCount = keySize; + const int rowCount = valueSize; + for (int line = 0; line < lineCount; ++line) { + QRgb *pixels = reinterpret_cast(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 (keyOversamplingFactor > 1 || valueOversamplingFactor > 1) { + if (keyAxis->orientation() == Qt::Horizontal) { + mMapImage = mUndersampledMapImage.scaled(keySize * keyOversamplingFactor, valueSize * valueOversamplingFactor, Qt::IgnoreAspectRatio, Qt::FastTransformation); + } else { + mMapImage = mUndersampledMapImage.scaled(valueSize * valueOversamplingFactor, keySize * keyOversamplingFactor, Qt::IgnoreAspectRatio, Qt::FastTransformation); + } + } + mMapData->mDataModified = false; + mMapImageInvalidated = false; } /* inherits documentation from base class */ void QCPColorMap::draw(QCPPainter *painter) { - if (mMapData->isEmpty()) return; - if (!mKeyAxis || !mValueAxis) return; - applyDefaultAntialiasingHint(painter); - - if (mMapData->mDataModified || mMapImageInvalidated) - updateMapImage(); - - // use buffer if painting vectorized (PDF): - 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) - { - mapBufferTarget = painter->clipRegion().boundingRect(); - mapBuffer = QPixmap((mapBufferTarget.size()*mapBufferPixelRatio).toSize()); - mapBuffer.fill(Qt::transparent); - localPainter = new QCPPainter(&mapBuffer); - localPainter->scale(mapBufferPixelRatio, mapBufferPixelRatio); - localPainter->translate(-mapBufferTarget.topLeft()); - } - - QRectF imageRect = QRectF(coordsToPixels(mMapData->keyRange().lower, mMapData->valueRange().lower), - coordsToPixels(mMapData->keyRange().upper, mMapData->valueRange().upper)).normalized(); - // extend imageRect to contain outer halves/quarters of bordering/cornering pixels (cells are centered on map range boundary): - double halfCellWidth = 0; // in pixels - double halfCellHeight = 0; // in pixels - if (keyAxis()->orientation() == Qt::Horizontal) - { - if (mMapData->keySize() > 1) - halfCellWidth = 0.5*imageRect.width()/(double)(mMapData->keySize()-1); - if (mMapData->valueSize() > 1) - halfCellHeight = 0.5*imageRect.height()/(double)(mMapData->valueSize()-1); - } else // keyAxis orientation is Qt::Vertical - { - if (mMapData->keySize() > 1) - halfCellHeight = 0.5*imageRect.height()/(double)(mMapData->keySize()-1); - if (mMapData->valueSize() > 1) - 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); - localPainter->setRenderHint(QPainter::SmoothPixmapTransform, mInterpolate); - QRegion clipBackup; - if (mTightBoundary) - { - clipBackup = localPainter->clipRegion(); - QRectF tightClipRect = QRectF(coordsToPixels(mMapData->keyRange().lower, mMapData->valueRange().lower), - coordsToPixels(mMapData->keyRange().upper, mMapData->valueRange().upper)).normalized(); - localPainter->setClipRect(tightClipRect, Qt::IntersectClip); - } - localPainter->drawImage(imageRect, mMapImage.mirrored(mirrorX, mirrorY)); - if (mTightBoundary) - localPainter->setClipRegion(clipBackup); - localPainter->setRenderHint(QPainter::SmoothPixmapTransform, smoothBackup); - - if (useBuffer) // localPainter painted to mapBuffer, so now draw buffer with original painter - { - delete localPainter; - painter->drawPixmap(mapBufferTarget.toRect(), mapBuffer); - } + if (mMapData->isEmpty()) { + return; + } + if (!mKeyAxis || !mValueAxis) { + return; + } + applyDefaultAntialiasingHint(painter); + + if (mMapData->mDataModified || mMapImageInvalidated) { + updateMapImage(); + } + + // use buffer if painting vectorized (PDF): + 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) { + mapBufferTarget = painter->clipRegion().boundingRect(); + mapBuffer = QPixmap((mapBufferTarget.size() * mapBufferPixelRatio).toSize()); + mapBuffer.fill(Qt::transparent); + localPainter = new QCPPainter(&mapBuffer); + localPainter->scale(mapBufferPixelRatio, mapBufferPixelRatio); + localPainter->translate(-mapBufferTarget.topLeft()); + } + + QRectF imageRect = QRectF(coordsToPixels(mMapData->keyRange().lower, mMapData->valueRange().lower), + coordsToPixels(mMapData->keyRange().upper, mMapData->valueRange().upper)).normalized(); + // extend imageRect to contain outer halves/quarters of bordering/cornering pixels (cells are centered on map range boundary): + double halfCellWidth = 0; // in pixels + double halfCellHeight = 0; // in pixels + if (keyAxis()->orientation() == Qt::Horizontal) { + if (mMapData->keySize() > 1) { + halfCellWidth = 0.5 * imageRect.width() / (double)(mMapData->keySize() - 1); + } + if (mMapData->valueSize() > 1) { + halfCellHeight = 0.5 * imageRect.height() / (double)(mMapData->valueSize() - 1); + } + } else { // keyAxis orientation is Qt::Vertical + if (mMapData->keySize() > 1) { + halfCellHeight = 0.5 * imageRect.height() / (double)(mMapData->keySize() - 1); + } + if (mMapData->valueSize() > 1) { + 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); + localPainter->setRenderHint(QPainter::SmoothPixmapTransform, mInterpolate); + QRegion clipBackup; + if (mTightBoundary) { + clipBackup = localPainter->clipRegion(); + QRectF tightClipRect = QRectF(coordsToPixels(mMapData->keyRange().lower, mMapData->valueRange().lower), + coordsToPixels(mMapData->keyRange().upper, mMapData->valueRange().upper)).normalized(); + localPainter->setClipRect(tightClipRect, Qt::IntersectClip); + } + localPainter->drawImage(imageRect, mMapImage.mirrored(mirrorX, mirrorY)); + if (mTightBoundary) { + localPainter->setClipRegion(clipBackup); + } + localPainter->setRenderHint(QPainter::SmoothPixmapTransform, smoothBackup); + + if (useBuffer) { // localPainter painted to mapBuffer, so now draw buffer with original painter + delete localPainter; + painter->drawPixmap(mapBufferTarget.toRect(), mapBuffer); + } } /* inherits documentation from base class */ void QCPColorMap::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const { - applyDefaultAntialiasingHint(painter); - // draw map thumbnail: - if (!mLegendIcon.isNull()) - { - QPixmap scaledIcon = mLegendIcon.scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::FastTransformation); - QRectF iconRect = QRectF(0, 0, scaledIcon.width(), scaledIcon.height()); - iconRect.moveCenter(rect.center()); - painter->drawPixmap(iconRect.topLeft(), scaledIcon); - } - /* - // draw frame: - painter->setBrush(Qt::NoBrush); - painter->setPen(Qt::black); - painter->drawRect(rect.adjusted(1, 1, 0, 0)); - */ + applyDefaultAntialiasingHint(painter); + // draw map thumbnail: + if (!mLegendIcon.isNull()) { + QPixmap scaledIcon = mLegendIcon.scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::FastTransformation); + QRectF iconRect = QRectF(0, 0, scaledIcon.width(), scaledIcon.height()); + iconRect.moveCenter(rect.center()); + painter->drawPixmap(iconRect.topLeft(), scaledIcon); + } + /* + // draw frame: + painter->setBrush(Qt::NoBrush); + painter->setPen(Qt::black); + painter->drawRect(rect.adjusted(1, 1, 0, 0)); + */ } /* 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; + 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; + 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; } @@ -20540,16 +20767,16 @@ 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 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 */ @@ -20557,11 +20784,11 @@ QCPRange QCPColorMap::getValueRange(bool &foundRange, SignDomain inSignDomain) c Constructs a data point with key and all values set to zero. */ QCPFinancialData::QCPFinancialData() : - key(0), - open(0), - high(0), - low(0), - close(0) + key(0), + open(0), + high(0), + low(0), + close(0) { } @@ -20569,11 +20796,11 @@ QCPFinancialData::QCPFinancialData() : Constructs a data point with the specified \a key and OHLC values. */ QCPFinancialData::QCPFinancialData(double key, double open, double high, double low, double close) : - key(key), - open(open), - high(high), - low(low), - close(close) + key(key), + open(open), + high(high), + low(low), + close(close) { } @@ -20586,38 +20813,38 @@ 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 - + 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, irrespective of whether the chart is single- or two-colored. - + */ /* start of documentation of inline functions */ /*! \fn QCPFinancialDataMap *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. @@ -20630,80 +20857,76 @@ QCPFinancialData::QCPFinancialData(double key, double open, double high, double 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 QCPFinancial can be added to the plot with QCustomPlot::addPlottable, QCustomPlot then takes ownership of the financial chart. */ QCPFinancial::QCPFinancial(QCPAxis *keyAxis, QCPAxis *valueAxis) : - QCPAbstractPlottable(keyAxis, valueAxis), - mData(0), - mChartStyle(csOhlc), - 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))) + QCPAbstractPlottable(keyAxis, valueAxis), + mData(0), + mChartStyle(csOhlc), + 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))) { - mData = new QCPFinancialDataMap; - - setSelectedPen(QPen(QColor(80, 80, 255), 2.5)); - setSelectedBrush(QBrush(QColor(80, 80, 255))); + mData = new QCPFinancialDataMap; + + setSelectedPen(QPen(QColor(80, 80, 255), 2.5)); + setSelectedBrush(QBrush(QColor(80, 80, 255))); } QCPFinancial::~QCPFinancial() { - delete mData; + 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; - } + 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. - + \see timeSeriesToOhlc */ void QCPFinancial::setData(const QVector &key, const QVector &open, const QVector &high, const QVector &low, const QVector &close) { - 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])); - } + 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; i < n; ++i) { + mData->insertMulti(key[i], QCPFinancialData(key[i], open[i], high[i], low[i], close[i])); + } } /*! @@ -20711,196 +20934,202 @@ void QCPFinancial::setData(const QVector &key, const QVector &op */ void QCPFinancial::setChartStyle(QCPFinancial::ChartStyle style) { - mChartStyle = style; + mChartStyle = style; } /*! Sets the width of the individual bars/candlesticks to \a width in plot key coordinates. - + A typical choice is to set it to (or slightly less than) one bin interval width. */ void QCPFinancial::setWidth(double width) { - mWidth = width; + mWidth = width; } /*! Sets whether this chart shall contrast positive from negative trends per data point by using two separate colors to draw the respective bars/candlesticks. - + If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref setBrush). - + \see setPenPositive, setPenNegative, setBrushPositive, setBrushNegative */ void QCPFinancial::setTwoColored(bool twoColored) { - mTwoColored = twoColored; + mTwoColored = twoColored; } /*! If \ref setTwoColored is set to true, this function controls the brush that is used to draw fills of data points with a positive trend (i.e. bars/candlesticks with close >= open). - + If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref setBrush). - + \see setBrushNegative, setPenPositive, setPenNegative */ void QCPFinancial::setBrushPositive(const QBrush &brush) { - mBrushPositive = brush; + mBrushPositive = brush; } /*! If \ref setTwoColored is set to true, this function controls the brush that is used to draw fills of data points with a negative trend (i.e. bars/candlesticks with close < open). - + If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref setBrush). - + \see setBrushPositive, setPenNegative, setPenPositive */ void QCPFinancial::setBrushNegative(const QBrush &brush) { - mBrushNegative = brush; + mBrushNegative = brush; } /*! If \ref setTwoColored is set to true, this function controls the pen that is used to draw outlines of data points with a positive trend (i.e. bars/candlesticks with close >= open). - + If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref setBrush). - + \see setPenNegative, setBrushPositive, setBrushNegative */ void QCPFinancial::setPenPositive(const QPen &pen) { - mPenPositive = pen; + mPenPositive = pen; } /*! If \ref setTwoColored is set to true, this function controls the pen that is used to draw outlines of data points with a negative trend (i.e. bars/candlesticks with close < open). - + If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref setBrush). - + \see setPenPositive, setBrushNegative, setBrushPositive */ void QCPFinancial::setPenNegative(const QPen &pen) { - mPenNegative = pen; + mPenNegative = pen; } /*! Adds the provided data points in \a dataMap 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 QCPFinancialDataMap. - + \see removeData */ void QCPFinancial::addData(const QCPFinancialDataMap &dataMap) { - mData->unite(dataMap); + mData->unite(dataMap); } /*! \overload - + Adds the provided single data point in \a data to the current data. - + Alternatively, you can also access and modify the data via the \ref data method, which returns a pointer to the internal \ref QCPFinancialData. - + \see removeData */ void QCPFinancial::addData(const QCPFinancialData &data) { - mData->insertMulti(data.key, 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 */ void QCPFinancial::addData(double key, double open, double high, double low, double close) { - mData->insertMulti(key, QCPFinancialData(key, open, high, low, close)); + mData->insertMulti(key, 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 */ void QCPFinancial::addData(const QVector &key, const QVector &open, const QVector &high, const QVector &low, const QVector &close) { - 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])); - } + 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; i < n; ++i) { + mData->insertMulti(key[i], QCPFinancialData(key[i], open[i], high[i], low[i], close[i])); + } } /*! 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); + 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); + 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); + 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. @@ -20909,54 +21138,59 @@ void QCPFinancial::removeData(double fromKey, double toKey) */ void QCPFinancial::removeData(double key) { - mData->remove(key); + mData->remove(key); } /*! Removes all data points. - + \see removeData, removeDataAfter, removeDataBefore */ void QCPFinancial::clearData() { - mData->clear(); + mData->clear(); } /* inherits documentation from base class */ double QCPFinancial::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { - Q_UNUSED(details) - if (onlySelectable && !mSelectable) - 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; - // perform select test according to configured style: - switch (mChartStyle) - { - case QCPFinancial::csOhlc: - return ohlcSelectTest(pos, lower, upper+1); break; - case QCPFinancial::csCandlestick: - return candlestickSelectTest(pos, lower, upper+1); break; + Q_UNUSED(details) + if (onlySelectable && !mSelectable) { + return -1; } - } - 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; + } + // perform select test according to configured style: + switch (mChartStyle) { + case QCPFinancial::csOhlc: + return ohlcSelectTest(pos, lower, upper + 1); + break; + case QCPFinancial::csCandlestick: + return candlestickSelectTest(pos, lower, upper + 1); + break; + } + } + return -1; } /*! 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. - + 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 each, set \a timeBinSize to 3600. - + \a timeBinOffset allows to control precisely at what \a time coordinate a bin should start. The value passed as \a timeBinOffset doesn't need to be in the range encompassed by the \a time keys. It merely defines the mathematical offset/phase of the bins that will be used to process the @@ -20964,492 +21198,470 @@ double QCPFinancial::selectTest(const QPointF &pos, bool onlySelectable, QVarian */ QCPFinancialDataMap QCPFinancial::timeSeriesToOhlc(const QVector &time, const QVector &value, double timeBinSize, double timeBinOffset) { - QCPFinancialDataMap map; - int count = qMin(time.size(), value.size()); - if (count == 0) - return QCPFinancialDataMap(); - - QCPFinancialData currentBinData(0, value.first(), value.first(), value.first(), value.first()); - int currentBinIndex = qFloor((time.first()-timeBinOffset)/timeBinSize+0.5); - for (int i=0; i currentBinData.high) currentBinData.high = value.at(i); - if (i == count-1) // last data point is in current bin, finalize bin: - { - currentBinData.close = value.at(i); - currentBinData.key = timeBinOffset+(index)*timeBinSize; - map.insert(currentBinData.key, 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); - // start next bin: - currentBinIndex = index; - currentBinData.open = value.at(i); - currentBinData.high = value.at(i); - currentBinData.low = value.at(i); + QCPFinancialDataMap map; + int count = qMin(time.size(), value.size()); + if (count == 0) { + return QCPFinancialDataMap(); } - } - - return map; + + QCPFinancialData currentBinData(0, value.first(), value.first(), value.first(), value.first()); + int currentBinIndex = qFloor((time.first() - timeBinOffset) / timeBinSize + 0.5); + for (int i = 0; i < count; ++i) { + int index = qFloor((time.at(i) - timeBinOffset) / timeBinSize + 0.5); + if (currentBinIndex == index) { // data point still in current bin, extend high/low: + if (value.at(i) < currentBinData.low) { + currentBinData.low = value.at(i); + } + if (value.at(i) > currentBinData.high) { + currentBinData.high = value.at(i); + } + if (i == count - 1) { // last data point is in current bin, finalize bin: + currentBinData.close = value.at(i); + currentBinData.key = timeBinOffset + (index) * timeBinSize; + map.insert(currentBinData.key, 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); + // start next bin: + currentBinIndex = index; + currentBinData.open = value.at(i); + currentBinData.high = value.at(i); + currentBinData.low = value.at(i); + } + } + + return map; } /* 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; - - // draw visible data range according to configured style: - switch (mChartStyle) - { - case QCPFinancial::csOhlc: - drawOhlcPlot(painter, lower, upper+1); break; - case QCPFinancial::csCandlestick: - drawCandlestickPlot(painter, lower, upper+1); break; - } + // 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; + } + + // draw visible data range according to configured style: + switch (mChartStyle) { + case QCPFinancial::csOhlc: + drawOhlcPlot(painter, lower, upper + 1); + break; + case QCPFinancial::csCandlestick: + drawCandlestickPlot(painter, lower, upper + 1); + break; + } } /* inherits documentation from base class */ void QCPFinancial::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const { - painter->setAntialiasing(false); // legend icon especially of csCandlestick looks better without antialiasing - if (mChartStyle == csOhlc) - { - if (mTwoColored) - { - // draw upper left half icon with positive color: - painter->setBrush(mBrushPositive); - painter->setPen(mPenPositive); - painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.topLeft().toPoint())); - 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: - painter->setBrush(mBrushNegative); - painter->setPen(mPenNegative); - painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.bottomRight().toPoint())); - 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())); - } else - { - painter->setBrush(mBrush); - painter->setPen(mPen); - 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())); + painter->setAntialiasing(false); // legend icon especially of csCandlestick looks better without antialiasing + if (mChartStyle == csOhlc) { + if (mTwoColored) { + // draw upper left half icon with positive color: + painter->setBrush(mBrushPositive); + painter->setPen(mPenPositive); + painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.topLeft().toPoint())); + 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: + painter->setBrush(mBrushNegative); + painter->setPen(mPenNegative); + painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.bottomRight().toPoint())); + 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())); + } else { + painter->setBrush(mBrush); + painter->setPen(mPen); + 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())); + } + } else if (mChartStyle == csCandlestick) { + if (mTwoColored) { + // draw upper left half icon with positive color: + painter->setBrush(mBrushPositive); + painter->setPen(mPenPositive); + painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.topLeft().toPoint())); + 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: + painter->setBrush(mBrushNegative); + painter->setPen(mPenNegative); + painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.bottomRight().toPoint())); + 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())); + } else { + painter->setBrush(mBrush); + painter->setPen(mPen); + 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())); + } } - } else if (mChartStyle == csCandlestick) - { - if (mTwoColored) - { - // draw upper left half icon with positive color: - painter->setBrush(mBrushPositive); - painter->setPen(mPenPositive); - painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.topLeft().toPoint())); - 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: - painter->setBrush(mBrushNegative); - painter->setPen(mPenNegative); - painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.bottomRight().toPoint())); - 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())); - } else - { - painter->setBrush(mBrush); - painter->setPen(mPen); - 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())); - } - } } /* 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; - } + 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; } - ++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; + // 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; - } + 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; } - // 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; + + foundRange = haveLower && haveUpper; + return range; } /*! \internal - + Draws the data from \a begin to \a end 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) { - 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) - { - if (mSelected) - linePen = mSelectedPen; - else if (mTwoColored) - linePen = it.value().close >= it.value().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); - // draw backbone: - painter->drawLine(QPointF(keyPixel, valueAxis->coordToPixel(it.value().high)), QPointF(keyPixel, valueAxis->coordToPixel(it.value().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)); - // draw close: - painter->drawLine(QPointF(keyPixel, closePixel), QPointF(keyPixel+keyWidthPixels, closePixel)); + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + return; } - } else - { - for (QCPFinancialDataMap::const_iterator it = begin; it != end; ++it) - { - if (mSelected) - linePen = mSelectedPen; - else if (mTwoColored) - linePen = it.value().close >= it.value().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); - // draw backbone: - painter->drawLine(QPointF(valueAxis->coordToPixel(it.value().high), keyPixel), QPointF(valueAxis->coordToPixel(it.value().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)); - // draw close: - painter->drawLine(QPointF(closePixel, keyPixel), QPointF(closePixel, keyPixel+keyWidthPixels)); + + QPen linePen; + + if (keyAxis->orientation() == Qt::Horizontal) { + for (QCPFinancialDataMap::const_iterator it = begin; it != end; ++it) { + if (mSelected) { + linePen = mSelectedPen; + } else if (mTwoColored) { + linePen = it.value().close >= it.value().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); + // draw backbone: + painter->drawLine(QPointF(keyPixel, valueAxis->coordToPixel(it.value().high)), QPointF(keyPixel, valueAxis->coordToPixel(it.value().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)); + // draw close: + painter->drawLine(QPointF(keyPixel, closePixel), QPointF(keyPixel + keyWidthPixels, closePixel)); + } + } else { + for (QCPFinancialDataMap::const_iterator it = begin; it != end; ++it) { + if (mSelected) { + linePen = mSelectedPen; + } else if (mTwoColored) { + linePen = it.value().close >= it.value().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); + // draw backbone: + painter->drawLine(QPointF(valueAxis->coordToPixel(it.value().high), keyPixel), QPointF(valueAxis->coordToPixel(it.value().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)); + // draw close: + painter->drawLine(QPointF(closePixel, keyPixel), QPointF(closePixel, keyPixel + keyWidthPixels)); + } } - } } /*! \internal - + Draws the data from \a begin to \a end 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) { - 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) - { - if (mSelected) - { - linePen = mSelectedPen; - boxBrush = mSelectedBrush; - } else if (mTwoColored) - { - if (it.value().close >= it.value().open) - { - linePen = mPenPositive; - boxBrush = mBrushPositive; - } else - { - linePen = mPenNegative; - boxBrush = mBrushNegative; - } - } else - { - linePen = mPen; - boxBrush = 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); - // draw high: - painter->drawLine(QPointF(keyPixel, valueAxis->coordToPixel(it.value().high)), QPointF(keyPixel, valueAxis->coordToPixel(qMax(it.value().open, it.value().close)))); - // draw low: - painter->drawLine(QPointF(keyPixel, valueAxis->coordToPixel(it.value().low)), QPointF(keyPixel, valueAxis->coordToPixel(qMin(it.value().open, it.value().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))); + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + return; } - } else // keyAxis->orientation() == Qt::Vertical - { - for (QCPFinancialDataMap::const_iterator it = begin; it != end; ++it) - { - if (mSelected) - { - linePen = mSelectedPen; - boxBrush = mSelectedBrush; - } else if (mTwoColored) - { - if (it.value().close >= it.value().open) - { - linePen = mPenPositive; - boxBrush = mBrushPositive; - } else - { - linePen = mPenNegative; - boxBrush = mBrushNegative; + + QPen linePen; + QBrush boxBrush; + + if (keyAxis->orientation() == Qt::Horizontal) { + for (QCPFinancialDataMap::const_iterator it = begin; it != end; ++it) { + if (mSelected) { + linePen = mSelectedPen; + boxBrush = mSelectedBrush; + } else if (mTwoColored) { + if (it.value().close >= it.value().open) { + linePen = mPenPositive; + boxBrush = mBrushPositive; + } else { + linePen = mPenNegative; + boxBrush = mBrushNegative; + } + } else { + linePen = mPen; + boxBrush = 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); + // draw high: + painter->drawLine(QPointF(keyPixel, valueAxis->coordToPixel(it.value().high)), QPointF(keyPixel, valueAxis->coordToPixel(qMax(it.value().open, it.value().close)))); + // draw low: + painter->drawLine(QPointF(keyPixel, valueAxis->coordToPixel(it.value().low)), QPointF(keyPixel, valueAxis->coordToPixel(qMin(it.value().open, it.value().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))); + } + } else { // keyAxis->orientation() == Qt::Vertical + for (QCPFinancialDataMap::const_iterator it = begin; it != end; ++it) { + if (mSelected) { + linePen = mSelectedPen; + boxBrush = mSelectedBrush; + } else if (mTwoColored) { + if (it.value().close >= it.value().open) { + linePen = mPenPositive; + boxBrush = mBrushPositive; + } else { + linePen = mPenNegative; + boxBrush = mBrushNegative; + } + } else { + linePen = mPen; + boxBrush = 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); + // draw high: + painter->drawLine(QPointF(valueAxis->coordToPixel(it.value().high), keyPixel), QPointF(valueAxis->coordToPixel(qMax(it.value().open, it.value().close)), keyPixel)); + // draw low: + painter->drawLine(QPointF(valueAxis->coordToPixel(it.value().low), keyPixel), QPointF(valueAxis->coordToPixel(qMin(it.value().open, it.value().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))); } - } else - { - linePen = mPen; - boxBrush = 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); - // draw high: - painter->drawLine(QPointF(valueAxis->coordToPixel(it.value().high), keyPixel), QPointF(valueAxis->coordToPixel(qMax(it.value().open, it.value().close)), keyPixel)); - // draw low: - painter->drawLine(QPointF(valueAxis->coordToPixel(it.value().low), keyPixel), QPointF(valueAxis->coordToPixel(qMin(it.value().open, it.value().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))); } - } } /*! \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. */ double QCPFinancial::ohlcSelectTest(const QPointF &pos, const QCPFinancialDataMap::const_iterator &begin, const QCPFinancialDataMap::const_iterator &end) const { - QCPAxis *keyAxis = mKeyAxis.data(); - QCPAxis *valueAxis = mValueAxis.data(); - if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; } + 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) - { - double keyPixel = keyAxis->coordToPixel(it.value().key); - // calculate distance to backbone: - double currentDistSqr = distSqrToLine(QPointF(keyPixel, valueAxis->coordToPixel(it.value().high)), QPointF(keyPixel, valueAxis->coordToPixel(it.value().low)), pos); - if (currentDistSqr < minDistSqr) - minDistSqr = currentDistSqr; + double minDistSqr = std::numeric_limits::max(); + QCPFinancialDataMap::const_iterator it; + if (keyAxis->orientation() == Qt::Horizontal) { + for (it = begin; it != end; ++it) { + double keyPixel = keyAxis->coordToPixel(it.value().key); + // calculate distance to backbone: + double currentDistSqr = distSqrToLine(QPointF(keyPixel, valueAxis->coordToPixel(it.value().high)), QPointF(keyPixel, valueAxis->coordToPixel(it.value().low)), pos); + if (currentDistSqr < minDistSqr) { + minDistSqr = currentDistSqr; + } + } + } else { // keyAxis->orientation() == Qt::Vertical + for (it = begin; it != end; ++it) { + double keyPixel = keyAxis->coordToPixel(it.value().key); + // calculate distance to backbone: + double currentDistSqr = distSqrToLine(QPointF(valueAxis->coordToPixel(it.value().high), keyPixel), QPointF(valueAxis->coordToPixel(it.value().low), keyPixel), pos); + if (currentDistSqr < minDistSqr) { + minDistSqr = currentDistSqr; + } + } } - } else // keyAxis->orientation() == Qt::Vertical - { - for (it = begin; it != end; ++it) - { - double keyPixel = keyAxis->coordToPixel(it.value().key); - // calculate distance to backbone: - double currentDistSqr = distSqrToLine(QPointF(valueAxis->coordToPixel(it.value().high), keyPixel), QPointF(valueAxis->coordToPixel(it.value().low), keyPixel), pos); - if (currentDistSqr < minDistSqr) - minDistSqr = currentDistSqr; - } - } - return qSqrt(minDistSqr); + return qSqrt(minDistSqr); } /*! \internal - + 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. */ double QCPFinancial::candlestickSelectTest(const QPointF &pos, const QCPFinancialDataMap::const_iterator &begin, const QCPFinancialDataMap::const_iterator &end) const { - QCPAxis *keyAxis = mKeyAxis.data(); - QCPAxis *valueAxis = mValueAxis.data(); - if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; } + 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) - { - 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); - double posKey, posValue; - pixelsToCoords(pos, posKey, posValue); - if (boxKeyRange.contains(posKey) && boxValueRange.contains(posValue)) // is in open-close-box - { - currentDistSqr = mParentPlot->selectionTolerance()*0.99 * mParentPlot->selectionTolerance()*0.99; - } 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); - currentDistSqr = qMin(highLineDistSqr, lowLineDistSqr); - } - if (currentDistSqr < minDistSqr) - minDistSqr = currentDistSqr; + double minDistSqr = std::numeric_limits::max(); + QCPFinancialDataMap::const_iterator it; + if (keyAxis->orientation() == Qt::Horizontal) { + for (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); + double posKey, posValue; + pixelsToCoords(pos, posKey, posValue); + if (boxKeyRange.contains(posKey) && boxValueRange.contains(posValue)) { // is in open-close-box + currentDistSqr = mParentPlot->selectionTolerance() * 0.99 * mParentPlot->selectionTolerance() * 0.99; + } 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); + currentDistSqr = qMin(highLineDistSqr, lowLineDistSqr); + } + if (currentDistSqr < minDistSqr) { + minDistSqr = currentDistSqr; + } + } + } else { // keyAxis->orientation() == Qt::Vertical + for (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); + double posKey, posValue; + pixelsToCoords(pos, posKey, posValue); + if (boxKeyRange.contains(posKey) && boxValueRange.contains(posValue)) { // is in open-close-box + currentDistSqr = mParentPlot->selectionTolerance() * 0.99 * mParentPlot->selectionTolerance() * 0.99; + } 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); + currentDistSqr = qMin(highLineDistSqr, lowLineDistSqr); + } + if (currentDistSqr < minDistSqr) { + minDistSqr = currentDistSqr; + } + } } - } else // keyAxis->orientation() == Qt::Vertical - { - for (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); - double posKey, posValue; - pixelsToCoords(pos, posKey, posValue); - if (boxKeyRange.contains(posKey) && boxValueRange.contains(posValue)) // is in open-close-box - { - currentDistSqr = mParentPlot->selectionTolerance()*0.99 * mParentPlot->selectionTolerance()*0.99; - } 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); - currentDistSqr = qMin(highLineDistSqr, lowLineDistSqr); - } - if (currentDistSqr < minDistSqr) - minDistSqr = currentDistSqr; - } - } - return qSqrt(minDistSqr); + return qSqrt(minDistSqr); } /*! \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 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 plottable contains no data, both \a lower and \a upper point to constEnd. - + \see QCPGraph::getVisibleDataBounds */ void QCPFinancial::getVisibleDataBounds(QCPFinancialDataMap::const_iterator &lower, QCPFinancialDataMap::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 - 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 + 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 + 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 } @@ -21467,19 +21679,19 @@ 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. */ QCPItemStraightLine::QCPItemStraightLine(QCustomPlot *parentPlot) : - QCPAbstractItem(parentPlot), - point1(createPosition(QLatin1String("point1"))), - point2(createPosition(QLatin1String("point2"))) + QCPAbstractItem(parentPlot), + point1(createPosition(QLatin1String("point1"))), + point2(createPosition(QLatin1String("point2"))) { - point1->setCoords(0, 0); - point2->setCoords(1, 1); - - setPen(QPen(Qt::black)); - setSelectedPen(QPen(Qt::blue,2)); + point1->setCoords(0, 0); + point2->setCoords(1, 1); + + setPen(QPen(Qt::black)); + setSelectedPen(QPen(Qt::blue, 2)); } QCPItemStraightLine::~QCPItemStraightLine() @@ -21488,146 +21700,145 @@ QCPItemStraightLine::~QCPItemStraightLine() /*! Sets the pen that will be used to draw the line - + \see setSelectedPen */ void QCPItemStraightLine::setPen(const QPen &pen) { - mPen = pen; + mPen = pen; } /*! Sets the pen that will be used to draw the line when selected - + \see setPen, setSelected */ void QCPItemStraightLine::setSelectedPen(const QPen &pen) { - mSelectedPen = pen; + mSelectedPen = pen; } /* inherits documentation from base class */ double QCPItemStraightLine::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { - Q_UNUSED(details) - if (onlySelectable && !mSelectable) - return -1; - - return distToStraightLine(QVector2D(point1->pixelPoint()), QVector2D(point2->pixelPoint()-point1->pixelPoint()), QVector2D(pos)); + Q_UNUSED(details) + if (onlySelectable && !mSelectable) { + return -1; + } + + return distToStraightLine(QVector2D(point1->pixelPoint()), QVector2D(point2->pixelPoint() - point1->pixelPoint()), QVector2D(pos)); } /* inherits documentation from base class */ void QCPItemStraightLine::draw(QCPPainter *painter) { - QVector2D start(point1->pixelPoint()); - QVector2D end(point2->pixelPoint()); - // get visible segment of straight line inside clipRect: - double clipPad = mainPen().widthF(); - QLineF line = getRectClippedStraightLine(start, end-start, clipRect().adjusted(-clipPad, -clipPad, clipPad, clipPad)); - // paint visible segment, if existent: - if (!line.isNull()) - { - painter->setPen(mainPen()); - painter->drawLine(line); - } + QVector2D start(point1->pixelPoint()); + QVector2D end(point2->pixelPoint()); + // get visible segment of straight line inside clipRect: + double clipPad = mainPen().widthF(); + QLineF line = getRectClippedStraightLine(start, end - start, clipRect().adjusted(-clipPad, -clipPad, clipPad, clipPad)); + // paint visible segment, if existent: + if (!line.isNull()) { + painter->setPen(mainPen()); + painter->drawLine(line); + } } /*! \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(); + 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 vec, that is visible in the specified \a rect. - + This is a helper function for \ref draw. */ QLineF QCPItemStraightLine::getRectClippedStraightLine(const QVector2D &base, const QVector2D &vec, const QRect &rect) const { - double bx, by; - double gamma; - QLineF result; - if (vec.x() == 0 && vec.y() == 0) - return result; - if (qFuzzyIsNull(vec.x())) // line is vertical - { - // 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()) - result.setLine(bx+gamma, rect.top(), bx+gamma, rect.bottom()); // no need to check bottom because we know line is vertical - } else if (qFuzzyIsNull(vec.y())) // line is horizontal - { - // 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()) - 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; - // 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)); - // 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)); - // 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)); - // 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)); - - // evaluate points: - if (pointVectors.size() == 2) - { - result.setPoints(pointVectors.at(0).toPointF(), pointVectors.at(1).toPointF()); - } else if (pointVectors.size() > 2) - { - // 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; - for (int i=0; i distSqrMax) - { - pv1 = pointVectors.at(i); - pv2 = pointVectors.at(k); - distSqrMax = distSqr; - } - } - } - result.setPoints(pv1.toPointF(), pv2.toPointF()); + double bx, by; + double gamma; + QLineF result; + if (vec.x() == 0 && vec.y() == 0) { + return result; } - } - return result; + if (qFuzzyIsNull(vec.x())) { // line is vertical + // 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()) { + result.setLine(bx + gamma, rect.top(), bx + gamma, rect.bottom()); // no need to check bottom because we know line is vertical + } + } else if (qFuzzyIsNull(vec.y())) { // line is horizontal + // 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()) { + 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; + // 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)); + } + // 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)); + } + // 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)); + } + // 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)); + } + + // evaluate points: + if (pointVectors.size() == 2) { + result.setPoints(pointVectors.at(0).toPointF(), pointVectors.at(1).toPointF()); + } else if (pointVectors.size() > 2) { + // 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; + for (int i = 0; i < pointVectors.size() - 1; ++i) { + for (int k = i + 1; k < pointVectors.size(); ++k) { + double distSqr = (pointVectors.at(i) - pointVectors.at(k)).lengthSquared(); + if (distSqr > distSqrMax) { + pv1 = pointVectors.at(i); + pv2 = pointVectors.at(k); + distSqrMax = distSqr; + } + } + } + result.setPoints(pv1.toPointF(), pv2.toPointF()); + } + } + return result; } /*! \internal @@ -21637,7 +21848,7 @@ QLineF QCPItemStraightLine::getRectClippedStraightLine(const QVector2D &base, co */ QPen QCPItemStraightLine::mainPen() const { - return mSelected ? mSelectedPen : mPen; + return mSelected ? mSelectedPen : mPen; } @@ -21651,25 +21862,25 @@ QPen QCPItemStraightLine::mainPen() const \image html QCPItemLine.png "Line example. Blue dotted circles are anchors, solid blue discs are positions." It has two positions, \a start and \a end, which define the end points of the line. - + With \ref setHead and \ref setTail you may set different line ending styles, e.g. to create an arrow. */ /*! Creates a line item and sets default values. - + The constructed item can be added to the plot with QCustomPlot::addItem. */ QCPItemLine::QCPItemLine(QCustomPlot *parentPlot) : - QCPAbstractItem(parentPlot), - start(createPosition(QLatin1String("start"))), - end(createPosition(QLatin1String("end"))) + QCPAbstractItem(parentPlot), + start(createPosition(QLatin1String("start"))), + end(createPosition(QLatin1String("end"))) { - start->setCoords(0, 0); - end->setCoords(1, 1); - - setPen(QPen(Qt::black)); - setSelectedPen(QPen(Qt::blue,2)); + start->setCoords(0, 0); + end->setCoords(1, 1); + + setPen(QPen(Qt::black)); + setSelectedPen(QPen(Qt::blue, 2)); } QCPItemLine::~QCPItemLine() @@ -21678,182 +21889,181 @@ QCPItemLine::~QCPItemLine() /*! Sets the pen that will be used to draw the line - + \see setSelectedPen */ void QCPItemLine::setPen(const QPen &pen) { - mPen = pen; + mPen = pen; } /*! Sets the pen that will be used to draw the line when selected - + \see setPen, setSelected */ void QCPItemLine::setSelectedPen(const QPen &pen) { - mSelectedPen = pen; + mSelectedPen = pen; } /*! Sets the line ending style of the head. The head corresponds to the \a end position. - + Note that due to the overloaded QCPLineEnding constructor, you may directly specify a QCPLineEnding::EndingStyle here, e.g. \code setHead(QCPLineEnding::esSpikeArrow) \endcode - + \see setTail */ void QCPItemLine::setHead(const QCPLineEnding &head) { - mHead = head; + mHead = head; } /*! Sets the line ending style of the tail. The tail corresponds to the \a start position. - + Note that due to the overloaded QCPLineEnding constructor, you may directly specify a QCPLineEnding::EndingStyle here, e.g. \code setTail(QCPLineEnding::esSpikeArrow) \endcode - + \see setHead */ void QCPItemLine::setTail(const QCPLineEnding &tail) { - mTail = tail; + mTail = tail; } /* inherits documentation from base class */ double QCPItemLine::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { - Q_UNUSED(details) - if (onlySelectable && !mSelectable) - return -1; - - return qSqrt(distSqrToLine(start->pixelPoint(), end->pixelPoint(), pos)); + Q_UNUSED(details) + if (onlySelectable && !mSelectable) { + return -1; + } + + return qSqrt(distSqrToLine(start->pixelPoint(), end->pixelPoint(), pos)); } /* inherits documentation from base class */ void QCPItemLine::draw(QCPPainter *painter) { - QVector2D startVec(start->pixelPoint()); - QVector2D endVec(end->pixelPoint()); - if (startVec.toPoint() == endVec.toPoint()) - return; - // get visible segment of straight line inside clipRect: - double clipPad = qMax(mHead.boundingDistance(), mTail.boundingDistance()); - clipPad = qMax(clipPad, (double)mainPen().widthF()); - QLineF line = getRectClippedLine(startVec, endVec, clipRect().adjusted(-clipPad, -clipPad, clipPad, clipPad)); - // paint visible segment, if existent: - if (!line.isNull()) - { - painter->setPen(mainPen()); - painter->drawLine(line); - painter->setBrush(Qt::SolidPattern); - if (mTail.style() != QCPLineEnding::esNone) - mTail.draw(painter, startVec, startVec-endVec); - if (mHead.style() != QCPLineEnding::esNone) - mHead.draw(painter, endVec, endVec-startVec); - } + QVector2D startVec(start->pixelPoint()); + QVector2D endVec(end->pixelPoint()); + if (startVec.toPoint() == endVec.toPoint()) { + return; + } + // get visible segment of straight line inside clipRect: + double clipPad = qMax(mHead.boundingDistance(), mTail.boundingDistance()); + clipPad = qMax(clipPad, (double)mainPen().widthF()); + QLineF line = getRectClippedLine(startVec, endVec, clipRect().adjusted(-clipPad, -clipPad, clipPad, clipPad)); + // paint visible segment, if existent: + if (!line.isNull()) { + painter->setPen(mainPen()); + painter->drawLine(line); + painter->setBrush(Qt::SolidPattern); + if (mTail.style() != QCPLineEnding::esNone) { + mTail.draw(painter, startVec, startVec - endVec); + } + if (mHead.style() != QCPLineEnding::esNone) { + mHead.draw(painter, endVec, endVec - startVec); + } + } } /*! \internal Returns the section of the line defined by \a start and \a end, that is visible in the specified \a rect. - + This is a helper function for \ref draw. */ QLineF QCPItemLine::getRectClippedLine(const QVector2D &start, const QVector2D &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; - double bx, by; - double gamma, mu; - QLineF result; - QList pointVectors; + 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()); + } - if (!qFuzzyIsNull(vec.y())) // line is not horizontal - { - // check top of rect: - bx = rect.left(); - by = rect.top(); - mu = (by-base.y())/vec.y(); - if (mu >= 0 && mu <= 1) - { - gamma = base.x()-bx + mu*vec.x(); - if (gamma >= 0 && gamma <= rect.width()) - pointVectors.append(QVector2D(bx+gamma, by)); - } - // check bottom of rect: - bx = rect.left(); - by = rect.bottom(); - mu = (by-base.y())/vec.y(); - if (mu >= 0 && mu <= 1) - { - gamma = base.x()-bx + mu*vec.x(); - if (gamma >= 0 && gamma <= rect.width()) - pointVectors.append(QVector2D(bx+gamma, by)); - } - } - if (!qFuzzyIsNull(vec.x())) // line is not vertical - { - // check left of rect: - bx = rect.left(); - by = rect.top(); - mu = (bx-base.x())/vec.x(); - if (mu >= 0 && mu <= 1) - { - gamma = base.y()-by + mu*vec.y(); - if (gamma >= 0 && gamma <= rect.height()) - pointVectors.append(QVector2D(bx, by+gamma)); - } - // check right of rect: - bx = rect.right(); - by = rect.top(); - mu = (bx-base.x())/vec.x(); - if (mu >= 0 && mu <= 1) - { - gamma = base.y()-by + mu*vec.y(); - if (gamma >= 0 && gamma <= rect.height()) - pointVectors.append(QVector2D(bx, by+gamma)); - } - } - - if (containsStart) - pointVectors.append(start); - if (containsEnd) - pointVectors.append(end); - - // evaluate points: - if (pointVectors.size() == 2) - { - result.setPoints(pointVectors.at(0).toPointF(), pointVectors.at(1).toPointF()); - } else if (pointVectors.size() > 2) - { - // 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; - for (int i=0; i distSqrMax) - { - pv1 = pointVectors.at(i); - pv2 = pointVectors.at(k); - distSqrMax = distSqr; + QVector2D base = start; + QVector2D vec = end - start; + double bx, by; + double gamma, mu; + QLineF result; + QList pointVectors; + + if (!qFuzzyIsNull(vec.y())) { // line is not horizontal + // check top of rect: + bx = rect.left(); + by = rect.top(); + mu = (by - base.y()) / vec.y(); + if (mu >= 0 && mu <= 1) { + gamma = base.x() - bx + mu * vec.x(); + if (gamma >= 0 && gamma <= rect.width()) { + pointVectors.append(QVector2D(bx + gamma, by)); + } + } + // check bottom of rect: + bx = rect.left(); + by = rect.bottom(); + mu = (by - base.y()) / vec.y(); + if (mu >= 0 && mu <= 1) { + gamma = base.x() - bx + mu * vec.x(); + if (gamma >= 0 && gamma <= rect.width()) { + pointVectors.append(QVector2D(bx + gamma, by)); + } } - } } - result.setPoints(pv1.toPointF(), pv2.toPointF()); - } - return result; + if (!qFuzzyIsNull(vec.x())) { // line is not vertical + // check left of rect: + bx = rect.left(); + by = rect.top(); + mu = (bx - base.x()) / vec.x(); + if (mu >= 0 && mu <= 1) { + gamma = base.y() - by + mu * vec.y(); + if (gamma >= 0 && gamma <= rect.height()) { + pointVectors.append(QVector2D(bx, by + gamma)); + } + } + // check right of rect: + bx = rect.right(); + by = rect.top(); + mu = (bx - base.x()) / vec.x(); + if (mu >= 0 && mu <= 1) { + gamma = base.y() - by + mu * vec.y(); + if (gamma >= 0 && gamma <= rect.height()) { + pointVectors.append(QVector2D(bx, by + gamma)); + } + } + } + + if (containsStart) { + pointVectors.append(start); + } + if (containsEnd) { + pointVectors.append(end); + } + + // evaluate points: + if (pointVectors.size() == 2) { + result.setPoints(pointVectors.at(0).toPointF(), pointVectors.at(1).toPointF()); + } else if (pointVectors.size() > 2) { + // 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; + for (int i = 0; i < pointVectors.size() - 1; ++i) { + for (int k = i + 1; k < pointVectors.size(); ++k) { + double distSqr = (pointVectors.at(i) - pointVectors.at(k)).lengthSquared(); + if (distSqr > distSqrMax) { + pv1 = pointVectors.at(i); + pv2 = pointVectors.at(k); + distSqrMax = distSqr; + } + } + } + result.setPoints(pv1.toPointF(), pv2.toPointF()); + } + return result; } /*! \internal @@ -21863,7 +22073,7 @@ QLineF QCPItemLine::getRectClippedLine(const QVector2D &start, const QVector2D & */ QPen QCPItemLine::mainPen() const { - return mSelected ? mSelectedPen : mPen; + return mSelected ? mSelectedPen : mPen; } @@ -21879,10 +22089,10 @@ QPen QCPItemLine::mainPen() const It has four positions, \a start and \a end, which define the end points of the line, and two control points which define the direction the line exits from the start and the direction from which it approaches the end: \a startDir and \a endDir. - + With \ref setHead and \ref setTail you may set different line ending styles, e.g. to create an arrow. - + Often it is desirable for the control points to stay at fixed relative positions to the start/end point. This can be achieved by setting the parent anchor e.g. of \a startDir simply to \a start, and then specify the desired pixel offset with QCPItemPosition::setCoords on \a startDir. @@ -21890,23 +22100,23 @@ QPen QCPItemLine::mainPen() const /*! Creates a curve item and sets default values. - + The constructed item can be added to the plot with QCustomPlot::addItem. */ QCPItemCurve::QCPItemCurve(QCustomPlot *parentPlot) : - QCPAbstractItem(parentPlot), - start(createPosition(QLatin1String("start"))), - startDir(createPosition(QLatin1String("startDir"))), - endDir(createPosition(QLatin1String("endDir"))), - end(createPosition(QLatin1String("end"))) + QCPAbstractItem(parentPlot), + start(createPosition(QLatin1String("start"))), + startDir(createPosition(QLatin1String("startDir"))), + endDir(createPosition(QLatin1String("endDir"))), + end(createPosition(QLatin1String("end"))) { - start->setCoords(0, 0); - startDir->setCoords(0.5, 0); - endDir->setCoords(0, 0.5); - end->setCoords(1, 1); - - setPen(QPen(Qt::black)); - setSelectedPen(QPen(Qt::blue,2)); + start->setCoords(0, 0); + startDir->setCoords(0.5, 0); + endDir->setCoords(0, 0.5); + end->setCoords(1, 1); + + setPen(QPen(Qt::black)); + setSelectedPen(QPen(Qt::blue, 2)); } QCPItemCurve::~QCPItemCurve() @@ -21915,104 +22125,108 @@ QCPItemCurve::~QCPItemCurve() /*! Sets the pen that will be used to draw the line - + \see setSelectedPen */ void QCPItemCurve::setPen(const QPen &pen) { - mPen = pen; + mPen = pen; } /*! Sets the pen that will be used to draw the line when selected - + \see setPen, setSelected */ void QCPItemCurve::setSelectedPen(const QPen &pen) { - mSelectedPen = pen; + mSelectedPen = pen; } /*! Sets the line ending style of the head. The head corresponds to the \a end position. - + Note that due to the overloaded QCPLineEnding constructor, you may directly specify a QCPLineEnding::EndingStyle here, e.g. \code setHead(QCPLineEnding::esSpikeArrow) \endcode - + \see setTail */ void QCPItemCurve::setHead(const QCPLineEnding &head) { - mHead = head; + mHead = head; } /*! Sets the line ending style of the tail. The tail corresponds to the \a start position. - + Note that due to the overloaded QCPLineEnding constructor, you may directly specify a QCPLineEnding::EndingStyle here, e.g. \code setTail(QCPLineEnding::esSpikeArrow) \endcode - + \see setHead */ void QCPItemCurve::setTail(const QCPLineEnding &tail) { - mTail = tail; + mTail = tail; } /* inherits documentation from base class */ double QCPItemCurve::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { - Q_UNUSED(details) - if (onlySelectable && !mSelectable) - return -1; - - QPointF startVec(start->pixelPoint()); - QPointF startDirVec(startDir->pixelPoint()); - QPointF endDirVec(endDir->pixelPoint()); - QPointF endVec(end->pixelPoint()); + Q_UNUSED(details) + if (onlySelectable && !mSelectable) { + return -1; + } - QPainterPath cubicPath(startVec); - cubicPath.cubicTo(startDirVec, endDirVec, endVec); - - QPolygonF polygon = cubicPath.toSubpathPolygons().first(); - double minDistSqr = std::numeric_limits::max(); - for (int i=1; ipixelPoint()); + QPointF startDirVec(startDir->pixelPoint()); + QPointF endDirVec(endDir->pixelPoint()); + QPointF endVec(end->pixelPoint()); + + QPainterPath cubicPath(startVec); + cubicPath.cubicTo(startDirVec, endDirVec, endVec); + + QPolygonF polygon = cubicPath.toSubpathPolygons().first(); + double minDistSqr = std::numeric_limits::max(); + for (int i = 1; i < polygon.size(); ++i) { + double distSqr = distSqrToLine(polygon.at(i - 1), polygon.at(i), pos); + if (distSqr < minDistSqr) { + minDistSqr = distSqr; + } + } + return qSqrt(minDistSqr); } /* inherits documentation from base class */ void QCPItemCurve::draw(QCPPainter *painter) { - QPointF startVec(start->pixelPoint()); - QPointF startDirVec(startDir->pixelPoint()); - QPointF endDirVec(endDir->pixelPoint()); - QPointF endVec(end->pixelPoint()); - if (QVector2D(endVec-startVec).length() > 1e10f) // too large curves cause crash - return; + QPointF startVec(start->pixelPoint()); + QPointF startDirVec(startDir->pixelPoint()); + QPointF endDirVec(endDir->pixelPoint()); + QPointF endVec(end->pixelPoint()); + if (QVector2D(endVec - startVec).length() > 1e10f) { // too large curves cause crash + return; + } - QPainterPath cubicPath(startVec); - cubicPath.cubicTo(startDirVec, endDirVec, endVec); + QPainterPath cubicPath(startVec); + cubicPath.cubicTo(startDirVec, endDirVec, endVec); - // paint visible segment, if existent: - QRect clip = clipRect().adjusted(-mainPen().widthF(), -mainPen().widthF(), mainPen().widthF(), mainPen().widthF()); - QRect cubicRect = cubicPath.controlPointRect().toRect(); - if (cubicRect.isEmpty()) // may happen when start and end exactly on same x or y position - cubicRect.adjust(0, 0, 1, 1); - if (clip.intersects(cubicRect)) - { - painter->setPen(mainPen()); - 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); - if (mHead.style() != QCPLineEnding::esNone) - mHead.draw(painter, QVector2D(endVec), -cubicPath.angleAtPercent(1)/180.0*M_PI); - } + // paint visible segment, if existent: + QRect clip = clipRect().adjusted(-mainPen().widthF(), -mainPen().widthF(), mainPen().widthF(), mainPen().widthF()); + QRect cubicRect = cubicPath.controlPointRect().toRect(); + if (cubicRect.isEmpty()) { // may happen when start and end exactly on same x or y position + cubicRect.adjust(0, 0, 1, 1); + } + if (clip.intersects(cubicRect)) { + painter->setPen(mainPen()); + 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); + } + if (mHead.style() != QCPLineEnding::esNone) { + mHead.draw(painter, QVector2D(endVec), -cubicPath.angleAtPercent(1) / 180.0 * M_PI); + } + } } /*! \internal @@ -22022,7 +22236,7 @@ void QCPItemCurve::draw(QCPPainter *painter) */ QPen QCPItemCurve::mainPen() const { - return mSelected ? mSelectedPen : mPen; + return mSelected ? mSelectedPen : mPen; } @@ -22040,27 +22254,27 @@ QPen QCPItemCurve::mainPen() const /*! Creates a rectangle item and sets default values. - + The constructed item can be added to the plot with QCustomPlot::addItem. */ QCPItemRect::QCPItemRect(QCustomPlot *parentPlot) : - QCPAbstractItem(parentPlot), - topLeft(createPosition(QLatin1String("topLeft"))), - bottomRight(createPosition(QLatin1String("bottomRight"))), - top(createAnchor(QLatin1String("top"), aiTop)), - topRight(createAnchor(QLatin1String("topRight"), aiTopRight)), - right(createAnchor(QLatin1String("right"), aiRight)), - bottom(createAnchor(QLatin1String("bottom"), aiBottom)), - bottomLeft(createAnchor(QLatin1String("bottomLeft"), aiBottomLeft)), - left(createAnchor(QLatin1String("left"), aiLeft)) + QCPAbstractItem(parentPlot), + topLeft(createPosition(QLatin1String("topLeft"))), + bottomRight(createPosition(QLatin1String("bottomRight"))), + top(createAnchor(QLatin1String("top"), aiTop)), + topRight(createAnchor(QLatin1String("topRight"), aiTopRight)), + right(createAnchor(QLatin1String("right"), aiRight)), + bottom(createAnchor(QLatin1String("bottom"), aiBottom)), + bottomLeft(createAnchor(QLatin1String("bottomLeft"), aiBottomLeft)), + left(createAnchor(QLatin1String("left"), aiLeft)) { - topLeft->setCoords(0, 1); - bottomRight->setCoords(1, 0); - - setPen(QPen(Qt::black)); - setSelectedPen(QPen(Qt::blue,2)); - setBrush(Qt::NoBrush); - setSelectedBrush(Qt::NoBrush); + topLeft->setCoords(0, 1); + bottomRight->setCoords(1, 0); + + setPen(QPen(Qt::black)); + setSelectedPen(QPen(Qt::blue, 2)); + setBrush(Qt::NoBrush); + setSelectedBrush(Qt::NoBrush); } QCPItemRect::~QCPItemRect() @@ -22069,92 +22283,98 @@ QCPItemRect::~QCPItemRect() /*! Sets the pen that will be used to draw the line of the rectangle - + \see setSelectedPen, setBrush */ void QCPItemRect::setPen(const QPen &pen) { - mPen = pen; + mPen = pen; } /*! Sets the pen that will be used to draw the line of the rectangle when selected - + \see setPen, setSelected */ void QCPItemRect::setSelectedPen(const QPen &pen) { - mSelectedPen = pen; + mSelectedPen = pen; } /*! Sets the brush that will be used to fill the rectangle. To disable filling, set \a brush to Qt::NoBrush. - + \see setSelectedBrush, setPen */ void QCPItemRect::setBrush(const QBrush &brush) { - mBrush = brush; + mBrush = brush; } /*! Sets the brush that will be used to fill the rectangle when selected. To disable filling, set \a brush to Qt::NoBrush. - + \see setBrush */ void QCPItemRect::setSelectedBrush(const QBrush &brush) { - mSelectedBrush = brush; + mSelectedBrush = brush; } /* inherits documentation from base class */ double QCPItemRect::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { - Q_UNUSED(details) - if (onlySelectable && !mSelectable) - return -1; - - QRectF rect = QRectF(topLeft->pixelPoint(), bottomRight->pixelPoint()).normalized(); - bool filledRect = mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0; - return rectSelectTest(rect, pos, filledRect); + Q_UNUSED(details) + if (onlySelectable && !mSelectable) { + return -1; + } + + QRectF rect = QRectF(topLeft->pixelPoint(), bottomRight->pixelPoint()).normalized(); + bool filledRect = mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0; + return rectSelectTest(rect, pos, filledRect); } /* inherits documentation from base class */ void QCPItemRect::draw(QCPPainter *painter) { - QPointF p1 = topLeft->pixelPoint(); - QPointF p2 = bottomRight->pixelPoint(); - if (p1.toPoint() == p2.toPoint()) - return; - QRectF rect = QRectF(p1, p2).normalized(); - double clipPad = mainPen().widthF(); - QRectF boundingRect = rect.adjusted(-clipPad, -clipPad, clipPad, clipPad); - if (boundingRect.intersects(clipRect())) // only draw if bounding rect of rect item is visible in cliprect - { - painter->setPen(mainPen()); - painter->setBrush(mainBrush()); - painter->drawRect(rect); - } + QPointF p1 = topLeft->pixelPoint(); + QPointF p2 = bottomRight->pixelPoint(); + if (p1.toPoint() == p2.toPoint()) { + return; + } + QRectF rect = QRectF(p1, p2).normalized(); + double clipPad = mainPen().widthF(); + QRectF boundingRect = rect.adjusted(-clipPad, -clipPad, clipPad, clipPad); + if (boundingRect.intersects(clipRect())) { // only draw if bounding rect of rect item is visible in cliprect + painter->setPen(mainPen()); + painter->setBrush(mainBrush()); + painter->drawRect(rect); + } } /* inherits documentation from base class */ QPointF QCPItemRect::anchorPixelPoint(int anchorId) const { - QRectF rect = QRectF(topLeft->pixelPoint(), bottomRight->pixelPoint()); - switch (anchorId) - { - case aiTop: return (rect.topLeft()+rect.topRight())*0.5; - case aiTopRight: return rect.topRight(); - case aiRight: return (rect.topRight()+rect.bottomRight())*0.5; - case aiBottom: return (rect.bottomLeft()+rect.bottomRight())*0.5; - case aiBottomLeft: return rect.bottomLeft(); - case aiLeft: return (rect.topLeft()+rect.bottomLeft())*0.5; - } - - qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId; - return QPointF(); + QRectF rect = QRectF(topLeft->pixelPoint(), bottomRight->pixelPoint()); + switch (anchorId) { + case aiTop: + return (rect.topLeft() + rect.topRight()) * 0.5; + case aiTopRight: + return rect.topRight(); + case aiRight: + return (rect.topRight() + rect.bottomRight()) * 0.5; + case aiBottom: + return (rect.bottomLeft() + rect.bottomRight()) * 0.5; + case aiBottomLeft: + return rect.bottomLeft(); + case aiLeft: + return (rect.topLeft() + rect.bottomLeft()) * 0.5; + } + + qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId; + return QPointF(); } /*! \internal @@ -22164,7 +22384,7 @@ QPointF QCPItemRect::anchorPixelPoint(int anchorId) const */ QPen QCPItemRect::mainPen() const { - return mSelected ? mSelectedPen : mPen; + return mSelected ? mSelectedPen : mPen; } /*! \internal @@ -22174,7 +22394,7 @@ QPen QCPItemRect::mainPen() const */ QBrush QCPItemRect::mainBrush() const { - return mSelected ? mSelectedBrush : mBrush; + return mSelected ? mSelectedBrush : mBrush; } @@ -22189,43 +22409,43 @@ QBrush QCPItemRect::mainBrush() const Its position is defined by the member \a position and the setting of \ref setPositionAlignment. The latter controls which part of the text rect shall be aligned with \a position. - + The text alignment itself (i.e. left, center, right) can be controlled with \ref setTextAlignment. - + The text may be rotated around the \a position point with \ref setRotation. */ /*! Creates a text item and sets default values. - + The constructed item can be added to the plot with QCustomPlot::addItem. */ QCPItemText::QCPItemText(QCustomPlot *parentPlot) : - QCPAbstractItem(parentPlot), - position(createPosition(QLatin1String("position"))), - topLeft(createAnchor(QLatin1String("topLeft"), aiTopLeft)), - top(createAnchor(QLatin1String("top"), aiTop)), - topRight(createAnchor(QLatin1String("topRight"), aiTopRight)), - right(createAnchor(QLatin1String("right"), aiRight)), - bottomRight(createAnchor(QLatin1String("bottomRight"), aiBottomRight)), - bottom(createAnchor(QLatin1String("bottom"), aiBottom)), - bottomLeft(createAnchor(QLatin1String("bottomLeft"), aiBottomLeft)), - left(createAnchor(QLatin1String("left"), aiLeft)) + QCPAbstractItem(parentPlot), + position(createPosition(QLatin1String("position"))), + topLeft(createAnchor(QLatin1String("topLeft"), aiTopLeft)), + top(createAnchor(QLatin1String("top"), aiTop)), + topRight(createAnchor(QLatin1String("topRight"), aiTopRight)), + right(createAnchor(QLatin1String("right"), aiRight)), + bottomRight(createAnchor(QLatin1String("bottomRight"), aiBottomRight)), + bottom(createAnchor(QLatin1String("bottom"), aiBottom)), + bottomLeft(createAnchor(QLatin1String("bottomLeft"), aiBottomLeft)), + left(createAnchor(QLatin1String("left"), aiLeft)) { - 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); - setSelectedBrush(Qt::NoBrush); - setColor(Qt::black); - setSelectedColor(Qt::blue); + 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); + setSelectedBrush(Qt::NoBrush); + setColor(Qt::black); + setSelectedColor(Qt::blue); } QCPItemText::~QCPItemText() @@ -22237,7 +22457,7 @@ QCPItemText::~QCPItemText() */ void QCPItemText::setColor(const QColor &color) { - mColor = color; + mColor = color; } /*! @@ -22245,99 +22465,99 @@ void QCPItemText::setColor(const QColor &color) */ void QCPItemText::setSelectedColor(const QColor &color) { - mSelectedColor = color; + mSelectedColor = color; } /*! Sets the pen that will be used do draw a rectangular border around the text. To disable the border, set \a pen to Qt::NoPen. - + \see setSelectedPen, setBrush, setPadding */ void QCPItemText::setPen(const QPen &pen) { - mPen = pen; + mPen = pen; } /*! Sets the pen that will be used do draw a rectangular border around the text, when the item is selected. To disable the border, set \a pen to Qt::NoPen. - + \see setPen */ void QCPItemText::setSelectedPen(const QPen &pen) { - mSelectedPen = pen; + mSelectedPen = pen; } /*! Sets the brush that will be used do fill the background of the text. To disable the background, set \a brush to Qt::NoBrush. - + \see setSelectedBrush, setPen, setPadding */ void QCPItemText::setBrush(const QBrush &brush) { - mBrush = brush; + mBrush = brush; } /*! Sets the brush that will be used do fill the background of the text, when the item is selected. To disable the background, set \a brush to Qt::NoBrush. - + \see setBrush */ void QCPItemText::setSelectedBrush(const QBrush &brush) { - mSelectedBrush = brush; + mSelectedBrush = brush; } /*! Sets the font of the text. - + \see setSelectedFont, setColor */ void QCPItemText::setFont(const QFont &font) { - mFont = font; + mFont = font; } /*! Sets the font of the text that will be used when the item is selected. - + \see setFont */ void QCPItemText::setSelectedFont(const QFont &font) { - mSelectedFont = font; + mSelectedFont = font; } /*! Sets the text that will be displayed. Multi-line texts are supported by inserting a line break character, e.g. '\n'. - + \see setFont, setColor, setTextAlignment */ void QCPItemText::setText(const QString &text) { - mText = text; + mText = text; } /*! Sets which point of the text rect shall be aligned with \a position. - + Examples: \li If \a alignment is Qt::AlignHCenter | Qt::AlignTop, the text will be positioned such that the top of the text rect will be horizontally centered on \a position. \li If \a alignment is Qt::AlignLeft | Qt::AlignBottom, \a position will indicate the bottom left corner of the text rect. - + If you want to control the alignment of (multi-lined) text within the text rect, use \ref setTextAlignment. */ void QCPItemText::setPositionAlignment(Qt::Alignment alignment) { - mPositionAlignment = alignment; + mPositionAlignment = alignment; } /*! @@ -22345,7 +22565,7 @@ void QCPItemText::setPositionAlignment(Qt::Alignment alignment) */ void QCPItemText::setTextAlignment(Qt::Alignment alignment) { - mTextAlignment = alignment; + mTextAlignment = alignment; } /*! @@ -22354,7 +22574,7 @@ void QCPItemText::setTextAlignment(Qt::Alignment alignment) */ void QCPItemText::setRotation(double degrees) { - mRotation = degrees; + mRotation = degrees; } /*! @@ -22363,122 +22583,133 @@ void QCPItemText::setRotation(double degrees) */ void QCPItemText::setPadding(const QMargins &padding) { - mPadding = padding; + mPadding = padding; } /* inherits documentation from base class */ double QCPItemText::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { - Q_UNUSED(details) - if (onlySelectable && !mSelectable) - 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()); - QTransform inputTransform; - inputTransform.translate(positionPixels.x(), positionPixels.y()); - inputTransform.rotate(-mRotation); - inputTransform.translate(-positionPixels.x(), -positionPixels.y()); - QPointF rotatedPos = inputTransform.map(pos); - QFontMetrics fontMetrics(mFont); - QRect textRect = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip|mTextAlignment, mText); - QRect textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom()); - QPointF textPos = getTextDrawPoint(positionPixels, textBoxRect, mPositionAlignment); - textBoxRect.moveTopLeft(textPos.toPoint()); + Q_UNUSED(details) + if (onlySelectable && !mSelectable) { + return -1; + } - return rectSelectTest(textBoxRect, rotatedPos, true); + // 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()); + QTransform inputTransform; + inputTransform.translate(positionPixels.x(), positionPixels.y()); + inputTransform.rotate(-mRotation); + inputTransform.translate(-positionPixels.x(), -positionPixels.y()); + QPointF rotatedPos = inputTransform.map(pos); + QFontMetrics fontMetrics(mFont); + QRect textRect = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip | mTextAlignment, mText); + QRect textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom()); + QPointF textPos = getTextDrawPoint(positionPixels, textBoxRect, mPositionAlignment); + textBoxRect.moveTopLeft(textPos.toPoint()); + + return rectSelectTest(textBoxRect, rotatedPos, true); } /* inherits documentation from base class */ void QCPItemText::draw(QCPPainter *painter) { - QPointF pos(position->pixelPoint()); - QTransform transform = painter->transform(); - transform.translate(pos.x(), pos.y()); - if (!qFuzzyIsNull(mRotation)) - transform.rotate(mRotation); - painter->setFont(mainFont()); - QRect textRect = painter->fontMetrics().boundingRect(0, 0, 0, 0, Qt::TextDontClip|mTextAlignment, mText); - QRect textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom()); - QPointF textPos = getTextDrawPoint(QPointF(0, 0), textBoxRect, mPositionAlignment); // 0, 0 because the transform does the translation - textRect.moveTopLeft(textPos.toPoint()+QPoint(mPadding.left(), mPadding.top())); - textBoxRect.moveTopLeft(textPos.toPoint()); - double clipPad = mainPen().widthF(); - QRect boundingRect = textBoxRect.adjusted(-clipPad, -clipPad, clipPad, clipPad); - if (transform.mapRect(boundingRect).intersects(painter->transform().mapRect(clipRect()))) - { - painter->setTransform(transform); - if ((mainBrush().style() != Qt::NoBrush && mainBrush().color().alpha() != 0) || - (mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0)) - { - painter->setPen(mainPen()); - painter->setBrush(mainBrush()); - painter->drawRect(textBoxRect); + QPointF pos(position->pixelPoint()); + QTransform transform = painter->transform(); + transform.translate(pos.x(), pos.y()); + if (!qFuzzyIsNull(mRotation)) { + transform.rotate(mRotation); + } + painter->setFont(mainFont()); + QRect textRect = painter->fontMetrics().boundingRect(0, 0, 0, 0, Qt::TextDontClip | mTextAlignment, mText); + QRect textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom()); + QPointF textPos = getTextDrawPoint(QPointF(0, 0), textBoxRect, mPositionAlignment); // 0, 0 because the transform does the translation + textRect.moveTopLeft(textPos.toPoint() + QPoint(mPadding.left(), mPadding.top())); + textBoxRect.moveTopLeft(textPos.toPoint()); + double clipPad = mainPen().widthF(); + QRect boundingRect = textBoxRect.adjusted(-clipPad, -clipPad, clipPad, clipPad); + if (transform.mapRect(boundingRect).intersects(painter->transform().mapRect(clipRect()))) { + painter->setTransform(transform); + if ((mainBrush().style() != Qt::NoBrush && mainBrush().color().alpha() != 0) || + (mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0)) { + painter->setPen(mainPen()); + painter->setBrush(mainBrush()); + painter->drawRect(textBoxRect); + } + painter->setBrush(Qt::NoBrush); + painter->setPen(QPen(mainColor())); + painter->drawText(textRect, Qt::TextDontClip | mTextAlignment, mText); } - painter->setBrush(Qt::NoBrush); - painter->setPen(QPen(mainColor())); - painter->drawText(textRect, Qt::TextDontClip|mTextAlignment, mText); - } } /* inherits documentation from base class */ QPointF QCPItemText::anchorPixelPoint(int anchorId) const { - // get actual rect points (pretty much copied from draw function): - QPointF pos(position->pixelPoint()); - QTransform transform; - transform.translate(pos.x(), pos.y()); - if (!qFuzzyIsNull(mRotation)) - transform.rotate(mRotation); - QFontMetrics fontMetrics(mainFont()); - QRect textRect = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip|mTextAlignment, mText); - QRectF textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom()); - QPointF textPos = getTextDrawPoint(QPointF(0, 0), textBoxRect, mPositionAlignment); // 0, 0 because the transform does the translation - textBoxRect.moveTopLeft(textPos.toPoint()); - QPolygonF rectPoly = transform.map(QPolygonF(textBoxRect)); - - switch (anchorId) - { - case aiTopLeft: return rectPoly.at(0); - case aiTop: return (rectPoly.at(0)+rectPoly.at(1))*0.5; - case aiTopRight: return rectPoly.at(1); - case aiRight: return (rectPoly.at(1)+rectPoly.at(2))*0.5; - case aiBottomRight: return rectPoly.at(2); - case aiBottom: return (rectPoly.at(2)+rectPoly.at(3))*0.5; - case aiBottomLeft: return rectPoly.at(3); - case aiLeft: return (rectPoly.at(3)+rectPoly.at(0))*0.5; - } - - qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId; - return QPointF(); + // get actual rect points (pretty much copied from draw function): + QPointF pos(position->pixelPoint()); + QTransform transform; + transform.translate(pos.x(), pos.y()); + if (!qFuzzyIsNull(mRotation)) { + transform.rotate(mRotation); + } + QFontMetrics fontMetrics(mainFont()); + QRect textRect = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip | mTextAlignment, mText); + QRectF textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom()); + QPointF textPos = getTextDrawPoint(QPointF(0, 0), textBoxRect, mPositionAlignment); // 0, 0 because the transform does the translation + textBoxRect.moveTopLeft(textPos.toPoint()); + QPolygonF rectPoly = transform.map(QPolygonF(textBoxRect)); + + switch (anchorId) { + case aiTopLeft: + return rectPoly.at(0); + case aiTop: + return (rectPoly.at(0) + rectPoly.at(1)) * 0.5; + case aiTopRight: + return rectPoly.at(1); + case aiRight: + return (rectPoly.at(1) + rectPoly.at(2)) * 0.5; + case aiBottomRight: + return rectPoly.at(2); + case aiBottom: + return (rectPoly.at(2) + rectPoly.at(3)) * 0.5; + case aiBottomLeft: + return rectPoly.at(3); + case aiLeft: + return (rectPoly.at(3) + rectPoly.at(0)) * 0.5; + } + + qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId; + return QPointF(); } /*! \internal - + Returns the point that must be given to the QPainter::drawText function (which expects the top left point of the text rect), according to the position \a pos, the text bounding box \a rect and the requested \a positionAlignment. - + For example, if \a positionAlignment is Qt::AlignLeft | Qt::AlignBottom the returned point will be shifted upward by the height of \a rect, starting from \a pos. So if the text is finally drawn at that point, the lower left corner of the resulting text rect is at \a pos. */ QPointF QCPItemText::getTextDrawPoint(const QPointF &pos, const QRectF &rect, Qt::Alignment positionAlignment) const { - if (positionAlignment == 0 || positionAlignment == (Qt::AlignLeft|Qt::AlignTop)) - return pos; - - QPointF result = pos; // start at top left - if (positionAlignment.testFlag(Qt::AlignHCenter)) - result.rx() -= rect.width()/2.0; - else if (positionAlignment.testFlag(Qt::AlignRight)) - result.rx() -= rect.width(); - if (positionAlignment.testFlag(Qt::AlignVCenter)) - result.ry() -= rect.height()/2.0; - else if (positionAlignment.testFlag(Qt::AlignBottom)) - result.ry() -= rect.height(); - return result; + if (positionAlignment == 0 || positionAlignment == (Qt::AlignLeft | Qt::AlignTop)) { + return pos; + } + + QPointF result = pos; // start at top left + if (positionAlignment.testFlag(Qt::AlignHCenter)) { + result.rx() -= rect.width() / 2.0; + } else if (positionAlignment.testFlag(Qt::AlignRight)) { + result.rx() -= rect.width(); + } + if (positionAlignment.testFlag(Qt::AlignVCenter)) { + result.ry() -= rect.height() / 2.0; + } else if (positionAlignment.testFlag(Qt::AlignBottom)) { + result.ry() -= rect.height(); + } + return result; } /*! \internal @@ -22488,7 +22719,7 @@ QPointF QCPItemText::getTextDrawPoint(const QPointF &pos, const QRectF &rect, Qt */ QFont QCPItemText::mainFont() const { - return mSelected ? mSelectedFont : mFont; + return mSelected ? mSelectedFont : mFont; } /*! \internal @@ -22498,7 +22729,7 @@ QFont QCPItemText::mainFont() const */ QColor QCPItemText::mainColor() const { - return mSelected ? mSelectedColor : mColor; + return mSelected ? mSelectedColor : mColor; } /*! \internal @@ -22508,7 +22739,7 @@ QColor QCPItemText::mainColor() const */ QPen QCPItemText::mainPen() const { - return mSelected ? mSelectedPen : mPen; + return mSelected ? mSelectedPen : mPen; } /*! \internal @@ -22518,7 +22749,7 @@ QPen QCPItemText::mainPen() const */ QBrush QCPItemText::mainBrush() const { - return mSelected ? mSelectedBrush : mBrush; + return mSelected ? mSelectedBrush : mBrush; } @@ -22536,30 +22767,30 @@ QBrush QCPItemText::mainBrush() const /*! Creates an ellipse item and sets default values. - + The constructed item can be added to the plot with QCustomPlot::addItem. */ QCPItemEllipse::QCPItemEllipse(QCustomPlot *parentPlot) : - QCPAbstractItem(parentPlot), - topLeft(createPosition(QLatin1String("topLeft"))), - bottomRight(createPosition(QLatin1String("bottomRight"))), - topLeftRim(createAnchor(QLatin1String("topLeftRim"), aiTopLeftRim)), - top(createAnchor(QLatin1String("top"), aiTop)), - topRightRim(createAnchor(QLatin1String("topRightRim"), aiTopRightRim)), - right(createAnchor(QLatin1String("right"), aiRight)), - bottomRightRim(createAnchor(QLatin1String("bottomRightRim"), aiBottomRightRim)), - bottom(createAnchor(QLatin1String("bottom"), aiBottom)), - bottomLeftRim(createAnchor(QLatin1String("bottomLeftRim"), aiBottomLeftRim)), - left(createAnchor(QLatin1String("left"), aiLeft)), - center(createAnchor(QLatin1String("center"), aiCenter)) + QCPAbstractItem(parentPlot), + topLeft(createPosition(QLatin1String("topLeft"))), + bottomRight(createPosition(QLatin1String("bottomRight"))), + topLeftRim(createAnchor(QLatin1String("topLeftRim"), aiTopLeftRim)), + top(createAnchor(QLatin1String("top"), aiTop)), + topRightRim(createAnchor(QLatin1String("topRightRim"), aiTopRightRim)), + right(createAnchor(QLatin1String("right"), aiRight)), + bottomRightRim(createAnchor(QLatin1String("bottomRightRim"), aiBottomRightRim)), + bottom(createAnchor(QLatin1String("bottom"), aiBottom)), + bottomLeftRim(createAnchor(QLatin1String("bottomLeftRim"), aiBottomLeftRim)), + left(createAnchor(QLatin1String("left"), aiLeft)), + center(createAnchor(QLatin1String("center"), aiCenter)) { - topLeft->setCoords(0, 1); - bottomRight->setCoords(1, 0); - - setPen(QPen(Qt::black)); - setSelectedPen(QPen(Qt::blue, 2)); - setBrush(Qt::NoBrush); - setSelectedBrush(Qt::NoBrush); + topLeft->setCoords(0, 1); + bottomRight->setCoords(1, 0); + + setPen(QPen(Qt::black)); + setSelectedPen(QPen(Qt::blue, 2)); + setBrush(Qt::NoBrush); + setSelectedBrush(Qt::NoBrush); } QCPItemEllipse::~QCPItemEllipse() @@ -22568,121 +22799,128 @@ QCPItemEllipse::~QCPItemEllipse() /*! Sets the pen that will be used to draw the line of the ellipse - + \see setSelectedPen, setBrush */ void QCPItemEllipse::setPen(const QPen &pen) { - mPen = pen; + mPen = pen; } /*! Sets the pen that will be used to draw the line of the ellipse when selected - + \see setPen, setSelected */ void QCPItemEllipse::setSelectedPen(const QPen &pen) { - mSelectedPen = pen; + mSelectedPen = pen; } /*! Sets the brush that will be used to fill the ellipse. To disable filling, set \a brush to Qt::NoBrush. - + \see setSelectedBrush, setPen */ void QCPItemEllipse::setBrush(const QBrush &brush) { - mBrush = brush; + mBrush = brush; } /*! Sets the brush that will be used to fill the ellipse when selected. To disable filling, set \a brush to Qt::NoBrush. - + \see setBrush */ void QCPItemEllipse::setSelectedBrush(const QBrush &brush) { - mSelectedBrush = brush; + mSelectedBrush = brush; } /* inherits documentation from base class */ double QCPItemEllipse::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { - Q_UNUSED(details) - if (onlySelectable && !mSelectable) - return -1; - - double result = -1; - QPointF p1 = topLeft->pixelPoint(); - QPointF p2 = bottomRight->pixelPoint(); - QPointF center((p1+p2)/2.0); - double a = qAbs(p1.x()-p2.x())/2.0; - double b = qAbs(p1.y()-p2.y())/2.0; - double x = pos.x()-center.x(); - double y = pos.y()-center.y(); - - // 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); - // filled ellipse, allow click inside to count as hit: - if (result > mParentPlot->selectionTolerance()*0.99 && mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0) - { - if (x*x/(a*a) + y*y/(b*b) <= 1) - result = mParentPlot->selectionTolerance()*0.99; - } - return result; + Q_UNUSED(details) + if (onlySelectable && !mSelectable) { + return -1; + } + + double result = -1; + QPointF p1 = topLeft->pixelPoint(); + QPointF p2 = bottomRight->pixelPoint(); + QPointF center((p1 + p2) / 2.0); + double a = qAbs(p1.x() - p2.x()) / 2.0; + double b = qAbs(p1.y() - p2.y()) / 2.0; + double x = pos.x() - center.x(); + double y = pos.y() - center.y(); + + // 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); + // filled ellipse, allow click inside to count as hit: + if (result > mParentPlot->selectionTolerance() * 0.99 && mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0) { + if (x * x / (a * a) + y * y / (b * b) <= 1) { + result = mParentPlot->selectionTolerance() * 0.99; + } + } + return result; } /* inherits documentation from base class */ void QCPItemEllipse::draw(QCPPainter *painter) { - QPointF p1 = topLeft->pixelPoint(); - QPointF p2 = bottomRight->pixelPoint(); - if (p1.toPoint() == p2.toPoint()) - return; - QRectF ellipseRect = QRectF(p1, p2).normalized(); - QRect clip = clipRect().adjusted(-mainPen().widthF(), -mainPen().widthF(), mainPen().widthF(), mainPen().widthF()); - if (ellipseRect.intersects(clip)) // only draw if bounding rect of ellipse is visible in cliprect - { - painter->setPen(mainPen()); - painter->setBrush(mainBrush()); -#ifdef __EXCEPTIONS - try // drawEllipse sometimes throws exceptions if ellipse is too big - { -#endif - painter->drawEllipse(ellipseRect); -#ifdef __EXCEPTIONS - } catch (...) - { - qDebug() << Q_FUNC_INFO << "Item too large for memory, setting invisible"; - setVisible(false); + QPointF p1 = topLeft->pixelPoint(); + QPointF p2 = bottomRight->pixelPoint(); + if (p1.toPoint() == p2.toPoint()) { + return; } + QRectF ellipseRect = QRectF(p1, p2).normalized(); + QRect clip = clipRect().adjusted(-mainPen().widthF(), -mainPen().widthF(), mainPen().widthF(), mainPen().widthF()); + if (ellipseRect.intersects(clip)) { // only draw if bounding rect of ellipse is visible in cliprect + painter->setPen(mainPen()); + painter->setBrush(mainBrush()); +#ifdef __EXCEPTIONS + try { // drawEllipse sometimes throws exceptions if ellipse is too big #endif - } + painter->drawEllipse(ellipseRect); +#ifdef __EXCEPTIONS + } catch (...) { + qDebug() << Q_FUNC_INFO << "Item too large for memory, setting invisible"; + setVisible(false); + } +#endif + } } /* inherits documentation from base class */ QPointF QCPItemEllipse::anchorPixelPoint(int anchorId) const { - QRectF rect = QRectF(topLeft->pixelPoint(), bottomRight->pixelPoint()); - switch (anchorId) - { - case aiTopLeftRim: return rect.center()+(rect.topLeft()-rect.center())*1/qSqrt(2); - case aiTop: return (rect.topLeft()+rect.topRight())*0.5; - case aiTopRightRim: return rect.center()+(rect.topRight()-rect.center())*1/qSqrt(2); - case aiRight: return (rect.topRight()+rect.bottomRight())*0.5; - case aiBottomRightRim: return rect.center()+(rect.bottomRight()-rect.center())*1/qSqrt(2); - case aiBottom: return (rect.bottomLeft()+rect.bottomRight())*0.5; - case aiBottomLeftRim: return rect.center()+(rect.bottomLeft()-rect.center())*1/qSqrt(2); - case aiLeft: return (rect.topLeft()+rect.bottomLeft())*0.5; - case aiCenter: return (rect.topLeft()+rect.bottomRight())*0.5; - } - - qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId; - return QPointF(); + QRectF rect = QRectF(topLeft->pixelPoint(), bottomRight->pixelPoint()); + switch (anchorId) { + case aiTopLeftRim: + return rect.center() + (rect.topLeft() - rect.center()) * 1 / qSqrt(2); + case aiTop: + return (rect.topLeft() + rect.topRight()) * 0.5; + case aiTopRightRim: + return rect.center() + (rect.topRight() - rect.center()) * 1 / qSqrt(2); + case aiRight: + return (rect.topRight() + rect.bottomRight()) * 0.5; + case aiBottomRightRim: + return rect.center() + (rect.bottomRight() - rect.center()) * 1 / qSqrt(2); + case aiBottom: + return (rect.bottomLeft() + rect.bottomRight()) * 0.5; + case aiBottomLeftRim: + return rect.center() + (rect.bottomLeft() - rect.center()) * 1 / qSqrt(2); + case aiLeft: + return (rect.topLeft() + rect.bottomLeft()) * 0.5; + case aiCenter: + return (rect.topLeft() + rect.bottomRight()) * 0.5; + } + + qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId; + return QPointF(); } /*! \internal @@ -22692,7 +22930,7 @@ QPointF QCPItemEllipse::anchorPixelPoint(int anchorId) const */ QPen QCPItemEllipse::mainPen() const { - return mSelected ? mSelectedPen : mPen; + return mSelected ? mSelectedPen : mPen; } /*! \internal @@ -22702,7 +22940,7 @@ QPen QCPItemEllipse::mainPen() const */ QBrush QCPItemEllipse::mainBrush() const { - return mSelected ? mSelectedBrush : mBrush; + return mSelected ? mSelectedBrush : mBrush; } @@ -22718,7 +22956,7 @@ QBrush QCPItemEllipse::mainBrush() const It has two positions, \a topLeft and \a bottomRight, which define the rectangle the pixmap will be drawn in. Depending on the scale setting (\ref setScaled), the pixmap will be either scaled to fit the rectangle or be drawn aligned to the topLeft position. - + If scaling is enabled and \a topLeft is further to the bottom/right than \a bottomRight (as shown on the right side of the example image), the pixmap will be flipped in the respective orientations. @@ -22726,27 +22964,27 @@ QBrush QCPItemEllipse::mainBrush() const /*! Creates a rectangle item and sets default values. - + The constructed item can be added to the plot with QCustomPlot::addItem. */ QCPItemPixmap::QCPItemPixmap(QCustomPlot *parentPlot) : - QCPAbstractItem(parentPlot), - topLeft(createPosition(QLatin1String("topLeft"))), - bottomRight(createPosition(QLatin1String("bottomRight"))), - top(createAnchor(QLatin1String("top"), aiTop)), - topRight(createAnchor(QLatin1String("topRight"), aiTopRight)), - right(createAnchor(QLatin1String("right"), aiRight)), - bottom(createAnchor(QLatin1String("bottom"), aiBottom)), - bottomLeft(createAnchor(QLatin1String("bottomLeft"), aiBottomLeft)), - left(createAnchor(QLatin1String("left"), aiLeft)), - mScaledPixmapInvalidated(true) + QCPAbstractItem(parentPlot), + topLeft(createPosition(QLatin1String("topLeft"))), + bottomRight(createPosition(QLatin1String("bottomRight"))), + top(createAnchor(QLatin1String("top"), aiTop)), + topRight(createAnchor(QLatin1String("topRight"), aiTopRight)), + right(createAnchor(QLatin1String("right"), aiRight)), + bottom(createAnchor(QLatin1String("bottom"), aiBottom)), + bottomLeft(createAnchor(QLatin1String("bottomLeft"), aiBottomLeft)), + left(createAnchor(QLatin1String("left"), aiLeft)), + mScaledPixmapInvalidated(true) { - topLeft->setCoords(0, 1); - bottomRight->setCoords(1, 0); - - setPen(Qt::NoPen); - setSelectedPen(QPen(Qt::blue)); - setScaled(false, Qt::KeepAspectRatio, 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() @@ -22758,10 +22996,11 @@ QCPItemPixmap::~QCPItemPixmap() */ void QCPItemPixmap::setPixmap(const QPixmap &pixmap) { - mPixmap = pixmap; - mScaledPixmapInvalidated = true; - if (mPixmap.isNull()) - qDebug() << Q_FUNC_INFO << "pixmap is null"; + mPixmap = pixmap; + mScaledPixmapInvalidated = true; + if (mPixmap.isNull()) { + qDebug() << Q_FUNC_INFO << "pixmap is null"; + } } /*! @@ -22770,175 +23009,182 @@ void QCPItemPixmap::setPixmap(const QPixmap &pixmap) */ void QCPItemPixmap::setScaled(bool scaled, Qt::AspectRatioMode aspectRatioMode, Qt::TransformationMode transformationMode) { - mScaled = scaled; - mAspectRatioMode = aspectRatioMode; - mTransformationMode = transformationMode; - mScaledPixmapInvalidated = true; + mScaled = scaled; + mAspectRatioMode = aspectRatioMode; + mTransformationMode = transformationMode; + mScaledPixmapInvalidated = true; } /*! Sets the pen that will be used to draw a border around the pixmap. - + \see setSelectedPen, setBrush */ void QCPItemPixmap::setPen(const QPen &pen) { - mPen = pen; + mPen = pen; } /*! Sets the pen that will be used to draw a border around the pixmap when selected - + \see setPen, setSelected */ void QCPItemPixmap::setSelectedPen(const QPen &pen) { - mSelectedPen = pen; + mSelectedPen = pen; } /* inherits documentation from base class */ double QCPItemPixmap::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { - Q_UNUSED(details) - if (onlySelectable && !mSelectable) - return -1; - - return rectSelectTest(getFinalRect(), pos, true); + Q_UNUSED(details) + if (onlySelectable && !mSelectable) { + return -1; + } + + return rectSelectTest(getFinalRect(), pos, true); } /* inherits documentation from base class */ void QCPItemPixmap::draw(QCPPainter *painter) { - bool flipHorz = false; - bool flipVert = false; - QRect rect = getFinalRect(&flipHorz, &flipVert); - double clipPad = mainPen().style() == Qt::NoPen ? 0 : mainPen().widthF(); - QRect boundingRect = rect.adjusted(-clipPad, -clipPad, clipPad, clipPad); - if (boundingRect.intersects(clipRect())) - { - updateScaledPixmap(rect, flipHorz, flipVert); - painter->drawPixmap(rect.topLeft(), mScaled ? mScaledPixmap : mPixmap); - QPen pen = mainPen(); - if (pen.style() != Qt::NoPen) - { - painter->setPen(pen); - painter->setBrush(Qt::NoBrush); - painter->drawRect(rect); + bool flipHorz = false; + bool flipVert = false; + QRect rect = getFinalRect(&flipHorz, &flipVert); + double clipPad = mainPen().style() == Qt::NoPen ? 0 : mainPen().widthF(); + QRect boundingRect = rect.adjusted(-clipPad, -clipPad, clipPad, clipPad); + if (boundingRect.intersects(clipRect())) { + updateScaledPixmap(rect, flipHorz, flipVert); + painter->drawPixmap(rect.topLeft(), mScaled ? mScaledPixmap : mPixmap); + QPen pen = mainPen(); + if (pen.style() != Qt::NoPen) { + painter->setPen(pen); + painter->setBrush(Qt::NoBrush); + painter->drawRect(rect); + } } - } } /* inherits documentation from base class */ QPointF QCPItemPixmap::anchorPixelPoint(int anchorId) const { - bool flipHorz; - bool flipVert; - QRect rect = getFinalRect(&flipHorz, &flipVert); - // we actually want denormal rects (negative width/height) here, so restore - // the flipped state: - if (flipHorz) - rect.adjust(rect.width(), 0, -rect.width(), 0); - if (flipVert) - rect.adjust(0, rect.height(), 0, -rect.height()); - - switch (anchorId) - { - case aiTop: return (rect.topLeft()+rect.topRight())*0.5; - case aiTopRight: return rect.topRight(); - case aiRight: return (rect.topRight()+rect.bottomRight())*0.5; - case aiBottom: return (rect.bottomLeft()+rect.bottomRight())*0.5; - case aiBottomLeft: return rect.bottomLeft(); - case aiLeft: return (rect.topLeft()+rect.bottomLeft())*0.5; - } - - qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId; - return QPointF(); + bool flipHorz; + bool flipVert; + QRect rect = getFinalRect(&flipHorz, &flipVert); + // we actually want denormal rects (negative width/height) here, so restore + // the flipped state: + if (flipHorz) { + rect.adjust(rect.width(), 0, -rect.width(), 0); + } + if (flipVert) { + rect.adjust(0, rect.height(), 0, -rect.height()); + } + + switch (anchorId) { + case aiTop: + return (rect.topLeft() + rect.topRight()) * 0.5; + case aiTopRight: + return rect.topRight(); + case aiRight: + return (rect.topRight() + rect.bottomRight()) * 0.5; + case aiBottom: + return (rect.bottomLeft() + rect.bottomRight()) * 0.5; + case aiBottomLeft: + return rect.bottomLeft(); + case aiLeft: + return (rect.topLeft() + rect.bottomLeft()) * 0.5; + } + + qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId; + return QPointF(); } /*! \internal - + Creates the buffered scaled image (\a mScaledPixmap) to fit the specified \a finalRect. The parameters \a flipHorz and \a flipVert control whether the resulting image shall be flipped horizontally or vertically. (This is used when \a topLeft is further to the bottom/right than \a bottomRight.) - + This function only creates the scaled pixmap when the buffered pixmap has a different size than the expected result, so calling this function repeatedly, e.g. in the \ref draw function, does not cause expensive rescaling every time. - + If scaling is disabled, sets mScaledPixmap to a null QPixmap. */ void QCPItemPixmap::updateScaledPixmap(QRect finalRect, bool flipHorz, bool flipVert) { - if (mPixmap.isNull()) - return; - - if (mScaled) - { - if (finalRect.isNull()) - finalRect = getFinalRect(&flipHorz, &flipVert); - if (mScaledPixmapInvalidated || finalRect.size() != mScaledPixmap.size()) - { - mScaledPixmap = mPixmap.scaled(finalRect.size(), mAspectRatioMode, mTransformationMode); - if (flipHorz || flipVert) - mScaledPixmap = QPixmap::fromImage(mScaledPixmap.toImage().mirrored(flipHorz, flipVert)); + if (mPixmap.isNull()) { + return; } - } else if (!mScaledPixmap.isNull()) - mScaledPixmap = QPixmap(); - mScaledPixmapInvalidated = false; + + if (mScaled) { + if (finalRect.isNull()) { + finalRect = getFinalRect(&flipHorz, &flipVert); + } + if (mScaledPixmapInvalidated || finalRect.size() != mScaledPixmap.size()) { + mScaledPixmap = mPixmap.scaled(finalRect.size(), mAspectRatioMode, mTransformationMode); + if (flipHorz || flipVert) { + mScaledPixmap = QPixmap::fromImage(mScaledPixmap.toImage().mirrored(flipHorz, flipVert)); + } + } + } else if (!mScaledPixmap.isNull()) { + mScaledPixmap = QPixmap(); + } + mScaledPixmapInvalidated = false; } /*! \internal - + Returns the final (tight) rect the pixmap is drawn in, depending on the current item positions and scaling settings. - + The output parameters \a flippedHorz and \a flippedVert return whether the pixmap should be drawn flipped horizontally or vertically in the returned rect. (The returned rect itself is always normalized, i.e. the top left corner of the rect is actually further to the top/left than the bottom right corner). This is the case when the item position \a topLeft is further to the bottom/right than \a bottomRight. - + If scaling is disabled, returns a rect with size of the original pixmap and the top left corner aligned with the item position \a topLeft. The position \a bottomRight is ignored. */ 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(); - if (p1 == p2) - return QRect(p1, QSize(0, 0)); - if (mScaled) - { - QSize newSize = QSize(p2.x()-p1.x(), p2.y()-p1.y()); - QPoint topLeft = p1; - if (newSize.width() < 0) - { - flipHorz = true; - newSize.rwidth() *= -1; - topLeft.setX(p2.x()); + QRect result; + bool flipHorz = false; + bool flipVert = false; + QPoint p1 = topLeft->pixelPoint().toPoint(); + QPoint p2 = bottomRight->pixelPoint().toPoint(); + if (p1 == p2) { + return QRect(p1, QSize(0, 0)); } - if (newSize.height() < 0) - { - flipVert = true; - newSize.rheight() *= -1; - topLeft.setY(p2.y()); + if (mScaled) { + QSize newSize = QSize(p2.x() - p1.x(), p2.y() - p1.y()); + QPoint topLeft = p1; + if (newSize.width() < 0) { + flipHorz = true; + newSize.rwidth() *= -1; + topLeft.setX(p2.x()); + } + if (newSize.height() < 0) { + flipVert = true; + newSize.rheight() *= -1; + topLeft.setY(p2.y()); + } + QSize scaledSize = mPixmap.size(); + scaledSize.scale(newSize, mAspectRatioMode); + result = QRect(topLeft, scaledSize); + } else { + result = QRect(p1, mPixmap.size()); } - QSize scaledSize = mPixmap.size(); - scaledSize.scale(newSize, mAspectRatioMode); - result = QRect(topLeft, scaledSize); - } else - { - result = QRect(p1, mPixmap.size()); - } - if (flippedHorz) - *flippedHorz = flipHorz; - if (flippedVert) - *flippedVert = flipVert; - return result; + if (flippedHorz) { + *flippedHorz = flipHorz; + } + if (flippedVert) { + *flippedVert = flipVert; + } + return result; } /*! \internal @@ -22948,7 +23194,7 @@ QRect QCPItemPixmap::getFinalRect(bool *flippedHorz, bool *flippedVert) const */ QPen QCPItemPixmap::mainPen() const { - return mSelected ? mSelectedPen : mPen; + return mSelected ? mSelectedPen : mPen; } @@ -22967,19 +23213,19 @@ QPen QCPItemPixmap::mainPen() const QCPGraph is connected, note that setting the coordinates of the tracer item directly via \a position will have no effect because they will be overriden in the next redraw (this is when the coordinate update happens). - + If the specified key in \ref setGraphKey is outside the key bounds of the graph, the tracer will stay at the corresponding end of the graph. - + With \ref setInterpolating you may specify whether the tracer may only stay exactly on data points or whether it interpolates data points linearly, if given a key that lies between two data points of the graph. - + The tracer has different visual styles, see \ref setStyle. It is also possible to make the tracer have no own visual appearance (set the style to \ref tsNone), and just connect other item positions to the tracer \a position (used as an anchor) via \ref 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 tracer are retrieved, they will not reflect the updated data of the graph. In this case \ref @@ -22988,24 +23234,24 @@ QPen QCPItemPixmap::mainPen() const /*! Creates a tracer item and sets default values. - + The constructed item can be added to the plot with QCustomPlot::addItem. */ QCPItemTracer::QCPItemTracer(QCustomPlot *parentPlot) : - QCPAbstractItem(parentPlot), - position(createPosition(QLatin1String("position"))), - mGraph(0) + QCPAbstractItem(parentPlot), + position(createPosition(QLatin1String("position"))), + mGraph(0) { - position->setCoords(0, 0); + position->setCoords(0, 0); - setBrush(Qt::NoBrush); - setSelectedBrush(Qt::NoBrush); - setPen(QPen(Qt::black)); - setSelectedPen(QPen(Qt::blue, 2)); - setStyle(tsCrosshair); - setSize(6); - setInterpolating(false); - setGraphKey(0); + setBrush(Qt::NoBrush); + setSelectedBrush(Qt::NoBrush); + setPen(QPen(Qt::black)); + setSelectedPen(QPen(Qt::blue, 2)); + setStyle(tsCrosshair); + setSize(6); + setInterpolating(false); + setGraphKey(0); } QCPItemTracer::~QCPItemTracer() @@ -23014,42 +23260,42 @@ QCPItemTracer::~QCPItemTracer() /*! Sets the pen that will be used to draw the line of the tracer - + \see setSelectedPen, setBrush */ void QCPItemTracer::setPen(const QPen &pen) { - mPen = pen; + mPen = pen; } /*! Sets the pen that will be used to draw the line of the tracer when selected - + \see setPen, setSelected */ void QCPItemTracer::setSelectedPen(const QPen &pen) { - mSelectedPen = pen; + mSelectedPen = pen; } /*! Sets the brush that will be used to draw any fills of the tracer - + \see setSelectedBrush, setPen */ void QCPItemTracer::setBrush(const QBrush &brush) { - mBrush = brush; + mBrush = brush; } /*! Sets the brush that will be used to draw any fills of the tracer, when selected. - + \see setBrush, setSelected */ void QCPItemTracer::setSelectedBrush(const QBrush &brush) { - mSelectedBrush = brush; + mSelectedBrush = brush; } /*! @@ -23058,240 +23304,230 @@ void QCPItemTracer::setSelectedBrush(const QBrush &brush) */ void QCPItemTracer::setSize(double size) { - mSize = size; + mSize = size; } /*! Sets the style/visual appearance of the tracer. - + If you only want to use the tracer \a position as an anchor for other items, set \a style to \ref tsNone. */ void QCPItemTracer::setStyle(QCPItemTracer::TracerStyle style) { - mStyle = style; + mStyle = style; } /*! Sets the QCPGraph this tracer sticks to. The tracer \a position will be set to type QCPItemPosition::ptPlotCoords and the axes will be set to the axes of \a graph. - + To free the tracer from any graph, set \a graph to 0. The tracer \a position can then be placed freely like any other item position. This is the state the tracer will assume when its graph gets deleted while still attached to it. - + \see setGraphKey */ void QCPItemTracer::setGraph(QCPGraph *graph) { - if (graph) - { - if (graph->parentPlot() == mParentPlot) - { - position->setType(QCPItemPosition::ptPlotCoords); - position->setAxes(graph->keyAxis(), graph->valueAxis()); - mGraph = graph; - updatePosition(); - } else - qDebug() << Q_FUNC_INFO << "graph isn't in same QCustomPlot instance as this item"; - } else - { - mGraph = 0; - } + if (graph) { + if (graph->parentPlot() == mParentPlot) { + position->setType(QCPItemPosition::ptPlotCoords); + position->setAxes(graph->keyAxis(), graph->valueAxis()); + mGraph = graph; + updatePosition(); + } else { + qDebug() << Q_FUNC_INFO << "graph isn't in same QCustomPlot instance as this item"; + } + } else { + mGraph = 0; + } } /*! Sets the key of the graph's data point the tracer will be positioned at. This is the only free coordinate of a tracer when attached to a graph. - + Depending on \ref setInterpolating, the tracer will be either positioned on the data point closest to \a key, or will stay exactly at \a key and interpolate the value linearly. - + \see setGraph, setInterpolating */ void QCPItemTracer::setGraphKey(double key) { - mGraphKey = key; + mGraphKey = key; } /*! Sets whether the value of the graph's data points shall be interpolated, when positioning the tracer. - + If \a enabled is set to false and a key is given with \ref setGraphKey, the tracer is placed on the data point of the graph which is closest to the key, but which is not necessarily exactly there. If \a enabled is true, the tracer will be positioned exactly at the specified key, and the appropriate value will be interpolated from the graph's data points linearly. - + \see setGraph, setGraphKey */ void QCPItemTracer::setInterpolating(bool enabled) { - mInterpolating = enabled; + mInterpolating = enabled; } /* inherits documentation from base class */ double QCPItemTracer::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { - Q_UNUSED(details) - if (onlySelectable && !mSelectable) - return -1; + Q_UNUSED(details) + if (onlySelectable && !mSelectable) { + return -1; + } - QPointF center(position->pixelPoint()); - double w = mSize/2.0; - QRect clip = clipRect(); - switch (mStyle) - { - case tsNone: return -1; - 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))); - 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))); - } - 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 circleLine = w; - double result = qAbs(centerDist-circleLine); - // filled ellipse, allow click inside to count as hit: - if (result > mParentPlot->selectionTolerance()*0.99 && mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0) - { - if (centerDist <= circleLine) - result = mParentPlot->selectionTolerance()*0.99; + QPointF center(position->pixelPoint()); + double w = mSize / 2.0; + QRect clip = clipRect(); + switch (mStyle) { + case tsNone: + return -1; + 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))); + 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))); + } + 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 circleLine = w; + double result = qAbs(centerDist - circleLine); + // filled ellipse, allow click inside to count as hit: + if (result > mParentPlot->selectionTolerance() * 0.99 && mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0) { + if (centerDist <= circleLine) { + result = mParentPlot->selectionTolerance() * 0.99; + } + } + return result; + } + break; + } + case tsSquare: { + if (clip.intersects(QRectF(center - QPointF(w, w), center + QPointF(w, w)).toRect())) { + 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); + } + break; } - return result; - } - break; } - case tsSquare: - { - if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect())) - { - 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); - } - break; - } - } - return -1; + return -1; } /* inherits documentation from base class */ void QCPItemTracer::draw(QCPPainter *painter) { - updatePosition(); - if (mStyle == tsNone) - return; + updatePosition(); + if (mStyle == tsNone) { + return; + } - painter->setPen(mainPen()); - painter->setBrush(mainBrush()); - QPointF center(position->pixelPoint()); - double w = mSize/2.0; - QRect clip = clipRect(); - switch (mStyle) - { - case tsNone: return; - case tsPlus: - { - if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect())) - { - painter->drawLine(QLineF(center+QPointF(-w, 0), center+QPointF(w, 0))); - painter->drawLine(QLineF(center+QPointF(0, -w), center+QPointF(0, w))); - } - break; + painter->setPen(mainPen()); + painter->setBrush(mainBrush()); + QPointF center(position->pixelPoint()); + double w = mSize / 2.0; + QRect clip = clipRect(); + switch (mStyle) { + case tsNone: + return; + case tsPlus: { + if (clip.intersects(QRectF(center - QPointF(w, w), center + QPointF(w, w)).toRect())) { + painter->drawLine(QLineF(center + QPointF(-w, 0), center + QPointF(w, 0))); + painter->drawLine(QLineF(center + QPointF(0, -w), center + QPointF(0, w))); + } + break; + } + case tsCrosshair: { + if (center.y() > clip.top() && center.y() < clip.bottom()) { + painter->drawLine(QLineF(clip.left(), center.y(), clip.right(), center.y())); + } + if (center.x() > clip.left() && center.x() < clip.right()) { + painter->drawLine(QLineF(center.x(), clip.top(), center.x(), clip.bottom())); + } + break; + } + case tsCircle: { + if (clip.intersects(QRectF(center - QPointF(w, w), center + QPointF(w, w)).toRect())) { + painter->drawEllipse(center, w, w); + } + break; + } + case tsSquare: { + if (clip.intersects(QRectF(center - QPointF(w, w), center + QPointF(w, w)).toRect())) { + painter->drawRect(QRectF(center - QPointF(w, w), center + QPointF(w, w))); + } + break; + } } - case tsCrosshair: - { - if (center.y() > clip.top() && center.y() < clip.bottom()) - painter->drawLine(QLineF(clip.left(), center.y(), clip.right(), center.y())); - if (center.x() > clip.left() && center.x() < clip.right()) - painter->drawLine(QLineF(center.x(), clip.top(), center.x(), clip.bottom())); - break; - } - case tsCircle: - { - if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect())) - painter->drawEllipse(center, w, w); - break; - } - case tsSquare: - { - if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect())) - painter->drawRect(QRectF(center-QPointF(w, w), center+QPointF(w, w))); - break; - } - } } /*! If the tracer is connected with a graph (\ref setGraph), this function updates the tracer's \a position to reside on the graph data, depending on the configured key (\ref setGraphKey). - + It is called automatically on every redraw and normally doesn't need to be called manually. One exception is when you want to read the tracer coordinates via \a position and are not sure that the graph's data (or the tracer key with \ref setGraphKey) hasn't changed since the last redraw. In that situation, call this function before accessing \a position, to make sure you don't get out-of-date coordinates. - + If there is no graph set on this tracer, this function does nothing. */ void QCPItemTracer::updatePosition() { - if (mGraph) - { - if (mParentPlot->hasPlottable(mGraph)) - { - 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); - else - { - QCPDataMap::const_iterator it = mGraph->data()->lowerBound(mGraphKey); - if (it != first) // mGraphKey is somewhere between iterators - { - QCPDataMap::const_iterator prevIt = it-1; - 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); - } 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 (mGraph) { + if (mParentPlot->hasPlottable(mGraph)) { + 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); + } else { + QCPDataMap::const_iterator it = mGraph->data()->lowerBound(mGraphKey); + if (it != first) { // mGraphKey is somewhere between iterators + QCPDataMap::const_iterator prevIt = it - 1; + 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); + } 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); + } + } else { // mGraphKey is exactly on first iterator + position->setCoords(it.key(), it.value().value); + } + } + } else if (mGraph->data()->size() == 1) { + QCPDataMap::const_iterator it = mGraph->data()->constBegin(); + position->setCoords(it.key(), it.value().value); + } else { + qDebug() << Q_FUNC_INFO << "graph has no data"; } - } else // mGraphKey is exactly on first iterator - position->setCoords(it.key(), it.value().value); + } else { + qDebug() << Q_FUNC_INFO << "graph not contained in QCustomPlot instance (anymore)"; } - } else if (mGraph->data()->size() == 1) - { - QCPDataMap::const_iterator it = mGraph->data()->constBegin(); - position->setCoords(it.key(), it.value().value); - } else - qDebug() << Q_FUNC_INFO << "graph has no data"; - } else - qDebug() << Q_FUNC_INFO << "graph not contained in QCustomPlot instance (anymore)"; - } + } } /*! \internal @@ -23301,7 +23537,7 @@ void QCPItemTracer::updatePosition() */ QPen QCPItemTracer::mainPen() const { - return mSelected ? mSelectedPen : mPen; + return mSelected ? mSelectedPen : mPen; } /*! \internal @@ -23311,7 +23547,7 @@ QPen QCPItemTracer::mainPen() const */ QBrush QCPItemTracer::mainBrush() const { - return mSelected ? mSelectedBrush : mBrush; + return mSelected ? mSelectedBrush : mBrush; } @@ -23327,36 +23563,36 @@ QBrush QCPItemTracer::mainBrush() const It has two positions, \a left and \a right, which define the span of the bracket. If \a left is actually farther to the left than \a right, the bracket is opened to the bottom, as shown in the example image. - + The bracket supports multiple styles via \ref setStyle. The length, i.e. how far the bracket stretches away from the embraced span, can be controlled with \ref setLength. - + \image html QCPItemBracket-length.png
Demonstrating the effect of different values for \ref setLength, for styles \ref bsCalligraphic and \ref bsSquare. Anchors and positions are displayed for reference.
- + It provides an anchor \a center, to allow connection of other items, e.g. an arrow (QCPItemLine or QCPItemCurve) or a text label (QCPItemText), to the bracket. */ /*! Creates a bracket item and sets default values. - + The constructed item can be added to the plot with QCustomPlot::addItem. */ QCPItemBracket::QCPItemBracket(QCustomPlot *parentPlot) : - QCPAbstractItem(parentPlot), - left(createPosition(QLatin1String("left"))), - right(createPosition(QLatin1String("right"))), - center(createAnchor(QLatin1String("center"), aiCenter)) + QCPAbstractItem(parentPlot), + left(createPosition(QLatin1String("left"))), + right(createPosition(QLatin1String("right"))), + center(createAnchor(QLatin1String("center"), aiCenter)) { - left->setCoords(0, 0); - right->setCoords(1, 1); - - setPen(QPen(Qt::black)); - setSelectedPen(QPen(Qt::blue, 2)); - setLength(8); - setStyle(bsCalligraphic); + left->setCoords(0, 0); + right->setCoords(1, 1); + + setPen(QPen(Qt::black)); + setSelectedPen(QPen(Qt::blue, 2)); + setLength(8); + setStyle(bsCalligraphic); } QCPItemBracket::~QCPItemBracket() @@ -23365,180 +23601,174 @@ QCPItemBracket::~QCPItemBracket() /*! Sets the pen that will be used to draw the bracket. - + Note that when the style is \ref bsCalligraphic, only the color will be taken from the pen, the stroke and width are ignored. To change the apparent stroke width of a calligraphic bracket, use \ref setLength, which has a similar effect. - + \see setSelectedPen */ void QCPItemBracket::setPen(const QPen &pen) { - mPen = pen; + mPen = pen; } /*! Sets the pen that will be used to draw the bracket when selected - + \see setPen, setSelected */ void QCPItemBracket::setSelectedPen(const QPen &pen) { - mSelectedPen = pen; + mSelectedPen = pen; } /*! Sets the \a length in pixels how far the bracket extends in the direction towards the embraced span of the bracket (i.e. perpendicular to the left-right-direction) - + \image html QCPItemBracket-length.png
Demonstrating the effect of different values for \ref setLength, for styles \ref bsCalligraphic and \ref bsSquare. Anchors and positions are displayed for reference.
*/ void QCPItemBracket::setLength(double length) { - mLength = length; + mLength = length; } /*! Sets the style of the bracket, i.e. the shape/visual appearance. - + \see setPen */ void QCPItemBracket::setStyle(QCPItemBracket::BracketStyle style) { - mStyle = style; + mStyle = style; } /* inherits documentation from base class */ double QCPItemBracket::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { - Q_UNUSED(details) - if (onlySelectable && !mSelectable) - return -1; - - QVector2D leftVec(left->pixelPoint()); - QVector2D rightVec(right->pixelPoint()); - 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; - - 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); - return qSqrt(qMin(qMin(a, b), c)); + Q_UNUSED(details) + if (onlySelectable && !mSelectable) { + return -1; } - 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); - return qSqrt(qMin(qMin(a, b), qMin(c, d))); + + QVector2D leftVec(left->pixelPoint()); + QVector2D rightVec(right->pixelPoint()); + if (leftVec.toPoint() == rightVec.toPoint()) { + return -1; } - } - 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; + + 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); + 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); + return qSqrt(qMin(qMin(a, b), qMin(c, d))); + } + } + return -1; } /* inherits documentation from base class */ void QCPItemBracket::draw(QCPPainter *painter) { - QVector2D leftVec(left->pixelPoint()); - QVector2D rightVec(right->pixelPoint()); - 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; - - QPolygon boundingPoly; - boundingPoly << leftVec.toPoint() << rightVec.toPoint() - << (rightVec-lengthVec).toPoint() << (leftVec-lengthVec).toPoint(); - QRect clip = clipRect().adjusted(-mainPen().widthF(), -mainPen().widthF(), mainPen().widthF(), mainPen().widthF()); - if (clip.intersects(boundingPoly.boundingRect())) - { - painter->setPen(mainPen()); - switch (mStyle) - { - case bsSquare: - { - painter->drawLine((centerVec+widthVec).toPointF(), (centerVec-widthVec).toPointF()); - painter->drawLine((centerVec+widthVec).toPointF(), (centerVec+widthVec+lengthVec).toPointF()); - painter->drawLine((centerVec-widthVec).toPointF(), (centerVec-widthVec+lengthVec).toPointF()); - break; - } - case bsRound: - { - painter->setBrush(Qt::NoBrush); - QPainterPath path; - path.moveTo((centerVec+widthVec+lengthVec).toPointF()); - path.cubicTo((centerVec+widthVec).toPointF(), (centerVec+widthVec).toPointF(), centerVec.toPointF()); - path.cubicTo((centerVec-widthVec).toPointF(), (centerVec-widthVec).toPointF(), (centerVec-widthVec+lengthVec).toPointF()); - painter->drawPath(path); - break; - } - case bsCurly: - { - 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()); - painter->drawPath(path); - break; - } - case bsCalligraphic: - { - painter->setPen(Qt::NoPen); - painter->setBrush(QBrush(mainPen().color())); - 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.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()); - - painter->drawPath(path); - break; - } + QVector2D leftVec(left->pixelPoint()); + QVector2D rightVec(right->pixelPoint()); + 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; + + QPolygon boundingPoly; + boundingPoly << leftVec.toPoint() << rightVec.toPoint() + << (rightVec - lengthVec).toPoint() << (leftVec - lengthVec).toPoint(); + QRect clip = clipRect().adjusted(-mainPen().widthF(), -mainPen().widthF(), mainPen().widthF(), mainPen().widthF()); + if (clip.intersects(boundingPoly.boundingRect())) { + painter->setPen(mainPen()); + switch (mStyle) { + case bsSquare: { + painter->drawLine((centerVec + widthVec).toPointF(), (centerVec - widthVec).toPointF()); + painter->drawLine((centerVec + widthVec).toPointF(), (centerVec + widthVec + lengthVec).toPointF()); + painter->drawLine((centerVec - widthVec).toPointF(), (centerVec - widthVec + lengthVec).toPointF()); + break; + } + case bsRound: { + painter->setBrush(Qt::NoBrush); + QPainterPath path; + path.moveTo((centerVec + widthVec + lengthVec).toPointF()); + path.cubicTo((centerVec + widthVec).toPointF(), (centerVec + widthVec).toPointF(), centerVec.toPointF()); + path.cubicTo((centerVec - widthVec).toPointF(), (centerVec - widthVec).toPointF(), (centerVec - widthVec + lengthVec).toPointF()); + painter->drawPath(path); + break; + } + case bsCurly: { + 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()); + painter->drawPath(path); + break; + } + case bsCalligraphic: { + painter->setPen(Qt::NoPen); + painter->setBrush(QBrush(mainPen().color())); + 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.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()); + + painter->drawPath(path); + break; + } + } } - } } /* inherits documentation from base class */ QPointF QCPItemBracket::anchorPixelPoint(int anchorId) const { - QVector2D leftVec(left->pixelPoint()); - QVector2D rightVec(right->pixelPoint()); - 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; - - switch (anchorId) - { - case aiCenter: - return centerVec.toPointF(); - } - qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId; - return QPointF(); + QVector2D leftVec(left->pixelPoint()); + QVector2D rightVec(right->pixelPoint()); + 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; + + switch (anchorId) { + case aiCenter: + return centerVec.toPointF(); + } + qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId; + return QPointF(); } /*! \internal diff --git a/third/3rd_qcustomplot/v1_3/qcustomplot.h b/third/3rd_qcustomplot/v1_3/qcustomplot.h index bb998f1..ef2e544 100644 --- a/third/3rd_qcustomplot/v1_3/qcustomplot.h +++ b/third/3rd_qcustomplot/v1_3/qcustomplot.h @@ -1,4 +1,4 @@ -/*************************************************************************** +/*************************************************************************** ** ** ** QCustomPlot, an easy to use, modern plotting widget for Qt ** ** Copyright (C) 2011-2015 Emanuel Eichhammer ** @@ -90,19 +90,18 @@ class QCPBars; /*! The QCP Namespace contains general enums and QFlags used throughout the QCustomPlot library */ -namespace QCP -{ +namespace QCP { /*! Defines the sides of a rectangular entity to which margins can be applied. - + \see QCPLayoutElement::setAutoMargins, QCPAxisRect::setAutoMargins */ enum MarginSide { msLeft = 0x01 ///< 0x01 left margin - ,msRight = 0x02 ///< 0x02 right margin - ,msTop = 0x04 ///< 0x04 top margin - ,msBottom = 0x08 ///< 0x08 bottom margin - ,msAll = 0xFF ///< 0xFF all margins - ,msNone = 0x00 ///< 0x00 no margin +, msRight = 0x02 ///< 0x02 right margin +, msTop = 0x04 ///< 0x04 top margin +, msBottom = 0x08 ///< 0x08 bottom margin +, msAll = 0xFF ///< 0xFF all margins +, msNone = 0x00 ///< 0x00 no margin }; Q_DECLARE_FLAGS(MarginSides, MarginSide) @@ -110,117 +109,131 @@ Q_DECLARE_FLAGS(MarginSides, MarginSide) Defines what objects of a plot can be forcibly drawn antialiased/not antialiased. If an object is neither forcibly drawn antialiased nor forcibly drawn not antialiased, it is up to the respective element how it is drawn. Typically it provides a \a setAntialiased function for this. - + \c AntialiasedElements is a flag of or-combined elements of this enum type. - + \see QCustomPlot::setAntialiasedElements, QCustomPlot::setNotAntialiasedElements */ enum AntialiasedElement { aeAxes = 0x0001 ///< 0x0001 Axis base line and tick marks - ,aeGrid = 0x0002 ///< 0x0002 Grid lines - ,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) - ,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 - ,aeAll = 0xFFFF ///< 0xFFFF All elements - ,aeNone = 0x0000 ///< 0x0000 No elements +, aeGrid = 0x0002 ///< 0x0002 Grid lines +, 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) +, 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 +, aeAll = 0xFFFF ///< 0xFFFF All elements +, aeNone = 0x0000 ///< 0x0000 No elements }; Q_DECLARE_FLAGS(AntialiasedElements, AntialiasedElement) /*! Defines plotting hints that control various aspects of the quality and speed of plotting. - + \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. +, 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. }; Q_DECLARE_FLAGS(PlottingHints, PlottingHint) /*! Defines the mouse interactions possible with QCustomPlot. - + \c Interactions is a flag of or-combined elements of this enum type. - + \see QCustomPlot::setInteractions */ enum Interaction { iRangeDrag = 0x001 ///< 0x001 Axis ranges are draggable (see \ref QCPAxisRect::setRangeDrag, \ref QCPAxisRect::setRangeDragAxes) - ,iRangeZoom = 0x002 ///< 0x002 Axis ranges are zoomable with the mouse wheel (see \ref QCPAxisRect::setRangeZoom, \ref QCPAxisRect::setRangeZoomAxes) - ,iMultiSelect = 0x004 ///< 0x004 The user can select multiple objects by holding the modifier set by \ref QCustomPlot::setMultiSelectModifier while clicking - ,iSelectPlottables = 0x008 ///< 0x008 Plottables are selectable (e.g. graphs, curves, bars,... see QCPAbstractPlottable) - ,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,...) +, iRangeZoom = 0x002 ///< 0x002 Axis ranges are zoomable with the mouse wheel (see \ref QCPAxisRect::setRangeZoom, \ref QCPAxisRect::setRangeZoomAxes) +, iMultiSelect = 0x004 ///< 0x004 The user can select multiple objects by holding the modifier set by \ref QCustomPlot::setMultiSelectModifier while clicking +, iSelectPlottables = 0x008 ///< 0x008 Plottables are selectable (e.g. graphs, curves, bars,... see QCPAbstractPlottable) +, 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,...) }; Q_DECLARE_FLAGS(Interactions, Interaction) /*! \internal - + Returns whether the specified \a value is considered an invalid data value for plottables (i.e. is \e nan or \e +/-inf). This function is used to check data validity upon replots, when the compiler flag \c QCUSTOMPLOT_CHECK_DATA is set. */ inline bool isInvalidData(double value) { - return qIsNaN(value) || qIsInf(value); + return qIsNaN(value) || qIsInf(value); } /*! \internal \overload - + Checks two arguments instead of one. */ inline bool isInvalidData(double value1, double value2) { - return isInvalidData(value1) || isInvalidData(value2); + return isInvalidData(value1) || isInvalidData(value2); } /*! \internal - + Sets the specified \a side of \a margins to \a value - + \see getMarginValue */ inline void setMarginValue(QMargins &margins, QCP::MarginSide side, int value) { - switch (side) - { - case QCP::msLeft: margins.setLeft(value); break; - case QCP::msRight: margins.setRight(value); break; - case QCP::msTop: margins.setTop(value); break; - case QCP::msBottom: margins.setBottom(value); break; - case QCP::msAll: margins = QMargins(value, value, value, value); break; - default: break; - } + switch (side) { + case QCP::msLeft: + margins.setLeft(value); + break; + case QCP::msRight: + margins.setRight(value); + break; + case QCP::msTop: + margins.setTop(value); + break; + case QCP::msBottom: + margins.setBottom(value); + break; + case QCP::msAll: + margins = QMargins(value, value, value, value); + break; + default: + break; + } } /*! \internal - + Returns the value of the specified \a side of \a margins. If \a side is \ref QCP::msNone or \ref QCP::msAll, returns 0. - + \see setMarginValue */ inline int getMarginValue(const QMargins &margins, QCP::MarginSide side) { - switch (side) - { - case QCP::msLeft: return margins.left(); - case QCP::msRight: return margins.right(); - case QCP::msTop: return margins.top(); - case QCP::msBottom: return margins.bottom(); - default: break; - } - return 0; + switch (side) { + case QCP::msLeft: + return margins.left(); + case QCP::msRight: + return margins.right(); + case QCP::msTop: + return margins.top(); + case QCP::msBottom: + return margins.bottom(); + default: + break; + } + return 0; } } // end of namespace QCP @@ -233,304 +246,364 @@ Q_DECLARE_OPERATORS_FOR_FLAGS(QCP::Interactions) class QCP_LIB_DECL QCPScatterStyle { - Q_GADGET + Q_GADGET public: - /*! - Defines the shape used for scatter points. + /*! + 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) - }; + 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); - - // 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; } + 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); - // 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); + // 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; + } - // 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; + // 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; - - // non-property members: - bool mPenDefined; + // 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); class QCP_LIB_DECL QCPPainter : public QPainter { - Q_GADGET + Q_GADGET public: - /*! - Defines special modes the painter can operate in. They disable or enable certain subsets of features/fixes/workarounds, - depending on whether they are wanted on the respective output device. - */ - enum PainterMode { pmDefault = 0x00 ///< 0x00 Default mode for painting on screen devices - ,pmVectorized = 0x01 ///< 0x01 Mode for vectorized painting (e.g. PDF export). For example, this prevents some antialiasing fixes. - ,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_DECLARE_FLAGS(PainterModes, PainterMode) - - QCPPainter(); - QCPPainter(QPaintDevice *device); - ~QCPPainter(); - - // getters: - bool antialiasing() const { return testRenderHint(QPainter::Antialiasing); } - PainterModes modes() const { return mModes; } + /*! + Defines special modes the painter can operate in. They disable or enable certain subsets of features/fixes/workarounds, + depending on whether they are wanted on the respective output device. + */ + enum PainterMode { pmDefault = 0x00 ///< 0x00 Default mode for painting on screen devices + , pmVectorized = 0x01 ///< 0x01 Mode for vectorized painting (e.g. PDF export). For example, this prevents some antialiasing fixes. + , 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_DECLARE_FLAGS(PainterModes, PainterMode) - // setters: - void setAntialiasing(bool enabled); - void setMode(PainterMode mode, bool enabled=true); - void setModes(PainterModes modes); + QCPPainter(); + QCPPainter(QPaintDevice *device); + ~QCPPainter(); + + // getters: + bool antialiasing() const { + return testRenderHint(QPainter::Antialiasing); + } + PainterModes modes() const { + return mModes; + } + + // setters: + void setAntialiasing(bool enabled); + void setMode(PainterMode mode, bool enabled = true); + void setModes(PainterModes modes); + + // methods hiding non-virtual base class functions (QPainter bug workarounds): + bool begin(QPaintDevice *device); + void setPen(const QPen &pen); + void setPen(const QColor &color); + void setPen(Qt::PenStyle penStyle); + void drawLine(const QLineF &line); + void drawLine(const QPointF &p1, const QPointF &p2) { + drawLine(QLineF(p1, p2)); + } + void save(); + void restore(); + + // non-virtual methods: + void makeNonCosmetic(); - // methods hiding non-virtual base class functions (QPainter bug workarounds): - bool begin(QPaintDevice *device); - void setPen(const QPen &pen); - void setPen(const QColor &color); - void setPen(Qt::PenStyle penStyle); - void drawLine(const QLineF &line); - void drawLine(const QPointF &p1, const QPointF &p2) {drawLine(QLineF(p1, p2));} - void save(); - void restore(); - - // non-virtual methods: - void makeNonCosmetic(); - protected: - // property members: - PainterModes mModes; - bool mIsAntialiasing; - - // non-property members: - QStack mAntialiasingStack; + // property members: + PainterModes mModes; + bool mIsAntialiasing; + + // non-property members: + QStack mAntialiasingStack; }; Q_DECLARE_OPERATORS_FOR_FLAGS(QCPPainter::PainterModes) class QCP_LIB_DECL QCPLayer : public QObject { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QCustomPlot* parentPlot READ parentPlot) - Q_PROPERTY(QString name READ name) - Q_PROPERTY(int index READ index) - Q_PROPERTY(QList children READ children) - Q_PROPERTY(bool visible READ visible WRITE setVisible) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QCustomPlot* parentPlot READ parentPlot) + Q_PROPERTY(QString name READ name) + Q_PROPERTY(int index READ index) + Q_PROPERTY(QList children READ children) + Q_PROPERTY(bool visible READ visible WRITE setVisible) + /// \endcond public: - QCPLayer(QCustomPlot* parentPlot, const QString &layerName); - ~QCPLayer(); - - // getters: - QCustomPlot *parentPlot() const { return mParentPlot; } - QString name() const { return mName; } - int index() const { return mIndex; } - QList children() const { return mChildren; } - bool visible() const { return mVisible; } - - // setters: - void setVisible(bool visible); - + QCPLayer(QCustomPlot *parentPlot, const QString &layerName); + ~QCPLayer(); + + // getters: + QCustomPlot *parentPlot() const { + return mParentPlot; + } + QString name() const { + return mName; + } + int index() const { + return mIndex; + } + QList children() const { + return mChildren; + } + bool visible() const { + return mVisible; + } + + // setters: + void setVisible(bool visible); + protected: - // property members: - QCustomPlot *mParentPlot; - QString mName; - int mIndex; - QList mChildren; - bool mVisible; - - // non-virtual methods: - void addChild(QCPLayerable *layerable, bool prepend); - void removeChild(QCPLayerable *layerable); - + // property members: + QCustomPlot *mParentPlot; + QString mName; + int mIndex; + QList mChildren; + bool mVisible; + + // non-virtual methods: + void addChild(QCPLayerable *layerable, bool prepend); + void removeChild(QCPLayerable *layerable); + private: - Q_DISABLE_COPY(QCPLayer) - - friend class QCustomPlot; - friend class QCPLayerable; + Q_DISABLE_COPY(QCPLayer) + + friend class QCustomPlot; + friend class QCPLayerable; }; class QCP_LIB_DECL QCPLayerable : public QObject { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(bool visible READ visible WRITE setVisible) - Q_PROPERTY(QCustomPlot* parentPlot READ parentPlot) - Q_PROPERTY(QCPLayerable* parentLayerable READ parentLayerable) - Q_PROPERTY(QCPLayer* layer READ layer WRITE setLayer NOTIFY layerChanged) - Q_PROPERTY(bool antialiased READ antialiased WRITE setAntialiased) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(bool visible READ visible WRITE setVisible) + Q_PROPERTY(QCustomPlot *parentPlot READ parentPlot) + Q_PROPERTY(QCPLayerable *parentLayerable READ parentLayerable) + Q_PROPERTY(QCPLayer *layer READ layer WRITE setLayer NOTIFY layerChanged) + Q_PROPERTY(bool antialiased READ antialiased WRITE setAntialiased) + /// \endcond public: - QCPLayerable(QCustomPlot *plot, QString targetLayer=QString(), QCPLayerable *parentLayerable=0); - ~QCPLayerable(); - - // getters: - bool visible() const { return mVisible; } - QCustomPlot *parentPlot() const { return mParentPlot; } - QCPLayerable *parentLayerable() const { return mParentLayerable.data(); } - QCPLayer *layer() const { return mLayer; } - bool antialiased() const { return mAntialiased; } - - // setters: - void setVisible(bool on); - Q_SLOT bool setLayer(QCPLayer *layer); - bool setLayer(const QString &layerName); - void setAntialiased(bool enabled); - - // introduced virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; - - // non-property methods: - bool realVisibility() const; - + QCPLayerable(QCustomPlot *plot, QString targetLayer = QString(), QCPLayerable *parentLayerable = 0); + ~QCPLayerable(); + + // getters: + bool visible() const { + return mVisible; + } + QCustomPlot *parentPlot() const { + return mParentPlot; + } + QCPLayerable *parentLayerable() const { + return mParentLayerable.data(); + } + QCPLayer *layer() const { + return mLayer; + } + bool antialiased() const { + return mAntialiased; + } + + // setters: + void setVisible(bool on); + Q_SLOT bool setLayer(QCPLayer *layer); + bool setLayer(const QString &layerName); + void setAntialiased(bool enabled); + + // introduced virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = 0) const; + + // non-property methods: + bool realVisibility() const; + signals: - void layerChanged(QCPLayer *newLayer); - + void layerChanged(QCPLayer *newLayer); + protected: - // property members: - bool mVisible; - QCustomPlot *mParentPlot; - QPointer mParentLayerable; - QCPLayer *mLayer; - bool mAntialiased; - - // introduced virtual methods: - virtual void parentPlotInitialized(QCustomPlot *parentPlot); - virtual QCP::Interaction selectionCategory() const; - virtual QRect clipRect() const; - virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const = 0; - virtual void draw(QCPPainter *painter) = 0; - // events: - virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged); - virtual void deselectEvent(bool *selectionStateChanged); - - // non-property methods: - void initializeParentPlot(QCustomPlot *parentPlot); - void setParentLayerable(QCPLayerable* parentLayerable); - bool moveToLayer(QCPLayer *layer, bool prepend); - void applyAntialiasingHint(QCPPainter *painter, bool localAntialiased, QCP::AntialiasedElement overrideElement) const; - + // property members: + bool mVisible; + QCustomPlot *mParentPlot; + QPointer mParentLayerable; + QCPLayer *mLayer; + bool mAntialiased; + + // introduced virtual methods: + virtual void parentPlotInitialized(QCustomPlot *parentPlot); + virtual QCP::Interaction selectionCategory() const; + virtual QRect clipRect() const; + virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const = 0; + virtual void draw(QCPPainter *painter) = 0; + // events: + virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged); + virtual void deselectEvent(bool *selectionStateChanged); + + // non-property methods: + void initializeParentPlot(QCustomPlot *parentPlot); + void setParentLayerable(QCPLayerable *parentLayerable); + bool moveToLayer(QCPLayer *layer, bool prepend); + void applyAntialiasingHint(QCPPainter *painter, bool localAntialiased, QCP::AntialiasedElement overrideElement) const; + private: - Q_DISABLE_COPY(QCPLayerable) - - friend class QCustomPlot; - friend class QCPAxisRect; + Q_DISABLE_COPY(QCPLayerable) + + friend class QCustomPlot; + friend class QCPAxisRect; }; class QCP_LIB_DECL QCPRange { public: - double lower, upper; - - QCPRange(); - QCPRange(double lower, double upper); - - bool operator==(const QCPRange& other) const { return lower == other.lower && upper == other.upper; } - bool operator!=(const QCPRange& other) const { return !(*this == other); } - - QCPRange &operator+=(const double& value) { lower+=value; upper+=value; return *this; } - QCPRange &operator-=(const double& value) { lower-=value; upper-=value; return *this; } - QCPRange &operator*=(const double& value) { lower*=value; upper*=value; return *this; } - QCPRange &operator/=(const double& value) { lower/=value; upper/=value; return *this; } - friend inline const QCPRange operator+(const QCPRange&, double); - friend inline const QCPRange operator+(double, const QCPRange&); - friend inline const QCPRange operator-(const QCPRange& range, double value); - friend inline const QCPRange operator*(const QCPRange& range, double value); - 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(); - void expand(const QCPRange &otherRange); - QCPRange expanded(const QCPRange &otherRange) const; - QCPRange sanitizedForLogScale() const; - QCPRange sanitizedForLinScale() const; - bool contains(double value) const; - - static bool validRange(double lower, double upper); - static bool validRange(const QCPRange &range); - static const double minRange; //1e-280; - static const double maxRange; //1e280; - + double lower, upper; + + QCPRange(); + QCPRange(double lower, double upper); + + bool operator==(const QCPRange &other) const { + return lower == other.lower && upper == other.upper; + } + bool operator!=(const QCPRange &other) const { + return !(*this == other); + } + + QCPRange &operator+=(const double &value) { + lower += value; + upper += value; + return *this; + } + QCPRange &operator-=(const double &value) { + lower -= value; + upper -= value; + return *this; + } + QCPRange &operator*=(const double &value) { + lower *= value; + upper *= value; + return *this; + } + QCPRange &operator/=(const double &value) { + lower /= value; + upper /= value; + return *this; + } + friend inline const QCPRange operator+(const QCPRange &, double); + friend inline const QCPRange operator+(double, const QCPRange &); + friend inline const QCPRange operator-(const QCPRange &range, double value); + friend inline const QCPRange operator*(const QCPRange &range, double value); + 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(); + void expand(const QCPRange &otherRange); + QCPRange expanded(const QCPRange &otherRange) const; + QCPRange sanitizedForLogScale() const; + QCPRange sanitizedForLinScale() const; + bool contains(double value) const; + + static bool validRange(double lower, double upper); + static bool validRange(const QCPRange &range); + static const double minRange; //1e-280; + static const double maxRange; //1e280; + }; Q_DECLARE_TYPEINFO(QCPRange, Q_MOVABLE_TYPE); /* documentation of inline functions */ /*! \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. */ @@ -539,779 +612,924 @@ Q_DECLARE_TYPEINFO(QCPRange, Q_MOVABLE_TYPE); /*! Adds \a value to both boundaries of the range. */ -inline const QCPRange operator+(const QCPRange& range, double value) +inline const QCPRange operator+(const QCPRange &range, double value) { - QCPRange result(range); - result += value; - return result; + QCPRange result(range); + result += value; + return result; } /*! Adds \a value to both boundaries of the range. */ -inline const QCPRange operator+(double value, const QCPRange& range) +inline const QCPRange operator+(double value, const QCPRange &range) { - QCPRange result(range); - result += value; - return result; + QCPRange result(range); + result += value; + return result; } /*! Subtracts \a value from both boundaries of the range. */ -inline const QCPRange operator-(const QCPRange& range, double value) +inline const QCPRange operator-(const QCPRange &range, double value) { - QCPRange result(range); - result -= value; - return result; + QCPRange result(range); + result -= value; + return result; } /*! Multiplies both boundaries of the range by \a value. */ -inline const QCPRange operator*(const QCPRange& range, double value) +inline const QCPRange operator*(const QCPRange &range, double value) { - QCPRange result(range); - result *= value; - return result; + QCPRange result(range); + result *= value; + return result; } /*! Multiplies both boundaries of the range by \a value. */ -inline const QCPRange operator*(double value, const QCPRange& range) +inline const QCPRange operator*(double value, const QCPRange &range) { - QCPRange result(range); - result *= value; - return result; + QCPRange result(range); + result *= value; + return result; } /*! Divides both boundaries of the range by \a value. */ -inline const QCPRange operator/(const QCPRange& range, double value) +inline const QCPRange operator/(const QCPRange &range, double value) { - QCPRange result(range); - result /= value; - return result; + QCPRange result(range); + result /= value; + return result; } class QCP_LIB_DECL QCPMarginGroup : public QObject { - Q_OBJECT -public: - QCPMarginGroup(QCustomPlot *parentPlot); - ~QCPMarginGroup(); - - // non-virtual methods: - QList elements(QCP::MarginSide side) const { return mChildren.value(side); } - bool isEmpty() const; - void clear(); - + Q_OBJECT +public: QCPMarginGroup(QCustomPlot *parentPlot); + ~QCPMarginGroup(); + + // non-virtual methods: + QList elements(QCP::MarginSide side) const { + return mChildren.value(side); + } + bool isEmpty() const; + void clear(); + protected: - // non-property members: - QCustomPlot *mParentPlot; - QHash > mChildren; - - // non-virtual methods: - int commonMargin(QCP::MarginSide side) const; - void addChild(QCP::MarginSide side, QCPLayoutElement *element); - void removeChild(QCP::MarginSide side, QCPLayoutElement *element); - + // non-property members: + QCustomPlot *mParentPlot; + QHash > mChildren; + + // non-virtual methods: + int commonMargin(QCP::MarginSide side) const; + void addChild(QCP::MarginSide side, QCPLayoutElement *element); + void removeChild(QCP::MarginSide side, QCPLayoutElement *element); + private: - Q_DISABLE_COPY(QCPMarginGroup) - - friend class QCPLayoutElement; + Q_DISABLE_COPY(QCPMarginGroup) + + friend class QCPLayoutElement; }; class QCP_LIB_DECL QCPLayoutElement : public QCPLayerable { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QCPLayout* layout READ layout) - Q_PROPERTY(QRect rect READ rect) - Q_PROPERTY(QRect outerRect READ outerRect WRITE setOuterRect) - Q_PROPERTY(QMargins margins READ margins WRITE setMargins) - Q_PROPERTY(QMargins minimumMargins READ minimumMargins WRITE setMinimumMargins) - Q_PROPERTY(QSize minimumSize READ minimumSize WRITE setMinimumSize) - Q_PROPERTY(QSize maximumSize READ maximumSize WRITE setMaximumSize) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(QCPLayout *layout READ layout) + Q_PROPERTY(QRect rect READ rect) + Q_PROPERTY(QRect outerRect READ outerRect WRITE setOuterRect) + Q_PROPERTY(QMargins margins READ margins WRITE setMargins) + Q_PROPERTY(QMargins minimumMargins READ minimumMargins WRITE setMinimumMargins) + Q_PROPERTY(QSize minimumSize READ minimumSize WRITE setMinimumSize) + Q_PROPERTY(QSize maximumSize READ maximumSize WRITE setMaximumSize) + /// \endcond public: - /*! - Defines the phases of the update process, that happens just before a replot. At each phase, - \ref update is called with the according UpdatePhase value. - */ - enum UpdatePhase { upPreparation ///< Phase used for any type of preparation that needs to be done before margin calculation and layout - ,upMargins ///< Phase in which the margins are calculated and set - ,upLayout ///< Final phase in which the layout system places the rects of the elements - }; - Q_ENUMS(UpdatePhase) + /*! + Defines the phases of the update process, that happens just before a replot. At each phase, + \ref update is called with the according UpdatePhase value. + */ + enum UpdatePhase { upPreparation ///< Phase used for any type of preparation that needs to be done before margin calculation and layout + , upMargins ///< Phase in which the margins are calculated and set + , upLayout ///< Final phase in which the layout system places the rects of the elements + }; + Q_ENUMS(UpdatePhase) + + explicit QCPLayoutElement(QCustomPlot *parentPlot = 0); + virtual ~QCPLayoutElement(); + + // getters: + QCPLayout *layout() const { + return mParentLayout; + } + QRect rect() const { + return mRect; + } + QRect outerRect() const { + return mOuterRect; + } + QMargins margins() const { + return mMargins; + } + QMargins minimumMargins() const { + return mMinimumMargins; + } + QCP::MarginSides autoMargins() const { + return mAutoMargins; + } + QSize minimumSize() const { + return mMinimumSize; + } + QSize maximumSize() const { + return mMaximumSize; + } + QCPMarginGroup *marginGroup(QCP::MarginSide side) const { + return mMarginGroups.value(side, (QCPMarginGroup *)0); + } + QHash marginGroups() const { + return mMarginGroups; + } + + // setters: + void setOuterRect(const QRect &rect); + void setMargins(const QMargins &margins); + void setMinimumMargins(const QMargins &margins); + void setAutoMargins(QCP::MarginSides sides); + void setMinimumSize(const QSize &size); + void setMinimumSize(int width, int height); + void setMaximumSize(const QSize &size); + void setMaximumSize(int width, int height); + void setMarginGroup(QCP::MarginSides sides, QCPMarginGroup *group); + + // introduced virtual methods: + virtual void update(UpdatePhase phase); + virtual QSize minimumSizeHint() const; + virtual QSize maximumSizeHint() const; + virtual QList elements(bool recursive) const; + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = 0) const; - explicit QCPLayoutElement(QCustomPlot *parentPlot=0); - virtual ~QCPLayoutElement(); - - // getters: - QCPLayout *layout() const { return mParentLayout; } - QRect rect() const { return mRect; } - QRect outerRect() const { return mOuterRect; } - QMargins margins() const { return mMargins; } - QMargins minimumMargins() const { return mMinimumMargins; } - QCP::MarginSides autoMargins() const { return mAutoMargins; } - QSize minimumSize() const { return mMinimumSize; } - QSize maximumSize() const { return mMaximumSize; } - QCPMarginGroup *marginGroup(QCP::MarginSide side) const { return mMarginGroups.value(side, (QCPMarginGroup*)0); } - QHash marginGroups() const { return mMarginGroups; } - - // setters: - void setOuterRect(const QRect &rect); - void setMargins(const QMargins &margins); - void setMinimumMargins(const QMargins &margins); - void setAutoMargins(QCP::MarginSides sides); - void setMinimumSize(const QSize &size); - void setMinimumSize(int width, int height); - void setMaximumSize(const QSize &size); - void setMaximumSize(int width, int height); - void setMarginGroup(QCP::MarginSides sides, QCPMarginGroup *group); - - // introduced virtual methods: - virtual void update(UpdatePhase phase); - virtual QSize minimumSizeHint() const; - virtual QSize maximumSizeHint() const; - virtual QList elements(bool recursive) const; - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; - protected: - // property members: - QCPLayout *mParentLayout; - QSize mMinimumSize, mMaximumSize; - QRect mRect, mOuterRect; - QMargins mMargins, mMinimumMargins; - QCP::MarginSides mAutoMargins; - QHash mMarginGroups; - - // 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)} - - // 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); + // property members: + QCPLayout *mParentLayout; + QSize mMinimumSize, mMaximumSize; + QRect mRect, mOuterRect; + QMargins mMargins, mMinimumMargins; + QCP::MarginSides mAutoMargins; + QHash mMarginGroups; + + // 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) + } + + // 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); private: - Q_DISABLE_COPY(QCPLayoutElement) - - friend class QCustomPlot; - friend class QCPLayout; - friend class QCPMarginGroup; + Q_DISABLE_COPY(QCPLayoutElement) + + friend class QCustomPlot; + friend class QCPLayout; + friend class QCPMarginGroup; }; class QCP_LIB_DECL QCPLayout : public QCPLayoutElement { - Q_OBJECT + Q_OBJECT public: - explicit QCPLayout(); - - // reimplemented virtual methods: - virtual void update(UpdatePhase phase); - virtual QList elements(bool recursive) const; - - // introduced virtual methods: - virtual int elementCount() const = 0; - virtual QCPLayoutElement* elementAt(int index) const = 0; - virtual QCPLayoutElement* takeAt(int index) = 0; - virtual bool take(QCPLayoutElement* element) = 0; - virtual void simplify(); - - // non-virtual methods: - bool removeAt(int index); - bool remove(QCPLayoutElement* element); - void clear(); - + explicit QCPLayout(); + + // reimplemented virtual methods: + virtual void update(UpdatePhase phase); + virtual QList elements(bool recursive) const; + + // introduced virtual methods: + virtual int elementCount() const = 0; + virtual QCPLayoutElement *elementAt(int index) const = 0; + virtual QCPLayoutElement *takeAt(int index) = 0; + virtual bool take(QCPLayoutElement *element) = 0; + virtual void simplify(); + + // non-virtual methods: + bool removeAt(int index); + bool remove(QCPLayoutElement *element); + void clear(); + protected: - // introduced virtual methods: - virtual void updateLayout(); - - // non-virtual methods: - void sizeConstraintsChanged() const; - void adoptElement(QCPLayoutElement *el); - void releaseElement(QCPLayoutElement *el); - QVector getSectionSizes(QVector maxSizes, QVector minSizes, QVector stretchFactors, int totalSize) const; - + // introduced virtual methods: + virtual void updateLayout(); + + // non-virtual methods: + void sizeConstraintsChanged() const; + void adoptElement(QCPLayoutElement *el); + void releaseElement(QCPLayoutElement *el); + QVector getSectionSizes(QVector maxSizes, QVector minSizes, QVector stretchFactors, int totalSize) const; + private: - Q_DISABLE_COPY(QCPLayout) - friend class QCPLayoutElement; + Q_DISABLE_COPY(QCPLayout) + friend class QCPLayoutElement; }; class QCP_LIB_DECL QCPLayoutGrid : public QCPLayout { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(int rowCount READ rowCount) - Q_PROPERTY(int columnCount READ columnCount) - Q_PROPERTY(QList columnStretchFactors READ columnStretchFactors WRITE setColumnStretchFactors) - Q_PROPERTY(QList rowStretchFactors READ rowStretchFactors WRITE setRowStretchFactors) - Q_PROPERTY(int columnSpacing READ columnSpacing WRITE setColumnSpacing) - Q_PROPERTY(int rowSpacing READ rowSpacing WRITE setRowSpacing) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(int rowCount READ rowCount) + Q_PROPERTY(int columnCount READ columnCount) + Q_PROPERTY(QList columnStretchFactors READ columnStretchFactors WRITE setColumnStretchFactors) + Q_PROPERTY(QList rowStretchFactors READ rowStretchFactors WRITE setRowStretchFactors) + Q_PROPERTY(int columnSpacing READ columnSpacing WRITE setColumnSpacing) + Q_PROPERTY(int rowSpacing READ rowSpacing WRITE setRowSpacing) + /// \endcond public: - explicit QCPLayoutGrid(); - virtual ~QCPLayoutGrid(); - - // getters: - int rowCount() const; - int columnCount() const; - QList columnStretchFactors() const { return mColumnStretchFactors; } - QList rowStretchFactors() const { return mRowStretchFactors; } - int columnSpacing() const { return mColumnSpacing; } - int rowSpacing() const { return mRowSpacing; } - - // setters: - void setColumnStretchFactor(int column, double factor); - void setColumnStretchFactors(const QList &factors); - void setRowStretchFactor(int row, double factor); - void setRowStretchFactors(const QList &factors); - void setColumnSpacing(int pixels); - void setRowSpacing(int pixels); - - // 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; - - // non-virtual methods: - QCPLayoutElement *element(int row, int column) const; - bool addElement(int row, int column, QCPLayoutElement *element); - bool hasElement(int row, int column); - void expandTo(int newRowCount, int newColumnCount); - void insertRow(int newIndex); - void insertColumn(int newIndex); - + explicit QCPLayoutGrid(); + virtual ~QCPLayoutGrid(); + + // getters: + int rowCount() const; + int columnCount() const; + QList columnStretchFactors() const { + return mColumnStretchFactors; + } + QList rowStretchFactors() const { + return mRowStretchFactors; + } + int columnSpacing() const { + return mColumnSpacing; + } + int rowSpacing() const { + return mRowSpacing; + } + + // setters: + void setColumnStretchFactor(int column, double factor); + void setColumnStretchFactors(const QList &factors); + void setRowStretchFactor(int row, double factor); + void setRowStretchFactors(const QList &factors); + void setColumnSpacing(int pixels); + void setRowSpacing(int pixels); + + // 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; + + // non-virtual methods: + QCPLayoutElement *element(int row, int column) const; + bool addElement(int row, int column, QCPLayoutElement *element); + bool hasElement(int row, int column); + void expandTo(int newRowCount, int newColumnCount); + void insertRow(int newIndex); + void insertColumn(int newIndex); + protected: - // property members: - QList > mElements; - QList mColumnStretchFactors; - QList mRowStretchFactors; - int mColumnSpacing, mRowSpacing; - - // non-virtual methods: - void getMinimumRowColSizes(QVector *minColWidths, QVector *minRowHeights) const; - void getMaximumRowColSizes(QVector *maxColWidths, QVector *maxRowHeights) const; - + // property members: + QList > mElements; + QList mColumnStretchFactors; + QList mRowStretchFactors; + int mColumnSpacing, mRowSpacing; + + // non-virtual methods: + void getMinimumRowColSizes(QVector *minColWidths, QVector *minRowHeights) const; + void getMaximumRowColSizes(QVector *maxColWidths, QVector *maxRowHeights) const; + private: - Q_DISABLE_COPY(QCPLayoutGrid) + Q_DISABLE_COPY(QCPLayoutGrid) }; class QCP_LIB_DECL QCPLayoutInset : public QCPLayout { - Q_OBJECT + Q_OBJECT public: - /*! - Defines how the placement and sizing is handled for a certain element in a QCPLayoutInset. - */ - 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 - }; - - explicit QCPLayoutInset(); - virtual ~QCPLayoutInset(); - - // getters: - InsetPlacement insetPlacement(int index) const; - Qt::Alignment insetAlignment(int index) const; - QRectF insetRect(int index) const; - - // setters: - void setInsetPlacement(int index, InsetPlacement placement); - void setInsetAlignment(int index, Qt::Alignment alignment); - 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; - - // non-virtual methods: - void addElement(QCPLayoutElement *element, Qt::Alignment alignment); - void addElement(QCPLayoutElement *element, const QRectF &rect); - + /*! + Defines how the placement and sizing is handled for a certain element in a QCPLayoutInset. + */ + 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 + }; + + explicit QCPLayoutInset(); + virtual ~QCPLayoutInset(); + + // getters: + InsetPlacement insetPlacement(int index) const; + Qt::Alignment insetAlignment(int index) const; + QRectF insetRect(int index) const; + + // setters: + void setInsetPlacement(int index, InsetPlacement placement); + void setInsetAlignment(int index, Qt::Alignment alignment); + 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; + + // non-virtual methods: + void addElement(QCPLayoutElement *element, Qt::Alignment alignment); + void addElement(QCPLayoutElement *element, const QRectF &rect); + protected: - // property members: - QList mElements; - QList mInsetPlacement; - QList mInsetAlignment; - QList mInsetRect; - + // property members: + QList mElements; + QList mInsetPlacement; + QList mInsetAlignment; + QList mInsetRect; + private: - Q_DISABLE_COPY(QCPLayoutInset) + Q_DISABLE_COPY(QCPLayoutInset) }; class QCP_LIB_DECL QCPLineEnding { - Q_GADGET + Q_GADGET public: - /*! - Defines the type of ending decoration for line-like items, e.g. an arrow. - - \image html QCPLineEnding.png - - The width and length of these decorations can be controlled with the functions \ref setWidth - and \ref setLength. Some decorations like \ref esDisc, \ref esSquare, \ref esDiamond and \ref esBar only - support a width, the length property is ignored. - - \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) - ,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) - }; - - QCPLineEnding(); - QCPLineEnding(EndingStyle style, double width=8, double length=10, bool inverted=false); - - // getters: - EndingStyle style() const { return mStyle; } - double width() const { return mWidth; } - double length() const { return mLength; } - bool inverted() const { return mInverted; } - - // setters: - void setStyle(EndingStyle style); - void setWidth(double width); - void setLength(double length); - void setInverted(bool inverted); - - // 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; - + /*! + Defines the type of ending decoration for line-like items, e.g. an arrow. + + \image html QCPLineEnding.png + + The width and length of these decorations can be controlled with the functions \ref setWidth + and \ref setLength. Some decorations like \ref esDisc, \ref esSquare, \ref esDiamond and \ref esBar only + support a width, the length property is ignored. + + \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) + , 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) + }; + + QCPLineEnding(); + QCPLineEnding(EndingStyle style, double width = 8, double length = 10, bool inverted = false); + + // getters: + EndingStyle style() const { + return mStyle; + } + double width() const { + return mWidth; + } + double length() const { + return mLength; + } + bool inverted() const { + return mInverted; + } + + // setters: + void setStyle(EndingStyle style); + void setWidth(double width); + void setLength(double length); + void setInverted(bool inverted); + + // 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; + protected: - // property members: - EndingStyle mStyle; - double mWidth, mLength; - bool mInverted; + // property members: + EndingStyle mStyle; + double mWidth, mLength; + bool mInverted; }; Q_DECLARE_TYPEINFO(QCPLineEnding, Q_MOVABLE_TYPE); -class QCP_LIB_DECL QCPGrid :public QCPLayerable +class QCP_LIB_DECL QCPGrid : public QCPLayerable { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(bool subGridVisible READ subGridVisible WRITE setSubGridVisible) - Q_PROPERTY(bool antialiasedSubGrid READ antialiasedSubGrid WRITE setAntialiasedSubGrid) - Q_PROPERTY(bool antialiasedZeroLine READ antialiasedZeroLine WRITE setAntialiasedZeroLine) - Q_PROPERTY(QPen pen READ pen WRITE setPen) - Q_PROPERTY(QPen subGridPen READ subGridPen WRITE setSubGridPen) - Q_PROPERTY(QPen zeroLinePen READ zeroLinePen WRITE setZeroLinePen) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(bool subGridVisible READ subGridVisible WRITE setSubGridVisible) + Q_PROPERTY(bool antialiasedSubGrid READ antialiasedSubGrid WRITE setAntialiasedSubGrid) + Q_PROPERTY(bool antialiasedZeroLine READ antialiasedZeroLine WRITE setAntialiasedZeroLine) + Q_PROPERTY(QPen pen READ pen WRITE setPen) + Q_PROPERTY(QPen subGridPen READ subGridPen WRITE setSubGridPen) + Q_PROPERTY(QPen zeroLinePen READ zeroLinePen WRITE setZeroLinePen) + /// \endcond public: - QCPGrid(QCPAxis *parentAxis); - - // getters: - bool subGridVisible() const { return mSubGridVisible; } - bool antialiasedSubGrid() const { return mAntialiasedSubGrid; } - bool antialiasedZeroLine() const { return mAntialiasedZeroLine; } - QPen pen() const { return mPen; } - QPen subGridPen() const { return mSubGridPen; } - QPen zeroLinePen() const { return mZeroLinePen; } - - // setters: - void setSubGridVisible(bool visible); - void setAntialiasedSubGrid(bool enabled); - void setAntialiasedZeroLine(bool enabled); - void setPen(const QPen &pen); - void setSubGridPen(const QPen &pen); - void setZeroLinePen(const QPen &pen); - + QCPGrid(QCPAxis *parentAxis); + + // getters: + bool subGridVisible() const { + return mSubGridVisible; + } + bool antialiasedSubGrid() const { + return mAntialiasedSubGrid; + } + bool antialiasedZeroLine() const { + return mAntialiasedZeroLine; + } + QPen pen() const { + return mPen; + } + QPen subGridPen() const { + return mSubGridPen; + } + QPen zeroLinePen() const { + return mZeroLinePen; + } + + // setters: + void setSubGridVisible(bool visible); + void setAntialiasedSubGrid(bool enabled); + void setAntialiasedZeroLine(bool enabled); + void setPen(const QPen &pen); + void setSubGridPen(const QPen &pen); + void setZeroLinePen(const QPen &pen); + protected: - // property members: - 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); - - // non-virtual methods: - void drawGridLines(QCPPainter *painter) const; - void drawSubGridLines(QCPPainter *painter) const; - - friend class QCPAxis; + // property members: + 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); + + // non-virtual methods: + void drawGridLines(QCPPainter *painter) const; + void drawSubGridLines(QCPPainter *painter) const; + + friend class QCPAxis; }; class QCP_LIB_DECL QCPAxis : public QCPLayerable { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - 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(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(int tickLengthIn READ tickLengthIn WRITE setTickLengthIn) - Q_PROPERTY(int tickLengthOut READ tickLengthOut WRITE setTickLengthOut) - Q_PROPERTY(int subTickCount READ subTickCount WRITE setSubTickCount) - Q_PROPERTY(int subTickLengthIn READ subTickLengthIn WRITE setSubTickLengthIn) - Q_PROPERTY(int subTickLengthOut READ subTickLengthOut WRITE setSubTickLengthOut) - Q_PROPERTY(QPen basePen READ basePen WRITE setBasePen) - Q_PROPERTY(QPen tickPen READ tickPen WRITE setTickPen) - Q_PROPERTY(QPen subTickPen READ subTickPen WRITE setSubTickPen) - Q_PROPERTY(QFont labelFont READ labelFont WRITE setLabelFont) - Q_PROPERTY(QColor labelColor READ labelColor WRITE setLabelColor) - Q_PROPERTY(QString label READ label WRITE setLabel) - Q_PROPERTY(int labelPadding READ labelPadding WRITE setLabelPadding) - Q_PROPERTY(int padding READ padding WRITE setPadding) - Q_PROPERTY(int offset READ offset WRITE setOffset) - Q_PROPERTY(SelectableParts selectedParts READ selectedParts WRITE setSelectedParts NOTIFY selectionChanged) - Q_PROPERTY(SelectableParts selectableParts READ selectableParts WRITE setSelectableParts NOTIFY selectableChanged) - Q_PROPERTY(QFont selectedTickLabelFont READ selectedTickLabelFont WRITE setSelectedTickLabelFont) - Q_PROPERTY(QFont selectedLabelFont READ selectedLabelFont WRITE setSelectedLabelFont) - Q_PROPERTY(QColor selectedTickLabelColor READ selectedTickLabelColor WRITE setSelectedTickLabelColor) - Q_PROPERTY(QColor selectedLabelColor READ selectedLabelColor WRITE setSelectedLabelColor) - Q_PROPERTY(QPen selectedBasePen READ selectedBasePen WRITE setSelectedBasePen) - Q_PROPERTY(QPen selectedTickPen READ selectedTickPen WRITE setSelectedTickPen) - Q_PROPERTY(QPen selectedSubTickPen READ selectedSubTickPen WRITE setSelectedSubTickPen) - Q_PROPERTY(QCPLineEnding lowerEnding READ lowerEnding WRITE setLowerEnding) - Q_PROPERTY(QCPLineEnding upperEnding READ upperEnding WRITE setUpperEnding) - Q_PROPERTY(QCPGrid* grid READ grid) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + 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(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(int tickLengthIn READ tickLengthIn WRITE setTickLengthIn) + Q_PROPERTY(int tickLengthOut READ tickLengthOut WRITE setTickLengthOut) + Q_PROPERTY(int subTickCount READ subTickCount WRITE setSubTickCount) + Q_PROPERTY(int subTickLengthIn READ subTickLengthIn WRITE setSubTickLengthIn) + Q_PROPERTY(int subTickLengthOut READ subTickLengthOut WRITE setSubTickLengthOut) + Q_PROPERTY(QPen basePen READ basePen WRITE setBasePen) + Q_PROPERTY(QPen tickPen READ tickPen WRITE setTickPen) + Q_PROPERTY(QPen subTickPen READ subTickPen WRITE setSubTickPen) + Q_PROPERTY(QFont labelFont READ labelFont WRITE setLabelFont) + Q_PROPERTY(QColor labelColor READ labelColor WRITE setLabelColor) + Q_PROPERTY(QString label READ label WRITE setLabel) + Q_PROPERTY(int labelPadding READ labelPadding WRITE setLabelPadding) + Q_PROPERTY(int padding READ padding WRITE setPadding) + Q_PROPERTY(int offset READ offset WRITE setOffset) + Q_PROPERTY(SelectableParts selectedParts READ selectedParts WRITE setSelectedParts NOTIFY selectionChanged) + Q_PROPERTY(SelectableParts selectableParts READ selectableParts WRITE setSelectableParts NOTIFY selectableChanged) + Q_PROPERTY(QFont selectedTickLabelFont READ selectedTickLabelFont WRITE setSelectedTickLabelFont) + Q_PROPERTY(QFont selectedLabelFont READ selectedLabelFont WRITE setSelectedLabelFont) + Q_PROPERTY(QColor selectedTickLabelColor READ selectedTickLabelColor WRITE setSelectedTickLabelColor) + Q_PROPERTY(QColor selectedLabelColor READ selectedLabelColor WRITE setSelectedLabelColor) + Q_PROPERTY(QPen selectedBasePen READ selectedBasePen WRITE setSelectedBasePen) + Q_PROPERTY(QPen selectedTickPen READ selectedTickPen WRITE setSelectedTickPen) + Q_PROPERTY(QPen selectedSubTickPen READ selectedSubTickPen WRITE setSelectedSubTickPen) + Q_PROPERTY(QCPLineEnding lowerEnding READ lowerEnding WRITE setLowerEnding) + Q_PROPERTY(QCPLineEnding upperEnding READ upperEnding WRITE setUpperEnding) + Q_PROPERTY(QCPGrid *grid READ grid) + /// \endcond public: - /*! - Defines at which side of the axis rect the axis will appear. This also affects how the tick - marks are drawn, on which side the labels are placed etc. - */ - enum AxisType { atLeft = 0x01 ///< 0x01 Axis is vertical and on the left side of the axis rect - ,atRight = 0x02 ///< 0x02 Axis is vertical and on the right side of the axis rect - ,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_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. - - \see setTickLabelSide - */ - enum LabelSide { lsInside ///< Tick labels will be displayed inside the axis rect and clipped to the inner axis rect - ,lsOutside ///< Tick labels will be displayed outside the axis rect - }; - Q_ENUMS(LabelSide) - /*! - Defines the scale of an axis. - \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). - }; - Q_ENUMS(ScaleType) - /*! - Defines the selectable parts of an axis. - \see setSelectableParts, setSelectedParts - */ - enum SelectablePart { spNone = 0 ///< None of the selectable parts - ,spAxis = 0x001 ///< The axis backbone and tick marks - ,spTickLabels = 0x002 ///< Tick labels (numbers) of this axis (as a whole, not individually) - ,spAxisLabel = 0x004 ///< The axis label - }; - Q_FLAGS(SelectablePart SelectableParts) - Q_DECLARE_FLAGS(SelectableParts, SelectablePart) - - explicit QCPAxis(QCPAxisRect *parent, AxisType type); - virtual ~QCPAxis(); - - // getters: - 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; } - 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; } - int subTickLengthIn() const; - int subTickLengthOut() const; - QPen basePen() const { return mBasePen; } - QPen tickPen() const { return mTickPen; } - QPen subTickPen() const { return mSubTickPen; } - QFont labelFont() const { return mLabelFont; } - QColor labelColor() const { return mLabelColor; } - QString label() const { return mLabel; } - int labelPadding() const; - int padding() const { return mPadding; } - int offset() const; - SelectableParts selectedParts() const { return mSelectedParts; } - SelectableParts selectableParts() const { return mSelectableParts; } - QFont selectedTickLabelFont() const { return mSelectedTickLabelFont; } - QFont selectedLabelFont() const { return mSelectedLabelFont; } - QColor selectedTickLabelColor() const { return mSelectedTickLabelColor; } - QColor selectedLabelColor() const { return mSelectedLabelColor; } - QPen selectedBasePen() const { return mSelectedBasePen; } - QPen selectedTickPen() const { return mSelectedTickPen; } - QPen selectedSubTickPen() const { return mSelectedSubTickPen; } - QCPLineEnding lowerEnding() const; - QCPLineEnding upperEnding() const; - QCPGrid *grid() const { return mGrid; } - - // 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 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 setSubTickLength(int inside, int outside=0); - void setSubTickLengthIn(int inside); - void setSubTickLengthOut(int outside); - void setBasePen(const QPen &pen); - void setTickPen(const QPen &pen); - void setSubTickPen(const QPen &pen); - void setLabelFont(const QFont &font); - void setLabelColor(const QColor &color); - void setLabel(const QString &str); - void setLabelPadding(int padding); - void setPadding(int padding); - void setOffset(int offset); - void setSelectedTickLabelFont(const QFont &font); - void setSelectedLabelFont(const QFont &font); - void setSelectedTickLabelColor(const QColor &color); - void setSelectedLabelColor(const QColor &color); - void setSelectedBasePen(const QPen &pen); - void setSelectedTickPen(const QPen &pen); - void setSelectedSubTickPen(const QPen &pen); - Q_SLOT void setSelectableParts(const QCPAxis::SelectableParts &selectableParts); - Q_SLOT void setSelectedParts(const QCPAxis::SelectableParts &selectedParts); - void setLowerEnding(const QCPLineEnding &ending); - void setUpperEnding(const QCPLineEnding &ending); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; - - // non-property methods: - Qt::Orientation orientation() const { return mOrientation; } - void moveRange(double diff); - void scaleRange(double factor, double center); - void setScaleRatio(const QCPAxis *otherAxis, double ratio=1.0); - void rescale(bool onlyVisiblePlottables=false); - double pixelToCoord(double value) const; - double coordToPixel(double value) const; - SelectablePart getPartAt(const QPointF &pos) const; - QList plottables() const; - QList graphs() const; - QList items() const; - - static AxisType marginSideToAxisType(QCP::MarginSide side); - static Qt::Orientation orientation(AxisType type) { return type==atBottom||type==atTop ? Qt::Horizontal : Qt::Vertical; } - static AxisType opposite(AxisType type); - + /*! + Defines at which side of the axis rect the axis will appear. This also affects how the tick + marks are drawn, on which side the labels are placed etc. + */ + enum AxisType { atLeft = 0x01 ///< 0x01 Axis is vertical and on the left side of the axis rect + , atRight = 0x02 ///< 0x02 Axis is vertical and on the right side of the axis rect + , 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_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. + + \see setTickLabelSide + */ + enum LabelSide { lsInside ///< Tick labels will be displayed inside the axis rect and clipped to the inner axis rect + , lsOutside ///< Tick labels will be displayed outside the axis rect + }; + Q_ENUMS(LabelSide) + /*! + Defines the scale of an axis. + \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). + }; + Q_ENUMS(ScaleType) + /*! + Defines the selectable parts of an axis. + \see setSelectableParts, setSelectedParts + */ + enum SelectablePart { spNone = 0 ///< None of the selectable parts + , spAxis = 0x001 ///< The axis backbone and tick marks + , spTickLabels = 0x002 ///< Tick labels (numbers) of this axis (as a whole, not individually) + , spAxisLabel = 0x004 ///< The axis label + }; + Q_FLAGS(SelectablePart SelectableParts) + Q_DECLARE_FLAGS(SelectableParts, SelectablePart) + + explicit QCPAxis(QCPAxisRect *parent, AxisType type); + virtual ~QCPAxis(); + + // getters: + 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; + } + 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; + } + int subTickLengthIn() const; + int subTickLengthOut() const; + QPen basePen() const { + return mBasePen; + } + QPen tickPen() const { + return mTickPen; + } + QPen subTickPen() const { + return mSubTickPen; + } + QFont labelFont() const { + return mLabelFont; + } + QColor labelColor() const { + return mLabelColor; + } + QString label() const { + return mLabel; + } + int labelPadding() const; + int padding() const { + return mPadding; + } + int offset() const; + SelectableParts selectedParts() const { + return mSelectedParts; + } + SelectableParts selectableParts() const { + return mSelectableParts; + } + QFont selectedTickLabelFont() const { + return mSelectedTickLabelFont; + } + QFont selectedLabelFont() const { + return mSelectedLabelFont; + } + QColor selectedTickLabelColor() const { + return mSelectedTickLabelColor; + } + QColor selectedLabelColor() const { + return mSelectedLabelColor; + } + QPen selectedBasePen() const { + return mSelectedBasePen; + } + QPen selectedTickPen() const { + return mSelectedTickPen; + } + QPen selectedSubTickPen() const { + return mSelectedSubTickPen; + } + QCPLineEnding lowerEnding() const; + QCPLineEnding upperEnding() const; + QCPGrid *grid() const { + return mGrid; + } + + // 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 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 setSubTickLength(int inside, int outside = 0); + void setSubTickLengthIn(int inside); + void setSubTickLengthOut(int outside); + void setBasePen(const QPen &pen); + void setTickPen(const QPen &pen); + void setSubTickPen(const QPen &pen); + void setLabelFont(const QFont &font); + void setLabelColor(const QColor &color); + void setLabel(const QString &str); + void setLabelPadding(int padding); + void setPadding(int padding); + void setOffset(int offset); + void setSelectedTickLabelFont(const QFont &font); + void setSelectedLabelFont(const QFont &font); + void setSelectedTickLabelColor(const QColor &color); + void setSelectedLabelColor(const QColor &color); + void setSelectedBasePen(const QPen &pen); + void setSelectedTickPen(const QPen &pen); + void setSelectedSubTickPen(const QPen &pen); + Q_SLOT void setSelectableParts(const QCPAxis::SelectableParts &selectableParts); + Q_SLOT void setSelectedParts(const QCPAxis::SelectableParts &selectedParts); + void setLowerEnding(const QCPLineEnding &ending); + void setUpperEnding(const QCPLineEnding &ending); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = 0) const; + + // non-property methods: + Qt::Orientation orientation() const { + return mOrientation; + } + void moveRange(double diff); + void scaleRange(double factor, double center); + void setScaleRatio(const QCPAxis *otherAxis, double ratio = 1.0); + void rescale(bool onlyVisiblePlottables = false); + double pixelToCoord(double value) const; + double coordToPixel(double value) const; + SelectablePart getPartAt(const QPointF &pos) const; + QList plottables() const; + QList graphs() const; + QList items() const; + + static AxisType marginSideToAxisType(QCP::MarginSide side); + static Qt::Orientation orientation(AxisType type) { + return type == atBottom || type == atTop ? Qt::Horizontal : Qt::Vertical; + } + 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); - void selectionChanged(const QCPAxis::SelectableParts &parts); - void selectableChanged(const QCPAxis::SelectableParts &parts); + void ticksRequest(); + void rangeChanged(const QCPRange &newRange); + void rangeChanged(const QCPRange &newRange, const QCPRange &oldRange); + void scaleTypeChanged(QCPAxis::ScaleType scaleType); + void selectionChanged(const QCPAxis::SelectableParts &parts); + void selectableChanged(const QCPAxis::SelectableParts &parts); protected: - // property members: - // axis base: - AxisType mAxisType; - QCPAxisRect *mAxisRect; - //int mOffset; // in QCPAxisPainter - int mPadding; - Qt::Orientation mOrientation; - SelectableParts mSelectableParts, mSelectedParts; - QPen mBasePen, mSelectedBasePen; - //QCPLineEnding mLowerEnding, mUpperEnding; // in QCPAxisPainter - // axis label: - //int mLabelPadding; // in QCPAxisPainter - QString mLabel; - QFont mLabelFont, mSelectedLabelFont; - QColor mLabelColor, mSelectedLabelColor; - // tick labels: - //int mTickLabelPadding; // in QCPAxisPainter - bool mTickLabels, mAutoTickLabels; - //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; - //int mTickLengthIn, mTickLengthOut, mSubTickLengthIn, mSubTickLengthOut; // QCPAxisPainter - QPen mTickPen, mSelectedTickPen; - QPen mSubTickPen, mSelectedSubTickPen; - // scale and range: - QCPRange mRange; - bool mRangeReversed; - ScaleType mScaleType; - double mScaleLogBase, mScaleLogBaseLogInv; - - // non-property members: - QCPGrid *mGrid; - QCPAxisPainterPrivate *mAxisPainter; - int mLowestVisibleTick, mHighestVisibleTick; - QVector mTickVector; - QVector mTickVectorLabels; - QVector mSubTickVector; - bool mCachedMarginValid; - 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; - // events: - virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged); - virtual void deselectEvent(bool *selectionStateChanged); - - // non-virtual methods: - void visibleTickBounds(int &lowIndex, int &highIndex) const; - double baseLog(double value) const; - double basePow(double value) const; - QPen getBasePen() const; - QPen getTickPen() const; - QPen getSubTickPen() const; - QFont getTickLabelFont() const; - QFont getLabelFont() const; - QColor getTickLabelColor() const; - QColor getLabelColor() const; - + // property members: + // axis base: + AxisType mAxisType; + QCPAxisRect *mAxisRect; + //int mOffset; // in QCPAxisPainter + int mPadding; + Qt::Orientation mOrientation; + SelectableParts mSelectableParts, mSelectedParts; + QPen mBasePen, mSelectedBasePen; + //QCPLineEnding mLowerEnding, mUpperEnding; // in QCPAxisPainter + // axis label: + //int mLabelPadding; // in QCPAxisPainter + QString mLabel; + QFont mLabelFont, mSelectedLabelFont; + QColor mLabelColor, mSelectedLabelColor; + // tick labels: + //int mTickLabelPadding; // in QCPAxisPainter + bool mTickLabels, mAutoTickLabels; + //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; + //int mTickLengthIn, mTickLengthOut, mSubTickLengthIn, mSubTickLengthOut; // QCPAxisPainter + QPen mTickPen, mSelectedTickPen; + QPen mSubTickPen, mSelectedSubTickPen; + // scale and range: + QCPRange mRange; + bool mRangeReversed; + ScaleType mScaleType; + double mScaleLogBase, mScaleLogBaseLogInv; + + // non-property members: + QCPGrid *mGrid; + QCPAxisPainterPrivate *mAxisPainter; + int mLowestVisibleTick, mHighestVisibleTick; + QVector mTickVector; + QVector mTickVectorLabels; + QVector mSubTickVector; + bool mCachedMarginValid; + 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; + // events: + virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged); + virtual void deselectEvent(bool *selectionStateChanged); + + // non-virtual methods: + void visibleTickBounds(int &lowIndex, int &highIndex) const; + double baseLog(double value) const; + double basePow(double value) const; + QPen getBasePen() const; + QPen getTickPen() const; + QPen getSubTickPen() const; + QFont getTickLabelFont() const; + QFont getLabelFont() const; + QColor getTickLabelColor() const; + QColor getLabelColor() const; + private: - Q_DISABLE_COPY(QCPAxis) - - friend class QCustomPlot; - friend class QCPGrid; - friend class QCPAxisRect; + Q_DISABLE_COPY(QCPAxis) + + friend class QCustomPlot; + friend class QCPGrid; + friend class QCPAxisRect; }; Q_DECLARE_OPERATORS_FOR_FLAGS(QCPAxis::SelectableParts) Q_DECLARE_OPERATORS_FOR_FLAGS(QCPAxis::AxisTypes) @@ -1321,218 +1539,249 @@ Q_DECLARE_METATYPE(QCPAxis::SelectablePart) class QCPAxisPainterPrivate { public: - explicit QCPAxisPainterPrivate(QCustomPlot *parentPlot); - virtual ~QCPAxisPainterPrivate(); - - virtual void draw(QCPPainter *painter); - virtual int size() const; - void clearCache(); - - QRect axisSelectionBox() const { return mAxisSelectionBox; } - QRect tickLabelsSelectionBox() const { return mTickLabelsSelectionBox; } - QRect labelSelectionBox() const { return mLabelSelectionBox; } - - // public property members: - QCPAxis::AxisType type; - QPen basePen; - QCPLineEnding lowerEnding, upperEnding; // directly accessed by QCPAxis setters/getters - int labelPadding; // directly accessed by QCPAxis setters/getters - QFont labelFont; - QColor labelColor; - QString label; - int tickLabelPadding; // directly accessed by QCPAxis setters/getters - double tickLabelRotation; // directly accessed by QCPAxis setters/getters - QCPAxis::LabelSide tickLabelSide; // directly accessed by QCPAxis setters/getters - bool substituteExponent; - bool numberMultiplyCross; // directly accessed by QCPAxis setters/getters - int tickLengthIn, tickLengthOut, subTickLengthIn, subTickLengthOut; // directly accessed by QCPAxis setters/getters - QPen tickPen, subTickPen; - QFont tickLabelFont; - QColor tickLabelColor; - QRect axisRect, viewportRect; - double offset; // directly accessed by QCPAxis setters/getters - bool abbreviateDecimalPowers; - bool reversedEndings; - - QVector subTickPositions; - QVector tickPositions; - QVector tickLabels; - + explicit QCPAxisPainterPrivate(QCustomPlot *parentPlot); + virtual ~QCPAxisPainterPrivate(); + + virtual void draw(QCPPainter *painter); + virtual int size() const; + void clearCache(); + + QRect axisSelectionBox() const { + return mAxisSelectionBox; + } + QRect tickLabelsSelectionBox() const { + return mTickLabelsSelectionBox; + } + QRect labelSelectionBox() const { + return mLabelSelectionBox; + } + + // public property members: + QCPAxis::AxisType type; + QPen basePen; + QCPLineEnding lowerEnding, upperEnding; // directly accessed by QCPAxis setters/getters + int labelPadding; // directly accessed by QCPAxis setters/getters + QFont labelFont; + QColor labelColor; + QString label; + int tickLabelPadding; // directly accessed by QCPAxis setters/getters + double tickLabelRotation; // directly accessed by QCPAxis setters/getters + QCPAxis::LabelSide tickLabelSide; // directly accessed by QCPAxis setters/getters + bool substituteExponent; + bool numberMultiplyCross; // directly accessed by QCPAxis setters/getters + int tickLengthIn, tickLengthOut, subTickLengthIn, subTickLengthOut; // directly accessed by QCPAxis setters/getters + QPen tickPen, subTickPen; + QFont tickLabelFont; + QColor tickLabelColor; + QRect axisRect, viewportRect; + double offset; // directly accessed by QCPAxis setters/getters + bool abbreviateDecimalPowers; + bool reversedEndings; + + QVector subTickPositions; + QVector tickPositions; + QVector tickLabels; + protected: - struct CachedLabel - { - QPointF offset; - QPixmap pixmap; - }; - struct TickLabelData - { - QString basePart, expPart; - QRect baseBounds, expBounds, totalBounds, rotatedTotalBounds; - QFont baseFont, expFont; - }; - QCustomPlot *mParentPlot; - QByteArray mLabelParameterHash; // to determine whether mLabelCache needs to be cleared due to changed parameters - QCache mLabelCache; - QRect mAxisSelectionBox, mTickLabelsSelectionBox, mLabelSelectionBox; - - virtual QByteArray generateLabelParameterHash() const; - - virtual void placeTickLabel(QCPPainter *painter, double position, int distanceToAxis, const QString &text, QSize *tickLabelsSize); - virtual void drawTickLabel(QCPPainter *painter, double x, double y, const TickLabelData &labelData) const; - virtual TickLabelData getTickLabelData(const QFont &font, const QString &text) const; - virtual QPointF getTickLabelDrawOffset(const TickLabelData &labelData) const; - virtual void getMaxTickLabelSize(const QFont &font, const QString &text, QSize *tickLabelsSize) const; + struct CachedLabel { + QPointF offset; + QPixmap pixmap; + }; + struct TickLabelData { + QString basePart, expPart; + QRect baseBounds, expBounds, totalBounds, rotatedTotalBounds; + QFont baseFont, expFont; + }; + QCustomPlot *mParentPlot; + QByteArray mLabelParameterHash; // to determine whether mLabelCache needs to be cleared due to changed parameters + QCache mLabelCache; + QRect mAxisSelectionBox, mTickLabelsSelectionBox, mLabelSelectionBox; + + virtual QByteArray generateLabelParameterHash() const; + + virtual void placeTickLabel(QCPPainter *painter, double position, int distanceToAxis, const QString &text, QSize *tickLabelsSize); + virtual void drawTickLabel(QCPPainter *painter, double x, double y, const TickLabelData &labelData) const; + virtual TickLabelData getTickLabelData(const QFont &font, const QString &text) const; + virtual QPointF getTickLabelDrawOffset(const TickLabelData &labelData) const; + virtual void getMaxTickLabelSize(const QFont &font, const QString &text, QSize *tickLabelsSize) const; }; class QCP_LIB_DECL QCPAbstractPlottable : public QCPLayerable { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - 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) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES 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) + /// \endcond public: - QCPAbstractPlottable(QCPAxis *keyAxis, QCPAxis *valueAxis); - - // 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; } - - // 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); + QCPAbstractPlottable(QCPAxis *keyAxis, QCPAxis *valueAxis); + + // 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; + } + + // 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); + + // 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; + + // non-property methods: + void rescaleAxes(bool onlyEnlarge = false) const; + void rescaleKeyAxis(bool onlyEnlarge = false) const; + void rescaleValueAxis(bool onlyEnlarge = false) const; - // 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; - - // 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); - + 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 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; + /*! + 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 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) - - friend class QCustomPlot; - friend class QCPAxis; - friend class QCPPlottableLegendItem; + Q_DISABLE_COPY(QCPAbstractPlottable) + + friend class QCustomPlot; + friend class QCPAxis; + friend class QCPPlottableLegendItem; }; class QCP_LIB_DECL QCPItemAnchor { public: - QCPItemAnchor(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString name, int anchorId=-1); - virtual ~QCPItemAnchor(); - - // getters: - QString name() const { return mName; } - virtual QPointF pixelPoint() const; - + QCPItemAnchor(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString name, int anchorId = -1); + virtual ~QCPItemAnchor(); + + // getters: + QString name() const { + return mName; + } + virtual QPointF pixelPoint() const; + protected: - // property members: - QString mName; - - // non-property members: - QCustomPlot *mParentPlot; - QCPAbstractItem *mParentItem; - int mAnchorId; - QSet mChildrenX, mChildrenY; - - // introduced virtual methods: - virtual QCPItemPosition *toQCPItemPosition() { return 0; } - - // non-virtual methods: - void addChildX(QCPItemPosition* pos); // called from pos when this anchor is set as parent - void removeChildX(QCPItemPosition *pos); // called from pos when its parent anchor is reset or pos deleted - void addChildY(QCPItemPosition* pos); // called from pos when this anchor is set as parent - void removeChildY(QCPItemPosition *pos); // called from pos when its parent anchor is reset or pos deleted - + // property members: + QString mName; + + // non-property members: + QCustomPlot *mParentPlot; + QCPAbstractItem *mParentItem; + int mAnchorId; + QSet mChildrenX, mChildrenY; + + // introduced virtual methods: + virtual QCPItemPosition *toQCPItemPosition() { + return 0; + } + + // non-virtual methods: + void addChildX(QCPItemPosition *pos); // called from pos when this anchor is set as parent + void removeChildX(QCPItemPosition *pos); // called from pos when its parent anchor is reset or pos deleted + void addChildY(QCPItemPosition *pos); // called from pos when this anchor is set as parent + void removeChildY(QCPItemPosition *pos); // called from pos when its parent anchor is reset or pos deleted + private: - Q_DISABLE_COPY(QCPItemAnchor) - - friend class QCPItemPosition; + Q_DISABLE_COPY(QCPItemAnchor) + + friend class QCPItemPosition; }; @@ -1540,751 +1789,895 @@ private: class QCP_LIB_DECL QCPItemPosition : public QCPItemAnchor { public: - /*! - Defines the ways an item position can be specified. Thus it defines what the numbers passed to - \ref setCoords actually mean. - - \see setType - */ - enum PositionType { ptAbsolute ///< Static positioning in pixels, starting from the top left corner of the viewport/widget. - ,ptViewportRatio ///< Static positioning given by a fraction of the viewport size. For example, if you call setCoords(0, 0), the position will be at the top - ///< left corner of the viewport/widget. setCoords(1, 1) will be at the bottom right corner, setCoords(0.5, 0) will be horizontally centered and - ///< vertically at the top of the viewport/widget, etc. - ,ptAxisRectRatio ///< Static positioning given by a fraction of the axis rect size (see \ref setAxisRect). For example, if you call setCoords(0, 0), the position will be at the top - ///< left corner of the axis rect. setCoords(1, 1) will be at the bottom right corner, setCoords(0.5, 0) will be horizontally centered and - ///< 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). - }; - - QCPItemPosition(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString name); - virtual ~QCPItemPosition(); - - // getters: - PositionType type() const { return typeX(); } - PositionType typeX() const { return mPositionTypeX; } - PositionType typeY() const { return mPositionTypeY; } - QCPItemAnchor *parentAnchor() const { return parentAnchorX(); } - QCPItemAnchor *parentAnchorX() const { return mParentAnchorX; } - QCPItemAnchor *parentAnchorY() const { return mParentAnchorY; } - double key() const { return mKey; } - double value() const { return mValue; } - QPointF coords() const { return QPointF(mKey, mValue); } - QCPAxis *keyAxis() const { return mKeyAxis.data(); } - QCPAxis *valueAxis() const { return mValueAxis.data(); } - QCPAxisRect *axisRect() const; - virtual QPointF pixelPoint() const; - - // setters: - void setType(PositionType type); - void setTypeX(PositionType type); - void setTypeY(PositionType type); - bool setParentAnchor(QCPItemAnchor *parentAnchor, bool keepPixelPosition=false); - bool setParentAnchorX(QCPItemAnchor *parentAnchor, bool keepPixelPosition=false); - bool setParentAnchorY(QCPItemAnchor *parentAnchor, bool keepPixelPosition=false); - void setCoords(double key, double value); - void setCoords(const QPointF &coords); - void setAxes(QCPAxis* keyAxis, QCPAxis* valueAxis); - void setAxisRect(QCPAxisRect *axisRect); - void setPixelPoint(const QPointF &pixelPoint); - + /*! + Defines the ways an item position can be specified. Thus it defines what the numbers passed to + \ref setCoords actually mean. + + \see setType + */ + enum PositionType { ptAbsolute ///< Static positioning in pixels, starting from the top left corner of the viewport/widget. + , ptViewportRatio ///< Static positioning given by a fraction of the viewport size. For example, if you call setCoords(0, 0), the position will be at the top + ///< left corner of the viewport/widget. setCoords(1, 1) will be at the bottom right corner, setCoords(0.5, 0) will be horizontally centered and + ///< vertically at the top of the viewport/widget, etc. + , ptAxisRectRatio ///< Static positioning given by a fraction of the axis rect size (see \ref setAxisRect). For example, if you call setCoords(0, 0), the position will be at the top + ///< left corner of the axis rect. setCoords(1, 1) will be at the bottom right corner, setCoords(0.5, 0) will be horizontally centered and + ///< 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). + }; + + QCPItemPosition(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString name); + virtual ~QCPItemPosition(); + + // getters: + PositionType type() const { + return typeX(); + } + PositionType typeX() const { + return mPositionTypeX; + } + PositionType typeY() const { + return mPositionTypeY; + } + QCPItemAnchor *parentAnchor() const { + return parentAnchorX(); + } + QCPItemAnchor *parentAnchorX() const { + return mParentAnchorX; + } + QCPItemAnchor *parentAnchorY() const { + return mParentAnchorY; + } + double key() const { + return mKey; + } + double value() const { + return mValue; + } + QPointF coords() const { + return QPointF(mKey, mValue); + } + QCPAxis *keyAxis() const { + return mKeyAxis.data(); + } + QCPAxis *valueAxis() const { + return mValueAxis.data(); + } + QCPAxisRect *axisRect() const; + virtual QPointF pixelPoint() const; + + // setters: + void setType(PositionType type); + void setTypeX(PositionType type); + void setTypeY(PositionType type); + bool setParentAnchor(QCPItemAnchor *parentAnchor, bool keepPixelPosition = false); + bool setParentAnchorX(QCPItemAnchor *parentAnchor, bool keepPixelPosition = false); + bool setParentAnchorY(QCPItemAnchor *parentAnchor, bool keepPixelPosition = false); + void setCoords(double key, double value); + void setCoords(const QPointF &coords); + void setAxes(QCPAxis *keyAxis, QCPAxis *valueAxis); + void setAxisRect(QCPAxisRect *axisRect); + void setPixelPoint(const QPointF &pixelPoint); + protected: - // property members: - PositionType mPositionTypeX, mPositionTypeY; - QPointer mKeyAxis, mValueAxis; - QPointer mAxisRect; - double mKey, mValue; - QCPItemAnchor *mParentAnchorX, *mParentAnchorY; - - // reimplemented virtual methods: - virtual QCPItemPosition *toQCPItemPosition() { return this; } - + // property members: + PositionType mPositionTypeX, mPositionTypeY; + QPointer mKeyAxis, mValueAxis; + QPointer mAxisRect; + double mKey, mValue; + QCPItemAnchor *mParentAnchorX, *mParentAnchorY; + + // reimplemented virtual methods: + virtual QCPItemPosition *toQCPItemPosition() { + return this; + } + private: - Q_DISABLE_COPY(QCPItemPosition) - + Q_DISABLE_COPY(QCPItemPosition) + }; class QCP_LIB_DECL QCPAbstractItem : public QCPLayerable { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(bool clipToAxisRect READ clipToAxisRect WRITE setClipToAxisRect) - Q_PROPERTY(QCPAxisRect* clipAxisRect READ clipAxisRect WRITE setClipAxisRect) - Q_PROPERTY(bool selectable READ selectable WRITE setSelectable NOTIFY selectableChanged) - Q_PROPERTY(bool selected READ selected WRITE setSelected NOTIFY selectionChanged) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(bool clipToAxisRect READ clipToAxisRect WRITE setClipToAxisRect) + Q_PROPERTY(QCPAxisRect *clipAxisRect READ clipAxisRect WRITE setClipAxisRect) + Q_PROPERTY(bool selectable READ selectable WRITE setSelectable NOTIFY selectableChanged) + Q_PROPERTY(bool selected READ selected WRITE setSelected NOTIFY selectionChanged) + /// \endcond public: - QCPAbstractItem(QCustomPlot *parentPlot); - virtual ~QCPAbstractItem(); - - // getters: - bool clipToAxisRect() const { return mClipToAxisRect; } - QCPAxisRect *clipAxisRect() const; - bool selectable() const { return mSelectable; } - bool selected() const { return mSelected; } - - // setters: - void setClipToAxisRect(bool clip); - void setClipAxisRect(QCPAxisRect *rect); - Q_SLOT void setSelectable(bool selectable); - Q_SLOT void setSelected(bool selected); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const = 0; - - // non-virtual methods: - QList positions() const { return mPositions; } - QList anchors() const { return mAnchors; } - QCPItemPosition *position(const QString &name) const; - QCPItemAnchor *anchor(const QString &name) const; - bool hasAnchor(const QString &name) const; - + QCPAbstractItem(QCustomPlot *parentPlot); + virtual ~QCPAbstractItem(); + + // getters: + bool clipToAxisRect() const { + return mClipToAxisRect; + } + QCPAxisRect *clipAxisRect() const; + bool selectable() const { + return mSelectable; + } + bool selected() const { + return mSelected; + } + + // setters: + void setClipToAxisRect(bool clip); + void setClipAxisRect(QCPAxisRect *rect); + Q_SLOT void setSelectable(bool selectable); + Q_SLOT void setSelected(bool selected); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = 0) const = 0; + + // non-virtual methods: + QList positions() const { + return mPositions; + } + QList anchors() const { + return mAnchors; + } + QCPItemPosition *position(const QString &name) const; + QCPItemAnchor *anchor(const QString &name) const; + bool hasAnchor(const QString &name) const; + signals: - void selectionChanged(bool selected); - void selectableChanged(bool selectable); - + void selectionChanged(bool selected); + void selectableChanged(bool selectable); + protected: - // property members: - bool mClipToAxisRect; - QPointer mClipAxisRect; - QList mPositions; - QList mAnchors; - 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; - // events: - virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged); - virtual void deselectEvent(bool *selectionStateChanged); - - // introduced virtual methods: - virtual QPointF anchorPixelPoint(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; - QCPItemPosition *createPosition(const QString &name); - QCPItemAnchor *createAnchor(const QString &name, int anchorId); - + // property members: + bool mClipToAxisRect; + QPointer mClipAxisRect; + QList mPositions; + QList mAnchors; + 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; + // events: + virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged); + virtual void deselectEvent(bool *selectionStateChanged); + + // introduced virtual methods: + virtual QPointF anchorPixelPoint(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; + QCPItemPosition *createPosition(const QString &name); + QCPItemAnchor *createAnchor(const QString &name, int anchorId); + private: - Q_DISABLE_COPY(QCPAbstractItem) - - friend class QCustomPlot; - friend class QCPItemAnchor; + Q_DISABLE_COPY(QCPAbstractItem) + + friend class QCustomPlot; + friend class QCPItemAnchor; }; class QCP_LIB_DECL QCustomPlot : public QWidget { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QRect viewport READ viewport WRITE setViewport) - Q_PROPERTY(QPixmap background READ background WRITE setBackground) - Q_PROPERTY(bool backgroundScaled READ backgroundScaled WRITE setBackgroundScaled) - Q_PROPERTY(Qt::AspectRatioMode backgroundScaledMode READ backgroundScaledMode WRITE setBackgroundScaledMode) - Q_PROPERTY(QCPLayoutGrid* plotLayout READ plotLayout) - Q_PROPERTY(bool autoAddPlottableToLegend READ autoAddPlottableToLegend WRITE setAutoAddPlottableToLegend) - 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) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(QRect viewport READ viewport WRITE setViewport) + Q_PROPERTY(QPixmap background READ background WRITE setBackground) + Q_PROPERTY(bool backgroundScaled READ backgroundScaled WRITE setBackgroundScaled) + Q_PROPERTY(Qt::AspectRatioMode backgroundScaledMode READ backgroundScaledMode WRITE setBackgroundScaledMode) + Q_PROPERTY(QCPLayoutGrid *plotLayout READ plotLayout) + Q_PROPERTY(bool autoAddPlottableToLegend READ autoAddPlottableToLegend WRITE setAutoAddPlottableToLegend) + 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) + /// \endcond public: - /*! - Defines how a layer should be inserted relative to an other layer. + /*! + Defines how a layer should be inserted relative to an other layer. - \see addLayer, moveLayer - */ - enum LayerInsertMode { limBelow ///< Layer is inserted below other layer - ,limAbove ///< Layer is inserted above other layer - }; - Q_ENUMS(LayerInsertMode) - - /*! - Defines with what timing the QCustomPlot surface is refreshed after a replot. + \see addLayer, moveLayer + */ + enum LayerInsertMode { limBelow ///< Layer is inserted below other layer + , limAbove ///< Layer is inserted above other layer + }; + Q_ENUMS(LayerInsertMode) - \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. - }; - - explicit QCustomPlot(QWidget *parent = 0); - virtual ~QCustomPlot(); - - // getters: - QRect viewport() const { return mViewport; } - QPixmap background() const { return mBackgroundPixmap; } - bool backgroundScaled() const { return mBackgroundScaled; } - Qt::AspectRatioMode backgroundScaledMode() const { return mBackgroundScaledMode; } - QCPLayoutGrid *plotLayout() const { return mPlotLayout; } - QCP::AntialiasedElements antialiasedElements() const { return mAntialiasedElements; } - QCP::AntialiasedElements notAntialiasedElements() const { return mNotAntialiasedElements; } - bool autoAddPlottableToLegend() const { return mAutoAddPlottableToLegend; } - const QCP::Interactions interactions() const { return mInteractions; } - int selectionTolerance() const { return mSelectionTolerance; } - bool noAntialiasingOnDrag() const { return mNoAntialiasingOnDrag; } - QCP::PlottingHints plottingHints() const { return mPlottingHints; } - Qt::KeyboardModifier multiSelectModifier() const { return mMultiSelectModifier; } + /*! + Defines with what timing the QCustomPlot surface is refreshed after a replot. - // setters: - void setViewport(const QRect &rect); - void setBackground(const QPixmap &pm); - void setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode=Qt::KeepAspectRatioByExpanding); - void setBackground(const QBrush &brush); - void setBackgroundScaled(bool scaled); - void setBackgroundScaledMode(Qt::AspectRatioMode mode); - void setAntialiasedElements(const QCP::AntialiasedElements &antialiasedElements); - void setAntialiasedElement(QCP::AntialiasedElement antialiasedElement, bool enabled=true); - void setNotAntialiasedElements(const QCP::AntialiasedElements ¬AntialiasedElements); - void setNotAntialiasedElement(QCP::AntialiasedElement notAntialiasedElement, bool enabled=true); - void setAutoAddPlottableToLegend(bool on); - void setInteractions(const QCP::Interactions &interactions); - void setInteraction(const QCP::Interaction &interaction, bool enabled=true); - void setSelectionTolerance(int pixels); - void setNoAntialiasingOnDrag(bool enabled); - void setPlottingHints(const QCP::PlottingHints &hints); - void setPlottingHint(QCP::PlottingHint hint, bool enabled=true); - void setMultiSelectModifier(Qt::KeyboardModifier modifier); - - // 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(); - int plottableCount() const; - QList selectedPlottables() const; - QCPAbstractPlottable *plottableAt(const QPointF &pos, bool onlySelectable=false) const; - bool hasPlottable(QCPAbstractPlottable *plottable) const; - - // specialized interface for QCPGraph: - QCPGraph *graph(int index) const; - QCPGraph *graph() const; - QCPGraph *addGraph(QCPAxis *keyAxis=0, QCPAxis *valueAxis=0); - bool removeGraph(QCPGraph *graph); - bool removeGraph(int index); - int clearGraphs(); - int graphCount() const; - QList selectedGraphs() const; + \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. + }; + + explicit QCustomPlot(QWidget *parent = 0); + virtual ~QCustomPlot(); + + // getters: + QRect viewport() const { + return mViewport; + } + QPixmap background() const { + return mBackgroundPixmap; + } + bool backgroundScaled() const { + return mBackgroundScaled; + } + Qt::AspectRatioMode backgroundScaledMode() const { + return mBackgroundScaledMode; + } + QCPLayoutGrid *plotLayout() const { + return mPlotLayout; + } + QCP::AntialiasedElements antialiasedElements() const { + return mAntialiasedElements; + } + QCP::AntialiasedElements notAntialiasedElements() const { + return mNotAntialiasedElements; + } + bool autoAddPlottableToLegend() const { + return mAutoAddPlottableToLegend; + } + const QCP::Interactions interactions() const { + return mInteractions; + } + int selectionTolerance() const { + return mSelectionTolerance; + } + bool noAntialiasingOnDrag() const { + return mNoAntialiasingOnDrag; + } + QCP::PlottingHints plottingHints() const { + return mPlottingHints; + } + Qt::KeyboardModifier multiSelectModifier() const { + return mMultiSelectModifier; + } + + // setters: + void setViewport(const QRect &rect); + void setBackground(const QPixmap &pm); + void setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode = Qt::KeepAspectRatioByExpanding); + void setBackground(const QBrush &brush); + void setBackgroundScaled(bool scaled); + void setBackgroundScaledMode(Qt::AspectRatioMode mode); + void setAntialiasedElements(const QCP::AntialiasedElements &antialiasedElements); + void setAntialiasedElement(QCP::AntialiasedElement antialiasedElement, bool enabled = true); + void setNotAntialiasedElements(const QCP::AntialiasedElements ¬AntialiasedElements); + void setNotAntialiasedElement(QCP::AntialiasedElement notAntialiasedElement, bool enabled = true); + void setAutoAddPlottableToLegend(bool on); + void setInteractions(const QCP::Interactions &interactions); + void setInteraction(const QCP::Interaction &interaction, bool enabled = true); + void setSelectionTolerance(int pixels); + void setNoAntialiasingOnDrag(bool enabled); + void setPlottingHints(const QCP::PlottingHints &hints); + void setPlottingHint(QCP::PlottingHint hint, bool enabled = true); + void setMultiSelectModifier(Qt::KeyboardModifier modifier); + + // 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(); + int plottableCount() const; + QList selectedPlottables() const; + QCPAbstractPlottable *plottableAt(const QPointF &pos, bool onlySelectable = false) const; + bool hasPlottable(QCPAbstractPlottable *plottable) const; + + // specialized interface for QCPGraph: + QCPGraph *graph(int index) const; + QCPGraph *graph() const; + QCPGraph *addGraph(QCPAxis *keyAxis = 0, QCPAxis *valueAxis = 0); + bool removeGraph(QCPGraph *graph); + bool removeGraph(int index); + int clearGraphs(); + int graphCount() const; + QList selectedGraphs() const; + + // item interface: + QCPAbstractItem *item(int index) const; + QCPAbstractItem *item() const; + bool addItem(QCPAbstractItem *item); + bool removeItem(QCPAbstractItem *item); + bool removeItem(int index); + int clearItems(); + int itemCount() const; + QList selectedItems() const; + QCPAbstractItem *itemAt(const QPointF &pos, bool onlySelectable = false) const; + bool hasItem(QCPAbstractItem *item) const; + + // layer interface: + QCPLayer *layer(const QString &name) const; + QCPLayer *layer(int index) const; + QCPLayer *currentLayer() const; + bool setCurrentLayer(const QString &name); + bool setCurrentLayer(QCPLayer *layer); + int layerCount() const; + bool addLayer(const QString &name, QCPLayer *otherLayer = 0, LayerInsertMode insertMode = limAbove); + bool removeLayer(QCPLayer *layer); + bool moveLayer(QCPLayer *layer, QCPLayer *otherLayer, LayerInsertMode insertMode = limAbove); + + // axis rect/layout interface: + int axisRectCount() const; + QCPAxisRect *axisRect(int index = 0) const; + QList axisRects() const; + QCPLayoutElement *layoutElementAt(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); + 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); + + QCPAxis *xAxis, *yAxis, *xAxis2, *yAxis2; + QCPLegend *legend; - // item interface: - QCPAbstractItem *item(int index) const; - QCPAbstractItem *item() const; - bool addItem(QCPAbstractItem* item); - bool removeItem(QCPAbstractItem *item); - bool removeItem(int index); - int clearItems(); - int itemCount() const; - QList selectedItems() const; - QCPAbstractItem *itemAt(const QPointF &pos, bool onlySelectable=false) const; - bool hasItem(QCPAbstractItem *item) const; - - // layer interface: - QCPLayer *layer(const QString &name) const; - QCPLayer *layer(int index) const; - QCPLayer *currentLayer() const; - bool setCurrentLayer(const QString &name); - bool setCurrentLayer(QCPLayer *layer); - int layerCount() const; - bool addLayer(const QString &name, QCPLayer *otherLayer=0, LayerInsertMode insertMode=limAbove); - bool removeLayer(QCPLayer *layer); - bool moveLayer(QCPLayer *layer, QCPLayer *otherLayer, LayerInsertMode insertMode=limAbove); - - // axis rect/layout interface: - int axisRectCount() const; - QCPAxisRect* axisRect(int index=0) const; - QList axisRects() const; - QCPLayoutElement* layoutElementAt(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); - 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); - - QCPAxis *xAxis, *yAxis, *xAxis2, *yAxis2; - QCPLegend *legend; - signals: - void mouseDoubleClick(QMouseEvent *event); - void mousePress(QMouseEvent *event); - void mouseMove(QMouseEvent *event); - void mouseRelease(QMouseEvent *event); - void mouseWheel(QWheelEvent *event); - - void plottableClick(QCPAbstractPlottable *plottable, QMouseEvent *event); - void plottableDoubleClick(QCPAbstractPlottable *plottable, 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(); - void afterReplot(); - + void mouseDoubleClick(QMouseEvent *event); + void mousePress(QMouseEvent *event); + void mouseMove(QMouseEvent *event); + void mouseRelease(QMouseEvent *event); + void mouseWheel(QWheelEvent *event); + + void plottableClick(QCPAbstractPlottable *plottable, QMouseEvent *event); + void plottableDoubleClick(QCPAbstractPlottable *plottable, 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(); + void afterReplot(); + protected: - // property members: - QRect mViewport; - QCPLayoutGrid *mPlotLayout; - bool mAutoAddPlottableToLegend; - QList mPlottables; - QList mGraphs; // extra list of plottables also in mPlottables that are of type QCPGraph - QList mItems; - QList mLayers; - QCP::AntialiasedElements mAntialiasedElements, mNotAntialiasedElements; - QCP::Interactions mInteractions; - int mSelectionTolerance; - bool mNoAntialiasingOnDrag; - QBrush mBackgroundBrush; - QPixmap mBackgroundPixmap; - QPixmap mScaledBackgroundPixmap; - bool mBackgroundScaled; - Qt::AspectRatioMode mBackgroundScaledMode; - QCPLayer *mCurrentLayer; - QCP::PlottingHints mPlottingHints; - Qt::KeyboardModifier mMultiSelectModifier; - - // non-property members: - QPixmap mPaintBuffer; - QPoint mMousePressPos; - QPointer mMouseEventElement; - bool mReplotting; - - // 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); - - // introduced virtual methods: - virtual void draw(QCPPainter *painter); - virtual void axisRemoved(QCPAxis *axis); - virtual void legendRemoved(QCPLegend *legend); - - // non-virtual methods: - void updateLayerIndices() const; - QCPLayerable *layerableAt(const QPointF &pos, bool onlySelectable, QVariant *selectionDetails=0) const; - void drawBackground(QCPPainter *painter); - - friend class QCPLegend; - friend class QCPAxis; - friend class QCPLayer; - friend class QCPAxisRect; + // property members: + QRect mViewport; + QCPLayoutGrid *mPlotLayout; + bool mAutoAddPlottableToLegend; + QList mPlottables; + QList mGraphs; // extra list of plottables also in mPlottables that are of type QCPGraph + QList mItems; + QList mLayers; + QCP::AntialiasedElements mAntialiasedElements, mNotAntialiasedElements; + QCP::Interactions mInteractions; + int mSelectionTolerance; + bool mNoAntialiasingOnDrag; + QBrush mBackgroundBrush; + QPixmap mBackgroundPixmap; + QPixmap mScaledBackgroundPixmap; + bool mBackgroundScaled; + Qt::AspectRatioMode mBackgroundScaledMode; + QCPLayer *mCurrentLayer; + QCP::PlottingHints mPlottingHints; + Qt::KeyboardModifier mMultiSelectModifier; + + // non-property members: + QPixmap mPaintBuffer; + QPoint mMousePressPos; + QPointer mMouseEventElement; + bool mReplotting; + + // 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); + + // introduced virtual methods: + virtual void draw(QCPPainter *painter); + virtual void axisRemoved(QCPAxis *axis); + virtual void legendRemoved(QCPLegend *legend); + + // non-virtual methods: + void updateLayerIndices() const; + QCPLayerable *layerableAt(const QPointF &pos, bool onlySelectable, QVariant *selectionDetails = 0) const; + void drawBackground(QCPPainter *painter); + + friend class QCPLegend; + friend class QCPAxis; + friend class QCPLayer; + friend class QCPAxisRect; }; class QCP_LIB_DECL QCPColorGradient { - Q_GADGET + Q_GADGET public: - /*! - Defines the color spaces in which color interpolation between gradient stops can be performed. - - \see setColorInterpolation - */ - enum ColorInterpolation { ciRGB ///< Color channels red, green and blue are linearly interpolated - ,ciHSV ///< Color channels hue, saturation and value are linearly interpolated (The hue is interpolated over the shortest angle distance) - }; - Q_ENUMS(ColorInterpolation) - - /*! - Defines the available presets that can be loaded with \ref loadPreset. See the documentation - there for an image of the presets. - */ - enum GradientPreset { gpGrayscale ///< Continuous lightness from black to white (suited for non-biased data representation) - ,gpHot ///< Continuous lightness from black over firey colors to white (suited for non-biased data representation) - ,gpCold ///< Continuous lightness from black over icey colors to white (suited for non-biased data representation) - ,gpNight ///< Continuous lightness from black over weak blueish colors to white (suited for non-biased data representation) - ,gpCandy ///< Blue over pink to white - ,gpGeography ///< Colors suitable to represent different elevations on geographical maps - ,gpIon ///< Half hue spectrum from black over purple to blue and finally green (creates banding illusion but allows more precise magnitude estimates) - ,gpThermal ///< Colors suitable for thermal imaging, ranging from dark blue over purple to orange, yellow and white - ,gpPolar ///< Colors suitable to emphasize polarity around the center, with blue for negative, black in the middle and red for positive values - ,gpSpectrum ///< An approximation of the visible light spectrum (creates banding illusion but allows more precise magnitude estimates) - ,gpJet ///< Hue variation similar to a spectrum, often used in numerical visualization (creates banding illusion but allows more precise magnitude estimates) - ,gpHues ///< Full hue cycle, with highest and lowest color red (suitable for periodic data, such as angles and phases, see \ref setPeriodic) - }; - Q_ENUMS(GradientPreset) - - QCPColorGradient(GradientPreset preset=gpCold); - bool operator==(const QCPColorGradient &other) const; - bool operator!=(const QCPColorGradient &other) const { return !(*this == other); } - - // getters: - int levelCount() const { return mLevelCount; } - QMap colorStops() const { return mColorStops; } - ColorInterpolation colorInterpolation() const { return mColorInterpolation; } - bool periodic() const { return mPeriodic; } - - // setters: - void setLevelCount(int n); - void setColorStops(const QMap &colorStops); - void setColorStopAt(double position, const QColor &color); - void setColorInterpolation(ColorInterpolation interpolation); - void setPeriodic(bool enabled); - - // non-property methods: - void colorize(const double *data, 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; - + /*! + Defines the color spaces in which color interpolation between gradient stops can be performed. + + \see setColorInterpolation + */ + enum ColorInterpolation { ciRGB ///< Color channels red, green and blue are linearly interpolated + , ciHSV ///< Color channels hue, saturation and value are linearly interpolated (The hue is interpolated over the shortest angle distance) + }; + Q_ENUMS(ColorInterpolation) + + /*! + Defines the available presets that can be loaded with \ref loadPreset. See the documentation + there for an image of the presets. + */ + enum GradientPreset { gpGrayscale ///< Continuous lightness from black to white (suited for non-biased data representation) + , gpHot ///< Continuous lightness from black over firey colors to white (suited for non-biased data representation) + , gpCold ///< Continuous lightness from black over icey colors to white (suited for non-biased data representation) + , gpNight ///< Continuous lightness from black over weak blueish colors to white (suited for non-biased data representation) + , gpCandy ///< Blue over pink to white + , gpGeography ///< Colors suitable to represent different elevations on geographical maps + , gpIon ///< Half hue spectrum from black over purple to blue and finally green (creates banding illusion but allows more precise magnitude estimates) + , gpThermal ///< Colors suitable for thermal imaging, ranging from dark blue over purple to orange, yellow and white + , gpPolar ///< Colors suitable to emphasize polarity around the center, with blue for negative, black in the middle and red for positive values + , gpSpectrum ///< An approximation of the visible light spectrum (creates banding illusion but allows more precise magnitude estimates) + , gpJet ///< Hue variation similar to a spectrum, often used in numerical visualization (creates banding illusion but allows more precise magnitude estimates) + , gpHues ///< Full hue cycle, with highest and lowest color red (suitable for periodic data, such as angles and phases, see \ref setPeriodic) + }; + Q_ENUMS(GradientPreset) + + QCPColorGradient(GradientPreset preset = gpCold); + bool operator==(const QCPColorGradient &other) const; + bool operator!=(const QCPColorGradient &other) const { + return !(*this == other); + } + + // getters: + int levelCount() const { + return mLevelCount; + } + QMap colorStops() const { + return mColorStops; + } + ColorInterpolation colorInterpolation() const { + return mColorInterpolation; + } + bool periodic() const { + return mPeriodic; + } + + // setters: + void setLevelCount(int n); + void setColorStops(const QMap &colorStops); + void setColorStopAt(double position, const QColor &color); + void setColorInterpolation(ColorInterpolation interpolation); + void setPeriodic(bool enabled); + + // non-property methods: + void colorize(const double *data, 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; - ColorInterpolation mColorInterpolation; - bool mPeriodic; - - // non-property members: - QVector mColorBuffer; - bool mColorBufferInvalidated; + void updateColorBuffer(); + + // property members: + int mLevelCount; + QMap mColorStops; + ColorInterpolation mColorInterpolation; + bool mPeriodic; + + // non-property members: + QVector mColorBuffer; + bool mColorBufferInvalidated; }; class QCP_LIB_DECL QCPAxisRect : public QCPLayoutElement { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QPixmap background READ background WRITE setBackground) - Q_PROPERTY(bool backgroundScaled READ backgroundScaled WRITE setBackgroundScaled) - Q_PROPERTY(Qt::AspectRatioMode backgroundScaledMode READ backgroundScaledMode WRITE setBackgroundScaledMode) - Q_PROPERTY(Qt::Orientations rangeDrag READ rangeDrag WRITE setRangeDrag) - Q_PROPERTY(Qt::Orientations rangeZoom READ rangeZoom WRITE setRangeZoom) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QPixmap background READ background WRITE setBackground) + Q_PROPERTY(bool backgroundScaled READ backgroundScaled WRITE setBackgroundScaled) + Q_PROPERTY(Qt::AspectRatioMode backgroundScaledMode READ backgroundScaledMode WRITE setBackgroundScaledMode) + Q_PROPERTY(Qt::Orientations rangeDrag READ rangeDrag WRITE setRangeDrag) + Q_PROPERTY(Qt::Orientations rangeZoom READ rangeZoom WRITE setRangeZoom) + /// \endcond public: - explicit QCPAxisRect(QCustomPlot *parentPlot, bool setupDefaultAxes=true); - virtual ~QCPAxisRect(); - - // getters: - QPixmap background() const { return mBackgroundPixmap; } - 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); - double rangeZoomFactor(Qt::Orientation orientation); - - // setters: - void setBackground(const QPixmap &pm); - void setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode=Qt::KeepAspectRatioByExpanding); - void setBackground(const QBrush &brush); - void setBackgroundScaled(bool scaled); - void setBackgroundScaledMode(Qt::AspectRatioMode mode); - void setRangeDrag(Qt::Orientations orientations); - void setRangeZoom(Qt::Orientations orientations); - void setRangeDragAxes(QCPAxis *horizontal, QCPAxis *vertical); - void setRangeZoomAxes(QCPAxis *horizontal, QCPAxis *vertical); - void setRangeZoomFactor(double horizontalFactor, double verticalFactor); - void setRangeZoomFactor(double factor); - - // non-property methods: - int axisCount(QCPAxis::AxisType type) const; - QCPAxis *axis(QCPAxis::AxisType type, int index=0) const; - QList axes(QCPAxis::AxisTypes types) const; - QList axes() const; - QCPAxis *addAxis(QCPAxis::AxisType type, QCPAxis *axis=0); - QList addAxes(QCPAxis::AxisTypes types); - bool removeAxis(QCPAxis *axis); - QCPLayoutInset *insetLayout() const { return mInsetLayout; } - - void setupFullAxesBox(bool connectRanges=false); - QList plottables() const; - QList graphs() const; - QList items() const; - - // read-only interface imitating a QRect: - int left() const { return mRect.left(); } - int right() const { return mRect.right(); } - int top() const { return mRect.top(); } - int bottom() const { return mRect.bottom(); } - int width() const { return mRect.width(); } - int height() const { return mRect.height(); } - QSize size() const { return mRect.size(); } - QPoint topLeft() const { return mRect.topLeft(); } - QPoint topRight() const { return mRect.topRight(); } - QPoint bottomLeft() const { return mRect.bottomLeft(); } - QPoint bottomRight() const { return mRect.bottomRight(); } - QPoint center() const { return mRect.center(); } - - // reimplemented virtual methods: - virtual void update(UpdatePhase phase); - virtual QList elements(bool recursive) const; + explicit QCPAxisRect(QCustomPlot *parentPlot, bool setupDefaultAxes = true); + virtual ~QCPAxisRect(); + + // getters: + QPixmap background() const { + return mBackgroundPixmap; + } + 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); + double rangeZoomFactor(Qt::Orientation orientation); + + // setters: + void setBackground(const QPixmap &pm); + void setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode = Qt::KeepAspectRatioByExpanding); + void setBackground(const QBrush &brush); + void setBackgroundScaled(bool scaled); + void setBackgroundScaledMode(Qt::AspectRatioMode mode); + void setRangeDrag(Qt::Orientations orientations); + void setRangeZoom(Qt::Orientations orientations); + void setRangeDragAxes(QCPAxis *horizontal, QCPAxis *vertical); + void setRangeZoomAxes(QCPAxis *horizontal, QCPAxis *vertical); + void setRangeZoomFactor(double horizontalFactor, double verticalFactor); + void setRangeZoomFactor(double factor); + + // non-property methods: + int axisCount(QCPAxis::AxisType type) const; + QCPAxis *axis(QCPAxis::AxisType type, int index = 0) const; + QList axes(QCPAxis::AxisTypes types) const; + QList axes() const; + QCPAxis *addAxis(QCPAxis::AxisType type, QCPAxis *axis = 0); + QList addAxes(QCPAxis::AxisTypes types); + bool removeAxis(QCPAxis *axis); + QCPLayoutInset *insetLayout() const { + return mInsetLayout; + } + + void setupFullAxesBox(bool connectRanges = false); + QList plottables() const; + QList graphs() const; + QList items() const; + + // read-only interface imitating a QRect: + int left() const { + return mRect.left(); + } + int right() const { + return mRect.right(); + } + int top() const { + return mRect.top(); + } + int bottom() const { + return mRect.bottom(); + } + int width() const { + return mRect.width(); + } + int height() const { + return mRect.height(); + } + QSize size() const { + return mRect.size(); + } + QPoint topLeft() const { + return mRect.topLeft(); + } + QPoint topRight() const { + return mRect.topRight(); + } + QPoint bottomLeft() const { + return mRect.bottomLeft(); + } + QPoint bottomRight() const { + return mRect.bottomRight(); + } + QPoint center() const { + return mRect.center(); + } + + // reimplemented virtual methods: + virtual void update(UpdatePhase phase); + virtual QList elements(bool recursive) const; protected: - // property members: - QBrush mBackgroundBrush; - QPixmap mBackgroundPixmap; - QPixmap mScaledBackgroundPixmap; - bool mBackgroundScaled; - Qt::AspectRatioMode mBackgroundScaledMode; - QCPLayoutInset *mInsetLayout; - Qt::Orientations mRangeDrag, mRangeZoom; - QPointer mRangeDragHorzAxis, mRangeDragVertAxis, mRangeZoomHorzAxis, mRangeZoomVertAxis; - double mRangeZoomFactorHorz, mRangeZoomFactorVert; - // non-property members: - QCPRange 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); - // events: - virtual void mousePressEvent(QMouseEvent *event); - virtual void mouseMoveEvent(QMouseEvent *event); - virtual void mouseReleaseEvent(QMouseEvent *event); - virtual void wheelEvent(QWheelEvent *event); - - // non-property methods: - void drawBackground(QCPPainter *painter); - void updateAxesOffset(QCPAxis::AxisType type); - + // property members: + QBrush mBackgroundBrush; + QPixmap mBackgroundPixmap; + QPixmap mScaledBackgroundPixmap; + bool mBackgroundScaled; + Qt::AspectRatioMode mBackgroundScaledMode; + QCPLayoutInset *mInsetLayout; + Qt::Orientations mRangeDrag, mRangeZoom; + QPointer mRangeDragHorzAxis, mRangeDragVertAxis, mRangeZoomHorzAxis, mRangeZoomVertAxis; + double mRangeZoomFactorHorz, mRangeZoomFactorVert; + // non-property members: + QCPRange 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); + // events: + virtual void mousePressEvent(QMouseEvent *event); + virtual void mouseMoveEvent(QMouseEvent *event); + virtual void mouseReleaseEvent(QMouseEvent *event); + virtual void wheelEvent(QWheelEvent *event); + + // non-property methods: + void drawBackground(QCPPainter *painter); + void updateAxesOffset(QCPAxis::AxisType type); + private: - Q_DISABLE_COPY(QCPAxisRect) - - friend class QCustomPlot; + Q_DISABLE_COPY(QCPAxisRect) + + friend class QCustomPlot; }; class QCP_LIB_DECL QCPAbstractLegendItem : public QCPLayoutElement { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QCPLegend* parentLegend READ parentLegend) - Q_PROPERTY(QFont font READ font WRITE setFont) - Q_PROPERTY(QColor textColor READ textColor WRITE setTextColor) - Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont) - Q_PROPERTY(QColor selectedTextColor READ selectedTextColor WRITE setSelectedTextColor) - Q_PROPERTY(bool selectable READ selectable WRITE setSelectable NOTIFY selectionChanged) - Q_PROPERTY(bool selected READ selected WRITE setSelected NOTIFY selectableChanged) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QCPLegend* parentLegend READ parentLegend) + Q_PROPERTY(QFont font READ font WRITE setFont) + Q_PROPERTY(QColor textColor READ textColor WRITE setTextColor) + Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont) + Q_PROPERTY(QColor selectedTextColor READ selectedTextColor WRITE setSelectedTextColor) + Q_PROPERTY(bool selectable READ selectable WRITE setSelectable NOTIFY selectionChanged) + Q_PROPERTY(bool selected READ selected WRITE setSelected NOTIFY selectableChanged) + /// \endcond public: - explicit QCPAbstractLegendItem(QCPLegend *parent); - - // getters: - QCPLegend *parentLegend() const { return mParentLegend; } - QFont font() const { return mFont; } - QColor textColor() const { return mTextColor; } - QFont selectedFont() const { return mSelectedFont; } - QColor selectedTextColor() const { return mSelectedTextColor; } - bool selectable() const { return mSelectable; } - bool selected() const { return mSelected; } - - // setters: - void setFont(const QFont &font); - void setTextColor(const QColor &color); - void setSelectedFont(const QFont &font); - void setSelectedTextColor(const QColor &color); - Q_SLOT void setSelectable(bool selectable); - Q_SLOT void setSelected(bool selected); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; - + explicit QCPAbstractLegendItem(QCPLegend *parent); + + // getters: + QCPLegend *parentLegend() const { + return mParentLegend; + } + QFont font() const { + return mFont; + } + QColor textColor() const { + return mTextColor; + } + QFont selectedFont() const { + return mSelectedFont; + } + QColor selectedTextColor() const { + return mSelectedTextColor; + } + bool selectable() const { + return mSelectable; + } + bool selected() const { + return mSelected; + } + + // setters: + void setFont(const QFont &font); + void setTextColor(const QColor &color); + void setSelectedFont(const QFont &font); + void setSelectedTextColor(const QColor &color); + Q_SLOT void setSelectable(bool selectable); + Q_SLOT void setSelected(bool selected); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = 0) const; + signals: - void selectionChanged(bool selected); - void selectableChanged(bool selectable); - + void selectionChanged(bool selected); + void selectableChanged(bool selectable); + protected: - // property members: - QCPLegend *mParentLegend; - QFont mFont; - QColor mTextColor; - QFont mSelectedFont; - QColor mSelectedTextColor; - 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; - // events: - virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged); - virtual void deselectEvent(bool *selectionStateChanged); - + // property members: + QCPLegend *mParentLegend; + QFont mFont; + QColor mTextColor; + QFont mSelectedFont; + QColor mSelectedTextColor; + 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; + // events: + virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged); + virtual void deselectEvent(bool *selectionStateChanged); + private: - Q_DISABLE_COPY(QCPAbstractLegendItem) - - friend class QCPLegend; + Q_DISABLE_COPY(QCPAbstractLegendItem) + + friend class QCPLegend; }; class QCP_LIB_DECL QCPPlottableLegendItem : public QCPAbstractLegendItem { - Q_OBJECT -public: - QCPPlottableLegendItem(QCPLegend *parent, QCPAbstractPlottable *plottable); - - // getters: - QCPAbstractPlottable *plottable() { return mPlottable; } - + Q_OBJECT +public: QCPPlottableLegendItem(QCPLegend *parent, QCPAbstractPlottable *plottable); + + // getters: + QCPAbstractPlottable *plottable() { + return mPlottable; + } + protected: - // property members: - QCPAbstractPlottable *mPlottable; - - // reimplemented virtual methods: - virtual void draw(QCPPainter *painter); - virtual QSize minimumSizeHint() const; - - // non-virtual methods: - QPen getIconBorderPen() const; - QColor getTextColor() const; - QFont getFont() const; + // property members: + QCPAbstractPlottable *mPlottable; + + // reimplemented virtual methods: + virtual void draw(QCPPainter *painter); + virtual QSize minimumSizeHint() const; + + // non-virtual methods: + QPen getIconBorderPen() const; + QColor getTextColor() const; + QFont getFont() const; }; class QCP_LIB_DECL QCPLegend : public QCPLayoutGrid { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QPen borderPen READ borderPen WRITE setBorderPen) - Q_PROPERTY(QBrush brush READ brush WRITE setBrush) - Q_PROPERTY(QFont font READ font WRITE setFont) - Q_PROPERTY(QColor textColor READ textColor WRITE setTextColor) - Q_PROPERTY(QSize iconSize READ iconSize WRITE setIconSize) - Q_PROPERTY(int iconTextPadding READ iconTextPadding WRITE setIconTextPadding) - Q_PROPERTY(QPen iconBorderPen READ iconBorderPen WRITE setIconBorderPen) - Q_PROPERTY(SelectableParts selectableParts READ selectableParts WRITE setSelectableParts NOTIFY selectionChanged) - Q_PROPERTY(SelectableParts selectedParts READ selectedParts WRITE setSelectedParts NOTIFY selectableChanged) - Q_PROPERTY(QPen selectedBorderPen READ selectedBorderPen WRITE setSelectedBorderPen) - Q_PROPERTY(QPen selectedIconBorderPen READ selectedIconBorderPen WRITE setSelectedIconBorderPen) - Q_PROPERTY(QBrush selectedBrush READ selectedBrush WRITE setSelectedBrush) - Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont) - Q_PROPERTY(QColor selectedTextColor READ selectedTextColor WRITE setSelectedTextColor) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(QPen borderPen READ borderPen WRITE setBorderPen) + Q_PROPERTY(QBrush brush READ brush WRITE setBrush) + Q_PROPERTY(QFont font READ font WRITE setFont) + Q_PROPERTY(QColor textColor READ textColor WRITE setTextColor) + Q_PROPERTY(QSize iconSize READ iconSize WRITE setIconSize) + Q_PROPERTY(int iconTextPadding READ iconTextPadding WRITE setIconTextPadding) + Q_PROPERTY(QPen iconBorderPen READ iconBorderPen WRITE setIconBorderPen) + Q_PROPERTY(SelectableParts selectableParts READ selectableParts WRITE setSelectableParts NOTIFY selectionChanged) + Q_PROPERTY(SelectableParts selectedParts READ selectedParts WRITE setSelectedParts NOTIFY selectableChanged) + Q_PROPERTY(QPen selectedBorderPen READ selectedBorderPen WRITE setSelectedBorderPen) + Q_PROPERTY(QPen selectedIconBorderPen READ selectedIconBorderPen WRITE setSelectedIconBorderPen) + Q_PROPERTY(QBrush selectedBrush READ selectedBrush WRITE setSelectedBrush) + Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont) + Q_PROPERTY(QColor selectedTextColor READ selectedTextColor WRITE setSelectedTextColor) + /// \endcond public: - /*! - Defines the selectable parts of a legend - - \see setSelectedParts, setSelectableParts - */ - 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_DECLARE_FLAGS(SelectableParts, SelectablePart) - - explicit QCPLegend(); - virtual ~QCPLegend(); - - // getters: - QPen borderPen() const { return mBorderPen; } - QBrush brush() const { return mBrush; } - QFont font() const { return mFont; } - QColor textColor() const { return mTextColor; } - QSize iconSize() const { return mIconSize; } - int iconTextPadding() const { return mIconTextPadding; } - QPen iconBorderPen() const { return mIconBorderPen; } - SelectableParts selectableParts() const { return mSelectableParts; } - SelectableParts selectedParts() const; - QPen selectedBorderPen() const { return mSelectedBorderPen; } - QPen selectedIconBorderPen() const { return mSelectedIconBorderPen; } - QBrush selectedBrush() const { return mSelectedBrush; } - QFont selectedFont() const { return mSelectedFont; } - QColor selectedTextColor() const { return mSelectedTextColor; } - - // setters: - void setBorderPen(const QPen &pen); - void setBrush(const QBrush &brush); - void setFont(const QFont &font); - void setTextColor(const QColor &color); - void setIconSize(const QSize &size); - void setIconSize(int width, int height); - void setIconTextPadding(int padding); - void setIconBorderPen(const QPen &pen); - Q_SLOT void setSelectableParts(const SelectableParts &selectableParts); - Q_SLOT void setSelectedParts(const SelectableParts &selectedParts); - void setSelectedBorderPen(const QPen &pen); - void setSelectedIconBorderPen(const QPen &pen); - void setSelectedBrush(const QBrush &brush); - void setSelectedFont(const QFont &font); - void setSelectedTextColor(const QColor &color); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; - - // non-virtual methods: - QCPAbstractLegendItem *item(int index) const; - QCPPlottableLegendItem *itemWithPlottable(const QCPAbstractPlottable *plottable) const; - int itemCount() const; - bool hasItem(QCPAbstractLegendItem *item) const; - bool hasItemWithPlottable(const QCPAbstractPlottable *plottable) const; - bool addItem(QCPAbstractLegendItem *item); - bool removeItem(int index); - bool removeItem(QCPAbstractLegendItem *item); - void clearItems(); - QList selectedItems() const; - + /*! + Defines the selectable parts of a legend + + \see setSelectedParts, setSelectableParts + */ + 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_DECLARE_FLAGS(SelectableParts, SelectablePart) + + explicit QCPLegend(); + virtual ~QCPLegend(); + + // getters: + QPen borderPen() const { + return mBorderPen; + } + QBrush brush() const { + return mBrush; + } + QFont font() const { + return mFont; + } + QColor textColor() const { + return mTextColor; + } + QSize iconSize() const { + return mIconSize; + } + int iconTextPadding() const { + return mIconTextPadding; + } + QPen iconBorderPen() const { + return mIconBorderPen; + } + SelectableParts selectableParts() const { + return mSelectableParts; + } + SelectableParts selectedParts() const; + QPen selectedBorderPen() const { + return mSelectedBorderPen; + } + QPen selectedIconBorderPen() const { + return mSelectedIconBorderPen; + } + QBrush selectedBrush() const { + return mSelectedBrush; + } + QFont selectedFont() const { + return mSelectedFont; + } + QColor selectedTextColor() const { + return mSelectedTextColor; + } + + // setters: + void setBorderPen(const QPen &pen); + void setBrush(const QBrush &brush); + void setFont(const QFont &font); + void setTextColor(const QColor &color); + void setIconSize(const QSize &size); + void setIconSize(int width, int height); + void setIconTextPadding(int padding); + void setIconBorderPen(const QPen &pen); + Q_SLOT void setSelectableParts(const SelectableParts &selectableParts); + Q_SLOT void setSelectedParts(const SelectableParts &selectedParts); + void setSelectedBorderPen(const QPen &pen); + void setSelectedIconBorderPen(const QPen &pen); + void setSelectedBrush(const QBrush &brush); + void setSelectedFont(const QFont &font); + void setSelectedTextColor(const QColor &color); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = 0) const; + + // non-virtual methods: + QCPAbstractLegendItem *item(int index) const; + QCPPlottableLegendItem *itemWithPlottable(const QCPAbstractPlottable *plottable) const; + int itemCount() const; + bool hasItem(QCPAbstractLegendItem *item) const; + bool hasItemWithPlottable(const QCPAbstractPlottable *plottable) const; + bool addItem(QCPAbstractLegendItem *item); + bool removeItem(int index); + bool removeItem(QCPAbstractLegendItem *item); + void clearItems(); + QList selectedItems() const; + signals: - void selectionChanged(QCPLegend::SelectableParts parts); - void selectableChanged(QCPLegend::SelectableParts parts); - + void selectionChanged(QCPLegend::SelectableParts parts); + void selectableChanged(QCPLegend::SelectableParts parts); + protected: - // property members: - QPen mBorderPen, mIconBorderPen; - QBrush mBrush; - QFont mFont; - QColor mTextColor; - QSize mIconSize; - int mIconTextPadding; - SelectableParts mSelectedParts, mSelectableParts; - QPen mSelectedBorderPen, mSelectedIconBorderPen; - QBrush mSelectedBrush; - QFont mSelectedFont; - 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); - // events: - virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged); - virtual void deselectEvent(bool *selectionStateChanged); - - // non-virtual methods: - QPen getBorderPen() const; - QBrush getBrush() const; - + // property members: + QPen mBorderPen, mIconBorderPen; + QBrush mBrush; + QFont mFont; + QColor mTextColor; + QSize mIconSize; + int mIconTextPadding; + SelectableParts mSelectedParts, mSelectableParts; + QPen mSelectedBorderPen, mSelectedIconBorderPen; + QBrush mSelectedBrush; + QFont mSelectedFont; + 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); + // events: + virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged); + virtual void deselectEvent(bool *selectionStateChanged); + + // non-virtual methods: + QPen getBorderPen() const; + QBrush getBrush() const; + private: - Q_DISABLE_COPY(QCPLegend) - - friend class QCustomPlot; - friend class QCPAbstractLegendItem; + Q_DISABLE_COPY(QCPLegend) + + friend class QCustomPlot; + friend class QCPAbstractLegendItem; }; Q_DECLARE_OPERATORS_FOR_FLAGS(QCPLegend::SelectableParts) Q_DECLARE_METATYPE(QCPLegend::SelectablePart) @@ -2292,171 +2685,195 @@ Q_DECLARE_METATYPE(QCPLegend::SelectablePart) class QCP_LIB_DECL QCPPlotTitle : public QCPLayoutElement { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QString text READ text WRITE setText) - Q_PROPERTY(QFont font READ font WRITE setFont) - Q_PROPERTY(QColor textColor READ textColor WRITE setTextColor) - Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont) - Q_PROPERTY(QColor selectedTextColor READ selectedTextColor WRITE setSelectedTextColor) - Q_PROPERTY(bool selectable READ selectable WRITE setSelectable NOTIFY selectableChanged) - Q_PROPERTY(bool selected READ selected WRITE setSelected NOTIFY selectionChanged) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QString text READ text WRITE setText) + Q_PROPERTY(QFont font READ font WRITE setFont) + Q_PROPERTY(QColor textColor READ textColor WRITE setTextColor) + Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont) + Q_PROPERTY(QColor selectedTextColor READ selectedTextColor WRITE setSelectedTextColor) + Q_PROPERTY(bool selectable READ selectable WRITE setSelectable NOTIFY selectableChanged) + Q_PROPERTY(bool selected READ selected WRITE setSelected NOTIFY selectionChanged) + /// \endcond public: - explicit QCPPlotTitle(QCustomPlot *parentPlot); - explicit QCPPlotTitle(QCustomPlot *parentPlot, const QString &text); - - // getters: - QString text() const { return mText; } - QFont font() const { return mFont; } - QColor textColor() const { return mTextColor; } - QFont selectedFont() const { return mSelectedFont; } - QColor selectedTextColor() const { return mSelectedTextColor; } - bool selectable() const { return mSelectable; } - bool selected() const { return mSelected; } - - // setters: - void setText(const QString &text); - void setFont(const QFont &font); - void setTextColor(const QColor &color); - void setSelectedFont(const QFont &font); - void setSelectedTextColor(const QColor &color); - Q_SLOT void setSelectable(bool selectable); - Q_SLOT void setSelected(bool selected); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; - + explicit QCPPlotTitle(QCustomPlot *parentPlot); + explicit QCPPlotTitle(QCustomPlot *parentPlot, const QString &text); + + // getters: + QString text() const { + return mText; + } + QFont font() const { + return mFont; + } + QColor textColor() const { + return mTextColor; + } + QFont selectedFont() const { + return mSelectedFont; + } + QColor selectedTextColor() const { + return mSelectedTextColor; + } + bool selectable() const { + return mSelectable; + } + bool selected() const { + return mSelected; + } + + // setters: + void setText(const QString &text); + void setFont(const QFont &font); + void setTextColor(const QColor &color); + void setSelectedFont(const QFont &font); + void setSelectedTextColor(const QColor &color); + Q_SLOT void setSelectable(bool selectable); + Q_SLOT void setSelected(bool selected); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = 0) const; + signals: - void selectionChanged(bool selected); - void selectableChanged(bool selectable); - + void selectionChanged(bool selected); + void selectableChanged(bool selectable); + protected: - // property members: - QString mText; - QFont mFont; - QColor mTextColor; - QFont mSelectedFont; - QColor mSelectedTextColor; - QRect mTextBoundingRect; - 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; - // events: - virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged); - virtual void deselectEvent(bool *selectionStateChanged); - - // non-virtual methods: - QFont mainFont() const; - QColor mainTextColor() const; - + // property members: + QString mText; + QFont mFont; + QColor mTextColor; + QFont mSelectedFont; + QColor mSelectedTextColor; + QRect mTextBoundingRect; + 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; + // events: + virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged); + virtual void deselectEvent(bool *selectionStateChanged); + + // non-virtual methods: + QFont mainFont() const; + QColor mainTextColor() const; + private: - Q_DISABLE_COPY(QCPPlotTitle) + Q_DISABLE_COPY(QCPPlotTitle) }; class QCPColorScaleAxisRectPrivate : public QCPAxisRect { - Q_OBJECT + Q_OBJECT public: - explicit QCPColorScaleAxisRectPrivate(QCPColorScale *parentColorScale); + explicit QCPColorScaleAxisRectPrivate(QCPColorScale *parentColorScale); protected: - QCPColorScale *mParentColorScale; - QImage mGradientImage; - bool mGradientImageInvalidated; - // re-using some methods of QCPAxisRect to make them available to friend class QCPColorScale - using QCPAxisRect::calculateAutoMargin; - using QCPAxisRect::mousePressEvent; - using QCPAxisRect::mouseMoveEvent; - using QCPAxisRect::mouseReleaseEvent; - using QCPAxisRect::wheelEvent; - using QCPAxisRect::update; - virtual void draw(QCPPainter *painter); - void updateGradientImage(); - Q_SLOT void axisSelectionChanged(QCPAxis::SelectableParts selectedParts); - Q_SLOT void axisSelectableChanged(QCPAxis::SelectableParts selectableParts); - friend class QCPColorScale; + QCPColorScale *mParentColorScale; + QImage mGradientImage; + bool mGradientImageInvalidated; + // re-using some methods of QCPAxisRect to make them available to friend class QCPColorScale + using QCPAxisRect::calculateAutoMargin; + using QCPAxisRect::mousePressEvent; + using QCPAxisRect::mouseMoveEvent; + using QCPAxisRect::mouseReleaseEvent; + using QCPAxisRect::wheelEvent; + using QCPAxisRect::update; + virtual void draw(QCPPainter *painter); + void updateGradientImage(); + Q_SLOT void axisSelectionChanged(QCPAxis::SelectableParts selectedParts); + Q_SLOT void axisSelectableChanged(QCPAxis::SelectableParts selectableParts); + friend class QCPColorScale; }; class QCP_LIB_DECL QCPColorScale : public QCPLayoutElement { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QCPAxis::AxisType type READ type WRITE setType) - Q_PROPERTY(QCPRange dataRange READ dataRange WRITE setDataRange NOTIFY dataRangeChanged) - Q_PROPERTY(QCPAxis::ScaleType dataScaleType READ dataScaleType WRITE setDataScaleType NOTIFY dataScaleTypeChanged) - Q_PROPERTY(QCPColorGradient gradient READ gradient WRITE setGradient NOTIFY gradientChanged) - Q_PROPERTY(QString label READ label WRITE setLabel) - Q_PROPERTY(int barWidth READ barWidth WRITE setBarWidth) - Q_PROPERTY(bool rangeDrag READ rangeDrag WRITE setRangeDrag) - Q_PROPERTY(bool rangeZoom READ rangeZoom WRITE setRangeZoom) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QCPAxis::AxisType type READ type WRITE setType) + Q_PROPERTY(QCPRange dataRange READ dataRange WRITE setDataRange NOTIFY dataRangeChanged) + Q_PROPERTY(QCPAxis::ScaleType dataScaleType READ dataScaleType WRITE setDataScaleType NOTIFY dataScaleTypeChanged) + Q_PROPERTY(QCPColorGradient gradient READ gradient WRITE setGradient NOTIFY gradientChanged) + Q_PROPERTY(QString label READ label WRITE setLabel) + Q_PROPERTY(int barWidth READ barWidth WRITE setBarWidth) + Q_PROPERTY(bool rangeDrag READ rangeDrag WRITE setRangeDrag) + Q_PROPERTY(bool rangeZoom READ rangeZoom WRITE setRangeZoom) + /// \endcond public: - explicit QCPColorScale(QCustomPlot *parentPlot); - virtual ~QCPColorScale(); - - // getters: - QCPAxis *axis() const { return mColorAxis.data(); } - QCPAxis::AxisType type() const { return mType; } - QCPRange dataRange() const { return mDataRange; } - QCPAxis::ScaleType dataScaleType() const { return mDataScaleType; } - QCPColorGradient gradient() const { return mGradient; } - QString label() const; - int barWidth () const { return mBarWidth; } - bool rangeDrag() const; - bool rangeZoom() const; - - // setters: - void setType(QCPAxis::AxisType type); - Q_SLOT void setDataRange(const QCPRange &dataRange); - Q_SLOT void setDataScaleType(QCPAxis::ScaleType scaleType); - Q_SLOT void setGradient(const QCPColorGradient &gradient); - void setLabel(const QString &str); - void setBarWidth(int width); - void setRangeDrag(bool enabled); - void setRangeZoom(bool enabled); - - // non-property methods: - QList colorMaps() const; - void rescaleDataRange(bool onlyVisibleMaps); - - // reimplemented virtual methods: - virtual void update(UpdatePhase phase); - + explicit QCPColorScale(QCustomPlot *parentPlot); + virtual ~QCPColorScale(); + + // getters: + QCPAxis *axis() const { + return mColorAxis.data(); + } + QCPAxis::AxisType type() const { + return mType; + } + QCPRange dataRange() const { + return mDataRange; + } + QCPAxis::ScaleType dataScaleType() const { + return mDataScaleType; + } + QCPColorGradient gradient() const { + return mGradient; + } + QString label() const; + int barWidth() const { + return mBarWidth; + } + bool rangeDrag() const; + bool rangeZoom() const; + + // setters: + void setType(QCPAxis::AxisType type); + Q_SLOT void setDataRange(const QCPRange &dataRange); + Q_SLOT void setDataScaleType(QCPAxis::ScaleType scaleType); + Q_SLOT void setGradient(const QCPColorGradient &gradient); + void setLabel(const QString &str); + void setBarWidth(int width); + void setRangeDrag(bool enabled); + void setRangeZoom(bool enabled); + + // non-property methods: + QList colorMaps() const; + void rescaleDataRange(bool onlyVisibleMaps); + + // reimplemented virtual methods: + virtual void update(UpdatePhase phase); + signals: - void dataRangeChanged(QCPRange newRange); - void dataScaleTypeChanged(QCPAxis::ScaleType scaleType); - void gradientChanged(QCPColorGradient newGradient); + void dataRangeChanged(QCPRange newRange); + void dataScaleTypeChanged(QCPAxis::ScaleType scaleType); + void gradientChanged(QCPColorGradient newGradient); protected: - // property members: - QCPAxis::AxisType mType; - QCPRange mDataRange; - QCPAxis::ScaleType mDataScaleType; - QCPColorGradient mGradient; - int mBarWidth; - - // non-property members: - QPointer mAxisRect; - QPointer mColorAxis; - - // reimplemented virtual methods: - virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const; - // events: - virtual void mousePressEvent(QMouseEvent *event); - virtual void mouseMoveEvent(QMouseEvent *event); - virtual void mouseReleaseEvent(QMouseEvent *event); - virtual void wheelEvent(QWheelEvent *event); - + // property members: + QCPAxis::AxisType mType; + QCPRange mDataRange; + QCPAxis::ScaleType mDataScaleType; + QCPColorGradient mGradient; + int mBarWidth; + + // non-property members: + QPointer mAxisRect; + QPointer mColorAxis; + + // reimplemented virtual methods: + virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const; + // events: + virtual void mousePressEvent(QMouseEvent *event); + virtual void mouseMoveEvent(QMouseEvent *event); + virtual void mouseReleaseEvent(QMouseEvent *event); + virtual void wheelEvent(QWheelEvent *event); + private: - Q_DISABLE_COPY(QCPColorScale) - - friend class QCPColorScaleAxisRectPrivate; + Q_DISABLE_COPY(QCPColorScale) + + friend class QCPColorScaleAxisRectPrivate; }; @@ -2467,18 +2884,18 @@ private: class QCP_LIB_DECL QCPData { public: - QCPData(); - QCPData(double key, double value); - double key, value; - double keyErrorPlus, keyErrorMinus; - double valueErrorPlus, valueErrorMinus; + 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. - + This is the container in which QCPGraph holds its data. \see QCPData, QCPGraph::setData */ @@ -2489,145 +2906,168 @@ typedef QMutableMapIterator QCPDataMutableMapIterator; class QCP_LIB_DECL QCPGraph : public QCPAbstractPlottable { - 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(QCPGraph* channelFillGraph READ channelFillGraph WRITE setChannelFillGraph) - Q_PROPERTY(bool adaptiveSampling READ adaptiveSampling WRITE setAdaptiveSampling) - /// \endcond + 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(QCPGraph *channelFillGraph READ channelFillGraph WRITE setChannelFillGraph) + Q_PROPERTY(bool adaptiveSampling READ adaptiveSampling WRITE setAdaptiveSampling) + /// \endcond public: - /*! - Defines how the graph's line is represented visually in the plot. The line is drawn with the - current pen of the graph (\ref setPen). - \see setLineStyle - */ - enum LineStyle { lsNone ///< data points are not connected with any lines (e.g. data only represented - ///< with symbols according to the scatter style, see \ref setScatterStyle) - ,lsLine ///< data points are connected by a straight line - ,lsStepLeft ///< line is drawn as steps where the step height is the value of the left data point - ,lsStepRight ///< line is drawn as steps where the step height is the value of the right data point - ,lsStepCenter ///< line is drawn as steps where the step is in between two data points - ,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; } - 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; } - 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 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 setChannelFillGraph(QCPGraph *targetGraph); - void setAdaptiveSampling(bool enabled); - - // non-property methods: - void addData(const QCPDataMap &dataMap); - void addData(const QCPData &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; - 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 - + /*! + Defines how the graph's line is represented visually in the plot. The line is drawn with the + current pen of the graph (\ref setPen). + \see setLineStyle + */ + enum LineStyle { lsNone ///< data points are not connected with any lines (e.g. data only represented + ///< with symbols according to the scatter style, see \ref setScatterStyle) + , lsLine ///< data points are connected by a straight line + , lsStepLeft ///< line is drawn as steps where the step height is the value of the left data point + , lsStepRight ///< line is drawn as steps where the step height is the value of the right data point + , lsStepCenter ///< line is drawn as steps where the step is in between two data points + , 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; + } + 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; + } + 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 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 setChannelFillGraph(QCPGraph *targetGraph); + void setAdaptiveSampling(bool enabled); + + // non-property methods: + void addData(const QCPDataMap &dataMap); + void addData(const QCPData &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; + 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 + protected: - // property members: - QCPDataMap *mData; - QPen mErrorPen; - LineStyle mLineStyle; - QCPScatterStyle mScatterStyle; - ErrorType mErrorType; - double mErrorBarSize; - bool mErrorBarSkipSymbol; - 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 - - // 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; - - // 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; - QPointF lowerFillBasePoint(double lowerKey) const; - QPointF upperFillBasePoint(double upperKey) const; - const QPolygonF getChannelFillPolygon(const QVector *lineData) 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; - - friend class QCustomPlot; - friend class QCPLegend; + // property members: + QCPDataMap *mData; + QPen mErrorPen; + LineStyle mLineStyle; + QCPScatterStyle mScatterStyle; + ErrorType mErrorType; + double mErrorBarSize; + bool mErrorBarSkipSymbol; + 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 + + int smooth; +public: + void setSmooth(int smooth); + +protected: + // 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; + + // 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; + QPointF lowerFillBasePoint(double lowerKey) const; + QPointF upperFillBasePoint(double upperKey) const; + const QPolygonF getChannelFillPolygon(const QVector *lineData) 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; + + friend class QCustomPlot; + friend class QCPLegend; }; @@ -2638,16 +3078,16 @@ protected: class QCP_LIB_DECL QCPCurveData { public: - QCPCurveData(); - QCPCurveData(double t, double key, double value); - double t, key, value; + QCPCurveData(); + QCPCurveData(double t, double key, double value); + double t, key, value; }; Q_DECLARE_TYPEINFO(QCPCurveData, Q_MOVABLE_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. - + This is the container in which QCPCurve holds its data. \see QCPCurveData, QCPCurve::setData */ @@ -2659,77 +3099,83 @@ typedef QMutableMapIterator QCPCurveDataMutableMapIterator class QCP_LIB_DECL QCPCurve : public QCPAbstractPlottable { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QCPScatterStyle scatterStyle READ scatterStyle WRITE setScatterStyle) - Q_PROPERTY(LineStyle lineStyle READ lineStyle WRITE setLineStyle) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(QCPScatterStyle scatterStyle READ scatterStyle WRITE setScatterStyle) + Q_PROPERTY(LineStyle lineStyle READ lineStyle WRITE setLineStyle) + /// \endcond public: - /*! - Defines how the curve's line is represented visually in the plot. The line is drawn with the - current pen of the curve (\ref setPen). - \see setLineStyle - */ - enum LineStyle { lsNone ///< No line is drawn between data points (e.g. only scatters) - ,lsLine ///< Data points are connected with a straight line - }; - explicit QCPCurve(QCPAxis *keyAxis, QCPAxis *valueAxis); - virtual ~QCPCurve(); - - // getters: - QCPCurveDataMap *data() const { return mData; } - QCPScatterStyle scatterStyle() const { return mScatterStyle; } - 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 setScatterStyle(const QCPScatterStyle &style); - void setLineStyle(LineStyle style); - - // non-property methods: - void addData(const QCPCurveDataMap &dataMap); - void addData(const QCPCurveData &data); - 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; - + /*! + Defines how the curve's line is represented visually in the plot. The line is drawn with the + current pen of the curve (\ref setPen). + \see setLineStyle + */ + enum LineStyle { lsNone ///< No line is drawn between data points (e.g. only scatters) + , lsLine ///< Data points are connected with a straight line + }; + explicit QCPCurve(QCPAxis *keyAxis, QCPAxis *valueAxis); + virtual ~QCPCurve(); + + // getters: + QCPCurveDataMap *data() const { + return mData; + } + QCPScatterStyle scatterStyle() const { + return mScatterStyle; + } + 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 setScatterStyle(const QCPScatterStyle &style); + void setLineStyle(LineStyle style); + + // non-property methods: + void addData(const QCPCurveDataMap &dataMap); + void addData(const QCPCurveData &data); + 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; + protected: - // property members: - QCPCurveDataMap *mData; - QCPScatterStyle mScatterStyle; - 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; - - // introduced virtual methods: - virtual void drawScatterPlot(QCPPainter *painter, const QVector *pointData) 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; - 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; - - friend class QCustomPlot; - friend class QCPLegend; + // property members: + QCPCurveDataMap *mData; + QCPScatterStyle mScatterStyle; + 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; + + // introduced virtual methods: + virtual void drawScatterPlot(QCPPainter *painter, const QVector *pointData) 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; + 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; + + friend class QCustomPlot; + friend class QCPLegend; }; @@ -2739,79 +3185,91 @@ protected: class QCP_LIB_DECL QCPBarsGroup : public QObject { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(SpacingType spacingType READ spacingType WRITE setSpacingType) - Q_PROPERTY(double spacing READ spacing WRITE setSpacing) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(SpacingType spacingType READ spacingType WRITE setSpacingType) + Q_PROPERTY(double spacing READ spacing WRITE setSpacing) + /// \endcond public: - /*! - Defines the ways the spacing between bars in the group can be specified. Thus it defines what - the number passed to \ref setSpacing actually means. - - \see setSpacingType, setSpacing - */ - 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 - }; - QCPBarsGroup(QCustomPlot *parentPlot); - ~QCPBarsGroup(); - - // getters: - SpacingType spacingType() const { return mSpacingType; } - double spacing() const { return mSpacing; } - - // setters: - void setSpacingType(SpacingType spacingType); - void setSpacing(double spacing); - - // non-virtual methods: - QList bars() const { return mBars; } - QCPBars* bars(int index) const; - int size() const { return mBars.size(); } - bool isEmpty() const { return mBars.isEmpty(); } - void clear(); - bool contains(QCPBars *bars) const { return mBars.contains(bars); } - void append(QCPBars *bars); - void insert(int i, QCPBars *bars); - void remove(QCPBars *bars); - + /*! + Defines the ways the spacing between bars in the group can be specified. Thus it defines what + the number passed to \ref setSpacing actually means. + + \see setSpacingType, setSpacing + */ + 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 + }; + QCPBarsGroup(QCustomPlot *parentPlot); + ~QCPBarsGroup(); + + // getters: + SpacingType spacingType() const { + return mSpacingType; + } + double spacing() const { + return mSpacing; + } + + // setters: + void setSpacingType(SpacingType spacingType); + void setSpacing(double spacing); + + // non-virtual methods: + QList bars() const { + return mBars; + } + QCPBars *bars(int index) const; + int size() const { + return mBars.size(); + } + bool isEmpty() const { + return mBars.isEmpty(); + } + void clear(); + bool contains(QCPBars *bars) const { + return mBars.contains(bars); + } + void append(QCPBars *bars); + void insert(int i, QCPBars *bars); + void remove(QCPBars *bars); + protected: - // non-property members: - QCustomPlot *mParentPlot; - SpacingType mSpacingType; - double mSpacing; - QList mBars; - - // non-virtual methods: - void registerBars(QCPBars *bars); - void unregisterBars(QCPBars *bars); - - // virtual methods: - double keyPixelOffset(const QCPBars *bars, double keyCoord); - double getPixelSpacing(const QCPBars *bars, double keyCoord); - + // non-property members: + QCustomPlot *mParentPlot; + SpacingType mSpacingType; + double mSpacing; + QList mBars; + + // non-virtual methods: + void registerBars(QCPBars *bars); + void unregisterBars(QCPBars *bars); + + // virtual methods: + double keyPixelOffset(const QCPBars *bars, double keyCoord); + double getPixelSpacing(const QCPBars *bars, double keyCoord); + private: - Q_DISABLE_COPY(QCPBarsGroup) - - friend class QCPBars; + Q_DISABLE_COPY(QCPBarsGroup) + + friend class QCPBars; }; class QCP_LIB_DECL QCPBarData { public: - QCPBarData(); - QCPBarData(double key, double value); - double key, value; + QCPBarData(); + QCPBarData(double key, double value); + double key, value; }; Q_DECLARE_TYPEINFO(QCPBarData, Q_MOVABLE_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. - + This is the container in which QCPBars holds its data. \see QCPBarData, QCPBars::setData */ @@ -2822,89 +3280,103 @@ typedef QMutableMapIterator QCPBarDataMutableMapIterator; class QCP_LIB_DECL QCPBars : public QCPAbstractPlottable { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(double width READ width WRITE setWidth) - 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(QCPBars* barBelow READ barBelow) - Q_PROPERTY(QCPBars* barAbove READ barAbove) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(double width READ width WRITE setWidth) + 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(QCPBars *barBelow READ barBelow) + Q_PROPERTY(QCPBars *barAbove READ barAbove) + /// \endcond public: - /*! - Defines the ways the width of the bar can be specified. Thus it defines what the number passed - to \ref setWidth actually means. - - \see setWidthType, setWidth - */ - enum WidthType { wtAbsolute ///< Bar width is in absolute pixels - ,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) - - explicit QCPBars(QCPAxis *keyAxis, QCPAxis *valueAxis); - virtual ~QCPBars(); - - // getters: - double width() const { return mWidth; } - WidthType widthType() const { return mWidthType; } - QCPBarsGroup *barsGroup() const { return mBarsGroup; } - double baseValue() const { return mBaseValue; } - QCPBars *barBelow() const { return mBarBelow.data(); } - QCPBars *barAbove() const { return mBarAbove.data(); } - QCPBarDataMap *data() const { return mData; } - - // setters: - 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); - - // non-property methods: - 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; - + /*! + Defines the ways the width of the bar can be specified. Thus it defines what the number passed + to \ref setWidth actually means. + + \see setWidthType, setWidth + */ + enum WidthType { wtAbsolute ///< Bar width is in absolute pixels + , 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) + + explicit QCPBars(QCPAxis *keyAxis, QCPAxis *valueAxis); + virtual ~QCPBars(); + + // getters: + double width() const { + return mWidth; + } + WidthType widthType() const { + return mWidthType; + } + QCPBarsGroup *barsGroup() const { + return mBarsGroup; + } + double baseValue() const { + return mBaseValue; + } + QCPBars *barBelow() const { + return mBarBelow.data(); + } + QCPBars *barAbove() const { + return mBarAbove.data(); + } + QCPBarDataMap *data() const { + return mData; + } + + // setters: + 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); + + // non-property methods: + 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; + protected: - // property members: - QCPBarDataMap *mData; - double mWidth; - WidthType mWidthType; - QCPBarsGroup *mBarsGroup; - double mBaseValue; - 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; - - // non-virtual methods: - void getVisibleDataBounds(QCPBarDataMap::const_iterator &lower, QCPBarDataMap::const_iterator &upperEnd) const; - QPolygonF getBarPolygon(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); - - friend class QCustomPlot; - friend class QCPLegend; - friend class QCPBarsGroup; + // property members: + QCPBarDataMap *mData; + double mWidth; + WidthType mWidthType; + QCPBarsGroup *mBarsGroup; + double mBaseValue; + 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; + + // non-virtual methods: + void getVisibleDataBounds(QCPBarDataMap::const_iterator &lower, QCPBarDataMap::const_iterator &upperEnd) const; + QPolygonF getBarPolygon(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); + + friend class QCustomPlot; + friend class QCPLegend; + friend class QCPBarsGroup; }; @@ -2914,206 +3386,256 @@ protected: class QCP_LIB_DECL QCPStatisticalBox : public QCPAbstractPlottable { - 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(QPen medianPen READ medianPen WRITE setMedianPen) - Q_PROPERTY(QCPScatterStyle outlierStyle READ outlierStyle WRITE setOutlierStyle) - /// \endcond + 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(QPen medianPen READ medianPen WRITE setMedianPen) + Q_PROPERTY(QCPScatterStyle outlierStyle READ outlierStyle WRITE setOutlierStyle) + /// \endcond 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; } - double width() const { return mWidth; } - double whiskerWidth() const { return mWhiskerWidth; } - QPen whiskerPen() const { return mWhiskerPen; } - QPen whiskerBarPen() const { return mWhiskerBarPen; } - QPen medianPen() const { return mMedianPen; } - QCPScatterStyle outlierStyle() const { return mOutlierStyle; } + 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; + } + double width() const { + return mWidth; + } + double whiskerWidth() const { + return mWhiskerWidth; + } + QPen whiskerPen() const { + return mWhiskerPen; + } + QPen whiskerBarPen() const { + return mWhiskerBarPen; + } + 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 setWidth(double width); + void setWhiskerWidth(double width); + void setWhiskerPen(const QPen &pen); + void setWhiskerBarPen(const QPen &pen); + 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; - // 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 setWidth(double width); - void setWhiskerWidth(double width); - void setWhiskerPen(const QPen &pen); - void setWhiskerBarPen(const QPen &pen); - 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; - protected: - // property members: - QVector mOutliers; - double mKey, mMinimum, mLowerQuartile, mMedian, mUpperQuartile, mMaximum; - double mWidth; - double mWhiskerWidth; - QPen mWhiskerPen, mWhiskerBarPen, 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; - - // 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; - - friend class QCustomPlot; - friend class QCPLegend; + // property members: + QVector mOutliers; + double mKey, mMinimum, mLowerQuartile, mMedian, mUpperQuartile, mMaximum; + double mWidth; + double mWhiskerWidth; + QPen mWhiskerPen, mWhiskerBarPen, 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; + + // 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; + + friend class QCustomPlot; + friend class QCPLegend; }; class QCP_LIB_DECL QCPColorMapData { public: - QCPColorMapData(int keySize, int valueSize, const QCPRange &keyRange, const QCPRange &valueRange); - ~QCPColorMapData(); - QCPColorMapData(const QCPColorMapData &other); - QCPColorMapData &operator=(const QCPColorMapData &other); - - // getters: - int keySize() const { return mKeySize; } - int valueSize() const { return mValueSize; } - QCPRange keyRange() const { return mKeyRange; } - QCPRange valueRange() const { return mValueRange; } - QCPRange dataBounds() const { return mDataBounds; } - double data(double key, double value); - double cell(int keyIndex, int valueIndex); - - // setters: - void setSize(int keySize, int valueSize); - void setKeySize(int keySize); - void setValueSize(int valueSize); - void setRange(const QCPRange &keyRange, const QCPRange &valueRange); - void setKeyRange(const QCPRange &keyRange); - void setValueRange(const QCPRange &valueRange); - void setData(double key, double value, double z); - void setCell(int keyIndex, int valueIndex, double z); - - // non-property methods: - void recalculateDataBounds(); - void clear(); - void fill(double z); - 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; - + QCPColorMapData(int keySize, int valueSize, const QCPRange &keyRange, const QCPRange &valueRange); + ~QCPColorMapData(); + QCPColorMapData(const QCPColorMapData &other); + QCPColorMapData &operator=(const QCPColorMapData &other); + + // getters: + int keySize() const { + return mKeySize; + } + int valueSize() const { + return mValueSize; + } + QCPRange keyRange() const { + return mKeyRange; + } + QCPRange valueRange() const { + return mValueRange; + } + QCPRange dataBounds() const { + return mDataBounds; + } + double data(double key, double value); + double cell(int keyIndex, int valueIndex); + + // setters: + void setSize(int keySize, int valueSize); + void setKeySize(int keySize); + void setValueSize(int valueSize); + void setRange(const QCPRange &keyRange, const QCPRange &valueRange); + void setKeyRange(const QCPRange &keyRange); + void setValueRange(const QCPRange &valueRange); + void setData(double key, double value, double z); + void setCell(int keyIndex, int valueIndex, double z); + + // non-property methods: + void recalculateDataBounds(); + void clear(); + void fill(double z); + 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; + protected: - // property members: - int mKeySize, mValueSize; - QCPRange mKeyRange, mValueRange; - bool mIsEmpty; - // non-property members: - double *mData; - QCPRange mDataBounds; - bool mDataModified; - - friend class QCPColorMap; + // property members: + int mKeySize, mValueSize; + QCPRange mKeyRange, mValueRange; + bool mIsEmpty; + // non-property members: + double *mData; + QCPRange mDataBounds; + bool mDataModified; + + friend class QCPColorMap; }; class QCP_LIB_DECL QCPColorMap : public QCPAbstractPlottable { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QCPRange dataRange READ dataRange WRITE setDataRange NOTIFY dataRangeChanged) - Q_PROPERTY(QCPAxis::ScaleType dataScaleType READ dataScaleType WRITE setDataScaleType NOTIFY dataScaleTypeChanged) - Q_PROPERTY(QCPColorGradient gradient READ gradient WRITE setGradient NOTIFY gradientChanged) - Q_PROPERTY(bool interpolate READ interpolate WRITE setInterpolate) - Q_PROPERTY(bool tightBoundary READ tightBoundary WRITE setTightBoundary) - Q_PROPERTY(QCPColorScale* colorScale READ colorScale WRITE setColorScale) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QCPRange dataRange READ dataRange WRITE setDataRange NOTIFY dataRangeChanged) + Q_PROPERTY(QCPAxis::ScaleType dataScaleType READ dataScaleType WRITE setDataScaleType NOTIFY dataScaleTypeChanged) + Q_PROPERTY(QCPColorGradient gradient READ gradient WRITE setGradient NOTIFY gradientChanged) + Q_PROPERTY(bool interpolate READ interpolate WRITE setInterpolate) + Q_PROPERTY(bool tightBoundary READ tightBoundary WRITE setTightBoundary) + Q_PROPERTY(QCPColorScale *colorScale READ colorScale WRITE setColorScale) + /// \endcond public: - explicit QCPColorMap(QCPAxis *keyAxis, QCPAxis *valueAxis); - virtual ~QCPColorMap(); - - // getters: - QCPColorMapData *data() const { return mMapData; } - QCPRange dataRange() const { return mDataRange; } - QCPAxis::ScaleType dataScaleType() const { return mDataScaleType; } - bool interpolate() const { return mInterpolate; } - bool tightBoundary() const { return mTightBoundary; } - QCPColorGradient gradient() const { return mGradient; } - QCPColorScale *colorScale() const { return mColorScale.data(); } - - // setters: - void setData(QCPColorMapData *data, bool copy=false); - Q_SLOT void setDataRange(const QCPRange &dataRange); - Q_SLOT void setDataScaleType(QCPAxis::ScaleType scaleType); - Q_SLOT void setGradient(const QCPColorGradient &gradient); - void setInterpolate(bool enabled); - void setTightBoundary(bool enabled); - void setColorScale(QCPColorScale *colorScale); - - // non-property methods: - void rescaleDataRange(bool recalculateDataBounds=false); - 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; - + explicit QCPColorMap(QCPAxis *keyAxis, QCPAxis *valueAxis); + virtual ~QCPColorMap(); + + // getters: + QCPColorMapData *data() const { + return mMapData; + } + QCPRange dataRange() const { + return mDataRange; + } + QCPAxis::ScaleType dataScaleType() const { + return mDataScaleType; + } + bool interpolate() const { + return mInterpolate; + } + bool tightBoundary() const { + return mTightBoundary; + } + QCPColorGradient gradient() const { + return mGradient; + } + QCPColorScale *colorScale() const { + return mColorScale.data(); + } + + // setters: + void setData(QCPColorMapData *data, bool copy = false); + Q_SLOT void setDataRange(const QCPRange &dataRange); + Q_SLOT void setDataScaleType(QCPAxis::ScaleType scaleType); + Q_SLOT void setGradient(const QCPColorGradient &gradient); + void setInterpolate(bool enabled); + void setTightBoundary(bool enabled); + void setColorScale(QCPColorScale *colorScale); + + // non-property methods: + void rescaleDataRange(bool recalculateDataBounds = false); + 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; + signals: - void dataRangeChanged(QCPRange newRange); - void dataScaleTypeChanged(QCPAxis::ScaleType scaleType); - void gradientChanged(QCPColorGradient newGradient); - + void dataRangeChanged(QCPRange newRange); + void dataScaleTypeChanged(QCPAxis::ScaleType scaleType); + void gradientChanged(QCPColorGradient newGradient); + protected: - // property members: - QCPRange mDataRange; - QCPAxis::ScaleType mDataScaleType; - QCPColorMapData *mMapData; - QCPColorGradient mGradient; - bool mInterpolate; - bool mTightBoundary; - QPointer mColorScale; - // non-property members: - QImage mMapImage, mUndersampledMapImage; - QPixmap mLegendIcon; - bool mMapImageInvalidated; - - // introduced virtual methods: - 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; - - friend class QCustomPlot; - friend class QCPLegend; + // property members: + QCPRange mDataRange; + QCPAxis::ScaleType mDataScaleType; + QCPColorMapData *mMapData; + QCPColorGradient mGradient; + bool mInterpolate; + bool mTightBoundary; + QPointer mColorScale; + // non-property members: + QImage mMapImage, mUndersampledMapImage; + QPixmap mLegendIcon; + bool mMapImageInvalidated; + + // introduced virtual methods: + 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; + + friend class QCustomPlot; + friend class QCPLegend; }; @@ -3124,16 +3646,16 @@ protected: class QCP_LIB_DECL QCPFinancialData { public: - QCPFinancialData(); - QCPFinancialData(double key, double open, double high, double low, double close); - double key, open, high, low, close; + QCPFinancialData(); + QCPFinancialData(double key, double open, double high, double low, double close); + double key, open, high, low, close; }; Q_DECLARE_TYPEINFO(QCPFinancialData, Q_MOVABLE_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. - + This is the container in which QCPFinancial holds its data. \see QCPFinancial, QCPFinancial::setData */ @@ -3144,624 +3666,733 @@ typedef QMutableMapIterator QCPFinancialDataMutableMap class QCP_LIB_DECL QCPFinancial : public QCPAbstractPlottable { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(ChartStyle chartStyle READ chartStyle WRITE setChartStyle) - Q_PROPERTY(double width READ width WRITE setWidth) - Q_PROPERTY(bool twoColored READ twoColored WRITE setTwoColored) - Q_PROPERTY(QBrush brushPositive READ brushPositive WRITE setBrushPositive) - Q_PROPERTY(QBrush brushNegative READ brushNegative WRITE setBrushNegative) - Q_PROPERTY(QPen penPositive READ penPositive WRITE setPenPositive) - Q_PROPERTY(QPen penNegative READ penNegative WRITE setPenNegative) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(ChartStyle chartStyle READ chartStyle WRITE setChartStyle) + Q_PROPERTY(double width READ width WRITE setWidth) + Q_PROPERTY(bool twoColored READ twoColored WRITE setTwoColored) + Q_PROPERTY(QBrush brushPositive READ brushPositive WRITE setBrushPositive) + Q_PROPERTY(QBrush brushNegative READ brushNegative WRITE setBrushNegative) + Q_PROPERTY(QPen penPositive READ penPositive WRITE setPenPositive) + Q_PROPERTY(QPen penNegative READ penNegative WRITE setPenNegative) + /// \endcond public: - /*! - Defines the possible representations of OHLC data in the plot. - - \see setChartStyle - */ - enum ChartStyle { csOhlc ///< Open-High-Low-Close bar representation - ,csCandlestick ///< Candlestick representation - }; - Q_ENUMS(ChartStyle) - - explicit QCPFinancial(QCPAxis *keyAxis, QCPAxis *valueAxis); - virtual ~QCPFinancial(); - - // getters: - QCPFinancialDataMap *data() const { return mData; } - ChartStyle chartStyle() const { return mChartStyle; } - double width() const { return mWidth; } - 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 setChartStyle(ChartStyle style); - void setWidth(double width); - void setTwoColored(bool twoColored); - void setBrushPositive(const QBrush &brush); - void setBrushNegative(const QBrush &brush); - void setPenPositive(const QPen &pen); - void setPenNegative(const QPen &pen); - - // non-property methods: - void addData(const QCPFinancialDataMap &dataMap); - void addData(const QCPFinancialData &data); - 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; - - // static methods: - static QCPFinancialDataMap timeSeriesToOhlc(const QVector &time, const QVector &value, double timeBinSize, double timeBinOffset = 0); - + /*! + Defines the possible representations of OHLC data in the plot. + + \see setChartStyle + */ + enum ChartStyle { csOhlc ///< Open-High-Low-Close bar representation + , csCandlestick ///< Candlestick representation + }; + Q_ENUMS(ChartStyle) + + explicit QCPFinancial(QCPAxis *keyAxis, QCPAxis *valueAxis); + virtual ~QCPFinancial(); + + // getters: + QCPFinancialDataMap *data() const { + return mData; + } + ChartStyle chartStyle() const { + return mChartStyle; + } + double width() const { + return mWidth; + } + 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 setChartStyle(ChartStyle style); + void setWidth(double width); + void setTwoColored(bool twoColored); + void setBrushPositive(const QBrush &brush); + void setBrushNegative(const QBrush &brush); + void setPenPositive(const QPen &pen); + void setPenNegative(const QPen &pen); + + // non-property methods: + void addData(const QCPFinancialDataMap &dataMap); + void addData(const QCPFinancialData &data); + 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; + + // static methods: + static QCPFinancialDataMap timeSeriesToOhlc(const QVector &time, const QVector &value, double timeBinSize, double timeBinOffset = 0); + protected: - // property members: - QCPFinancialDataMap *mData; - ChartStyle mChartStyle; - double mWidth; - 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; - - // 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; - - friend class QCustomPlot; - friend class QCPLegend; + // property members: + QCPFinancialDataMap *mData; + ChartStyle mChartStyle; + double mWidth; + 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; + + // 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; + + friend class QCustomPlot; + friend class QCPLegend; }; class QCP_LIB_DECL QCPItemStraightLine : public QCPAbstractItem { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QPen pen READ pen WRITE setPen) - Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QPen pen READ pen WRITE setPen) + Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) + /// \endcond public: - QCPItemStraightLine(QCustomPlot *parentPlot); - virtual ~QCPItemStraightLine(); - - // getters: - QPen pen() const { return mPen; } - QPen selectedPen() const { return mSelectedPen; } - - // setters; - void setPen(const QPen &pen); - void setSelectedPen(const QPen &pen); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; - - QCPItemPosition * const point1; - QCPItemPosition * const point2; - + QCPItemStraightLine(QCustomPlot *parentPlot); + virtual ~QCPItemStraightLine(); + + // getters: + QPen pen() const { + return mPen; + } + QPen selectedPen() const { + return mSelectedPen; + } + + // setters; + void setPen(const QPen &pen); + void setSelectedPen(const QPen &pen); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = 0) const; + + QCPItemPosition *const point1; + QCPItemPosition *const point2; + protected: - // property members: - QPen mPen, mSelectedPen; - - // reimplemented virtual methods: - virtual void draw(QCPPainter *painter); - - // 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; - QPen mainPen() const; + // property members: + QPen mPen, mSelectedPen; + + // reimplemented virtual methods: + virtual void draw(QCPPainter *painter); + + // 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; + QPen mainPen() const; }; class QCP_LIB_DECL QCPItemLine : public QCPAbstractItem { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QPen pen READ pen WRITE setPen) - Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) - Q_PROPERTY(QCPLineEnding head READ head WRITE setHead) - Q_PROPERTY(QCPLineEnding tail READ tail WRITE setTail) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QPen pen READ pen WRITE setPen) + Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) + Q_PROPERTY(QCPLineEnding head READ head WRITE setHead) + Q_PROPERTY(QCPLineEnding tail READ tail WRITE setTail) + /// \endcond public: - QCPItemLine(QCustomPlot *parentPlot); - virtual ~QCPItemLine(); - - // getters: - QPen pen() const { return mPen; } - QPen selectedPen() const { return mSelectedPen; } - QCPLineEnding head() const { return mHead; } - QCPLineEnding tail() const { return mTail; } - - // setters; - void setPen(const QPen &pen); - void setSelectedPen(const QPen &pen); - void setHead(const QCPLineEnding &head); - void setTail(const QCPLineEnding &tail); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; - - QCPItemPosition * const start; - QCPItemPosition * const end; - + QCPItemLine(QCustomPlot *parentPlot); + virtual ~QCPItemLine(); + + // getters: + QPen pen() const { + return mPen; + } + QPen selectedPen() const { + return mSelectedPen; + } + QCPLineEnding head() const { + return mHead; + } + QCPLineEnding tail() const { + return mTail; + } + + // setters; + void setPen(const QPen &pen); + void setSelectedPen(const QPen &pen); + void setHead(const QCPLineEnding &head); + void setTail(const QCPLineEnding &tail); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = 0) const; + + QCPItemPosition *const start; + QCPItemPosition *const end; + protected: - // property members: - QPen mPen, mSelectedPen; - QCPLineEnding mHead, mTail; - - // reimplemented virtual methods: - virtual void draw(QCPPainter *painter); - - // non-virtual methods: - QLineF getRectClippedLine(const QVector2D &start, const QVector2D &end, const QRect &rect) const; - QPen mainPen() const; + // property members: + QPen mPen, mSelectedPen; + QCPLineEnding mHead, mTail; + + // reimplemented virtual methods: + virtual void draw(QCPPainter *painter); + + // non-virtual methods: + QLineF getRectClippedLine(const QVector2D &start, const QVector2D &end, const QRect &rect) const; + QPen mainPen() const; }; class QCP_LIB_DECL QCPItemCurve : public QCPAbstractItem { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QPen pen READ pen WRITE setPen) - Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) - Q_PROPERTY(QCPLineEnding head READ head WRITE setHead) - Q_PROPERTY(QCPLineEnding tail READ tail WRITE setTail) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QPen pen READ pen WRITE setPen) + Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) + Q_PROPERTY(QCPLineEnding head READ head WRITE setHead) + Q_PROPERTY(QCPLineEnding tail READ tail WRITE setTail) + /// \endcond public: - QCPItemCurve(QCustomPlot *parentPlot); - virtual ~QCPItemCurve(); - - // getters: - QPen pen() const { return mPen; } - QPen selectedPen() const { return mSelectedPen; } - QCPLineEnding head() const { return mHead; } - QCPLineEnding tail() const { return mTail; } - - // setters; - void setPen(const QPen &pen); - void setSelectedPen(const QPen &pen); - void setHead(const QCPLineEnding &head); - void setTail(const QCPLineEnding &tail); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; - - QCPItemPosition * const start; - QCPItemPosition * const startDir; - QCPItemPosition * const endDir; - QCPItemPosition * const end; - + QCPItemCurve(QCustomPlot *parentPlot); + virtual ~QCPItemCurve(); + + // getters: + QPen pen() const { + return mPen; + } + QPen selectedPen() const { + return mSelectedPen; + } + QCPLineEnding head() const { + return mHead; + } + QCPLineEnding tail() const { + return mTail; + } + + // setters; + void setPen(const QPen &pen); + void setSelectedPen(const QPen &pen); + void setHead(const QCPLineEnding &head); + void setTail(const QCPLineEnding &tail); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = 0) const; + + QCPItemPosition *const start; + QCPItemPosition *const startDir; + QCPItemPosition *const endDir; + QCPItemPosition *const end; + protected: - // property members: - QPen mPen, mSelectedPen; - QCPLineEnding mHead, mTail; - - // reimplemented virtual methods: - virtual void draw(QCPPainter *painter); - - // non-virtual methods: - QPen mainPen() const; + // property members: + QPen mPen, mSelectedPen; + QCPLineEnding mHead, mTail; + + // reimplemented virtual methods: + virtual void draw(QCPPainter *painter); + + // non-virtual methods: + QPen mainPen() const; }; class QCP_LIB_DECL QCPItemRect : public QCPAbstractItem { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - 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) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES 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) + /// \endcond public: - QCPItemRect(QCustomPlot *parentPlot); - virtual ~QCPItemRect(); - - // getters: - QPen pen() const { return mPen; } - QPen selectedPen() const { return mSelectedPen; } - QBrush brush() const { return mBrush; } - QBrush selectedBrush() const { return mSelectedBrush; } - - // setters; - void setPen(const QPen &pen); - void setSelectedPen(const QPen &pen); - void setBrush(const QBrush &brush); - void setSelectedBrush(const QBrush &brush); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; - - QCPItemPosition * const topLeft; - QCPItemPosition * const bottomRight; - QCPItemAnchor * const top; - QCPItemAnchor * const topRight; - QCPItemAnchor * const right; - QCPItemAnchor * const bottom; - QCPItemAnchor * const bottomLeft; - QCPItemAnchor * const left; - + QCPItemRect(QCustomPlot *parentPlot); + virtual ~QCPItemRect(); + + // getters: + QPen pen() const { + return mPen; + } + QPen selectedPen() const { + return mSelectedPen; + } + QBrush brush() const { + return mBrush; + } + QBrush selectedBrush() const { + return mSelectedBrush; + } + + // setters; + void setPen(const QPen &pen); + void setSelectedPen(const QPen &pen); + void setBrush(const QBrush &brush); + void setSelectedBrush(const QBrush &brush); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = 0) const; + + QCPItemPosition *const topLeft; + QCPItemPosition *const bottomRight; + QCPItemAnchor *const top; + QCPItemAnchor *const topRight; + QCPItemAnchor *const right; + QCPItemAnchor *const bottom; + QCPItemAnchor *const bottomLeft; + QCPItemAnchor *const left; + protected: - enum AnchorIndex {aiTop, aiTopRight, aiRight, aiBottom, aiBottomLeft, aiLeft}; - - // property members: - QPen mPen, mSelectedPen; - QBrush mBrush, mSelectedBrush; - - // reimplemented virtual methods: - virtual void draw(QCPPainter *painter); - virtual QPointF anchorPixelPoint(int anchorId) const; - - // non-virtual methods: - QPen mainPen() const; - QBrush mainBrush() const; + enum AnchorIndex {aiTop, aiTopRight, aiRight, aiBottom, aiBottomLeft, aiLeft}; + + // property members: + QPen mPen, mSelectedPen; + QBrush mBrush, mSelectedBrush; + + // reimplemented virtual methods: + virtual void draw(QCPPainter *painter); + virtual QPointF anchorPixelPoint(int anchorId) const; + + // non-virtual methods: + QPen mainPen() const; + QBrush mainBrush() const; }; class QCP_LIB_DECL QCPItemText : public QCPAbstractItem { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QColor color READ color WRITE setColor) - Q_PROPERTY(QColor selectedColor READ selectedColor WRITE setSelectedColor) - 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(QFont font READ font WRITE setFont) - Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont) - Q_PROPERTY(QString text READ text WRITE setText) - Q_PROPERTY(Qt::Alignment positionAlignment READ positionAlignment WRITE setPositionAlignment) - Q_PROPERTY(Qt::Alignment textAlignment READ textAlignment WRITE setTextAlignment) - Q_PROPERTY(double rotation READ rotation WRITE setRotation) - Q_PROPERTY(QMargins padding READ padding WRITE setPadding) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QColor color READ color WRITE setColor) + Q_PROPERTY(QColor selectedColor READ selectedColor WRITE setSelectedColor) + 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(QFont font READ font WRITE setFont) + Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont) + Q_PROPERTY(QString text READ text WRITE setText) + Q_PROPERTY(Qt::Alignment positionAlignment READ positionAlignment WRITE setPositionAlignment) + Q_PROPERTY(Qt::Alignment textAlignment READ textAlignment WRITE setTextAlignment) + Q_PROPERTY(double rotation READ rotation WRITE setRotation) + Q_PROPERTY(QMargins padding READ padding WRITE setPadding) + /// \endcond public: - QCPItemText(QCustomPlot *parentPlot); - virtual ~QCPItemText(); - - // getters: - QColor color() const { return mColor; } - QColor selectedColor() const { return mSelectedColor; } - QPen pen() const { return mPen; } - QPen selectedPen() const { return mSelectedPen; } - QBrush brush() const { return mBrush; } - QBrush selectedBrush() const { return mSelectedBrush; } - QFont font() const { return mFont; } - QFont selectedFont() const { return mSelectedFont; } - QString text() const { return mText; } - Qt::Alignment positionAlignment() const { return mPositionAlignment; } - Qt::Alignment textAlignment() const { return mTextAlignment; } - double rotation() const { return mRotation; } - QMargins padding() const { return mPadding; } - - // setters; - void setColor(const QColor &color); - void setSelectedColor(const QColor &color); - void setPen(const QPen &pen); - void setSelectedPen(const QPen &pen); - void setBrush(const QBrush &brush); - void setSelectedBrush(const QBrush &brush); - void setFont(const QFont &font); - void setSelectedFont(const QFont &font); - void setText(const QString &text); - void setPositionAlignment(Qt::Alignment alignment); - void setTextAlignment(Qt::Alignment alignment); - void setRotation(double degrees); - void setPadding(const QMargins &padding); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; - - QCPItemPosition * const position; - QCPItemAnchor * const topLeft; - QCPItemAnchor * const top; - QCPItemAnchor * const topRight; - QCPItemAnchor * const right; - QCPItemAnchor * const bottomRight; - QCPItemAnchor * const bottom; - QCPItemAnchor * const bottomLeft; - QCPItemAnchor * const left; - + QCPItemText(QCustomPlot *parentPlot); + virtual ~QCPItemText(); + + // getters: + QColor color() const { + return mColor; + } + QColor selectedColor() const { + return mSelectedColor; + } + QPen pen() const { + return mPen; + } + QPen selectedPen() const { + return mSelectedPen; + } + QBrush brush() const { + return mBrush; + } + QBrush selectedBrush() const { + return mSelectedBrush; + } + QFont font() const { + return mFont; + } + QFont selectedFont() const { + return mSelectedFont; + } + QString text() const { + return mText; + } + Qt::Alignment positionAlignment() const { + return mPositionAlignment; + } + Qt::Alignment textAlignment() const { + return mTextAlignment; + } + double rotation() const { + return mRotation; + } + QMargins padding() const { + return mPadding; + } + + // setters; + void setColor(const QColor &color); + void setSelectedColor(const QColor &color); + void setPen(const QPen &pen); + void setSelectedPen(const QPen &pen); + void setBrush(const QBrush &brush); + void setSelectedBrush(const QBrush &brush); + void setFont(const QFont &font); + void setSelectedFont(const QFont &font); + void setText(const QString &text); + void setPositionAlignment(Qt::Alignment alignment); + void setTextAlignment(Qt::Alignment alignment); + void setRotation(double degrees); + void setPadding(const QMargins &padding); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = 0) const; + + QCPItemPosition *const position; + QCPItemAnchor *const topLeft; + QCPItemAnchor *const top; + QCPItemAnchor *const topRight; + QCPItemAnchor *const right; + QCPItemAnchor *const bottomRight; + QCPItemAnchor *const bottom; + QCPItemAnchor *const bottomLeft; + QCPItemAnchor *const left; + protected: - enum AnchorIndex {aiTopLeft, aiTop, aiTopRight, aiRight, aiBottomRight, aiBottom, aiBottomLeft, aiLeft}; - - // property members: - QColor mColor, mSelectedColor; - QPen mPen, mSelectedPen; - QBrush mBrush, mSelectedBrush; - QFont mFont, mSelectedFont; - QString mText; - Qt::Alignment mPositionAlignment; - Qt::Alignment mTextAlignment; - double mRotation; - QMargins mPadding; - - // reimplemented virtual methods: - virtual void draw(QCPPainter *painter); - virtual QPointF anchorPixelPoint(int anchorId) const; - - // non-virtual methods: - QPointF getTextDrawPoint(const QPointF &pos, const QRectF &rect, Qt::Alignment positionAlignment) const; - QFont mainFont() const; - QColor mainColor() const; - QPen mainPen() const; - QBrush mainBrush() const; + enum AnchorIndex {aiTopLeft, aiTop, aiTopRight, aiRight, aiBottomRight, aiBottom, aiBottomLeft, aiLeft}; + + // property members: + QColor mColor, mSelectedColor; + QPen mPen, mSelectedPen; + QBrush mBrush, mSelectedBrush; + QFont mFont, mSelectedFont; + QString mText; + Qt::Alignment mPositionAlignment; + Qt::Alignment mTextAlignment; + double mRotation; + QMargins mPadding; + + // reimplemented virtual methods: + virtual void draw(QCPPainter *painter); + virtual QPointF anchorPixelPoint(int anchorId) const; + + // non-virtual methods: + QPointF getTextDrawPoint(const QPointF &pos, const QRectF &rect, Qt::Alignment positionAlignment) const; + QFont mainFont() const; + QColor mainColor() const; + QPen mainPen() const; + QBrush mainBrush() const; }; class QCP_LIB_DECL QCPItemEllipse : public QCPAbstractItem { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - 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) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES 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) + /// \endcond public: - QCPItemEllipse(QCustomPlot *parentPlot); - virtual ~QCPItemEllipse(); - - // getters: - QPen pen() const { return mPen; } - QPen selectedPen() const { return mSelectedPen; } - QBrush brush() const { return mBrush; } - QBrush selectedBrush() const { return mSelectedBrush; } - - // setters; - void setPen(const QPen &pen); - void setSelectedPen(const QPen &pen); - void setBrush(const QBrush &brush); - void setSelectedBrush(const QBrush &brush); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; - - QCPItemPosition * const topLeft; - QCPItemPosition * const bottomRight; - QCPItemAnchor * const topLeftRim; - QCPItemAnchor * const top; - QCPItemAnchor * const topRightRim; - QCPItemAnchor * const right; - QCPItemAnchor * const bottomRightRim; - QCPItemAnchor * const bottom; - QCPItemAnchor * const bottomLeftRim; - QCPItemAnchor * const left; - QCPItemAnchor * const center; - + QCPItemEllipse(QCustomPlot *parentPlot); + virtual ~QCPItemEllipse(); + + // getters: + QPen pen() const { + return mPen; + } + QPen selectedPen() const { + return mSelectedPen; + } + QBrush brush() const { + return mBrush; + } + QBrush selectedBrush() const { + return mSelectedBrush; + } + + // setters; + void setPen(const QPen &pen); + void setSelectedPen(const QPen &pen); + void setBrush(const QBrush &brush); + void setSelectedBrush(const QBrush &brush); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = 0) const; + + QCPItemPosition *const topLeft; + QCPItemPosition *const bottomRight; + QCPItemAnchor *const topLeftRim; + QCPItemAnchor *const top; + QCPItemAnchor *const topRightRim; + QCPItemAnchor *const right; + QCPItemAnchor *const bottomRightRim; + QCPItemAnchor *const bottom; + QCPItemAnchor *const bottomLeftRim; + QCPItemAnchor *const left; + QCPItemAnchor *const center; + protected: - enum AnchorIndex {aiTopLeftRim, aiTop, aiTopRightRim, aiRight, aiBottomRightRim, aiBottom, aiBottomLeftRim, aiLeft, aiCenter}; - - // property members: - QPen mPen, mSelectedPen; - QBrush mBrush, mSelectedBrush; - - // reimplemented virtual methods: - virtual void draw(QCPPainter *painter); - virtual QPointF anchorPixelPoint(int anchorId) const; - - // non-virtual methods: - QPen mainPen() const; - QBrush mainBrush() const; + enum AnchorIndex {aiTopLeftRim, aiTop, aiTopRightRim, aiRight, aiBottomRightRim, aiBottom, aiBottomLeftRim, aiLeft, aiCenter}; + + // property members: + QPen mPen, mSelectedPen; + QBrush mBrush, mSelectedBrush; + + // reimplemented virtual methods: + virtual void draw(QCPPainter *painter); + virtual QPointF anchorPixelPoint(int anchorId) const; + + // non-virtual methods: + QPen mainPen() const; + QBrush mainBrush() const; }; class QCP_LIB_DECL QCPItemPixmap : public QCPAbstractItem { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QPixmap pixmap READ pixmap WRITE setPixmap) - Q_PROPERTY(bool scaled READ scaled WRITE setScaled) - Q_PROPERTY(Qt::AspectRatioMode aspectRatioMode READ aspectRatioMode) - Q_PROPERTY(Qt::TransformationMode transformationMode READ transformationMode) - Q_PROPERTY(QPen pen READ pen WRITE setPen) - Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QPixmap pixmap READ pixmap WRITE setPixmap) + Q_PROPERTY(bool scaled READ scaled WRITE setScaled) + Q_PROPERTY(Qt::AspectRatioMode aspectRatioMode READ aspectRatioMode) + Q_PROPERTY(Qt::TransformationMode transformationMode READ transformationMode) + Q_PROPERTY(QPen pen READ pen WRITE setPen) + Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) + /// \endcond public: - QCPItemPixmap(QCustomPlot *parentPlot); - virtual ~QCPItemPixmap(); - - // getters: - QPixmap pixmap() const { return mPixmap; } - bool scaled() const { return mScaled; } - Qt::AspectRatioMode aspectRatioMode() const { return mAspectRatioMode; } - Qt::TransformationMode transformationMode() const { return mTransformationMode; } - QPen pen() const { return mPen; } - QPen selectedPen() const { return mSelectedPen; } - - // setters; - void setPixmap(const QPixmap &pixmap); - void setScaled(bool scaled, Qt::AspectRatioMode aspectRatioMode=Qt::KeepAspectRatio, Qt::TransformationMode transformationMode=Qt::SmoothTransformation); - void setPen(const QPen &pen); - void setSelectedPen(const QPen &pen); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; - - QCPItemPosition * const topLeft; - QCPItemPosition * const bottomRight; - QCPItemAnchor * const top; - QCPItemAnchor * const topRight; - QCPItemAnchor * const right; - QCPItemAnchor * const bottom; - QCPItemAnchor * const bottomLeft; - QCPItemAnchor * const left; - + QCPItemPixmap(QCustomPlot *parentPlot); + virtual ~QCPItemPixmap(); + + // getters: + QPixmap pixmap() const { + return mPixmap; + } + bool scaled() const { + return mScaled; + } + Qt::AspectRatioMode aspectRatioMode() const { + return mAspectRatioMode; + } + Qt::TransformationMode transformationMode() const { + return mTransformationMode; + } + QPen pen() const { + return mPen; + } + QPen selectedPen() const { + return mSelectedPen; + } + + // setters; + void setPixmap(const QPixmap &pixmap); + void setScaled(bool scaled, Qt::AspectRatioMode aspectRatioMode = Qt::KeepAspectRatio, Qt::TransformationMode transformationMode = Qt::SmoothTransformation); + void setPen(const QPen &pen); + void setSelectedPen(const QPen &pen); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = 0) const; + + QCPItemPosition *const topLeft; + QCPItemPosition *const bottomRight; + QCPItemAnchor *const top; + QCPItemAnchor *const topRight; + QCPItemAnchor *const right; + QCPItemAnchor *const bottom; + QCPItemAnchor *const bottomLeft; + QCPItemAnchor *const left; + protected: - enum AnchorIndex {aiTop, aiTopRight, aiRight, aiBottom, aiBottomLeft, aiLeft}; - - // property members: - 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; - - // non-virtual methods: - void updateScaledPixmap(QRect finalRect=QRect(), bool flipHorz=false, bool flipVert=false); - QRect getFinalRect(bool *flippedHorz=0, bool *flippedVert=0) const; - QPen mainPen() const; + enum AnchorIndex {aiTop, aiTopRight, aiRight, aiBottom, aiBottomLeft, aiLeft}; + + // property members: + 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; + + // non-virtual methods: + void updateScaledPixmap(QRect finalRect = QRect(), bool flipHorz = false, bool flipVert = false); + QRect getFinalRect(bool *flippedHorz = 0, bool *flippedVert = 0) const; + QPen mainPen() const; }; class QCP_LIB_DECL QCPItemTracer : public QCPAbstractItem { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - 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(double size READ size WRITE setSize) - Q_PROPERTY(TracerStyle style READ style WRITE setStyle) - Q_PROPERTY(QCPGraph* graph READ graph WRITE setGraph) - Q_PROPERTY(double graphKey READ graphKey WRITE setGraphKey) - Q_PROPERTY(bool interpolating READ interpolating WRITE setInterpolating) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + 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(double size READ size WRITE setSize) + Q_PROPERTY(TracerStyle style READ style WRITE setStyle) + Q_PROPERTY(QCPGraph *graph READ graph WRITE setGraph) + Q_PROPERTY(double graphKey READ graphKey WRITE setGraphKey) + Q_PROPERTY(bool interpolating READ interpolating WRITE setInterpolating) + /// \endcond public: - /*! - The different visual appearances a tracer item can have. Some styles size may be controlled with \ref setSize. - - \see setStyle - */ - enum TracerStyle { tsNone ///< The tracer is not visible - ,tsPlus ///< A plus shaped crosshair with limited size - ,tsCrosshair ///< A plus shaped crosshair which spans the complete axis rect - ,tsCircle ///< A circle - ,tsSquare ///< A square - }; - Q_ENUMS(TracerStyle) + /*! + The different visual appearances a tracer item can have. Some styles size may be controlled with \ref setSize. - QCPItemTracer(QCustomPlot *parentPlot); - virtual ~QCPItemTracer(); + \see setStyle + */ + enum TracerStyle { tsNone ///< The tracer is not visible + , tsPlus ///< A plus shaped crosshair with limited size + , tsCrosshair ///< A plus shaped crosshair which spans the complete axis rect + , tsCircle ///< A circle + , tsSquare ///< A square + }; + Q_ENUMS(TracerStyle) - // getters: - QPen pen() const { return mPen; } - QPen selectedPen() const { return mSelectedPen; } - QBrush brush() const { return mBrush; } - QBrush selectedBrush() const { return mSelectedBrush; } - double size() const { return mSize; } - TracerStyle style() const { return mStyle; } - QCPGraph *graph() const { return mGraph; } - double graphKey() const { return mGraphKey; } - bool interpolating() const { return mInterpolating; } + QCPItemTracer(QCustomPlot *parentPlot); + virtual ~QCPItemTracer(); - // setters; - void setPen(const QPen &pen); - void setSelectedPen(const QPen &pen); - void setBrush(const QBrush &brush); - void setSelectedBrush(const QBrush &brush); - void setSize(double size); - void setStyle(TracerStyle style); - void setGraph(QCPGraph *graph); - void setGraphKey(double key); - void setInterpolating(bool enabled); + // getters: + QPen pen() const { + return mPen; + } + QPen selectedPen() const { + return mSelectedPen; + } + QBrush brush() const { + return mBrush; + } + QBrush selectedBrush() const { + return mSelectedBrush; + } + double size() const { + return mSize; + } + TracerStyle style() const { + return mStyle; + } + QCPGraph *graph() const { + return mGraph; + } + double graphKey() const { + return mGraphKey; + } + bool interpolating() const { + return mInterpolating; + } - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; - - // non-virtual methods: - void updatePosition(); + // setters; + void setPen(const QPen &pen); + void setSelectedPen(const QPen &pen); + void setBrush(const QBrush &brush); + void setSelectedBrush(const QBrush &brush); + void setSize(double size); + void setStyle(TracerStyle style); + void setGraph(QCPGraph *graph); + void setGraphKey(double key); + void setInterpolating(bool enabled); - QCPItemPosition * const position; + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = 0) const; + + // non-virtual methods: + void updatePosition(); + + QCPItemPosition *const position; protected: - // property members: - QPen mPen, mSelectedPen; - QBrush mBrush, mSelectedBrush; - double mSize; - TracerStyle mStyle; - QCPGraph *mGraph; - double mGraphKey; - bool mInterpolating; + // property members: + QPen mPen, mSelectedPen; + QBrush mBrush, mSelectedBrush; + double mSize; + TracerStyle mStyle; + QCPGraph *mGraph; + double mGraphKey; + bool mInterpolating; - // reimplemented virtual methods: - virtual void draw(QCPPainter *painter); + // reimplemented virtual methods: + virtual void draw(QCPPainter *painter); - // non-virtual methods: - QPen mainPen() const; - QBrush mainBrush() const; + // non-virtual methods: + QPen mainPen() const; + QBrush mainBrush() const; }; class QCP_LIB_DECL QCPItemBracket : public QCPAbstractItem { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QPen pen READ pen WRITE setPen) - Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) - Q_PROPERTY(double length READ length WRITE setLength) - Q_PROPERTY(BracketStyle style READ style WRITE setStyle) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(QPen pen READ pen WRITE setPen) + Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) + Q_PROPERTY(double length READ length WRITE setLength) + Q_PROPERTY(BracketStyle style READ style WRITE setStyle) + /// \endcond public: - 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 - }; + 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 + }; + + QCPItemBracket(QCustomPlot *parentPlot); + virtual ~QCPItemBracket(); + + // getters: + QPen pen() const { + return mPen; + } + QPen selectedPen() const { + return mSelectedPen; + } + double length() const { + return mLength; + } + BracketStyle style() const { + return mStyle; + } + + // setters; + void setPen(const QPen &pen); + void setSelectedPen(const QPen &pen); + void setLength(double length); + void setStyle(BracketStyle style); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = 0) const; + + QCPItemPosition *const left; + QCPItemPosition *const right; + QCPItemAnchor *const center; - QCPItemBracket(QCustomPlot *parentPlot); - virtual ~QCPItemBracket(); - - // getters: - QPen pen() const { return mPen; } - QPen selectedPen() const { return mSelectedPen; } - double length() const { return mLength; } - BracketStyle style() const { return mStyle; } - - // setters; - void setPen(const QPen &pen); - void setSelectedPen(const QPen &pen); - void setLength(double length); - void setStyle(BracketStyle style); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; - - QCPItemPosition * const left; - QCPItemPosition * const right; - QCPItemAnchor * const center; - protected: - // property members: - enum AnchorIndex {aiCenter}; - QPen mPen, mSelectedPen; - double mLength; - BracketStyle mStyle; - - // reimplemented virtual methods: - virtual void draw(QCPPainter *painter); - virtual QPointF anchorPixelPoint(int anchorId) const; - - // non-virtual methods: - QPen mainPen() const; + // property members: + enum AnchorIndex {aiCenter}; + QPen mPen, mSelectedPen; + double mLength; + BracketStyle mStyle; + + // reimplemented virtual methods: + virtual void draw(QCPPainter *painter); + virtual QPointF anchorPixelPoint(int anchorId) const; + + // non-virtual methods: + QPen mainPen() const; }; #endif // QCUSTOMPLOT_H diff --git a/third/3rd_qcustomplot/v2_0/qcustomplot.cpp b/third/3rd_qcustomplot/v2_0/qcustomplot.cpp index 2966b6f..249d369 100644 --- a/third/3rd_qcustomplot/v2_0/qcustomplot.cpp +++ b/third/3rd_qcustomplot/v2_0/qcustomplot.cpp @@ -24,7 +24,7 @@ ****************************************************************************/ #include "qcustomplot.h" - +#include "smoothcurve.h" /* including file 'src/vector2d.cpp', size 7340 */ /* commit ce344b3f96a62e5f652585e55f1ae7c7883cd45b 2018-06-25 01:03:39 +0200 */ @@ -35,7 +35,7 @@ /*! \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. */ @@ -43,63 +43,63 @@ /* 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. */ @@ -109,8 +109,8 @@ Creates a QCPVector2D object and initializes the x and y coordinates to 0. */ QCPVector2D::QCPVector2D() : - mX(0), - mY(0) + mX(0), + mY(0) { } @@ -119,8 +119,8 @@ QCPVector2D::QCPVector2D() : values. */ QCPVector2D::QCPVector2D(double x, double y) : - mX(x), - mY(y) + mX(x), + mY(y) { } @@ -129,8 +129,8 @@ QCPVector2D::QCPVector2D(double x, double y) : the specified \a point. */ QCPVector2D::QCPVector2D(const QPoint &point) : - mX(point.x()), - mY(point.y()) + mX(point.x()), + mY(point.y()) { } @@ -139,80 +139,81 @@ QCPVector2D::QCPVector2D(const QPoint &point) : the specified \a point. */ QCPVector2D::QCPVector2D(const QPointF &point) : - mX(point.x()), - mY(point.y()) + 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; + 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; + 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(); + 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())); + 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(); + return qAbs((*this - base).dot(direction.perpendicular())) / direction.length(); } /*! @@ -221,9 +222,9 @@ double QCPVector2D::distanceToStraightLine(const QCPVector2D &base, const QCPVec */ QCPVector2D &QCPVector2D::operator*=(double factor) { - mX *= factor; - mY *= factor; - return *this; + mX *= factor; + mY *= factor; + return *this; } /*! @@ -232,9 +233,9 @@ QCPVector2D &QCPVector2D::operator*=(double factor) */ QCPVector2D &QCPVector2D::operator/=(double divisor) { - mX /= divisor; - mY /= divisor; - return *this; + mX /= divisor; + mY /= divisor; + return *this; } /*! @@ -242,9 +243,9 @@ QCPVector2D &QCPVector2D::operator/=(double divisor) */ QCPVector2D &QCPVector2D::operator+=(const QCPVector2D &vector) { - mX += vector.mX; - mY += vector.mY; - return *this; + mX += vector.mX; + mY += vector.mY; + return *this; } /*! @@ -252,9 +253,9 @@ QCPVector2D &QCPVector2D::operator+=(const QCPVector2D &vector) */ QCPVector2D &QCPVector2D::operator-=(const QCPVector2D &vector) { - mX -= vector.mX; - mY -= vector.mY; - return *this; + mX -= vector.mX; + mY -= vector.mY; + return *this; } /* end of 'src/vector2d.cpp' */ @@ -268,11 +269,11 @@ QCPVector2D &QCPVector2D::operator-=(const QCPVector2D &vector) /*! \class QCPPainter \brief QPainter subclass used internally - + This QPainter subclass is used to provide some extended functionality e.g. for tweaking position consistency between antialiased and non-antialiased painting. Further it provides workarounds for QPainter quirks. - + \warning This class intentionally hides non-virtual functions of QPainter, e.g. setPen, save and restore. So while it is possible to pass a QCPPainter instance to a function that expects a QPainter pointer, some of the workarounds and tweaks will be unavailable to the function (because @@ -283,86 +284,91 @@ QCPVector2D &QCPVector2D::operator-=(const QCPVector2D &vector) Creates a new QCPPainter instance and sets default values */ QCPPainter::QCPPainter() : - QPainter(), - mModes(pmDefault), - mIsAntialiasing(false) + QPainter(), + mModes(pmDefault), + mIsAntialiasing(false) { - // don't setRenderHint(QPainter::NonCosmeticDefautPen) here, because painter isn't active yet and - // a call to begin() will follow + // don't setRenderHint(QPainter::NonCosmeticDefautPen) here, because painter isn't active yet and + // a call to begin() will follow } /*! Creates a new QCPPainter instance on the specified paint \a device and sets default values. Just like the analogous QPainter constructor, begins painting on \a device immediately. - + Like \ref begin, this method sets QPainter::NonCosmeticDefaultPen in Qt versions before Qt5. */ QCPPainter::QCPPainter(QPaintDevice *device) : - QPainter(device), - mModes(pmDefault), - mIsAntialiasing(false) + QPainter(device), + mModes(pmDefault), + mIsAntialiasing(false) { #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) // before Qt5, default pens used to be cosmetic if NonCosmeticDefaultPen flag isn't set. So we set it to get consistency across Qt versions. - if (isActive()) - setRenderHint(QPainter::NonCosmeticDefaultPen); + if (isActive()) { + setRenderHint(QPainter::NonCosmeticDefaultPen); + } #endif } /*! Sets the pen of the painter and applies certain fixes to it, depending on the mode of this QCPPainter. - + \note this function hides the non-virtual base class implementation. */ void QCPPainter::setPen(const QPen &pen) { - QPainter::setPen(pen); - if (mModes.testFlag(pmNonCosmetic)) - makeNonCosmetic(); + QPainter::setPen(pen); + if (mModes.testFlag(pmNonCosmetic)) { + makeNonCosmetic(); + } } /*! \overload - + Sets the pen (by color) of the painter and applies certain fixes to it, depending on the mode of this QCPPainter. - + \note this function hides the non-virtual base class implementation. */ void QCPPainter::setPen(const QColor &color) { - QPainter::setPen(color); - if (mModes.testFlag(pmNonCosmetic)) - makeNonCosmetic(); + QPainter::setPen(color); + if (mModes.testFlag(pmNonCosmetic)) { + makeNonCosmetic(); + } } /*! \overload - + Sets the pen (by style) of the painter and applies certain fixes to it, depending on the mode of this QCPPainter. - + \note this function hides the non-virtual base class implementation. */ void QCPPainter::setPen(Qt::PenStyle penStyle) { - QPainter::setPen(penStyle); - if (mModes.testFlag(pmNonCosmetic)) - makeNonCosmetic(); + QPainter::setPen(penStyle); + if (mModes.testFlag(pmNonCosmetic)) { + makeNonCosmetic(); + } } /*! \overload - + Works around a Qt bug introduced with Qt 4.8 which makes drawing QLineF unpredictable when antialiasing is disabled. Thus when antialiasing is disabled, it rounds the \a line to integer coordinates and then passes it to the original drawLine. - + \note this function hides the non-virtual base class implementation. */ void QCPPainter::drawLine(const QLineF &line) { - if (mIsAntialiasing || mModes.testFlag(pmVectorized)) - QPainter::drawLine(line); - else - QPainter::drawLine(line.toLine()); + if (mIsAntialiasing || mModes.testFlag(pmVectorized)) { + QPainter::drawLine(line); + } else { + QPainter::drawLine(line.toLine()); + } } /*! @@ -373,18 +379,17 @@ void QCPPainter::drawLine(const QLineF &line) */ void QCPPainter::setAntialiasing(bool enabled) { - setRenderHint(QPainter::Antialiasing, enabled); - if (mIsAntialiasing != enabled) - { - mIsAntialiasing = enabled; - if (!mModes.testFlag(pmVectorized)) // antialiasing half-pixel shift only needed for rasterized outputs - { - if (mIsAntialiasing) - translate(0.5, 0.5); - else - translate(-0.5, -0.5); + setRenderHint(QPainter::Antialiasing, enabled); + if (mIsAntialiasing != enabled) { + mIsAntialiasing = enabled; + if (!mModes.testFlag(pmVectorized)) { // antialiasing half-pixel shift only needed for rasterized outputs + if (mIsAntialiasing) { + translate(0.5, 0.5); + } else { + translate(-0.5, -0.5); + } + } } - } } /*! @@ -393,7 +398,7 @@ void QCPPainter::setAntialiasing(bool enabled) */ void QCPPainter::setModes(QCPPainter::PainterModes modes) { - mModes = modes; + mModes = modes; } /*! @@ -401,64 +406,67 @@ void QCPPainter::setModes(QCPPainter::PainterModes modes) device. This is necessary to get cosmetic pen consistency across Qt versions, because since Qt5, all pens are non-cosmetic by default, and in Qt4 this render hint must be set to get that behaviour. - + The Constructor \ref QCPPainter(QPaintDevice *device) which directly starts painting also sets the render hint as appropriate. - + \note this function hides the non-virtual base class implementation. */ bool QCPPainter::begin(QPaintDevice *device) { - bool result = QPainter::begin(device); + bool result = QPainter::begin(device); #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) // before Qt5, default pens used to be cosmetic if NonCosmeticDefaultPen flag isn't set. So we set it to get consistency across Qt versions. - if (result) - setRenderHint(QPainter::NonCosmeticDefaultPen); + if (result) { + setRenderHint(QPainter::NonCosmeticDefaultPen); + } #endif - return result; + return result; } /*! \overload - + Sets the mode of the painter. This controls whether the painter shall adjust its fixes/workarounds optimized for certain output devices. */ void QCPPainter::setMode(QCPPainter::PainterMode mode, bool enabled) { - if (!enabled && mModes.testFlag(mode)) - mModes &= ~mode; - else if (enabled && !mModes.testFlag(mode)) - mModes |= mode; + if (!enabled && mModes.testFlag(mode)) { + mModes &= ~mode; + } else if (enabled && !mModes.testFlag(mode)) { + mModes |= mode; + } } /*! Saves the painter (see QPainter::save). Since QCPPainter adds some new internal state to QPainter, the save/restore functions are reimplemented to also save/restore those members. - + \note this function hides the non-virtual base class implementation. - + \see restore */ void QCPPainter::save() { - mAntialiasingStack.push(mIsAntialiasing); - QPainter::save(); + mAntialiasingStack.push(mIsAntialiasing); + QPainter::save(); } /*! Restores the painter (see QPainter::restore). Since QCPPainter adds some new internal state to QPainter, the save/restore functions are reimplemented to also save/restore those members. - + \note this function hides the non-virtual base class implementation. - + \see save */ void QCPPainter::restore() { - if (!mAntialiasingStack.isEmpty()) - mIsAntialiasing = mAntialiasingStack.pop(); - else - qDebug() << Q_FUNC_INFO << "Unbalanced save/restore"; - QPainter::restore(); + if (!mAntialiasingStack.isEmpty()) { + mIsAntialiasing = mAntialiasingStack.pop(); + } else { + qDebug() << Q_FUNC_INFO << "Unbalanced save/restore"; + } + QPainter::restore(); } /*! @@ -467,12 +475,11 @@ void QCPPainter::restore() */ void QCPPainter::makeNonCosmetic() { - if (qFuzzyIsNull(pen().widthF())) - { - QPen p = pen(); - p.setWidth(1); - QPainter::setPen(p); - } + if (qFuzzyIsNull(pen().widthF())) { + QPen p = pen(); + p.setWidth(1); + QPainter::setPen(p); + } } /* end of 'src/painter.cpp' */ @@ -568,9 +575,9 @@ void QCPPainter::makeNonCosmetic() Subclasses must call their \ref reallocateBuffer implementation in their respective constructors. */ QCPAbstractPaintBuffer::QCPAbstractPaintBuffer(const QSize &size, double devicePixelRatio) : - mSize(size), - mDevicePixelRatio(devicePixelRatio), - mInvalidated(true) + mSize(size), + mDevicePixelRatio(devicePixelRatio), + mInvalidated(true) { } @@ -588,11 +595,10 @@ QCPAbstractPaintBuffer::~QCPAbstractPaintBuffer() */ void QCPAbstractPaintBuffer::setSize(const QSize &size) { - if (mSize != size) - { - mSize = size; - reallocateBuffer(); - } + if (mSize != size) { + mSize = size; + reallocateBuffer(); + } } /*! @@ -612,7 +618,7 @@ void QCPAbstractPaintBuffer::setSize(const QSize &size) */ void QCPAbstractPaintBuffer::setInvalidated(bool invalidated) { - mInvalidated = invalidated; + mInvalidated = invalidated; } /*! @@ -626,16 +632,15 @@ void QCPAbstractPaintBuffer::setInvalidated(bool invalidated) */ void QCPAbstractPaintBuffer::setDevicePixelRatio(double ratio) { - if (!qFuzzyCompare(ratio, mDevicePixelRatio)) - { + if (!qFuzzyCompare(ratio, mDevicePixelRatio)) { #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED - mDevicePixelRatio = ratio; - reallocateBuffer(); + mDevicePixelRatio = ratio; + reallocateBuffer(); #else - qDebug() << Q_FUNC_INFO << "Device pixel ratios not supported for Qt versions before 5.4"; - mDevicePixelRatio = 1.0; + qDebug() << Q_FUNC_INFO << "Device pixel ratios not supported for Qt versions before 5.4"; + mDevicePixelRatio = 1.0; #endif - } + } } //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -654,9 +659,9 @@ void QCPAbstractPaintBuffer::setDevicePixelRatio(double ratio) applicable. */ QCPPaintBufferPixmap::QCPPaintBufferPixmap(const QSize &size, double devicePixelRatio) : - QCPAbstractPaintBuffer(size, devicePixelRatio) + QCPAbstractPaintBuffer(size, devicePixelRatio) { - QCPPaintBufferPixmap::reallocateBuffer(); + QCPPaintBufferPixmap::reallocateBuffer(); } QCPPaintBufferPixmap::~QCPPaintBufferPixmap() @@ -666,44 +671,43 @@ QCPPaintBufferPixmap::~QCPPaintBufferPixmap() /* inherits documentation from base class */ QCPPainter *QCPPaintBufferPixmap::startPainting() { - QCPPainter *result = new QCPPainter(&mBuffer); - result->setRenderHint(QPainter::HighQualityAntialiasing); - return result; + 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"; + 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); + mBuffer.fill(color); } /* inherits documentation from base class */ void QCPPaintBufferPixmap::reallocateBuffer() { - setInvalidated(); - if (!qFuzzyCompare(1.0, mDevicePixelRatio)) - { + setInvalidated(); + if (!qFuzzyCompare(1.0, mDevicePixelRatio)) { #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED - mBuffer = QPixmap(mSize*mDevicePixelRatio); - mBuffer.setDevicePixelRatio(mDevicePixelRatio); + 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); + 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); - } + } else { + mBuffer = QPixmap(mSize); + } } @@ -732,72 +736,71 @@ void QCPPaintBufferPixmap::reallocateBuffer() 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)) + QCPAbstractPaintBuffer(size, devicePixelRatio), + mGlPBuffer(0), + mMultisamples(qMax(0, multisamples)) { - QCPPaintBufferGlPbuffer::reallocateBuffer(); + QCPPaintBufferGlPbuffer::reallocateBuffer(); } QCPPaintBufferGlPbuffer::~QCPPaintBufferGlPbuffer() { - if (mGlPBuffer) - delete mGlPBuffer; + 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; + 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()); + 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"; + 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); + if (mGlPBuffer) { + delete mGlPBuffer; + } + + QGLFormat format; + format.setAlpha(true); + format.setSamples(mMultisamples); + mGlPBuffer = new QGLPixelBuffer(mSize, format); } #endif // QCP_OPENGL_PBUFFER @@ -828,122 +831,119 @@ void QCPPaintBufferGlPbuffer::reallocateBuffer() instance. */ QCPPaintBufferGlFbo::QCPPaintBufferGlFbo(const QSize &size, double devicePixelRatio, QWeakPointer glContext, QWeakPointer glPaintDevice) : - QCPAbstractPaintBuffer(size, devicePixelRatio), - mGlContext(glContext), - mGlPaintDevice(glPaintDevice), - mGlFrameBuffer(0) + QCPAbstractPaintBuffer(size, devicePixelRatio), + mGlContext(glContext), + mGlPaintDevice(glPaintDevice), + mGlFrameBuffer(0) { - QCPPaintBufferGlFbo::reallocateBuffer(); + QCPPaintBufferGlFbo::reallocateBuffer(); } QCPPaintBufferGlFbo::~QCPPaintBufferGlFbo() { - if (mGlFrameBuffer) - delete mGlFrameBuffer; + 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; + 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"; + 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()); + 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(); + 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); + // 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); + mGlPaintDevice.data()->setDevicePixelRatio(mDevicePixelRatio); #endif } #endif // QCP_OPENGL_FBO @@ -1016,16 +1016,16 @@ void QCPPaintBufferGlFbo::reallocateBuffer() /* start documentation of inline functions */ /*! \fn QList QCPLayer::children() const - + Returns a list of all layerables on this layer. The order corresponds to the rendering order: layerables with higher indices are drawn above layerables with lower indices. */ /*! \fn int QCPLayer::index() const - + Returns the index this layer has in the QCustomPlot. The index is the integer number by which this layer can be accessed via \ref QCustomPlot::layer. - + Layers with higher indices will be drawn above layers with lower indices. */ @@ -1033,36 +1033,38 @@ void QCPPaintBufferGlFbo::reallocateBuffer() /*! Creates a new QCPLayer instance. - + Normally you shouldn't directly instantiate layers, use \ref QCustomPlot::addLayer instead. - + \warning It is not checked that \a layerName is actually a unique layer name in \a parentPlot. This check is only performed by \ref QCustomPlot::addLayer. */ QCPLayer::QCPLayer(QCustomPlot *parentPlot, const QString &layerName) : - QObject(parentPlot), - mParentPlot(parentPlot), - mName(layerName), - mIndex(-1), // will be set to a proper value by the QCustomPlot layer creation function - mVisible(true), - mMode(lmLogical) + QObject(parentPlot), + mParentPlot(parentPlot), + mName(layerName), + mIndex(-1), // will be set to a proper value by the QCustomPlot layer creation function + mVisible(true), + mMode(lmLogical) { - // Note: no need to make sure layerName is unique, because layer - // management is done with QCustomPlot functions. + // Note: no need to make sure layerName is unique, because layer + // management is done with QCustomPlot functions. } QCPLayer::~QCPLayer() { - // If child layerables are still on this layer, detach them, so they don't try to reach back to this - // then invalid layer once they get deleted/moved themselves. This only happens when layers are deleted - // directly, like in the QCustomPlot destructor. (The regular layer removal procedure for the user is to - // call QCustomPlot::removeLayer, which moves all layerables off this layer before deleting it.) - - while (!mChildren.isEmpty()) - mChildren.last()->setLayer(0); // removes itself from mChildren via removeChild() - - if (mParentPlot->currentLayer() == this) - qDebug() << Q_FUNC_INFO << "The parent plot's mCurrentLayer will be a dangling pointer. Should have been set to a valid layer or 0 beforehand."; + // If child layerables are still on this layer, detach them, so they don't try to reach back to this + // then invalid layer once they get deleted/moved themselves. This only happens when layers are deleted + // directly, like in the QCustomPlot destructor. (The regular layer removal procedure for the user is to + // call QCustomPlot::removeLayer, which moves all layerables off this layer before deleting it.) + + while (!mChildren.isEmpty()) { + mChildren.last()->setLayer(0); // removes itself from mChildren via removeChild() + } + + if (mParentPlot->currentLayer() == this) { + qDebug() << Q_FUNC_INFO << "The parent plot's mCurrentLayer will be a dangling pointer. Should have been set to a valid layer or 0 beforehand."; + } } /*! @@ -1075,7 +1077,7 @@ QCPLayer::~QCPLayer() */ void QCPLayer::setVisible(bool visible) { - mVisible = visible; + mVisible = visible; } /*! @@ -1101,12 +1103,12 @@ void QCPLayer::setVisible(bool visible) */ void QCPLayer::setMode(QCPLayer::LayerMode mode) { - if (mMode != mode) - { - mMode = mode; - if (!mPaintBuffer.isNull()) - mPaintBuffer.data()->setInvalidated(); - } + if (mMode != mode) { + mMode = mode; + if (!mPaintBuffer.isNull()) { + mPaintBuffer.data()->setInvalidated(); + } + } } /*! \internal @@ -1117,17 +1119,15 @@ void QCPLayer::setMode(QCPLayer::LayerMode mode) */ 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(); + 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 @@ -1140,20 +1140,21 @@ void QCPLayer::draw(QCPPainter *painter) */ 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 (!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"; + } } /*! @@ -1171,61 +1172,64 @@ void QCPLayer::drawToPaintBuffer() */ 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(); + 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 be prepended to the list, i.e. be drawn beneath the other layerables already in the list. - + This function does not change the \a mLayer member of \a layerable to this layer. (Use QCPLayerable::setLayer to change the layer of an object, not this function.) - + \see removeChild */ void QCPLayer::addChild(QCPLayerable *layerable, bool prepend) { - if (!mChildren.contains(layerable)) - { - if (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); + if (!mChildren.contains(layerable)) { + if (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); + } } /*! \internal - + Removes the \a layerable from the list of this layer. - + This function does not change the \a mLayer member of \a layerable. (Use QCPLayerable::setLayer to change the layer of an object, not this function.) - + \see addChild */ void QCPLayer::removeChild(QCPLayerable *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); + 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); + } } @@ -1235,27 +1239,27 @@ void QCPLayer::removeChild(QCPLayerable *layerable) /*! \class QCPLayerable \brief Base class for all drawable objects - + This is the abstract base class most visible objects derive from, e.g. plottables, axes, grid etc. Every layerable is on a layer (QCPLayer) which allows controlling the rendering order by stacking the layers accordingly. - + For details about the layering mechanism, see the QCPLayer documentation. */ /* start documentation of inline functions */ /*! \fn QCPLayerable *QCPLayerable::parentLayerable() const - + Returns the parent layerable of this layerable. The parent layerable is used to provide visibility hierarchies in conjunction with the method \ref realVisibility. This way, layerables only get drawn if their parent layerables are visible, too. - + 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 when placed inside layout elements and doesn't need to be set manually by the user. */ @@ -1265,7 +1269,7 @@ void QCPLayer::removeChild(QCPLayerable *layerable) /*! \fn virtual void QCPLayerable::applyDefaultAntialiasingHint(QCPPainter *painter) const = 0 \internal - + This function applies the default antialiasing setting to the specified \a painter, using the function \ref applyAntialiasingHint. It is the antialiasing state the painter is put in, when \ref draw is called on the layerable. If the layerable has multiple entities whose antialiasing @@ -1273,7 +1277,7 @@ void QCPLayer::removeChild(QCPLayerable *layerable) most prominent entity. In this case however, the \ref draw function usually calls the specialized versions of this function before drawing each entity, effectively overriding the setting of the default antialiasing hint. - + First example: QCPGraph has multiple entities that have an antialiasing setting: The graph line, fills and scatters. Those can be configured via QCPGraph::setAntialiased, QCPGraph::setAntialiasedFill and QCPGraph::setAntialiasedScatters. Consequently, there isn't only @@ -1281,7 +1285,7 @@ void QCPLayer::removeChild(QCPLayerable *layerable) 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. - + Second example: QCPItemLine consists only of a line so there is only one antialiasing setting which can be controlled with QCPItemLine::setAntialiased. (This function is inherited by all layerables. The specialized functions, as seen on QCPGraph, must be added explicitly to the @@ -1294,10 +1298,10 @@ void QCPLayer::removeChild(QCPLayerable *layerable) /*! \fn virtual void QCPLayerable::draw(QCPPainter *painter) const = 0 \internal - + This function draws the layerable with the specified \a painter. It is only called by QCustomPlot, if the layerable is visible (\ref setVisible). - + Before this function is called, the painter's antialiasing state is set via \ref applyDefaultAntialiasingHint, see the documentation there. Further, the clipping rectangle was set to \ref clipRect. @@ -1307,10 +1311,10 @@ void QCPLayer::removeChild(QCPLayerable *layerable) /* start documentation of signals */ /*! \fn void QCPLayerable::layerChanged(QCPLayer *newLayer); - + This signal is emitted when the layer of this layerable changes, i.e. this layerable is moved to a different layer. - + \see setLayer */ @@ -1318,17 +1322,17 @@ void QCPLayer::removeChild(QCPLayerable *layerable) /*! Creates a new QCPLayerable instance. - + Since QCPLayerable is an abstract base class, it can't be instantiated directly. Use one of the derived classes. - + If \a plot is provided, it automatically places itself on the layer named \a targetLayer. If \a targetLayer is an empty string, it places itself on the current layer of the plot (see \ref QCustomPlot::setCurrentLayer). - + 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 @@ -1337,29 +1341,28 @@ void QCPLayer::removeChild(QCPLayerable *layerable) QCPLayerable subclasses, to guarantee a working destruction hierarchy. */ QCPLayerable::QCPLayerable(QCustomPlot *plot, QString targetLayer, QCPLayerable *parentLayerable) : - QObject(plot), - mVisible(true), - mParentPlot(plot), - mParentLayerable(parentLayerable), - mLayer(0), - mAntialiased(true) + QObject(plot), + mVisible(true), + mParentPlot(plot), + mParentLayerable(parentLayerable), + mLayer(0), + mAntialiased(true) { - if (mParentPlot) - { - if (targetLayer.isEmpty()) - setLayer(mParentPlot->currentLayer()); - else if (!setLayer(targetLayer)) - qDebug() << Q_FUNC_INFO << "setting QCPlayerable initial layer to" << targetLayer << "failed."; - } + if (mParentPlot) { + if (targetLayer.isEmpty()) { + setLayer(mParentPlot->currentLayer()); + } else if (!setLayer(targetLayer)) { + qDebug() << Q_FUNC_INFO << "setting QCPlayerable initial layer to" << targetLayer << "failed."; + } + } } QCPLayerable::~QCPLayerable() { - if (mLayer) - { - mLayer->removeChild(this); - mLayer = 0; - } + if (mLayer) { + mLayer->removeChild(this); + mLayer = 0; + } } /*! @@ -1369,61 +1372,58 @@ QCPLayerable::~QCPLayerable() */ void QCPLayerable::setVisible(bool on) { - mVisible = on; + mVisible = on; } /*! Sets the \a layer of this layerable object. The object will be placed on top of the other objects already on \a 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) { - return moveToLayer(layer, false); + return moveToLayer(layer, false); } /*! \overload Sets the layer of this layerable object by name - + Returns true on success, i.e. if \a layerName is a valid layer name. */ bool QCPLayerable::setLayer(const QString &layerName) { - if (!mParentPlot) - { - qDebug() << Q_FUNC_INFO << "no parent QCustomPlot set"; - return false; - } - if (QCPLayer *layer = mParentPlot->layer(layerName)) - { - return setLayer(layer); - } else - { - qDebug() << Q_FUNC_INFO << "there is no layer with name" << layerName; - return false; - } + if (!mParentPlot) { + qDebug() << Q_FUNC_INFO << "no parent QCustomPlot set"; + return false; + } + if (QCPLayer *layer = mParentPlot->layer(layerName)) { + return setLayer(layer); + } else { + qDebug() << Q_FUNC_INFO << "there is no layer with name" << layerName; + return false; + } } /*! Sets whether this object will be drawn antialiased or not. - + Note that antialiasing settings may be overridden by QCustomPlot::setAntialiasedElements and QCustomPlot::setNotAntialiasedElements. */ void QCPLayerable::setAntialiased(bool enabled) { - mAntialiased = enabled; + mAntialiased = enabled; } /*! Returns whether this layerable is visible, taking the visibility of the layerable parent and the 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 \ref QCPLayoutElement), this function returns true only if this layerable has its visibility set to true and the parent layerable's \ref realVisibility returns @@ -1431,7 +1431,7 @@ void QCPLayerable::setAntialiased(bool enabled) */ bool QCPLayerable::realVisibility() const { - return mVisible && (!mLayer || mLayer->visible()) && (!mParentLayerable || mParentLayerable.data()->realVisibility()); + return mVisible && (!mLayer || mLayer->visible()) && (!mParentLayerable || mParentLayerable.data()->realVisibility()); } /*! @@ -1446,15 +1446,15 @@ bool QCPLayerable::realVisibility() const bars of a \ref QCPBars plottable, a click inside the area should also be considered a hit. In these cases this function thus returns a constant value greater zero but still below the parent plot's selection tolerance. (typically the selectionTolerance multiplied by 0.99). - + Providing a constant value for area objects allows selecting line objects even when they are obscured by such area objects, by clicking close to the lines (i.e. closer than 0.99*selectionTolerance). - + 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 \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 decides on the basis of this selectTest call, that the object was successfully selected. The @@ -1463,101 +1463,102 @@ bool QCPLayerable::realVisibility() const is only done once in \ref selectTest. The result (i.e. the actually clicked part) can then be placed in \a details. So in the subsequent \ref selectEvent, the decision which part was selected doesn't have to be done a second time for a single selection operation. - + In the case of 1D Plottables (\ref QCPAbstractPlottable1D, like \ref QCPGraph or \ref QCPBars) \a details will be set to a \ref QCPDataSelection, describing the closest data point to \a pos. - + You may pass 0 as \a details to indicate that you are not interested in those selection details. - + \see selectEvent, deselectEvent, mousePressEvent, wheelEvent, QCustomPlot::setInteractions, QCPAbstractPlottable1D::selectTestRect */ double QCPLayerable::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { - Q_UNUSED(pos) - Q_UNUSED(onlySelectable) - Q_UNUSED(details) - return -1.0; + Q_UNUSED(pos) + Q_UNUSED(onlySelectable) + Q_UNUSED(details) + return -1.0; } /*! \internal - + Sets the parent plot of this layerable. Use this function once to set the parent plot if you have passed 0 in the constructor. It can not be used to move a layerable from one QCustomPlot to another one. - + Note that, unlike when passing a non-null parent plot in the constructor, this function does not make \a parentPlot the QObject-parent of this layerable. If you want this, call QObject::setParent(\a parentPlot) in addition to this function. - + Further, you will probably want to set a layer (\ref setLayer) after calling this function, to make the layerable appear on the QCustomPlot. - + The parent plot change will be propagated to subclasses via a call to \ref parentPlotInitialized so they can react accordingly (e.g. also initialize the parent plot of child layerables, like QCPLayout does). */ void QCPLayerable::initializeParentPlot(QCustomPlot *parentPlot) { - if (mParentPlot) - { - qDebug() << Q_FUNC_INFO << "called with mParentPlot already initialized"; - return; - } - - if (!parentPlot) - qDebug() << Q_FUNC_INFO << "called with parentPlot zero"; - - mParentPlot = parentPlot; - parentPlotInitialized(mParentPlot); + if (mParentPlot) { + qDebug() << Q_FUNC_INFO << "called with mParentPlot already initialized"; + return; + } + + if (!parentPlot) { + qDebug() << Q_FUNC_INFO << "called with parentPlot zero"; + } + + mParentPlot = parentPlot; + parentPlotInitialized(mParentPlot); } /*! \internal - + Sets the parent layerable of this layerable to \a parentLayerable. Note that \a parentLayerable does not become the QObject-parent (for memory management) of this layerable. - + The parent layerable has influence on the return value of the \ref realVisibility method. Only layerables with a fully visible parent tree will return true for \ref realVisibility, and thus be drawn. - + \see realVisibility */ void QCPLayerable::setParentLayerable(QCPLayerable *parentLayerable) { - mParentLayerable = parentLayerable; + mParentLayerable = parentLayerable; } /*! \internal - + Moves this layerable object to \a layer. If \a prepend is true, this object will be prepended to the new layer's list, i.e. it will be drawn below the objects already on the layer. If it is false, the object will be appended. - + Returns true on success, i.e. if \a layer is a valid layer. */ bool QCPLayerable::moveToLayer(QCPLayer *layer, bool prepend) { - if (layer && !mParentPlot) - { - qDebug() << Q_FUNC_INFO << "no parent QCustomPlot set"; - return false; - } - if (layer && layer->parentPlot() != mParentPlot) - { - qDebug() << Q_FUNC_INFO << "layer" << layer->name() << "is not in same QCustomPlot as this layerable"; - return false; - } - - QCPLayer *oldLayer = mLayer; - if (mLayer) - mLayer->removeChild(this); - mLayer = layer; - if (mLayer) - mLayer->addChild(this, prepend); - if (mLayer != oldLayer) - emit layerChanged(mLayer); - return true; + if (layer && !mParentPlot) { + qDebug() << Q_FUNC_INFO << "no parent QCustomPlot set"; + return false; + } + if (layer && layer->parentPlot() != mParentPlot) { + qDebug() << Q_FUNC_INFO << "layer" << layer->name() << "is not in same QCustomPlot as this layerable"; + return false; + } + + QCPLayer *oldLayer = mLayer; + if (mLayer) { + mLayer->removeChild(this); + } + mLayer = layer; + if (mLayer) { + mLayer->addChild(this, prepend); + } + if (mLayer != oldLayer) { + emit layerChanged(mLayer); + } + return true; } /*! \internal @@ -1569,12 +1570,13 @@ bool QCPLayerable::moveToLayer(QCPLayer *layer, bool prepend) */ void QCPLayerable::applyAntialiasingHint(QCPPainter *painter, bool localAntialiased, QCP::AntialiasedElement overrideElement) const { - if (mParentPlot && mParentPlot->notAntialiasedElements().testFlag(overrideElement)) - painter->setAntialiasing(false); - else if (mParentPlot && mParentPlot->antialiasedElements().testFlag(overrideElement)) - painter->setAntialiasing(true); - else - painter->setAntialiasing(localAntialiased); + if (mParentPlot && mParentPlot->notAntialiasedElements().testFlag(overrideElement)) { + painter->setAntialiasing(false); + } else if (mParentPlot && mParentPlot->antialiasedElements().testFlag(overrideElement)) { + painter->setAntialiasing(true); + } else { + painter->setAntialiasing(localAntialiased); + } } /*! \internal @@ -1582,20 +1584,20 @@ void QCPLayerable::applyAntialiasingHint(QCPPainter *painter, bool localAntialia This function is called by \ref initializeParentPlot, to allow subclasses to react on the setting of a parent plot. This is the case when 0 was passed as parent plot in the constructor, and the parent plot is set at a later time. - + For example, QCPLayoutElement/QCPLayout hierarchies may be created independently of any QCustomPlot at first. When they are then added to a layout inside the QCustomPlot, the top level element of the hierarchy gets its parent plot initialized with \ref initializeParentPlot. To propagate the parent plot to all the children of the hierarchy, the top level element then uses this function to pass the parent plot on to its child elements. - + The default implementation does nothing. - + \see initializeParentPlot */ void QCPLayerable::parentPlotInitialized(QCustomPlot *parentPlot) { - Q_UNUSED(parentPlot) + Q_UNUSED(parentPlot) } /*! \internal @@ -1603,45 +1605,46 @@ void QCPLayerable::parentPlotInitialized(QCustomPlot *parentPlot) Returns the selection category this layerable shall belong to. The selection category is used in conjunction with \ref QCustomPlot::setInteractions to control which objects are selectable and which aren't. - + Subclasses that don't fit any of the normal \ref QCP::Interaction values can use \ref QCP::iSelectOther. This is what the default implementation returns. - + \see QCustomPlot::setInteractions */ QCP::Interaction QCPLayerable::selectionCategory() const { - return QCP::iSelectOther; + return QCP::iSelectOther; } /*! \internal - + Returns the clipping rectangle of this layerable object. By default, this is the viewport of the parent QCustomPlot. Specific subclasses may reimplement this function to provide different clipping rects. - + The returned clipping rect is set on the painter before the draw function of the respective object is called. */ QRect QCPLayerable::clipRect() const { - if (mParentPlot) - return mParentPlot->viewport(); - else - return QRect(); + if (mParentPlot) { + return mParentPlot->viewport(); + } else { + return QRect(); + } } /*! \internal - + This event is called when the layerable shall be selected, as a consequence of a click by the user. Subclasses should react to it by setting their selection state appropriately. The default implementation does nothing. - + \a event is the mouse event that caused the selection. \a additive indicates, whether the user was holding the multi-select-modifier while performing the selection (see \ref QCustomPlot::setMultiSelectModifier). if \a additive is true, the selection state must be toggled (i.e. become selected when unselected and unselected when selected). - + Every selectEvent is preceded by a call to \ref selectTest, which has returned positively (i.e. returned a value greater than 0 and less than the selection tolerance of the parent QCustomPlot). The \a details data you output from \ref selectTest is fed back via \a details here. You may @@ -1649,39 +1652,39 @@ QRect QCPLayerable::clipRect() const selectEvent. Usually \a details is used to transfer which part was clicked, if it is a layerable that has multiple individually selectable parts (like QCPAxis). This way selectEvent doesn't need to do the calculation again to find out which part was actually clicked. - + \a selectionStateChanged is an output parameter. If the pointer is non-null, this function must set the value either to true or false, depending on whether the selection state of this layerable was actually changed. For layerables that only are selectable as a whole and not in parts, this is simple: if \a additive is true, \a selectionStateChanged must also be set to true, because the selection toggles. If \a additive is false, \a selectionStateChanged is only set to true, if the layerable was previously unselected and now is switched to the selected state. - + \see selectTest, deselectEvent */ void QCPLayerable::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) { - Q_UNUSED(event) - Q_UNUSED(additive) - Q_UNUSED(details) - Q_UNUSED(selectionStateChanged) + Q_UNUSED(event) + Q_UNUSED(additive) + Q_UNUSED(details) + Q_UNUSED(selectionStateChanged) } /*! \internal - + This event is called when the layerable shall be deselected, either as consequence of a user interaction or a call to \ref QCustomPlot::deselectAll. Subclasses should react to it by unsetting their selection appropriately. - + just as in \ref selectEvent, the output parameter \a selectionStateChanged (if non-null), must return true or false when the selection state of this layerable has changed or not changed, respectively. - + \see selectTest, selectEvent */ void QCPLayerable::deselectEvent(bool *selectionStateChanged) { - Q_UNUSED(selectionStateChanged) + Q_UNUSED(selectionStateChanged) } /*! @@ -1711,8 +1714,8 @@ void QCPLayerable::deselectEvent(bool *selectionStateChanged) */ void QCPLayerable::mousePressEvent(QMouseEvent *event, const QVariant &details) { - Q_UNUSED(details) - event->ignore(); + Q_UNUSED(details) + event->ignore(); } /*! @@ -1729,8 +1732,8 @@ void QCPLayerable::mousePressEvent(QMouseEvent *event, const QVariant &details) */ void QCPLayerable::mouseMoveEvent(QMouseEvent *event, const QPointF &startPos) { - Q_UNUSED(startPos) - event->ignore(); + Q_UNUSED(startPos) + event->ignore(); } /*! @@ -1747,8 +1750,8 @@ void QCPLayerable::mouseMoveEvent(QMouseEvent *event, const QPointF &startPos) */ void QCPLayerable::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos) { - Q_UNUSED(startPos) - event->ignore(); + Q_UNUSED(startPos) + event->ignore(); } /*! @@ -1779,8 +1782,8 @@ void QCPLayerable::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos */ void QCPLayerable::mouseDoubleClickEvent(QMouseEvent *event, const QVariant &details) { - Q_UNUSED(details) - event->ignore(); + Q_UNUSED(details) + event->ignore(); } /*! @@ -1802,7 +1805,7 @@ void QCPLayerable::mouseDoubleClickEvent(QMouseEvent *event, const QVariant &det */ void QCPLayerable::wheelEvent(QWheelEvent *event) { - event->ignore(); + event->ignore(); } /* end of 'src/layer.cpp' */ @@ -1815,10 +1818,10 @@ void QCPLayerable::wheelEvent(QWheelEvent *event) //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPRange \brief Represents the range an axis is encompassing. - + contains a \a lower and \a upper double value and provides convenience input, output and modification functions. - + \see QCPAxis::setRange */ @@ -1897,8 +1900,8 @@ const double QCPRange::maxRange = 1e250; Constructs a range with \a lower and \a upper set to zero. */ QCPRange::QCPRange() : - lower(0), - upper(0) + lower(0), + upper(0) { } @@ -1910,10 +1913,10 @@ QCPRange::QCPRange() : smaller than \a upper, they will be swapped. */ QCPRange::QCPRange(double lower, double upper) : - lower(lower), - upper(upper) + lower(lower), + upper(upper) { - normalize(); + normalize(); } /*! \overload @@ -1930,10 +1933,12 @@ QCPRange::QCPRange(double lower, double upper) : */ void QCPRange::expand(const QCPRange &otherRange) { - if (lower > otherRange.lower || qIsNaN(lower)) - lower = otherRange.lower; - if (upper < otherRange.upper || qIsNaN(upper)) - upper = otherRange.upper; + if (lower > otherRange.lower || qIsNaN(lower)) { + lower = otherRange.lower; + } + if (upper < otherRange.upper || qIsNaN(upper)) { + upper = otherRange.upper; + } } /*! \overload @@ -1950,10 +1955,12 @@ void QCPRange::expand(const QCPRange &otherRange) */ void QCPRange::expand(double includeCoord) { - if (lower > includeCoord || qIsNaN(lower)) - lower = includeCoord; - if (upper < includeCoord || qIsNaN(upper)) - upper = includeCoord; + if (lower > includeCoord || qIsNaN(lower)) { + lower = includeCoord; + } + if (upper < includeCoord || qIsNaN(upper)) { + upper = includeCoord; + } } @@ -1969,9 +1976,9 @@ void QCPRange::expand(double includeCoord) */ QCPRange QCPRange::expanded(const QCPRange &otherRange) const { - QCPRange result = *this; - result.expand(otherRange); - return result; + QCPRange result = *this; + result.expand(otherRange); + return result; } /*! \overload @@ -1986,47 +1993,48 @@ QCPRange QCPRange::expanded(const QCPRange &otherRange) const */ QCPRange QCPRange::expanded(double includeCoord) const { - QCPRange result = *this; - result.expand(includeCoord); - return result; + 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; + 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 \a lower will always be numerically smaller (or equal) to \a upper. - + If the original range does span positive and negative sign domains or contains zero, the returned range will try to approximate the original range as good as possible. If the positive interval of the original range is wider than the negative interval, the @@ -2036,47 +2044,46 @@ QCPRange QCPRange::bounded(double lowerBound, double upperBound) const */ QCPRange QCPRange::sanitizedForLogScale() const { - double rangeFac = 1e-3; - QCPRange sanitizedRange(lower, upper); - sanitizedRange.normalize(); - // can't have range spanning negative and positive values in log plot, so change range to fix it - //if (qFuzzyCompare(sanitizedRange.lower+1, 1) && !qFuzzyCompare(sanitizedRange.upper+1, 1)) - if (sanitizedRange.lower == 0.0 && sanitizedRange.upper != 0.0) - { - // case lower is 0 - if (rangeFac < sanitizedRange.upper*rangeFac) - sanitizedRange.lower = rangeFac; - else - sanitizedRange.lower = sanitizedRange.upper*rangeFac; - } //else if (!qFuzzyCompare(lower+1, 1) && qFuzzyCompare(upper+1, 1)) - else if (sanitizedRange.lower != 0.0 && sanitizedRange.upper == 0.0) - { - // case upper is 0 - if (-rangeFac > sanitizedRange.lower*rangeFac) - sanitizedRange.upper = -rangeFac; - else - sanitizedRange.upper = sanitizedRange.lower*rangeFac; - } else if (sanitizedRange.lower < 0 && sanitizedRange.upper > 0) - { - // find out whether negative or positive interval is wider to decide which sign domain will be chosen - if (-sanitizedRange.lower > sanitizedRange.upper) - { - // negative is wider, do same as in case upper is 0 - if (-rangeFac > sanitizedRange.lower*rangeFac) - sanitizedRange.upper = -rangeFac; - else - sanitizedRange.upper = sanitizedRange.lower*rangeFac; - } else - { - // positive is wider, do same as in case lower is 0 - if (rangeFac < sanitizedRange.upper*rangeFac) - sanitizedRange.lower = rangeFac; - else - sanitizedRange.lower = sanitizedRange.upper*rangeFac; + double rangeFac = 1e-3; + QCPRange sanitizedRange(lower, upper); + sanitizedRange.normalize(); + // can't have range spanning negative and positive values in log plot, so change range to fix it + //if (qFuzzyCompare(sanitizedRange.lower+1, 1) && !qFuzzyCompare(sanitizedRange.upper+1, 1)) + if (sanitizedRange.lower == 0.0 && sanitizedRange.upper != 0.0) { + // case lower is 0 + if (rangeFac < sanitizedRange.upper * rangeFac) { + sanitizedRange.lower = rangeFac; + } else { + sanitizedRange.lower = sanitizedRange.upper * rangeFac; + } + } //else if (!qFuzzyCompare(lower+1, 1) && qFuzzyCompare(upper+1, 1)) + else if (sanitizedRange.lower != 0.0 && sanitizedRange.upper == 0.0) { + // case upper is 0 + if (-rangeFac > sanitizedRange.lower * rangeFac) { + sanitizedRange.upper = -rangeFac; + } else { + sanitizedRange.upper = sanitizedRange.lower * rangeFac; + } + } else if (sanitizedRange.lower < 0 && sanitizedRange.upper > 0) { + // find out whether negative or positive interval is wider to decide which sign domain will be chosen + if (-sanitizedRange.lower > sanitizedRange.upper) { + // negative is wider, do same as in case upper is 0 + if (-rangeFac > sanitizedRange.lower * rangeFac) { + sanitizedRange.upper = -rangeFac; + } else { + sanitizedRange.upper = sanitizedRange.lower * rangeFac; + } + } else { + // positive is wider, do same as in case lower is 0 + if (rangeFac < sanitizedRange.upper * rangeFac) { + sanitizedRange.lower = rangeFac; + } else { + sanitizedRange.lower = sanitizedRange.upper * rangeFac; + } + } } - } - // due to normalization, case lower>0 && upper<0 should never occur, because that implies upper0 && upper<0 should never occur, because that implies upper -maxRange && - upper < maxRange && - qAbs(lower-upper) > minRange && - qAbs(lower-upper) < maxRange && - !(lower > 0 && qIsInf(upper/lower)) && - !(upper < 0 && qIsInf(lower/upper))); + return (lower > -maxRange && + upper < maxRange && + qAbs(lower - upper) > minRange && + qAbs(lower - upper) < maxRange && + !(lower > 0 && qIsInf(upper / lower)) && + !(upper < 0 && qIsInf(lower / upper))); } /*! @@ -2119,12 +2126,12 @@ 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 > 0 && qIsInf(range.upper/range.lower)) && - !(range.upper < 0 && qIsInf(range.lower/range.upper))); + 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' */ @@ -2138,26 +2145,26 @@ bool QCPRange::validRange(const QCPRange &range) /*! \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 just after 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. */ @@ -2165,43 +2172,43 @@ bool QCPRange::validRange(const QCPRange &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 after 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 @@ -2210,14 +2217,14 @@ bool QCPRange::validRange(const QCPRange &range) */ /*! \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. */ @@ -2228,26 +2235,26 @@ bool QCPRange::validRange(const QCPRange &range) Creates an empty QCPDataRange, with begin and end set to 0. */ QCPDataRange::QCPDataRange() : - mBegin(0), - mEnd(0) + 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) + 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 @@ -2255,15 +2262,15 @@ QCPDataRange::QCPDataRange(int begin, int end) : */ 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; + 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; } /*! @@ -2271,47 +2278,48 @@ QCPDataRange QCPDataRange::bounded(const QCPDataRange &other) const */ QCPDataRange QCPDataRange::expanded(const QCPDataRange &other) const { - return QCPDataRange(qMin(mBegin, other.mBegin), qMax(mEnd, other.mEnd)); + 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(); + 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) ); + return !((mBegin > other.mBegin && mBegin >= other.mEnd) || + (mEnd <= other.mBegin && mEnd < other.mEnd)); } /*! Returns whether all data points of \a other are also contained inside this data range. - + \see intersects */ bool QCPDataRange::contains(const QCPDataRange &other) const { - return mBegin <= other.mBegin && mEnd >= other.mEnd; + return mBegin <= other.mBegin && mEnd >= other.mEnd; } @@ -2322,14 +2330,14 @@ bool QCPDataRange::contains(const QCPDataRange &other) const /*! \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 @@ -2337,46 +2345,46 @@ bool QCPDataRange::contains(const QCPDataRange &other) const 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 */ @@ -2394,7 +2402,7 @@ QCPDataSelection::QCPDataSelection() */ QCPDataSelection::QCPDataSelection(const QCPDataRange &range) { - mDataRanges.append(range); + mDataRanges.append(range); } /*! @@ -2406,14 +2414,15 @@ QCPDataSelection::QCPDataSelection(const QCPDataRange &range) */ 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 - } - } + if (other.isEmpty() || isEmpty()) { + return *this; } - ++i; - } - - return *this; + + simplify(); + int i = 0; + while (i < mDataRanges.size()) { + const int thisBegin = mDataRanges.at(i).begin(); + const int thisEnd = mDataRanges.at(i).end(); + if (thisBegin >= other.end()) { + break; // since data ranges are sorted after the simplify() call, no ranges which contain other will come after this + } + + if (thisEnd > other.begin()) { // ranges which don't fulfill this are entirely before other and can be ignored + if (thisBegin >= other.begin()) { // range leading segment is encompassed + if (thisEnd <= other.end()) { // range fully encompassed, remove completely + mDataRanges.removeAt(i); + continue; + } else { // only leading segment is encompassed, trim accordingly + mDataRanges[i].setBegin(other.end()); + } + } else { // leading segment is not encompassed + if (thisEnd <= other.end()) { // only trailing segment is encompassed, trim accordingly + mDataRanges[i].setEnd(other.begin()); + } else { // other lies inside this range, so split range + mDataRanges[i].setEnd(other.begin()); + mDataRanges.insert(i + 1, QCPDataRange(other.end(), thisEnd)); + break; // since data ranges are sorted (and don't overlap) after simplify() call, we're done here + } + } + } + ++i; + } + + return *this; } /*! @@ -2500,30 +2506,29 @@ QCPDataSelection &QCPDataSelection::operator-=(const QCPDataRange &other) */ 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(); - } + if (index >= 0 && index < mDataRanges.size()) { + return mDataRanges.at(index); + } else { + qDebug() << Q_FUNC_INFO << "index out of range:" << index; + return QCPDataRange(); + } } /*! @@ -2532,10 +2537,11 @@ QCPDataRange QCPDataSelection::dataRange(int index) const */ QCPDataRange QCPDataSelection::span() const { - if (isEmpty()) - return QCPDataRange(); - else - return QCPDataRange(mDataRanges.first().begin(), mDataRanges.last().end()); + if (isEmpty()) { + return QCPDataRange(); + } else { + return QCPDataRange(mDataRanges.first().begin(), mDataRanges.last().end()); + } } /*! @@ -2546,19 +2552,20 @@ QCPDataRange QCPDataSelection::span() const */ void QCPDataSelection::addDataRange(const QCPDataRange &dataRange, bool simplify) { - mDataRanges.append(dataRange); - if (simplify) - this->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(); + mDataRanges.clear(); } /*! @@ -2572,102 +2579,100 @@ void QCPDataSelection::clear() */ 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; - } + // 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; + 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: { + if (!isEmpty()) { + mDataRanges = QList() << span(); + } + break; + } + case QCP::stMultipleDataRanges: { + // this is the selection type that allows all concievable combinations of ranges, so do nothing + 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: - { - if (!isEmpty()) - 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 + 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 } /*! @@ -2680,11 +2685,12 @@ bool QCPDataSelection::contains(const QCPDataSelection &other) const */ 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(); - } + if (axis) { + if (axis->orientation() == Qt::Horizontal) { + return QCPRange(axis->pixelToCoord(mRect.left()), axis->pixelToCoord(mRect.left() + mRect.width())); + } else { + return QCPRange(axis->pixelToCoord(mRect.top() + mRect.height()), axis->pixelToCoord(mRect.top())); + } + } else { + qDebug() << Q_FUNC_INFO << "called with axis zero"; + return QCPRange(); + } } /*! Sets the pen that will be used to draw the selection rect outline. - + \see setBrush */ void QCPSelectionRect::setPen(const QPen &pen) { - mPen = pen; + 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; + mBrush = brush; } /*! @@ -2875,87 +2885,84 @@ void QCPSelectionRect::setBrush(const QBrush &brush) */ void QCPSelectionRect::cancel() { - if (mActive) - { - mActive = false; - emit canceled(mRect, 0); - } + 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); + 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(); + 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); + 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); - } + 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); + 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); - } + if (mActive) { + painter->setPen(mPen); + painter->setBrush(mBrush); + painter->drawRect(mRect); + } } /* end of 'src/selectionrect.cpp' */ @@ -2969,27 +2976,27 @@ void QCPSelectionRect::draw(QCPPainter *painter) /*! \class QCPMarginGroup \brief A margin group allows synchronization of margin sides if working with multiple layout elements. - + QCPMarginGroup allows you to tie a margin side of two or more layout elements together, such that they will all have the same size, based on the largest required margin in the group. - + \n \image html QCPMarginGroup.png "Demonstration of QCPMarginGroup" \n - + In certain situations it is desirable that margins at specific sides are synchronized across layout elements. For example, if one QCPAxisRect is below another one in a grid layout, it will provide a cleaner look to the user if the left and right margins of the two axis rects are of the same size. The left axis of the top axis rect will then be at the same horizontal position as the left axis of the lower axis rect, making them appear aligned. The same applies for the right axes. This is what QCPMarginGroup makes possible. - + To add/remove a specific side of a layout element to/from a margin group, use the \ref QCPLayoutElement::setMarginGroup method. To completely break apart the margin group, either call \ref clear, or just delete the margin group. - + \section QCPMarginGroup-example Example - + First create a margin group: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpmargingroup-creation-1 Then set this group on the layout element sides: @@ -3001,7 +3008,7 @@ void QCPSelectionRect::draw(QCPPainter *painter) /* start documentation of inline functions */ /*! \fn QList QCPMarginGroup::elements(QCP::MarginSide side) const - + Returns a list of all layout elements that have their margin \a side associated with this margin group. */ @@ -3012,18 +3019,18 @@ void QCPSelectionRect::draw(QCPPainter *painter) Creates a new QCPMarginGroup instance in \a parentPlot. */ QCPMarginGroup::QCPMarginGroup(QCustomPlot *parentPlot) : - QObject(parentPlot), - mParentPlot(parentPlot) + QObject(parentPlot), + mParentPlot(parentPlot) { - mChildren.insert(QCP::msLeft, QList()); - mChildren.insert(QCP::msRight, QList()); - mChildren.insert(QCP::msTop, QList()); - mChildren.insert(QCP::msBottom, QList()); + mChildren.insert(QCP::msLeft, QList()); + mChildren.insert(QCP::msRight, QList()); + mChildren.insert(QCP::msTop, QList()); + mChildren.insert(QCP::msBottom, QList()); } QCPMarginGroup::~QCPMarginGroup() { - clear(); + clear(); } /*! @@ -3032,14 +3039,14 @@ QCPMarginGroup::~QCPMarginGroup() */ bool QCPMarginGroup::isEmpty() const { - QHashIterator > it(mChildren); - while (it.hasNext()) - { - it.next(); - if (!it.value().isEmpty()) - return false; - } - return true; + QHashIterator > it(mChildren); + while (it.hasNext()) { + it.next(); + if (!it.value().isEmpty()) { + return false; + } + } + return true; } /*! @@ -3048,22 +3055,22 @@ bool QCPMarginGroup::isEmpty() const */ void QCPMarginGroup::clear() { - // make all children remove themselves from this margin group: - QHashIterator > it(mChildren); - while (it.hasNext()) - { - it.next(); - const QList elements = it.value(); - for (int i=elements.size()-1; i>=0; --i) - elements.at(i)->setMarginGroup(it.key(), 0); // removes itself from mChildren via removeChild - } + // make all children remove themselves from this margin group: + QHashIterator > it(mChildren); + while (it.hasNext()) { + it.next(); + const QList elements = it.value(); + for (int i = elements.size() - 1; i >= 0; --i) { + elements.at(i)->setMarginGroup(it.key(), 0); // removes itself from mChildren via removeChild + } + } } /*! \internal - + Returns the synchronized common margin for \a side. This is the margin value that will be used by the layout element on the respective side, if it is part of this margin group. - + The common margin is calculated by requesting the automatic margin (\ref QCPLayoutElement::calculateAutoMargin) of each element associated with \a side in this margin group, and choosing the largest returned value. (QCPLayoutElement::minimumMargins is taken into @@ -3071,44 +3078,47 @@ void QCPMarginGroup::clear() */ int QCPMarginGroup::commonMargin(QCP::MarginSide side) const { - // query all automatic margins of the layout elements in this margin group side and find maximum: - int result = 0; - const QList elements = mChildren.value(side); - for (int i=0; iautoMargins().testFlag(side)) - continue; - int m = qMax(elements.at(i)->calculateAutoMargin(side), QCP::getMarginValue(elements.at(i)->minimumMargins(), side)); - if (m > result) - result = m; - } - return result; + // query all automatic margins of the layout elements in this margin group side and find maximum: + int result = 0; + const QList elements = mChildren.value(side); + for (int i = 0; i < elements.size(); ++i) { + if (!elements.at(i)->autoMargins().testFlag(side)) { + continue; + } + int m = qMax(elements.at(i)->calculateAutoMargin(side), QCP::getMarginValue(elements.at(i)->minimumMargins(), side)); + if (m > result) { + result = m; + } + } + return result; } /*! \internal - + Adds \a element to the internal list of child elements, for the margin \a side. - + This function does not modify the margin group property of \a element. */ void QCPMarginGroup::addChild(QCP::MarginSide side, QCPLayoutElement *element) { - if (!mChildren[side].contains(element)) - mChildren[side].append(element); - else - qDebug() << Q_FUNC_INFO << "element is already child of this margin group side" << reinterpret_cast(element); + if (!mChildren[side].contains(element)) { + mChildren[side].append(element); + } else { + qDebug() << Q_FUNC_INFO << "element is already child of this margin group side" << reinterpret_cast(element); + } } /*! \internal - + Removes \a element from the internal list of child elements, for the margin \a side. - + This function does not modify the margin group property of \a element. */ void QCPMarginGroup::removeChild(QCP::MarginSide side, QCPLayoutElement *element) { - if (!mChildren[side].removeOne(element)) - qDebug() << Q_FUNC_INFO << "element is not child of this margin group side" << reinterpret_cast(element); + if (!mChildren[side].removeOne(element)) { + qDebug() << Q_FUNC_INFO << "element is not child of this margin group side" << reinterpret_cast(element); + } } @@ -3118,20 +3128,20 @@ void QCPMarginGroup::removeChild(QCP::MarginSide side, QCPLayoutElement *element /*! \class QCPLayoutElement \brief The abstract base class for all objects that form \ref thelayoutsystem "the layout system". - + This is an abstract base class. As such, it can't be instantiated directly, rather use one of its subclasses. - + A Layout element is a rectangular object which can be placed in layouts. It has an outer rect (QCPLayoutElement::outerRect) and an inner rect (\ref QCPLayoutElement::rect). The difference between outer and inner rect is called its margin. The margin can either be set to automatic or manual (\ref setAutoMargins) on a per-side basis. If a side is set to manual, that margin can be set explicitly with \ref setMargins and will stay fixed at that value. If it's set to automatic, the layout element subclass will control the value itself (via \ref calculateAutoMargin). - + Layout elements can be placed in layouts (base class QCPLayout) like QCPLayoutGrid. The top level layout is reachable via \ref QCustomPlot::plotLayout, and is a \ref QCPLayoutGrid. Since \ref QCPLayout itself derives from \ref QCPLayoutElement, layouts can be nested. - + Thus in QCustomPlot one can divide layout elements into two categories: The ones that are 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 @@ -3145,31 +3155,31 @@ void QCPMarginGroup::removeChild(QCP::MarginSide side, QCPLayoutElement *element /* start documentation of inline functions */ /*! \fn QCPLayout *QCPLayoutElement::layout() const - + Returns the parent layout of this layout element. */ /*! \fn QRect QCPLayoutElement::rect() const - + Returns the inner rect of this layout element. The inner rect is the outer rect (\ref outerRect, \ref setOuterRect) shrinked by the margins (\ref setMargins, \ref setAutoMargins). - + In some cases, the area between outer and inner rect is left blank. In other cases the margin area is used to display peripheral graphics while the main content is in the inner rect. This is where automatic margin calculation becomes interesting because it allows the layout element to adapt the margins to the peripheral graphics it wants to draw. For example, \ref QCPAxisRect draws the axis labels and tick labels in the margin area, thus needs to adjust the margins (if \ref setAutoMargins is enabled) according to the space required by the labels of the axes. - + \see outerRect */ /*! \fn QRect QCPLayoutElement::outerRect() const - + Returns the outer rect of this layout element. The outer rect is the inner rect expanded by the margins (\ref setMargins, \ref setAutoMargins). The outer rect is used (and set via \ref setOuterRect) by the parent \ref QCPLayout to control the size of this layout element. - + \see rect */ @@ -3179,221 +3189,224 @@ void QCPMarginGroup::removeChild(QCP::MarginSide side, QCPLayoutElement *element Creates an instance of QCPLayoutElement and sets default values. */ QCPLayoutElement::QCPLayoutElement(QCustomPlot *parentPlot) : - QCPLayerable(parentPlot), // parenthood is changed as soon as layout element gets inserted into a layout (except for top level layout) - mParentLayout(0), - mMinimumSize(), - mMaximumSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX), - mSizeConstraintRect(scrInnerRect), - mRect(0, 0, 0, 0), - mOuterRect(0, 0, 0, 0), - mMargins(0, 0, 0, 0), - mMinimumMargins(0, 0, 0, 0), - mAutoMargins(QCP::msAll) + QCPLayerable(parentPlot), // parenthood is changed as soon as layout element gets inserted into a layout (except for top level layout) + mParentLayout(0), + mMinimumSize(), + mMaximumSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX), + mSizeConstraintRect(scrInnerRect), + mRect(0, 0, 0, 0), + mOuterRect(0, 0, 0, 0), + mMargins(0, 0, 0, 0), + mMinimumMargins(0, 0, 0, 0), + mAutoMargins(QCP::msAll) { } QCPLayoutElement::~QCPLayoutElement() { - setMarginGroup(QCP::msAll, 0); // unregister at margin groups, if there are any - // unregister at layout: - if (qobject_cast(mParentLayout)) // the qobject_cast is just a safeguard in case the layout forgets to call clear() in its dtor and this dtor is called by QObject dtor - mParentLayout->take(this); + setMarginGroup(QCP::msAll, 0); // unregister at margin groups, if there are any + // unregister at layout: + if (qobject_cast(mParentLayout)) { // the qobject_cast is just a safeguard in case the layout forgets to call clear() in its dtor and this dtor is called by QObject dtor + mParentLayout->take(this); + } } /*! Sets the outer rect of this layout element. If the layout element is inside a layout, the layout sets the position and size of this layout element using this function. - + Calling this function externally has no effect, since the layout will overwrite any changes to the outer rect upon the next replot. - + The layout element will adapt its inner \ref rect by applying the margins inward to the outer rect. - + \see rect */ void QCPLayoutElement::setOuterRect(const QRect &rect) { - if (mOuterRect != rect) - { - mOuterRect = rect; - mRect = mOuterRect.adjusted(mMargins.left(), mMargins.top(), -mMargins.right(), -mMargins.bottom()); - } + if (mOuterRect != rect) { + mOuterRect = rect; + mRect = mOuterRect.adjusted(mMargins.left(), mMargins.top(), -mMargins.right(), -mMargins.bottom()); + } } /*! Sets the margins of this layout element. If \ref setAutoMargins is disabled for some or all sides, this function is used to manually set the margin on those sides. Sides that are still set to be handled automatically are ignored and may have any value in \a margins. - + The margin is the distance between the outer rect (controlled by the parent layout via \ref setOuterRect) and the inner \ref rect (which usually contains the main content of this layout element). - + \see setAutoMargins */ void QCPLayoutElement::setMargins(const QMargins &margins) { - if (mMargins != margins) - { - mMargins = margins; - mRect = mOuterRect.adjusted(mMargins.left(), mMargins.top(), -mMargins.right(), -mMargins.bottom()); - } + if (mMargins != margins) { + mMargins = margins; + mRect = mOuterRect.adjusted(mMargins.left(), mMargins.top(), -mMargins.right(), -mMargins.bottom()); + } } /*! If \ref setAutoMargins is enabled on some or all margins, this function is used to provide minimum values for those margins. - + The minimum values are not enforced on margin sides that were set to be under manual control via \ref setAutoMargins. - + \see setAutoMargins */ void QCPLayoutElement::setMinimumMargins(const QMargins &margins) { - if (mMinimumMargins != margins) - { - mMinimumMargins = margins; - } + if (mMinimumMargins != margins) { + mMinimumMargins = margins; + } } /*! Sets on which sides the margin shall be calculated automatically. If a side is calculated automatically, a minimum margin value may be provided with \ref setMinimumMargins. If a side is set to be controlled manually, the value may be specified with \ref setMargins. - + 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, QCP::MarginSide */ void QCPLayoutElement::setAutoMargins(QCP::MarginSides sides) { - mAutoMargins = sides; + mAutoMargins = sides; } /*! Sets the minimum size of this layout element. A parent layout tries to respect the \a size here by changing row/column sizes in the layout accordingly. - + If the parent layout size is not sufficient to satisfy all minimum size constraints of its child layout elements, the layout may set a size that is actually smaller than \a size. QCustomPlot propagates the layout's size constraints to the outside by setting its own minimum QWidget size accordingly, so violations of \a size should be exceptions. - + Whether this constraint applies to the inner or the outer rect can be specified with \ref setSizeConstraintRect (see \ref rect and \ref outerRect). */ void QCPLayoutElement::setMinimumSize(const QSize &size) { - if (mMinimumSize != size) - { - mMinimumSize = size; - if (mParentLayout) - mParentLayout->sizeConstraintsChanged(); - } + if (mMinimumSize != size) { + mMinimumSize = size; + if (mParentLayout) { + mParentLayout->sizeConstraintsChanged(); + } + } } /*! \overload - + Sets the minimum size of this layout element. - + Whether this constraint applies to the inner or the outer rect can be specified with \ref setSizeConstraintRect (see \ref rect and \ref outerRect). */ void QCPLayoutElement::setMinimumSize(int width, int height) { - setMinimumSize(QSize(width, height)); + setMinimumSize(QSize(width, height)); } /*! Sets the maximum size of this layout element. A parent layout tries to respect the \a size here by changing row/column sizes in the layout accordingly. - + Whether this constraint applies to the inner or the outer rect can be specified with \ref setSizeConstraintRect (see \ref rect and \ref outerRect). */ void QCPLayoutElement::setMaximumSize(const QSize &size) { - if (mMaximumSize != size) - { - mMaximumSize = size; - if (mParentLayout) - mParentLayout->sizeConstraintsChanged(); - } + if (mMaximumSize != size) { + mMaximumSize = size; + if (mParentLayout) { + mParentLayout->sizeConstraintsChanged(); + } + } } /*! \overload - + Sets the maximum size of this layout element. - + Whether this constraint applies to the inner or the outer rect can be specified with \ref setSizeConstraintRect (see \ref rect and \ref outerRect). */ void QCPLayoutElement::setMaximumSize(int width, int height) { - setMaximumSize(QSize(width, height)); + setMaximumSize(QSize(width, height)); } /*! Sets to which rect of a layout element the size constraints apply. Size constraints can be set via \ref setMinimumSize and \ref setMaximumSize. - + The outer rect (\ref outerRect) includes the margins (e.g. in the case of a QCPAxisRect the axis labels), whereas the inner rect (\ref rect) does not. - + \see setMinimumSize, setMaximumSize */ void QCPLayoutElement::setSizeConstraintRect(SizeConstraintRect constraintRect) { - if (mSizeConstraintRect != constraintRect) - { - mSizeConstraintRect = constraintRect; - if (mParentLayout) - mParentLayout->sizeConstraintsChanged(); - } + if (mSizeConstraintRect != constraintRect) { + mSizeConstraintRect = constraintRect; + if (mParentLayout) { + mParentLayout->sizeConstraintsChanged(); + } + } } /*! Sets the margin \a group of the specified margin \a sides. - + Margin groups allow synchronizing specified margins across layout elements, see the documentation of \ref QCPMarginGroup. - + To unset the margin group of \a sides, set \a group to 0. - + 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) { - QVector sideVector; - if (sides.testFlag(QCP::msLeft)) sideVector.append(QCP::msLeft); - if (sides.testFlag(QCP::msRight)) sideVector.append(QCP::msRight); - if (sides.testFlag(QCP::msTop)) sideVector.append(QCP::msTop); - if (sides.testFlag(QCP::msBottom)) sideVector.append(QCP::msBottom); - - for (int i=0; iremoveChild(side, this); - - if (!group) // if setting to 0, remove hash entry. Else set hash entry to new group and register there - { - mMarginGroups.remove(side); - } else // setting to a new group - { - mMarginGroups[side] = group; - group->addChild(side, this); - } + QVector sideVector; + if (sides.testFlag(QCP::msLeft)) { + sideVector.append(QCP::msLeft); + } + if (sides.testFlag(QCP::msRight)) { + sideVector.append(QCP::msRight); + } + if (sides.testFlag(QCP::msTop)) { + sideVector.append(QCP::msTop); + } + if (sides.testFlag(QCP::msBottom)) { + sideVector.append(QCP::msBottom); + } + + for (int i = 0; i < sideVector.size(); ++i) { + QCP::MarginSide side = sideVector.at(i); + if (marginGroup(side) != group) { + QCPMarginGroup *oldGroup = marginGroup(side); + if (oldGroup) { // unregister at old group + oldGroup->removeChild(side, this); + } + + if (!group) { // if setting to 0, remove hash entry. Else set hash entry to new group and register there + mMarginGroups.remove(side); + } else { // setting to a new group + mMarginGroups[side] = group; + group->addChild(side, this); + } + } } - } } /*! @@ -3401,89 +3414,87 @@ void QCPLayoutElement::setMarginGroup(QCP::MarginSides sides, QCPMarginGroup *gr replot by the parent layout element. It is called multiple times, once for every \ref UpdatePhase. The phases are run through in the order of the enum values. For details about what happens at the different phases, see the documentation of \ref UpdatePhase. - + Layout elements that have child elements should call the \ref update method of their child elements, and pass the current \a phase unchanged. - + The default implementation executes the automatic margin mechanism in the \ref upMargins phase. Subclasses should make sure to call the base class implementation. */ void QCPLayoutElement::update(UpdatePhase phase) { - if (phase == upMargins) - { - if (mAutoMargins != QCP::msNone) - { - // set the margins of this layout element according to automatic margin calculation, either directly or via a margin group: - QMargins newMargins = mMargins; - QList allMarginSides = QList() << QCP::msLeft << QCP::msRight << QCP::msTop << QCP::msBottom; - foreach (QCP::MarginSide side, allMarginSides) - { - if (mAutoMargins.testFlag(side)) // this side's margin shall be calculated automatically - { - if (mMarginGroups.contains(side)) - QCP::setMarginValue(newMargins, side, mMarginGroups[side]->commonMargin(side)); // this side is part of a margin group, so get the margin value from that group - else - QCP::setMarginValue(newMargins, side, calculateAutoMargin(side)); // this side is not part of a group, so calculate the value directly - // apply minimum margin restrictions: - if (QCP::getMarginValue(newMargins, side) < QCP::getMarginValue(mMinimumMargins, side)) - QCP::setMarginValue(newMargins, side, QCP::getMarginValue(mMinimumMargins, side)); + if (phase == upMargins) { + if (mAutoMargins != QCP::msNone) { + // set the margins of this layout element according to automatic margin calculation, either directly or via a margin group: + QMargins newMargins = mMargins; + QList allMarginSides = QList() << QCP::msLeft << QCP::msRight << QCP::msTop << QCP::msBottom; + foreach (QCP::MarginSide side, allMarginSides) { + if (mAutoMargins.testFlag(side)) { // this side's margin shall be calculated automatically + if (mMarginGroups.contains(side)) { + QCP::setMarginValue(newMargins, side, mMarginGroups[side]->commonMargin(side)); // this side is part of a margin group, so get the margin value from that group + } else { + QCP::setMarginValue(newMargins, side, calculateAutoMargin(side)); // this side is not part of a group, so calculate the value directly + } + // apply minimum margin restrictions: + if (QCP::getMarginValue(newMargins, side) < QCP::getMarginValue(mMinimumMargins, side)) { + QCP::setMarginValue(newMargins, side, QCP::getMarginValue(mMinimumMargins, side)); + } + } + } + setMargins(newMargins); } - } - setMargins(newMargins); } - } } /*! Returns the suggested minimum size this layout element (the \ref outerRect) may be compressed to, if no manual minimum size is set. - + if a minimum size (\ref setMinimumSize) was not set manually, parent layouts use the returned size (usually indirectly through \ref QCPLayout::getFinalMinimumOuterSize) to determine the minimum allowed size of this layout element. A manual minimum size is considered set if it is non-zero. - + The default implementation simply returns the sum of the horizontal margins for the width and the sum of the vertical margins for the height. Reimplementations may use their detailed knowledge about the layout element's content to provide size hints. */ QSize QCPLayoutElement::minimumOuterSizeHint() const { - return QSize(mMargins.left()+mMargins.right(), mMargins.top()+mMargins.bottom()); + return QSize(mMargins.left() + mMargins.right(), mMargins.top() + mMargins.bottom()); } /*! Returns the suggested maximum size this layout element (the \ref outerRect) may be expanded to, if no manual maximum size is set. - + if a maximum size (\ref setMaximumSize) was not set manually, parent layouts use the returned size (usually indirectly through \ref QCPLayout::getFinalMaximumOuterSize) to determine the maximum allowed size of this layout element. A manual maximum size is considered set if it is smaller than Qt's \c QWIDGETSIZE_MAX. - + The default implementation simply returns \c QWIDGETSIZE_MAX for both width and height, implying no suggested maximum size. Reimplementations may use their detailed knowledge about the layout element's content to provide size hints. */ QSize QCPLayoutElement::maximumOuterSizeHint() const { - return QSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX); + return QSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX); } /*! Returns a list of all child elements in this layout element. If \a recursive is true, all sub-child elements are included in the list, too. - + \warning There may be entries with value 0 in the returned list. (For example, QCPLayoutGrid may have empty cells which yield 0 at the respective index.) */ -QList QCPLayoutElement::elements(bool recursive) const +QList QCPLayoutElement::elements(bool recursive) const { - Q_UNUSED(recursive) - return QList(); + Q_UNUSED(recursive) + return QList(); } /*! @@ -3491,69 +3502,69 @@ QList QCPLayoutElement::elements(bool recursive) const rect, this method returns a value corresponding to 0.99 times the parent plot's selection tolerance. However, layout elements are not selectable by default. So if \a onlySelectable is true, -1.0 is returned. - + See \ref QCPLayerable::selectTest for a general explanation of this virtual method. - + QCPLayoutElement subclasses may reimplement this method to provide more specific selection test behaviour. */ double QCPLayoutElement::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { - Q_UNUSED(details) - - if (onlySelectable) - return -1; - - if (QRectF(mOuterRect).contains(pos)) - { - if (mParentPlot) - return mParentPlot->selectionTolerance()*0.99; - else - { - qDebug() << Q_FUNC_INFO << "parent plot not defined"; - return -1; + Q_UNUSED(details) + + if (onlySelectable) { + return -1; + } + + if (QRectF(mOuterRect).contains(pos)) { + if (mParentPlot) { + return mParentPlot->selectionTolerance() * 0.99; + } else { + qDebug() << Q_FUNC_INFO << "parent plot not defined"; + return -1; + } + } else { + return -1; } - } else - return -1; } /*! \internal - + propagates the parent plot initialization to all child elements, by calling \ref QCPLayerable::initializeParentPlot on them. */ void QCPLayoutElement::parentPlotInitialized(QCustomPlot *parentPlot) { - foreach (QCPLayoutElement* el, elements(false)) - { - if (!el->parentPlot()) - el->initializeParentPlot(parentPlot); - } + foreach (QCPLayoutElement *el, elements(false)) { + if (!el->parentPlot()) { + el->initializeParentPlot(parentPlot); + } + } } /*! \internal - + Returns the margin size for this \a side. It is used if automatic margins is enabled for this \a side (see \ref setAutoMargins). If a minimum margin was set with \ref setMinimumMargins, the returned value will not be smaller than the specified minimum margin. - + The default implementation just returns the respective manual margin (\ref setMargins) or the minimum margin, whichever is larger. */ int QCPLayoutElement::calculateAutoMargin(QCP::MarginSide side) { - return qMax(QCP::getMarginValue(mMargins, side), QCP::getMarginValue(mMinimumMargins, 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() @@ -3566,23 +3577,23 @@ void QCPLayoutElement::layoutChanged() /*! \class QCPLayout \brief The abstract base class for layouts - + This is an abstract base class for layout elements whose main purpose is to define the position and size of other child layout elements. In most cases, layouts don't draw anything themselves (but there are exceptions to this, e.g. QCPLegend). - + QCPLayout derives from QCPLayoutElement, and thus can itself be nested in other layouts. - + QCPLayout introduces a common interface for accessing and manipulating the child elements. Those functions are most notably \ref elementCount, \ref elementAt, \ref takeAt, \ref take, \ref simplify, \ref removeAt, \ref remove and \ref clear. Individual subclasses may add more functions to this interface which are more specialized to the form of the layout. For example, \ref QCPLayoutGrid adds functions that take row and column indices to access cells of the layout grid more conveniently. - + Since this is an abstract base class, you can't instantiate it directly. Rather use one of its subclasses like QCPLayoutGrid or QCPLayoutInset. - + For a general introduction to the layout system, see the dedicated documentation page \ref thelayoutsystem "The Layout System". */ @@ -3590,44 +3601,44 @@ void QCPLayoutElement::layoutChanged() /* start documentation of pure virtual functions */ /*! \fn virtual int QCPLayout::elementCount() const = 0 - + Returns the number of elements/cells in the layout. - + \see elements, elementAt */ /*! \fn virtual QCPLayoutElement* QCPLayout::elementAt(int index) const = 0 - + Returns the element in the cell with the given \a index. If \a index is invalid, returns 0. - + Note that even if \a index is valid, the respective cell may be empty in some layouts (e.g. QCPLayoutGrid), so this function may return 0 in those cases. You may use this function to check whether a cell is empty or not. - + \see elements, elementCount, takeAt */ /*! \fn virtual QCPLayoutElement* QCPLayout::takeAt(int index) = 0 - + Removes the element with the given \a index from the layout and returns it. - + If the \a index is invalid or the cell with that index is empty, returns 0. - + Note that some layouts don't remove the respective cell right away but leave an empty cell after successful removal of the layout element. To collapse empty cells, use \ref simplify. - + \see elementAt, take */ /*! \fn virtual bool QCPLayout::take(QCPLayoutElement* element) = 0 - + Removes the specified \a element from the layout and returns true on success. - + If the \a element isn't in this layout, returns false. - + Note that some layouts don't remove the respective cell right away but leave an empty cell after successful removal of the layout element. To collapse empty cells, use \ref simplify. - + \see takeAt */ @@ -3644,54 +3655,55 @@ QCPLayout::QCPLayout() /*! If \a phase is \ref upLayout, calls \ref updateLayout, which subclasses may reimplement to reposition and resize their cells. - + Finally, the call is propagated down to all child \ref QCPLayoutElement "QCPLayoutElements". - + For details about this method and the update phases, see the documentation of \ref QCPLayoutElement::update. */ void QCPLayout::update(UpdatePhase phase) { - QCPLayoutElement::update(phase); - - // set child element rects according to layout: - if (phase == upLayout) - updateLayout(); - - // propagate update call to child elements: - const int elCount = elementCount(); - for (int i=0; iupdate(phase); - } + QCPLayoutElement::update(phase); + + // set child element rects according to layout: + if (phase == upLayout) { + updateLayout(); + } + + // propagate update call to child elements: + const int elCount = elementCount(); + for (int i = 0; i < elCount; ++i) { + if (QCPLayoutElement *el = elementAt(i)) { + el->update(phase); + } + } } /* inherits documentation from base class */ -QList QCPLayout::elements(bool recursive) const +QList QCPLayout::elements(bool recursive) const { - const int c = elementCount(); - QList result; + const int c = elementCount(); + QList result; #if QT_VERSION >= QT_VERSION_CHECK(4, 7, 0) - result.reserve(c); + result.reserve(c); #endif - for (int i=0; ielements(recursive); + for (int i = 0; i < c; ++i) { + result.append(elementAt(i)); } - } - return result; + if (recursive) { + for (int i = 0; i < c; ++i) { + if (result.at(i)) { + result << result.at(i)->elements(recursive); + } + } + } + return result; } /*! Simplifies the layout by collapsing empty cells. The exact behavior depends on subclasses, the default implementation does nothing. - + Not all layouts need simplification. For example, QCPLayoutInset doesn't use explicit simplification while QCPLayoutGrid does. */ @@ -3702,64 +3714,64 @@ void QCPLayout::simplify() /*! Removes and deletes the element at the provided \a index. Returns true on success. If \a index is invalid or points to an empty cell, returns false. - + This function internally uses \ref takeAt to remove the element from the layout and then deletes the returned element. Note that some layouts don't remove the respective cell right away but leave an empty cell after successful removal of the layout element. To collapse empty cells, use \ref simplify. - + \see remove, takeAt */ bool QCPLayout::removeAt(int index) { - if (QCPLayoutElement *el = takeAt(index)) - { - delete el; - return true; - } else - return false; + if (QCPLayoutElement *el = takeAt(index)) { + delete el; + return true; + } else { + return false; + } } /*! Removes and deletes the provided \a element. Returns true on success. If \a element is not in the layout, returns false. - + This function internally uses \ref takeAt to remove the element from the layout and then deletes the element. Note that some layouts don't remove the respective cell right away but leave an empty cell after successful removal of the layout element. To collapse empty cells, use \ref simplify. - + \see removeAt, take */ bool QCPLayout::remove(QCPLayoutElement *element) { - if (take(element)) - { - delete element; - return true; - } else - return false; + if (take(element)) { + delete element; + return true; + } else { + return false; + } } /*! Removes and deletes all layout elements in this layout. Finally calls \ref simplify to make sure all empty cells are collapsed. - + \see remove, removeAt */ void QCPLayout::clear() { - for (int i=elementCount()-1; i>=0; --i) - { - if (elementAt(i)) - removeAt(i); - } - simplify(); + for (int i = elementCount() - 1; i >= 0; --i) { + if (elementAt(i)) { + removeAt(i); + } + } + simplify(); } /*! Subclasses call this method to report changed (minimum/maximum) size constraints. - + If the parent of this layout is again a QCPLayout, forwards the call to the parent's \ref sizeConstraintsChanged. If the parent is a QWidget (i.e. is the \ref QCustomPlot::plotLayout of QCustomPlot), calls QWidget::updateGeometry, so if the QCustomPlot widget is inside a Qt QLayout, @@ -3767,22 +3779,23 @@ void QCPLayout::clear() */ void QCPLayout::sizeConstraintsChanged() const { - if (QWidget *w = qobject_cast(parent())) - w->updateGeometry(); - else if (QCPLayout *l = qobject_cast(parent())) - l->sizeConstraintsChanged(); + if (QWidget *w = qobject_cast(parent())) { + w->updateGeometry(); + } else if (QCPLayout *l = qobject_cast(parent())) { + l->sizeConstraintsChanged(); + } } /*! \internal - + Subclasses reimplement this method to update the position and sizes of the child elements/cells via calling their \ref QCPLayoutElement::setOuterRect. The default implementation does nothing. - + The geometry used as a reference is the inner \ref rect of this layout. Child elements should stay within that rect. - + \ref getSectionSizes may help with the reimplementation of this function. - + \see update */ void QCPLayout::updateLayout() @@ -3791,202 +3804,200 @@ void QCPLayout::updateLayout() /*! \internal - + Associates \a el with this layout. This is done by setting the \ref QCPLayoutElement::layout, the \ref QCPLayerable::parentLayerable and the QObject parent to this layout. - + Further, if \a el didn't previously have a parent plot, calls \ref QCPLayerable::initializeParentPlot on \a el to set the paret plot. - + This method is used by subclass specific methods that add elements to the layout. Note that this method only changes properties in \a el. The removal from the old layout and the insertion into the new layout must be done additionally. */ void QCPLayout::adoptElement(QCPLayoutElement *el) { - if (el) - { - el->mParentLayout = this; - el->setParentLayerable(this); - el->setParent(this); - if (!el->parentPlot()) - el->initializeParentPlot(mParentPlot); - el->layoutChanged(); - } else - qDebug() << Q_FUNC_INFO << "Null element passed"; + if (el) { + el->mParentLayout = this; + el->setParentLayerable(this); + el->setParent(this); + if (!el->parentPlot()) { + el->initializeParentPlot(mParentPlot); + } + el->layoutChanged(); + } else { + qDebug() << Q_FUNC_INFO << "Null element passed"; + } } /*! \internal - + Disassociates \a el from this layout. This is done by setting the \ref QCPLayoutElement::layout and the \ref QCPLayerable::parentLayerable to zero. The QObject parent is set to the parent QCustomPlot. - + This method is used by subclass specific methods that remove elements from the layout (e.g. \ref take or \ref takeAt). Note that this method only changes properties in \a el. The removal from the old layout must be done additionally. */ void QCPLayout::releaseElement(QCPLayoutElement *el) { - if (el) - { - el->mParentLayout = 0; - el->setParentLayerable(0); - el->setParent(mParentPlot); - // Note: Don't initializeParentPlot(0) here, because layout element will stay in same parent plot - } else - qDebug() << Q_FUNC_INFO << "Null element passed"; + if (el) { + el->mParentLayout = 0; + el->setParentLayerable(0); + el->setParent(mParentPlot); + // Note: Don't initializeParentPlot(0) here, because layout element will stay in same parent plot + } else { + qDebug() << Q_FUNC_INFO << "Null element passed"; + } } /*! \internal - + This is a helper function for the implementation of \ref updateLayout in subclasses. - + It calculates the sizes of one-dimensional sections with provided constraints on maximum section sizes, minimum section sizes, relative stretch factors and the final total size of all sections. - + The QVector entries refer to the sections. Thus all QVectors must have the same size. - + \a maxSizes gives the maximum allowed size of each section. If there shall be no maximum size imposed, set all vector values to Qt's QWIDGETSIZE_MAX. - + \a minSizes gives the minimum allowed size of each section. If there shall be no minimum size imposed, set all vector values to zero. If the \a minSizes entries add up to a value greater than \a totalSize, sections will be scaled smaller than the proposed minimum sizes. (In other words, not exceeding the allowed total size is taken to be more important than not going below minimum section sizes.) - + \a stretchFactors give the relative proportions of the sections to each other. If all sections shall be scaled equally, set all values equal. If the first section shall be double the size of each individual other section, set the first number of \a stretchFactors to double the value of the other individual values (e.g. {2, 1, 1, 1}). - + \a totalSize is the value that the final section sizes will add up to. Due to rounding, the actual sum may differ slightly. If you want the section sizes to sum up to exactly that value, you could distribute the remaining difference on the sections. - + The return value is a QVector containing the section sizes. */ QVector QCPLayout::getSectionSizes(QVector maxSizes, QVector minSizes, QVector stretchFactors, int totalSize) const { - if (maxSizes.size() != minSizes.size() || minSizes.size() != stretchFactors.size()) - { - qDebug() << Q_FUNC_INFO << "Passed vector sizes aren't equal:" << maxSizes << minSizes << stretchFactors; - return QVector(); - } - if (stretchFactors.isEmpty()) - return QVector(); - int sectionCount = stretchFactors.size(); - QVector sectionSizes(sectionCount); - // if provided total size is forced smaller than total minimum size, ignore minimum sizes (squeeze sections): - int minSizeSum = 0; - for (int i=0; i(); } - } - - QList minimumLockedSections; - QList unfinishedSections; - for (int i=0; i(); + } + int sectionCount = stretchFactors.size(); + QVector sectionSizes(sectionCount); + // if provided total size is forced smaller than total minimum size, ignore minimum sizes (squeeze sections): + int minSizeSum = 0; + for (int i = 0; i < sectionCount; ++i) { + minSizeSum += minSizes.at(i); + } + if (totalSize < minSizeSum) { + // new stretch factors are minimum sizes and minimum sizes are set to zero: + for (int i = 0; i < sectionCount; ++i) { + stretchFactors[i] = minSizes.at(i); + minSizes[i] = 0; } - } - // check if that maximum is actually within the bounds of the total size (i.e. can we stretch all remaining sections so far that the found section - // actually hits its maximum, without exceeding the total size when we add up all sections) - double stretchFactorSum = 0; - for (int i=0; i minimumLockedSections; + QList unfinishedSections; + for (int i = 0; i < sectionCount; ++i) { + unfinishedSections.append(i); + } + double freeSize = totalSize; + + int outerIterations = 0; + while (!unfinishedSections.isEmpty() && outerIterations < sectionCount * 2) { // the iteration check ist just a failsafe in case something really strange happens + ++outerIterations; + int innerIterations = 0; + while (!unfinishedSections.isEmpty() && innerIterations < sectionCount * 2) { // the iteration check ist just a failsafe in case something really strange happens + ++innerIterations; + // find section that hits its maximum next: + int nextId = -1; + double nextMax = 1e12; + for (int i = 0; i < unfinishedSections.size(); ++i) { + int secId = unfinishedSections.at(i); + double hitsMaxAt = (maxSizes.at(secId) - sectionSizes.at(secId)) / stretchFactors.at(secId); + if (hitsMaxAt < nextMax) { + nextMax = hitsMaxAt; + nextId = secId; + } + } + // check if that maximum is actually within the bounds of the total size (i.e. can we stretch all remaining sections so far that the found section + // actually hits its maximum, without exceeding the total size when we add up all sections) + double stretchFactorSum = 0; + for (int i = 0; i < unfinishedSections.size(); ++i) { + stretchFactorSum += stretchFactors.at(unfinishedSections.at(i)); + } + double nextMaxLimit = freeSize / stretchFactorSum; + if (nextMax < nextMaxLimit) { // next maximum is actually hit, move forward to that point and fix the size of that section + for (int i = 0; i < unfinishedSections.size(); ++i) { + sectionSizes[unfinishedSections.at(i)] += nextMax * stretchFactors.at(unfinishedSections.at(i)); // increment all sections + freeSize -= nextMax * stretchFactors.at(unfinishedSections.at(i)); + } + unfinishedSections.removeOne(nextId); // exclude the section that is now at maximum from further changes + } else { // next maximum isn't hit, just distribute rest of free space on remaining sections + for (int i = 0; i < unfinishedSections.size(); ++i) { + sectionSizes[unfinishedSections.at(i)] += nextMaxLimit * stretchFactors.at(unfinishedSections.at(i)); // increment all sections + } + unfinishedSections.clear(); + } + } + if (innerIterations == sectionCount * 2) { + qDebug() << Q_FUNC_INFO << "Exceeded maximum expected inner iteration count, layouting aborted. Input was:" << maxSizes << minSizes << stretchFactors << totalSize; + } + + // now check whether the resulting section sizes violate minimum restrictions: + bool foundMinimumViolation = false; + for (int i = 0; i < sectionSizes.size(); ++i) { + if (minimumLockedSections.contains(i)) { + continue; + } + if (sectionSizes.at(i) < minSizes.at(i)) { // section violates minimum + sectionSizes[i] = minSizes.at(i); // set it to minimum + foundMinimumViolation = true; // make sure we repeat the whole optimization process + minimumLockedSections.append(i); + } + } + if (foundMinimumViolation) { + freeSize = totalSize; + for (int i = 0; i < sectionCount; ++i) { + if (!minimumLockedSections.contains(i)) { // only put sections that haven't hit their minimum back into the pool + unfinishedSections.append(i); + } else { + freeSize -= sectionSizes.at(i); // remove size of minimum locked sections from available space in next round + } + } + // reset all section sizes to zero that are in unfinished sections (all others have been set to their minimum): + for (int i = 0; i < unfinishedSections.size(); ++i) { + sectionSizes[unfinishedSections.at(i)] = 0; + } } - unfinishedSections.removeOne(nextId); // exclude the section that is now at maximum from further changes - } else // next maximum isn't hit, just distribute rest of free space on remaining sections - { - for (int i=0; i result(sectionCount); + for (int i = 0; i < sectionCount; ++i) { + result[i] = qRound(sectionSizes.at(i)); } - } - if (outerIterations == sectionCount*2) - qDebug() << Q_FUNC_INFO << "Exceeded maximum expected outer iteration count, layouting aborted. Input was:" << maxSizes << minSizes << stretchFactors << totalSize; - - QVector result(sectionCount); - for (int i=0; i QCPLayout::getSectionSizes(QVector maxSizes, QVector minS */ QSize QCPLayout::getFinalMinimumOuterSize(const QCPLayoutElement *el) { - QSize minOuterHint = el->minimumOuterSizeHint(); - QSize minOuter = el->minimumSize(); // depending on sizeConstraitRect this might be with respect to inner rect, so possibly add margins in next four lines (preserving unset minimum of 0) - if (minOuter.width() > 0 && el->sizeConstraintRect() == QCPLayoutElement::scrInnerRect) - minOuter.rwidth() += el->margins().left() + el->margins().right(); - if (minOuter.height() > 0 && el->sizeConstraintRect() == QCPLayoutElement::scrInnerRect) - minOuter.rheight() += el->margins().top() + el->margins().bottom(); - - return QSize(minOuter.width() > 0 ? minOuter.width() : minOuterHint.width(), - minOuter.height() > 0 ? minOuter.height() : minOuterHint.height()); + QSize minOuterHint = el->minimumOuterSizeHint(); + QSize minOuter = el->minimumSize(); // depending on sizeConstraitRect this might be with respect to inner rect, so possibly add margins in next four lines (preserving unset minimum of 0) + if (minOuter.width() > 0 && el->sizeConstraintRect() == QCPLayoutElement::scrInnerRect) { + minOuter.rwidth() += el->margins().left() + el->margins().right(); + } + if (minOuter.height() > 0 && el->sizeConstraintRect() == QCPLayoutElement::scrInnerRect) { + minOuter.rheight() += el->margins().top() + el->margins().bottom(); + } + + return QSize(minOuter.width() > 0 ? minOuter.width() : minOuterHint.width(), + minOuter.height() > 0 ? minOuter.height() : minOuterHint.height()); } /*! \internal - + This is a helper function for the implementation of subclasses. - + It returns the maximum size that should finally be used for the outer rect of the passed layout element \a el. - + It takes into account whether a manual maximum size is set (\ref QCPLayoutElement::setMaximumSize), which size constraint is set (\ref QCPLayoutElement::setSizeConstraintRect), as well as the maximum size hint, if no manual maximum @@ -4019,15 +4032,17 @@ QSize QCPLayout::getFinalMinimumOuterSize(const QCPLayoutElement *el) */ QSize QCPLayout::getFinalMaximumOuterSize(const QCPLayoutElement *el) { - QSize maxOuterHint = el->maximumOuterSizeHint(); - QSize maxOuter = el->maximumSize(); // depending on sizeConstraitRect this might be with respect to inner rect, so possibly add margins in next four lines (preserving unset maximum of QWIDGETSIZE_MAX) - if (maxOuter.width() < QWIDGETSIZE_MAX && el->sizeConstraintRect() == QCPLayoutElement::scrInnerRect) - maxOuter.rwidth() += el->margins().left() + el->margins().right(); - if (maxOuter.height() < QWIDGETSIZE_MAX && el->sizeConstraintRect() == QCPLayoutElement::scrInnerRect) - maxOuter.rheight() += el->margins().top() + el->margins().bottom(); - - return QSize(maxOuter.width() < QWIDGETSIZE_MAX ? maxOuter.width() : maxOuterHint.width(), - maxOuter.height() < QWIDGETSIZE_MAX ? maxOuter.height() : maxOuterHint.height()); + QSize maxOuterHint = el->maximumOuterSizeHint(); + QSize maxOuter = el->maximumSize(); // depending on sizeConstraitRect this might be with respect to inner rect, so possibly add margins in next four lines (preserving unset maximum of QWIDGETSIZE_MAX) + if (maxOuter.width() < QWIDGETSIZE_MAX && el->sizeConstraintRect() == QCPLayoutElement::scrInnerRect) { + maxOuter.rwidth() += el->margins().left() + el->margins().right(); + } + if (maxOuter.height() < QWIDGETSIZE_MAX && el->sizeConstraintRect() == QCPLayoutElement::scrInnerRect) { + maxOuter.rheight() += el->margins().top() + el->margins().bottom(); + } + + return QSize(maxOuter.width() < QWIDGETSIZE_MAX ? maxOuter.width() : maxOuterHint.width(), + maxOuter.height() < QWIDGETSIZE_MAX ? maxOuter.height() : maxOuterHint.height()); } @@ -4077,43 +4092,44 @@ QSize QCPLayout::getFinalMaximumOuterSize(const QCPLayoutElement *el) Creates an instance of QCPLayoutGrid and sets default values. */ QCPLayoutGrid::QCPLayoutGrid() : - mColumnSpacing(5), - mRowSpacing(5), - mWrap(0), - mFillOrder(foColumnsFirst) + mColumnSpacing(5), + mRowSpacing(5), + mWrap(0), + mFillOrder(foColumnsFirst) { } QCPLayoutGrid::~QCPLayoutGrid() { - // clear all child layout elements. This is important because only the specific layouts know how - // to handle removing elements (clear calls virtual removeAt method to do that). - clear(); + // clear all child layout elements. This is important because only the specific layouts know how + // to handle removing elements (clear calls virtual removeAt method to do that). + clear(); } /*! Returns the element in the cell in \a row and \a column. - + Returns 0 if either the row/column is invalid or if the cell is empty. In those cases, a qDebug message is printed. To check whether a cell exists and isn't empty, use \ref hasElement. - + \see addElement, hasElement */ QCPLayoutElement *QCPLayoutGrid::element(int row, int column) const { - if (row >= 0 && row < mElements.size()) - { - if (column >= 0 && column < mElements.first().size()) - { - if (QCPLayoutElement *result = mElements.at(row).at(column)) - return result; - else - qDebug() << Q_FUNC_INFO << "Requested cell is empty. Row:" << row << "Column:" << column; - } else - qDebug() << Q_FUNC_INFO << "Invalid column. Row:" << row << "Column:" << column; - } else - qDebug() << Q_FUNC_INFO << "Invalid row. Row:" << row << "Column:" << column; - return 0; + if (row >= 0 && row < mElements.size()) { + if (column >= 0 && column < mElements.first().size()) { + if (QCPLayoutElement *result = mElements.at(row).at(column)) { + return result; + } else { + qDebug() << Q_FUNC_INFO << "Requested cell is empty. Row:" << row << "Column:" << column; + } + } else { + qDebug() << Q_FUNC_INFO << "Invalid column. Row:" << row << "Column:" << column; + } + } else { + qDebug() << Q_FUNC_INFO << "Invalid row. Row:" << row << "Column:" << column; + } + return 0; } @@ -4133,18 +4149,20 @@ QCPLayoutElement *QCPLayoutGrid::element(int row, int column) const */ bool QCPLayoutGrid::addElement(int row, int column, QCPLayoutElement *element) { - if (!hasElement(row, column)) - { - 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 false; + if (!hasElement(row, column)) { + 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 false; } /*! \overload @@ -4159,172 +4177,165 @@ bool QCPLayoutGrid::addElement(int row, int column, QCPLayoutElement *element) */ 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; - } + 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; + } + } } - } else - { - while (hasElement(rowIndex, colIndex)) - { - ++rowIndex; - if (rowIndex >= mWrap && mWrap > 0) - { - rowIndex = 0; - ++colIndex; - } - } - } - return addElement(rowIndex, colIndex, element); + 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. - + \see element */ bool QCPLayoutGrid::hasElement(int row, int column) { - if (row >= 0 && row < rowCount() && column >= 0 && column < columnCount()) - return mElements.at(row).at(column); - else - return false; + if (row >= 0 && row < rowCount() && column >= 0 && column < columnCount()) { + return mElements.at(row).at(column); + } else { + return false; + } } /*! Sets the stretch \a factor of \a column. - + Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond their minimum and maximum widths/heights, regardless of the stretch factor. (see \ref QCPLayoutElement::setMinimumSize, \ref QCPLayoutElement::setMaximumSize, \ref QCPLayoutElement::setSizeConstraintRect.) - + The default stretch factor of newly created rows/columns is 1. - + \see setColumnStretchFactors, setRowStretchFactor */ void QCPLayoutGrid::setColumnStretchFactor(int column, double factor) { - if (column >= 0 && column < columnCount()) - { - if (factor > 0) - mColumnStretchFactors[column] = factor; - else - qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << factor; - } else - qDebug() << Q_FUNC_INFO << "Invalid column:" << column; + if (column >= 0 && column < columnCount()) { + if (factor > 0) { + mColumnStretchFactors[column] = factor; + } else { + qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << factor; + } + } else { + qDebug() << Q_FUNC_INFO << "Invalid column:" << column; + } } /*! Sets the stretch \a factors of all columns. \a factors must have the size \ref columnCount. - + Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond their minimum and maximum widths/heights, regardless of the stretch factor. (see \ref QCPLayoutElement::setMinimumSize, \ref QCPLayoutElement::setMaximumSize, \ref QCPLayoutElement::setSizeConstraintRect.) - + The default stretch factor of newly created rows/columns is 1. - + \see setColumnStretchFactor, setRowStretchFactors */ void QCPLayoutGrid::setColumnStretchFactors(const QList &factors) { - if (factors.size() == mColumnStretchFactors.size()) - { - mColumnStretchFactors = factors; - for (int i=0; i= 0 && row < rowCount()) - { - if (factor > 0) - mRowStretchFactors[row] = factor; - else - qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << factor; - } else - qDebug() << Q_FUNC_INFO << "Invalid row:" << row; + if (row >= 0 && row < rowCount()) { + if (factor > 0) { + mRowStretchFactors[row] = factor; + } else { + qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << factor; + } + } else { + qDebug() << Q_FUNC_INFO << "Invalid row:" << row; + } } /*! Sets the stretch \a factors of all rows. \a factors must have the size \ref rowCount. - + Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond their minimum and maximum widths/heights, regardless of the stretch factor. (see \ref QCPLayoutElement::setMinimumSize, \ref QCPLayoutElement::setMaximumSize, \ref QCPLayoutElement::setSizeConstraintRect.) - + The default stretch factor of newly created rows/columns is 1. - + \see setRowStretchFactor, setColumnStretchFactors */ void QCPLayoutGrid::setRowStretchFactors(const QList &factors) { - if (factors.size() == mRowStretchFactors.size()) - { - mRowStretchFactors = factors; - for (int i=0; i tempElements; - if (rearrange) - { - tempElements.reserve(elCount); - for (int i=0; i tempElements; + if (rearrange) { + tempElements.reserve(elCount); + for (int i = 0; i < elCount; ++i) { + if (elementAt(i)) { + tempElements.append(takeAt(i)); + } + } + simplify(); + } + // change fill order as requested: + mFillOrder = order; + // if rearranging, re-insert via linear index according to new fill order: + if (rearrange) { + for (int i = 0; i < tempElements.size(); ++i) { + addElement(tempElements.at(i)); + } } - simplify(); - } - // change fill order as requested: - mFillOrder = order; - // if rearranging, re-insert via linear index according to new fill order: - if (rearrange) - { - for (int i=0; i()); - mRowStretchFactors.append(1); - } - // go through rows and expand columns as necessary: - int newColCount = qMax(columnCount(), newColumnCount); - for (int i=0; i()); + mRowStretchFactors.append(1); + } + // go through rows and expand columns as necessary: + int newColCount = qMax(columnCount(), newColumnCount); + for (int i = 0; i < rowCount(); ++i) { + while (mElements.at(i).size() < newColCount) { + mElements[i].append(0); + } + } + while (mColumnStretchFactors.size() < newColCount) { + mColumnStretchFactors.append(1); + } } /*! Inserts a new row with empty cells at the row index \a newIndex. Valid values for \a newIndex range from 0 (inserts a row at the top) to \a rowCount (appends a row at the bottom). - + \see insertColumn */ void QCPLayoutGrid::insertRow(int newIndex) { - if (mElements.isEmpty() || mElements.first().isEmpty()) // if grid is completely empty, add first cell - { - expandTo(1, 1); - return; - } - - if (newIndex < 0) - newIndex = 0; - if (newIndex > rowCount()) - newIndex = rowCount(); - - mRowStretchFactors.insert(newIndex, 1); - QList newRow; - for (int col=0; col rowCount()) { + newIndex = rowCount(); + } + + mRowStretchFactors.insert(newIndex, 1); + QList newRow; + for (int col = 0; col < columnCount(); ++col) { + newRow.append((QCPLayoutElement *)0); + } + mElements.insert(newIndex, newRow); } /*! Inserts a new column with empty cells at the column index \a newIndex. Valid values for \a newIndex range from 0 (inserts a column at the left) to \a columnCount (appends a column at the right). - + \see insertRow */ void QCPLayoutGrid::insertColumn(int newIndex) { - if (mElements.isEmpty() || mElements.first().isEmpty()) // if grid is completely empty, add first cell - { - expandTo(1, 1); - return; - } - - if (newIndex < 0) - newIndex = 0; - if (newIndex > columnCount()) - newIndex = columnCount(); - - mColumnStretchFactors.insert(newIndex, 1); - for (int row=0; row columnCount()) { + newIndex = columnCount(); + } + + mColumnStretchFactors.insert(newIndex, 1); + for (int row = 0; row < rowCount(); ++row) { + mElements[row].insert(newIndex, (QCPLayoutElement *)0); + } } /*! @@ -4498,20 +4512,21 @@ void QCPLayoutGrid::insertColumn(int newIndex) */ int QCPLayoutGrid::rowColToIndex(int row, int column) const { - if (row >= 0 && row < rowCount()) - { - if (column >= 0 && column < columnCount()) - { - switch (mFillOrder) - { - case foRowsFirst: return column*rowCount() + row; - case foColumnsFirst: return row*columnCount() + column; - } - } else - qDebug() << Q_FUNC_INFO << "row index out of bounds:" << row; - } else - qDebug() << Q_FUNC_INFO << "column index out of bounds:" << column; - return 0; + if (row >= 0 && row < rowCount()) { + if (column >= 0 && column < columnCount()) { + switch (mFillOrder) { + case foRowsFirst: + return column * rowCount() + row; + case foColumnsFirst: + return row * columnCount() + column; + } + } else { + qDebug() << Q_FUNC_INFO << "row index out of bounds:" << row; + } + } else { + qDebug() << Q_FUNC_INFO << "column index out of bounds:" << column; + } + return 0; } /*! @@ -4531,62 +4546,60 @@ int QCPLayoutGrid::rowColToIndex(int row, int column) const */ void QCPLayoutGrid::indexToRowCol(int index, int &row, int &column) const { - row = -1; - column = -1; - const int nCols = columnCount(); - const int nRows = rowCount(); - if (nCols == 0 || nRows == 0) - return; - if (index < 0 || index >= elementCount()) - { - qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; - return; - } - - switch (mFillOrder) - { - case foRowsFirst: - { - column = index / nRows; - row = index % nRows; - break; + row = -1; + column = -1; + const int nCols = columnCount(); + const int nRows = rowCount(); + if (nCols == 0 || nRows == 0) { + return; } - case foColumnsFirst: - { - row = index / nCols; - column = index % nCols; - break; + if (index < 0 || index >= elementCount()) { + qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; + return; + } + + switch (mFillOrder) { + case foRowsFirst: { + column = index / nRows; + row = index % nRows; + break; + } + case foColumnsFirst: { + row = index / nCols; + column = index % nCols; + break; + } } - } } /* inherits documentation from base class */ void QCPLayoutGrid::updateLayout() { - QVector minColWidths, minRowHeights, maxColWidths, maxRowHeights; - getMinimumRowColSizes(&minColWidths, &minRowHeights); - getMaximumRowColSizes(&maxColWidths, &maxRowHeights); - - int totalRowSpacing = (rowCount()-1) * mRowSpacing; - int totalColSpacing = (columnCount()-1) * mColumnSpacing; - QVector colWidths = getSectionSizes(maxColWidths, minColWidths, mColumnStretchFactors.toVector(), mRect.width()-totalColSpacing); - QVector rowHeights = getSectionSizes(maxRowHeights, minRowHeights, mRowStretchFactors.toVector(), mRect.height()-totalRowSpacing); - - // go through cells and set rects accordingly: - int yOffset = mRect.top(); - for (int row=0; row 0) - yOffset += rowHeights.at(row-1)+mRowSpacing; - int xOffset = mRect.left(); - for (int col=0; col 0) - xOffset += colWidths.at(col-1)+mColumnSpacing; - if (mElements.at(row).at(col)) - mElements.at(row).at(col)->setOuterRect(QRect(xOffset, yOffset, colWidths.at(col), rowHeights.at(row))); + QVector minColWidths, minRowHeights, maxColWidths, maxRowHeights; + getMinimumRowColSizes(&minColWidths, &minRowHeights); + getMaximumRowColSizes(&maxColWidths, &maxRowHeights); + + int totalRowSpacing = (rowCount() - 1) * mRowSpacing; + int totalColSpacing = (columnCount() - 1) * mColumnSpacing; + QVector colWidths = getSectionSizes(maxColWidths, minColWidths, mColumnStretchFactors.toVector(), mRect.width() - totalColSpacing); + QVector rowHeights = getSectionSizes(maxRowHeights, minRowHeights, mRowStretchFactors.toVector(), mRect.height() - totalRowSpacing); + + // go through cells and set rects accordingly: + int yOffset = mRect.top(); + for (int row = 0; row < rowCount(); ++row) { + if (row > 0) { + yOffset += rowHeights.at(row - 1) + mRowSpacing; + } + int xOffset = mRect.left(); + for (int col = 0; col < columnCount(); ++col) { + if (col > 0) { + xOffset += colWidths.at(col - 1) + mColumnSpacing; + } + if (mElements.at(row).at(col)) { + mElements.at(row).at(col)->setOuterRect(QRect(xOffset, yOffset, colWidths.at(col), rowHeights.at(row))); + } + } } - } } /*! @@ -4599,13 +4612,13 @@ void QCPLayoutGrid::updateLayout() */ QCPLayoutElement *QCPLayoutGrid::elementAt(int index) const { - if (index >= 0 && index < elementCount()) - { - int row, col; - indexToRowCol(index, row, col); - return mElements.at(row).at(col); - } else - return 0; + if (index >= 0 && index < elementCount()) { + int row, col; + indexToRowCol(index, row, col); + return mElements.at(row).at(col); + } else { + return 0; + } } /*! @@ -4618,58 +4631,54 @@ QCPLayoutElement *QCPLayoutGrid::elementAt(int index) const */ QCPLayoutElement *QCPLayoutGrid::takeAt(int index) { - if (QCPLayoutElement *el = elementAt(index)) - { - releaseElement(el); - int row, col; - indexToRowCol(index, row, col); - mElements[row][col] = 0; - return el; - } else - { - qDebug() << Q_FUNC_INFO << "Attempt to take invalid index:" << index; - return 0; - } + if (QCPLayoutElement *el = elementAt(index)) { + releaseElement(el); + int row, col; + indexToRowCol(index, row, col); + mElements[row][col] = 0; + return el; + } else { + qDebug() << Q_FUNC_INFO << "Attempt to take invalid index:" << index; + return 0; + } } /* inherits documentation from base class */ bool QCPLayoutGrid::take(QCPLayoutElement *element) { - if (element) - { - for (int i=0; i QCPLayoutGrid::elements(bool recursive) const +QList QCPLayoutGrid::elements(bool recursive) const { - QList result; - const int elCount = elementCount(); + QList result; + const int elCount = elementCount(); #if QT_VERSION >= QT_VERSION_CHECK(4, 7, 0) - result.reserve(elCount); + result.reserve(elCount); #endif - for (int i=0; ielements(recursive); + for (int i = 0; i < elCount; ++i) { + result.append(elementAt(i)); } - } - return result; + if (recursive) { + for (int i = 0; i < elCount; ++i) { + if (result.at(i)) { + result << result.at(i)->elements(recursive); + } + } + } + return result; } /*! @@ -4677,151 +4686,149 @@ QList QCPLayoutGrid::elements(bool recursive) const */ void QCPLayoutGrid::simplify() { - // remove rows with only empty cells: - for (int row=rowCount()-1; row>=0; --row) - { - bool hasElements = false; - for (int col=0; col= 0; --row) { + bool hasElements = false; + for (int col = 0; col < columnCount(); ++col) { + if (mElements.at(row).at(col)) { + hasElements = true; + break; + } + } + if (!hasElements) { + mRowStretchFactors.removeAt(row); + mElements.removeAt(row); + if (mElements.isEmpty()) { // removed last element, also remove stretch factor (wouldn't happen below because also columnCount changed to 0 now) + mColumnStretchFactors.clear(); + } + } } - if (!hasElements) - { - mRowStretchFactors.removeAt(row); - mElements.removeAt(row); - if (mElements.isEmpty()) // removed last element, also remove stretch factor (wouldn't happen below because also columnCount changed to 0 now) - mColumnStretchFactors.clear(); + + // remove columns with only empty cells: + for (int col = columnCount() - 1; col >= 0; --col) { + bool hasElements = false; + for (int row = 0; row < rowCount(); ++row) { + if (mElements.at(row).at(col)) { + hasElements = true; + break; + } + } + if (!hasElements) { + mColumnStretchFactors.removeAt(col); + for (int row = 0; row < rowCount(); ++row) { + mElements[row].removeAt(col); + } + } } - } - - // remove columns with only empty cells: - for (int col=columnCount()-1; col>=0; --col) - { - bool hasElements = false; - for (int row=0; row minColWidths, minRowHeights; - getMinimumRowColSizes(&minColWidths, &minRowHeights); - QSize result(0, 0); - for (int i=0; i minColWidths, minRowHeights; + getMinimumRowColSizes(&minColWidths, &minRowHeights); + QSize result(0, 0); + for (int i = 0; i < minColWidths.size(); ++i) { + result.rwidth() += minColWidths.at(i); + } + for (int i = 0; i < minRowHeights.size(); ++i) { + result.rheight() += minRowHeights.at(i); + } + result.rwidth() += qMax(0, columnCount() - 1) * mColumnSpacing; + result.rheight() += qMax(0, rowCount() - 1) * mRowSpacing; + result.rwidth() += mMargins.left() + mMargins.right(); + result.rheight() += mMargins.top() + mMargins.bottom(); + return result; } /* inherits documentation from base class */ QSize QCPLayoutGrid::maximumOuterSizeHint() const { - QVector maxColWidths, maxRowHeights; - getMaximumRowColSizes(&maxColWidths, &maxRowHeights); - - QSize result(0, 0); - for (int i=0; i QWIDGETSIZE_MAX) - result.setHeight(QWIDGETSIZE_MAX); - if (result.width() > QWIDGETSIZE_MAX) - result.setWidth(QWIDGETSIZE_MAX); - return result; + QVector maxColWidths, maxRowHeights; + getMaximumRowColSizes(&maxColWidths, &maxRowHeights); + + QSize result(0, 0); + for (int i = 0; i < maxColWidths.size(); ++i) { + result.setWidth(qMin(result.width() + maxColWidths.at(i), QWIDGETSIZE_MAX)); + } + for (int i = 0; i < maxRowHeights.size(); ++i) { + result.setHeight(qMin(result.height() + maxRowHeights.at(i), QWIDGETSIZE_MAX)); + } + result.rwidth() += qMax(0, columnCount() - 1) * mColumnSpacing; + result.rheight() += qMax(0, rowCount() - 1) * mRowSpacing; + result.rwidth() += mMargins.left() + mMargins.right(); + result.rheight() += mMargins.top() + mMargins.bottom(); + if (result.height() > QWIDGETSIZE_MAX) { + result.setHeight(QWIDGETSIZE_MAX); + } + if (result.width() > QWIDGETSIZE_MAX) { + result.setWidth(QWIDGETSIZE_MAX); + } + return result; } /*! \internal - + Places the minimum column widths and row heights into \a minColWidths and \a minRowHeights respectively. - + The minimum height of a row is the largest minimum height of any element's outer rect in that row. The minimum width of a column is the largest minimum width of any element's outer rect in that column. - + This is a helper function for \ref updateLayout. - + \see getMaximumRowColSizes */ void QCPLayoutGrid::getMinimumRowColSizes(QVector *minColWidths, QVector *minRowHeights) const { - *minColWidths = QVector(columnCount(), 0); - *minRowHeights = QVector(rowCount(), 0); - for (int row=0; rowat(col) < minSize.width()) - (*minColWidths)[col] = minSize.width(); - if (minRowHeights->at(row) < minSize.height()) - (*minRowHeights)[row] = minSize.height(); - } + *minColWidths = QVector(columnCount(), 0); + *minRowHeights = QVector(rowCount(), 0); + for (int row = 0; row < rowCount(); ++row) { + for (int col = 0; col < columnCount(); ++col) { + if (QCPLayoutElement *el = mElements.at(row).at(col)) { + QSize minSize = getFinalMinimumOuterSize(el); + if (minColWidths->at(col) < minSize.width()) { + (*minColWidths)[col] = minSize.width(); + } + if (minRowHeights->at(row) < minSize.height()) { + (*minRowHeights)[row] = minSize.height(); + } + } + } } - } } /*! \internal - + Places the maximum column widths and row heights into \a maxColWidths and \a maxRowHeights respectively. - + The maximum height of a row is the smallest maximum height of any element's outer rect in that row. The maximum width of a column is the smallest maximum width of any element's outer rect in that column. - + This is a helper function for \ref updateLayout. - + \see getMinimumRowColSizes */ void QCPLayoutGrid::getMaximumRowColSizes(QVector *maxColWidths, QVector *maxRowHeights) const { - *maxColWidths = QVector(columnCount(), QWIDGETSIZE_MAX); - *maxRowHeights = QVector(rowCount(), QWIDGETSIZE_MAX); - for (int row=0; rowat(col) > maxSize.width()) - (*maxColWidths)[col] = maxSize.width(); - if (maxRowHeights->at(row) > maxSize.height()) - (*maxRowHeights)[row] = maxSize.height(); - } + *maxColWidths = QVector(columnCount(), QWIDGETSIZE_MAX); + *maxRowHeights = QVector(rowCount(), QWIDGETSIZE_MAX); + for (int row = 0; row < rowCount(); ++row) { + for (int col = 0; col < columnCount(); ++col) { + if (QCPLayoutElement *el = mElements.at(row).at(col)) { + QSize maxSize = getFinalMaximumOuterSize(el); + if (maxColWidths->at(col) > maxSize.width()) { + (*maxColWidths)[col] = maxSize.width(); + } + if (maxRowHeights->at(row) > maxSize.height()) { + (*maxRowHeights)[row] = maxSize.height(); + } + } + } } - } } @@ -4830,7 +4837,7 @@ void QCPLayoutGrid::getMaximumRowColSizes(QVector *maxColWidths, QVector *maxColWidths, QVector finalMaxSize.width()) - insetRect.setWidth(finalMaxSize.width()); - if (insetRect.size().height() > finalMaxSize.height()) - insetRect.setHeight(finalMaxSize.height()); - } else if (mInsetPlacement.at(i) == ipBorderAligned) - { - insetRect.setSize(finalMinSize); - Qt::Alignment al = mInsetAlignment.at(i); - if (al.testFlag(Qt::AlignLeft)) insetRect.moveLeft(rect().x()); - else if (al.testFlag(Qt::AlignRight)) insetRect.moveRight(rect().x()+rect().width()); - else insetRect.moveLeft(rect().x()+rect().width()*0.5-finalMinSize.width()*0.5); // default to Qt::AlignHCenter - if (al.testFlag(Qt::AlignTop)) insetRect.moveTop(rect().y()); - else if (al.testFlag(Qt::AlignBottom)) insetRect.moveBottom(rect().y()+rect().height()); - else insetRect.moveTop(rect().y()+rect().height()*0.5-finalMinSize.height()*0.5); // default to Qt::AlignVCenter + for (int i = 0; i < mElements.size(); ++i) { + QCPLayoutElement *el = mElements.at(i); + QRect insetRect; + QSize finalMinSize = getFinalMinimumOuterSize(el); + QSize finalMaxSize = getFinalMaximumOuterSize(el); + if (mInsetPlacement.at(i) == ipFree) { + insetRect = QRect(rect().x() + rect().width() * mInsetRect.at(i).x(), + rect().y() + rect().height() * mInsetRect.at(i).y(), + rect().width() * mInsetRect.at(i).width(), + rect().height() * mInsetRect.at(i).height()); + if (insetRect.size().width() < finalMinSize.width()) { + insetRect.setWidth(finalMinSize.width()); + } + if (insetRect.size().height() < finalMinSize.height()) { + insetRect.setHeight(finalMinSize.height()); + } + if (insetRect.size().width() > finalMaxSize.width()) { + insetRect.setWidth(finalMaxSize.width()); + } + if (insetRect.size().height() > finalMaxSize.height()) { + insetRect.setHeight(finalMaxSize.height()); + } + } else if (mInsetPlacement.at(i) == ipBorderAligned) { + insetRect.setSize(finalMinSize); + Qt::Alignment al = mInsetAlignment.at(i); + if (al.testFlag(Qt::AlignLeft)) { + insetRect.moveLeft(rect().x()); + } else if (al.testFlag(Qt::AlignRight)) { + insetRect.moveRight(rect().x() + rect().width()); + } else { + insetRect.moveLeft(rect().x() + rect().width() * 0.5 - finalMinSize.width() * 0.5); // default to Qt::AlignHCenter + } + if (al.testFlag(Qt::AlignTop)) { + insetRect.moveTop(rect().y()); + } else if (al.testFlag(Qt::AlignBottom)) { + insetRect.moveBottom(rect().y() + rect().height()); + } else { + insetRect.moveTop(rect().y() + rect().height() * 0.5 - finalMinSize.height() * 0.5); // default to Qt::AlignVCenter + } + } + mElements.at(i)->setOuterRect(insetRect); } - mElements.at(i)->setOuterRect(insetRect); - } } /* inherits documentation from base class */ int QCPLayoutInset::elementCount() const { - return mElements.size(); + return mElements.size(); } /* inherits documentation from base class */ QCPLayoutElement *QCPLayoutInset::elementAt(int index) const { - if (index >= 0 && index < mElements.size()) - return mElements.at(index); - else - return 0; + if (index >= 0 && index < mElements.size()) { + return mElements.at(index); + } else { + return 0; + } } /* inherits documentation from base class */ QCPLayoutElement *QCPLayoutInset::takeAt(int index) { - if (QCPLayoutElement *el = elementAt(index)) - { - releaseElement(el); - mElements.removeAt(index); - mInsetPlacement.removeAt(index); - mInsetAlignment.removeAt(index); - mInsetRect.removeAt(index); - return el; - } else - { - qDebug() << Q_FUNC_INFO << "Attempt to take invalid index:" << index; - return 0; - } + if (QCPLayoutElement *el = elementAt(index)) { + releaseElement(el); + mElements.removeAt(index); + mInsetPlacement.removeAt(index); + mInsetAlignment.removeAt(index); + mInsetRect.removeAt(index); + return el; + } else { + qDebug() << Q_FUNC_INFO << "Attempt to take invalid index:" << index; + return 0; + } } /* inherits documentation from base class */ bool QCPLayoutInset::take(QCPLayoutElement *element) { - if (element) - { - for (int i=0; irealVisibility() && mElements.at(i)->selectTest(pos, onlySelectable) >= 0) { + return mParentPlot->selectionTolerance() * 0.99; + } + } return -1; - - for (int i=0; irealVisibility() && mElements.at(i)->selectTest(pos, onlySelectable) >= 0) - return mParentPlot->selectionTolerance()*0.99; - } - return -1; } /*! Adds the specified \a element to the layout as an inset aligned at the border (\ref setInsetAlignment is initialized with \ref ipBorderAligned). The alignment is set to \a alignment. - + \a alignment is an or combination of the following alignment flags: Qt::AlignLeft, Qt::AlignHCenter, Qt::AlighRight, Qt::AlignTop, Qt::AlignVCenter, Qt::AlignBottom. Any other alignment flags will be ignored. - + \see addElement(QCPLayoutElement *element, const QRectF &rect) */ void QCPLayoutInset::addElement(QCPLayoutElement *element, Qt::Alignment alignment) { - if (element) - { - if (element->layout()) // remove from old layout first - element->layout()->take(element); - mElements.append(element); - mInsetPlacement.append(ipBorderAligned); - mInsetAlignment.append(alignment); - mInsetRect.append(QRectF(0.6, 0.6, 0.4, 0.4)); - adoptElement(element); - } else - qDebug() << Q_FUNC_INFO << "Can't add null element"; + if (element) { + if (element->layout()) { // remove from old layout first + element->layout()->take(element); + } + mElements.append(element); + mInsetPlacement.append(ipBorderAligned); + mInsetAlignment.append(alignment); + mInsetRect.append(QRectF(0.6, 0.6, 0.4, 0.4)); + adoptElement(element); + } else { + qDebug() << Q_FUNC_INFO << "Can't add null element"; + } } /*! Adds the specified \a element to the layout as an inset with free positioning/sizing (\ref setInsetAlignment is initialized with \ref ipFree). The position and size is set to \a rect. - + \a rect is given in fractions of the whole inset layout rect. So an inset with rect (0, 0, 1, 1) will span the entire layout. An inset with rect (0.6, 0.1, 0.35, 0.35) will be in the top right corner of the layout, with 35% width and height of the parent layout. - + \see addElement(QCPLayoutElement *element, Qt::Alignment alignment) */ void QCPLayoutInset::addElement(QCPLayoutElement *element, const QRectF &rect) { - if (element) - { - if (element->layout()) // remove from old layout first - element->layout()->take(element); - mElements.append(element); - mInsetPlacement.append(ipFree); - mInsetAlignment.append(Qt::AlignRight|Qt::AlignTop); - mInsetRect.append(rect); - adoptElement(element); - } else - qDebug() << Q_FUNC_INFO << "Can't add null element"; + if (element) { + if (element->layout()) { // remove from old layout first + element->layout()->take(element); + } + mElements.append(element); + mInsetPlacement.append(ipFree); + mInsetAlignment.append(Qt::AlignRight | Qt::AlignTop); + mInsetRect.append(rect); + adoptElement(element); + } else { + qDebug() << Q_FUNC_INFO << "Can't add null element"; + } } /* end of 'src/layout.cpp' */ @@ -5140,19 +5156,19 @@ void QCPLayoutInset::addElement(QCPLayoutElement *element, const QRectF &rect) /*! \class QCPLineEnding \brief Handles the different ending decorations for line-like items - + \image html QCPLineEnding.png "The various ending styles currently supported" - + For every ending a line-like item has, an instance of this class exists. For example, QCPItemLine has two endings which can be set with QCPItemLine::setHead and QCPItemLine::setTail. - + The styles themselves are defined via the enum QCPLineEnding::EndingStyle. Most decorations can be modified regarding width and length, see \ref setWidth and \ref setLength. The direction of the ending decoration (e.g. direction an arrow is pointing) is controlled by the line-like item. For example, when both endings of a QCPItemLine are set to be arrows, they will point to opposite directions, e.g. "outward". This can be changed by \ref setInverted, which would make the respective arrow point inward. - + Note that due to the overloaded QCPLineEnding constructor, you may directly specify a QCPLineEnding::EndingStyle where actually a QCPLineEnding is expected, e.g. \snippet documentation/doc-code-snippets/mainwindow.cpp qcplineending-sethead @@ -5162,10 +5178,10 @@ void QCPLayoutInset::addElement(QCPLayoutElement *element, const QRectF &rect) Creates a QCPLineEnding instance with default values (style \ref esNone). */ QCPLineEnding::QCPLineEnding() : - mStyle(esNone), - mWidth(8), - mLength(10), - mInverted(false) + mStyle(esNone), + mWidth(8), + mLength(10), + mInverted(false) { } @@ -5173,10 +5189,10 @@ QCPLineEnding::QCPLineEnding() : Creates a QCPLineEnding instance with the specified values. */ QCPLineEnding::QCPLineEnding(QCPLineEnding::EndingStyle style, double width, double length, bool inverted) : - mStyle(style), - mWidth(width), - mLength(length), - mInverted(inverted) + mStyle(style), + mWidth(width), + mLength(length), + mInverted(inverted) { } @@ -5185,29 +5201,29 @@ QCPLineEnding::QCPLineEnding(QCPLineEnding::EndingStyle style, double width, dou */ void QCPLineEnding::setStyle(QCPLineEnding::EndingStyle style) { - mStyle = style; + mStyle = style; } /*! Sets the width of the ending decoration, if the style supports it. On arrows, for example, the width defines the size perpendicular to the arrow's pointing direction. - + \see setLength */ void QCPLineEnding::setWidth(double width) { - mWidth = width; + mWidth = width; } /*! Sets the length of the ending decoration, if the style supports it. On arrows, for example, the length defines the size in pointing direction. - + \see setWidth */ void QCPLineEnding::setLength(double length) { - mLength = length; + mLength = length; } /*! @@ -5220,212 +5236,201 @@ void QCPLineEnding::setLength(double length) */ void QCPLineEnding::setInverted(bool inverted) { - mInverted = inverted; + mInverted = inverted; } /*! \internal - + Returns the maximum pixel radius the ending decoration might cover, starting from the position the decoration is drawn at (typically a line ending/\ref QCPItemPosition of an item). - + This is relevant for clipping. Only omit painting of the decoration when the position where the decoration is supposed to be drawn is farther away from the clipping rect than the returned distance. */ double QCPLineEnding::boundingDistance() const { - switch (mStyle) - { - case esNone: - return 0; - - case esFlatArrow: - case esSpikeArrow: - case esLineArrow: - case esSkewedBar: - return qSqrt(mWidth*mWidth+mLength*mLength); // items that have width and length - - case esDisc: - case esSquare: - case esDiamond: - case esBar: - case esHalfBar: - return mWidth*1.42; // items that only have a width -> width*sqrt(2) + switch (mStyle) { + case esNone: + return 0; - } - return 0; + case esFlatArrow: + case esSpikeArrow: + case esLineArrow: + case esSkewedBar: + return qSqrt(mWidth * mWidth + mLength * mLength); // items that have width and length + + case esDisc: + case esSquare: + case esDiamond: + case esBar: + case esHalfBar: + return mWidth * 1.42; // items that only have a width -> width*sqrt(2) + + } + return 0; } /*! Starting from the origin of this line ending (which is style specific), returns the length covered by the line ending symbol, in backward direction. - + For example, the \ref esSpikeArrow has a shorter real length than a \ref esFlatArrow, even if both have the same \ref setLength value, because the spike arrow has an inward curved back, which reduces the length along its center axis (the drawing origin for arrows is at the tip). - + This function is used for precise, style specific placement of line endings, for example in QCPAxes. */ double QCPLineEnding::realLength() const { - switch (mStyle) - { - case esNone: - case esLineArrow: - case esSkewedBar: - case esBar: - case esHalfBar: - return 0; - - case esFlatArrow: - return mLength; - - case esDisc: - case esSquare: - case esDiamond: - return mWidth*0.5; - - case esSpikeArrow: - return mLength*0.8; - } - return 0; + switch (mStyle) { + case esNone: + case esLineArrow: + case esSkewedBar: + case esBar: + case esHalfBar: + return 0; + + case esFlatArrow: + return mLength; + + case esDisc: + case esSquare: + case esDiamond: + return mWidth * 0.5; + + case esSpikeArrow: + return mLength * 0.8; + } + return 0; } /*! \internal - + 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 QCPVector2D &pos, const QCPVector2D &dir) const { - if (mStyle == esNone) - return; - - QCPVector2D lengthVec = dir.normalized() * mLength*(mInverted ? -1 : 1); - if (lengthVec.isNull()) - lengthVec = QCPVector2D(1, 0); - QCPVector2D widthVec = dir.normalized().perpendicular() * mWidth*0.5*(mInverted ? -1 : 1); - - QPen penBackup = painter->pen(); - QBrush brushBackup = painter->brush(); - QPen miterPen = penBackup; - miterPen.setJoinStyle(Qt::MiterJoin); // to make arrow heads spikey - QBrush brush(painter->pen().color(), Qt::SolidPattern); - switch (mStyle) - { - case esNone: break; - case esFlatArrow: - { - QPointF points[3] = {pos.toPointF(), - (pos-lengthVec+widthVec).toPointF(), - (pos-lengthVec-widthVec).toPointF() - }; - painter->setPen(miterPen); - painter->setBrush(brush); - painter->drawConvexPolygon(points, 3); - painter->setBrush(brushBackup); - painter->setPen(penBackup); - break; + if (mStyle == esNone) { + return; } - case esSpikeArrow: - { - QPointF points[4] = {pos.toPointF(), - (pos-lengthVec+widthVec).toPointF(), - (pos-lengthVec*0.8).toPointF(), - (pos-lengthVec-widthVec).toPointF() - }; - painter->setPen(miterPen); - painter->setBrush(brush); - painter->drawConvexPolygon(points, 4); - painter->setBrush(brushBackup); - painter->setPen(penBackup); - break; + + QCPVector2D lengthVec = dir.normalized() * mLength * (mInverted ? -1 : 1); + if (lengthVec.isNull()) { + lengthVec = QCPVector2D(1, 0); } - case esLineArrow: - { - QPointF points[3] = {(pos-lengthVec+widthVec).toPointF(), - pos.toPointF(), - (pos-lengthVec-widthVec).toPointF() - }; - painter->setPen(miterPen); - painter->drawPolyline(points, 3); - painter->setPen(penBackup); - break; + QCPVector2D widthVec = dir.normalized().perpendicular() * mWidth * 0.5 * (mInverted ? -1 : 1); + + QPen penBackup = painter->pen(); + QBrush brushBackup = painter->brush(); + QPen miterPen = penBackup; + miterPen.setJoinStyle(Qt::MiterJoin); // to make arrow heads spikey + QBrush brush(painter->pen().color(), Qt::SolidPattern); + switch (mStyle) { + case esNone: + break; + case esFlatArrow: { + QPointF points[3] = {pos.toPointF(), + (pos - lengthVec + widthVec).toPointF(), + (pos - lengthVec - widthVec).toPointF() + }; + painter->setPen(miterPen); + painter->setBrush(brush); + painter->drawConvexPolygon(points, 3); + painter->setBrush(brushBackup); + painter->setPen(penBackup); + break; + } + case esSpikeArrow: { + QPointF points[4] = {pos.toPointF(), + (pos - lengthVec + widthVec).toPointF(), + (pos - lengthVec * 0.8).toPointF(), + (pos - lengthVec - widthVec).toPointF() + }; + painter->setPen(miterPen); + painter->setBrush(brush); + painter->drawConvexPolygon(points, 4); + painter->setBrush(brushBackup); + painter->setPen(penBackup); + break; + } + case esLineArrow: { + QPointF points[3] = {(pos - lengthVec + widthVec).toPointF(), + pos.toPointF(), + (pos - lengthVec - widthVec).toPointF() + }; + painter->setPen(miterPen); + painter->drawPolyline(points, 3); + painter->setPen(penBackup); + break; + } + case esDisc: { + painter->setBrush(brush); + painter->drawEllipse(pos.toPointF(), mWidth * 0.5, mWidth * 0.5); + painter->setBrush(brushBackup); + break; + } + case esSquare: { + QCPVector2D widthVecPerp = widthVec.perpendicular(); + QPointF points[4] = {(pos - widthVecPerp + widthVec).toPointF(), + (pos - widthVecPerp - widthVec).toPointF(), + (pos + widthVecPerp - widthVec).toPointF(), + (pos + widthVecPerp + widthVec).toPointF() + }; + painter->setPen(miterPen); + painter->setBrush(brush); + painter->drawConvexPolygon(points, 4); + painter->setBrush(brushBackup); + painter->setPen(penBackup); + break; + } + case esDiamond: { + QCPVector2D widthVecPerp = widthVec.perpendicular(); + QPointF points[4] = {(pos - widthVecPerp).toPointF(), + (pos - widthVec).toPointF(), + (pos + widthVecPerp).toPointF(), + (pos + widthVec).toPointF() + }; + painter->setPen(miterPen); + painter->setBrush(brush); + painter->drawConvexPolygon(points, 4); + painter->setBrush(brushBackup); + painter->setPen(penBackup); + break; + } + case esBar: { + painter->drawLine((pos + widthVec).toPointF(), (pos - widthVec).toPointF()); + break; + } + case esHalfBar: { + painter->drawLine((pos + widthVec).toPointF(), pos.toPointF()); + break; + } + case esSkewedBar: { + 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.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.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; + } } - case esDisc: - { - painter->setBrush(brush); - painter->drawEllipse(pos.toPointF(), mWidth*0.5, mWidth*0.5); - painter->setBrush(brushBackup); - break; - } - case esSquare: - { - QCPVector2D widthVecPerp = widthVec.perpendicular(); - QPointF points[4] = {(pos-widthVecPerp+widthVec).toPointF(), - (pos-widthVecPerp-widthVec).toPointF(), - (pos+widthVecPerp-widthVec).toPointF(), - (pos+widthVecPerp+widthVec).toPointF() - }; - painter->setPen(miterPen); - painter->setBrush(brush); - painter->drawConvexPolygon(points, 4); - painter->setBrush(brushBackup); - painter->setPen(penBackup); - break; - } - case esDiamond: - { - QCPVector2D widthVecPerp = widthVec.perpendicular(); - QPointF points[4] = {(pos-widthVecPerp).toPointF(), - (pos-widthVec).toPointF(), - (pos+widthVecPerp).toPointF(), - (pos+widthVec).toPointF() - }; - painter->setPen(miterPen); - painter->setBrush(brush); - painter->drawConvexPolygon(points, 4); - painter->setBrush(brushBackup); - painter->setPen(penBackup); - break; - } - case esBar: - { - painter->drawLine((pos+widthVec).toPointF(), (pos-widthVec).toPointF()); - break; - } - case esHalfBar: - { - painter->drawLine((pos+widthVec).toPointF(), pos.toPointF()); - break; - } - case esSkewedBar: - { - 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.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.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; - } - } } /*! \internal \overload - + Draws the line ending. The direction is controlled with the \a angle parameter in radians. */ void QCPLineEnding::draw(QCPPainter *painter, const QCPVector2D &pos, double angle) const { - draw(painter, pos, QCPVector2D(qCos(angle), qSin(angle))); + draw(painter, pos, QCPVector2D(qCos(angle), qSin(angle))); } /* end of 'src/lineending.cpp' */ @@ -5438,12 +5443,12 @@ void QCPLineEnding::draw(QCPPainter *painter, const QCPVector2D &pos, double ang //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \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. @@ -5451,10 +5456,10 @@ void QCPLineEnding::draw(QCPPainter *painter, const QCPVector2D &pos, double ang 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: - +
@@ -5466,25 +5471,25 @@ void QCPLineEnding::draw(QCPPainter *painter, const QCPVector2D &pos, double ang \image html axisticker-time2.png
QCPAxisTickerFixed\image html axisticker-fixed.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. */ @@ -5494,15 +5499,15 @@ void QCPLineEnding::draw(QCPPainter *painter, const QCPVector2D &pos, double ang managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker. */ QCPAxisTicker::QCPAxisTicker() : - mTickStepStrategy(tssReadability), - mTickCount(5), - mTickOrigin(0) + mTickStepStrategy(tssReadability), + mTickCount(5), + mTickOrigin(0) { } QCPAxisTicker::~QCPAxisTicker() { - + } /*! @@ -5511,7 +5516,7 @@ QCPAxisTicker::~QCPAxisTicker() */ void QCPAxisTicker::setTickStepStrategy(QCPAxisTicker::TickStepStrategy strategy) { - mTickStepStrategy = strategy; + mTickStepStrategy = strategy; } /*! @@ -5524,33 +5529,34 @@ void QCPAxisTicker::setTickStepStrategy(QCPAxisTicker::TickStepStrategy strategy */ void QCPAxisTicker::setTickCount(int count) { - if (count > 0) - mTickCount = count; - else - qDebug() << Q_FUNC_INFO << "tick count must be greater than zero:" << 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; + 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 @@ -5558,110 +5564,142 @@ void QCPAxisTicker::setTickOrigin(double origin) */ 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); + // 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); + 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 + 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 } - } 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; + + 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 @@ -5669,44 +5707,45 @@ int QCPAxisTicker::getSubTickCount(double tickStep) */ QString QCPAxisTicker::getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision) { - return locale.toString(tick, formatChar.toLatin1(), 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) + QVector result; + if (subTickCount <= 0 || ticks.size() < 2) { + return result; + } + + result.reserve((ticks.size() - 1)*subTickCount); + for (int i = 1; i < ticks.size(); ++i) { + double subTickStep = (ticks.at(i) - ticks.at(i - 1)) / (double)(subTickCount + 1); + for (int k = 1; k <= subTickCount; ++k) { + result.append(ticks.at(i - 1) + k * subTickStep); + } + } return result; - - result.reserve((ticks.size()-1)*subTickCount); - for (int i=1; i QCPAxisTicker::createSubTickVector(int subTickCount, const QVect */ QVector 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 result; + // Generate tick positions according to tickStep: + qint64 firstStep = floor((range.lower - mTickOrigin) / tickStep); // do not use qFloor here, or we'll lose 64 bit precision + qint64 lastStep = ceil((range.upper - mTickOrigin) / tickStep); // do not use qCeil here, or we'll lose 64 bit precision + int tickcount = lastStep - firstStep + 1; + if (tickcount < 0) { + tickcount = 0; + } + result.resize(tickcount); + for (int i = 0; i < tickcount; ++i) { + result[i] = mTickOrigin + (firstStep + i) * tickStep; + } + return result; } /*! \internal - + Returns a vector containing all tick label strings corresponding to the tick coordinates provided in \a ticks. The default implementation calls \ref getTickLabel to generate the respective strings. - + It is possible but uncommon for QCPAxisTicker subclasses to reimplement this method, as reimplementing \ref getTickLabel often achieves the intended result easier. */ QVector QCPAxisTicker::createLabelVector(const QVector &ticks, const QLocale &locale, QChar formatChar, int precision) { - QVector result; - result.reserve(ticks.size()); - for (int i=0; i result; + result.reserve(ticks.size()); + for (int i = 0; i < ticks.size(); ++i) { + result.append(getTickLabel(ticks.at(i), locale, formatChar, precision)); + } + return result; } /*! \internal - + Removes tick coordinates from \a ticks which lie outside the specified \a range. If \a keepOneOutlier is true, it preserves one tick just outside the range on both sides, if present. - + The passed \a ticks must be sorted in ascending order. */ void QCPAxisTicker::trimTicks(const QCPRange &range, QVector &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; + 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; + 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(); } - } - - 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; + 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; + 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; + 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 + } + } } - 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; + return input; } /* end of 'src/axis/axisticker.cpp' */ @@ -5858,9 +5900,9 @@ double QCPAxisTicker::cleanMantissa(double input) const //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \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 @@ -5868,25 +5910,25 @@ double QCPAxisTicker::cleanMantissa(double input) const 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. @@ -5897,24 +5939,24 @@ double QCPAxisTicker::cleanMantissa(double input) const 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) + mDateTimeFormat(QLatin1String("hh:mm:ss\ndd.MM.yy")), + mDateTimeSpec(Qt::LocalTime), + mDateStrategy(dsNone) { - setTickCount(4); + 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; + mDateTimeFormat = format; } /*! @@ -5924,224 +5966,255 @@ void QCPAxisTickerDateTime::setDateTimeFormat(const QString &format) 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; + 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); + 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)); + 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; + 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; + 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); + 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); - } + 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 < result.size(); ++i) { + tickDateTime = keyToDateTime(result.at(i)); + tickDateTime.setTime(uniformDateTime.time()); + result[i] = dateTimeToKey(tickDateTime); + } + } else if (mDateStrategy == dsUniformDayInMonth) { + QDateTime uniformDateTime = keyToDateTime(mTickOrigin); // this day (in month) and time will be set for all other ticks, if possible + QDateTime tickDateTime; + for (int i = 0; i < result.size(); ++i) { + tickDateTime = keyToDateTime(result.at(i)); + tickDateTime.setTime(uniformDateTime.time()); + int thisUniformDay = uniformDateTime.date().day() <= tickDateTime.date().daysInMonth() ? uniformDateTime.date().day() : tickDateTime.date().daysInMonth(); // don't exceed month (e.g. try to set day 31 in February) + if (thisUniformDay - tickDateTime.date().day() < -15) { // with leap years involved, date month may jump backwards or forwards, and needs to be corrected before setting day + tickDateTime = tickDateTime.addMonths(1); + } else if (thisUniformDay - tickDateTime.date().day() > 15) { // with leap years involved, date month may jump backwards or forwards, and needs to be corrected before setting day + tickDateTime = tickDateTime.addMonths(-1); + } + tickDateTime.setDate(QDate(tickDateTime.date().year(), tickDateTime.date().month(), thisUniformDay)); + result[i] = dateTimeToKey(tickDateTime); + } + } } - } - return result; + 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); + return QDateTime::fromTime_t(key).addMSecs((key - (qint64)key) * 1000); # else - return QDateTime::fromMSecsSinceEpoch(key*1000.0); + 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; + return dateTime.toTime_t() + dateTime.time().msec() / 1000.0; # else - return dateTime.toMSecsSinceEpoch()/1000.0; + 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(); + return QDateTime(date).toTime_t(); # else - return QDateTime(date).toMSecsSinceEpoch()/1000.0; + return QDateTime(date).toMSecsSinceEpoch() / 1000.0; # endif } /* end of 'src/axis/axistickerdatetime.cpp' */ @@ -6155,16 +6228,16 @@ double QCPAxisTickerDateTime::dateTimeToKey(const QDate date) //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \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 @@ -6172,19 +6245,19 @@ double QCPAxisTickerDateTime::dateTimeToKey(const QDate date) 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. */ @@ -6194,36 +6267,36 @@ double QCPAxisTickerDateTime::dateTimeToKey(const QDate date) managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker. */ QCPAxisTickerTime::QCPAxisTickerTime() : - mTimeFormat(QLatin1String("%h:%m:%s")), - mSmallestUnit(tuSeconds), - mBiggestUnit(tuHours) + 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"); + 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 @@ -6232,38 +6305,35 @@ QCPAxisTickerTime::QCPAxisTickerTime() : */ 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; + 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); + mFieldWidth[unit] = qMax(width, 1); } /*! \internal @@ -6272,126 +6342,153 @@ void QCPAxisTickerTime::setFieldWidth(QCPAxisTickerTime::TimeUnit unit, int widt 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; + 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; + 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; + 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); + 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' */ @@ -6404,20 +6501,20 @@ void QCPAxisTickerTime::replaceUnit(QString &text, QCPAxisTickerTime::TimeUnit u //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \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 */ @@ -6427,14 +6524,14 @@ void QCPAxisTickerTime::replaceUnit(QString &text, QCPAxisTickerTime::TimeUnit u managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker. */ QCPAxisTickerFixed::QCPAxisTickerFixed() : - mTickStep(1.0), - mScaleStrategy(ssNone) + 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 @@ -6443,57 +6540,55 @@ QCPAxisTickerFixed::QCPAxisTickerFixed() : */ void QCPAxisTickerFixed::setTickStep(double step) { - if (step > 0) - mTickStep = step; - else - qDebug() << Q_FUNC_INFO << "tick step must be greater than zero:" << 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; + 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; + 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)); + } } - 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; + return mTickStep; } /* end of 'src/axis/axistickerfixed.cpp' */ @@ -6506,20 +6601,20 @@ double QCPAxisTickerFixed::getTickStep(const QCPRange &range) //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \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 */ @@ -6527,7 +6622,7 @@ double QCPAxisTickerFixed::getTickStep(const QCPRange &range) /* 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. @@ -6542,37 +6637,37 @@ double QCPAxisTickerFixed::getTickStep(const QCPRange &range) managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker. */ QCPAxisTickerText::QCPAxisTickerText() : - mSubTickCount(0) + 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; + 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); + clear(); + addTicks(positions, labels); } /*! @@ -6582,131 +6677,140 @@ void QCPAxisTickerText::setTicks(const QVector &positions, const QVector */ void QCPAxisTickerText::setSubTickCount(int subTicks) { - if (subTicks >= 0) - mSubTickCount = subTicks; - else - qDebug() << Q_FUNC_INFO << "sub tick count can't be negative:" << 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(); + 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, const QString &label) { - mTicks.insert(position, 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); + 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()) + 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; - - 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' */ @@ -6719,16 +6823,16 @@ QVector QCPAxisTickerText::createTickVector(double tickStep, const QCPRa //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \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 */ @@ -6738,25 +6842,25 @@ QVector QCPAxisTickerText::createTickVector(double tickStep, const QCPRa 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) + mPiSymbol(QLatin1String(" ") + QChar(0x03C0)), + mPiValue(M_PI), + mPeriodicity(0), + mFractionStyle(fsUnicodeFractions), + mPiTickStep(0) { - setTickCount(4); + 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; + mPiSymbol = symbol; } /*! @@ -6767,20 +6871,20 @@ void QCPAxisTickerPi::setPiSymbol(QString symbol) */ void QCPAxisTickerPi::setPiValue(double pi) { - mPiValue = 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); + mPeriodicity = qAbs(multiplesOfPi); } /*! @@ -6789,211 +6893,215 @@ void QCPAxisTickerPi::setPeriodicity(int multiplesOfPi) */ void QCPAxisTickerPi::setFractionStyle(QCPAxisTickerPi::FractionStyle style) { - mFractionStyle = 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; + 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); + 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; - } + 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; + 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)); - } + if (denominator == 0) { + qDebug() << Q_FUNC_INFO << "called with zero denominator"; + return QString(); } - } - 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); + 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; } + if (number == 0) { + return QString(QChar(0x2070)); } - number /= 10; - } - return result; + + 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; + 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' */ @@ -7006,18 +7114,18 @@ QString QCPAxisTickerPi::unicodeSubscript(int number) const //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \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: @@ -7029,9 +7137,9 @@ QString QCPAxisTickerPi::unicodeSubscript(int number) const 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)) + mLogBase(10.0), + mSubTickCount(8), // generates 10 intervals + mLogBaseLnInv(1.0 / qLn(mLogBase)) { } @@ -7041,19 +7149,19 @@ QCPAxisTickerLog::QCPAxisTickerLog() : */ 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; + 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, @@ -7061,80 +7169,76 @@ void QCPAxisTickerLog::setLogBase(double base) */ void QCPAxisTickerLog::setSubTickCount(int subTicks) { - if (subTicks >= 0) - mSubTickCount = subTicks; - else - qDebug() << Q_FUNC_INFO << "sub tick count can't be negative:" << 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; + // 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; + 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); + 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; } - } 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; + + return result; } /* end of 'src/axis/axistickerlog.cpp' */ @@ -7149,11 +7253,11 @@ QVector QCPAxisTickerLog::createTickVector(double tickStep, const QCPRan /*! \class QCPGrid \brief Responsible for drawing the grid of a QCPAxis. - + This class is tightly bound to QCPAxis. Every axis owns a grid instance and uses it to draw the grid lines, sub grid lines and zero-line. You can interact with the grid of an axis via \ref QCPAxis::grid. Normally, you don't need to create an instance of QCPGrid yourself. - + The axis and grid drawing was split into two classes to allow them to be placed on different layers (both QCPAxis and QCPGrid inherit from QCPLayerable). Thus it is possible to have the grid in the background and the axes in the foreground, and any plottables/items in between. This @@ -7162,32 +7266,32 @@ QVector QCPAxisTickerLog::createTickVector(double tickStep, const QCPRan /*! Creates a QCPGrid instance and sets default values. - + You shouldn't instantiate grids on their own, since every QCPAxis brings its own QCPGrid. */ QCPGrid::QCPGrid(QCPAxis *parentAxis) : - QCPLayerable(parentAxis->parentPlot(), QString(), parentAxis), - mParentAxis(parentAxis) + QCPLayerable(parentAxis->parentPlot(), QString(), parentAxis), + mParentAxis(parentAxis) { - // warning: this is called in QCPAxis constructor, so parentAxis members should not be accessed/called - setParent(parentAxis); - setPen(QPen(QColor(200,200,200), 0, Qt::DotLine)); - setSubGridPen(QPen(QColor(220,220,220), 0, Qt::DotLine)); - setZeroLinePen(QPen(QColor(200,200,200), 0, Qt::SolidLine)); - setSubGridVisible(false); - setAntialiased(false); - setAntialiasedSubGrid(false); - setAntialiasedZeroLine(false); + // warning: this is called in QCPAxis constructor, so parentAxis members should not be accessed/called + setParent(parentAxis); + setPen(QPen(QColor(200, 200, 200), 0, Qt::DotLine)); + setSubGridPen(QPen(QColor(220, 220, 220), 0, Qt::DotLine)); + setZeroLinePen(QPen(QColor(200, 200, 200), 0, Qt::SolidLine)); + setSubGridVisible(false); + setAntialiased(false); + setAntialiasedSubGrid(false); + setAntialiasedZeroLine(false); } /*! Sets whether grid lines at sub tick marks are drawn. - + \see setSubGridPen */ void QCPGrid::setSubGridVisible(bool visible) { - mSubGridVisible = visible; + mSubGridVisible = visible; } /*! @@ -7195,7 +7299,7 @@ void QCPGrid::setSubGridVisible(bool visible) */ void QCPGrid::setAntialiasedSubGrid(bool enabled) { - mAntialiasedSubGrid = enabled; + mAntialiasedSubGrid = enabled; } /*! @@ -7203,7 +7307,7 @@ void QCPGrid::setAntialiasedSubGrid(bool enabled) */ void QCPGrid::setAntialiasedZeroLine(bool enabled) { - mAntialiasedZeroLine = enabled; + mAntialiasedZeroLine = enabled; } /*! @@ -7211,7 +7315,7 @@ void QCPGrid::setAntialiasedZeroLine(bool enabled) */ void QCPGrid::setPen(const QPen &pen) { - mPen = pen; + mPen = pen; } /*! @@ -7219,18 +7323,18 @@ void QCPGrid::setPen(const QPen &pen) */ void QCPGrid::setSubGridPen(const QPen &pen) { - mSubGridPen = pen; + mSubGridPen = pen; } /*! Sets the pen with which zero lines are drawn. - + Zero lines are lines at value coordinate 0 which may be drawn with a different pen than other grid lines. To disable zero lines and just draw normal grid lines at zero, set \a pen to Qt::NoPen. */ void QCPGrid::setZeroLinePen(const QPen &pen) { - mZeroLinePen = pen; + mZeroLinePen = pen; } /*! \internal @@ -7239,133 +7343,133 @@ void QCPGrid::setZeroLinePen(const QPen &pen) before drawing the major grid lines. This is the antialiasing state the painter passed to the \ref draw method is in by default. - + 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 */ void QCPGrid::applyDefaultAntialiasingHint(QCPPainter *painter) const { - applyAntialiasingHint(painter, mAntialiased, QCP::aeGrid); + applyAntialiasingHint(painter, mAntialiased, QCP::aeGrid); } /*! \internal - + Draws grid lines and sub grid lines at the positions of (sub) ticks of the parent axis, spanning over the complete axis rect. Also draws the zero line, if appropriate (\ref setZeroLinePen). */ void QCPGrid::draw(QCPPainter *painter) { - if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; } - - if (mParentAxis->subTicks() && mSubGridVisible) - drawSubGridLines(painter); - drawGridLines(painter); + if (!mParentAxis) { + qDebug() << Q_FUNC_INFO << "invalid parent axis"; + return; + } + + if (mParentAxis->subTicks() && mSubGridVisible) { + drawSubGridLines(painter); + } + drawGridLines(painter); } /*! \internal - + Draws the main grid lines and possibly a zero line with the specified painter. - + This is a helper function called by \ref draw. */ void QCPGrid::drawGridLines(QCPPainter *painter) const { - if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; } - - const int tickCount = mParentAxis->mTickVector.size(); - double t; // helper variable, result of coordinate-to-pixel transforms - if (mParentAxis->orientation() == Qt::Horizontal) - { - // draw zeroline: - int zeroLineIndex = -1; - if (mZeroLinePen.style() != Qt::NoPen && mParentAxis->mRange.lower < 0 && mParentAxis->mRange.upper > 0) - { - applyAntialiasingHint(painter, mAntialiasedZeroLine, QCP::aeZeroLine); - painter->setPen(mZeroLinePen); - double epsilon = mParentAxis->range().size()*1E-6; // for comparing double to zero - for (int i=0; imTickVector.at(i)) < epsilon) - { - zeroLineIndex = i; - t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // x - painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top())); - break; + if (!mParentAxis) { + qDebug() << Q_FUNC_INFO << "invalid parent axis"; + return; + } + + const int tickCount = mParentAxis->mTickVector.size(); + double t; // helper variable, result of coordinate-to-pixel transforms + if (mParentAxis->orientation() == Qt::Horizontal) { + // draw zeroline: + int zeroLineIndex = -1; + if (mZeroLinePen.style() != Qt::NoPen && mParentAxis->mRange.lower < 0 && mParentAxis->mRange.upper > 0) { + applyAntialiasingHint(painter, mAntialiasedZeroLine, QCP::aeZeroLine); + painter->setPen(mZeroLinePen); + double epsilon = mParentAxis->range().size() * 1E-6; // for comparing double to zero + for (int i = 0; i < tickCount; ++i) { + if (qAbs(mParentAxis->mTickVector.at(i)) < epsilon) { + zeroLineIndex = i; + t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // x + painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top())); + break; + } + } } - } - } - // draw grid lines: - applyDefaultAntialiasingHint(painter); - painter->setPen(mPen); - for (int i=0; icoordToPixel(mParentAxis->mTickVector.at(i)); // x - painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top())); - } - } else - { - // draw zeroline: - int zeroLineIndex = -1; - if (mZeroLinePen.style() != Qt::NoPen && mParentAxis->mRange.lower < 0 && mParentAxis->mRange.upper > 0) - { - applyAntialiasingHint(painter, mAntialiasedZeroLine, QCP::aeZeroLine); - painter->setPen(mZeroLinePen); - double epsilon = mParentAxis->mRange.size()*1E-6; // for comparing double to zero - for (int i=0; imTickVector.at(i)) < epsilon) - { - zeroLineIndex = i; - t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // y - painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t)); - break; + // draw grid lines: + applyDefaultAntialiasingHint(painter); + painter->setPen(mPen); + for (int i = 0; i < tickCount; ++i) { + if (i == zeroLineIndex) { + continue; // don't draw a gridline on top of the zeroline + } + t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // x + painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top())); + } + } else { + // draw zeroline: + int zeroLineIndex = -1; + if (mZeroLinePen.style() != Qt::NoPen && mParentAxis->mRange.lower < 0 && mParentAxis->mRange.upper > 0) { + applyAntialiasingHint(painter, mAntialiasedZeroLine, QCP::aeZeroLine); + painter->setPen(mZeroLinePen); + double epsilon = mParentAxis->mRange.size() * 1E-6; // for comparing double to zero + for (int i = 0; i < tickCount; ++i) { + if (qAbs(mParentAxis->mTickVector.at(i)) < epsilon) { + zeroLineIndex = i; + t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // y + painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t)); + break; + } + } + } + // draw grid lines: + applyDefaultAntialiasingHint(painter); + painter->setPen(mPen); + for (int i = 0; i < tickCount; ++i) { + if (i == zeroLineIndex) { + continue; // don't draw a gridline on top of the zeroline + } + t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // y + painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t)); } - } } - // draw grid lines: - applyDefaultAntialiasingHint(painter); - painter->setPen(mPen); - for (int i=0; icoordToPixel(mParentAxis->mTickVector.at(i)); // y - painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t)); - } - } } /*! \internal - + Draws the sub grid lines with the specified painter. - + This is a helper function called by \ref draw. */ void QCPGrid::drawSubGridLines(QCPPainter *painter) const { - if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; } - - applyAntialiasingHint(painter, mAntialiasedSubGrid, QCP::aeSubGrid); - double t; // helper variable, result of coordinate-to-pixel transforms - painter->setPen(mSubGridPen); - if (mParentAxis->orientation() == Qt::Horizontal) - { - for (int i=0; imSubTickVector.size(); ++i) - { - t = mParentAxis->coordToPixel(mParentAxis->mSubTickVector.at(i)); // x - painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top())); + if (!mParentAxis) { + qDebug() << Q_FUNC_INFO << "invalid parent axis"; + return; } - } else - { - for (int i=0; imSubTickVector.size(); ++i) - { - t = mParentAxis->coordToPixel(mParentAxis->mSubTickVector.at(i)); // y - painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t)); + + applyAntialiasingHint(painter, mAntialiasedSubGrid, QCP::aeSubGrid); + double t; // helper variable, result of coordinate-to-pixel transforms + painter->setPen(mSubGridPen); + if (mParentAxis->orientation() == Qt::Horizontal) { + for (int i = 0; i < mParentAxis->mSubTickVector.size(); ++i) { + t = mParentAxis->coordToPixel(mParentAxis->mSubTickVector.at(i)); // x + painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top())); + } + } else { + for (int i = 0; i < mParentAxis->mSubTickVector.size(); ++i) { + t = mParentAxis->coordToPixel(mParentAxis->mSubTickVector.at(i)); // y + painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t)); + } } - } } @@ -7379,16 +7483,16 @@ void QCPGrid::drawSubGridLines(QCPPainter *painter) const Usually doesn't need to be instantiated externally. Access %QCustomPlot's default four axes via QCustomPlot::xAxis (bottom), QCustomPlot::yAxis (left), QCustomPlot::xAxis2 (top) and QCustomPlot::yAxis2 (right). - + Axes are always part of an axis rect, see QCPAxisRect. \image html AxisNamesOverview.png
Naming convention of axis parts
\n - + \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 @@ -7406,7 +7510,7 @@ void QCPGrid::drawSubGridLines(QCPPainter *painter) const */ /*! \fn QCPGrid *QCPAxis::grid() const - + Returns the \ref QCPGrid instance belonging to this axis. Access it to set details about the way the grid is displayed. */ @@ -7461,7 +7565,7 @@ void QCPGrid::drawSubGridLines(QCPPainter *painter) const This signal is emitted when the range of this axis has changed. You can connect it to the \ref setRange slot of another axis to communicate the new range to the other axis, in order for it to be synchronized. - + 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 (see \ref QCPRange::bounded). For example, the following @@ -7473,24 +7577,24 @@ void QCPGrid::drawSubGridLines(QCPPainter *painter) const /*! \fn void QCPAxis::rangeChanged(const QCPRange &newRange, const QCPRange &oldRange) \overload - + Additionally to the new range, this signal also provides the previous range held by the axis as \a oldRange. */ /*! \fn void QCPAxis::scaleTypeChanged(QCPAxis::ScaleType scaleType); - + This signal is emitted when the scale type changes, by calls to \ref setScaleType */ /*! \fn void QCPAxis::selectionChanged(QCPAxis::SelectableParts selection) - + This signal is emitted when the selection state of this axis has changed, either by user interaction or by a direct call to \ref setSelectedParts. */ /*! \fn void QCPAxis::selectableChanged(const QCPAxis::SelectableParts &parts); - + This signal is emitted when the selectability changes, by calls to \ref setSelectableParts */ @@ -7498,294 +7602,290 @@ void QCPGrid::drawSubGridLines(QCPPainter *painter) const /*! Constructs an Axis instance of Type \a type for the axis rect \a parent. - + Usually it isn't necessary to instantiate axes directly, because you can let QCustomPlot create them for you with \ref QCPAxisRect::addAxis. If you want to use own QCPAxis-subclasses however, create them manually and then inject them also via \ref QCPAxisRect::addAxis. */ QCPAxis::QCPAxis(QCPAxisRect *parent, AxisType type) : - QCPLayerable(parent->parentPlot(), QString(), parent), - // axis base: - mAxisType(type), - mAxisRect(parent), - mPadding(5), - mOrientation(orientation(type)), - mSelectableParts(spAxis | spTickLabels | spAxisLabel), - mSelectedParts(spNone), - mBasePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), - mSelectedBasePen(QPen(Qt::blue, 2)), - // axis label: - mLabel(), - mLabelFont(mParentPlot->font()), - mSelectedLabelFont(QFont(mLabelFont.family(), mLabelFont.pointSize(), QFont::Bold)), - mLabelColor(Qt::black), - mSelectedLabelColor(Qt::blue), - // tick labels: - mTickLabels(true), - mTickLabelFont(mParentPlot->font()), - mSelectedTickLabelFont(QFont(mTickLabelFont.family(), mTickLabelFont.pointSize(), QFont::Bold)), - mTickLabelColor(Qt::black), - mSelectedTickLabelColor(Qt::blue), - mNumberPrecision(6), - mNumberFormatChar('g'), - mNumberBeautifulPowers(true), - // ticks and subticks: - mTicks(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)), - mSelectedSubTickPen(QPen(Qt::blue, 2)), - // scale and range: - mRange(0, 5), - mRangeReversed(false), - mScaleType(stLinear), - // internal members: - mGrid(new QCPGrid(this)), - mAxisPainter(new QCPAxisPainterPrivate(parent->parentPlot())), - mTicker(new QCPAxisTicker), - mCachedMarginValid(false), - mCachedMargin(0) + QCPLayerable(parent->parentPlot(), QString(), parent), + // axis base: + mAxisType(type), + mAxisRect(parent), + mPadding(5), + mOrientation(orientation(type)), + mSelectableParts(spAxis | spTickLabels | spAxisLabel), + mSelectedParts(spNone), + mBasePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), + mSelectedBasePen(QPen(Qt::blue, 2)), + // axis label: + mLabel(), + mLabelFont(mParentPlot->font()), + mSelectedLabelFont(QFont(mLabelFont.family(), mLabelFont.pointSize(), QFont::Bold)), + mLabelColor(Qt::black), + mSelectedLabelColor(Qt::blue), + // tick labels: + mTickLabels(true), + mTickLabelFont(mParentPlot->font()), + mSelectedTickLabelFont(QFont(mTickLabelFont.family(), mTickLabelFont.pointSize(), QFont::Bold)), + mTickLabelColor(Qt::black), + mSelectedTickLabelColor(Qt::blue), + mNumberPrecision(6), + mNumberFormatChar('g'), + mNumberBeautifulPowers(true), + // ticks and subticks: + mTicks(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)), + mSelectedSubTickPen(QPen(Qt::blue, 2)), + // scale and range: + mRange(0, 5), + mRangeReversed(false), + mScaleType(stLinear), + // internal members: + mGrid(new QCPGrid(this)), + mAxisPainter(new QCPAxisPainterPrivate(parent->parentPlot())), + 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 - - if (type == atTop) - { - setTickLabelPadding(3); - setLabelPadding(6); - } else if (type == atRight) - { - setTickLabelPadding(7); - setLabelPadding(12); - } else if (type == atBottom) - { - setTickLabelPadding(3); - setLabelPadding(3); - } else if (type == atLeft) - { - setTickLabelPadding(5); - setLabelPadding(10); - } + 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 + + if (type == atTop) { + setTickLabelPadding(3); + setLabelPadding(6); + } else if (type == atRight) { + setTickLabelPadding(7); + setLabelPadding(12); + } else if (type == atBottom) { + setTickLabelPadding(3); + setLabelPadding(3); + } else if (type == atLeft) { + setTickLabelPadding(5); + setLabelPadding(10); + } } QCPAxis::~QCPAxis() { - delete mAxisPainter; - delete mGrid; // delete grid here instead of via parent ~QObject for better defined deletion order + delete mAxisPainter; + delete mGrid; // delete grid here instead of via parent ~QObject for better defined deletion order } /* No documentation as it is a property getter */ int QCPAxis::tickLabelPadding() const { - return mAxisPainter->tickLabelPadding; + return mAxisPainter->tickLabelPadding; } /* No documentation as it is a property getter */ double QCPAxis::tickLabelRotation() const { - return mAxisPainter->tickLabelRotation; + return mAxisPainter->tickLabelRotation; } /* No documentation as it is a property getter */ QCPAxis::LabelSide QCPAxis::tickLabelSide() const { - return mAxisPainter->tickLabelSide; + return mAxisPainter->tickLabelSide; } /* No documentation as it is a property getter */ QString QCPAxis::numberFormat() const { - QString result; - result.append(mNumberFormatChar); - if (mNumberBeautifulPowers) - { - result.append(QLatin1Char('b')); - if (mAxisPainter->numberMultiplyCross) - result.append(QLatin1Char('c')); - } - return result; + QString result; + result.append(mNumberFormatChar); + if (mNumberBeautifulPowers) { + result.append(QLatin1Char('b')); + if (mAxisPainter->numberMultiplyCross) { + result.append(QLatin1Char('c')); + } + } + return result; } /* No documentation as it is a property getter */ int QCPAxis::tickLengthIn() const { - return mAxisPainter->tickLengthIn; + return mAxisPainter->tickLengthIn; } /* No documentation as it is a property getter */ int QCPAxis::tickLengthOut() const { - return mAxisPainter->tickLengthOut; + return mAxisPainter->tickLengthOut; } /* No documentation as it is a property getter */ int QCPAxis::subTickLengthIn() const { - return mAxisPainter->subTickLengthIn; + return mAxisPainter->subTickLengthIn; } /* No documentation as it is a property getter */ int QCPAxis::subTickLengthOut() const { - return mAxisPainter->subTickLengthOut; + return mAxisPainter->subTickLengthOut; } /* No documentation as it is a property getter */ int QCPAxis::labelPadding() const { - return mAxisPainter->labelPadding; + return mAxisPainter->labelPadding; } /* No documentation as it is a property getter */ int QCPAxis::offset() const { - return mAxisPainter->offset; + return mAxisPainter->offset; } /* No documentation as it is a property getter */ QCPLineEnding QCPAxis::lowerEnding() const { - return mAxisPainter->lowerEnding; + return mAxisPainter->lowerEnding; } /* No documentation as it is a property getter */ QCPLineEnding QCPAxis::upperEnding() const { - return mAxisPainter->upperEnding; + return mAxisPainter->upperEnding; } /*! Sets whether the axis uses a linear scale or a logarithmic scale. - + Note that this method controls the coordinate transformation. For logarithmic scales, you will likely also want to use a logarithmic tick spacing and labeling, which can be achieved by setting the axis ticker to an instance of \ref QCPAxisTickerLog : - + \snippet documentation/doc-code-snippets/mainwindow.cpp qcpaxisticker-log-creation - + See the documentation of \ref QCPAxisTickerLog about the details of logarithmic axis tick creation. - + \ref setNumberPrecision */ void QCPAxis::setScaleType(QCPAxis::ScaleType type) { - if (mScaleType != type) - { - mScaleType = type; - if (mScaleType == stLogarithmic) - setRange(mRange.sanitizedForLogScale()); - mCachedMarginValid = false; - emit scaleTypeChanged(mScaleType); - } + if (mScaleType != type) { + mScaleType = type; + if (mScaleType == stLogarithmic) { + setRange(mRange.sanitizedForLogScale()); + } + mCachedMarginValid = false; + emit scaleTypeChanged(mScaleType); + } } /*! Sets the range of the axis. - + This slot may be connected with the \ref rangeChanged signal of another axis so this axis is always synchronized with the other axis range, when it changes. - + To invert the direction of an axis, use \ref setRangeReversed. */ void QCPAxis::setRange(const QCPRange &range) { - if (range.lower == mRange.lower && range.upper == mRange.upper) - return; - - if (!QCPRange::validRange(range)) return; - QCPRange oldRange = mRange; - if (mScaleType == stLogarithmic) - { - mRange = range.sanitizedForLogScale(); - } else - { - mRange = range.sanitizedForLinScale(); - } - emit rangeChanged(mRange); - emit rangeChanged(mRange, oldRange); + if (range.lower == mRange.lower && range.upper == mRange.upper) { + return; + } + + if (!QCPRange::validRange(range)) { + return; + } + QCPRange oldRange = mRange; + if (mScaleType == stLogarithmic) { + mRange = range.sanitizedForLogScale(); + } else { + mRange = range.sanitizedForLinScale(); + } + emit rangeChanged(mRange); + emit rangeChanged(mRange, oldRange); } /*! Sets whether the user can (de-)select the parts in \a selectable by clicking on the QCustomPlot surface. (When \ref QCustomPlot::setInteractions contains iSelectAxes.) - + However, even when \a selectable is set to a value not allowing the selection of a specific part, it is still possible to set the selection of this part manually, by calling \ref setSelectedParts directly. - + \see SelectablePart, setSelectedParts */ void QCPAxis::setSelectableParts(const SelectableParts &selectable) { - if (mSelectableParts != selectable) - { - mSelectableParts = selectable; - emit selectableChanged(mSelectableParts); - } + if (mSelectableParts != selectable) { + mSelectableParts = selectable; + emit selectableChanged(mSelectableParts); + } } /*! Sets the selected state of the respective axis parts described by \ref SelectablePart. When a part is selected, it uses a different pen/font. - + The entire selection mechanism for axes is handled automatically when \ref QCustomPlot::setInteractions contains iSelectAxes. You only need to call this function when you wish to change the selection state manually. - + This function can change the selection state of a part, independent of the \ref setSelectableParts setting. - + emits the \ref selectionChanged signal when \a selected is different from the previous selection state. - + \see SelectablePart, setSelectableParts, selectTest, setSelectedBasePen, setSelectedTickPen, setSelectedSubTickPen, setSelectedTickLabelFont, setSelectedLabelFont, setSelectedTickLabelColor, setSelectedLabelColor */ void QCPAxis::setSelectedParts(const SelectableParts &selected) { - if (mSelectedParts != selected) - { - mSelectedParts = selected; - emit selectionChanged(mSelectedParts); - } + if (mSelectedParts != selected) { + mSelectedParts = selected; + emit selectionChanged(mSelectedParts); + } } /*! \overload - + Sets the lower and upper bound of the axis range. - + To invert the direction of an axis, use \ref setRangeReversed. - + There is also a slot to set a range, see \ref setRange(const QCPRange &range). */ void QCPAxis::setRange(double lower, double upper) { - if (lower == mRange.lower && upper == mRange.upper) - return; - - if (!QCPRange::validRange(lower, upper)) return; - QCPRange oldRange = mRange; - mRange.lower = lower; - mRange.upper = upper; - if (mScaleType == stLogarithmic) - { - mRange = mRange.sanitizedForLogScale(); - } else - { - mRange = mRange.sanitizedForLinScale(); - } - emit rangeChanged(mRange); - emit rangeChanged(mRange, oldRange); + if (lower == mRange.lower && upper == mRange.upper) { + return; + } + + if (!QCPRange::validRange(lower, upper)) { + return; + } + QCPRange oldRange = mRange; + mRange.lower = lower; + mRange.upper = upper; + if (mScaleType == stLogarithmic) { + mRange = mRange.sanitizedForLogScale(); + } else { + mRange = mRange.sanitizedForLinScale(); + } + emit rangeChanged(mRange); + emit rangeChanged(mRange, oldRange); } /*! \overload - + Sets the range of the axis. - + The \a position coordinate indicates together with the \a alignment parameter, where the new range will be positioned. \a size defines the size of the new axis range. \a alignment may be Qt::AlignLeft, Qt::AlignRight or Qt::AlignCenter. This will cause the left border, right border, @@ -7794,12 +7894,13 @@ void QCPAxis::setRange(double lower, double upper) */ void QCPAxis::setRange(double position, double size, Qt::AlignmentFlag alignment) { - if (alignment == Qt::AlignLeft) - setRange(position, position+size); - else if (alignment == Qt::AlignRight) - setRange(position-size, position); - else // alignment == Qt::AlignCenter - setRange(position-size/2.0, position+size/2.0); + if (alignment == Qt::AlignLeft) { + setRange(position, position + size); + } else if (alignment == Qt::AlignRight) { + setRange(position - size, position); + } else { // alignment == Qt::AlignCenter + setRange(position - size / 2.0, position + size / 2.0); + } } /*! @@ -7808,20 +7909,19 @@ void QCPAxis::setRange(double position, double size, Qt::AlignmentFlag alignment */ void QCPAxis::setRangeLower(double lower) { - if (mRange.lower == lower) - return; - - QCPRange oldRange = mRange; - mRange.lower = lower; - if (mScaleType == stLogarithmic) - { - mRange = mRange.sanitizedForLogScale(); - } else - { - mRange = mRange.sanitizedForLinScale(); - } - emit rangeChanged(mRange); - emit rangeChanged(mRange, oldRange); + if (mRange.lower == lower) { + return; + } + + QCPRange oldRange = mRange; + mRange.lower = lower; + if (mScaleType == stLogarithmic) { + mRange = mRange.sanitizedForLogScale(); + } else { + mRange = mRange.sanitizedForLinScale(); + } + emit rangeChanged(mRange); + emit rangeChanged(mRange, oldRange); } /*! @@ -7830,20 +7930,19 @@ void QCPAxis::setRangeLower(double lower) */ void QCPAxis::setRangeUpper(double upper) { - if (mRange.upper == upper) - return; - - QCPRange oldRange = mRange; - mRange.upper = upper; - if (mScaleType == stLogarithmic) - { - mRange = mRange.sanitizedForLogScale(); - } else - { - mRange = mRange.sanitizedForLinScale(); - } - emit rangeChanged(mRange); - emit rangeChanged(mRange, oldRange); + if (mRange.upper == upper) { + return; + } + + QCPRange oldRange = mRange; + mRange.upper = upper; + if (mScaleType == stLogarithmic) { + mRange = mRange.sanitizedForLogScale(); + } else { + mRange = mRange.sanitizedForLinScale(); + } + emit rangeChanged(mRange); + emit rangeChanged(mRange, oldRange); } /*! @@ -7857,29 +7956,30 @@ void QCPAxis::setRangeUpper(double upper) */ void QCPAxis::setRangeReversed(bool reversed) { - mRangeReversed = reversed; + mRangeReversed = reversed; } /*! 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. - + 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. - + 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 ticker */ void QCPAxis::setTicker(QSharedPointer ticker) { - 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 + 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 } /*! @@ -7887,16 +7987,15 @@ void QCPAxis::setTicker(QSharedPointer ticker) 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) { - if (mTicks != show) - { - mTicks = show; - mCachedMarginValid = false; - } + if (mTicks != show) { + mTicks = show; + mCachedMarginValid = false; + } } /*! @@ -7904,13 +8003,13 @@ void QCPAxis::setTicks(bool show) */ void QCPAxis::setTickLabels(bool show) { - if (mTickLabels != show) - { - mTickLabels = show; - mCachedMarginValid = false; - if (!mTickLabels) - mTickVectorLabels.clear(); - } + if (mTickLabels != show) { + mTickLabels = show; + mCachedMarginValid = false; + if (!mTickLabels) { + mTickVectorLabels.clear(); + } + } } /*! @@ -7919,77 +8018,74 @@ void QCPAxis::setTickLabels(bool show) */ void QCPAxis::setTickLabelPadding(int padding) { - if (mAxisPainter->tickLabelPadding != padding) - { - mAxisPainter->tickLabelPadding = padding; - mCachedMarginValid = false; - } + if (mAxisPainter->tickLabelPadding != padding) { + mAxisPainter->tickLabelPadding = padding; + mCachedMarginValid = false; + } } /*! Sets the font of the tick labels. - + \see setTickLabels, setTickLabelColor */ void QCPAxis::setTickLabelFont(const QFont &font) { - if (font != mTickLabelFont) - { - mTickLabelFont = font; - mCachedMarginValid = false; - } + if (font != mTickLabelFont) { + mTickLabelFont = font; + mCachedMarginValid = false; + } } /*! Sets the color of the tick labels. - + \see setTickLabels, setTickLabelFont */ void QCPAxis::setTickLabelColor(const QColor &color) { - mTickLabelColor = color; + mTickLabelColor = color; } /*! Sets the rotation of the tick labels. If \a degrees is zero, the labels are drawn normally. Else, the tick labels are drawn rotated by \a degrees clockwise. The specified angle is bound to values from -90 to 90 degrees. - + If \a degrees is exactly -90, 0 or 90, the tick labels are centered on the tick coordinate. For other angles, the label is drawn with an offset such that it seems to point toward or away from the tick mark. */ void QCPAxis::setTickLabelRotation(double degrees) { - if (!qFuzzyIsNull(degrees-mAxisPainter->tickLabelRotation)) - { - mAxisPainter->tickLabelRotation = qBound(-90.0, degrees, 90.0); - mCachedMarginValid = false; - } + if (!qFuzzyIsNull(degrees - mAxisPainter->tickLabelRotation)) { + mAxisPainter->tickLabelRotation = qBound(-90.0, degrees, 90.0); + mCachedMarginValid = false; + } } /*! Sets whether the tick labels (numbers) shall appear inside or outside the axis rect. - + The usual and default setting is \ref lsOutside. Very compact plots sometimes require tick labels to be inside the axis rect, to save space. If \a side is set to \ref lsInside, the tick labels appear on the inside are additionally clipped to the axis rect. */ void QCPAxis::setTickLabelSide(LabelSide side) { - mAxisPainter->tickLabelSide = side; - mCachedMarginValid = false; + mAxisPainter->tickLabelSide = side; + mCachedMarginValid = false; } /*! 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. - + \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. "5.5e9", which is ugly in a plot. So when the second char of \a formatCode is set to 'b' (for @@ -7998,7 +8094,7 @@ void QCPAxis::setTickLabelSide(LabelSide side) If instead a cross should be shown (as is usual in the USA), the third char of \a formatCode can be set to 'c'. The inserted multiplication signs are the UTF-8 characters 215 (0xD7) for the cross and 183 (0xB7) for the dot. - + 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 @@ -8013,57 +8109,47 @@ void QCPAxis::setTickLabelSide(LabelSide side) */ void QCPAxis::setNumberFormat(const QString &formatCode) { - if (formatCode.isEmpty()) - { - qDebug() << Q_FUNC_INFO << "Passed formatCode is empty"; - return; - } - mCachedMarginValid = false; - - // interpret first char as number format char: - QString allowedFormatChars(QLatin1String("eEfgG")); - if (allowedFormatChars.contains(formatCode.at(0))) - { - mNumberFormatChar = QLatin1Char(formatCode.at(0).toLatin1()); - } else - { - qDebug() << Q_FUNC_INFO << "Invalid number format code (first char not in 'eEfgG'):" << formatCode; - return; - } - if (formatCode.length() < 2) - { - mNumberBeautifulPowers = false; - mAxisPainter->numberMultiplyCross = false; - return; - } - - // interpret second char as indicator for beautiful decimal powers: - if (formatCode.at(1) == QLatin1Char('b') && (mNumberFormatChar == QLatin1Char('e') || mNumberFormatChar == QLatin1Char('g'))) - { - mNumberBeautifulPowers = true; - } else - { - qDebug() << Q_FUNC_INFO << "Invalid number format code (second char not 'b' or first char neither 'e' nor 'g'):" << formatCode; - return; - } - if (formatCode.length() < 3) - { - mAxisPainter->numberMultiplyCross = false; - return; - } - - // interpret third char as indicator for dot or cross multiplication symbol: - if (formatCode.at(2) == QLatin1Char('c')) - { - mAxisPainter->numberMultiplyCross = true; - } else if (formatCode.at(2) == QLatin1Char('d')) - { - mAxisPainter->numberMultiplyCross = false; - } else - { - qDebug() << Q_FUNC_INFO << "Invalid number format code (third char neither 'c' nor 'd'):" << formatCode; - return; - } + if (formatCode.isEmpty()) { + qDebug() << Q_FUNC_INFO << "Passed formatCode is empty"; + return; + } + mCachedMarginValid = false; + + // interpret first char as number format char: + QString allowedFormatChars(QLatin1String("eEfgG")); + if (allowedFormatChars.contains(formatCode.at(0))) { + mNumberFormatChar = QLatin1Char(formatCode.at(0).toLatin1()); + } else { + qDebug() << Q_FUNC_INFO << "Invalid number format code (first char not in 'eEfgG'):" << formatCode; + return; + } + if (formatCode.length() < 2) { + mNumberBeautifulPowers = false; + mAxisPainter->numberMultiplyCross = false; + return; + } + + // interpret second char as indicator for beautiful decimal powers: + if (formatCode.at(1) == QLatin1Char('b') && (mNumberFormatChar == QLatin1Char('e') || mNumberFormatChar == QLatin1Char('g'))) { + mNumberBeautifulPowers = true; + } else { + qDebug() << Q_FUNC_INFO << "Invalid number format code (second char not 'b' or first char neither 'e' nor 'g'):" << formatCode; + return; + } + if (formatCode.length() < 3) { + mAxisPainter->numberMultiplyCross = false; + return; + } + + // interpret third char as indicator for dot or cross multiplication symbol: + if (formatCode.at(2) == QLatin1Char('c')) { + mAxisPainter->numberMultiplyCross = true; + } else if (formatCode.at(2) == QLatin1Char('d')) { + mAxisPainter->numberMultiplyCross = false; + } else { + qDebug() << Q_FUNC_INFO << "Invalid number format code (third char neither 'c' nor 'd'):" << formatCode; + return; + } } /*! @@ -8073,11 +8159,10 @@ void QCPAxis::setNumberFormat(const QString &formatCode) */ void QCPAxis::setNumberPrecision(int precision) { - if (mNumberPrecision != precision) - { - mNumberPrecision = precision; - mCachedMarginValid = false; - } + if (mNumberPrecision != precision) { + mNumberPrecision = precision; + mCachedMarginValid = false; + } } /*! @@ -8085,59 +8170,56 @@ void QCPAxis::setNumberPrecision(int precision) plot and \a outside is the length they will reach outside the plot. If \a outside is greater than zero, the tick labels and axis label will increase their distance to the axis accordingly, so they won't collide with the ticks. - + \see setSubTickLength, setTickLengthIn, setTickLengthOut */ void QCPAxis::setTickLength(int inside, int outside) { - setTickLengthIn(inside); - setTickLengthOut(outside); + setTickLengthIn(inside); + setTickLengthOut(outside); } /*! Sets the length of the inward ticks in pixels. \a inside is the length the ticks will reach inside the plot. - + \see setTickLengthOut, setTickLength, setSubTickLength */ void QCPAxis::setTickLengthIn(int inside) { - if (mAxisPainter->tickLengthIn != inside) - { - mAxisPainter->tickLengthIn = inside; - } + if (mAxisPainter->tickLengthIn != inside) { + mAxisPainter->tickLengthIn = inside; + } } /*! Sets the length of the outward ticks in pixels. \a outside is the length the ticks will reach outside the plot. If \a outside is greater than zero, the tick labels and axis label will increase their distance to the axis accordingly, so they won't collide with the ticks. - + \see setTickLengthIn, setTickLength, setSubTickLength */ void QCPAxis::setTickLengthOut(int outside) { - if (mAxisPainter->tickLengthOut != outside) - { - mAxisPainter->tickLengthOut = outside; - mCachedMarginValid = false; // only outside tick length can change margin - } + if (mAxisPainter->tickLengthOut != outside) { + mAxisPainter->tickLengthOut = outside; + mCachedMarginValid = false; // only outside tick length can change margin + } } /*! Sets whether sub tick marks are displayed. - + Sub ticks are only potentially visible if (major) ticks are also visible (see \ref setTicks) - + \see setTicks */ void QCPAxis::setSubTicks(bool show) { - if (mSubTicks != show) - { - mSubTicks = show; - mCachedMarginValid = false; - } + if (mSubTicks != show) { + mSubTicks = show; + mCachedMarginValid = false; + } } /*! @@ -8145,97 +8227,94 @@ void QCPAxis::setSubTicks(bool show) the plot and \a outside is the length they will reach outside the plot. If \a outside is greater than zero, the tick labels and axis label will increase their distance to the axis accordingly, so they won't collide with the ticks. - + \see setTickLength, setSubTickLengthIn, setSubTickLengthOut */ void QCPAxis::setSubTickLength(int inside, int outside) { - setSubTickLengthIn(inside); - setSubTickLengthOut(outside); + setSubTickLengthIn(inside); + setSubTickLengthOut(outside); } /*! Sets the length of the inward subticks in pixels. \a inside is the length the subticks will reach inside the plot. - + \see setSubTickLengthOut, setSubTickLength, setTickLength */ void QCPAxis::setSubTickLengthIn(int inside) { - if (mAxisPainter->subTickLengthIn != inside) - { - mAxisPainter->subTickLengthIn = inside; - } + if (mAxisPainter->subTickLengthIn != inside) { + mAxisPainter->subTickLengthIn = inside; + } } /*! Sets the length of the outward subticks in pixels. \a outside is the length the subticks will reach outside the plot. If \a outside is greater than zero, the tick labels will increase their distance to the axis accordingly, so they won't collide with the ticks. - + \see setSubTickLengthIn, setSubTickLength, setTickLength */ void QCPAxis::setSubTickLengthOut(int outside) { - if (mAxisPainter->subTickLengthOut != outside) - { - mAxisPainter->subTickLengthOut = outside; - mCachedMarginValid = false; // only outside tick length can change margin - } + if (mAxisPainter->subTickLengthOut != outside) { + mAxisPainter->subTickLengthOut = outside; + mCachedMarginValid = false; // only outside tick length can change margin + } } /*! Sets the pen, the axis base line is drawn with. - + \see setTickPen, setSubTickPen */ void QCPAxis::setBasePen(const QPen &pen) { - mBasePen = pen; + mBasePen = pen; } /*! Sets the pen, tick marks will be drawn with. - + \see setTickLength, setBasePen */ void QCPAxis::setTickPen(const QPen &pen) { - mTickPen = pen; + mTickPen = pen; } /*! Sets the pen, subtick marks will be drawn with. - + \see setSubTickCount, setSubTickLength, setBasePen */ void QCPAxis::setSubTickPen(const QPen &pen) { - mSubTickPen = pen; + mSubTickPen = pen; } /*! Sets the font of the axis label. - + \see setLabelColor */ void QCPAxis::setLabelFont(const QFont &font) { - if (mLabelFont != font) - { - mLabelFont = font; - mCachedMarginValid = false; - } + if (mLabelFont != font) { + mLabelFont = font; + mCachedMarginValid = false; + } } /*! Sets the color of the axis label. - + \see setLabelFont */ void QCPAxis::setLabelColor(const QColor &color) { - mLabelColor = color; + mLabelColor = color; } /*! @@ -8244,25 +8323,23 @@ void QCPAxis::setLabelColor(const QColor &color) */ void QCPAxis::setLabel(const QString &str) { - if (mLabel != str) - { - mLabel = str; - mCachedMarginValid = false; - } + if (mLabel != str) { + mLabel = str; + mCachedMarginValid = false; + } } /*! Sets the distance between the tick labels and the axis label. - + \see setTickLabelPadding, setPadding */ void QCPAxis::setLabelPadding(int padding) { - if (mAxisPainter->labelPadding != padding) - { - mAxisPainter->labelPadding = padding; - mCachedMarginValid = false; - } + if (mAxisPainter->labelPadding != padding) { + mAxisPainter->labelPadding = padding; + mCachedMarginValid = false; + } } /*! @@ -8270,23 +8347,22 @@ void QCPAxis::setLabelPadding(int padding) When \ref QCPAxisRect::setAutoMargins is enabled, the padding is the additional outer most space, that is left blank. - + The axis padding has no meaning if \ref QCPAxisRect::setAutoMargins is disabled. - + \see setLabelPadding, setTickLabelPadding */ void QCPAxis::setPadding(int padding) { - if (mPadding != padding) - { - mPadding = padding; - mCachedMarginValid = false; - } + if (mPadding != padding) { + mPadding = padding; + mCachedMarginValid = false; + } } /*! Sets the offset the axis has to its axis rect side. - + If an axis rect side has multiple axes and automatic margin calculation is enabled for that side, only the offset of the inner most axis has meaning (even if it is set to be invisible). The offset of the other, outer axes is controlled automatically, to place them at appropriate @@ -8294,138 +8370,134 @@ void QCPAxis::setPadding(int padding) */ void QCPAxis::setOffset(int offset) { - mAxisPainter->offset = offset; + mAxisPainter->offset = offset; } /*! Sets the font that is used for tick labels when they are selected. - + \see setTickLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPAxis::setSelectedTickLabelFont(const QFont &font) { - if (font != mSelectedTickLabelFont) - { - mSelectedTickLabelFont = font; - // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts - } + if (font != mSelectedTickLabelFont) { + mSelectedTickLabelFont = font; + // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts + } } /*! Sets the font that is used for the axis label when it is selected. - + \see setLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPAxis::setSelectedLabelFont(const QFont &font) { - mSelectedLabelFont = font; - // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts + mSelectedLabelFont = font; + // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts } /*! Sets the color that is used for tick labels when they are selected. - + \see setTickLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPAxis::setSelectedTickLabelColor(const QColor &color) { - if (color != mSelectedTickLabelColor) - { - mSelectedTickLabelColor = color; - } + if (color != mSelectedTickLabelColor) { + mSelectedTickLabelColor = color; + } } /*! Sets the color that is used for the axis label when it is selected. - + \see setLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPAxis::setSelectedLabelColor(const QColor &color) { - mSelectedLabelColor = color; + mSelectedLabelColor = color; } /*! Sets the pen that is used to draw the axis base line when selected. - + \see setBasePen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPAxis::setSelectedBasePen(const QPen &pen) { - mSelectedBasePen = pen; + mSelectedBasePen = pen; } /*! Sets the pen that is used to draw the (major) ticks when selected. - + \see setTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPAxis::setSelectedTickPen(const QPen &pen) { - mSelectedTickPen = pen; + mSelectedTickPen = pen; } /*! Sets the pen that is used to draw the subticks when selected. - + \see setSubTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPAxis::setSelectedSubTickPen(const QPen &pen) { - mSelectedSubTickPen = pen; + mSelectedSubTickPen = pen; } /*! Sets the style for the lower axis ending. See the documentation of QCPLineEnding for available styles. - + For horizontal axes, this method refers to the left ending, for vertical axes the bottom ending. Note that this meaning does not change when the axis range is reversed with \ref setRangeReversed. - + \see setUpperEnding */ void QCPAxis::setLowerEnding(const QCPLineEnding &ending) { - mAxisPainter->lowerEnding = ending; + mAxisPainter->lowerEnding = ending; } /*! Sets the style for the upper axis ending. See the documentation of QCPLineEnding for available styles. - + For horizontal axes, this method refers to the right ending, for vertical axes the top ending. Note that this meaning does not change when the axis range is reversed with \ref setRangeReversed. - + \see setLowerEnding */ void QCPAxis::setUpperEnding(const QCPLineEnding &ending) { - mAxisPainter->upperEnding = ending; + mAxisPainter->upperEnding = ending; } /*! If the scale type (\ref setScaleType) is \ref stLinear, \a diff is added to the lower and upper bounds of the range. The range is simply moved by \a diff. - + If the scale type is \ref stLogarithmic, the range bounds are multiplied by \a diff. This corresponds to an apparent "linear" move in logarithmic scaling by a distance of log(diff). */ void QCPAxis::moveRange(double diff) { - QCPRange oldRange = mRange; - if (mScaleType == stLinear) - { - mRange.lower += diff; - mRange.upper += diff; - } else // mScaleType == stLogarithmic - { - mRange.lower *= diff; - mRange.upper *= diff; - } - emit rangeChanged(mRange); - emit rangeChanged(mRange, oldRange); + QCPRange oldRange = mRange; + if (mScaleType == stLinear) { + mRange.lower += diff; + mRange.upper += diff; + } else { // mScaleType == stLogarithmic + mRange.lower *= diff; + mRange.upper *= diff; + } + emit rangeChanged(mRange); + emit rangeChanged(mRange, oldRange); } /*! @@ -8439,7 +8511,7 @@ void QCPAxis::moveRange(double diff) */ void QCPAxis::scaleRange(double factor) { - scaleRange(factor, range().center()); + scaleRange(factor, range().center()); } /*! \overload @@ -8453,28 +8525,28 @@ void QCPAxis::scaleRange(double factor) */ void QCPAxis::scaleRange(double factor, double center) { - QCPRange oldRange = mRange; - if (mScaleType == stLinear) - { - QCPRange newRange; - newRange.lower = (mRange.lower-center)*factor + center; - newRange.upper = (mRange.upper-center)*factor + center; - if (QCPRange::validRange(newRange)) - mRange = newRange.sanitizedForLinScale(); - } else // mScaleType == stLogarithmic - { - if ((mRange.upper < 0 && center < 0) || (mRange.upper > 0 && center > 0)) // make sure center has same sign as range - { - QCPRange newRange; - newRange.lower = qPow(mRange.lower/center, factor)*center; - newRange.upper = qPow(mRange.upper/center, factor)*center; - if (QCPRange::validRange(newRange)) - mRange = newRange.sanitizedForLogScale(); - } else - qDebug() << Q_FUNC_INFO << "Center of scaling operation doesn't lie in same logarithmic sign domain as range:" << center; - } - emit rangeChanged(mRange); - emit rangeChanged(mRange, oldRange); + QCPRange oldRange = mRange; + if (mScaleType == stLinear) { + QCPRange newRange; + newRange.lower = (mRange.lower - center) * factor + center; + newRange.upper = (mRange.upper - center) * factor + center; + if (QCPRange::validRange(newRange)) { + mRange = newRange.sanitizedForLinScale(); + } + } else { // mScaleType == stLogarithmic + if ((mRange.upper < 0 && center < 0) || (mRange.upper > 0 && center > 0)) { // make sure center has same sign as range + QCPRange newRange; + newRange.lower = qPow(mRange.lower / center, factor) * center; + newRange.upper = qPow(mRange.upper / center, factor) * center; + if (QCPRange::validRange(newRange)) { + mRange = newRange.sanitizedForLogScale(); + } + } else { + qDebug() << Q_FUNC_INFO << "Center of scaling operation doesn't lie in same logarithmic sign domain as range:" << center; + } + } + emit rangeChanged(mRange); + emit rangeChanged(mRange, oldRange); } /*! @@ -8492,72 +8564,72 @@ void QCPAxis::scaleRange(double factor, double center) */ void QCPAxis::setScaleRatio(const QCPAxis *otherAxis, double ratio) { - int otherPixelSize, ownPixelSize; - - if (otherAxis->orientation() == Qt::Horizontal) - otherPixelSize = otherAxis->axisRect()->width(); - else - otherPixelSize = otherAxis->axisRect()->height(); - - if (orientation() == Qt::Horizontal) - ownPixelSize = axisRect()->width(); - else - ownPixelSize = axisRect()->height(); - - double newRangeSize = ratio*otherAxis->range().size()*ownPixelSize/(double)otherPixelSize; - setRange(range().center(), newRangeSize, Qt::AlignCenter); + int otherPixelSize, ownPixelSize; + + if (otherAxis->orientation() == Qt::Horizontal) { + otherPixelSize = otherAxis->axisRect()->width(); + } else { + otherPixelSize = otherAxis->axisRect()->height(); + } + + if (orientation() == Qt::Horizontal) { + ownPixelSize = axisRect()->width(); + } else { + ownPixelSize = axisRect()->height(); + } + + double newRangeSize = ratio * otherAxis->range().size() * ownPixelSize / (double)otherPixelSize; + setRange(range().center(), newRangeSize, Qt::AlignCenter); } /*! Changes the axis range such that all plottables associated with this axis are fully visible in that dimension. - + \see QCPAbstractPlottable::rescaleAxes, QCustomPlot::rescaleAxes */ void QCPAxis::rescale(bool onlyVisiblePlottables) { - QList p = plottables(); - QCPRange newRange; - bool haveRange = false; - for (int i=0; irealVisibility() && onlyVisiblePlottables) - continue; - QCPRange plottableRange; - bool currentFoundRange; - QCP::SignDomain signDomain = QCP::sdBoth; - if (mScaleType == stLogarithmic) - signDomain = (mRange.upper < 0 ? QCP::sdNegative : QCP::sdPositive); - if (p.at(i)->keyAxis() == this) - plottableRange = p.at(i)->getKeyRange(currentFoundRange, signDomain); - else - plottableRange = p.at(i)->getValueRange(currentFoundRange, signDomain); - if (currentFoundRange) - { - if (!haveRange) - newRange = plottableRange; - else - newRange.expand(plottableRange); - haveRange = true; + QList p = plottables(); + QCPRange newRange; + bool haveRange = false; + for (int i = 0; i < p.size(); ++i) { + if (!p.at(i)->realVisibility() && onlyVisiblePlottables) { + continue; + } + QCPRange plottableRange; + bool currentFoundRange; + QCP::SignDomain signDomain = QCP::sdBoth; + if (mScaleType == stLogarithmic) { + signDomain = (mRange.upper < 0 ? QCP::sdNegative : QCP::sdPositive); + } + if (p.at(i)->keyAxis() == this) { + plottableRange = p.at(i)->getKeyRange(currentFoundRange, signDomain); + } else { + plottableRange = p.at(i)->getValueRange(currentFoundRange, signDomain); + } + if (currentFoundRange) { + if (!haveRange) { + newRange = plottableRange; + } else { + newRange.expand(plottableRange); + } + haveRange = true; + } } - } - if (haveRange) - { - if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable - { - double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason - if (mScaleType == stLinear) - { - newRange.lower = center-mRange.size()/2.0; - newRange.upper = center+mRange.size()/2.0; - } else // mScaleType == stLogarithmic - { - newRange.lower = center/qSqrt(mRange.upper/mRange.lower); - newRange.upper = center*qSqrt(mRange.upper/mRange.lower); - } + if (haveRange) { + if (!QCPRange::validRange(newRange)) { // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable + double center = (newRange.lower + newRange.upper) * 0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason + if (mScaleType == stLinear) { + newRange.lower = center - mRange.size() / 2.0; + newRange.upper = center + mRange.size() / 2.0; + } else { // mScaleType == stLogarithmic + newRange.lower = center / qSqrt(mRange.upper / mRange.lower); + newRange.upper = center * qSqrt(mRange.upper / mRange.lower); + } + } + setRange(newRange); } - setRange(newRange); - } } /*! @@ -8565,37 +8637,35 @@ void QCPAxis::rescale(bool onlyVisiblePlottables) */ double QCPAxis::pixelToCoord(double value) const { - if (orientation() == Qt::Horizontal) - { - if (mScaleType == stLinear) - { - if (!mRangeReversed) - return (value-mAxisRect->left())/(double)mAxisRect->width()*mRange.size()+mRange.lower; - else - return -(value-mAxisRect->left())/(double)mAxisRect->width()*mRange.size()+mRange.upper; - } else // mScaleType == stLogarithmic - { - if (!mRangeReversed) - return qPow(mRange.upper/mRange.lower, (value-mAxisRect->left())/(double)mAxisRect->width())*mRange.lower; - else - return qPow(mRange.upper/mRange.lower, (mAxisRect->left()-value)/(double)mAxisRect->width())*mRange.upper; + if (orientation() == Qt::Horizontal) { + if (mScaleType == stLinear) { + if (!mRangeReversed) { + return (value - mAxisRect->left()) / (double)mAxisRect->width() * mRange.size() + mRange.lower; + } else { + return -(value - mAxisRect->left()) / (double)mAxisRect->width() * mRange.size() + mRange.upper; + } + } else { // mScaleType == stLogarithmic + if (!mRangeReversed) { + return qPow(mRange.upper / mRange.lower, (value - mAxisRect->left()) / (double)mAxisRect->width()) * mRange.lower; + } else { + return qPow(mRange.upper / mRange.lower, (mAxisRect->left() - value) / (double)mAxisRect->width()) * mRange.upper; + } + } + } else { // orientation() == Qt::Vertical + if (mScaleType == stLinear) { + if (!mRangeReversed) { + return (mAxisRect->bottom() - value) / (double)mAxisRect->height() * mRange.size() + mRange.lower; + } else { + return -(mAxisRect->bottom() - value) / (double)mAxisRect->height() * mRange.size() + mRange.upper; + } + } else { // mScaleType == stLogarithmic + if (!mRangeReversed) { + return qPow(mRange.upper / mRange.lower, (mAxisRect->bottom() - value) / (double)mAxisRect->height()) * mRange.lower; + } else { + return qPow(mRange.upper / mRange.lower, (value - mAxisRect->bottom()) / (double)mAxisRect->height()) * mRange.upper; + } + } } - } else // orientation() == Qt::Vertical - { - if (mScaleType == stLinear) - { - if (!mRangeReversed) - return (mAxisRect->bottom()-value)/(double)mAxisRect->height()*mRange.size()+mRange.lower; - else - return -(mAxisRect->bottom()-value)/(double)mAxisRect->height()*mRange.size()+mRange.upper; - } else // mScaleType == stLogarithmic - { - if (!mRangeReversed) - return qPow(mRange.upper/mRange.lower, (mAxisRect->bottom()-value)/(double)mAxisRect->height())*mRange.lower; - else - return qPow(mRange.upper/mRange.lower, (value-mAxisRect->bottom())/(double)mAxisRect->height())*mRange.upper; - } - } } /*! @@ -8603,152 +8673,157 @@ double QCPAxis::pixelToCoord(double value) const */ double QCPAxis::coordToPixel(double value) const { - if (orientation() == Qt::Horizontal) - { - if (mScaleType == stLinear) - { - if (!mRangeReversed) - return (value-mRange.lower)/mRange.size()*mAxisRect->width()+mAxisRect->left(); - else - return (mRange.upper-value)/mRange.size()*mAxisRect->width()+mAxisRect->left(); - } else // mScaleType == stLogarithmic - { - if (value >= 0.0 && mRange.upper < 0.0) // invalid value for logarithmic scale, just draw it outside visible range - return !mRangeReversed ? mAxisRect->right()+200 : mAxisRect->left()-200; - else if (value <= 0.0 && mRange.upper >= 0.0) // invalid value for logarithmic scale, just draw it outside visible range - return !mRangeReversed ? mAxisRect->left()-200 : mAxisRect->right()+200; - else - { - if (!mRangeReversed) - return qLn(value/mRange.lower)/qLn(mRange.upper/mRange.lower)*mAxisRect->width()+mAxisRect->left(); - else - return qLn(mRange.upper/value)/qLn(mRange.upper/mRange.lower)*mAxisRect->width()+mAxisRect->left(); - } + if (orientation() == Qt::Horizontal) { + if (mScaleType == stLinear) { + if (!mRangeReversed) { + return (value - mRange.lower) / mRange.size() * mAxisRect->width() + mAxisRect->left(); + } else { + return (mRange.upper - value) / mRange.size() * mAxisRect->width() + mAxisRect->left(); + } + } else { // mScaleType == stLogarithmic + if (value >= 0.0 && mRange.upper < 0.0) { // invalid value for logarithmic scale, just draw it outside visible range + return !mRangeReversed ? mAxisRect->right() + 200 : mAxisRect->left() - 200; + } else if (value <= 0.0 && mRange.upper >= 0.0) { // invalid value for logarithmic scale, just draw it outside visible range + return !mRangeReversed ? mAxisRect->left() - 200 : mAxisRect->right() + 200; + } else { + if (!mRangeReversed) { + return qLn(value / mRange.lower) / qLn(mRange.upper / mRange.lower) * mAxisRect->width() + mAxisRect->left(); + } else { + return qLn(mRange.upper / value) / qLn(mRange.upper / mRange.lower) * mAxisRect->width() + mAxisRect->left(); + } + } + } + } else { // orientation() == Qt::Vertical + if (mScaleType == stLinear) { + if (!mRangeReversed) { + return mAxisRect->bottom() - (value - mRange.lower) / mRange.size() * mAxisRect->height(); + } else { + return mAxisRect->bottom() - (mRange.upper - value) / mRange.size() * mAxisRect->height(); + } + } else { // mScaleType == stLogarithmic + if (value >= 0.0 && mRange.upper < 0.0) { // invalid value for logarithmic scale, just draw it outside visible range + return !mRangeReversed ? mAxisRect->top() - 200 : mAxisRect->bottom() + 200; + } else if (value <= 0.0 && mRange.upper >= 0.0) { // invalid value for logarithmic scale, just draw it outside visible range + return !mRangeReversed ? mAxisRect->bottom() + 200 : mAxisRect->top() - 200; + } else { + if (!mRangeReversed) { + return mAxisRect->bottom() - qLn(value / mRange.lower) / qLn(mRange.upper / mRange.lower) * mAxisRect->height(); + } else { + return mAxisRect->bottom() - qLn(mRange.upper / value) / qLn(mRange.upper / mRange.lower) * mAxisRect->height(); + } + } + } } - } else // orientation() == Qt::Vertical - { - if (mScaleType == stLinear) - { - if (!mRangeReversed) - return mAxisRect->bottom()-(value-mRange.lower)/mRange.size()*mAxisRect->height(); - else - return mAxisRect->bottom()-(mRange.upper-value)/mRange.size()*mAxisRect->height(); - } else // mScaleType == stLogarithmic - { - if (value >= 0.0 && mRange.upper < 0.0) // invalid value for logarithmic scale, just draw it outside visible range - return !mRangeReversed ? mAxisRect->top()-200 : mAxisRect->bottom()+200; - else if (value <= 0.0 && mRange.upper >= 0.0) // invalid value for logarithmic scale, just draw it outside visible range - return !mRangeReversed ? mAxisRect->bottom()+200 : mAxisRect->top()-200; - else - { - if (!mRangeReversed) - return mAxisRect->bottom()-qLn(value/mRange.lower)/qLn(mRange.upper/mRange.lower)*mAxisRect->height(); - else - return mAxisRect->bottom()-qLn(mRange.upper/value)/qLn(mRange.upper/mRange.lower)*mAxisRect->height(); - } - } - } } /*! Returns the part of the axis that is hit by \a pos (in pixels). The return value of this function is independent of the user-selectable parts defined with \ref setSelectableParts. Further, this function does not change the current selection state of the axis. - + If the axis is not visible (\ref setVisible), this function always returns \ref spNone. - + \see setSelectedParts, setSelectableParts, QCustomPlot::setInteractions */ QCPAxis::SelectablePart QCPAxis::getPartAt(const QPointF &pos) const { - if (!mVisible) - return spNone; - - if (mAxisPainter->axisSelectionBox().contains(pos.toPoint())) - return spAxis; - else if (mAxisPainter->tickLabelsSelectionBox().contains(pos.toPoint())) - return spTickLabels; - else if (mAxisPainter->labelSelectionBox().contains(pos.toPoint())) - return spAxisLabel; - else - return spNone; + if (!mVisible) { + return spNone; + } + + if (mAxisPainter->axisSelectionBox().contains(pos.toPoint())) { + return spAxis; + } else if (mAxisPainter->tickLabelsSelectionBox().contains(pos.toPoint())) { + return spTickLabels; + } else if (mAxisPainter->labelSelectionBox().contains(pos.toPoint())) { + return spAxisLabel; + } else { + return spNone; + } } /* inherits documentation from base class */ double QCPAxis::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { - if (!mParentPlot) return -1; - SelectablePart part = getPartAt(pos); - if ((onlySelectable && !mSelectableParts.testFlag(part)) || part == spNone) - return -1; - - if (details) - details->setValue(part); - return mParentPlot->selectionTolerance()*0.99; + if (!mParentPlot) { + return -1; + } + SelectablePart part = getPartAt(pos); + if ((onlySelectable && !mSelectableParts.testFlag(part)) || part == spNone) { + return -1; + } + + if (details) { + details->setValue(part); + } + return mParentPlot->selectionTolerance() * 0.99; } /*! Returns a list of all the plottables that have this axis as key or value axis. - + If you are only interested in plottables of type QCPGraph, see \ref graphs. - + \see graphs, items */ -QList QCPAxis::plottables() const +QList QCPAxis::plottables() const { - QList result; - if (!mParentPlot) return result; - - for (int i=0; imPlottables.size(); ++i) - { - if (mParentPlot->mPlottables.at(i)->keyAxis() == this ||mParentPlot->mPlottables.at(i)->valueAxis() == this) - result.append(mParentPlot->mPlottables.at(i)); - } - return result; + QList result; + if (!mParentPlot) { + return result; + } + + for (int i = 0; i < mParentPlot->mPlottables.size(); ++i) { + if (mParentPlot->mPlottables.at(i)->keyAxis() == this || mParentPlot->mPlottables.at(i)->valueAxis() == this) { + result.append(mParentPlot->mPlottables.at(i)); + } + } + return result; } /*! Returns a list of all the graphs that have this axis as key or value axis. - + \see plottables, items */ -QList QCPAxis::graphs() const +QList QCPAxis::graphs() const { - QList result; - if (!mParentPlot) return result; - - for (int i=0; imGraphs.size(); ++i) - { - if (mParentPlot->mGraphs.at(i)->keyAxis() == this || mParentPlot->mGraphs.at(i)->valueAxis() == this) - result.append(mParentPlot->mGraphs.at(i)); - } - return result; + QList result; + if (!mParentPlot) { + return result; + } + + for (int i = 0; i < mParentPlot->mGraphs.size(); ++i) { + if (mParentPlot->mGraphs.at(i)->keyAxis() == this || mParentPlot->mGraphs.at(i)->valueAxis() == this) { + result.append(mParentPlot->mGraphs.at(i)); + } + } + return result; } /*! Returns a list of all the items that are associated with this axis. An item is considered associated with an axis if at least one of its positions uses the axis as key or value axis. - + \see plottables, graphs */ -QList QCPAxis::items() const +QList QCPAxis::items() const { - QList result; - if (!mParentPlot) return result; - - for (int itemId=0; itemIdmItems.size(); ++itemId) - { - QList positions = mParentPlot->mItems.at(itemId)->positions(); - for (int posId=0; posIdkeyAxis() == this || positions.at(posId)->valueAxis() == this) - { - result.append(mParentPlot->mItems.at(itemId)); - break; - } + QList result; + if (!mParentPlot) { + return result; } - } - return result; + + for (int itemId = 0; itemId < mParentPlot->mItems.size(); ++itemId) { + QList positions = mParentPlot->mItems.at(itemId)->positions(); + for (int posId = 0; posId < positions.size(); ++posId) { + if (positions.at(posId)->keyAxis() == this || positions.at(posId)->valueAxis() == this) { + result.append(mParentPlot->mItems.at(itemId)); + break; + } + } + } + return result; } /*! @@ -8757,16 +8832,20 @@ QList QCPAxis::items() const */ QCPAxis::AxisType QCPAxis::marginSideToAxisType(QCP::MarginSide side) { - switch (side) - { - case QCP::msLeft: return atLeft; - case QCP::msRight: return atRight; - case QCP::msTop: return atTop; - case QCP::msBottom: return atBottom; - default: break; - } - qDebug() << Q_FUNC_INFO << "Invalid margin side passed:" << (int)side; - return atLeft; + switch (side) { + case QCP::msLeft: + return atLeft; + case QCP::msRight: + return atRight; + case QCP::msTop: + return atTop; + case QCP::msBottom: + return atBottom; + default: + break; + } + qDebug() << Q_FUNC_INFO << "Invalid margin side passed:" << (int)side; + return atLeft; } /*! @@ -8774,41 +8853,52 @@ QCPAxis::AxisType QCPAxis::marginSideToAxisType(QCP::MarginSide side) */ QCPAxis::AxisType QCPAxis::opposite(QCPAxis::AxisType type) { - switch (type) - { - case atLeft: return atRight; break; - case atRight: return atLeft; break; - case atBottom: return atTop; break; - case atTop: return atBottom; break; - default: qDebug() << Q_FUNC_INFO << "invalid axis type"; return atLeft; break; - } + switch (type) { + case atLeft: + return atRight; + break; + case atRight: + return atLeft; + break; + case atBottom: + return atTop; + break; + case atTop: + return atBottom; + break; + default: + qDebug() << Q_FUNC_INFO << "invalid axis type"; + return atLeft; + break; + } } /* inherits documentation from base class */ void QCPAxis::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) { - Q_UNUSED(event) - SelectablePart part = details.value(); - if (mSelectableParts.testFlag(part)) - { - SelectableParts selBefore = mSelectedParts; - setSelectedParts(additive ? mSelectedParts^part : part); - if (selectionStateChanged) - *selectionStateChanged = mSelectedParts != selBefore; - } + Q_UNUSED(event) + SelectablePart part = details.value(); + if (mSelectableParts.testFlag(part)) { + SelectableParts selBefore = mSelectedParts; + setSelectedParts(additive ? mSelectedParts ^part : part); + if (selectionStateChanged) { + *selectionStateChanged = mSelectedParts != selBefore; + } + } } /* inherits documentation from base class */ void QCPAxis::deselectEvent(bool *selectionStateChanged) { - SelectableParts selBefore = mSelectedParts; - setSelectedParts(mSelectedParts & ~mSelectableParts); - if (selectionStateChanged) - *selectionStateChanged = mSelectedParts != selBefore; + SelectableParts selBefore = mSelectedParts; + setSelectedParts(mSelectedParts & ~mSelectableParts); + if (selectionStateChanged) { + *selectionStateChanged = mSelectedParts != selBefore; + } } /*! \internal - + This mouse event reimplementation provides the functionality to let the user drag individual axes exclusively, by startig the drag on top of the axis. @@ -8816,98 +8906,93 @@ void QCPAxis::deselectEvent(bool *selectionStateChanged) must be configured accordingly, i.e. it must allow range dragging in the orientation of this axis (\ref QCPAxisRect::setRangeDrag) and this axis must be a draggable axis (\ref QCPAxisRect::setRangeDragAxes) - + \seebaseclassmethod - + \note The dragging of possibly multiple axes at once by starting the drag anywhere in the axis rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::mousePressEvent. */ void QCPAxis::mousePressEvent(QMouseEvent *event, const QVariant &details) { - Q_UNUSED(details) - if (!mParentPlot->interactions().testFlag(QCP::iRangeDrag) || - !mAxisRect->rangeDrag().testFlag(orientation()) || - !mAxisRect->rangeDragAxes(orientation()).contains(this)) - { - event->ignore(); - return; - } - - if (event->buttons() & Qt::LeftButton) - { - mDragging = true; - // initialize antialiasing backup in case we start dragging: - if (mParentPlot->noAntialiasingOnDrag()) - { - mAADragBackup = mParentPlot->antialiasedElements(); - mNotAADragBackup = mParentPlot->notAntialiasedElements(); + Q_UNUSED(details) + if (!mParentPlot->interactions().testFlag(QCP::iRangeDrag) || + !mAxisRect->rangeDrag().testFlag(orientation()) || + !mAxisRect->rangeDragAxes(orientation()).contains(this)) { + event->ignore(); + return; + } + + if (event->buttons() & Qt::LeftButton) { + mDragging = true; + // initialize antialiasing backup in case we start dragging: + if (mParentPlot->noAntialiasingOnDrag()) { + mAADragBackup = mParentPlot->antialiasedElements(); + mNotAADragBackup = mParentPlot->notAntialiasedElements(); + } + // Mouse range dragging interaction: + if (mParentPlot->interactions().testFlag(QCP::iRangeDrag)) { + mDragStartRange = mRange; + } } - // Mouse range dragging interaction: - if (mParentPlot->interactions().testFlag(QCP::iRangeDrag)) - mDragStartRange = mRange; - } } /*! \internal - + This mouse event reimplementation provides the functionality to let the user drag individual axes exclusively, by startig the drag on top of the axis. - + \seebaseclassmethod - + \note The dragging of possibly multiple axes at once by starting the drag anywhere in the axis rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::mousePressEvent. - + \see QCPAxis::mousePressEvent */ void QCPAxis::mouseMoveEvent(QMouseEvent *event, const QPointF &startPos) { - if (mDragging) - { - const double startPixel = orientation() == Qt::Horizontal ? startPos.x() : startPos.y(); - const double currentPixel = orientation() == Qt::Horizontal ? event->pos().x() : event->pos().y(); - if (mScaleType == QCPAxis::stLinear) - { - const double diff = pixelToCoord(startPixel) - pixelToCoord(currentPixel); - setRange(mDragStartRange.lower+diff, mDragStartRange.upper+diff); - } else if (mScaleType == QCPAxis::stLogarithmic) - { - const double diff = pixelToCoord(startPixel) / pixelToCoord(currentPixel); - setRange(mDragStartRange.lower*diff, mDragStartRange.upper*diff); + if (mDragging) { + const double startPixel = orientation() == Qt::Horizontal ? startPos.x() : startPos.y(); + const double currentPixel = orientation() == Qt::Horizontal ? event->pos().x() : event->pos().y(); + if (mScaleType == QCPAxis::stLinear) { + const double diff = pixelToCoord(startPixel) - pixelToCoord(currentPixel); + setRange(mDragStartRange.lower + diff, mDragStartRange.upper + diff); + } else if (mScaleType == QCPAxis::stLogarithmic) { + const double diff = pixelToCoord(startPixel) / pixelToCoord(currentPixel); + setRange(mDragStartRange.lower * diff, mDragStartRange.upper * diff); + } + + if (mParentPlot->noAntialiasingOnDrag()) { + mParentPlot->setNotAntialiasedElements(QCP::aeAll); + } + mParentPlot->replot(QCustomPlot::rpQueuedReplot); } - - if (mParentPlot->noAntialiasingOnDrag()) - mParentPlot->setNotAntialiasedElements(QCP::aeAll); - mParentPlot->replot(QCustomPlot::rpQueuedReplot); - } } /*! \internal - + This mouse event reimplementation provides the functionality to let the user drag individual axes exclusively, by startig the drag on top of the axis. - + \seebaseclassmethod - + \note The dragging of possibly multiple axes at once by starting the drag anywhere in the axis rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::mousePressEvent. - + \see QCPAxis::mousePressEvent */ void QCPAxis::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos) { - Q_UNUSED(event) - Q_UNUSED(startPos) - mDragging = false; - if (mParentPlot->noAntialiasingOnDrag()) - { - mParentPlot->setAntialiasedElements(mAADragBackup); - mParentPlot->setNotAntialiasedElements(mNotAADragBackup); - } + Q_UNUSED(event) + Q_UNUSED(startPos) + mDragging = false; + if (mParentPlot->noAntialiasingOnDrag()) { + mParentPlot->setAntialiasedElements(mAADragBackup); + mParentPlot->setNotAntialiasedElements(mNotAADragBackup); + } } /*! \internal - + This mouse event reimplementation provides the functionality to let the user zoom individual axes exclusively, by performing the wheel event on top of the axis. @@ -8915,27 +9000,26 @@ void QCPAxis::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos) must be configured accordingly, i.e. it must allow range zooming in the orientation of this axis (\ref QCPAxisRect::setRangeZoom) and this axis must be a zoomable axis (\ref QCPAxisRect::setRangeZoomAxes) - + \seebaseclassmethod - + \note The zooming of possibly multiple axes at once by performing the wheel event anywhere in the axis rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::wheelEvent. */ void QCPAxis::wheelEvent(QWheelEvent *event) { - // Mouse range zooming interaction: - if (!mParentPlot->interactions().testFlag(QCP::iRangeZoom) || - !mAxisRect->rangeZoom().testFlag(orientation()) || - !mAxisRect->rangeZoomAxes(orientation()).contains(this)) - { - event->ignore(); - return; - } - - const double wheelSteps = event->delta()/120.0; // a single step delta is +/-120 usually - const double factor = qPow(mAxisRect->rangeZoomFactor(orientation()), wheelSteps); - scaleRange(factor, pixelToCoord(orientation() == Qt::Horizontal ? event->pos().x() : event->pos().y())); - mParentPlot->replot(); + // Mouse range zooming interaction: + if (!mParentPlot->interactions().testFlag(QCP::iRangeZoom) || + !mAxisRect->rangeZoom().testFlag(orientation()) || + !mAxisRect->rangeZoomAxes(orientation()).contains(this)) { + event->ignore(); + return; + } + + const double wheelSteps = event->delta() / 120.0; // a single step delta is +/-120 usually + const double factor = qPow(mAxisRect->rangeZoomFactor(orientation()), wheelSteps); + scaleRange(factor, pixelToCoord(orientation() == Qt::Horizontal ? event->pos().x() : event->pos().y())); + mParentPlot->replot(); } /*! \internal @@ -8944,223 +9028,227 @@ void QCPAxis::wheelEvent(QWheelEvent *event) before drawing axis lines. This is the antialiasing state the painter passed to the \ref draw method is in by default. - + 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. - + \seebaseclassmethod - + \see setAntialiased */ void QCPAxis::applyDefaultAntialiasingHint(QCPPainter *painter) const { - applyAntialiasingHint(painter, mAntialiased, QCP::aeAxes); + applyAntialiasingHint(painter, mAntialiased, QCP::aeAxes); } /*! \internal - + Draws the axis with the specified \a painter, using the internal QCPAxisPainterPrivate instance. \seebaseclassmethod */ void QCPAxis::draw(QCPPainter *painter) { - 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(mTickVector.size()); - tickLabels.reserve(mTickVector.size()); - subTickPositions.reserve(mSubTickVector.size()); - - if (mTicks) - { - for (int i=0; i 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(mTickVector.size()); + tickLabels.reserve(mTickVector.size()); + subTickPositions.reserve(mSubTickVector.size()); + + if (mTicks) { + for (int i = 0; i < mTickVector.size(); ++i) { + tickPositions.append(coordToPixel(mTickVector.at(i))); + if (mTickLabels) { + tickLabels.append(mTickVectorLabels.at(i)); + } + } + + if (mSubTicks) { + const int subTickCount = mSubTickVector.size(); + for (int i = 0; i < subTickCount; ++i) { + subTickPositions.append(coordToPixel(mSubTickVector.at(i))); + } + } } - if (mSubTicks) - { - const int subTickCount = mSubTickVector.size(); - for (int i=0; itype = mAxisType; - mAxisPainter->basePen = getBasePen(); - mAxisPainter->labelFont = getLabelFont(); - mAxisPainter->labelColor = getLabelColor(); - mAxisPainter->label = mLabel; - mAxisPainter->substituteExponent = mNumberBeautifulPowers; - mAxisPainter->tickPen = getTickPen(); - mAxisPainter->subTickPen = getSubTickPen(); - mAxisPainter->tickLabelFont = getTickLabelFont(); - mAxisPainter->tickLabelColor = getTickLabelColor(); - mAxisPainter->axisRect = mAxisRect->rect(); - mAxisPainter->viewportRect = mParentPlot->viewport(); - mAxisPainter->abbreviateDecimalPowers = mScaleType == stLogarithmic; - mAxisPainter->reversedEndings = mRangeReversed; - mAxisPainter->tickPositions = tickPositions; - mAxisPainter->tickLabels = tickLabels; - mAxisPainter->subTickPositions = subTickPositions; - mAxisPainter->draw(painter); + // transfer all properties of this axis to QCPAxisPainterPrivate which it needs to draw the axis. + // Note that some axis painter properties are already set by direct feed-through with QCPAxis setters + mAxisPainter->type = mAxisType; + mAxisPainter->basePen = getBasePen(); + mAxisPainter->labelFont = getLabelFont(); + mAxisPainter->labelColor = getLabelColor(); + mAxisPainter->label = mLabel; + mAxisPainter->substituteExponent = mNumberBeautifulPowers; + mAxisPainter->tickPen = getTickPen(); + mAxisPainter->subTickPen = getSubTickPen(); + mAxisPainter->tickLabelFont = getTickLabelFont(); + mAxisPainter->tickLabelColor = getTickLabelColor(); + mAxisPainter->axisRect = mAxisRect->rect(); + mAxisPainter->viewportRect = mParentPlot->viewport(); + mAxisPainter->abbreviateDecimalPowers = mScaleType == stLogarithmic; + mAxisPainter->reversedEndings = mRangeReversed; + mAxisPainter->tickPositions = tickPositions; + mAxisPainter->tickLabels = tickLabels; + mAxisPainter->subTickPositions = subTickPositions; + mAxisPainter->draw(painter); } /*! \internal - + Prepares the internal tick vector, sub tick vector and tick label vector. This is done by calling QCPAxisTicker::generate on the currently installed ticker. - + 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::setupTickVectors() { - if (!mParentPlot) return; - if ((!mTicks && !mTickLabels && !mGrid->visible()) || mRange.size() <= 0) return; - - 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 + if (!mParentPlot) { + return; + } + if ((!mTicks && !mTickLabels && !mGrid->visible()) || mRange.size() <= 0) { + return; + } + + 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 - + Returns the pen that is used to draw the axis base line. Depending on the selection state, this is either mSelectedBasePen or mBasePen. */ QPen QCPAxis::getBasePen() const { - return mSelectedParts.testFlag(spAxis) ? mSelectedBasePen : mBasePen; + return mSelectedParts.testFlag(spAxis) ? mSelectedBasePen : mBasePen; } /*! \internal - + Returns the pen that is used to draw the (major) ticks. Depending on the selection state, this is either mSelectedTickPen or mTickPen. */ QPen QCPAxis::getTickPen() const { - return mSelectedParts.testFlag(spAxis) ? mSelectedTickPen : mTickPen; + return mSelectedParts.testFlag(spAxis) ? mSelectedTickPen : mTickPen; } /*! \internal - + Returns the pen that is used to draw the subticks. Depending on the selection state, this is either mSelectedSubTickPen or mSubTickPen. */ QPen QCPAxis::getSubTickPen() const { - return mSelectedParts.testFlag(spAxis) ? mSelectedSubTickPen : mSubTickPen; + return mSelectedParts.testFlag(spAxis) ? mSelectedSubTickPen : mSubTickPen; } /*! \internal - + Returns the font that is used to draw the tick labels. Depending on the selection state, this is either mSelectedTickLabelFont or mTickLabelFont. */ QFont QCPAxis::getTickLabelFont() const { - return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelFont : mTickLabelFont; + return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelFont : mTickLabelFont; } /*! \internal - + Returns the font that is used to draw the axis label. Depending on the selection state, this is either mSelectedLabelFont or mLabelFont. */ QFont QCPAxis::getLabelFont() const { - return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelFont : mLabelFont; + return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelFont : mLabelFont; } /*! \internal - + Returns the color that is used to draw the tick labels. Depending on the selection state, this is either mSelectedTickLabelColor or mTickLabelColor. */ QColor QCPAxis::getTickLabelColor() const { - return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelColor : mTickLabelColor; + return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelColor : mTickLabelColor; } /*! \internal - + Returns the color that is used to draw the axis label. Depending on the selection state, this is either mSelectedLabelColor or mLabelColor. */ QColor QCPAxis::getLabelColor() const { - return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelColor : mLabelColor; + return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelColor : mLabelColor; } /*! \internal - + Returns the appropriate outward margin for this axis. It is needed if \ref QCPAxisRect::setAutoMargins is set to true on the parent axis rect. An axis with axis type \ref atLeft will return an appropriate left margin, \ref atBottom will return an appropriate bottom margin and so forth. For the calculation, this function goes through similar steps as \ref draw, so changing one function likely requires the modification of the other one as well. - + The margin consists of the outward tick length, tick label padding, tick label size, label padding, label size, and padding. - + The margin is cached internally, so repeated calls while leaving the axis range, fonts, etc. unchanged are very fast. */ int QCPAxis::calculateMargin() { - if (!mVisible) // if not visible, directly return 0, don't cache 0 because we can't react to setVisible in QCPAxis - return 0; - - if (mCachedMarginValid) - return mCachedMargin; - - // run through similar steps as QCPAxis::draw, and calculate margin needed to fit axis and its labels - int margin = 0; - - QVector tickPositions; // the final coordToPixel transformed vector passed to QCPAxisPainter - QVector tickLabels; // the final vector passed to QCPAxisPainter - tickPositions.reserve(mTickVector.size()); - tickLabels.reserve(mTickVector.size()); - - if (mTicks) - { - for (int i=0; itype = mAxisType; - mAxisPainter->labelFont = getLabelFont(); - mAxisPainter->label = mLabel; - mAxisPainter->tickLabelFont = mTickLabelFont; - mAxisPainter->axisRect = mAxisRect->rect(); - mAxisPainter->viewportRect = mParentPlot->viewport(); - mAxisPainter->tickPositions = tickPositions; - mAxisPainter->tickLabels = tickLabels; - margin += mAxisPainter->size(); - margin += mPadding; - mCachedMargin = margin; - mCachedMarginValid = true; - return margin; + if (mCachedMarginValid) { + return mCachedMargin; + } + + // run through similar steps as QCPAxis::draw, and calculate margin needed to fit axis and its labels + int margin = 0; + + QVector tickPositions; // the final coordToPixel transformed vector passed to QCPAxisPainter + QVector tickLabels; // the final vector passed to QCPAxisPainter + tickPositions.reserve(mTickVector.size()); + tickLabels.reserve(mTickVector.size()); + + if (mTicks) { + for (int i = 0; i < mTickVector.size(); ++i) { + tickPositions.append(coordToPixel(mTickVector.at(i))); + if (mTickLabels) { + tickLabels.append(mTickVectorLabels.at(i)); + } + } + } + // transfer all properties of this axis to QCPAxisPainterPrivate which it needs to calculate the size. + // Note that some axis painter properties are already set by direct feed-through with QCPAxis setters + mAxisPainter->type = mAxisType; + mAxisPainter->labelFont = getLabelFont(); + mAxisPainter->label = mLabel; + mAxisPainter->tickLabelFont = mTickLabelFont; + mAxisPainter->axisRect = mAxisRect->rect(); + mAxisPainter->viewportRect = mParentPlot->viewport(); + mAxisPainter->tickPositions = tickPositions; + mAxisPainter->tickLabels = tickLabels; + margin += mAxisPainter->size(); + margin += mPadding; + + mCachedMargin = margin; + mCachedMarginValid = true; + return margin; } /* inherits documentation from base class */ QCP::Interaction QCPAxis::selectionCategory() const { - return QCP::iSelectAxes; + return QCP::iSelectAxes; } @@ -9172,9 +9260,9 @@ QCP::Interaction QCPAxis::selectionCategory() const \internal \brief (Private) - + This is a private class and not part of the public QCustomPlot interface. - + It is used by QCPAxis to do the low-level drawing of axis backbone, tick marks, tick labels and axis label. It also buffers the labels to reduce replot times. The parameters are configured by directly accessing the public member variables. @@ -9185,27 +9273,27 @@ QCP::Interaction QCPAxis::selectionCategory() const redraw, to utilize the caching mechanisms. */ QCPAxisPainterPrivate::QCPAxisPainterPrivate(QCustomPlot *parentPlot) : - type(QCPAxis::atLeft), - basePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), - lowerEnding(QCPLineEnding::esNone), - upperEnding(QCPLineEnding::esNone), - labelPadding(0), - tickLabelPadding(0), - tickLabelRotation(0), - tickLabelSide(QCPAxis::lsOutside), - substituteExponent(true), - numberMultiplyCross(false), - tickLengthIn(5), - tickLengthOut(0), - subTickLengthIn(2), - subTickLengthOut(0), - tickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), - subTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), - offset(0), - abbreviateDecimalPowers(false), - reversedEndings(false), - mParentPlot(parentPlot), - mLabelCache(16) // cache at most 16 (tick) labels + type(QCPAxis::atLeft), + basePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), + lowerEnding(QCPLineEnding::esNone), + upperEnding(QCPLineEnding::esNone), + labelPadding(0), + tickLabelPadding(0), + tickLabelRotation(0), + tickLabelSide(QCPAxis::lsOutside), + substituteExponent(true), + numberMultiplyCross(false), + tickLengthIn(5), + tickLengthOut(0), + subTickLengthIn(2), + subTickLengthOut(0), + tickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), + subTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), + offset(0), + abbreviateDecimalPowers(false), + reversedEndings(false), + mParentPlot(parentPlot), + mLabelCache(16) // cache at most 16 (tick) labels { } @@ -9214,251 +9302,256 @@ QCPAxisPainterPrivate::~QCPAxisPainterPrivate() } /*! \internal - + Draws the axis with the specified \a painter. - + The selection boxes (mAxisSelectionBox, mTickLabelsSelectionBox, mLabelSelectionBox) are set here, too. */ void QCPAxisPainterPrivate::draw(QCPPainter *painter) { - QByteArray newHash = generateLabelParameterHash(); - if (newHash != mLabelParameterHash) - { - mLabelCache.clear(); - mLabelParameterHash = newHash; - } - - QPoint origin; - switch (type) - { - case QCPAxis::atLeft: origin = axisRect.bottomLeft() +QPoint(-offset, 0); break; - case QCPAxis::atRight: origin = axisRect.bottomRight()+QPoint(+offset, 0); break; - case QCPAxis::atTop: origin = axisRect.topLeft() +QPoint(0, -offset); break; - case QCPAxis::atBottom: origin = axisRect.bottomLeft() +QPoint(0, +offset); break; - } + QByteArray newHash = generateLabelParameterHash(); + if (newHash != mLabelParameterHash) { + mLabelCache.clear(); + mLabelParameterHash = newHash; + } - double xCor = 0, yCor = 0; // paint system correction, for pixel exact matches (affects baselines and ticks of top/right axes) - switch (type) - { - case QCPAxis::atTop: yCor = -1; break; - case QCPAxis::atRight: xCor = 1; break; - default: break; - } - int margin = 0; - // draw baseline: - QLineF baseLine; - painter->setPen(basePen); - if (QCPAxis::orientation(type) == Qt::Horizontal) - baseLine.setPoints(origin+QPointF(xCor, yCor), origin+QPointF(axisRect.width()+xCor, yCor)); - else - baseLine.setPoints(origin+QPointF(xCor, yCor), origin+QPointF(xCor, -axisRect.height()+yCor)); - if (reversedEndings) - baseLine = QLineF(baseLine.p2(), baseLine.p1()); // won't make a difference for line itself, but for line endings later - painter->drawLine(baseLine); - - // draw ticks: - if (!tickPositions.isEmpty()) - { - painter->setPen(tickPen); - int tickDir = (type == QCPAxis::atBottom || type == QCPAxis::atRight) ? -1 : 1; // direction of ticks ("inward" is right for left axis and left for right axis) - if (QCPAxis::orientation(type) == Qt::Horizontal) - { - for (int i=0; idrawLine(QLineF(tickPositions.at(i)+xCor, origin.y()-tickLengthOut*tickDir+yCor, tickPositions.at(i)+xCor, origin.y()+tickLengthIn*tickDir+yCor)); - } else - { - for (int i=0; idrawLine(QLineF(origin.x()-tickLengthOut*tickDir+xCor, tickPositions.at(i)+yCor, origin.x()+tickLengthIn*tickDir+xCor, tickPositions.at(i)+yCor)); + QPoint origin; + switch (type) { + case QCPAxis::atLeft: + origin = axisRect.bottomLeft() + QPoint(-offset, 0); + break; + case QCPAxis::atRight: + origin = axisRect.bottomRight() + QPoint(+offset, 0); + break; + case QCPAxis::atTop: + origin = axisRect.topLeft() + QPoint(0, -offset); + break; + case QCPAxis::atBottom: + origin = axisRect.bottomLeft() + QPoint(0, +offset); + break; } - } - - // draw subticks: - if (!subTickPositions.isEmpty()) - { - painter->setPen(subTickPen); - // direction of ticks ("inward" is right for left axis and left for right axis) - int tickDir = (type == QCPAxis::atBottom || type == QCPAxis::atRight) ? -1 : 1; - if (QCPAxis::orientation(type) == Qt::Horizontal) - { - for (int i=0; idrawLine(QLineF(subTickPositions.at(i)+xCor, origin.y()-subTickLengthOut*tickDir+yCor, subTickPositions.at(i)+xCor, origin.y()+subTickLengthIn*tickDir+yCor)); - } else - { - for (int i=0; idrawLine(QLineF(origin.x()-subTickLengthOut*tickDir+xCor, subTickPositions.at(i)+yCor, origin.x()+subTickLengthIn*tickDir+xCor, subTickPositions.at(i)+yCor)); + + double xCor = 0, yCor = 0; // paint system correction, for pixel exact matches (affects baselines and ticks of top/right axes) + switch (type) { + case QCPAxis::atTop: + yCor = -1; + break; + case QCPAxis::atRight: + xCor = 1; + break; + default: + break; } - } - margin += qMax(0, qMax(tickLengthOut, subTickLengthOut)); - - // draw axis base endings: - bool antialiasingBackup = painter->antialiasing(); - painter->setAntialiasing(true); // always want endings to be antialiased, even if base and ticks themselves aren't - painter->setBrush(QBrush(basePen.color())); - QCPVector2D baseLineVector(baseLine.dx(), baseLine.dy()); - if (lowerEnding.style() != QCPLineEnding::esNone) - lowerEnding.draw(painter, QCPVector2D(baseLine.p1())-baseLineVector.normalized()*lowerEnding.realLength()*(lowerEnding.inverted()?-1:1), -baseLineVector); - if (upperEnding.style() != QCPLineEnding::esNone) - upperEnding.draw(painter, QCPVector2D(baseLine.p2())+baseLineVector.normalized()*upperEnding.realLength()*(upperEnding.inverted()?-1:1), baseLineVector); - painter->setAntialiasing(antialiasingBackup); - - // tick labels: - QRect oldClipRect; - if (tickLabelSide == QCPAxis::lsInside) // if using inside labels, clip them to the axis rect - { - oldClipRect = painter->clipRegion().boundingRect(); - painter->setClipRect(axisRect); - } - QSize tickLabelsSize(0, 0); // size of largest tick label, for offset calculation of axis label - if (!tickLabels.isEmpty()) - { - if (tickLabelSide == QCPAxis::lsOutside) - margin += tickLabelPadding; - painter->setFont(tickLabelFont); - painter->setPen(QPen(tickLabelColor)); - const int maxLabelIndex = qMin(tickPositions.size(), tickLabels.size()); - int distanceToAxis = margin; - if (tickLabelSide == QCPAxis::lsInside) - distanceToAxis = -(qMax(tickLengthIn, subTickLengthIn)+tickLabelPadding); - for (int i=0; isetClipRect(oldClipRect); - - // axis label: - QRect labelBounds; - if (!label.isEmpty()) - { - margin += labelPadding; - painter->setFont(labelFont); - painter->setPen(QPen(labelColor)); - labelBounds = painter->fontMetrics().boundingRect(0, 0, 0, 0, Qt::TextDontClip, label); - if (type == QCPAxis::atLeft) - { - QTransform oldTransform = painter->transform(); - painter->translate((origin.x()-margin-labelBounds.height()), origin.y()); - painter->rotate(-90); - painter->drawText(0, 0, axisRect.height(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label); - painter->setTransform(oldTransform); + int margin = 0; + // draw baseline: + QLineF baseLine; + painter->setPen(basePen); + if (QCPAxis::orientation(type) == Qt::Horizontal) { + baseLine.setPoints(origin + QPointF(xCor, yCor), origin + QPointF(axisRect.width() + xCor, yCor)); + } else { + baseLine.setPoints(origin + QPointF(xCor, yCor), origin + QPointF(xCor, -axisRect.height() + yCor)); } - else if (type == QCPAxis::atRight) - { - QTransform oldTransform = painter->transform(); - painter->translate((origin.x()+margin+labelBounds.height()), origin.y()-axisRect.height()); - painter->rotate(90); - painter->drawText(0, 0, axisRect.height(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label); - painter->setTransform(oldTransform); + if (reversedEndings) { + baseLine = QLineF(baseLine.p2(), baseLine.p1()); // won't make a difference for line itself, but for line endings later } - else if (type == QCPAxis::atTop) - painter->drawText(origin.x(), origin.y()-margin-labelBounds.height(), axisRect.width(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label); - else if (type == QCPAxis::atBottom) - painter->drawText(origin.x(), origin.y()+margin, axisRect.width(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label); - } - - // set selection boxes: - int selectionTolerance = 0; - if (mParentPlot) - selectionTolerance = mParentPlot->selectionTolerance(); - else - qDebug() << Q_FUNC_INFO << "mParentPlot is null"; - int selAxisOutSize = qMax(qMax(tickLengthOut, subTickLengthOut), selectionTolerance); - int selAxisInSize = selectionTolerance; - int selTickLabelSize; - int selTickLabelOffset; - if (tickLabelSide == QCPAxis::lsOutside) - { - selTickLabelSize = (QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width()); - selTickLabelOffset = qMax(tickLengthOut, subTickLengthOut)+tickLabelPadding; - } else - { - selTickLabelSize = -(QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width()); - selTickLabelOffset = -(qMax(tickLengthIn, subTickLengthIn)+tickLabelPadding); - } - int selLabelSize = labelBounds.height(); - int selLabelOffset = qMax(tickLengthOut, subTickLengthOut)+(!tickLabels.isEmpty() && tickLabelSide == QCPAxis::lsOutside ? tickLabelPadding+selTickLabelSize : 0)+labelPadding; - if (type == QCPAxis::atLeft) - { - mAxisSelectionBox.setCoords(origin.x()-selAxisOutSize, axisRect.top(), origin.x()+selAxisInSize, axisRect.bottom()); - mTickLabelsSelectionBox.setCoords(origin.x()-selTickLabelOffset-selTickLabelSize, axisRect.top(), origin.x()-selTickLabelOffset, axisRect.bottom()); - mLabelSelectionBox.setCoords(origin.x()-selLabelOffset-selLabelSize, axisRect.top(), origin.x()-selLabelOffset, axisRect.bottom()); - } else if (type == QCPAxis::atRight) - { - mAxisSelectionBox.setCoords(origin.x()-selAxisInSize, axisRect.top(), origin.x()+selAxisOutSize, axisRect.bottom()); - mTickLabelsSelectionBox.setCoords(origin.x()+selTickLabelOffset+selTickLabelSize, axisRect.top(), origin.x()+selTickLabelOffset, axisRect.bottom()); - mLabelSelectionBox.setCoords(origin.x()+selLabelOffset+selLabelSize, axisRect.top(), origin.x()+selLabelOffset, axisRect.bottom()); - } else if (type == QCPAxis::atTop) - { - mAxisSelectionBox.setCoords(axisRect.left(), origin.y()-selAxisOutSize, axisRect.right(), origin.y()+selAxisInSize); - mTickLabelsSelectionBox.setCoords(axisRect.left(), origin.y()-selTickLabelOffset-selTickLabelSize, axisRect.right(), origin.y()-selTickLabelOffset); - mLabelSelectionBox.setCoords(axisRect.left(), origin.y()-selLabelOffset-selLabelSize, axisRect.right(), origin.y()-selLabelOffset); - } else if (type == QCPAxis::atBottom) - { - mAxisSelectionBox.setCoords(axisRect.left(), origin.y()-selAxisInSize, axisRect.right(), origin.y()+selAxisOutSize); - mTickLabelsSelectionBox.setCoords(axisRect.left(), origin.y()+selTickLabelOffset+selTickLabelSize, axisRect.right(), origin.y()+selTickLabelOffset); - mLabelSelectionBox.setCoords(axisRect.left(), origin.y()+selLabelOffset+selLabelSize, axisRect.right(), origin.y()+selLabelOffset); - } - mAxisSelectionBox = mAxisSelectionBox.normalized(); - mTickLabelsSelectionBox = mTickLabelsSelectionBox.normalized(); - mLabelSelectionBox = mLabelSelectionBox.normalized(); - // draw hitboxes for debug purposes: - //painter->setBrush(Qt::NoBrush); - //painter->drawRects(QVector() << mAxisSelectionBox << mTickLabelsSelectionBox << mLabelSelectionBox); + painter->drawLine(baseLine); + + // draw ticks: + if (!tickPositions.isEmpty()) { + painter->setPen(tickPen); + int tickDir = (type == QCPAxis::atBottom || type == QCPAxis::atRight) ? -1 : 1; // direction of ticks ("inward" is right for left axis and left for right axis) + if (QCPAxis::orientation(type) == Qt::Horizontal) { + for (int i = 0; i < tickPositions.size(); ++i) { + painter->drawLine(QLineF(tickPositions.at(i) + xCor, origin.y() - tickLengthOut * tickDir + yCor, tickPositions.at(i) + xCor, origin.y() + tickLengthIn * tickDir + yCor)); + } + } else { + for (int i = 0; i < tickPositions.size(); ++i) { + painter->drawLine(QLineF(origin.x() - tickLengthOut * tickDir + xCor, tickPositions.at(i) + yCor, origin.x() + tickLengthIn * tickDir + xCor, tickPositions.at(i) + yCor)); + } + } + } + + // draw subticks: + if (!subTickPositions.isEmpty()) { + painter->setPen(subTickPen); + // direction of ticks ("inward" is right for left axis and left for right axis) + int tickDir = (type == QCPAxis::atBottom || type == QCPAxis::atRight) ? -1 : 1; + if (QCPAxis::orientation(type) == Qt::Horizontal) { + for (int i = 0; i < subTickPositions.size(); ++i) { + painter->drawLine(QLineF(subTickPositions.at(i) + xCor, origin.y() - subTickLengthOut * tickDir + yCor, subTickPositions.at(i) + xCor, origin.y() + subTickLengthIn * tickDir + yCor)); + } + } else { + for (int i = 0; i < subTickPositions.size(); ++i) { + painter->drawLine(QLineF(origin.x() - subTickLengthOut * tickDir + xCor, subTickPositions.at(i) + yCor, origin.x() + subTickLengthIn * tickDir + xCor, subTickPositions.at(i) + yCor)); + } + } + } + margin += qMax(0, qMax(tickLengthOut, subTickLengthOut)); + + // draw axis base endings: + bool antialiasingBackup = painter->antialiasing(); + painter->setAntialiasing(true); // always want endings to be antialiased, even if base and ticks themselves aren't + painter->setBrush(QBrush(basePen.color())); + QCPVector2D baseLineVector(baseLine.dx(), baseLine.dy()); + if (lowerEnding.style() != QCPLineEnding::esNone) { + lowerEnding.draw(painter, QCPVector2D(baseLine.p1()) - baseLineVector.normalized()*lowerEnding.realLength() * (lowerEnding.inverted() ? -1 : 1), -baseLineVector); + } + if (upperEnding.style() != QCPLineEnding::esNone) { + upperEnding.draw(painter, QCPVector2D(baseLine.p2()) + baseLineVector.normalized()*upperEnding.realLength() * (upperEnding.inverted() ? -1 : 1), baseLineVector); + } + painter->setAntialiasing(antialiasingBackup); + + // tick labels: + QRect oldClipRect; + if (tickLabelSide == QCPAxis::lsInside) { // if using inside labels, clip them to the axis rect + oldClipRect = painter->clipRegion().boundingRect(); + painter->setClipRect(axisRect); + } + QSize tickLabelsSize(0, 0); // size of largest tick label, for offset calculation of axis label + if (!tickLabels.isEmpty()) { + if (tickLabelSide == QCPAxis::lsOutside) { + margin += tickLabelPadding; + } + painter->setFont(tickLabelFont); + painter->setPen(QPen(tickLabelColor)); + const int maxLabelIndex = qMin(tickPositions.size(), tickLabels.size()); + int distanceToAxis = margin; + if (tickLabelSide == QCPAxis::lsInside) { + distanceToAxis = -(qMax(tickLengthIn, subTickLengthIn) + tickLabelPadding); + } + for (int i = 0; i < maxLabelIndex; ++i) { + placeTickLabel(painter, tickPositions.at(i), distanceToAxis, tickLabels.at(i), &tickLabelsSize); + } + if (tickLabelSide == QCPAxis::lsOutside) { + margin += (QCPAxis::orientation(type) == Qt::Horizontal) ? tickLabelsSize.height() : tickLabelsSize.width(); + } + } + if (tickLabelSide == QCPAxis::lsInside) { + painter->setClipRect(oldClipRect); + } + + // axis label: + QRect labelBounds; + if (!label.isEmpty()) { + margin += labelPadding; + painter->setFont(labelFont); + painter->setPen(QPen(labelColor)); + labelBounds = painter->fontMetrics().boundingRect(0, 0, 0, 0, Qt::TextDontClip, label); + if (type == QCPAxis::atLeft) { + QTransform oldTransform = painter->transform(); + painter->translate((origin.x() - margin - labelBounds.height()), origin.y()); + painter->rotate(-90); + painter->drawText(0, 0, axisRect.height(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label); + painter->setTransform(oldTransform); + } else if (type == QCPAxis::atRight) { + QTransform oldTransform = painter->transform(); + painter->translate((origin.x() + margin + labelBounds.height()), origin.y() - axisRect.height()); + painter->rotate(90); + painter->drawText(0, 0, axisRect.height(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label); + painter->setTransform(oldTransform); + } else if (type == QCPAxis::atTop) { + painter->drawText(origin.x(), origin.y() - margin - labelBounds.height(), axisRect.width(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label); + } else if (type == QCPAxis::atBottom) { + painter->drawText(origin.x(), origin.y() + margin, axisRect.width(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label); + } + } + + // set selection boxes: + int selectionTolerance = 0; + if (mParentPlot) { + selectionTolerance = mParentPlot->selectionTolerance(); + } else { + qDebug() << Q_FUNC_INFO << "mParentPlot is null"; + } + int selAxisOutSize = qMax(qMax(tickLengthOut, subTickLengthOut), selectionTolerance); + int selAxisInSize = selectionTolerance; + int selTickLabelSize; + int selTickLabelOffset; + if (tickLabelSide == QCPAxis::lsOutside) { + selTickLabelSize = (QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width()); + selTickLabelOffset = qMax(tickLengthOut, subTickLengthOut) + tickLabelPadding; + } else { + selTickLabelSize = -(QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width()); + selTickLabelOffset = -(qMax(tickLengthIn, subTickLengthIn) + tickLabelPadding); + } + int selLabelSize = labelBounds.height(); + int selLabelOffset = qMax(tickLengthOut, subTickLengthOut) + (!tickLabels.isEmpty() && tickLabelSide == QCPAxis::lsOutside ? tickLabelPadding + selTickLabelSize : 0) + labelPadding; + if (type == QCPAxis::atLeft) { + mAxisSelectionBox.setCoords(origin.x() - selAxisOutSize, axisRect.top(), origin.x() + selAxisInSize, axisRect.bottom()); + mTickLabelsSelectionBox.setCoords(origin.x() - selTickLabelOffset - selTickLabelSize, axisRect.top(), origin.x() - selTickLabelOffset, axisRect.bottom()); + mLabelSelectionBox.setCoords(origin.x() - selLabelOffset - selLabelSize, axisRect.top(), origin.x() - selLabelOffset, axisRect.bottom()); + } else if (type == QCPAxis::atRight) { + mAxisSelectionBox.setCoords(origin.x() - selAxisInSize, axisRect.top(), origin.x() + selAxisOutSize, axisRect.bottom()); + mTickLabelsSelectionBox.setCoords(origin.x() + selTickLabelOffset + selTickLabelSize, axisRect.top(), origin.x() + selTickLabelOffset, axisRect.bottom()); + mLabelSelectionBox.setCoords(origin.x() + selLabelOffset + selLabelSize, axisRect.top(), origin.x() + selLabelOffset, axisRect.bottom()); + } else if (type == QCPAxis::atTop) { + mAxisSelectionBox.setCoords(axisRect.left(), origin.y() - selAxisOutSize, axisRect.right(), origin.y() + selAxisInSize); + mTickLabelsSelectionBox.setCoords(axisRect.left(), origin.y() - selTickLabelOffset - selTickLabelSize, axisRect.right(), origin.y() - selTickLabelOffset); + mLabelSelectionBox.setCoords(axisRect.left(), origin.y() - selLabelOffset - selLabelSize, axisRect.right(), origin.y() - selLabelOffset); + } else if (type == QCPAxis::atBottom) { + mAxisSelectionBox.setCoords(axisRect.left(), origin.y() - selAxisInSize, axisRect.right(), origin.y() + selAxisOutSize); + mTickLabelsSelectionBox.setCoords(axisRect.left(), origin.y() + selTickLabelOffset + selTickLabelSize, axisRect.right(), origin.y() + selTickLabelOffset); + mLabelSelectionBox.setCoords(axisRect.left(), origin.y() + selLabelOffset + selLabelSize, axisRect.right(), origin.y() + selLabelOffset); + } + mAxisSelectionBox = mAxisSelectionBox.normalized(); + mTickLabelsSelectionBox = mTickLabelsSelectionBox.normalized(); + mLabelSelectionBox = mLabelSelectionBox.normalized(); + // draw hitboxes for debug purposes: + //painter->setBrush(Qt::NoBrush); + //painter->drawRects(QVector() << mAxisSelectionBox << mTickLabelsSelectionBox << mLabelSelectionBox); } /*! \internal - + Returns the size ("margin" in QCPAxisRect context, so measured perpendicular to the axis backbone direction) needed to fit the axis. */ int QCPAxisPainterPrivate::size() const { - int result = 0; - - // get length of tick marks pointing outwards: - if (!tickPositions.isEmpty()) - result += qMax(0, qMax(tickLengthOut, subTickLengthOut)); - - // calculate size of tick labels: - if (tickLabelSide == QCPAxis::lsOutside) - { - QSize tickLabelsSize(0, 0); - if (!tickLabels.isEmpty()) - { - for (int i=0; ibufferDevicePixelRatio())); - result.append(QByteArray::number(tickLabelRotation)); - result.append(QByteArray::number((int)tickLabelSide)); - result.append(QByteArray::number((int)substituteExponent)); - result.append(QByteArray::number((int)numberMultiplyCross)); - result.append(tickLabelColor.name().toLatin1()+QByteArray::number(tickLabelColor.alpha(), 16)); - result.append(tickLabelFont.toString().toLatin1()); - return result; + 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)); + result.append(QByteArray::number((int)numberMultiplyCross)); + result.append(tickLabelColor.name().toLatin1() + QByteArray::number(tickLabelColor.alpha(), 16)); + result.append(tickLabelFont.toString().toLatin1()); + return result; } /*! \internal - + Draws a single tick label with the provided \a painter, utilizing the internal label cache to significantly speed up drawing of labels that were drawn in previous calls. The tick label is always bound to an axis, the distance to the axis is controllable via \a distanceToAxis in pixels. The pixel position in the axis direction is passed in the \a position parameter. Hence for the bottom axis, \a position would indicate the horizontal pixel position (not coordinate), at which the label should be drawn. - + In order to later draw the axis label in a place that doesn't overlap with the tick labels, the largest tick label size is needed. This is acquired by passing a \a tickLabelsSize to the \ref drawTickLabel calls during the process of drawing all tick labels of one axis. In every call, \a tickLabelsSize is expanded, if the drawn label exceeds the value \a tickLabelsSize currently holds. - + The label is drawn with the font and pen that are currently set on the \a painter. To draw superscripted powers, the font is temporarily made smaller by a fixed factor (see \ref getTickLabelData). */ void QCPAxisPainterPrivate::placeTickLabel(QCPPainter *painter, double position, int distanceToAxis, const QString &text, QSize *tickLabelsSize) { - // warning: if you change anything here, also adapt getMaxTickLabelSize() accordingly! - if (text.isEmpty()) return; - QSize finalSize; - QPointF labelAnchor; - switch (type) - { - case QCPAxis::atLeft: labelAnchor = QPointF(axisRect.left()-distanceToAxis-offset, position); break; - case QCPAxis::atRight: labelAnchor = QPointF(axisRect.right()+distanceToAxis+offset, position); break; - case QCPAxis::atTop: labelAnchor = QPointF(position, axisRect.top()-distanceToAxis-offset); break; - case QCPAxis::atBottom: labelAnchor = QPointF(position, axisRect.bottom()+distanceToAxis+offset); break; - } - if (mParentPlot->plottingHints().testFlag(QCP::phCacheLabels) && !painter->modes().testFlag(QCPPainter::pmNoCaching)) // label caching enabled - { - CachedLabel *cachedLabel = mLabelCache.take(text); // attempt to get label from cache - if (!cachedLabel) // no cached label existed, create it - { - 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()); + // warning: if you change anything here, also adapt getMaxTickLabelSize() accordingly! + if (text.isEmpty()) { + return; + } + QSize finalSize; + QPointF labelAnchor; + switch (type) { + case QCPAxis::atLeft: + labelAnchor = QPointF(axisRect.left() - distanceToAxis - offset, position); + break; + case QCPAxis::atRight: + labelAnchor = QPointF(axisRect.right() + distanceToAxis + offset, position); + break; + case QCPAxis::atTop: + labelAnchor = QPointF(position, axisRect.top() - distanceToAxis - offset); + break; + case QCPAxis::atBottom: + labelAnchor = QPointF(position, axisRect.bottom() + distanceToAxis + offset); + break; + } + if (mParentPlot->plottingHints().testFlag(QCP::phCacheLabels) && !painter->modes().testFlag(QCPPainter::pmNoCaching)) { // label caching enabled + CachedLabel *cachedLabel = mLabelCache.take(text); // attempt to get label from cache + if (!cachedLabel) { // no cached label existed, create it + 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 # ifdef QCP_DEVICEPIXELRATIO_FLOAT - cachedLabel->pixmap.setDevicePixelRatio(mParentPlot->devicePixelRatioF()); + cachedLabel->pixmap.setDevicePixelRatio(mParentPlot->devicePixelRatioF()); # else - cachedLabel->pixmap.setDevicePixelRatio(mParentPlot->devicePixelRatio()); + cachedLabel->pixmap.setDevicePixelRatio(mParentPlot->devicePixelRatio()); # endif #endif - } else - cachedLabel->pixmap = QPixmap(labelData.rotatedTotalBounds.size()); - cachedLabel->pixmap.fill(Qt::transparent); - QCPPainter cachePainter(&cachedLabel->pixmap); - cachePainter.setPen(painter->pen()); - drawTickLabel(&cachePainter, -labelData.rotatedTotalBounds.topLeft().x(), -labelData.rotatedTotalBounds.topLeft().y(), labelData); + } else { + cachedLabel->pixmap = QPixmap(labelData.rotatedTotalBounds.size()); + } + cachedLabel->pixmap.fill(Qt::transparent); + QCPPainter cachePainter(&cachedLabel->pixmap); + cachePainter.setPen(painter->pen()); + drawTickLabel(&cachePainter, -labelData.rotatedTotalBounds.topLeft().x(), -labelData.rotatedTotalBounds.topLeft().y(), labelData); + } + // if label would be partly clipped by widget border on sides, don't draw it (only for outside tick labels): + bool labelClippedByBorder = false; + if (tickLabelSide == QCPAxis::lsOutside) { + if (QCPAxis::orientation(type) == Qt::Horizontal) { + 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() / mParentPlot->bufferDevicePixelRatio() > viewportRect.bottom() || labelAnchor.y() + cachedLabel->offset.y() < viewportRect.top(); + } + } + if (!labelClippedByBorder) { + painter->drawPixmap(labelAnchor + cachedLabel->offset, cachedLabel->pixmap); + 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: + TickLabelData labelData = getTickLabelData(painter->font(), text); + QPointF finalPosition = labelAnchor + getTickLabelDrawOffset(labelData); + // if label would be partly clipped by widget border on sides, don't draw it (only for outside tick labels): + bool labelClippedByBorder = false; + if (tickLabelSide == QCPAxis::lsOutside) { + if (QCPAxis::orientation(type) == Qt::Horizontal) { + labelClippedByBorder = finalPosition.x() + (labelData.rotatedTotalBounds.width() + labelData.rotatedTotalBounds.left()) > viewportRect.right() || finalPosition.x() + labelData.rotatedTotalBounds.left() < viewportRect.left(); + } else { + labelClippedByBorder = finalPosition.y() + (labelData.rotatedTotalBounds.height() + labelData.rotatedTotalBounds.top()) > viewportRect.bottom() || finalPosition.y() + labelData.rotatedTotalBounds.top() < viewportRect.top(); + } + } + if (!labelClippedByBorder) { + drawTickLabel(painter, finalPosition.x(), finalPosition.y(), labelData); + finalSize = labelData.rotatedTotalBounds.size(); + } } - // if label would be partly clipped by widget border on sides, don't draw it (only for outside tick labels): - bool labelClippedByBorder = false; - if (tickLabelSide == QCPAxis::lsOutside) - { - if (QCPAxis::orientation(type) == Qt::Horizontal) - 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()/mParentPlot->bufferDevicePixelRatio() > viewportRect.bottom() || labelAnchor.y()+cachedLabel->offset.y() < viewportRect.top(); + + // expand passed tickLabelsSize if current tick label is larger: + if (finalSize.width() > tickLabelsSize->width()) { + tickLabelsSize->setWidth(finalSize.width()); } - if (!labelClippedByBorder) - { - painter->drawPixmap(labelAnchor+cachedLabel->offset, cachedLabel->pixmap); - finalSize = cachedLabel->pixmap.size()/mParentPlot->bufferDevicePixelRatio(); + if (finalSize.height() > tickLabelsSize->height()) { + tickLabelsSize->setHeight(finalSize.height()); } - 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: - { - TickLabelData labelData = getTickLabelData(painter->font(), text); - QPointF finalPosition = labelAnchor + getTickLabelDrawOffset(labelData); - // if label would be partly clipped by widget border on sides, don't draw it (only for outside tick labels): - bool labelClippedByBorder = false; - if (tickLabelSide == QCPAxis::lsOutside) - { - if (QCPAxis::orientation(type) == Qt::Horizontal) - labelClippedByBorder = finalPosition.x()+(labelData.rotatedTotalBounds.width()+labelData.rotatedTotalBounds.left()) > viewportRect.right() || finalPosition.x()+labelData.rotatedTotalBounds.left() < viewportRect.left(); - else - labelClippedByBorder = finalPosition.y()+(labelData.rotatedTotalBounds.height()+labelData.rotatedTotalBounds.top()) > viewportRect.bottom() || finalPosition.y()+labelData.rotatedTotalBounds.top() < viewportRect.top(); - } - if (!labelClippedByBorder) - { - drawTickLabel(painter, finalPosition.x(), finalPosition.y(), labelData); - finalSize = labelData.rotatedTotalBounds.size(); - } - } - - // expand passed tickLabelsSize if current tick label is larger: - if (finalSize.width() > tickLabelsSize->width()) - tickLabelsSize->setWidth(finalSize.width()); - if (finalSize.height() > tickLabelsSize->height()) - tickLabelsSize->setHeight(finalSize.height()); } /*! \internal - + This is a \ref placeTickLabel helper function. - + Draws the tick label specified in \a labelData with \a painter at the pixel positions \a x and \a y. This function is used by \ref placeTickLabel to create new tick labels for the cache, or to directly draw the labels on the QCustomPlot surface when label caching is disabled, i.e. when @@ -9587,220 +9686,203 @@ void QCPAxisPainterPrivate::placeTickLabel(QCPPainter *painter, double position, */ void QCPAxisPainterPrivate::drawTickLabel(QCPPainter *painter, double x, double y, const TickLabelData &labelData) const { - // backup painter settings that we're about to change: - QTransform oldTransform = painter->transform(); - QFont oldFont = painter->font(); - - // transform painter to position/rotation: - painter->translate(x, y); - if (!qFuzzyIsNull(tickLabelRotation)) - painter->rotate(tickLabelRotation); - - // draw text: - if (!labelData.expPart.isEmpty()) // indicator that beautiful powers must be used - { - 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 - { - painter->setFont(labelData.baseFont); - painter->drawText(0, 0, labelData.totalBounds.width(), labelData.totalBounds.height(), Qt::TextDontClip | Qt::AlignHCenter, labelData.basePart); - } - - // reset painter settings to what it was before: - painter->setTransform(oldTransform); - painter->setFont(oldFont); + // backup painter settings that we're about to change: + QTransform oldTransform = painter->transform(); + QFont oldFont = painter->font(); + + // transform painter to position/rotation: + painter->translate(x, y); + if (!qFuzzyIsNull(tickLabelRotation)) { + painter->rotate(tickLabelRotation); + } + + // draw text: + if (!labelData.expPart.isEmpty()) { // indicator that beautiful powers must be used + 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 { + painter->setFont(labelData.baseFont); + painter->drawText(0, 0, labelData.totalBounds.width(), labelData.totalBounds.height(), Qt::TextDontClip | Qt::AlignHCenter, labelData.basePart); + } + + // reset painter settings to what it was before: + painter->setTransform(oldTransform); + painter->setFont(oldFont); } /*! \internal - + This is a \ref placeTickLabel helper function. - + Transforms the passed \a text and \a font to a tickLabelData structure that can then be further processed by \ref getTickLabelDrawOffset and \ref drawTickLabel. It splits the text into base and exponent if necessary (member substituteExponent) and calculates appropriate bounding boxes. */ QCPAxisPainterPrivate::TickLabelData QCPAxisPainterPrivate::getTickLabelData(const QFont &font, const QString &text) const { - TickLabelData result; - - // determine whether beautiful decimal powers should be used - bool useBeautifulPowers = false; - 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 > 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; + TickLabelData result; + + // determine whether beautiful decimal powers should be used + bool useBeautifulPowers = false; + 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 > 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: - result.baseFont = font; - if (result.baseFont.pointSizeF() > 0) // might return -1 if specified with setPixelSize, in that case we can't do correction in next line - result.baseFont.setPointSizeF(result.baseFont.pointSizeF()+0.05); // QFontMetrics.boundingRect has a bug for exact point sizes that make the results oscillate due to internal rounding - if (useBeautifulPowers) - { - // 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, 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); - if (!result.expPart.isEmpty() && result.expPart.at(0) == QLatin1Char('+')) - result.expPart.remove(0, 1); - // prepare smaller font for exponent: - result.expFont = font; - if (result.expFont.pointSize() > 0) - result.expFont.setPointSize(result.expFont.pointSize()*0.75); - else - result.expFont.setPixelSize(result.expFont.pixelSize()*0.75); - // 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); - 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; - result.totalBounds = QFontMetrics(result.baseFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip | Qt::AlignHCenter, result.basePart); - } - result.totalBounds.moveTopLeft(QPoint(0, 0)); // want bounding box aligned top left at origin, independent of how it was created, to make further processing simpler - - // calculate possibly different bounding rect after rotation: - result.rotatedTotalBounds = result.totalBounds; - if (!qFuzzyIsNull(tickLabelRotation)) - { - QTransform transform; - transform.rotate(tickLabelRotation); - result.rotatedTotalBounds = transform.mapRect(result.rotatedTotalBounds); - } - - return result; + + // calculate text bounding rects and do string preparation for beautiful decimal powers: + result.baseFont = font; + if (result.baseFont.pointSizeF() > 0) { // might return -1 if specified with setPixelSize, in that case we can't do correction in next line + result.baseFont.setPointSizeF(result.baseFont.pointSizeF() + 0.05); // QFontMetrics.boundingRect has a bug for exact point sizes that make the results oscillate due to internal rounding + } + if (useBeautifulPowers) { + // 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, 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); + } + if (!result.expPart.isEmpty() && result.expPart.at(0) == QLatin1Char('+')) { + result.expPart.remove(0, 1); + } + // prepare smaller font for exponent: + result.expFont = font; + if (result.expFont.pointSize() > 0) { + result.expFont.setPointSize(result.expFont.pointSize() * 0.75); + } else { + result.expFont.setPixelSize(result.expFont.pixelSize() * 0.75); + } + // 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); + 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; + result.totalBounds = QFontMetrics(result.baseFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip | Qt::AlignHCenter, result.basePart); + } + result.totalBounds.moveTopLeft(QPoint(0, 0)); // want bounding box aligned top left at origin, independent of how it was created, to make further processing simpler + + // calculate possibly different bounding rect after rotation: + result.rotatedTotalBounds = result.totalBounds; + if (!qFuzzyIsNull(tickLabelRotation)) { + QTransform transform; + transform.rotate(tickLabelRotation); + result.rotatedTotalBounds = transform.mapRect(result.rotatedTotalBounds); + } + + return result; } /*! \internal - + This is a \ref placeTickLabel helper function. - + Calculates the offset at which the top left corner of the specified tick label shall be drawn. The offset is relative to a point right next to the tick the label belongs to. - + This function is thus responsible for e.g. centering tick labels under ticks and positioning them appropriately when they are rotated. */ QPointF QCPAxisPainterPrivate::getTickLabelDrawOffset(const TickLabelData &labelData) const { - /* - calculate label offset from base point at tick (non-trivial, for best visual appearance): short - explanation for bottom axis: The anchor, i.e. the point in the label that is placed - horizontally under the corresponding tick is always on the label side that is closer to the - axis (e.g. the left side of the text when we're rotating clockwise). On that side, the height - is halved and the resulting point is defined the anchor. This way, a 90 degree rotated text - will be centered under the tick (i.e. displaced horizontally by half its height). At the same - time, a 45 degree rotated text will "point toward" its tick, as is typical for rotated tick - labels. - */ - bool doRotation = !qFuzzyIsNull(tickLabelRotation); - bool flip = qFuzzyCompare(qAbs(tickLabelRotation), 90.0); // perfect +/-90 degree flip. Indicates vertical label centering on vertical axes. - double radians = tickLabelRotation/180.0*M_PI; - int x=0, y=0; - if ((type == QCPAxis::atLeft && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atRight && tickLabelSide == QCPAxis::lsInside)) // Anchor at right side of tick label - { - if (doRotation) - { - if (tickLabelRotation > 0) - { - x = -qCos(radians)*labelData.totalBounds.width(); - y = flip ? -labelData.totalBounds.width()/2.0 : -qSin(radians)*labelData.totalBounds.width()-qCos(radians)*labelData.totalBounds.height()/2.0; - } else - { - x = -qCos(-radians)*labelData.totalBounds.width()-qSin(-radians)*labelData.totalBounds.height(); - y = flip ? +labelData.totalBounds.width()/2.0 : +qSin(-radians)*labelData.totalBounds.width()-qCos(-radians)*labelData.totalBounds.height()/2.0; - } - } else - { - x = -labelData.totalBounds.width(); - y = -labelData.totalBounds.height()/2.0; + /* + calculate label offset from base point at tick (non-trivial, for best visual appearance): short + explanation for bottom axis: The anchor, i.e. the point in the label that is placed + horizontally under the corresponding tick is always on the label side that is closer to the + axis (e.g. the left side of the text when we're rotating clockwise). On that side, the height + is halved and the resulting point is defined the anchor. This way, a 90 degree rotated text + will be centered under the tick (i.e. displaced horizontally by half its height). At the same + time, a 45 degree rotated text will "point toward" its tick, as is typical for rotated tick + labels. + */ + bool doRotation = !qFuzzyIsNull(tickLabelRotation); + bool flip = qFuzzyCompare(qAbs(tickLabelRotation), 90.0); // perfect +/-90 degree flip. Indicates vertical label centering on vertical axes. + double radians = tickLabelRotation / 180.0 * M_PI; + int x = 0, y = 0; + if ((type == QCPAxis::atLeft && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atRight && tickLabelSide == QCPAxis::lsInside)) { // Anchor at right side of tick label + if (doRotation) { + if (tickLabelRotation > 0) { + x = -qCos(radians) * labelData.totalBounds.width(); + y = flip ? -labelData.totalBounds.width() / 2.0 : -qSin(radians) * labelData.totalBounds.width() - qCos(radians) * labelData.totalBounds.height() / 2.0; + } else { + x = -qCos(-radians) * labelData.totalBounds.width() - qSin(-radians) * labelData.totalBounds.height(); + y = flip ? +labelData.totalBounds.width() / 2.0 : +qSin(-radians) * labelData.totalBounds.width() - qCos(-radians) * labelData.totalBounds.height() / 2.0; + } + } else { + x = -labelData.totalBounds.width(); + y = -labelData.totalBounds.height() / 2.0; + } + } else if ((type == QCPAxis::atRight && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atLeft && tickLabelSide == QCPAxis::lsInside)) { // Anchor at left side of tick label + if (doRotation) { + if (tickLabelRotation > 0) { + x = +qSin(radians) * labelData.totalBounds.height(); + y = flip ? -labelData.totalBounds.width() / 2.0 : -qCos(radians) * labelData.totalBounds.height() / 2.0; + } else { + x = 0; + y = flip ? +labelData.totalBounds.width() / 2.0 : -qCos(-radians) * labelData.totalBounds.height() / 2.0; + } + } else { + x = 0; + y = -labelData.totalBounds.height() / 2.0; + } + } else if ((type == QCPAxis::atTop && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atBottom && tickLabelSide == QCPAxis::lsInside)) { // Anchor at bottom side of tick label + if (doRotation) { + if (tickLabelRotation > 0) { + x = -qCos(radians) * labelData.totalBounds.width() + qSin(radians) * labelData.totalBounds.height() / 2.0; + y = -qSin(radians) * labelData.totalBounds.width() - qCos(radians) * labelData.totalBounds.height(); + } else { + x = -qSin(-radians) * labelData.totalBounds.height() / 2.0; + y = -qCos(-radians) * labelData.totalBounds.height(); + } + } else { + x = -labelData.totalBounds.width() / 2.0; + y = -labelData.totalBounds.height(); + } + } else if ((type == QCPAxis::atBottom && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atTop && tickLabelSide == QCPAxis::lsInside)) { // Anchor at top side of tick label + if (doRotation) { + if (tickLabelRotation > 0) { + x = +qSin(radians) * labelData.totalBounds.height() / 2.0; + y = 0; + } else { + x = -qCos(-radians) * labelData.totalBounds.width() - qSin(-radians) * labelData.totalBounds.height() / 2.0; + y = +qSin(-radians) * labelData.totalBounds.width(); + } + } else { + x = -labelData.totalBounds.width() / 2.0; + y = 0; + } } - } else if ((type == QCPAxis::atRight && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atLeft && tickLabelSide == QCPAxis::lsInside)) // Anchor at left side of tick label - { - if (doRotation) - { - if (tickLabelRotation > 0) - { - x = +qSin(radians)*labelData.totalBounds.height(); - y = flip ? -labelData.totalBounds.width()/2.0 : -qCos(radians)*labelData.totalBounds.height()/2.0; - } else - { - x = 0; - y = flip ? +labelData.totalBounds.width()/2.0 : -qCos(-radians)*labelData.totalBounds.height()/2.0; - } - } else - { - x = 0; - y = -labelData.totalBounds.height()/2.0; - } - } else if ((type == QCPAxis::atTop && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atBottom && tickLabelSide == QCPAxis::lsInside)) // Anchor at bottom side of tick label - { - if (doRotation) - { - if (tickLabelRotation > 0) - { - x = -qCos(radians)*labelData.totalBounds.width()+qSin(radians)*labelData.totalBounds.height()/2.0; - y = -qSin(radians)*labelData.totalBounds.width()-qCos(radians)*labelData.totalBounds.height(); - } else - { - x = -qSin(-radians)*labelData.totalBounds.height()/2.0; - y = -qCos(-radians)*labelData.totalBounds.height(); - } - } else - { - x = -labelData.totalBounds.width()/2.0; - y = -labelData.totalBounds.height(); - } - } else if ((type == QCPAxis::atBottom && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atTop && tickLabelSide == QCPAxis::lsInside)) // Anchor at top side of tick label - { - if (doRotation) - { - if (tickLabelRotation > 0) - { - x = +qSin(radians)*labelData.totalBounds.height()/2.0; - y = 0; - } else - { - x = -qCos(-radians)*labelData.totalBounds.width()-qSin(-radians)*labelData.totalBounds.height()/2.0; - y = +qSin(-radians)*labelData.totalBounds.width(); - } - } else - { - x = -labelData.totalBounds.width()/2.0; - y = 0; - } - } - - return QPointF(x, y); + + return QPointF(x, y); } /*! \internal - + Simulates the steps done by \ref placeTickLabel by calculating bounding boxes of the text label to be drawn, depending on number format etc. Since only the largest tick label is wanted for the margin calculation, the passed \a tickLabelsSize is only expanded, if it's currently set to a @@ -9808,23 +9890,23 @@ QPointF QCPAxisPainterPrivate::getTickLabelDrawOffset(const TickLabelData &label */ void QCPAxisPainterPrivate::getMaxTickLabelSize(const QFont &font, const QString &text, QSize *tickLabelsSize) const { - // note: this function must return the same tick label sizes as the placeTickLabel function. - QSize finalSize; - 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()/mParentPlot->bufferDevicePixelRatio(); - } else // label caching disabled or no label with this text cached: - { - TickLabelData labelData = getTickLabelData(font, text); - finalSize = labelData.rotatedTotalBounds.size(); - } - - // expand passed tickLabelsSize if current tick label is larger: - if (finalSize.width() > tickLabelsSize->width()) - tickLabelsSize->setWidth(finalSize.width()); - if (finalSize.height() > tickLabelsSize->height()) - tickLabelsSize->setHeight(finalSize.height()); + // note: this function must return the same tick label sizes as the placeTickLabel function. + QSize finalSize; + 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() / mParentPlot->bufferDevicePixelRatio(); + } else { // label caching disabled or no label with this text cached: + TickLabelData labelData = getTickLabelData(font, text); + finalSize = labelData.rotatedTotalBounds.size(); + } + + // expand passed tickLabelsSize if current tick label is larger: + if (finalSize.width() > tickLabelsSize->width()) { + tickLabelsSize->setWidth(finalSize.width()); + } + if (finalSize.height() > tickLabelsSize->height()) { + tickLabelsSize->setHeight(finalSize.height()); + } } /* end of 'src/axis/axis.cpp' */ @@ -9838,33 +9920,33 @@ void QCPAxisPainterPrivate::getMaxTickLabelSize(const QFont &font, const QString /*! \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 @@ -9872,15 +9954,15 @@ void QCPAxisPainterPrivate::getMaxTickLabelSize(const QFont &font, const QString 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. @@ -9889,23 +9971,23 @@ void QCPAxisPainterPrivate::getMaxTickLabelSize(const QFont &font, const QString /* 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 */ @@ -9913,32 +9995,32 @@ void QCPAxisPainterPrivate::getMaxTickLabelSize(const QFont &font, const QString /*! 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) + 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) + mSize(size), + mShape(shape), + mPen(Qt::NoPen), + mBrush(Qt::NoBrush), + mPenDefined(false) { } @@ -9947,11 +10029,11 @@ QCPScatterStyle::QCPScatterStyle(ScatterShape shape, double size) : 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) + mSize(size), + mShape(shape), + mPen(QPen(color)), + mBrush(Qt::NoBrush), + mPenDefined(true) { } @@ -9960,18 +10042,18 @@ QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QColor &color, double 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) + 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 @@ -9984,11 +10066,11 @@ QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QColor &color, const 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) + mSize(size), + mShape(shape), + mPen(pen), + mBrush(brush), + mPenDefined(pen.style() != Qt::NoPen) { } @@ -9997,31 +10079,31 @@ QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QPen &pen, const QBru is set to \ref ssPixmap. */ QCPScatterStyle::QCPScatterStyle(const QPixmap &pixmap) : - mSize(5), - mShape(ssPixmap), - mPen(Qt::NoPen), - mBrush(Qt::NoBrush), - mPixmap(pixmap), - mPenDefined(false) + 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 in its original size by default. To for example double the size of the path, 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) + mSize(size), + mShape(ssCustom), + mPen(pen), + mBrush(brush), + mCustomPath(customPath), + mPenDefined(pen.style() != Qt::NoPen) { } @@ -10030,97 +10112,99 @@ QCPScatterStyle::QCPScatterStyle(const QPainterPath &customPath, const QPen &pen */ 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()); - } + 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; + 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; + 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; + 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; + 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; + 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; + setShape(ssCustom); + mCustomPath = customPath; } /*! @@ -10131,35 +10215,35 @@ void QCPScatterStyle::setCustomPath(const QPainterPath &customPath) */ void QCPScatterStyle::undefinePen() { - mPenDefined = false; + 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); + 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()); + drawShape(painter, pos.x(), pos.y()); } /*! \overload @@ -10167,137 +10251,124 @@ void QCPScatterStyle::drawShape(QCPPainter *painter, const QPointF &pos) const */ 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: - { - QPointF lineArray[4] = {QPointF(x-w, y), - QPointF( x, y-w), - QPointF(x+w, y), - QPointF( x, y+w)}; - painter->drawPolygon(lineArray, 4); - 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: - { - QPointF lineArray[3] = {QPointF(x-w, y+0.755*w), - QPointF(x+w, y+0.755*w), - QPointF( x, y-0.977*w)}; - painter->drawPolygon(lineArray, 3); - break; - } - case ssTriangleInverted: - { - QPointF lineArray[3] = {QPointF(x-w, y-0.755*w), - QPointF(x+w, y-0.755*w), - QPointF( x, y+0.977*w)}; - painter->drawPolygon(lineArray, 3); - break; - } - case ssCrossSquare: - { - painter->drawRect(QRectF(x-w, y-w, mSize, mSize)); - 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)); - break; - } - case ssPlusSquare: - { - painter->drawRect(QRectF(x-w, y-w, mSize, mSize)); - painter->drawLine(QLineF(x-w, y, x+w*0.95, y)); - painter->drawLine(QLineF( x, y+w, x, y-w)); - break; - } - case ssCrossCircle: - { - painter->drawEllipse(QPointF(x, y), w, w); - 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)); - break; - } - case ssPlusCircle: - { - painter->drawEllipse(QPointF(x, y), w, w); - painter->drawLine(QLineF(x-w, y, x+w, y)); - painter->drawLine(QLineF( x, y+w, x, y-w)); - break; - } - case ssPeace: - { - painter->drawEllipse(QPointF(x, y), w, w); - 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)); - break; - } - case ssPixmap: - { - const double widthHalf = mPixmap.width()*0.5; - const double heightHalf = mPixmap.height()*0.5; + 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: { + QPointF lineArray[4] = {QPointF(x - w, y), + QPointF(x, y - w), + QPointF(x + w, y), + QPointF(x, y + w) + }; + painter->drawPolygon(lineArray, 4); + 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: { + QPointF lineArray[3] = {QPointF(x - w, y + 0.755 * w), + QPointF(x + w, y + 0.755 * w), + QPointF(x, y - 0.977 * w) + }; + painter->drawPolygon(lineArray, 3); + break; + } + case ssTriangleInverted: { + QPointF lineArray[3] = {QPointF(x - w, y - 0.755 * w), + QPointF(x + w, y - 0.755 * w), + QPointF(x, y + 0.977 * w) + }; + painter->drawPolygon(lineArray, 3); + break; + } + case ssCrossSquare: { + painter->drawRect(QRectF(x - w, y - w, mSize, mSize)); + 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)); + break; + } + case ssPlusSquare: { + painter->drawRect(QRectF(x - w, y - w, mSize, mSize)); + painter->drawLine(QLineF(x - w, y, x + w * 0.95, y)); + painter->drawLine(QLineF(x, y + w, x, y - w)); + break; + } + case ssCrossCircle: { + painter->drawEllipse(QPointF(x, y), w, w); + 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)); + break; + } + case ssPlusCircle: { + painter->drawEllipse(QPointF(x, y), w, w); + painter->drawLine(QLineF(x - w, y, x + w, y)); + painter->drawLine(QLineF(x, y + w, x, y - w)); + break; + } + case ssPeace: { + painter->drawEllipse(QPointF(x, y), w, w); + 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)); + 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); + const QRectF clipRect = painter->clipRegion().boundingRect().adjusted(-widthHalf, -heightHalf, widthHalf, heightHalf); #else - const QRectF clipRect = painter->clipBoundingRect().adjusted(-widthHalf, -heightHalf, widthHalf, heightHalf); + const QRectF clipRect = painter->clipBoundingRect().adjusted(-widthHalf, -heightHalf, widthHalf, heightHalf); #endif - if (clipRect.contains(x, y)) - painter->drawPixmap(x-widthHalf, y-heightHalf, mPixmap); - break; + 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; + } } - 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' */ @@ -10312,24 +10383,24 @@ void QCPScatterStyle::drawShape(QCPPainter *painter, double x, double y) const /*! \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 @@ -10340,11 +10411,11 @@ void QCPScatterStyle::drawShape(QCPPainter *painter, double x, double y) const Creates a new QCPSelectionDecorator instance with default values */ QCPSelectionDecorator::QCPSelectionDecorator() : - mPen(QColor(80, 80, 255), 2.5), - mBrush(Qt::NoBrush), - mScatterStyle(), - mUsedScatterProperties(QCPScatterStyle::spNone), - mPlottable(0) + mPen(QColor(80, 80, 255), 2.5), + mBrush(Qt::NoBrush), + mScatterStyle(), + mUsedScatterProperties(QCPScatterStyle::spNone), + mPlottable(0) { } @@ -10357,7 +10428,7 @@ QCPSelectionDecorator::~QCPSelectionDecorator() */ void QCPSelectionDecorator::setPen(const QPen &pen) { - mPen = pen; + mPen = pen; } /*! @@ -10365,52 +10436,52 @@ void QCPSelectionDecorator::setPen(const QPen &pen) */ void QCPSelectionDecorator::setBrush(const QBrush &brush) { - mBrush = 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); + 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. - + \see QCPScatterStyle::ScatterProperty */ void QCPSelectionDecorator::setUsedScatterProperties(const QCPScatterStyle::ScatterProperties &properties) { - mUsedScatterProperties = 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); + 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); + painter->setBrush(mBrush); } /*! @@ -10418,21 +10489,22 @@ void QCPSelectionDecorator::applyBrush(QCPPainter *painter) const 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; + 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; } /*! @@ -10441,45 +10513,43 @@ QCPScatterStyle QCPSelectionDecorator::getFinalScatterStyle(const QCPScatterStyl */ void QCPSelectionDecorator::copyFrom(const QCPSelectionDecorator *other) { - setPen(other->pen()); - setBrush(other->brush()); - setScatterStyle(other->scatterStyle(), other->usedScatterProperties()); + 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) + 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; - } + if (!mPlottable) { + mPlottable = plottable; + return true; + } else { + qDebug() << Q_FUNC_INFO << "This selection decorator is already registered with plottable:" << reinterpret_cast(mPlottable); + return false; + } } @@ -10496,7 +10566,7 @@ bool QCPSelectionDecorator::registerWithPlottable(QCPAbstractPlottable *plottabl 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 and/or scatter points \ref QCPGraph (typically created with \ref QCustomPlot::addGraph) @@ -10505,14 +10575,14 @@ bool QCPSelectionDecorator::registerWithPlottable(QCPAbstractPlottable *plottabl \li A statistical box plot: \ref QCPStatisticalBox \li A color encoded two-dimensional map: \ref QCPColorMap \li An OHLC/Candlestick chart: \ref QCPFinancial - + \section plottables-subclassing Creating own plottables - + 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 @@ -10520,9 +10590,9 @@ bool QCPSelectionDecorator::registerWithPlottable(QCPAbstractPlottable *plottabl \li \ref drawLegendIcon \li \ref getKeyRange \li \ref getValueRange - + See the documentation of those functions for what they need to do. - + For drawing your plot, you can use the \ref coordsToPixels functions to translate a point in plot coordinates to pixel coordinates. This function is quite convenient, because it takes the orientation of the key and value axes into account for you (x and y are swapped when the key axis @@ -10530,7 +10600,7 @@ bool QCPSelectionDecorator::registerWithPlottable(QCPAbstractPlottable *plottabl to translate many points in a loop like QCPGraph), you can directly use \ref QCPAxis::coordToPixel. However, you must then take care about the orientation of the axis yourself. - + Here are some important members you inherit from QCPAbstractPlottable: @@ -10571,35 +10641,35 @@ bool QCPSelectionDecorator::registerWithPlottable(QCPAbstractPlottable *plottabl /* start of documentation of inline functions */ /*! \fn QCPSelectionDecorator *QCPAbstractPlottable::selectionDecorator() const - + Provides access to the selection decorator of this plottable. The selection decorator controls how selected data ranges are drawn (e.g. their pen color and fill), see \ref QCPSelectionDecorator for details. - + If you wish to use an own \ref QCPSelectionDecorator subclass, pass an instance of it to \ref setSelectionDecorator. */ /*! \fn bool QCPAbstractPlottable::selected() const - + Returns true if there are any data points of the plottable currently selected. Use \ref selection to retrieve the current \ref QCPDataSelection. */ /*! \fn QCPDataSelection QCPAbstractPlottable::selection() const - + Returns a \ref QCPDataSelection encompassing all the data points that are currently selected on this plottable. - + \see selected, setSelection, setSelectable */ /*! \fn 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. */ @@ -10609,16 +10679,16 @@ bool QCPSelectionDecorator::registerWithPlottable(QCPAbstractPlottable *plottabl /*! \fn void QCPAbstractPlottable::drawLegendIcon(QCPPainter *painter, const QRect &rect) const = 0 \internal - + called by QCPLegend::draw (via QCPPlottableLegendItem::draw) to create a graphical representation of this plottable inside \a rect, next to the plottable name. - + The passed \a painter has its cliprect set to \a rect, so painting outside of \a rect won't appear outside the legend icon border. */ /*! \fn QCPRange QCPAbstractPlottable::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const = 0 - + 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 @@ -10631,12 +10701,12 @@ bool QCPSelectionDecorator::registerWithPlottable(QCPAbstractPlottable *plottabl 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, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const = 0 - + Returns the coordinate range that the data points in the specified key range (\a inKeyRange) span in the value axis dimension. For logarithmic plots, one can set \a inSignDomain to either \ref QCP::sdNegative or \ref QCP::sdPositive in order to restrict the returned range to that sign @@ -10645,7 +10715,7 @@ bool QCPSelectionDecorator::registerWithPlottable(QCPAbstractPlottable *plottabl 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. @@ -10653,7 +10723,7 @@ bool QCPSelectionDecorator::registerWithPlottable(QCPAbstractPlottable *plottabl 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 */ @@ -10661,27 +10731,27 @@ bool QCPSelectionDecorator::registerWithPlottable(QCPAbstractPlottable *plottabl /* start of documentation of signals */ /*! \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 setSelection. The parameter \a selected indicates whether there are any points selected or not. - + \see selectionChanged(const QCPDataSelection &selection) */ /*! \fn void QCPAbstractPlottable::selectionChanged(const QCPDataSelection &selection) - + This signal is emitted when the selection state of this plottable has changed, either by user interaction or by a direct call to \ref setSelection. The parameter \a selection holds the currently selected data ranges. - + \see selectionChanged(bool selected) */ /*! \fn void QCPAbstractPlottable::selectableChanged(QCP::SelectionType selectable); - + This signal is emitted when the selectability of this plottable has changed. - + \see setSelectable */ @@ -10692,40 +10762,41 @@ bool QCPSelectionDecorator::registerWithPlottable(QCPAbstractPlottable *plottabl its value axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and have perpendicular orientations. If either of these restrictions is violated, a corresponding message is printed to the debug output (qDebug), the construction is not aborted, though. - + Since QCPAbstractPlottable is an abstract class that defines the basic interface to plottables, it can't be directly instantiated. - + You probably want one of the subclasses like \ref QCPGraph or \ref QCPCurve instead. */ QCPAbstractPlottable::QCPAbstractPlottable(QCPAxis *keyAxis, QCPAxis *valueAxis) : - QCPLayerable(keyAxis->parentPlot(), QString(), keyAxis->axisRect()), - mName(), - mAntialiasedFill(true), - mAntialiasedScatters(true), - mPen(Qt::black), - mBrush(Qt::NoBrush), - mKeyAxis(keyAxis), - mValueAxis(valueAxis), - mSelectable(QCP::stWhole), - mSelectionDecorator(0) + QCPLayerable(keyAxis->parentPlot(), QString(), keyAxis->axisRect()), + mName(), + mAntialiasedFill(true), + mAntialiasedScatters(true), + mPen(Qt::black), + mBrush(Qt::NoBrush), + mKeyAxis(keyAxis), + mValueAxis(valueAxis), + 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); + 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; - } + if (mSelectionDecorator) { + delete mSelectionDecorator; + mSelectionDecorator = 0; + } } /*! @@ -10734,48 +10805,48 @@ QCPAbstractPlottable::~QCPAbstractPlottable() */ void QCPAbstractPlottable::setName(const QString &name) { - mName = name; + mName = name; } /*! Sets whether fills 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::setAntialiasedFill(bool enabled) { - mAntialiasedFill = enabled; + mAntialiasedFill = enabled; } /*! Sets whether the scatter symbols 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::setAntialiasedScatters(bool enabled) { - mAntialiasedScatters = enabled; + mAntialiasedScatters = enabled; } /*! The pen is used to draw basic lines that make up the plottable representation in the plot. - + For example, the \ref QCPGraph subclass draws its graph lines with this pen. \see setBrush */ void QCPAbstractPlottable::setPen(const QPen &pen) { - mPen = pen; + mPen = 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. - + For example, the \ref QCPGraph subclass draws the fill under the graph with this brush, when it's not set to Qt::NoBrush. @@ -10783,7 +10854,7 @@ void QCPAbstractPlottable::setPen(const QPen &pen) */ void QCPAbstractPlottable::setBrush(const QBrush &brush) { - mBrush = brush; + mBrush = brush; } /*! @@ -10791,7 +10862,7 @@ void QCPAbstractPlottable::setBrush(const QBrush &brush) to the plottable's value axis. This function performs no checks to make sure this is the case. The typical mathematical choice is to use the x-axis (QCustomPlot::xAxis) as key axis and the y-axis (QCustomPlot::yAxis) as value axis. - + Normally, the key and value axes are set in the constructor of the plottable (or \ref QCustomPlot::addGraph when working with QCPGraphs through the dedicated graph interface). @@ -10799,7 +10870,7 @@ void QCPAbstractPlottable::setBrush(const QBrush &brush) */ void QCPAbstractPlottable::setKeyAxis(QCPAxis *axis) { - mKeyAxis = axis; + mKeyAxis = axis; } /*! @@ -10810,12 +10881,12 @@ void QCPAbstractPlottable::setKeyAxis(QCPAxis *axis) Normally, the key and value axes are set in the constructor of the plottable (or \ref QCustomPlot::addGraph when working with QCPGraphs through the dedicated graph interface). - + \see setKeyAxis */ void QCPAbstractPlottable::setValueAxis(QCPAxis *axis) { - mValueAxis = axis; + mValueAxis = axis; } @@ -10823,55 +10894,52 @@ void QCPAbstractPlottable::setValueAxis(QCPAxis *axis) 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 programmatically. - + Using \ref setSelectable you can further specify for each plottable whether and to which granularity it is selectable. If \a selection is not compatible with the current \ref QCP::SelectionType set via \ref setSelectable, the resulting selection will be adjusted accordingly (see \ref QCPDataSelection::enforceType). - + emits the \ref selectionChanged signal when \a selected is different from the previous selection state. - + \see setSelectable, selectTest */ void QCPAbstractPlottable::setSelection(QCPDataSelection selection) { - selection.enforceType(mSelectable); - if (mSelection != selection) - { - mSelection = selection; - emit selectionChanged(selected()); - emit selectionChanged(mSelection); - } + selection.enforceType(mSelectable); + if (mSelection != selection) { + mSelection = selection; + emit selectionChanged(selected()); + emit selectionChanged(mSelection); + } } /*! Use this method to set an own QCPSelectionDecorator (subclass) instance. This allows you to customize the visual representation of selected data ranges further than by using the default QCPSelectionDecorator. - + The plottable takes ownership of the \a decorator. - + The currently set decorator can be accessed via \ref selectionDecorator. */ void QCPAbstractPlottable::setSelectionDecorator(QCPSelectionDecorator *decorator) { - if (decorator) - { - if (decorator->registerWithPlottable(this)) - { - if (mSelectionDecorator) // delete old decorator if necessary + 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 = decorator; + mSelectionDecorator = 0; } - } else if (mSelectionDecorator) // just clear decorator - { - delete mSelectionDecorator; - mSelectionDecorator = 0; - } } /*! @@ -10881,23 +10949,21 @@ void QCPAbstractPlottable::setSelectionDecorator(QCPSelectionDecorator *decorato 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); + if (mSelectable != selectable) { + mSelectable = selectable; + QCPDataSelection oldSelection = mSelection; + mSelection.enforceType(mSelectable); + emit selectableChanged(mSelectable); + if (mSelection != oldSelection) { + emit selectionChanged(selected()); + emit selectionChanged(mSelection); + } } - } } @@ -10912,19 +10978,20 @@ void QCPAbstractPlottable::setSelectable(QCP::SelectionType selectable) */ 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); - } + 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 @@ -10933,14 +11000,18 @@ void QCPAbstractPlottable::coordsToPixels(double key, double value, double &x, d */ 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)); + 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)); + } } /*! @@ -10954,19 +11025,20 @@ const QPointF QCPAbstractPlottable::coordsToPixels(double key, double value) con */ 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); - } + 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 @@ -10975,7 +11047,7 @@ void QCPAbstractPlottable::pixelsToCoords(double x, double y, double &key, doubl */ void QCPAbstractPlottable::pixelsToCoords(const QPointF &pixelPos, double &key, double &value) const { - pixelsToCoords(pixelPos.x(), pixelPos.y(), key, value); + pixelsToCoords(pixelPos.x(), pixelPos.y(), key, value); } /*! @@ -10984,54 +11056,55 @@ void QCPAbstractPlottable::pixelsToCoords(const QPointF &pixelPos, double &key, sure not to rescale to an illegal range i.e. a range containing different signs and/or zero. Instead it will stay in the current sign domain and ignore all parts of the plottable that lie outside of that domain. - + \a onlyEnlarge makes sure the ranges are only expanded, never reduced. So it's possible to show multiple plottables in their entirety by multiple calls to rescaleAxes where the first call has \a onlyEnlarge set to false (the default), and all subsequent set to true. - + \see rescaleKeyAxis, rescaleValueAxis, QCustomPlot::rescaleAxes, QCPAxis::rescale */ void QCPAbstractPlottable::rescaleAxes(bool onlyEnlarge) const { - rescaleKeyAxis(onlyEnlarge); - rescaleValueAxis(onlyEnlarge); + rescaleKeyAxis(onlyEnlarge); + rescaleValueAxis(onlyEnlarge); } /*! Rescales the key axis of the plottable so the whole plottable is visible. - + See \ref rescaleAxes for detailed behaviour. */ void QCPAbstractPlottable::rescaleKeyAxis(bool onlyEnlarge) const { - QCPAxis *keyAxis = mKeyAxis.data(); - if (!keyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; } - - QCP::SignDomain signDomain = QCP::sdBoth; - if (keyAxis->scaleType() == QCPAxis::stLogarithmic) - signDomain = (keyAxis->range().upper < 0 ? QCP::sdNegative : QCP::sdPositive); - - bool foundRange; - QCPRange newRange = getKeyRange(foundRange, signDomain); - if (foundRange) - { - if (onlyEnlarge) - newRange.expand(keyAxis->range()); - if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable - { - double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason - if (keyAxis->scaleType() == QCPAxis::stLinear) - { - newRange.lower = center-keyAxis->range().size()/2.0; - newRange.upper = center+keyAxis->range().size()/2.0; - } else // scaleType() == stLogarithmic - { - newRange.lower = center/qSqrt(keyAxis->range().upper/keyAxis->range().lower); - newRange.upper = center*qSqrt(keyAxis->range().upper/keyAxis->range().lower); - } + QCPAxis *keyAxis = mKeyAxis.data(); + if (!keyAxis) { + qDebug() << Q_FUNC_INFO << "invalid key axis"; + return; + } + + QCP::SignDomain signDomain = QCP::sdBoth; + if (keyAxis->scaleType() == QCPAxis::stLogarithmic) { + signDomain = (keyAxis->range().upper < 0 ? QCP::sdNegative : QCP::sdPositive); + } + + bool foundRange; + QCPRange newRange = getKeyRange(foundRange, signDomain); + if (foundRange) { + if (onlyEnlarge) { + newRange.expand(keyAxis->range()); + } + if (!QCPRange::validRange(newRange)) { // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable + double center = (newRange.lower + newRange.upper) * 0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason + if (keyAxis->scaleType() == QCPAxis::stLinear) { + newRange.lower = center - keyAxis->range().size() / 2.0; + newRange.upper = center + keyAxis->range().size() / 2.0; + } else { // scaleType() == stLogarithmic + newRange.lower = center / qSqrt(keyAxis->range().upper / keyAxis->range().lower); + newRange.upper = center * qSqrt(keyAxis->range().upper / keyAxis->range().lower); + } + } + keyAxis->setRange(newRange); } - keyAxis->setRange(newRange); - } } /*! @@ -11046,35 +11119,36 @@ void QCPAbstractPlottable::rescaleKeyAxis(bool onlyEnlarge) const */ void QCPAbstractPlottable::rescaleValueAxis(bool onlyEnlarge, bool inKeyRange) const { - QCPAxis *keyAxis = mKeyAxis.data(); - QCPAxis *valueAxis = mValueAxis.data(); - if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } - - QCP::SignDomain signDomain = QCP::sdBoth; - if (valueAxis->scaleType() == QCPAxis::stLogarithmic) - signDomain = (valueAxis->range().upper < 0 ? QCP::sdNegative : QCP::sdPositive); - - bool foundRange; - QCPRange newRange = getValueRange(foundRange, signDomain, inKeyRange ? keyAxis->range() : QCPRange()); - if (foundRange) - { - if (onlyEnlarge) - newRange.expand(valueAxis->range()); - if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable - { - double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason - if (valueAxis->scaleType() == QCPAxis::stLinear) - { - newRange.lower = center-valueAxis->range().size()/2.0; - newRange.upper = center+valueAxis->range().size()/2.0; - } else // scaleType() == stLogarithmic - { - newRange.lower = center/qSqrt(valueAxis->range().upper/valueAxis->range().lower); - newRange.upper = center*qSqrt(valueAxis->range().upper/valueAxis->range().lower); - } + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + return; + } + + QCP::SignDomain signDomain = QCP::sdBoth; + if (valueAxis->scaleType() == QCPAxis::stLogarithmic) { + signDomain = (valueAxis->range().upper < 0 ? QCP::sdNegative : QCP::sdPositive); + } + + bool foundRange; + QCPRange newRange = getValueRange(foundRange, signDomain, inKeyRange ? keyAxis->range() : QCPRange()); + if (foundRange) { + if (onlyEnlarge) { + newRange.expand(valueAxis->range()); + } + if (!QCPRange::validRange(newRange)) { // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable + double center = (newRange.lower + newRange.upper) * 0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason + if (valueAxis->scaleType() == QCPAxis::stLinear) { + newRange.lower = center - valueAxis->range().size() / 2.0; + newRange.upper = center + valueAxis->range().size() / 2.0; + } else { // scaleType() == stLogarithmic + newRange.lower = center / qSqrt(valueAxis->range().upper / valueAxis->range().lower); + newRange.upper = center * qSqrt(valueAxis->range().upper / valueAxis->range().lower); + } + } + valueAxis->setRange(newRange); } - valueAxis->setRange(newRange); - } } /*! \overload @@ -11093,23 +11167,21 @@ void QCPAbstractPlottable::rescaleValueAxis(bool onlyEnlarge, bool inKeyRange) c */ bool QCPAbstractPlottable::addToLegend(QCPLegend *legend) { - if (!legend) - { - qDebug() << Q_FUNC_INFO << "passed legend is null"; - return false; - } - if (legend->parentPlot() != mParentPlot) - { - qDebug() << Q_FUNC_INFO << "passed legend isn't in the same QCustomPlot as this plottable"; - return false; - } - - if (!legend->hasItemWithPlottable(this)) - { - legend->addItem(new QCPPlottableLegendItem(legend, this)); - return true; - } else - return false; + if (!legend) { + qDebug() << Q_FUNC_INFO << "passed legend is null"; + return false; + } + if (legend->parentPlot() != mParentPlot) { + qDebug() << Q_FUNC_INFO << "passed legend isn't in the same QCustomPlot as this plottable"; + return false; + } + + if (!legend->hasItemWithPlottable(this)) { + legend->addItem(new QCPPlottableLegendItem(legend, this)); + return true; + } else { + return false; + } } /*! \overload @@ -11120,10 +11192,11 @@ bool QCPAbstractPlottable::addToLegend(QCPLegend *legend) */ bool QCPAbstractPlottable::addToLegend() { - if (!mParentPlot || !mParentPlot->legend) - return false; - else - return addToLegend(mParentPlot->legend); + if (!mParentPlot || !mParentPlot->legend) { + return false; + } else { + return addToLegend(mParentPlot->legend); + } } /*! \overload @@ -11138,16 +11211,16 @@ bool QCPAbstractPlottable::addToLegend() */ 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; + 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 @@ -11158,25 +11231,27 @@ bool QCPAbstractPlottable::removeFromLegend(QCPLegend *legend) const */ bool QCPAbstractPlottable::removeFromLegend() const { - if (!mParentPlot || !mParentPlot->legend) - return false; - else - return removeFromLegend(mParentPlot->legend); + if (!mParentPlot || !mParentPlot->legend) { + return false; + } else { + return removeFromLegend(mParentPlot->legend); + } } /* inherits documentation from base class */ QRect QCPAbstractPlottable::clipRect() const { - if (mKeyAxis && mValueAxis) - return mKeyAxis.data()->axisRect()->rect() & mValueAxis.data()->axisRect()->rect(); - else - return QRect(); + if (mKeyAxis && mValueAxis) { + return mKeyAxis.data()->axisRect()->rect() & mValueAxis.data()->axisRect()->rect(); + } else { + return QRect(); + } } /* inherits documentation from base class */ QCP::Interaction QCPAbstractPlottable::selectionCategory() const { - return QCP::iSelectPlottables; + return QCP::iSelectPlottables; } /*! \internal @@ -11185,93 +11260,93 @@ QCP::Interaction QCPAbstractPlottable::selectionCategory() const before drawing plottable lines. This is the antialiasing state the painter passed to the \ref draw method is in by default. - + 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. - + \seebaseclassmethod - + \see setAntialiased, applyFillAntialiasingHint, applyScattersAntialiasingHint */ void QCPAbstractPlottable::applyDefaultAntialiasingHint(QCPPainter *painter) const { - applyAntialiasingHint(painter, mAntialiased, QCP::aePlottables); + applyAntialiasingHint(painter, mAntialiased, QCP::aePlottables); } /*! \internal A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter before drawing plottable fills. - + 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, applyDefaultAntialiasingHint, applyScattersAntialiasingHint */ void QCPAbstractPlottable::applyFillAntialiasingHint(QCPPainter *painter) const { - applyAntialiasingHint(painter, mAntialiasedFill, QCP::aeFills); + applyAntialiasingHint(painter, mAntialiasedFill, QCP::aeFills); } /*! \internal A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter before drawing plottable scatter points. - + 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, applyDefaultAntialiasingHint */ void QCPAbstractPlottable::applyScattersAntialiasingHint(QCPPainter *painter) const { - applyAntialiasingHint(painter, mAntialiasedScatters, QCP::aeScatters); + applyAntialiasingHint(painter, mAntialiasedScatters, QCP::aeScatters); } /* inherits documentation from base class */ void QCPAbstractPlottable::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) { - Q_UNUSED(event) - - if (mSelectable != QCP::stNone) - { - 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 = mSelection != selectionBefore; - } + Q_UNUSED(event) + + if (mSelectable != QCP::stNone) { + 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 = mSelection != selectionBefore; + } + } } /* inherits documentation from base class */ void QCPAbstractPlottable::deselectEvent(bool *selectionStateChanged) { - if (mSelectable != QCP::stNone) - { - QCPDataSelection selectionBefore = mSelection; - setSelection(QCPDataSelection()); - if (selectionStateChanged) - *selectionStateChanged = mSelection != selectionBefore; - } + if (mSelectable != QCP::stNone) { + QCPDataSelection selectionBefore = mSelection; + setSelection(QCPDataSelection()); + if (selectionStateChanged) { + *selectionStateChanged = mSelection != selectionBefore; + } + } } /* end of 'src/plottable.cpp' */ @@ -11285,7 +11360,7 @@ void QCPAbstractPlottable::deselectEvent(bool *selectionStateChanged) /*! \class QCPItemAnchor \brief An anchor of an item to which positions can be attached to. - + An item (QCPAbstractItem) may have one or more anchors. Unlike QCPItemPosition, an anchor doesn't control anything on its item, but provides a way to tie other items via their positions to the anchor. @@ -11296,10 +11371,10 @@ void QCPAbstractPlottable::deselectEvent(bool *selectionStateChanged) calling QCPItemPosition::setParentAnchor on \a start, passing the wanted anchor of the QCPItemRect. This way the start of the line will now always follow the respective anchor location on the rect item. - + Note that QCPItemPosition derives from QCPItemAnchor, so every position can also serve as an anchor to other positions. - + To learn how to provide anchors in your own item subclasses, see the subclassing section of the QCPAbstractItem documentation. */ @@ -11307,10 +11382,10 @@ void QCPAbstractPlottable::deselectEvent(bool *selectionStateChanged) /* start documentation of inline functions */ /*! \fn virtual QCPItemPosition *QCPItemAnchor::toQCPItemPosition() - + Returns 0 if this instance is merely a QCPItemAnchor, and a valid pointer of type QCPItemPosition* if it actually is a QCPItemPosition (which is a subclass of QCPItemAnchor). - + This safe downcast functionality could also be achieved with a dynamic_cast. However, QCustomPlot avoids dynamic_cast to work with projects that don't have RTTI support enabled (e.g. -fno-rtti flag with gcc compiler). @@ -11324,51 +11399,47 @@ void QCPAbstractPlottable::deselectEvent(bool *selectionStateChanged) explained in the subclassing section of the QCPAbstractItem documentation. */ QCPItemAnchor::QCPItemAnchor(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString &name, int anchorId) : - mName(name), - mParentPlot(parentPlot), - mParentItem(parentItem), - mAnchorId(anchorId) + mName(name), + mParentPlot(parentPlot), + mParentItem(parentItem), + mAnchorId(anchorId) { } QCPItemAnchor::~QCPItemAnchor() { - // unregister as parent at children: - foreach (QCPItemPosition *child, mChildrenX.toList()) - { - if (child->parentAnchorX() == this) - child->setParentAnchorX(0); // this acts back on this anchor and child removes itself from mChildrenX - } - foreach (QCPItemPosition *child, mChildrenY.toList()) - { - if (child->parentAnchorY() == this) - child->setParentAnchorY(0); // this acts back on this anchor and child removes itself from mChildrenY - } + // unregister as parent at children: + foreach (QCPItemPosition *child, mChildrenX.toList()) { + if (child->parentAnchorX() == this) { + child->setParentAnchorX(0); // this acts back on this anchor and child removes itself from mChildrenX + } + } + foreach (QCPItemPosition *child, mChildrenY.toList()) { + if (child->parentAnchorY() == this) { + child->setParentAnchorY(0); // this acts back on this anchor and child removes itself from mChildrenY + } + } } /*! Returns the final absolute pixel position of the QCPItemAnchor on the QCustomPlot surface. - + The pixel information is internally retrieved via QCPAbstractItem::anchorPixelPosition of the parent item, QCPItemAnchor is just an intermediary. */ QPointF QCPItemAnchor::pixelPosition() const { - if (mParentItem) - { - if (mAnchorId > -1) - { - return mParentItem->anchorPixelPosition(mAnchorId); - } else - { - qDebug() << Q_FUNC_INFO << "no valid anchor id set:" << mAnchorId; - return QPointF(); + if (mParentItem) { + if (mAnchorId > -1) { + return mParentItem->anchorPixelPosition(mAnchorId); + } else { + qDebug() << Q_FUNC_INFO << "no valid anchor id set:" << mAnchorId; + return QPointF(); + } + } else { + qDebug() << Q_FUNC_INFO << "no parent item set"; + return QPointF(); } - } else - { - qDebug() << Q_FUNC_INFO << "no parent item set"; - return QPointF(); - } } /*! \internal @@ -11376,27 +11447,29 @@ QPointF QCPItemAnchor::pixelPosition() const Adds \a pos to the childX list of this anchor, which keeps track of which children use this anchor as parent anchor for the respective coordinate. This is necessary to notify the children prior to destruction of the anchor. - + Note that this function does not change the parent setting in \a pos. */ void QCPItemAnchor::addChildX(QCPItemPosition *pos) { - if (!mChildrenX.contains(pos)) - mChildrenX.insert(pos); - else - qDebug() << Q_FUNC_INFO << "provided pos is child already" << reinterpret_cast(pos); + if (!mChildrenX.contains(pos)) { + mChildrenX.insert(pos); + } else { + qDebug() << Q_FUNC_INFO << "provided pos is child already" << reinterpret_cast(pos); + } } /*! \internal Removes \a pos from the childX list of this anchor. - + Note that this function does not change the parent setting in \a pos. */ void QCPItemAnchor::removeChildX(QCPItemPosition *pos) { - if (!mChildrenX.remove(pos)) - qDebug() << Q_FUNC_INFO << "provided pos isn't child" << reinterpret_cast(pos); + if (!mChildrenX.remove(pos)) { + qDebug() << Q_FUNC_INFO << "provided pos isn't child" << reinterpret_cast(pos); + } } /*! \internal @@ -11404,27 +11477,29 @@ void QCPItemAnchor::removeChildX(QCPItemPosition *pos) Adds \a pos to the childY list of this anchor, which keeps track of which children use this anchor as parent anchor for the respective coordinate. This is necessary to notify the children prior to destruction of the anchor. - + Note that this function does not change the parent setting in \a pos. */ void QCPItemAnchor::addChildY(QCPItemPosition *pos) { - if (!mChildrenY.contains(pos)) - mChildrenY.insert(pos); - else - qDebug() << Q_FUNC_INFO << "provided pos is child already" << reinterpret_cast(pos); + if (!mChildrenY.contains(pos)) { + mChildrenY.insert(pos); + } else { + qDebug() << Q_FUNC_INFO << "provided pos is child already" << reinterpret_cast(pos); + } } /*! \internal Removes \a pos from the childY list of this anchor. - + Note that this function does not change the parent setting in \a pos. */ void QCPItemAnchor::removeChildY(QCPItemPosition *pos) { - if (!mChildrenY.remove(pos)) - qDebug() << Q_FUNC_INFO << "provided pos isn't child" << reinterpret_cast(pos); + if (!mChildrenY.remove(pos)) { + qDebug() << Q_FUNC_INFO << "provided pos isn't child" << reinterpret_cast(pos); + } } @@ -11434,7 +11509,7 @@ void QCPItemAnchor::removeChildY(QCPItemPosition *pos) /*! \class QCPItemPosition \brief Manages the position of an item. - + Every item has at least one public QCPItemPosition member pointer which provides ways to position the item on the QCustomPlot surface. Some items have multiple positions, for example QCPItemRect has two: \a topLeft and \a bottomRight. @@ -11469,23 +11544,23 @@ void QCPItemAnchor::removeChildY(QCPItemPosition *pos) /* start documentation of inline functions */ /*! \fn QCPItemPosition::PositionType *QCPItemPosition::type() const - + Returns the current position type. - + If different types were set for X and Y (\ref setTypeX, \ref setTypeY), this method returns the type of the X coordinate. In that case rather use \a typeX() and \a typeY(). - + \see setType */ /*! \fn QCPItemAnchor *QCPItemPosition::parentAnchor() const - + Returns the current parent anchor. - + If different parent anchors were set for X and Y (\ref setParentAnchorX, \ref setParentAnchorY), this method returns the parent anchor of the Y coordinate. In that case rather use \a parentAnchorX() and \a parentAnchorY(). - + \see setParentAnchor */ @@ -11497,133 +11572,141 @@ void QCPItemAnchor::removeChildY(QCPItemPosition *pos) explained in the subclassing section of the QCPAbstractItem documentation. */ QCPItemPosition::QCPItemPosition(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString &name) : - QCPItemAnchor(parentPlot, parentItem, name), - mPositionTypeX(ptAbsolute), - mPositionTypeY(ptAbsolute), - mKey(0), - mValue(0), - mParentAnchorX(0), - mParentAnchorY(0) + QCPItemAnchor(parentPlot, parentItem, name), + mPositionTypeX(ptAbsolute), + mPositionTypeY(ptAbsolute), + mKey(0), + mValue(0), + mParentAnchorX(0), + mParentAnchorY(0) { } 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::pixelPosition function instead of QCPItemAnchor::pixelPosition - foreach (QCPItemPosition *child, mChildrenX.toList()) - { - if (child->parentAnchorX() == this) - child->setParentAnchorX(0); // this acts back on this anchor and child removes itself from mChildrenX - } - foreach (QCPItemPosition *child, mChildrenY.toList()) - { - if (child->parentAnchorY() == this) - child->setParentAnchorY(0); // this acts back on this anchor and child removes itself from mChildrenY - } - // unregister as child in parent: - if (mParentAnchorX) - mParentAnchorX->removeChildX(this); - if (mParentAnchorY) - mParentAnchorY->removeChildY(this); + // 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::pixelPosition function instead of QCPItemAnchor::pixelPosition + foreach (QCPItemPosition *child, mChildrenX.toList()) { + if (child->parentAnchorX() == this) { + child->setParentAnchorX(0); // this acts back on this anchor and child removes itself from mChildrenX + } + } + foreach (QCPItemPosition *child, mChildrenY.toList()) { + if (child->parentAnchorY() == this) { + child->setParentAnchorY(0); // this acts back on this anchor and child removes itself from mChildrenY + } + } + // unregister as child in parent: + if (mParentAnchorX) { + mParentAnchorX->removeChildX(this); + } + if (mParentAnchorY) { + mParentAnchorY->removeChildY(this); + } } /* can't make this a header inline function, because QPointer breaks with forward declared types, see QTBUG-29588 */ QCPAxisRect *QCPItemPosition::axisRect() const { - return mAxisRect.data(); + return mAxisRect.data(); } /*! Sets the type of the position. The type defines how the coordinates passed to \ref setCoords should be handled and how the QCPItemPosition should behave in the plot. - + The possible values for \a type can be separated in two main categories: \li The position is regarded as a point in plot coordinates. This corresponds to \ref ptPlotCoords and requires two axes that define the plot coordinate system. They can be specified with \ref setAxes. By default, the QCustomPlot's x- and yAxis are used. - + \li The position is fixed on the QCustomPlot surface, i.e. independent of axis ranges. This corresponds to all other types, i.e. \ref ptAbsolute, \ref ptViewportRatio and \ref ptAxisRectRatio. They differ only in the way the absolute position is described, see the documentation of \ref PositionType for details. For \ref ptAxisRectRatio, note that you can specify the axis rect with \ref setAxisRect. By default this is set to the main axis rect. - + Note that the position type \ref ptPlotCoords is only available (and sensible) when the position has no parent anchor (\ref setParentAnchor). - + If the type is changed, the apparent pixel position on the plot is preserved. This means the coordinates as retrieved with coords() and set with \ref setCoords may change in the process. - + This method sets the type for both X and Y directions. It is also possible to set different types for X and Y, see \ref setTypeX, \ref setTypeY. */ void QCPItemPosition::setType(QCPItemPosition::PositionType type) { - setTypeX(type); - setTypeY(type); + setTypeX(type); + setTypeY(type); } /*! This method sets the position type of the X coordinate to \a type. - + For a detailed description of what a position type is, see the documentation of \ref setType. - + \see setType, setTypeY */ 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 pixelPosition() because it would output a qDebug warning. - bool retainPixelPosition = true; - if ((mPositionTypeX == ptPlotCoords || type == ptPlotCoords) && (!mKeyAxis || !mValueAxis)) - retainPixelPosition = false; - if ((mPositionTypeX == ptAxisRectRatio || type == ptAxisRectRatio) && (!mAxisRect)) - retainPixelPosition = false; - - QPointF pixel; - if (retainPixelPosition) - pixel = pixelPosition(); - - mPositionTypeX = type; - - if (retainPixelPosition) - setPixelPosition(pixel); - } + 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 pixelPosition() because it would output a qDebug warning. + bool retainPixelPosition = true; + if ((mPositionTypeX == ptPlotCoords || type == ptPlotCoords) && (!mKeyAxis || !mValueAxis)) { + retainPixelPosition = false; + } + if ((mPositionTypeX == ptAxisRectRatio || type == ptAxisRectRatio) && (!mAxisRect)) { + retainPixelPosition = false; + } + + QPointF pixel; + if (retainPixelPosition) { + pixel = pixelPosition(); + } + + mPositionTypeX = type; + + if (retainPixelPosition) { + setPixelPosition(pixel); + } + } } /*! This method sets the position type of the Y coordinate to \a type. - + For a detailed description of what a position type is, see the documentation of \ref setType. - + \see setType, setTypeX */ 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 pixelPosition() because it would output a qDebug warning. - bool retainPixelPosition = true; - if ((mPositionTypeY == ptPlotCoords || type == ptPlotCoords) && (!mKeyAxis || !mValueAxis)) - retainPixelPosition = false; - if ((mPositionTypeY == ptAxisRectRatio || type == ptAxisRectRatio) && (!mAxisRect)) - retainPixelPosition = false; - - QPointF pixel; - if (retainPixelPosition) - pixel = pixelPosition(); - - mPositionTypeY = type; - - if (retainPixelPosition) - setPixelPosition(pixel); - } + 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 pixelPosition() because it would output a qDebug warning. + bool retainPixelPosition = true; + if ((mPositionTypeY == ptPlotCoords || type == ptPlotCoords) && (!mKeyAxis || !mValueAxis)) { + retainPixelPosition = false; + } + if ((mPositionTypeY == ptAxisRectRatio || type == ptAxisRectRatio) && (!mAxisRect)) { + retainPixelPosition = false; + } + + QPointF pixel; + if (retainPixelPosition) { + pixel = pixelPosition(); + } + + mPositionTypeY = type; + + if (retainPixelPosition) { + setPixelPosition(pixel); + } + } } /*! @@ -11631,167 +11714,165 @@ void QCPItemPosition::setTypeY(QCPItemPosition::PositionType type) follow any position changes of the anchor. The local coordinate system of positions with a parent anchor always is absolute pixels, with (0, 0) being exactly on top of the parent anchor. (Hence the type shouldn't be set to \ref ptPlotCoords for positions with parent anchors.) - + if \a keepPixelPosition is true, the current pixel position of the QCPItemPosition is preserved during reparenting. If it's set to false, the coordinates are set to (0, 0), i.e. the position will be exactly on top of the parent anchor. - + To remove this QCPItemPosition from any parent anchor, set \a parentAnchor to 0. - + If the QCPItemPosition previously had no parent and the type is \ref ptPlotCoords, the type is set to \ref ptAbsolute, to keep the position in a valid state. - + This method sets the parent anchor for both X and Y directions. It is also possible to set different parents for X and Y, see \ref setParentAnchorX, \ref setParentAnchorY. */ bool QCPItemPosition::setParentAnchor(QCPItemAnchor *parentAnchor, bool keepPixelPosition) { - bool successX = setParentAnchorX(parentAnchor, keepPixelPosition); - bool successY = setParentAnchorY(parentAnchor, keepPixelPosition); - return successX && successY; + bool successX = setParentAnchorX(parentAnchor, keepPixelPosition); + bool successY = setParentAnchorY(parentAnchor, keepPixelPosition); + return successX && successY; } /*! This method sets the parent anchor of the X coordinate to \a parentAnchor. - + For a detailed description of what a parent anchor is, see the documentation of \ref setParentAnchor. - + \see setParentAnchor, setParentAnchorY */ bool QCPItemPosition::setParentAnchorX(QCPItemAnchor *parentAnchor, bool keepPixelPosition) { - // make sure self is not assigned as parent: - if (parentAnchor == this) - { - qDebug() << Q_FUNC_INFO << "can't set self as parent anchor" << reinterpret_cast(parentAnchor); - return false; - } - // make sure no recursive parent-child-relationships are created: - QCPItemAnchor *currentParent = parentAnchor; - while (currentParent) - { - if (QCPItemPosition *currentParentPos = currentParent->toQCPItemPosition()) - { - // is a QCPItemPosition, might have further parent, so keep iterating - if (currentParentPos == this) - { - qDebug() << Q_FUNC_INFO << "can't create recursive parent-child-relationship" << reinterpret_cast(parentAnchor); + // make sure self is not assigned as parent: + if (parentAnchor == this) { + qDebug() << Q_FUNC_INFO << "can't set self as parent anchor" << reinterpret_cast(parentAnchor); return false; - } - currentParent = currentParentPos->parentAnchorX(); - } else - { - // is a QCPItemAnchor, can't have further parent. Now make sure the parent items aren't the - // same, to prevent a position being child of an anchor which itself depends on the position, - // because they're both on the same item: - if (currentParent->mParentItem == mParentItem) - { - qDebug() << Q_FUNC_INFO << "can't set parent to be an anchor which itself depends on this position" << reinterpret_cast(parentAnchor); - return false; - } - break; } - } - - // if previously no parent set and PosType is still ptPlotCoords, set to ptAbsolute: - if (!mParentAnchorX && mPositionTypeX == ptPlotCoords) - setTypeX(ptAbsolute); - - // save pixel position: - QPointF pixelP; - if (keepPixelPosition) - pixelP = pixelPosition(); - // unregister at current parent anchor: - if (mParentAnchorX) - mParentAnchorX->removeChildX(this); - // register at new parent anchor: - if (parentAnchor) - parentAnchor->addChildX(this); - mParentAnchorX = parentAnchor; - // restore pixel position under new parent: - if (keepPixelPosition) - setPixelPosition(pixelP); - else - setCoords(0, coords().y()); - return true; + // make sure no recursive parent-child-relationships are created: + QCPItemAnchor *currentParent = parentAnchor; + while (currentParent) { + if (QCPItemPosition *currentParentPos = currentParent->toQCPItemPosition()) { + // is a QCPItemPosition, might have further parent, so keep iterating + if (currentParentPos == this) { + qDebug() << Q_FUNC_INFO << "can't create recursive parent-child-relationship" << reinterpret_cast(parentAnchor); + return false; + } + currentParent = currentParentPos->parentAnchorX(); + } else { + // is a QCPItemAnchor, can't have further parent. Now make sure the parent items aren't the + // same, to prevent a position being child of an anchor which itself depends on the position, + // because they're both on the same item: + if (currentParent->mParentItem == mParentItem) { + qDebug() << Q_FUNC_INFO << "can't set parent to be an anchor which itself depends on this position" << reinterpret_cast(parentAnchor); + return false; + } + break; + } + } + + // if previously no parent set and PosType is still ptPlotCoords, set to ptAbsolute: + if (!mParentAnchorX && mPositionTypeX == ptPlotCoords) { + setTypeX(ptAbsolute); + } + + // save pixel position: + QPointF pixelP; + if (keepPixelPosition) { + pixelP = pixelPosition(); + } + // unregister at current parent anchor: + if (mParentAnchorX) { + mParentAnchorX->removeChildX(this); + } + // register at new parent anchor: + if (parentAnchor) { + parentAnchor->addChildX(this); + } + mParentAnchorX = parentAnchor; + // restore pixel position under new parent: + if (keepPixelPosition) { + setPixelPosition(pixelP); + } else { + setCoords(0, coords().y()); + } + return true; } /*! This method sets the parent anchor of the Y coordinate to \a parentAnchor. - + For a detailed description of what a parent anchor is, see the documentation of \ref setParentAnchor. - + \see setParentAnchor, setParentAnchorX */ bool QCPItemPosition::setParentAnchorY(QCPItemAnchor *parentAnchor, bool keepPixelPosition) { - // make sure self is not assigned as parent: - if (parentAnchor == this) - { - qDebug() << Q_FUNC_INFO << "can't set self as parent anchor" << reinterpret_cast(parentAnchor); - return false; - } - // make sure no recursive parent-child-relationships are created: - QCPItemAnchor *currentParent = parentAnchor; - while (currentParent) - { - if (QCPItemPosition *currentParentPos = currentParent->toQCPItemPosition()) - { - // is a QCPItemPosition, might have further parent, so keep iterating - if (currentParentPos == this) - { - qDebug() << Q_FUNC_INFO << "can't create recursive parent-child-relationship" << reinterpret_cast(parentAnchor); + // make sure self is not assigned as parent: + if (parentAnchor == this) { + qDebug() << Q_FUNC_INFO << "can't set self as parent anchor" << reinterpret_cast(parentAnchor); return false; - } - currentParent = currentParentPos->parentAnchorY(); - } else - { - // is a QCPItemAnchor, can't have further parent. Now make sure the parent items aren't the - // same, to prevent a position being child of an anchor which itself depends on the position, - // because they're both on the same item: - if (currentParent->mParentItem == mParentItem) - { - qDebug() << Q_FUNC_INFO << "can't set parent to be an anchor which itself depends on this position" << reinterpret_cast(parentAnchor); - return false; - } - break; } - } - - // if previously no parent set and PosType is still ptPlotCoords, set to ptAbsolute: - if (!mParentAnchorY && mPositionTypeY == ptPlotCoords) - setTypeY(ptAbsolute); - - // save pixel position: - QPointF pixelP; - if (keepPixelPosition) - pixelP = pixelPosition(); - // unregister at current parent anchor: - if (mParentAnchorY) - mParentAnchorY->removeChildY(this); - // register at new parent anchor: - if (parentAnchor) - parentAnchor->addChildY(this); - mParentAnchorY = parentAnchor; - // restore pixel position under new parent: - if (keepPixelPosition) - setPixelPosition(pixelP); - else - setCoords(coords().x(), 0); - return true; + // make sure no recursive parent-child-relationships are created: + QCPItemAnchor *currentParent = parentAnchor; + while (currentParent) { + if (QCPItemPosition *currentParentPos = currentParent->toQCPItemPosition()) { + // is a QCPItemPosition, might have further parent, so keep iterating + if (currentParentPos == this) { + qDebug() << Q_FUNC_INFO << "can't create recursive parent-child-relationship" << reinterpret_cast(parentAnchor); + return false; + } + currentParent = currentParentPos->parentAnchorY(); + } else { + // is a QCPItemAnchor, can't have further parent. Now make sure the parent items aren't the + // same, to prevent a position being child of an anchor which itself depends on the position, + // because they're both on the same item: + if (currentParent->mParentItem == mParentItem) { + qDebug() << Q_FUNC_INFO << "can't set parent to be an anchor which itself depends on this position" << reinterpret_cast(parentAnchor); + return false; + } + break; + } + } + + // if previously no parent set and PosType is still ptPlotCoords, set to ptAbsolute: + if (!mParentAnchorY && mPositionTypeY == ptPlotCoords) { + setTypeY(ptAbsolute); + } + + // save pixel position: + QPointF pixelP; + if (keepPixelPosition) { + pixelP = pixelPosition(); + } + // unregister at current parent anchor: + if (mParentAnchorY) { + mParentAnchorY->removeChildY(this); + } + // register at new parent anchor: + if (parentAnchor) { + parentAnchor->addChildY(this); + } + mParentAnchorY = parentAnchor; + // restore pixel position under new parent: + if (keepPixelPosition) { + setPixelPosition(pixelP); + } else { + setCoords(coords().x(), 0); + } + return true; } /*! Sets the coordinates of this QCPItemPosition. What the coordinates mean, is defined by the type (\ref setType, \ref setTypeX, \ref setTypeY). - + For example, if the type is \ref ptAbsolute, \a key and \a value mean the x and y pixel position on the QCustomPlot surface. In that case the origin (0, 0) is in the top left corner of the QCustomPlot viewport. If the type is \ref ptPlotCoords, \a key and \a value mean a point in the plot coordinate system defined by the axes set by \ref setAxes. By default those are the QCustomPlot's xAxis and yAxis. See the documentation of \ref setType for other available coordinate types and their meaning. - + If different types were configured for X and Y (\ref setTypeX, \ref setTypeY), \a key and \a 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. @@ -11800,8 +11881,8 @@ bool QCPItemPosition::setParentAnchorY(QCPItemAnchor *parentAnchor, bool keepPix */ void QCPItemPosition::setCoords(double key, double value) { - mKey = key; - mValue = value; + mKey = key; + mValue = value; } /*! \overload @@ -11811,7 +11892,7 @@ void QCPItemPosition::setCoords(double key, double value) */ void QCPItemPosition::setCoords(const QPointF &pos) { - setCoords(pos.x(), pos.y()); + setCoords(pos.x(), pos.y()); } /*! @@ -11822,97 +11903,95 @@ void QCPItemPosition::setCoords(const QPointF &pos) */ QPointF QCPItemPosition::pixelPosition() const { - QPointF result; - - // determine X: - switch (mPositionTypeX) - { - case ptAbsolute: - { - result.rx() = mKey; - if (mParentAnchorX) - result.rx() += mParentAnchorX->pixelPosition().x(); - break; + QPointF result; + + // determine X: + switch (mPositionTypeX) { + case ptAbsolute: { + result.rx() = mKey; + if (mParentAnchorX) { + result.rx() += mParentAnchorX->pixelPosition().x(); + } + break; + } + case ptViewportRatio: { + result.rx() = mKey * mParentPlot->viewport().width(); + if (mParentAnchorX) { + result.rx() += mParentAnchorX->pixelPosition().x(); + } else { + result.rx() += mParentPlot->viewport().left(); + } + break; + } + case ptAxisRectRatio: { + if (mAxisRect) { + result.rx() = mKey * mAxisRect.data()->width(); + if (mParentAnchorX) { + result.rx() += mParentAnchorX->pixelPosition().x(); + } else { + result.rx() += mAxisRect.data()->left(); + } + } else { + qDebug() << Q_FUNC_INFO << "Item position type x is ptAxisRectRatio, but no axis rect was defined"; + } + break; + } + case ptPlotCoords: { + if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Horizontal) { + result.rx() = mKeyAxis.data()->coordToPixel(mKey); + } else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Horizontal) { + result.rx() = mValueAxis.data()->coordToPixel(mValue); + } else { + qDebug() << Q_FUNC_INFO << "Item position type x is ptPlotCoords, but no axes were defined"; + } + break; + } } - case ptViewportRatio: - { - result.rx() = mKey*mParentPlot->viewport().width(); - if (mParentAnchorX) - result.rx() += mParentAnchorX->pixelPosition().x(); - else - result.rx() += mParentPlot->viewport().left(); - break; + + // determine Y: + switch (mPositionTypeY) { + case ptAbsolute: { + result.ry() = mValue; + if (mParentAnchorY) { + result.ry() += mParentAnchorY->pixelPosition().y(); + } + break; + } + case ptViewportRatio: { + result.ry() = mValue * mParentPlot->viewport().height(); + if (mParentAnchorY) { + result.ry() += mParentAnchorY->pixelPosition().y(); + } else { + result.ry() += mParentPlot->viewport().top(); + } + break; + } + case ptAxisRectRatio: { + if (mAxisRect) { + result.ry() = mValue * mAxisRect.data()->height(); + if (mParentAnchorY) { + result.ry() += mParentAnchorY->pixelPosition().y(); + } else { + result.ry() += mAxisRect.data()->top(); + } + } else { + qDebug() << Q_FUNC_INFO << "Item position type y is ptAxisRectRatio, but no axis rect was defined"; + } + break; + } + case ptPlotCoords: { + if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Vertical) { + result.ry() = mKeyAxis.data()->coordToPixel(mKey); + } else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Vertical) { + result.ry() = mValueAxis.data()->coordToPixel(mValue); + } else { + qDebug() << Q_FUNC_INFO << "Item position type y is ptPlotCoords, but no axes were defined"; + } + break; + } } - case ptAxisRectRatio: - { - if (mAxisRect) - { - result.rx() = mKey*mAxisRect.data()->width(); - if (mParentAnchorX) - result.rx() += mParentAnchorX->pixelPosition().x(); - else - result.rx() += mAxisRect.data()->left(); - } else - qDebug() << Q_FUNC_INFO << "Item position type x is ptAxisRectRatio, but no axis rect was defined"; - break; - } - case ptPlotCoords: - { - if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Horizontal) - result.rx() = mKeyAxis.data()->coordToPixel(mKey); - else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Horizontal) - result.rx() = mValueAxis.data()->coordToPixel(mValue); - else - qDebug() << Q_FUNC_INFO << "Item position type x is ptPlotCoords, but no axes were defined"; - break; - } - } - - // determine Y: - switch (mPositionTypeY) - { - case ptAbsolute: - { - result.ry() = mValue; - if (mParentAnchorY) - result.ry() += mParentAnchorY->pixelPosition().y(); - break; - } - case ptViewportRatio: - { - result.ry() = mValue*mParentPlot->viewport().height(); - if (mParentAnchorY) - result.ry() += mParentAnchorY->pixelPosition().y(); - else - result.ry() += mParentPlot->viewport().top(); - break; - } - case ptAxisRectRatio: - { - if (mAxisRect) - { - result.ry() = mValue*mAxisRect.data()->height(); - if (mParentAnchorY) - result.ry() += mParentAnchorY->pixelPosition().y(); - else - result.ry() += mAxisRect.data()->top(); - } else - qDebug() << Q_FUNC_INFO << "Item position type y is ptAxisRectRatio, but no axis rect was defined"; - break; - } - case ptPlotCoords: - { - if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Vertical) - result.ry() = mKeyAxis.data()->coordToPixel(mKey); - else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Vertical) - result.ry() = mValueAxis.data()->coordToPixel(mValue); - else - qDebug() << Q_FUNC_INFO << "Item position type y is ptPlotCoords, but no axes were defined"; - break; - } - } - - return result; + + return result; } /*! @@ -11922,8 +12001,8 @@ QPointF QCPItemPosition::pixelPosition() const */ void QCPItemPosition::setAxes(QCPAxis *keyAxis, QCPAxis *valueAxis) { - mKeyAxis = keyAxis; - mValueAxis = valueAxis; + mKeyAxis = keyAxis; + mValueAxis = valueAxis; } /*! @@ -11933,7 +12012,7 @@ void QCPItemPosition::setAxes(QCPAxis *keyAxis, QCPAxis *valueAxis) */ void QCPItemPosition::setAxisRect(QCPAxisRect *axisRect) { - mAxisRect = axisRect; + mAxisRect = axisRect; } /*! @@ -11948,94 +12027,92 @@ void QCPItemPosition::setAxisRect(QCPAxisRect *axisRect) */ void QCPItemPosition::setPixelPosition(const QPointF &pixelPosition) { - double x = pixelPosition.x(); - double y = pixelPosition.y(); - - switch (mPositionTypeX) - { - case ptAbsolute: - { - if (mParentAnchorX) - x -= mParentAnchorX->pixelPosition().x(); - break; + double x = pixelPosition.x(); + double y = pixelPosition.y(); + + switch (mPositionTypeX) { + case ptAbsolute: { + if (mParentAnchorX) { + x -= mParentAnchorX->pixelPosition().x(); + } + break; + } + case ptViewportRatio: { + if (mParentAnchorX) { + x -= mParentAnchorX->pixelPosition().x(); + } else { + x -= mParentPlot->viewport().left(); + } + x /= (double)mParentPlot->viewport().width(); + break; + } + case ptAxisRectRatio: { + if (mAxisRect) { + if (mParentAnchorX) { + x -= mParentAnchorX->pixelPosition().x(); + } else { + x -= mAxisRect.data()->left(); + } + x /= (double)mAxisRect.data()->width(); + } else { + qDebug() << Q_FUNC_INFO << "Item position type x is ptAxisRectRatio, but no axis rect was defined"; + } + break; + } + case ptPlotCoords: { + if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Horizontal) { + x = mKeyAxis.data()->pixelToCoord(x); + } else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Horizontal) { + y = mValueAxis.data()->pixelToCoord(x); + } else { + qDebug() << Q_FUNC_INFO << "Item position type x is ptPlotCoords, but no axes were defined"; + } + break; + } } - case ptViewportRatio: - { - if (mParentAnchorX) - x -= mParentAnchorX->pixelPosition().x(); - else - x -= mParentPlot->viewport().left(); - x /= (double)mParentPlot->viewport().width(); - break; + + switch (mPositionTypeY) { + case ptAbsolute: { + if (mParentAnchorY) { + y -= mParentAnchorY->pixelPosition().y(); + } + break; + } + case ptViewportRatio: { + if (mParentAnchorY) { + y -= mParentAnchorY->pixelPosition().y(); + } else { + y -= mParentPlot->viewport().top(); + } + y /= (double)mParentPlot->viewport().height(); + break; + } + case ptAxisRectRatio: { + if (mAxisRect) { + if (mParentAnchorY) { + y -= mParentAnchorY->pixelPosition().y(); + } else { + y -= mAxisRect.data()->top(); + } + y /= (double)mAxisRect.data()->height(); + } else { + qDebug() << Q_FUNC_INFO << "Item position type y is ptAxisRectRatio, but no axis rect was defined"; + } + break; + } + case ptPlotCoords: { + if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Vertical) { + x = mKeyAxis.data()->pixelToCoord(y); + } else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Vertical) { + y = mValueAxis.data()->pixelToCoord(y); + } else { + qDebug() << Q_FUNC_INFO << "Item position type y is ptPlotCoords, but no axes were defined"; + } + break; + } } - case ptAxisRectRatio: - { - if (mAxisRect) - { - if (mParentAnchorX) - x -= mParentAnchorX->pixelPosition().x(); - else - x -= mAxisRect.data()->left(); - x /= (double)mAxisRect.data()->width(); - } else - qDebug() << Q_FUNC_INFO << "Item position type x is ptAxisRectRatio, but no axis rect was defined"; - break; - } - case ptPlotCoords: - { - if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Horizontal) - x = mKeyAxis.data()->pixelToCoord(x); - else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Horizontal) - y = mValueAxis.data()->pixelToCoord(x); - else - qDebug() << Q_FUNC_INFO << "Item position type x is ptPlotCoords, but no axes were defined"; - break; - } - } - - switch (mPositionTypeY) - { - case ptAbsolute: - { - if (mParentAnchorY) - y -= mParentAnchorY->pixelPosition().y(); - break; - } - case ptViewportRatio: - { - if (mParentAnchorY) - y -= mParentAnchorY->pixelPosition().y(); - else - y -= mParentPlot->viewport().top(); - y /= (double)mParentPlot->viewport().height(); - break; - } - case ptAxisRectRatio: - { - if (mAxisRect) - { - if (mParentAnchorY) - y -= mParentAnchorY->pixelPosition().y(); - else - y -= mAxisRect.data()->top(); - y /= (double)mAxisRect.data()->height(); - } else - qDebug() << Q_FUNC_INFO << "Item position type y is ptAxisRectRatio, but no axis rect was defined"; - break; - } - case ptPlotCoords: - { - if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Vertical) - x = mKeyAxis.data()->pixelToCoord(y); - else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Vertical) - y = mValueAxis.data()->pixelToCoord(y); - else - qDebug() << Q_FUNC_INFO << "Item position type y is ptPlotCoords, but no axes were defined"; - break; - } - } - - setCoords(x, y); + + setCoords(x, y); } @@ -12045,18 +12122,18 @@ void QCPItemPosition::setPixelPosition(const QPointF &pixelPosition) /*! \class QCPAbstractItem \brief The abstract base class for all items in a plot. - + In QCustomPlot, items are supplemental graphical elements that are neither plottables (QCPAbstractPlottable) nor axes (QCPAxis). While plottables are always tied to two axes and thus plot coordinates, items can also be placed in absolute coordinates independent of any axes. Each specific item has at least one QCPItemPosition member which controls the positioning. Some items are defined by more than one coordinate and thus have two or more QCPItemPosition members (For example, QCPItemRect has \a topLeft and \a bottomRight). - + This abstract base class defines a very basic interface like visibility and clipping. Since this class is abstract, it can't be instantiated. Use one of the subclasses or create a subclass yourself to create new items. - + The built-in items are:
@@ -12069,7 +12146,7 @@ void QCPItemPosition::setPixelPosition(const QPointF &pixelPosition)
QCPItemLineA line defined by a start and an end point. May have different ending styles on each side (e.g. arrows).
QCPItemBracketA bracket which may be used to reference/highlight certain parts in the plot.
QCPItemTracerAn item that can be attached to a QCPGraph and sticks to its data points, given a key coordinate.
- + \section items-clipping Clipping Items are by default clipped to the main axis rect (they are only visible inside the axis rect). @@ -12081,9 +12158,9 @@ void QCPItemPosition::setPixelPosition(const QPointF &pixelPosition) in principle is independent of the coordinate axes the item might be tied to via its position members (\ref QCPItemPosition::setAxes). However, it is common that the axis rect for clipping also contains the axes used for the item positions. - + \section items-using Using items - + First you instantiate the item you want to use and add it to the plot: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-1 by default, the positions of the item are bound to the x- and y-Axis of the plot. So we can just @@ -12096,35 +12173,35 @@ void QCPItemPosition::setPixelPosition(const QPointF &pixelPosition) \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-4 and make the line visible on the entire QCustomPlot, by disabling clipping to the axis rect: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-5 - + For more advanced plots, it is even possible to set different types and parent anchors per X/Y coordinate of an item position, using for example \ref QCPItemPosition::setTypeX or \ref QCPItemPosition::setParentAnchorX. For details, see the documentation of \ref QCPItemPosition. - + \section items-subclassing Creating own items - + To create an own item, you implement a subclass of QCPAbstractItem. These are the pure virtual functions, you must implement: \li \ref selectTest \li \ref draw - + See the documentation of those functions for what they need to do. - + \subsection items-positioning Allowing the item to be positioned - + As mentioned, item positions are represented by QCPItemPosition members. Let's assume the new item shall have only one point as its position (as opposed to two like a rect or multiple like a polygon). You then add a public member of type QCPItemPosition like so: - + \code QCPItemPosition * const myPosition;\endcode - + the const makes sure the pointer itself can't be modified from the user of your new item (the QCPItemPosition instance it points to, can be modified, of course). The initialization of this pointer is made easy with the \ref createPosition function. Just assign the return value of this function to each QCPItemPosition in the constructor of your item. \ref createPosition takes a string which is the name of the position, typically this is identical to the variable name. For example, the constructor of QCPItemExample could look like this: - + \code QCPItemExample::QCPItemExample(QCustomPlot *parentPlot) : QCPAbstractItem(parentPlot), @@ -12133,9 +12210,9 @@ void QCPItemPosition::setPixelPosition(const QPointF &pixelPosition) // other constructor code } \endcode - + \subsection items-drawing The draw function - + 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::pixelPosition. @@ -12143,19 +12220,19 @@ void QCPItemPosition::setPixelPosition(const QPointF &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 if this is the case. - + \subsection items-selection The selectTest function - + 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 - + Providing anchors (QCPItemAnchor) starts off like adding a position. First you create a public member, e.g. - + \code QCPItemAnchor * const bottom;\endcode and create it in the constructor with the \ref createAnchor function, assigning it a name and an @@ -12163,7 +12240,7 @@ void QCPItemPosition::setPixelPosition(const QPointF &pixelPosition) 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 anchorPixelPosition(int anchorId) function. - + In essence the QCPItemAnchor is merely an intermediary that itself asks your item for the pixel position when anything attached to the anchor needs to know the coordinates. */ @@ -12171,17 +12248,17 @@ void QCPItemPosition::setPixelPosition(const QPointF &pixelPosition) /* start of documentation of inline functions */ /*! \fn QList QCPAbstractItem::positions() const - + Returns all positions of the item in a list. - + \see anchors, position */ /*! \fn QList QCPAbstractItem::anchors() const - + Returns all anchors of the item in a list. Note that since a position (QCPItemPosition) is always also an anchor, the list will also contain the positions of this item. - + \see positions, anchor */ @@ -12190,9 +12267,9 @@ void QCPItemPosition::setPixelPosition(const QPointF &pixelPosition) /*! \fn void QCPAbstractItem::draw(QCPPainter *painter) = 0 \internal - + Draws this item with the provided \a painter. - + The cliprect of the provided painter is set to the rect returned by \ref clipRect before this function is called. The clipRect depends on the clipping settings defined by \ref setClipToAxisRect and \ref setClipAxisRect. @@ -12212,75 +12289,75 @@ void QCPItemPosition::setPixelPosition(const QPointF &pixelPosition) Base class constructor which initializes base class members. */ QCPAbstractItem::QCPAbstractItem(QCustomPlot *parentPlot) : - QCPLayerable(parentPlot), - mClipToAxisRect(false), - mSelectable(true), - mSelected(false) + QCPLayerable(parentPlot), + mClipToAxisRect(false), + mSelectable(true), + mSelected(false) { - parentPlot->registerItem(this); - - QList rects = parentPlot->axisRects(); - if (rects.size() > 0) - { - setClipToAxisRect(true); - setClipAxisRect(rects.first()); - } + parentPlot->registerItem(this); + + QList rects = parentPlot->axisRects(); + if (rects.size() > 0) { + setClipToAxisRect(true); + setClipAxisRect(rects.first()); + } } QCPAbstractItem::~QCPAbstractItem() { - // don't delete mPositions because every position is also an anchor and thus in mAnchors - qDeleteAll(mAnchors); + // don't delete mPositions because every position is also an anchor and thus in mAnchors + qDeleteAll(mAnchors); } /* can't make this a header inline function, because QPointer breaks with forward declared types, see QTBUG-29588 */ QCPAxisRect *QCPAbstractItem::clipAxisRect() const { - return mClipAxisRect.data(); + return mClipAxisRect.data(); } /*! Sets whether the item shall be clipped to an axis rect or whether it shall be visible on the entire QCustomPlot. The axis rect can be set with \ref setClipAxisRect. - + \see setClipAxisRect */ void QCPAbstractItem::setClipToAxisRect(bool clip) { - mClipToAxisRect = clip; - if (mClipToAxisRect) - setParentLayerable(mClipAxisRect.data()); + mClipToAxisRect = clip; + if (mClipToAxisRect) { + setParentLayerable(mClipAxisRect.data()); + } } /*! Sets the clip axis rect. It defines the rect that will be used to clip the item when \ref setClipToAxisRect is set to true. - + \see setClipToAxisRect */ void QCPAbstractItem::setClipAxisRect(QCPAxisRect *rect) { - mClipAxisRect = rect; - if (mClipToAxisRect) - setParentLayerable(mClipAxisRect.data()); + mClipAxisRect = rect; + if (mClipToAxisRect) { + setParentLayerable(mClipAxisRect.data()); + } } /*! Sets whether the user can (de-)select this item by clicking on the QCustomPlot surface. (When \ref QCustomPlot::setInteractions contains QCustomPlot::iSelectItems.) - + However, even when \a selectable was set to false, it is possible to set the selection manually, by calling \ref setSelected. - + \see QCustomPlot::setInteractions, setSelected */ void QCPAbstractItem::setSelectable(bool selectable) { - if (mSelectable != selectable) - { - mSelectable = selectable; - emit selectableChanged(mSelectable); - } + if (mSelectable != selectable) { + mSelectable = selectable; + emit selectableChanged(mSelectable); + } } /*! @@ -12290,97 +12367,97 @@ void QCPAbstractItem::setSelectable(bool selectable) The entire selection mechanism for items is handled automatically when \ref QCustomPlot::setInteractions contains QCustomPlot::iSelectItems. You only need to call this function when you wish to change the selection state manually. - + This function can change the selection state even when \ref setSelectable was set to false. - + emits the \ref selectionChanged signal when \a selected is different from the previous selection state. - + \see setSelectable, selectTest */ void QCPAbstractItem::setSelected(bool selected) { - if (mSelected != selected) - { - mSelected = selected; - emit selectionChanged(mSelected); - } + if (mSelected != selected) { + mSelected = selected; + emit selectionChanged(mSelected); + } } /*! Returns the QCPItemPosition with the specified \a name. If this item doesn't have a position by that name, returns 0. - + This function provides an alternative way to access item positions. Normally, you access positions direcly by their member pointers (which typically have the same variable name as \a name). - + \see positions, anchor */ QCPItemPosition *QCPAbstractItem::position(const QString &name) const { - for (int i=0; iname() == name) - return mPositions.at(i); - } - qDebug() << Q_FUNC_INFO << "position with name not found:" << name; - return 0; + for (int i = 0; i < mPositions.size(); ++i) { + if (mPositions.at(i)->name() == name) { + return mPositions.at(i); + } + } + qDebug() << Q_FUNC_INFO << "position with name not found:" << name; + return 0; } /*! Returns the QCPItemAnchor with the specified \a name. If this item doesn't have an anchor by that name, returns 0. - + This function provides an alternative way to access item anchors. Normally, you access anchors direcly by their member pointers (which typically have the same variable name as \a name). - + \see anchors, position */ QCPItemAnchor *QCPAbstractItem::anchor(const QString &name) const { - for (int i=0; iname() == name) - return mAnchors.at(i); - } - qDebug() << Q_FUNC_INFO << "anchor with name not found:" << name; - return 0; + for (int i = 0; i < mAnchors.size(); ++i) { + if (mAnchors.at(i)->name() == name) { + return mAnchors.at(i); + } + } + qDebug() << Q_FUNC_INFO << "anchor with name not found:" << name; + return 0; } /*! Returns whether this item has an anchor with the specified \a name. - + Note that you can check for positions with this function, too. This is because every position is also an anchor (QCPItemPosition inherits from QCPItemAnchor). - + \see anchor, position */ bool QCPAbstractItem::hasAnchor(const QString &name) const { - for (int i=0; iname() == name) - return true; - } - return false; + for (int i = 0; i < mAnchors.size(); ++i) { + if (mAnchors.at(i)->name() == name) { + return true; + } + } + return false; } /*! \internal - + 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, QCustomPlot's viewport rect is returned. - + \see draw */ QRect QCPAbstractItem::clipRect() const { - if (mClipToAxisRect && mClipAxisRect) - return mClipAxisRect.data()->rect(); - else - return mParentPlot->viewport(); + if (mClipToAxisRect && mClipAxisRect) { + return mClipAxisRect.data()->rect(); + } else { + return mParentPlot->viewport(); + } } /*! \internal @@ -12389,16 +12466,16 @@ QRect QCPAbstractItem::clipRect() const before drawing item lines. This is the antialiasing state the painter passed to the \ref draw method is in by default. - + 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 */ void QCPAbstractItem::applyDefaultAntialiasingHint(QCPPainter *painter) const { - applyAntialiasingHint(painter, mAntialiased, QCP::aeItems); + applyAntialiasingHint(painter, mAntialiased, QCP::aeItems); } /*! \internal @@ -12406,54 +12483,54 @@ void QCPAbstractItem::applyDefaultAntialiasingHint(QCPPainter *painter) const A convenience function which returns the selectTest value for a specified \a rect and a specified click position \a pos. \a filledRect defines whether a click inside the rect should also be considered a hit or whether only the rect border is sensitive to hits. - + This function may be used to help with the implementation of the \ref selectTest function for 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 (non -1) of all four returned values. */ double QCPAbstractItem::rectDistance(const QRectF &rect, const QPointF &pos, bool filledRect) const { - double result = -1; + double result = -1; - // distance to border: - QList lines; - lines << QLineF(rect.topLeft(), rect.topRight()) << QLineF(rect.bottomLeft(), rect.bottomRight()) - << QLineF(rect.topLeft(), rect.bottomLeft()) << QLineF(rect.topRight(), rect.bottomRight()); - double minDistSqr = (std::numeric_limits::max)(); - for (int i=0; i mParentPlot->selectionTolerance()*0.99) - { - if (rect.contains(pos)) - result = mParentPlot->selectionTolerance()*0.99; - } - return result; + // distance to border: + QList lines; + lines << QLineF(rect.topLeft(), rect.topRight()) << QLineF(rect.bottomLeft(), rect.bottomRight()) + << QLineF(rect.topLeft(), rect.bottomLeft()) << QLineF(rect.topRight(), rect.bottomRight()); + double minDistSqr = (std::numeric_limits::max)(); + for (int i = 0; i < lines.size(); ++i) { + double distSqr = QCPVector2D(pos).distanceSquaredToLine(lines.at(i).p1(), lines.at(i).p2()); + if (distSqr < minDistSqr) { + minDistSqr = distSqr; + } + } + result = qSqrt(minDistSqr); + + // filled rect, allow click inside to count as hit: + if (filledRect && result > mParentPlot->selectionTolerance() * 0.99) { + if (rect.contains(pos)) { + result = mParentPlot->selectionTolerance() * 0.99; + } + } + return result; } /*! \internal Returns the pixel position of the anchor with Id \a anchorId. This function must be reimplemented in item subclasses if they want to provide anchors (QCPItemAnchor). - + For example, if the item has two anchors with id 0 and 1, this function takes one of these anchor ids and returns the respective pixel points of the specified anchor. - + \see createAnchor */ QPointF QCPAbstractItem::anchorPixelPosition(int anchorId) const { - qDebug() << Q_FUNC_INFO << "called on item which shouldn't have any anchors (this method not reimplemented). anchorId" << anchorId; - return QPointF(); + qDebug() << Q_FUNC_INFO << "called on item which shouldn't have any anchors (this method not reimplemented). anchorId" << anchorId; + return QPointF(); } /*! \internal @@ -12461,28 +12538,30 @@ QPointF QCPAbstractItem::anchorPixelPosition(int anchorId) const Creates a QCPItemPosition, registers it with this item and returns a pointer to it. The specified \a name must be a unique string that is usually identical to the variable name of the position member (This is needed to provide the name-based \ref position access to positions). - + Don't delete positions created by this function manually, as the item will take care of it. - + Use this function in the constructor (initialization list) of the specific item subclass to create each position member. Don't create QCPItemPositions with \b new yourself, because they won't be registered with the item properly. - + \see createAnchor */ QCPItemPosition *QCPAbstractItem::createPosition(const QString &name) { - if (hasAnchor(name)) - qDebug() << Q_FUNC_INFO << "anchor/position with name exists already:" << name; - QCPItemPosition *newPosition = new QCPItemPosition(mParentPlot, this, name); - mPositions.append(newPosition); - mAnchors.append(newPosition); // every position is also an anchor - newPosition->setAxes(mParentPlot->xAxis, mParentPlot->yAxis); - newPosition->setType(QCPItemPosition::ptPlotCoords); - if (mParentPlot->axisRect()) - newPosition->setAxisRect(mParentPlot->axisRect()); - newPosition->setCoords(0, 0); - return newPosition; + if (hasAnchor(name)) { + qDebug() << Q_FUNC_INFO << "anchor/position with name exists already:" << name; + } + QCPItemPosition *newPosition = new QCPItemPosition(mParentPlot, this, name); + mPositions.append(newPosition); + mAnchors.append(newPosition); // every position is also an anchor + newPosition->setAxes(mParentPlot->xAxis, mParentPlot->yAxis); + newPosition->setType(QCPItemPosition::ptPlotCoords); + if (mParentPlot->axisRect()) { + newPosition->setAxisRect(mParentPlot->axisRect()); + } + newPosition->setCoords(0, 0); + return newPosition; } /*! \internal @@ -12490,59 +12569,60 @@ QCPItemPosition *QCPAbstractItem::createPosition(const QString &name) Creates a QCPItemAnchor, registers it with this item and returns a pointer to it. The specified \a name must be a unique string that is usually identical to the variable name of the anchor member (This is needed to provide the name based \ref anchor access to anchors). - + The \a anchorId must be a number identifying the created anchor. It is recommended to create an enum (e.g. "AnchorIndex") for this on each item that uses anchors. This id is used by the anchor to identify itself when it calls QCPAbstractItem::anchorPixelPosition. That function then returns the correct pixel coordinates for the passed anchor id. - + Don't delete anchors created by this function manually, as the item will take care of it. - + Use this function in the constructor (initialization list) of the specific item subclass to create each anchor member. Don't create QCPItemAnchors with \b new yourself, because then they won't be registered with the item properly. - + \see createPosition */ QCPItemAnchor *QCPAbstractItem::createAnchor(const QString &name, int anchorId) { - if (hasAnchor(name)) - qDebug() << Q_FUNC_INFO << "anchor/position with name exists already:" << name; - QCPItemAnchor *newAnchor = new QCPItemAnchor(mParentPlot, this, name, anchorId); - mAnchors.append(newAnchor); - return newAnchor; + if (hasAnchor(name)) { + qDebug() << Q_FUNC_INFO << "anchor/position with name exists already:" << name; + } + QCPItemAnchor *newAnchor = new QCPItemAnchor(mParentPlot, this, name, anchorId); + mAnchors.append(newAnchor); + return newAnchor; } /* inherits documentation from base class */ void QCPAbstractItem::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) { - Q_UNUSED(event) - Q_UNUSED(details) - if (mSelectable) - { - bool selBefore = mSelected; - setSelected(additive ? !mSelected : true); - if (selectionStateChanged) - *selectionStateChanged = mSelected != selBefore; - } + Q_UNUSED(event) + Q_UNUSED(details) + if (mSelectable) { + bool selBefore = mSelected; + setSelected(additive ? !mSelected : true); + if (selectionStateChanged) { + *selectionStateChanged = mSelected != selBefore; + } + } } /* inherits documentation from base class */ void QCPAbstractItem::deselectEvent(bool *selectionStateChanged) { - if (mSelectable) - { - bool selBefore = mSelected; - setSelected(false); - if (selectionStateChanged) - *selectionStateChanged = mSelected != selBefore; - } + if (mSelectable) { + bool selBefore = mSelected; + setSelected(false); + if (selectionStateChanged) { + *selectionStateChanged = mSelected != selBefore; + } + } } /* inherits documentation from base class */ QCP::Interaction QCPAbstractItem::selectionCategory() const { - return QCP::iSelectItems; + return QCP::iSelectItems; } /* end of 'src/item.cpp' */ @@ -12555,10 +12635,10 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCustomPlot - + \brief The central class of the library. This is the QWidget which displays the plot and interacts with the user. - + For tutorials on how to use QCustomPlot, see the website\n http://www.qcustomplot.com/ */ @@ -12566,15 +12646,15 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const /* start of documentation of inline functions */ /*! \fn QCPSelectionRect *QCustomPlot::selectionRect() const - + Allows access to the currently used QCPSelectionRect instance (or subclass thereof), that is used to handle and draw selection rect interactions (see \ref setSelectionRectMode). - + \see setSelectionRect */ /*! \fn QCPLayoutGrid *QCustomPlot::plotLayout() const - + Returns the top level layout of this QCustomPlot instance. It is a \ref QCPLayoutGrid, initially containing just one cell with the main QCPAxisRect inside. */ @@ -12590,7 +12670,7 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const /*! \fn void QCustomPlot::mousePress(QMouseEvent *event) This signal is emitted when the QCustomPlot receives a mouse press event. - + It is emitted before QCustomPlot handles any other mechanism like range dragging. So a slot connected to this signal can still influence the behaviour e.g. with \ref QCPAxisRect::setRangeDrag or \ref QCPAxisRect::setRangeDragAxes. @@ -12599,11 +12679,11 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const /*! \fn void QCustomPlot::mouseMove(QMouseEvent *event) This signal is emitted when the QCustomPlot receives a mouse move event. - + It is emitted before QCustomPlot handles any other mechanism like range dragging. So a slot connected to this signal can still influence the behaviour e.g. with \ref QCPAxisRect::setRangeDrag or \ref QCPAxisRect::setRangeDragAxes. - + \warning It is discouraged to change the drag-axes with \ref QCPAxisRect::setRangeDragAxes here, because the dragging starting point was saved the moment the mouse was pressed. Thus it only has a meaning for the range drag axes that were set at that moment. If you want to change the drag @@ -12613,7 +12693,7 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const /*! \fn void QCustomPlot::mouseRelease(QMouseEvent *event) This signal is emitted when the QCustomPlot receives a mouse release event. - + It is emitted before QCustomPlot handles any other mechanisms like object selection. So a slot connected to this signal can still influence the behaviour e.g. with \ref setInteractions or \ref QCPAbstractPlottable::setSelectable. @@ -12622,7 +12702,7 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const /*! \fn void QCustomPlot::mouseWheel(QMouseEvent *event) This signal is emitted when the QCustomPlot receives a mouse wheel event. - + It is emitted before QCustomPlot handles any other mechanisms like range zooming. So a slot connected to this signal can still influence the behaviour e.g. with \ref QCPAxisRect::setRangeZoom, \ref QCPAxisRect::setRangeZoomAxes or \ref QCPAxisRect::setRangeZoomFactor. @@ -12651,104 +12731,104 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const */ /*! \fn void QCustomPlot::itemClick(QCPAbstractItem *item, QMouseEvent *event) - + This signal is emitted when an item is clicked. \a event is the mouse event that caused the click and \a item is the item that received the click. - + \see itemDoubleClick */ /*! \fn void QCustomPlot::itemDoubleClick(QCPAbstractItem *item, QMouseEvent *event) - + This signal is emitted when an item is double clicked. - + \a event is the mouse event that caused the click and \a item is the item that received the click. - + \see itemClick */ /*! \fn void QCustomPlot::axisClick(QCPAxis *axis, QCPAxis::SelectablePart part, QMouseEvent *event) - + This signal is emitted when an axis is clicked. - + \a event is the mouse event that caused the click, \a axis is the axis that received the click and \a part indicates the part of the axis that was clicked. - + \see axisDoubleClick */ /*! \fn void QCustomPlot::axisDoubleClick(QCPAxis *axis, QCPAxis::SelectablePart part, QMouseEvent *event) This signal is emitted when an axis is double clicked. - + \a event is the mouse event that caused the click, \a axis is the axis that received the click and \a part indicates the part of the axis that was clicked. - + \see axisClick */ /*! \fn void QCustomPlot::legendClick(QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event) This signal is emitted when a legend (item) is clicked. - + \a event is the mouse event that caused the click, \a legend is the legend that received the click and \a item is the legend item that received the click. If only the legend and no item is clicked, \a item is 0. This happens for a click inside the legend padding or the space between two items. - + \see legendDoubleClick */ /*! \fn void QCustomPlot::legendDoubleClick(QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event) This signal is emitted when a legend (item) is double clicked. - + \a event is the mouse event that caused the click, \a legend is the legend that received the click and \a item is the legend item that received the click. If only the legend and no item is clicked, \a item is 0. This happens for a click inside the legend padding or the space between two items. - + \see legendClick */ /*! \fn void QCustomPlot::selectionChangedByUser() - + This signal is emitted after the user has changed the selection in the QCustomPlot, e.g. by clicking. It is not emitted when the selection state of an object has changed programmatically by a direct call to setSelected()/setSelection() on an object or by calling \ref deselectAll. - + 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. - + \see selectedPlottables, selectedGraphs, selectedItems, selectedAxes, selectedLegends */ /*! \fn void QCustomPlot::beforeReplot() - + This signal is emitted immediately before a replot takes place (caused by a call to the slot \ref replot). - + It is safe to mutually connect the replot slot with this signal on two QCustomPlots to make them replot synchronously, it won't cause an infinite recursion. - + \see replot, afterReplot */ /*! \fn void QCustomPlot::afterReplot() - + This signal is emitted immediately after a replot has taken place (caused by a call to the slot \ref replot). - + It is safe to mutually connect the replot slot with this signal on two QCustomPlots to make them replot synchronously, it won't cause an infinite recursion. - + \see replot, beforeReplot */ @@ -12758,7 +12838,7 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const /*! \var QCPAxis *QCustomPlot::xAxis A pointer to the primary x Axis (bottom) of the main axis rect of the plot. - + QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref yAxis2) and the \ref legend. They make it very easy working with plots that only have a single axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the @@ -12766,7 +12846,7 @@ 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 @@ -12776,7 +12856,7 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const /*! \var QCPAxis *QCustomPlot::yAxis A pointer to the primary y Axis (left) of the main axis rect of the plot. - + QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref yAxis2) and the \ref legend. They make it very easy working with plots that only have a single axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the @@ -12784,7 +12864,7 @@ 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 @@ -12796,7 +12876,7 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const A pointer to the secondary x Axis (top) of the main axis rect of the plot. Secondary axes are invisible by default. Use QCPAxis::setVisible to change this (or use \ref QCPAxisRect::setupFullAxesBox). - + QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref yAxis2) and the \ref legend. They make it very easy working with plots that only have a single axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the @@ -12804,7 +12884,7 @@ 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 @@ -12816,7 +12896,7 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const A pointer to the secondary y Axis (right) of the main axis rect of the plot. Secondary axes are invisible by default. Use QCPAxis::setVisible to change this (or use \ref QCPAxisRect::setupFullAxesBox). - + QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref yAxis2) and the \ref legend. They make it very easy working with plots that only have a single axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the @@ -12824,7 +12904,7 @@ 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 @@ -12835,7 +12915,7 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const A pointer to the default legend of the main axis rect. The legend is invisible by default. Use QCPLegend::setVisible to change this. - + QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref yAxis2) and the \ref legend. They make it very easy working with plots that only have a single axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the @@ -12844,7 +12924,7 @@ 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 @@ -12857,230 +12937,235 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const Constructs a QCustomPlot and sets reasonable default values. */ QCustomPlot::QCustomPlot(QWidget *parent) : - QWidget(parent), - xAxis(0), - yAxis(0), - xAxis2(0), - yAxis2(0), - legend(0), - mBufferDevicePixelRatio(1.0), // will be adapted to primary screen below - mPlotLayout(0), - mAutoAddPlottableToLegend(true), - mAntialiasedElements(QCP::aeNone), - mNotAntialiasedElements(QCP::aeNone), - mInteractions(0), - mSelectionTolerance(8), - mNoAntialiasingOnDrag(false), - mBackgroundBrush(Qt::white, Qt::SolidPattern), - mBackgroundScaled(true), - mBackgroundScaledMode(Qt::KeepAspectRatioByExpanding), - mCurrentLayer(0), - mPlottingHints(QCP::phCacheLabels|QCP::phImmediateRefresh), - mMultiSelectModifier(Qt::ControlModifier), - mSelectionRectMode(QCP::srmNone), - mSelectionRect(0), - mOpenGl(false), - mMouseHasMoved(false), - mMouseEventLayerable(0), - mMouseSignalLayerable(0), - mReplotting(false), - mReplotQueued(false), - mOpenGlMultisamples(16), - mOpenGlAntialiasedElementsBackup(QCP::aeNone), - mOpenGlCacheLabelsBackup(true) + QWidget(parent), + xAxis(0), + yAxis(0), + xAxis2(0), + yAxis2(0), + legend(0), + mBufferDevicePixelRatio(1.0), // will be adapted to primary screen below + mPlotLayout(0), + mAutoAddPlottableToLegend(true), + mAntialiasedElements(QCP::aeNone), + mNotAntialiasedElements(QCP::aeNone), + mInteractions(0), + mSelectionTolerance(8), + mNoAntialiasingOnDrag(false), + mBackgroundBrush(Qt::white, Qt::SolidPattern), + mBackgroundScaled(true), + mBackgroundScaledMode(Qt::KeepAspectRatioByExpanding), + mCurrentLayer(0), + mPlottingHints(QCP::phCacheLabels | QCP::phImmediateRefresh), + mMultiSelectModifier(Qt::ControlModifier), + mSelectionRectMode(QCP::srmNone), + mSelectionRect(0), + mOpenGl(false), + mMouseHasMoved(false), + mMouseEventLayerable(0), + mMouseSignalLayerable(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); + 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 # ifdef QCP_DEVICEPIXELRATIO_FLOAT - setBufferDevicePixelRatio(QWidget::devicePixelRatioF()); + setBufferDevicePixelRatio(QWidget::devicePixelRatioF()); # else - setBufferDevicePixelRatio(QWidget::devicePixelRatio()); + setBufferDevicePixelRatio(QWidget::devicePixelRatio()); # endif #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; - mPlotLayout->initializeParentPlot(this); - mPlotLayout->setParent(this); // important because if parent is QWidget, QCPLayout::sizeConstraintsChanged will call QWidget::updateGeometry - mPlotLayout->setLayer(QLatin1String("main")); - QCPAxisRect *defaultAxisRect = new QCPAxisRect(this, true); - mPlotLayout->addElement(0, 0, defaultAxisRect); - xAxis = defaultAxisRect->axis(QCPAxis::atBottom); - yAxis = defaultAxisRect->axis(QCPAxis::atLeft); - xAxis2 = defaultAxisRect->axis(QCPAxis::atTop); - yAxis2 = defaultAxisRect->axis(QCPAxis::atRight); - legend = new QCPLegend; - legend->setVisible(false); - defaultAxisRect->insetLayout()->addElement(legend, Qt::AlignRight|Qt::AlignTop); - defaultAxisRect->insetLayout()->setMargins(QMargins(12, 12, 12, 12)); - - defaultAxisRect->setLayer(QLatin1String("background")); - xAxis->setLayer(QLatin1String("axes")); - yAxis->setLayer(QLatin1String("axes")); - xAxis2->setLayer(QLatin1String("axes")); - yAxis2->setLayer(QLatin1String("axes")); - xAxis->grid()->setLayer(QLatin1String("grid")); - yAxis->grid()->setLayer(QLatin1String("grid")); - xAxis2->grid()->setLayer(QLatin1String("grid")); - 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(rpQueuedReplot); + + 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; + mPlotLayout->initializeParentPlot(this); + mPlotLayout->setParent(this); // important because if parent is QWidget, QCPLayout::sizeConstraintsChanged will call QWidget::updateGeometry + mPlotLayout->setLayer(QLatin1String("main")); + QCPAxisRect *defaultAxisRect = new QCPAxisRect(this, true); + mPlotLayout->addElement(0, 0, defaultAxisRect); + xAxis = defaultAxisRect->axis(QCPAxis::atBottom); + yAxis = defaultAxisRect->axis(QCPAxis::atLeft); + xAxis2 = defaultAxisRect->axis(QCPAxis::atTop); + yAxis2 = defaultAxisRect->axis(QCPAxis::atRight); + legend = new QCPLegend; + legend->setVisible(false); + defaultAxisRect->insetLayout()->addElement(legend, Qt::AlignRight | Qt::AlignTop); + defaultAxisRect->insetLayout()->setMargins(QMargins(12, 12, 12, 12)); + + defaultAxisRect->setLayer(QLatin1String("background")); + xAxis->setLayer(QLatin1String("axes")); + yAxis->setLayer(QLatin1String("axes")); + xAxis2->setLayer(QLatin1String("axes")); + yAxis2->setLayer(QLatin1String("axes")); + xAxis->grid()->setLayer(QLatin1String("grid")); + yAxis->grid()->setLayer(QLatin1String("grid")); + xAxis2->grid()->setLayer(QLatin1String("grid")); + 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(rpQueuedReplot); } QCustomPlot::~QCustomPlot() { - clearPlottables(); - clearItems(); + clearPlottables(); + clearItems(); - if (mPlotLayout) - { - delete mPlotLayout; - mPlotLayout = 0; - } - - mCurrentLayer = 0; - qDeleteAll(mLayers); // don't use removeLayer, because it would prevent the last layer to be removed - mLayers.clear(); + if (mPlotLayout) { + delete mPlotLayout; + mPlotLayout = 0; + } + + mCurrentLayer = 0; + qDeleteAll(mLayers); // don't use removeLayer, because it would prevent the last layer to be removed + mLayers.clear(); } /*! Sets which elements are forcibly drawn antialiased as an \a or combination of QCP::AntialiasedElement. - + This overrides the antialiasing settings for whole element groups, normally controlled with the \a setAntialiasing function on the individual elements. If an element is neither specified in \ref setAntialiasedElements nor in \ref setNotAntialiasedElements, the antialiasing setting on each individual element instance is used. - + For example, if \a antialiasedElements contains \ref QCP::aePlottables, all plottables will be drawn antialiased, no matter what the specific QCPAbstractPlottable::setAntialiased value was set to. - + if an element in \a antialiasedElements is already set in \ref setNotAntialiasedElements, it is removed from there. - + \see setNotAntialiasedElements */ void QCustomPlot::setAntialiasedElements(const QCP::AntialiasedElements &antialiasedElements) { - mAntialiasedElements = antialiasedElements; - - // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously: - if ((mNotAntialiasedElements & mAntialiasedElements) != 0) - mNotAntialiasedElements |= ~mAntialiasedElements; + mAntialiasedElements = antialiasedElements; + + // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously: + if ((mNotAntialiasedElements & mAntialiasedElements) != 0) { + mNotAntialiasedElements |= ~mAntialiasedElements; + } } /*! Sets whether the specified \a antialiasedElement is forcibly drawn antialiased. - + See \ref setAntialiasedElements for details. - + \see setNotAntialiasedElement */ void QCustomPlot::setAntialiasedElement(QCP::AntialiasedElement antialiasedElement, bool enabled) { - if (!enabled && mAntialiasedElements.testFlag(antialiasedElement)) - mAntialiasedElements &= ~antialiasedElement; - else if (enabled && !mAntialiasedElements.testFlag(antialiasedElement)) - mAntialiasedElements |= antialiasedElement; - - // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously: - if ((mNotAntialiasedElements & mAntialiasedElements) != 0) - mNotAntialiasedElements |= ~mAntialiasedElements; + if (!enabled && mAntialiasedElements.testFlag(antialiasedElement)) { + mAntialiasedElements &= ~antialiasedElement; + } else if (enabled && !mAntialiasedElements.testFlag(antialiasedElement)) { + mAntialiasedElements |= antialiasedElement; + } + + // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously: + if ((mNotAntialiasedElements & mAntialiasedElements) != 0) { + mNotAntialiasedElements |= ~mAntialiasedElements; + } } /*! Sets which elements are forcibly drawn not antialiased as an \a or combination of QCP::AntialiasedElement. - + This overrides the antialiasing settings for whole element groups, normally controlled with the \a setAntialiasing function on the individual elements. If an element is neither specified in \ref setAntialiasedElements nor in \ref setNotAntialiasedElements, the antialiasing setting on each individual element instance is used. - + For example, if \a notAntialiasedElements contains \ref QCP::aePlottables, no plottables will be drawn antialiased, no matter what the specific QCPAbstractPlottable::setAntialiased value was set to. - + if an element in \a notAntialiasedElements is already set in \ref setAntialiasedElements, it is removed from there. - + \see setAntialiasedElements */ void QCustomPlot::setNotAntialiasedElements(const QCP::AntialiasedElements ¬AntialiasedElements) { - mNotAntialiasedElements = notAntialiasedElements; - - // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously: - if ((mNotAntialiasedElements & mAntialiasedElements) != 0) - mAntialiasedElements |= ~mNotAntialiasedElements; + mNotAntialiasedElements = notAntialiasedElements; + + // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously: + if ((mNotAntialiasedElements & mAntialiasedElements) != 0) { + mAntialiasedElements |= ~mNotAntialiasedElements; + } } /*! Sets whether the specified \a notAntialiasedElement is forcibly drawn not antialiased. - + See \ref setNotAntialiasedElements for details. - + \see setAntialiasedElement */ void QCustomPlot::setNotAntialiasedElement(QCP::AntialiasedElement notAntialiasedElement, bool enabled) { - if (!enabled && mNotAntialiasedElements.testFlag(notAntialiasedElement)) - mNotAntialiasedElements &= ~notAntialiasedElement; - else if (enabled && !mNotAntialiasedElements.testFlag(notAntialiasedElement)) - mNotAntialiasedElements |= notAntialiasedElement; - - // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously: - if ((mNotAntialiasedElements & mAntialiasedElements) != 0) - mAntialiasedElements |= ~mNotAntialiasedElements; + if (!enabled && mNotAntialiasedElements.testFlag(notAntialiasedElement)) { + mNotAntialiasedElements &= ~notAntialiasedElement; + } else if (enabled && !mNotAntialiasedElements.testFlag(notAntialiasedElement)) { + mNotAntialiasedElements |= notAntialiasedElement; + } + + // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously: + if ((mNotAntialiasedElements & mAntialiasedElements) != 0) { + mAntialiasedElements |= ~mNotAntialiasedElements; + } } /*! 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 addGraph, QCPLegend::addItem */ void QCustomPlot::setAutoAddPlottableToLegend(bool on) { - mAutoAddPlottableToLegend = on; + mAutoAddPlottableToLegend = on; } /*! Sets the possible interactions of this QCustomPlot as an or-combination of \ref QCP::Interaction enums. There are the following types of interactions: - + Axis range manipulation is controlled via \ref QCP::iRangeDrag and \ref QCP::iRangeZoom. When the respective interaction is enabled, the user may drag axes ranges and zoom with the mouse wheel. For details how to control which axes the user may drag/zoom and in what orientations, see \ref QCPAxisRect::setRangeDrag, \ref QCPAxisRect::setRangeZoom, \ref QCPAxisRect::setRangeDragAxes, \ref QCPAxisRect::setRangeZoomAxes. - + 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 @@ -13089,78 +13174,79 @@ void QCustomPlot::setAutoAddPlottableToLegend(bool on) 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 out whether a specific item is selected, call QCPAbstractItem::selected(). To retrieve a list of all currently selected items, call \ref selectedItems. - + Axis selection is controlled with \ref QCP::iSelectAxes. If \ref QCP::iSelectAxes is set, the user may select parts of the axes by clicking on them. What parts exactly (e.g. Axis base line, tick labels, axis label) are selectable can be controlled via \ref QCPAxis::setSelectableParts for each axis. To retrieve a list of all axes that currently contain selected parts, call \ref selectedAxes. Which parts of an axis are selected, can be retrieved with QCPAxis::selectedParts(). - + Legend selection is controlled with \ref QCP::iSelectLegend. If this is set, the user may select the legend itself or individual items by clicking on them. What parts exactly are selectable can be controlled via \ref QCPLegend::setSelectableParts. To find out whether the legend or any of its child items are selected, check the value of QCPLegend::selectedParts. To find out which child items are selected, call \ref QCPLegend::selectedItems. - + All other selectable elements The selection of all other selectable objects (e.g. 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. - + If the selection state has changed by user interaction, the \ref selectionChangedByUser signal is emitted. Each selectable object additionally emits an individual selectionChanged signal whenever their selection state has changed, i.e. not only by user interaction. - + To allow multiple objects to be selected by holding the selection modifier (\ref setMultiSelectModifier), set the flag \ref QCP::iMultiSelect. - + \note In addition to the selection mechanism presented here, QCustomPlot always emits corresponding signals, when an object is clicked or double clicked. see \ref plottableClick and \ref plottableDoubleClick for example. - + \see setInteraction, setSelectionTolerance */ void QCustomPlot::setInteractions(const QCP::Interactions &interactions) { - mInteractions = interactions; + mInteractions = interactions; } /*! Sets the single \a interaction of this QCustomPlot to \a enabled. - + For details about the interaction system, see \ref setInteractions. - + \see setInteractions */ void QCustomPlot::setInteraction(const QCP::Interaction &interaction, bool enabled) { - if (!enabled && mInteractions.testFlag(interaction)) - mInteractions &= ~interaction; - else if (enabled && !mInteractions.testFlag(interaction)) - mInteractions |= interaction; + if (!enabled && mInteractions.testFlag(interaction)) { + mInteractions &= ~interaction; + } else if (enabled && !mInteractions.testFlag(interaction)) { + mInteractions |= interaction; + } } /*! Sets the tolerance that is used to decide whether a click selects an object (e.g. a plottable) or not. - + If the user clicks in the vicinity of the line of e.g. a QCPGraph, it's only regarded as a potential selection when the minimum distance between the click position and the graph line is smaller than \a pixels. Objects that are defined by an area (e.g. QCPBars) only react to clicks directly inside the area and ignore this selection tolerance. In other words, it only has meaning for parts of objects that are too thin to exactly hit with a click and thus need such a tolerance. - + \see setInteractions, QCPLayerable::selectTest */ void QCustomPlot::setSelectionTolerance(int pixels) { - mSelectionTolerance = pixels; + mSelectionTolerance = pixels; } /*! @@ -13169,54 +13255,56 @@ void QCustomPlot::setSelectionTolerance(int pixels) performance during dragging. Thus it creates a more responsive user experience. As soon as the user stops dragging, the last replot is done with normal antialiasing, to restore high image quality. - + \see setAntialiasedElements, setNotAntialiasedElements */ void QCustomPlot::setNoAntialiasingOnDrag(bool enabled) { - mNoAntialiasingOnDrag = enabled; + mNoAntialiasingOnDrag = enabled; } /*! Sets the plotting hints for this QCustomPlot instance as an \a or combination of QCP::PlottingHint. - + \see setPlottingHint */ void QCustomPlot::setPlottingHints(const QCP::PlottingHints &hints) { - mPlottingHints = hints; + mPlottingHints = hints; } /*! Sets the specified plotting \a hint to \a enabled. - + \see setPlottingHints */ void QCustomPlot::setPlottingHint(QCP::PlottingHint hint, bool enabled) { - QCP::PlottingHints newHints = mPlottingHints; - if (!enabled) - newHints &= ~hint; - else - newHints |= hint; - - if (newHints != mPlottingHints) - setPlottingHints(newHints); + QCP::PlottingHints newHints = mPlottingHints; + if (!enabled) { + newHints &= ~hint; + } else { + newHints |= hint; + } + + if (newHints != mPlottingHints) { + setPlottingHints(newHints); + } } /*! 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 (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. - + \see setInteractions */ void QCustomPlot::setMultiSelectModifier(Qt::KeyboardModifier modifier) { - mMultiSelectModifier = modifier; + mMultiSelectModifier = modifier; } /*! @@ -13226,74 +13314,77 @@ void QCustomPlot::setMultiSelectModifier(Qt::KeyboardModifier modifier) 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; + 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*))); - } + 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 *))); + } + } } /*! \warning This is still an experimental feature and its performance depends on the system that it runs on. Having multiple QCustomPlot widgets in one application with enabled OpenGL rendering might cause context conflicts on some systems. - + This method allows to enable OpenGL plot rendering, for increased plotting performance of graphically demanding plots (thick lines, translucent fills, etc.). @@ -13327,39 +13418,37 @@ void QCustomPlot::setSelectionRect(QCPSelectionRect *selectionRect) */ void QCustomPlot::setOpenGl(bool enabled, int multisampling) { - mOpenGlMultisamples = qMax(0, 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; + 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(); } - } 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(); + // 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)"; + 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 } @@ -13381,9 +13470,10 @@ void QCustomPlot::setOpenGl(bool enabled, int multisampling) */ void QCustomPlot::setViewport(const QRect &rect) { - mViewport = rect; - if (mPlotLayout) - mPlotLayout->setOuterRect(mViewport); + mViewport = rect; + if (mPlotLayout) { + mPlotLayout->setOuterRect(mViewport); + } } /*! @@ -13399,18 +13489,18 @@ void QCustomPlot::setViewport(const QRect &rect) */ void QCustomPlot::setBufferDevicePixelRatio(double ratio) { - if (!qFuzzyCompare(ratio, mBufferDevicePixelRatio)) - { + 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 + mBufferDevicePixelRatio = ratio; + for (int i = 0; i < mPaintBuffers.size(); ++i) { + mPaintBuffers.at(i)->setDevicePixelRatio(mBufferDevicePixelRatio); + } + // Note: axis label cache has devicePixelRatio as part of cache hash, so no need to manually clear cache here #else - qDebug() << Q_FUNC_INFO << "Device pixel ratios not supported for Qt versions before 5.4"; - mBufferDevicePixelRatio = 1.0; + qDebug() << Q_FUNC_INFO << "Device pixel ratios not supported for Qt versions before 5.4"; + mBufferDevicePixelRatio = 1.0; #endif - } + } } /*! @@ -13421,7 +13511,7 @@ void QCustomPlot::setBufferDevicePixelRatio(double ratio) enabled with \ref setBackgroundScaled and the scaling mode (whether and how the aspect ratio is preserved) can be set with \ref setBackgroundScaledMode. To set all these options in one call, consider using the overloaded version of this function. - + If a background brush was set with \ref setBackground(const QBrush &brush), the viewport will first be filled with that brush, before drawing the background pixmap. This can be useful for background pixmaps with translucent areas. @@ -13430,8 +13520,8 @@ void QCustomPlot::setBufferDevicePixelRatio(double ratio) */ void QCustomPlot::setBackground(const QPixmap &pm) { - mBackgroundPixmap = pm; - mScaledBackgroundPixmap = QPixmap(); + mBackgroundPixmap = pm; + mScaledBackgroundPixmap = QPixmap(); } /*! @@ -13441,7 +13531,7 @@ void QCustomPlot::setBackground(const QPixmap &pm) was set with \ref setBackground(const QPixmap &pm), this brush will be used to fill the viewport before the background pixmap is drawn. This can be useful for background pixmaps with translucent areas. - + Set \a brush to Qt::NoBrush or Qt::Transparent to leave background transparent. This can be useful for exporting to image formats which support transparency, e.g. \ref savePng. @@ -13449,11 +13539,11 @@ void QCustomPlot::setBackground(const QPixmap &pm) */ void QCustomPlot::setBackground(const QBrush &brush) { - mBackgroundBrush = brush; + mBackgroundBrush = brush; } /*! \overload - + Allows setting the background pixmap of the viewport, whether it shall be scaled and how it shall be scaled in one call. @@ -13461,193 +13551,189 @@ void QCustomPlot::setBackground(const QBrush &brush) */ void QCustomPlot::setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode) { - mBackgroundPixmap = pm; - mScaledBackgroundPixmap = QPixmap(); - mBackgroundScaled = scaled; - mBackgroundScaledMode = mode; + mBackgroundPixmap = pm; + mScaledBackgroundPixmap = QPixmap(); + mBackgroundScaled = scaled; + mBackgroundScaledMode = mode; } /*! Sets whether the viewport background pixmap shall be scaled to fit the viewport. If \a scaled is set to true, control whether and how the aspect ratio of the original pixmap is preserved with \ref setBackgroundScaledMode. - + Note that the scaled version of the original pixmap is buffered, so there is no performance penalty on replots. (Except when the viewport dimensions are changed continuously.) - + \see setBackground, setBackgroundScaledMode */ void QCustomPlot::setBackgroundScaled(bool scaled) { - mBackgroundScaled = scaled; + mBackgroundScaled = scaled; } /*! If scaling of the viewport background pixmap is enabled (\ref setBackgroundScaled), use this function to define whether and how the aspect ratio of the original pixmap is preserved. - + \see setBackground, setBackgroundScaled */ void QCustomPlot::setBackgroundScaledMode(Qt::AspectRatioMode mode) { - mBackgroundScaledMode = mode; + mBackgroundScaledMode = mode; } /*! Returns the plottable with \a index. If the index is invalid, returns 0. - + There is an overloaded version of this function with no parameter which returns the last added plottable, see QCustomPlot::plottable() - + \see plottableCount */ QCPAbstractPlottable *QCustomPlot::plottable(int index) { - if (index >= 0 && index < mPlottables.size()) - { - return mPlottables.at(index); - } else - { - qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; - return 0; - } + if (index >= 0 && index < mPlottables.size()) { + return mPlottables.at(index); + } else { + qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; + return 0; + } } /*! \overload - + Returns the last plottable that was added to the plot. If there are no plottables in the plot, returns 0. - + \see plottableCount */ QCPAbstractPlottable *QCustomPlot::plottable() { - if (!mPlottables.isEmpty()) - { - return mPlottables.last(); - } else - return 0; + if (!mPlottables.isEmpty()) { + return mPlottables.last(); + } else { + return 0; + } } /*! 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 clearPlottables */ bool QCustomPlot::removePlottable(QCPAbstractPlottable *plottable) { - if (!mPlottables.contains(plottable)) - { - qDebug() << Q_FUNC_INFO << "plottable not in list:" << reinterpret_cast(plottable); - return false; - } - - // remove plottable from legend: - plottable->removeFromLegend(); - // special handling for QCPGraphs to maintain the simple graph interface: - if (QCPGraph *graph = qobject_cast(plottable)) - mGraphs.removeOne(graph); - // remove plottable: - delete plottable; - mPlottables.removeOne(plottable); - return true; + if (!mPlottables.contains(plottable)) { + qDebug() << Q_FUNC_INFO << "plottable not in list:" << reinterpret_cast(plottable); + return false; + } + + // remove plottable from legend: + plottable->removeFromLegend(); + // special handling for QCPGraphs to maintain the simple graph interface: + if (QCPGraph *graph = qobject_cast(plottable)) { + mGraphs.removeOne(graph); + } + // remove plottable: + delete plottable; + mPlottables.removeOne(plottable); + return true; } /*! \overload - + Removes and deletes the plottable by its \a index. */ bool QCustomPlot::removePlottable(int index) { - if (index >= 0 && index < mPlottables.size()) - return removePlottable(mPlottables[index]); - else - { - qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; - return false; - } + if (index >= 0 && index < mPlottables.size()) { + return removePlottable(mPlottables[index]); + } else { + qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; + return false; + } } /*! 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. - + \see removePlottable */ int QCustomPlot::clearPlottables() { - int c = mPlottables.size(); - for (int i=c-1; i >= 0; --i) - removePlottable(mPlottables[i]); - return c; + int c = mPlottables.size(); + for (int i = c - 1; i >= 0; --i) { + removePlottable(mPlottables[i]); + } + return c; } /*! Returns the number of currently existing plottables in the plot - + \see plottable */ int QCustomPlot::plottableCount() const { - return mPlottables.size(); + return mPlottables.size(); } /*! Returns a list of the selected plottables. If no plottables are currently selected, the list is empty. - + There is a convenience function if you're only interested in selected graphs, see \ref selectedGraphs. - + \see setInteractions, QCPAbstractPlottable::setSelectable, QCPAbstractPlottable::setSelection */ -QList QCustomPlot::selectedPlottables() const +QList QCustomPlot::selectedPlottables() const { - QList result; - foreach (QCPAbstractPlottable *plottable, mPlottables) - { - if (plottable->selected()) - result.append(plottable); - } - return result; + QList result; + foreach (QCPAbstractPlottable *plottable, mPlottables) { + if (plottable->selected()) { + result.append(plottable); + } + } + return result; } /*! Returns the plottable at the pixel position \a pos. Plottables that only consist of single lines (like graphs) have a tolerance band around them, see \ref setSelectionTolerance. If multiple plottables come into consideration, the one closest to \a pos is returned. - + If \a onlySelectable is true, only plottables that are selectable (QCPAbstractPlottable::setSelectable) are considered. - + If there is no plottable at \a pos, the return value is 0. - + \see itemAt, layoutElementAt */ QCPAbstractPlottable *QCustomPlot::plottableAt(const QPointF &pos, bool onlySelectable) const { - QCPAbstractPlottable *resultPlottable = 0; - double resultDistance = mSelectionTolerance; // only regard clicks with distances smaller than mSelectionTolerance as selections, so initialize with that value - - foreach (QCPAbstractPlottable *plottable, mPlottables) - { - if (onlySelectable && !plottable->selectable()) // we could have also passed onlySelectable to the selectTest function, but checking here is faster, because we have access to QCPabstractPlottable::selectable - continue; - if ((plottable->keyAxis()->axisRect()->rect() & plottable->valueAxis()->axisRect()->rect()).contains(pos.toPoint())) // only consider clicks inside the rect that is spanned by the plottable's key/value axes - { - double currentDistance = plottable->selectTest(pos, false); - if (currentDistance >= 0 && currentDistance < resultDistance) - { - resultPlottable = plottable; - resultDistance = currentDistance; - } + QCPAbstractPlottable *resultPlottable = 0; + double resultDistance = mSelectionTolerance; // only regard clicks with distances smaller than mSelectionTolerance as selections, so initialize with that value + + foreach (QCPAbstractPlottable *plottable, mPlottables) { + if (onlySelectable && !plottable->selectable()) { // we could have also passed onlySelectable to the selectTest function, but checking here is faster, because we have access to QCPabstractPlottable::selectable + continue; + } + if ((plottable->keyAxis()->axisRect()->rect() & plottable->valueAxis()->axisRect()->rect()).contains(pos.toPoint())) { // only consider clicks inside the rect that is spanned by the plottable's key/value axes + double currentDistance = plottable->selectTest(pos, false); + if (currentDistance >= 0 && currentDistance < resultDistance) { + resultPlottable = plottable; + resultDistance = currentDistance; + } + } } - } - - return resultPlottable; + + return resultPlottable; } /*! @@ -13655,75 +13741,75 @@ QCPAbstractPlottable *QCustomPlot::plottableAt(const QPointF &pos, bool onlySele */ bool QCustomPlot::hasPlottable(QCPAbstractPlottable *plottable) const { - return mPlottables.contains(plottable); + return mPlottables.contains(plottable); } /*! Returns the graph with \a index. If the index is invalid, returns 0. - + There is an overloaded version of this function with no parameter which returns the last created graph, see QCustomPlot::graph() - + \see graphCount, addGraph */ QCPGraph *QCustomPlot::graph(int index) const { - if (index >= 0 && index < mGraphs.size()) - { - return mGraphs.at(index); - } else - { - qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; - return 0; - } + if (index >= 0 && index < mGraphs.size()) { + return mGraphs.at(index); + } else { + qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; + return 0; + } } /*! \overload - + Returns the last graph, that was created with \ref addGraph. If there are no graphs in the plot, returns 0. - + \see graphCount, addGraph */ QCPGraph *QCustomPlot::graph() const { - if (!mGraphs.isEmpty()) - { - return mGraphs.last(); - } else - return 0; + if (!mGraphs.isEmpty()) { + return mGraphs.last(); + } else { + return 0; + } } /*! Creates a new graph inside the plot. If \a keyAxis and \a valueAxis are left unspecified (0), the bottom (xAxis) is used as key and the left (yAxis) is used as value axis. If specified, \a keyAxis and \a valueAxis must reside in this QCustomPlot. - + \a keyAxis will be used as key axis (typically "x") and \a valueAxis as value axis (typically "y") for the graph. - + Returns a pointer to the newly created graph, or 0 if adding the graph failed. - + \see graph, graphCount, removeGraph, clearGraphs */ QCPGraph *QCustomPlot::addGraph(QCPAxis *keyAxis, QCPAxis *valueAxis) { - if (!keyAxis) keyAxis = xAxis; - if (!valueAxis) valueAxis = yAxis; - if (!keyAxis || !valueAxis) - { - qDebug() << Q_FUNC_INFO << "can't use default QCustomPlot xAxis or yAxis, because at least one is invalid (has been deleted)"; - return 0; - } - if (keyAxis->parentPlot() != this || valueAxis->parentPlot() != this) - { - qDebug() << Q_FUNC_INFO << "passed keyAxis or valueAxis doesn't have this QCustomPlot as parent"; - return 0; - } - - QCPGraph *newGraph = new QCPGraph(keyAxis, valueAxis); - newGraph->setName(QLatin1String("Graph ")+QString::number(mGraphs.size())); - return newGraph; + if (!keyAxis) { + keyAxis = xAxis; + } + if (!valueAxis) { + valueAxis = yAxis; + } + if (!keyAxis || !valueAxis) { + qDebug() << Q_FUNC_INFO << "can't use default QCustomPlot xAxis or yAxis, because at least one is invalid (has been deleted)"; + return 0; + } + if (keyAxis->parentPlot() != this || valueAxis->parentPlot() != this) { + qDebug() << Q_FUNC_INFO << "passed keyAxis or valueAxis doesn't have this QCustomPlot as parent"; + return 0; + } + + QCPGraph *newGraph = new QCPGraph(keyAxis, valueAxis); + newGraph->setName(QLatin1String("Graph ") + QString::number(mGraphs.size())); + return newGraph; } /*! @@ -13731,26 +13817,27 @@ QCPGraph *QCustomPlot::addGraph(QCPAxis *keyAxis, QCPAxis *valueAxis) 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. - + \see clearGraphs */ bool QCustomPlot::removeGraph(QCPGraph *graph) { - return removePlottable(graph); + return removePlottable(graph); } /*! \overload - + Removes and deletes the graph by its \a index. */ bool QCustomPlot::removeGraph(int index) { - if (index >= 0 && index < mGraphs.size()) - return removeGraph(mGraphs[index]); - else - return false; + if (index >= 0 && index < mGraphs.size()) { + return removeGraph(mGraphs[index]); + } else { + return false; + } } /*! @@ -13758,157 +13845,154 @@ bool QCustomPlot::removeGraph(int index) from the default legend (QCustomPlot::legend). Returns the number of graphs removed. - + \see removeGraph */ int QCustomPlot::clearGraphs() { - int c = mGraphs.size(); - for (int i=c-1; i >= 0; --i) - removeGraph(mGraphs[i]); - return c; + int c = mGraphs.size(); + for (int i = c - 1; i >= 0; --i) { + removeGraph(mGraphs[i]); + } + return c; } /*! Returns the number of currently existing graphs in the plot - + \see graph, addGraph */ int QCustomPlot::graphCount() const { - return mGraphs.size(); + return mGraphs.size(); } /*! Returns a list of the selected graphs. If no graphs are currently selected, the list is empty. - + 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::setSelection */ -QList QCustomPlot::selectedGraphs() const +QList QCustomPlot::selectedGraphs() const { - QList result; - foreach (QCPGraph *graph, mGraphs) - { - if (graph->selected()) - result.append(graph); - } - return result; + QList result; + foreach (QCPGraph *graph, mGraphs) { + if (graph->selected()) { + result.append(graph); + } + } + return result; } /*! Returns the item with \a index. If the index is invalid, returns 0. - + There is an overloaded version of this function with no parameter which returns the last added item, see QCustomPlot::item() - + \see itemCount */ QCPAbstractItem *QCustomPlot::item(int index) const { - if (index >= 0 && index < mItems.size()) - { - return mItems.at(index); - } else - { - qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; - return 0; - } + if (index >= 0 && index < mItems.size()) { + return mItems.at(index); + } else { + qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; + return 0; + } } /*! \overload - + Returns the last item that was added to this plot. If there are no items in the plot, returns 0. - + \see itemCount */ QCPAbstractItem *QCustomPlot::item() const { - if (!mItems.isEmpty()) - { - return mItems.last(); - } else - return 0; + if (!mItems.isEmpty()) { + return mItems.last(); + } else { + return 0; + } } /*! Removes the specified item from the plot and deletes it. - + Returns true on success. - + \see clearItems */ bool QCustomPlot::removeItem(QCPAbstractItem *item) { - if (mItems.contains(item)) - { - delete item; - mItems.removeOne(item); - return true; - } else - { - qDebug() << Q_FUNC_INFO << "item not in list:" << reinterpret_cast(item); - return false; - } + if (mItems.contains(item)) { + delete item; + mItems.removeOne(item); + return true; + } else { + qDebug() << Q_FUNC_INFO << "item not in list:" << reinterpret_cast(item); + return false; + } } /*! \overload - + Removes and deletes the item by its \a index. */ bool QCustomPlot::removeItem(int index) { - if (index >= 0 && index < mItems.size()) - return removeItem(mItems[index]); - else - { - qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; - return false; - } + if (index >= 0 && index < mItems.size()) { + return removeItem(mItems[index]); + } else { + qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; + return false; + } } /*! Removes all items from the plot and deletes them. - + Returns the number of items removed. - + \see removeItem */ int QCustomPlot::clearItems() { - int c = mItems.size(); - for (int i=c-1; i >= 0; --i) - removeItem(mItems[i]); - return c; + int c = mItems.size(); + for (int i = c - 1; i >= 0; --i) { + removeItem(mItems[i]); + } + return c; } /*! Returns the number of currently existing items in the plot - + \see item */ int QCustomPlot::itemCount() const { - return mItems.size(); + return mItems.size(); } /*! Returns a list of the selected items. If no items are currently selected, the list is empty. - + \see setInteractions, QCPAbstractItem::setSelectable, QCPAbstractItem::setSelected */ -QList QCustomPlot::selectedItems() const +QList QCustomPlot::selectedItems() const { - QList result; - foreach (QCPAbstractItem *item, mItems) - { - if (item->selected()) - result.append(item); - } - return result; + QList result; + foreach (QCPAbstractItem *item, mItems) { + if (item->selected()) { + result.append(item); + } + } + return result; } /*! @@ -13916,81 +14000,77 @@ QList QCustomPlot::selectedItems() const QCPItemLine or \ref QCPItemCurve) have a tolerance band around them, see \ref setSelectionTolerance. If multiple items come into consideration, the one closest to \a pos is returned. - + If \a onlySelectable is true, only items that are selectable (QCPAbstractItem::setSelectable) are considered. - + If there is no item at \a pos, the return value is 0. - + \see plottableAt, layoutElementAt */ QCPAbstractItem *QCustomPlot::itemAt(const QPointF &pos, bool onlySelectable) const { - QCPAbstractItem *resultItem = 0; - double resultDistance = mSelectionTolerance; // only regard clicks with distances smaller than mSelectionTolerance as selections, so initialize with that value - - foreach (QCPAbstractItem *item, mItems) - { - if (onlySelectable && !item->selectable()) // we could have also passed onlySelectable to the selectTest function, but checking here is faster, because we have access to QCPAbstractItem::selectable - continue; - if (!item->clipToAxisRect() || item->clipRect().contains(pos.toPoint())) // only consider clicks inside axis cliprect of the item if actually clipped to it - { - double currentDistance = item->selectTest(pos, false); - if (currentDistance >= 0 && currentDistance < resultDistance) - { - resultItem = item; - resultDistance = currentDistance; - } + QCPAbstractItem *resultItem = 0; + double resultDistance = mSelectionTolerance; // only regard clicks with distances smaller than mSelectionTolerance as selections, so initialize with that value + + foreach (QCPAbstractItem *item, mItems) { + if (onlySelectable && !item->selectable()) { // we could have also passed onlySelectable to the selectTest function, but checking here is faster, because we have access to QCPAbstractItem::selectable + continue; + } + if (!item->clipToAxisRect() || item->clipRect().contains(pos.toPoint())) { // only consider clicks inside axis cliprect of the item if actually clipped to it + double currentDistance = item->selectTest(pos, false); + if (currentDistance >= 0 && currentDistance < resultDistance) { + resultItem = item; + resultDistance = currentDistance; + } + } } - } - - return resultItem; + + return resultItem; } /*! Returns whether this QCustomPlot contains the \a item. - + \see item */ bool QCustomPlot::hasItem(QCPAbstractItem *item) const { - return mItems.contains(item); + return mItems.contains(item); } /*! Returns the layer with the specified \a name. If there is no layer with the specified name, 0 is returned. - + Layer names are case-sensitive. - + \see addLayer, moveLayer, removeLayer */ QCPLayer *QCustomPlot::layer(const QString &name) const { - foreach (QCPLayer *layer, mLayers) - { - if (layer->name() == name) - return layer; - } - return 0; + foreach (QCPLayer *layer, mLayers) { + if (layer->name() == name) { + return layer; + } + } + return 0; } /*! \overload - + Returns the layer by \a index. If the index is invalid, 0 is returned. - + \see addLayer, moveLayer, removeLayer */ QCPLayer *QCustomPlot::layer(int index) const { - if (index >= 0 && index < mLayers.size()) - { - return mLayers.at(index); - } else - { - qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; - return 0; - } + if (index >= 0 && index < mLayers.size()) { + return mLayers.at(index); + } else { + qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; + return 0; + } } /*! @@ -13998,294 +14078,285 @@ QCPLayer *QCustomPlot::layer(int index) const */ QCPLayer *QCustomPlot::currentLayer() const { - return mCurrentLayer; + return mCurrentLayer; } /*! Sets the layer with the specified \a name to be the current layer. All layerables (\ref QCPLayerable), e.g. plottables and items, are created on the current layer. - + Returns true on success, i.e. if there is a layer with the specified \a name in the QCustomPlot. - + Layer names are case-sensitive. - + \see addLayer, moveLayer, removeLayer, QCPLayerable::setLayer */ bool QCustomPlot::setCurrentLayer(const QString &name) { - if (QCPLayer *newCurrentLayer = layer(name)) - { - return setCurrentLayer(newCurrentLayer); - } else - { - qDebug() << Q_FUNC_INFO << "layer with name doesn't exist:" << name; - return false; - } + if (QCPLayer *newCurrentLayer = layer(name)) { + return setCurrentLayer(newCurrentLayer); + } else { + qDebug() << Q_FUNC_INFO << "layer with name doesn't exist:" << name; + return false; + } } /*! \overload - + Sets the provided \a layer to be the current layer. - + Returns true on success, i.e. when \a layer is a valid layer in the QCustomPlot. - + \see addLayer, moveLayer, removeLayer */ bool QCustomPlot::setCurrentLayer(QCPLayer *layer) { - if (!mLayers.contains(layer)) - { - qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast(layer); - return false; - } - - mCurrentLayer = layer; - return true; + if (!mLayers.contains(layer)) { + qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast(layer); + return false; + } + + mCurrentLayer = layer; + return true; } /*! Returns the number of currently existing layers in the plot - + \see layer, addLayer */ int QCustomPlot::layerCount() const { - return mLayers.size(); + return mLayers.size(); } /*! Adds a new layer to this QCustomPlot instance. The new layer will have the name \a name, which must be unique. Depending on \a insertMode, it is positioned either below or above \a otherLayer. - + Returns true on success, i.e. if there is no other layer named \a name and \a otherLayer is a valid layer inside this QCustomPlot. - + If \a otherLayer is 0, the highest layer in the QCustomPlot will be used. - + For an explanation of what layers are in QCustomPlot, see the documentation of \ref QCPLayer. - + \see layer, moveLayer, removeLayer */ bool QCustomPlot::addLayer(const QString &name, QCPLayer *otherLayer, QCustomPlot::LayerInsertMode insertMode) { - if (!otherLayer) - otherLayer = mLayers.last(); - if (!mLayers.contains(otherLayer)) - { - qDebug() << Q_FUNC_INFO << "otherLayer not a layer of this QCustomPlot:" << reinterpret_cast(otherLayer); - return false; - } - if (layer(name)) - { - qDebug() << Q_FUNC_INFO << "A layer exists already with the name" << name; - return false; - } - - 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; + if (!otherLayer) { + otherLayer = mLayers.last(); + } + if (!mLayers.contains(otherLayer)) { + qDebug() << Q_FUNC_INFO << "otherLayer not a layer of this QCustomPlot:" << reinterpret_cast(otherLayer); + return false; + } + if (layer(name)) { + qDebug() << Q_FUNC_INFO << "A layer exists already with the name" << name; + return false; + } + + 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; } /*! Removes the specified \a layer and returns true on success. - + All layerables (e.g. plottables and items) on the removed layer will be moved to the layer below \a layer. If \a layer is the bottom layer, the layerables are moved to the layer above. In both cases, the total rendering order of all layerables in the QCustomPlot is preserved. - + If \a layer is the current layer (\ref setCurrentLayer), the layer below (or above, if bottom layer) becomes the new current layer. - + It is not possible to remove the last layer of the plot. - + \see layer, addLayer, moveLayer */ bool QCustomPlot::removeLayer(QCPLayer *layer) { - if (!mLayers.contains(layer)) - { - qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast(layer); - return false; - } - if (mLayers.size() < 2) - { - qDebug() << Q_FUNC_INFO << "can't remove last layer"; - return false; - } - - // append all children of this layer to layer below (if this is lowest layer, prepend to layer above) - int removedIndex = layer->index(); - bool isFirstLayer = removedIndex==0; - QCPLayer *targetLayer = isFirstLayer ? mLayers.at(removedIndex+1) : mLayers.at(removedIndex-1); - QList children = layer->children(); - if (isFirstLayer) // prepend in reverse order (so order relative to each other stays the same) - { - for (int i=children.size()-1; i>=0; --i) - children.at(i)->moveToLayer(targetLayer, true); - } else // append normally - { - for (int i=0; imoveToLayer(targetLayer, false); - } - // 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); - updateLayerIndices(); - return true; + if (!mLayers.contains(layer)) { + qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast(layer); + return false; + } + if (mLayers.size() < 2) { + qDebug() << Q_FUNC_INFO << "can't remove last layer"; + return false; + } + + // append all children of this layer to layer below (if this is lowest layer, prepend to layer above) + int removedIndex = layer->index(); + bool isFirstLayer = removedIndex == 0; + QCPLayer *targetLayer = isFirstLayer ? mLayers.at(removedIndex + 1) : mLayers.at(removedIndex - 1); + QList children = layer->children(); + if (isFirstLayer) { // prepend in reverse order (so order relative to each other stays the same) + for (int i = children.size() - 1; i >= 0; --i) { + children.at(i)->moveToLayer(targetLayer, true); + } + } else { // append normally + for (int i = 0; i < children.size(); ++i) { + children.at(i)->moveToLayer(targetLayer, false); + } + } + // 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); + updateLayerIndices(); + return true; } /*! Moves the specified \a layer either above or below \a otherLayer. Whether it's placed above or below is controlled with \a insertMode. - + Returns true on success, i.e. when both \a layer and \a otherLayer are valid layers in the QCustomPlot. - + \see layer, addLayer, moveLayer */ bool QCustomPlot::moveLayer(QCPLayer *layer, QCPLayer *otherLayer, QCustomPlot::LayerInsertMode insertMode) { - if (!mLayers.contains(layer)) - { - qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast(layer); - return false; - } - if (!mLayers.contains(otherLayer)) - { - qDebug() << Q_FUNC_INFO << "otherLayer not a layer of this QCustomPlot:" << reinterpret_cast(otherLayer); - return false; - } - - 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; + if (!mLayers.contains(layer)) { + qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast(layer); + return false; + } + if (!mLayers.contains(otherLayer)) { + qDebug() << Q_FUNC_INFO << "otherLayer not a layer of this QCustomPlot:" << reinterpret_cast(otherLayer); + return false; + } + + 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; } /*! Returns the number of axis rects in the plot. - + All axis rects can be accessed via QCustomPlot::axisRect(). - + Initially, only one axis rect exists in the plot. - + \see axisRect, axisRects */ int QCustomPlot::axisRectCount() const { - return axisRects().size(); + return axisRects().size(); } /*! Returns the axis rect with \a index. - + Initially, only one axis rect (with index 0) exists in the plot. If multiple axis rects were added, all of them may be accessed with this function in a linear fashion (even when they are nested in a layout hierarchy or inside other axis rects via QCPAxisRect::insetLayout). - + The order of the axis rects is given by the fill order of the \ref QCPLayout that is holding them. For example, if the axis rects are in the top level grid layout (accessible via \ref QCustomPlot::plotLayout), they are ordered from left to right, top to bottom, if the layout's default \ref QCPLayoutGrid::setFillOrder "setFillOrder" of \ref QCPLayoutGrid::foColumnsFirst "foColumnsFirst" wasn't changed. - + If you want to access axis rects by their row and column index, use the layout interface. For example, use \ref QCPLayoutGrid::element of the top level grid layout, and \c qobject_cast the returned layout element to \ref QCPAxisRect. (See also \ref thelayoutsystem.) - + \see axisRectCount, axisRects, QCPLayoutGrid::setFillOrder */ QCPAxisRect *QCustomPlot::axisRect(int index) const { - const QList rectList = axisRects(); - if (index >= 0 && index < rectList.size()) - { - return rectList.at(index); - } else - { - qDebug() << Q_FUNC_INFO << "invalid axis rect index" << index; - return 0; - } + const QList rectList = axisRects(); + if (index >= 0 && index < rectList.size()) { + return rectList.at(index); + } else { + qDebug() << Q_FUNC_INFO << "invalid axis rect index" << index; + return 0; + } } /*! Returns all axis rects in the plot. - + The order of the axis rects is given by the fill order of the \ref QCPLayout that is holding them. For example, if the axis rects are in the top level grid layout (accessible via \ref QCustomPlot::plotLayout), they are ordered from left to right, top to bottom, if the layout's default \ref QCPLayoutGrid::setFillOrder "setFillOrder" of \ref QCPLayoutGrid::foColumnsFirst "foColumnsFirst" wasn't changed. - + \see axisRectCount, axisRect, QCPLayoutGrid::setFillOrder */ -QList QCustomPlot::axisRects() const +QList QCustomPlot::axisRects() const { - QList result; - QStack elementStack; - if (mPlotLayout) - elementStack.push(mPlotLayout); - - while (!elementStack.isEmpty()) - { - foreach (QCPLayoutElement *element, elementStack.pop()->elements(false)) - { - if (element) - { - elementStack.push(element); - if (QCPAxisRect *ar = qobject_cast(element)) - result.append(ar); - } + QList result; + QStack elementStack; + if (mPlotLayout) { + elementStack.push(mPlotLayout); } - } - - return result; + + while (!elementStack.isEmpty()) { + foreach (QCPLayoutElement *element, elementStack.pop()->elements(false)) { + if (element) { + elementStack.push(element); + if (QCPAxisRect *ar = qobject_cast(element)) { + result.append(ar); + } + } + } + } + + return result; } /*! Returns the layout element at pixel position \a pos. If there is no element at that position, returns 0. - + Only visible elements are used. If \ref QCPLayoutElement::setVisible on the element itself or on any of its parent elements is set to false, it will not be considered. - + \see itemAt, plottableAt */ QCPLayoutElement *QCustomPlot::layoutElementAt(const QPointF &pos) const { - 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; - break; - } + 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; + break; + } + } } - } - return currentElement; + return currentElement; } /*! @@ -14300,99 +14371,96 @@ QCPLayoutElement *QCustomPlot::layoutElementAt(const QPointF &pos) const */ 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; - } + 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; + return result; } /*! Returns the axes that currently have selected parts, i.e. whose selection state is not \ref QCPAxis::spNone. - + \see selectedPlottables, selectedLegends, setInteractions, QCPAxis::setSelectedParts, QCPAxis::setSelectableParts */ -QList QCustomPlot::selectedAxes() const +QList QCustomPlot::selectedAxes() const { - QList result, allAxes; - foreach (QCPAxisRect *rect, axisRects()) - allAxes << rect->axes(); - - foreach (QCPAxis *axis, allAxes) - { - if (axis->selectedParts() != QCPAxis::spNone) - result.append(axis); - } - - return result; + QList result, allAxes; + foreach (QCPAxisRect *rect, axisRects()) { + allAxes << rect->axes(); + } + + foreach (QCPAxis *axis, allAxes) { + if (axis->selectedParts() != QCPAxis::spNone) { + result.append(axis); + } + } + + return result; } /*! Returns the legends that currently have selected parts, i.e. whose selection state is not \ref QCPLegend::spNone. - + \see selectedPlottables, selectedAxes, setInteractions, QCPLegend::setSelectedParts, QCPLegend::setSelectableParts, QCPLegend::selectedItems */ -QList QCustomPlot::selectedLegends() const +QList QCustomPlot::selectedLegends() const { - QList result; - - QStack elementStack; - if (mPlotLayout) - elementStack.push(mPlotLayout); - - while (!elementStack.isEmpty()) - { - foreach (QCPLayoutElement *subElement, elementStack.pop()->elements(false)) - { - if (subElement) - { - elementStack.push(subElement); - if (QCPLegend *leg = qobject_cast(subElement)) - { - if (leg->selectedParts() != QCPLegend::spNone) - result.append(leg); - } - } + QList result; + + QStack elementStack; + if (mPlotLayout) { + elementStack.push(mPlotLayout); } - } - - return result; + + while (!elementStack.isEmpty()) { + foreach (QCPLayoutElement *subElement, elementStack.pop()->elements(false)) { + if (subElement) { + elementStack.push(subElement); + if (QCPLegend *leg = qobject_cast(subElement)) { + if (leg->selectedParts() != QCPLegend::spNone) { + result.append(leg); + } + } + } + } + } + + return result; } /*! Deselects all layerables (plottables, items, axes, legends,...) of the QCustomPlot. - + Since calling this function is not a user interaction, this does not emit the \ref selectionChangedByUser signal. The individual selectionChanged signals are emitted though, if the objects were previously selected. - + \see setInteractions, selectedPlottables, selectedItems, selectedAxes, selectedLegends */ void QCustomPlot::deselectAll() { - foreach (QCPLayer *layer, mLayers) - { - foreach (QCPLayerable *layerable, layer->children()) - layerable->deselectEvent(0); - } + foreach (QCPLayer *layer, mLayers) { + foreach (QCPLayerable *layerable, layer->children()) { + layerable->deselectEvent(0); + } + } } /*! @@ -14422,55 +14490,59 @@ void QCustomPlot::deselectAll() */ void QCustomPlot::replot(QCustomPlot::RefreshPriority refreshPriority) { - if (refreshPriority == QCustomPlot::rpQueuedReplot) - { - if (!mReplotQueued) - { - mReplotQueued = true; - QTimer::singleShot(0, this, SLOT(replot())); + if (refreshPriority == QCustomPlot::rpQueuedReplot) { + if (!mReplotQueued) { + mReplotQueued = true; + QTimer::singleShot(0, this, SLOT(replot())); + } + return; } - return; - } - - if (mReplotting) // incase signals loop back to replot slot - return; - mReplotting = true; - mReplotQueued = false; - emit beforeReplot(); - - 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; + + if (mReplotting) { // incase signals loop back to replot slot + return; + } + mReplotting = true; + mReplotQueued = false; + emit beforeReplot(); + + updateLayout(); + // draw all layered objects (grid, axes, plottables, items, legend,...) into their buffers: + setupPaintBuffers(); + foreach (QCPLayer *layer, mLayers) { + layer->drawToPaintBuffer(); + } + for (int i = 0; i < mPaintBuffers.size(); ++i) { + mPaintBuffers.at(i)->setInvalidated(false); + } + + if ((refreshPriority == rpRefreshHint && mPlottingHints.testFlag(QCP::phImmediateRefresh)) || refreshPriority == rpImmediateRefresh) { + repaint(); + } else { + update(); + } + + emit afterReplot(); + mReplotting = false; } /*! Rescales the axes such that all plottables (like graphs) in the plot are fully visible. - + if \a onlyVisiblePlottables is set to true, only the plottables that have their visibility set to true (QCPLayerable::setVisible), will be used to rescale the axes. - + \see QCPAbstractPlottable::rescaleAxes, QCPAxis::rescale */ void QCustomPlot::rescaleAxes(bool onlyVisiblePlottables) { - QList allAxes; - foreach (QCPAxisRect *rect, axisRects()) - allAxes << rect->axes(); - - foreach (QCPAxis *axis, allAxes) - axis->rescale(onlyVisiblePlottables); + QList allAxes; + foreach (QCPAxisRect *rect, axisRects()) { + allAxes << rect->axes(); + } + + foreach (QCPAxis *axis, allAxes) { + axis->rescale(onlyVisiblePlottables); + } } /*! @@ -14512,65 +14584,63 @@ void QCustomPlot::rescaleAxes(bool onlyVisiblePlottables) */ bool QCustomPlot::savePdf(const QString &fileName, int width, int height, QCP::ExportPen exportPen, const QString &pdfCreator, const QString &pdfTitle) { - bool success = false; + bool success = false; #ifdef QT_NO_PRINTER - Q_UNUSED(fileName) - Q_UNUSED(exportPen) - Q_UNUSED(width) - Q_UNUSED(height) - Q_UNUSED(pdfCreator) - Q_UNUSED(pdfTitle) - qDebug() << Q_FUNC_INFO << "Qt was built without printer support (QT_NO_PRINTER). PDF not created."; + Q_UNUSED(fileName) + Q_UNUSED(exportPen) + Q_UNUSED(width) + Q_UNUSED(height) + Q_UNUSED(pdfCreator) + Q_UNUSED(pdfTitle) + qDebug() << Q_FUNC_INFO << "Qt was built without printer support (QT_NO_PRINTER). PDF not created."; #else - int newWidth, newHeight; - if (width == 0 || height == 0) - { - newWidth = this->width(); - newHeight = this->height(); - } else - { - newWidth = width; - newHeight = height; - } - - QPrinter printer(QPrinter::ScreenResolution); - printer.setOutputFileName(fileName); - printer.setOutputFormat(QPrinter::PdfFormat); - printer.setColorMode(QPrinter::Color); - printer.printEngine()->setProperty(QPrintEngine::PPK_Creator, pdfCreator); - printer.printEngine()->setProperty(QPrintEngine::PPK_DocumentName, pdfTitle); - QRect oldViewport = viewport(); - setViewport(QRect(0, 0, newWidth, newHeight)); + int newWidth, newHeight; + if (width == 0 || height == 0) { + newWidth = this->width(); + newHeight = this->height(); + } else { + newWidth = width; + newHeight = height; + } + + QPrinter printer(QPrinter::ScreenResolution); + printer.setOutputFileName(fileName); + printer.setOutputFormat(QPrinter::PdfFormat); + printer.setColorMode(QPrinter::Color); + printer.printEngine()->setProperty(QPrintEngine::PPK_Creator, pdfCreator); + printer.printEngine()->setProperty(QPrintEngine::PPK_DocumentName, pdfTitle); + QRect oldViewport = viewport(); + setViewport(QRect(0, 0, newWidth, newHeight)); #if QT_VERSION < QT_VERSION_CHECK(5, 3, 0) - printer.setFullPage(true); - printer.setPaperSize(viewport().size(), QPrinter::DevicePixel); + printer.setFullPage(true); + printer.setPaperSize(viewport().size(), QPrinter::DevicePixel); #else - QPageLayout pageLayout; - pageLayout.setMode(QPageLayout::FullPageMode); - pageLayout.setOrientation(QPageLayout::Portrait); - pageLayout.setMargins(QMarginsF(0, 0, 0, 0)); - pageLayout.setPageSize(QPageSize(viewport().size(), QPageSize::Point, QString(), QPageSize::ExactMatch)); - printer.setPageLayout(pageLayout); + QPageLayout pageLayout; + pageLayout.setMode(QPageLayout::FullPageMode); + pageLayout.setOrientation(QPageLayout::Portrait); + pageLayout.setMargins(QMarginsF(0, 0, 0, 0)); + pageLayout.setPageSize(QPageSize(viewport().size(), QPageSize::Point, QString(), QPageSize::ExactMatch)); + printer.setPageLayout(pageLayout); #endif - QCPPainter printpainter; - if (printpainter.begin(&printer)) - { - printpainter.setMode(QCPPainter::pmVectorized); - printpainter.setMode(QCPPainter::pmNoCaching); - printpainter.setMode(QCPPainter::pmNonCosmetic, exportPen==QCP::epNoCosmetic); - printpainter.setWindow(mViewport); - if (mBackgroundBrush.style() != Qt::NoBrush && - mBackgroundBrush.color() != Qt::white && - mBackgroundBrush.color() != Qt::transparent && - mBackgroundBrush.color().alpha() > 0) // draw pdf background color if not white/transparent - printpainter.fillRect(viewport(), mBackgroundBrush); - draw(&printpainter); - printpainter.end(); - success = true; - } - setViewport(oldViewport); + QCPPainter printpainter; + if (printpainter.begin(&printer)) { + printpainter.setMode(QCPPainter::pmVectorized); + printpainter.setMode(QCPPainter::pmNoCaching); + printpainter.setMode(QCPPainter::pmNonCosmetic, exportPen == QCP::epNoCosmetic); + printpainter.setWindow(mViewport); + if (mBackgroundBrush.style() != Qt::NoBrush && + mBackgroundBrush.color() != Qt::white && + mBackgroundBrush.color() != Qt::transparent && + mBackgroundBrush.color().alpha() > 0) { // draw pdf background color if not white/transparent + printpainter.fillRect(viewport(), mBackgroundBrush); + } + draw(&printpainter); + printpainter.end(); + success = true; + } + setViewport(oldViewport); #endif // QT_NO_PRINTER - return success; + return success; } /*! @@ -14620,7 +14690,7 @@ bool QCustomPlot::savePdf(const QString &fileName, int width, int height, QCP::E */ 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); + return saveRastered(fileName, width, height, scale, "PNG", quality, resolution, resolutionUnit); } /*! @@ -14667,7 +14737,7 @@ bool QCustomPlot::savePng(const QString &fileName, int width, int height, double */ 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, resolution, resolutionUnit); + return saveRastered(fileName, width, height, scale, "JPG", quality, resolution, resolutionUnit); } /*! @@ -14711,11 +14781,11 @@ bool QCustomPlot::saveJpg(const QString &fileName, int width, int height, double */ bool QCustomPlot::saveBmp(const QString &fileName, int width, int height, double scale, int resolution, QCP::ResolutionUnit resolutionUnit) { - return saveRastered(fileName, width, height, scale, "BMP", -1, resolution, resolutionUnit); + return saveRastered(fileName, width, height, scale, "BMP", -1, resolution, resolutionUnit); } /*! \internal - + Returns a minimum size hint that corresponds to the minimum size of the top level layout (\ref plotLayout). To prevent QCustomPlot from being collapsed to size/width zero, set a minimum size (setMinimumSize) either on the whole QCustomPlot or on any layout elements inside the plot. @@ -14724,176 +14794,173 @@ bool QCustomPlot::saveBmp(const QString &fileName, int width, int height, double */ QSize QCustomPlot::minimumSizeHint() const { - return mPlotLayout->minimumOuterSizeHint(); + return mPlotLayout->minimumOuterSizeHint(); } /*! \internal - + Returns a size hint that is the same as \ref minimumSizeHint. - + */ QSize QCustomPlot::sizeHint() const { - return mPlotLayout->minimumOuterSizeHint(); + return mPlotLayout->minimumOuterSizeHint(); } /*! \internal - + Event handler for when the QCustomPlot widget needs repainting. This does not cause a \ref replot, but draws the internal buffer on the widget surface. */ void QCustomPlot::paintEvent(QPaintEvent *event) { - Q_UNUSED(event); - 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); - } + Q_UNUSED(event); + 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. 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: - setViewport(rect()); - replot(rpQueuedRefresh); // queued refresh is important here, to prevent painting issues in some contexts (e.g. MDI subwindow) + Q_UNUSED(event) + // resize and repaint the buffer: + setViewport(rect()); + 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 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(); - - // 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; iaccept(); // default impl of QCPLayerable's mouse events ignore the event, in that case propagate to next candidate in list - candidates.at(i)->mouseDoubleClickEvent(event, details.at(i)); - if (event->isAccepted()) - { - mMouseEventLayerable = candidates.at(i); - mMouseEventLayerableDetails = details.at(i); - break; + emit mouseDoubleClick(event); + mMouseHasMoved = false; + mMousePressPos = event->pos(); + + // 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; i < candidates.size(); ++i) { + event->accept(); // default impl of QCPLayerable's mouse events ignore the event, in that case propagate to next candidate in list + candidates.at(i)->mouseDoubleClickEvent(event, details.at(i)); + if (event->isAccepted()) { + mMouseEventLayerable = candidates.at(i); + mMouseEventLayerableDetails = details.at(i); + break; + } } - } - - // emit specialized object double click signals: - if (!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. + + // 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. 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); - // save some state to tell in releaseEvent whether it was a click: - mMouseHasMoved = false; - mMousePressPos = event->pos(); - - 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, prepare for click signal emission and forward event to layerable under the cursor: - QList details; - QList candidates = layerableListAt(mMousePressPos, false, &details); - if (!candidates.isEmpty()) - { - mMouseSignalLayerable = candidates.first(); // candidate for signal emission is always topmost hit layerable (signal emitted in release event) - mMouseSignalLayerableDetails = details.first(); + emit mousePress(event); + // save some state to tell in releaseEvent whether it was a click: + mMouseHasMoved = false; + mMousePressPos = event->pos(); + + 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, prepare for click signal emission and forward event to layerable under the cursor: + QList details; + QList candidates = layerableListAt(mMousePressPos, false, &details); + if (!candidates.isEmpty()) { + mMouseSignalLayerable = candidates.first(); // candidate for signal emission is always topmost hit layerable (signal emitted in release event) + mMouseSignalLayerableDetails = details.first(); + } + // forward event to topmost candidate which accepts the event: + for (int i = 0; i < candidates.size(); ++i) { + event->accept(); // default impl of QCPLayerable's mouse events call ignore() on 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; + } + } } - // forward event to topmost candidate which accepts the event: - for (int i=0; iaccept(); // default impl of QCPLayerable's mouse events call ignore() on 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; - } - } - } - - event->accept(); // in case QCPLayerable reimplementation manipulates event accepted state. In QWidget event system, QCustomPlot wants to accept the 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 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); - - 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. + emit mouseMove(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 @@ -14912,51 +14979,51 @@ void QCustomPlot::mouseMoveEvent(QMouseEvent *event) */ void QCustomPlot::mouseReleaseEvent(QMouseEvent *event) { - emit mouseRelease(event); - - 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) - processPointSelection(event); - - // emit specialized click signals of QCustomPlot instance: - if (QCPAbstractPlottable *ap = qobject_cast(mMouseSignalLayerable)) - { - int dataIndex = 0; - if (!mMouseSignalLayerableDetails.value().isEmpty()) - dataIndex = mMouseSignalLayerableDetails.value().dataRange().begin(); - emit plottableClick(ap, dataIndex, event); - } else if (QCPAxis *ax = qobject_cast(mMouseSignalLayerable)) - emit axisClick(ax, mMouseSignalLayerableDetails.value(), event); - else if (QCPAbstractItem *ai = qobject_cast(mMouseSignalLayerable)) - emit itemClick(ai, event); - else if (QCPLegend *lg = qobject_cast(mMouseSignalLayerable)) - emit legendClick(lg, 0, event); - else if (QCPAbstractLegendItem *li = qobject_cast(mMouseSignalLayerable)) - emit legendClick(li->parentLegend(), li, event); - mMouseSignalLayerable = 0; - } - - if (mSelectionRect && mSelectionRect->isActive()) // Note: if a click was detected above, the selection rect is canceled there - { - // finish selection rect, the appropriate action will be taken via signal-slot connection: - mSelectionRect->endSelection(event); - } else - { - // call event of affected layerable: - if (mMouseEventLayerable) - { - mMouseEventLayerable->mouseReleaseEvent(event, mMousePressPos); - mMouseEventLayerable = 0; + emit mouseRelease(event); + + 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) { + processPointSelection(event); + } + + // emit specialized click signals of QCustomPlot instance: + if (QCPAbstractPlottable *ap = qobject_cast(mMouseSignalLayerable)) { + int dataIndex = 0; + if (!mMouseSignalLayerableDetails.value().isEmpty()) { + dataIndex = mMouseSignalLayerableDetails.value().dataRange().begin(); + } + emit plottableClick(ap, dataIndex, event); + } else if (QCPAxis *ax = qobject_cast(mMouseSignalLayerable)) { + emit axisClick(ax, mMouseSignalLayerableDetails.value(), event); + } else if (QCPAbstractItem *ai = qobject_cast(mMouseSignalLayerable)) { + emit itemClick(ai, event); + } else if (QCPLegend *lg = qobject_cast(mMouseSignalLayerable)) { + emit legendClick(lg, 0, event); + } else if (QCPAbstractLegendItem *li = qobject_cast(mMouseSignalLayerable)) { + emit legendClick(li->parentLegend(), li, event); + } + mMouseSignalLayerable = 0; } - } - - if (noAntialiasingOnDrag()) - replot(rpQueuedReplot); - - event->accept(); // in case QCPLayerable reimplementation manipulates event accepted state. In QWidget event system, QCustomPlot wants to accept the event. + + if (mSelectionRect && mSelectionRect->isActive()) { // Note: if a click was detected above, the selection rect is canceled there + // finish selection rect, the appropriate action will be taken via signal-slot connection: + mSelectionRect->endSelection(event); + } else { + // call event of affected layerable: + if (mMouseEventLayerable) { + mMouseEventLayerable->mouseReleaseEvent(event, mMousePressPos); + mMouseEventLayerable = 0; + } + } + + if (noAntialiasingOnDrag()) { + replot(rpQueuedReplot); + } + + event->accept(); // in case QCPLayerable reimplementation manipulates event accepted state. In QWidget event system, QCustomPlot wants to accept the event. } /*! \internal @@ -14966,21 +15033,21 @@ void QCustomPlot::mouseReleaseEvent(QMouseEvent *event) */ void QCustomPlot::wheelEvent(QWheelEvent *event) { - emit mouseWheel(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. + emit mouseWheel(event); + // forward event to layerable under cursor: + QList candidates = layerableListAt(event->pos(), false); + for (int i = 0; i < candidates.size(); ++i) { + event->accept(); // default impl of QCPLayerable's mouse events ignore the event, in that case propagate to next candidate in list + candidates.at(i)->wheelEvent(event); + if (event->isAccepted()) { + break; + } + } + event->accept(); // in case QCPLayerable reimplementation manipulates event accepted state. In QWidget event system, QCustomPlot wants to accept the event. } /*! \internal - + This 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. @@ -14991,25 +15058,26 @@ void QCustomPlot::wheelEvent(QWheelEvent *event) */ void QCustomPlot::draw(QCPPainter *painter) { - updateLayout(); - - // draw viewport background pixmap: - drawBackground(painter); + updateLayout(); - // draw all layered objects (grid, axes, plottables, items, legend,...): - foreach (QCPLayer *layer, mLayers) - layer->draw(painter); - - /* Debug code to draw all layout element rects - foreach (QCPLayoutElement* el, findChildren()) - { - painter->setBrush(Qt::NoBrush); - painter->setPen(QPen(QColor(0, 0, 0, 100), 0, Qt::DashLine)); - painter->drawRect(el->rect()); - painter->setPen(QPen(QColor(255, 0, 0, 100), 0, Qt::DashLine)); - painter->drawRect(el->outerRect()); - } - */ + // draw viewport background pixmap: + drawBackground(painter); + + // draw all layered objects (grid, axes, plottables, items, legend,...): + foreach (QCPLayer *layer, mLayers) { + layer->draw(painter); + } + + /* Debug code to draw all layout element rects + foreach (QCPLayoutElement* el, findChildren()) + { + painter->setBrush(Qt::NoBrush); + painter->setPen(QPen(QColor(0, 0, 0, 100), 0, Qt::DashLine)); + painter->drawRect(el->rect()); + painter->setPen(QPen(QColor(255, 0, 0, 100), 0, Qt::DashLine)); + painter->drawRect(el->outerRect()); + } + */ } /*! \internal @@ -15022,16 +15090,16 @@ void QCustomPlot::draw(QCPPainter *painter) */ void QCustomPlot::updateLayout() { - // run through layout phases: - mPlotLayout->update(QCPLayoutElement::upPreparation); - mPlotLayout->update(QCPLayoutElement::upMargins); - mPlotLayout->update(QCPLayoutElement::upLayout); + // 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. - + If a pixmap was provided via \ref setBackground, this function buffers the scaled version depending on \ref setBackgroundScaled and \ref setBackgroundScaledMode and then draws it inside the viewport with the provided \a painter. The scaled version is buffered in @@ -15039,32 +15107,30 @@ void QCustomPlot::updateLayout() the axis rect has changed in a way that requires a rescale of the background pixmap (this is 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. - + \see setBackground, setBackgroundScaled, setBackgroundScaledMode */ void QCustomPlot::drawBackground(QCPPainter *painter) { - // Note: background color is handled in individual replot/save functions + // Note: background color is handled in individual replot/save functions - // draw background pixmap (on top of fill, if brush specified): - if (!mBackgroundPixmap.isNull()) - { - if (mBackgroundScaled) - { - // check whether mScaledBackground needs to be updated: - QSize scaledSize(mBackgroundPixmap.size()); - scaledSize.scale(mViewport.size(), mBackgroundScaledMode); - if (mScaledBackgroundPixmap.size() != scaledSize) - mScaledBackgroundPixmap = mBackgroundPixmap.scaled(mViewport.size(), mBackgroundScaledMode, Qt::SmoothTransformation); - painter->drawPixmap(mViewport.topLeft(), mScaledBackgroundPixmap, QRect(0, 0, mViewport.width(), mViewport.height()) & mScaledBackgroundPixmap.rect()); - } else - { - painter->drawPixmap(mViewport.topLeft(), mBackgroundPixmap, QRect(0, 0, mViewport.width(), mViewport.height())); + // draw background pixmap (on top of fill, if brush specified): + if (!mBackgroundPixmap.isNull()) { + if (mBackgroundScaled) { + // check whether mScaledBackground needs to be updated: + QSize scaledSize(mBackgroundPixmap.size()); + scaledSize.scale(mViewport.size(), mBackgroundScaledMode); + if (mScaledBackgroundPixmap.size() != scaledSize) { + mScaledBackgroundPixmap = mBackgroundPixmap.scaled(mViewport.size(), mBackgroundScaledMode, Qt::SmoothTransformation); + } + painter->drawPixmap(mViewport.topLeft(), mScaledBackgroundPixmap, QRect(0, 0, mViewport.width(), mViewport.height()) & mScaledBackgroundPixmap.rect()); + } else { + painter->drawPixmap(mViewport.topLeft(), mBackgroundPixmap, QRect(0, 0, mViewport.width(), mViewport.height())); + } } - } } /*! \internal @@ -15088,40 +15154,39 @@ void QCustomPlot::drawBackground(QCPPainter *painter) */ 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()) + int bufferIndex = 0; + if (mPaintBuffers.isEmpty()) { 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(); - } + + 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; i < mPaintBuffers.size(); ++i) { + mPaintBuffers.at(i)->setSize(viewport().size()); // won't do anything if already correct size + mPaintBuffers.at(i)->clear(Qt::transparent); + mPaintBuffers.at(i)->setInvalidated(); + } } /*! \internal @@ -15134,18 +15199,18 @@ void QCustomPlot::setupPaintBuffers() */ QCPAbstractPaintBuffer *QCustomPlot::createPaintBuffer() { - if (mOpenGl) - { + if (mOpenGl) { #if defined(QCP_OPENGL_FBO) - return new QCPPaintBufferGlFbo(viewport().size(), mBufferDevicePixelRatio, mGlContext, mGlPaintDevice); + return new QCPPaintBufferGlFbo(viewport().size(), mBufferDevicePixelRatio, mGlContext, mGlPaintDevice); #elif defined(QCP_OPENGL_PBUFFER) - return new QCPPaintBufferGlPbuffer(viewport().size(), mBufferDevicePixelRatio, mOpenGlMultisamples); + 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); + 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); + } else { + return new QCPPaintBufferPixmap(viewport().size(), mBufferDevicePixelRatio); + } } /*! @@ -15161,12 +15226,12 @@ QCPAbstractPaintBuffer *QCustomPlot::createPaintBuffer() */ bool QCustomPlot::hasInvalidatedPaintBuffers() { - for (int i=0; iinvalidated()) - return true; - } - return false; + for (int i = 0; i < mPaintBuffers.size(); ++i) { + if (mPaintBuffers.at(i)->invalidated()) { + return true; + } + } + return false; } /*! \internal @@ -15185,47 +15250,44 @@ bool QCustomPlot::hasInvalidatedPaintBuffers() bool QCustomPlot::setupOpenGl() { #ifdef QCP_OPENGL_FBO - freeOpenGl(); - QSurfaceFormat proposedSurfaceFormat; - proposedSurfaceFormat.setSamples(mOpenGlMultisamples); + freeOpenGl(); + QSurfaceFormat proposedSurfaceFormat; + proposedSurfaceFormat.setSamples(mOpenGlMultisamples); #ifdef QCP_OPENGL_OFFSCREENSURFACE - QOffscreenSurface *surface = new QOffscreenSurface; + QOffscreenSurface *surface = new QOffscreenSurface; #else - QWindow *surface = new QWindow; - surface->setSurfaceType(QSurface::OpenGLSurface); + 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; + 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(); + return QGLFormat::hasOpenGL(); #else - return false; + return false; #endif } @@ -15243,44 +15305,49 @@ bool QCustomPlot::setupOpenGl() void QCustomPlot::freeOpenGl() { #ifdef QCP_OPENGL_FBO - mGlPaintDevice.clear(); - mGlContext.clear(); - mGlSurface.clear(); + mGlPaintDevice.clear(); + mGlContext.clear(); + mGlSurface.clear(); #endif } /*! \internal - + This method is used by \ref QCPAxisRect::removeAxis to report removed axes to the QCustomPlot so it may clear its QCustomPlot::xAxis, yAxis, xAxis2 and yAxis2 members accordingly. */ void QCustomPlot::axisRemoved(QCPAxis *axis) { - if (xAxis == axis) - xAxis = 0; - if (xAxis2 == axis) - xAxis2 = 0; - if (yAxis == axis) - yAxis = 0; - if (yAxis2 == axis) - yAxis2 = 0; - - // Note: No need to take care of range drag axes and range zoom axes, because they are stored in smart pointers + if (xAxis == axis) { + xAxis = 0; + } + if (xAxis2 == axis) { + xAxis2 = 0; + } + if (yAxis == axis) { + yAxis = 0; + } + if (yAxis2 == axis) { + yAxis2 = 0; + } + + // Note: No need to take care of range drag axes and range zoom axes, because they are stored in smart pointers } /*! \internal - + This method is used by the QCPLegend destructor to report legend removal to the QCustomPlot so it may clear its QCustomPlot::legend member accordingly. */ void QCustomPlot::legendRemoved(QCPLegend *legend) { - if (this->legend == legend) - this->legend = 0; + if (this->legend == 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. @@ -15288,109 +15355,98 @@ void QCustomPlot::legendRemoved(QCPLegend *legend) 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; + 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; + } } - } } - } - - // 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(); + + 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 + 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 @@ -15412,138 +15468,130 @@ void QCustomPlot::processRectZoom(QRect rect, QMouseEvent *event) */ 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; + 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); - } + 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; + 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; + 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; + 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 after every operation that changes the layer indices, like layer removal, layer creation, layer moving. */ void QCustomPlot::updateLayerIndices() const { - for (int i=0; imIndex = i; + for (int i = 0; i < mLayers.size(); ++i) { + mLayers.at(i)->mIndex = i; + } } /*! \internal @@ -15558,19 +15606,21 @@ void QCustomPlot::updateLayerIndices() const 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 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; + 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 @@ -15588,30 +15638,29 @@ QCPLayerable *QCustomPlot::layerableAt(const QPointF &pos, bool onlySelectable, 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 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(); - 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, selectionDetails ? &details : 0); - if (dist >= 0 && dist < selectionTolerance()) - { - result.append(layerables.at(i)); - if (selectionDetails) - selectionDetails->append(details); - } + QList result; + for (int layerIndex = mLayers.size() - 1; layerIndex >= 0; --layerIndex) { + const QList layerables = mLayers.at(layerIndex)->children(); + 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, selectionDetails ? &details : 0); + if (dist >= 0 && dist < selectionTolerance()) { + result.append(layerables.at(i)); + if (selectionDetails) { + selectionDetails->append(details); + } + } + } } - } - return result; + return result; } /*! @@ -15634,112 +15683,114 @@ QList QCustomPlot::layerableListAt(const QPointF &pos, bool onlyS */ bool QCustomPlot::saveRastered(const QString &fileName, int width, int height, double scale, const char *format, int quality, int resolution, QCP::ResolutionUnit resolutionUnit) { - 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 - return false; + 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 { + return false; + } } /*! Renders the plot to a pixmap and returns it. - + The plot is 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 pixmap with width 200.) - + \see toPainter, saveRastered, saveBmp, savePng, saveJpg, savePdf */ QPixmap QCustomPlot::toPixmap(int width, int height, double scale) { - // this method is somewhat similar to toPainter. Change something here, and a change in toPainter might be necessary, too. - int newWidth, newHeight; - if (width == 0 || height == 0) - { - newWidth = this->width(); - newHeight = this->height(); - } else - { - newWidth = width; - newHeight = height; - } - int scaledWidth = qRound(scale*newWidth); - int scaledHeight = qRound(scale*newHeight); - - QPixmap result(scaledWidth, scaledHeight); - result.fill(mBackgroundBrush.style() == Qt::SolidPattern ? mBackgroundBrush.color() : Qt::transparent); // if using non-solid pattern, make transparent now and draw brush pattern later - QCPPainter painter; - painter.begin(&result); - if (painter.isActive()) - { - QRect oldViewport = viewport(); - setViewport(QRect(0, 0, newWidth, newHeight)); - painter.setMode(QCPPainter::pmNoCaching); - if (!qFuzzyCompare(scale, 1.0)) - { - if (scale > 1.0) // for scale < 1 we always want cosmetic pens where possible, because else lines might disappear for very small scales - painter.setMode(QCPPainter::pmNonCosmetic); - painter.scale(scale, scale); + // this method is somewhat similar to toPainter. Change something here, and a change in toPainter might be necessary, too. + int newWidth, newHeight; + if (width == 0 || height == 0) { + newWidth = this->width(); + newHeight = this->height(); + } else { + newWidth = width; + newHeight = height; } - if (mBackgroundBrush.style() != Qt::SolidPattern && mBackgroundBrush.style() != Qt::NoBrush) // solid fills were done a few lines above with QPixmap::fill - painter.fillRect(mViewport, mBackgroundBrush); - draw(&painter); - setViewport(oldViewport); - painter.end(); - } else // might happen if pixmap has width or height zero - { - qDebug() << Q_FUNC_INFO << "Couldn't activate painter on pixmap"; - return QPixmap(); - } - return result; + int scaledWidth = qRound(scale * newWidth); + int scaledHeight = qRound(scale * newHeight); + + QPixmap result(scaledWidth, scaledHeight); + result.fill(mBackgroundBrush.style() == Qt::SolidPattern ? mBackgroundBrush.color() : Qt::transparent); // if using non-solid pattern, make transparent now and draw brush pattern later + QCPPainter painter; + painter.begin(&result); + if (painter.isActive()) { + QRect oldViewport = viewport(); + setViewport(QRect(0, 0, newWidth, newHeight)); + painter.setMode(QCPPainter::pmNoCaching); + if (!qFuzzyCompare(scale, 1.0)) { + if (scale > 1.0) { // for scale < 1 we always want cosmetic pens where possible, because else lines might disappear for very small scales + painter.setMode(QCPPainter::pmNonCosmetic); + } + painter.scale(scale, scale); + } + if (mBackgroundBrush.style() != Qt::SolidPattern && mBackgroundBrush.style() != Qt::NoBrush) { // solid fills were done a few lines above with QPixmap::fill + painter.fillRect(mViewport, mBackgroundBrush); + } + draw(&painter); + setViewport(oldViewport); + painter.end(); + } else { // might happen if pixmap has width or height zero + qDebug() << Q_FUNC_INFO << "Couldn't activate painter on pixmap"; + return QPixmap(); + } + return result; } /*! Renders the plot using the passed \a painter. - + The plot is sized to \a width and \a height in pixels. If the \a painter's scale is not 1.0, the resulting plot will appear scaled accordingly. - + \note If you are restricted to using a QPainter (instead of QCPPainter), create a temporary QPicture and open a QCPPainter on it. Then call \ref toPainter with this QCPPainter. After ending the paint operation on the picture, draw it with the QPainter. This will reproduce the painter actions the QCPPainter took, with a QPainter. - + \see toPixmap */ void QCustomPlot::toPainter(QCPPainter *painter, int width, int height) { - // this method is somewhat similar to toPixmap. Change something here, and a change in toPixmap might be necessary, too. - int newWidth, newHeight; - if (width == 0 || height == 0) - { - newWidth = this->width(); - newHeight = this->height(); - } else - { - newWidth = width; - newHeight = height; - } + // this method is somewhat similar to toPixmap. Change something here, and a change in toPixmap might be necessary, too. + int newWidth, newHeight; + if (width == 0 || height == 0) { + newWidth = this->width(); + newHeight = this->height(); + } else { + newWidth = width; + newHeight = height; + } - if (painter->isActive()) - { - QRect oldViewport = viewport(); - setViewport(QRect(0, 0, newWidth, newHeight)); - painter->setMode(QCPPainter::pmNoCaching); - if (mBackgroundBrush.style() != Qt::NoBrush) // unlike in toPixmap, we can't do QPixmap::fill for Qt::SolidPattern brush style, so we also draw solid fills with fillRect here - painter->fillRect(mViewport, mBackgroundBrush); - draw(painter); - setViewport(oldViewport); - } else - qDebug() << Q_FUNC_INFO << "Passed painter is not active"; + if (painter->isActive()) { + QRect oldViewport = viewport(); + setViewport(QRect(0, 0, newWidth, newHeight)); + painter->setMode(QCPPainter::pmNoCaching); + if (mBackgroundBrush.style() != Qt::NoBrush) { // unlike in toPixmap, we can't do QPixmap::fill for Qt::SolidPattern brush style, so we also draw solid fills with fillRect here + painter->fillRect(mViewport, mBackgroundBrush); + } + draw(painter); + setViewport(oldViewport); + } else { + qDebug() << Q_FUNC_INFO << "Passed painter is not active"; + } } /* end of 'src/core.cpp' */ @@ -15755,7 +15806,7 @@ void QCustomPlot::toPainter(QCPPainter *painter, int width, int height) /*! \class QCPColorGradient \brief Defines a color gradient for use with e.g. \ref QCPColorMap - + This class describes a color gradient which can be used to encode data with color. For example, QCPColorMap and QCPColorScale have \ref QCPColorMap::setGradient "setGradient" methods which take an instance of this class. Colors are set with \ref setColorStopAt(double position, const QColor &color) @@ -15764,18 +15815,18 @@ 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 \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 color gradient shall be applied periodically (wrapping around) to data values that lie outside the data range specified on the plottable instance can be controlled with \ref setPeriodic. @@ -15788,12 +15839,12 @@ void QCustomPlot::toPainter(QCPPainter *painter, int width, int height) The color level count is initialized to 350. */ QCPColorGradient::QCPColorGradient() : - mLevelCount(350), - mColorInterpolation(ciRGB), - mPeriodic(false), - mColorBufferInvalidated(true) + mLevelCount(350), + mColorInterpolation(ciRGB), + mPeriodic(false), + mColorBufferInvalidated(true) { - mColorBuffer.fill(qRgb(0, 0, 0), mLevelCount); + mColorBuffer.fill(qRgb(0, 0, 0), mLevelCount); } /*! @@ -15803,22 +15854,22 @@ QCPColorGradient::QCPColorGradient() : The color level count is initialized to 350. */ QCPColorGradient::QCPColorGradient(GradientPreset preset) : - mLevelCount(350), - mColorInterpolation(ciRGB), - mPeriodic(false), - mColorBufferInvalidated(true) + mLevelCount(350), + mColorInterpolation(ciRGB), + mPeriodic(false), + mColorBufferInvalidated(true) { - mColorBuffer.fill(qRgb(0, 0, 0), mLevelCount); - loadPreset(preset); + mColorBuffer.fill(qRgb(0, 0, 0), mLevelCount); + loadPreset(preset); } /* undocumented operator */ bool QCPColorGradient::operator==(const QCPColorGradient &other) const { - return ((other.mLevelCount == this->mLevelCount) && - (other.mColorInterpolation == this->mColorInterpolation) && - (other.mPeriodic == this->mPeriodic) && - (other.mColorStops == this->mColorStops)); + return ((other.mLevelCount == this->mLevelCount) && + (other.mColorInterpolation == this->mColorInterpolation) && + (other.mPeriodic == this->mPeriodic) && + (other.mColorStops == this->mColorStops)); } /*! @@ -15829,85 +15880,82 @@ bool QCPColorGradient::operator==(const QCPColorGradient &other) const */ void QCPColorGradient::setLevelCount(int n) { - if (n < 2) - { - qDebug() << Q_FUNC_INFO << "n must be greater or equal 2 but was" << n; - n = 2; - } - if (n != mLevelCount) - { - mLevelCount = n; - mColorBufferInvalidated = true; - } + if (n < 2) { + qDebug() << Q_FUNC_INFO << "n must be greater or equal 2 but was" << n; + n = 2; + } + if (n != mLevelCount) { + mLevelCount = n; + mColorBufferInvalidated = true; + } } /*! Sets at which positions from 0 to 1 which color shall occur. The positions are the keys, the colors are the values of the passed QMap \a colorStops. In between these color stops, the color 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 (or creating a new, empty QCPColorGradient) and then adding them one by one with \ref setColorStopAt. - + \see clearColorStops */ void QCPColorGradient::setColorStops(const QMap &colorStops) { - mColorStops = colorStops; - mColorBufferInvalidated = true; + mColorStops = colorStops; + mColorBufferInvalidated = true; } /*! Sets the \a color the gradient will have at the specified \a position (from 0 to 1). In between these color stops, the color is interpolated according to \ref setColorInterpolation. - + \see setColorStops, clearColorStops */ void QCPColorGradient::setColorStopAt(double position, const QColor &color) { - mColorStops.insert(position, color); - mColorBufferInvalidated = true; + mColorStops.insert(position, color); + mColorBufferInvalidated = true; } /*! Sets whether the colors in between the configured color stops (see \ref setColorStopAt) shall be interpolated linearly in RGB or in HSV color space. - + For example, a sweep in RGB space from red to green will have a muddy brown intermediate color, whereas in HSV space the intermediate color is yellow. */ void QCPColorGradient::setColorInterpolation(QCPColorGradient::ColorInterpolation interpolation) { - if (interpolation != mColorInterpolation) - { - mColorInterpolation = interpolation; - mColorBufferInvalidated = true; - } + if (interpolation != mColorInterpolation) { + mColorInterpolation = interpolation; + mColorBufferInvalidated = true; + } } /*! Sets whether data points that are outside the configured data range (e.g. \ref QCPColorMap::setDataRange) are colored by periodically repeating the color gradient or whether they all have the same color, corresponding to the respective gradient boundary color. - + \image html QCPColorGradient-periodic.png - + As shown in the image above, gradients that have the same start and end color are especially suitable for a periodic gradient mapping, since they produce smooth color transitions throughout the color map. A preset that has this property is \ref gpHues. - + In practice, using periodic color gradients makes sense when the data corresponds to a periodic dimension, such as an angle or a phase. If this is not the case, the color encoding might become ambiguous, because multiple different data values are shown as the same color. */ void QCPColorGradient::setPeriodic(bool enabled) { - mPeriodic = 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 @@ -15918,7 +15966,7 @@ void QCPColorGradient::setPeriodic(bool enabled) 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 @@ -15926,68 +15974,61 @@ void QCPColorGradient::setPeriodic(bool enabled) */ 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() and the other colorize() overload - if (!data) - { - qDebug() << Q_FUNC_INFO << "null pointer given as data"; - 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; - scanLine[i] = mColorBuffer.at(index); - } + // 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; } - } else // logarithmic == true - { - if (mPeriodic) - { - for (int i=0; i= mLevelCount) - index = mLevelCount-1; - scanLine[i] = mColorBuffer.at(index); - } + if (!scanLine) { + qDebug() << Q_FUNC_INFO << "null pointer given as scanLine"; + return; + } + if (mColorBufferInvalidated) { + updateColorBuffer(); + } + + if (!logarithmic) { + const double posToIndexFactor = (mLevelCount - 1) / range.size(); + if (mPeriodic) { + for (int i = 0; i < n; ++i) { + int index = (int)((data[dataIndexFactor * i] - range.lower) * posToIndexFactor) % mLevelCount; + if (index < 0) { + index += mLevelCount; + } + scanLine[i] = mColorBuffer.at(index); + } + } else { + for (int i = 0; i < n; ++i) { + int index = (data[dataIndexFactor * i] - range.lower) * posToIndexFactor; + if (index < 0) { + index = 0; + } else if (index >= mLevelCount) { + index = mLevelCount - 1; + } + scanLine[i] = mColorBuffer.at(index); + } + } + } else { // logarithmic == true + if (mPeriodic) { + for (int i = 0; i < n; ++i) { + int index = (int)(qLn(data[dataIndexFactor * i] / range.lower) / qLn(range.upper / range.lower) * (mLevelCount - 1)) % mLevelCount; + if (index < 0) { + index += mLevelCount; + } + scanLine[i] = mColorBuffer.at(index); + } + } else { + for (int i = 0; i < n; ++i) { + int index = qLn(data[dataIndexFactor * i] / range.lower) / qLn(range.upper / range.lower) * (mLevelCount - 1); + if (index < 0) { + index = 0; + } else if (index >= mLevelCount) { + index = mLevelCount - 1; + } + scanLine[i] = mColorBuffer.at(index); + } + } } - } } /*! \overload @@ -16000,105 +16041,89 @@ void QCPColorGradient::colorize(const double *data, const QCPRange &range, QRgb */ 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); - } - } + // 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; } - } 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); - } - } + if (!alpha) { + qDebug() << Q_FUNC_INFO << "null pointer given as alpha"; + return; + } + if (!scanLine) { + qDebug() << Q_FUNC_INFO << "null pointer given as scanLine"; + return; + } + if (mColorBufferInvalidated) { + updateColorBuffer(); + } + + if (!logarithmic) { + const double posToIndexFactor = (mLevelCount - 1) / range.size(); + if (mPeriodic) { + for (int i = 0; i < n; ++i) { + int index = (int)((data[dataIndexFactor * i] - range.lower) * posToIndexFactor) % mLevelCount; + if (index < 0) { + index += mLevelCount; + } + if (alpha[dataIndexFactor * i] == 255) { + scanLine[i] = mColorBuffer.at(index); + } else { + const QRgb rgb = mColorBuffer.at(index); + const float alphaF = alpha[dataIndexFactor * i] / 255.0f; + scanLine[i] = qRgba(qRed(rgb) * alphaF, qGreen(rgb) * alphaF, qBlue(rgb) * alphaF, qAlpha(rgb) * alphaF); + } + } + } else { + for (int i = 0; i < n; ++i) { + int index = (data[dataIndexFactor * i] - range.lower) * posToIndexFactor; + if (index < 0) { + index = 0; + } else if (index >= mLevelCount) { + index = mLevelCount - 1; + } + if (alpha[dataIndexFactor * i] == 255) { + scanLine[i] = mColorBuffer.at(index); + } else { + const QRgb rgb = mColorBuffer.at(index); + const float alphaF = alpha[dataIndexFactor * i] / 255.0f; + scanLine[i] = qRgba(qRed(rgb) * alphaF, qGreen(rgb) * alphaF, qBlue(rgb) * alphaF, qAlpha(rgb) * alphaF); + } + } + } + } else { // logarithmic == true + if (mPeriodic) { + for (int i = 0; i < n; ++i) { + int index = (int)(qLn(data[dataIndexFactor * i] / range.lower) / qLn(range.upper / range.lower) * (mLevelCount - 1)) % mLevelCount; + if (index < 0) { + index += mLevelCount; + } + if (alpha[dataIndexFactor * i] == 255) { + scanLine[i] = mColorBuffer.at(index); + } else { + const QRgb rgb = mColorBuffer.at(index); + const float alphaF = alpha[dataIndexFactor * i] / 255.0f; + scanLine[i] = qRgba(qRed(rgb) * alphaF, qGreen(rgb) * alphaF, qBlue(rgb) * alphaF, qAlpha(rgb) * alphaF); + } + } + } else { + for (int i = 0; i < n; ++i) { + int index = qLn(data[dataIndexFactor * i] / range.lower) / qLn(range.upper / range.lower) * (mLevelCount - 1); + if (index < 0) { + index = 0; + } else if (index >= mLevelCount) { + index = mLevelCount - 1; + } + if (alpha[dataIndexFactor * i] == 255) { + scanLine[i] = mColorBuffer.at(index); + } else { + const QRgb rgb = mColorBuffer.at(index); + const float alphaF = alpha[dataIndexFactor * i] / 255.0f; + scanLine[i] = qRgba(qRed(rgb) * alphaF, qGreen(rgb) * alphaF, qBlue(rgb) * alphaF, qAlpha(rgb) * alphaF); + } + } + } } - } } /*! \internal @@ -16115,284 +16140,276 @@ void QCPColorGradient::colorize(const double *data, const unsigned char *alpha, */ QRgb QCPColorGradient::color(double position, const QCPRange &range, bool logarithmic) { - // If you change something here, make sure to also adapt ::colorize() - if (mColorBufferInvalidated) - updateColorBuffer(); - int index = 0; - if (!logarithmic) - index = (position-range.lower)*(mLevelCount-1)/range.size(); - else - index = qLn(position/range.lower)/qLn(range.upper/range.lower)*(mLevelCount-1); - if (mPeriodic) - { - index = index % mLevelCount; - if (index < 0) - index += mLevelCount; - } else - { - if (index < 0) - index = 0; - else if (index >= mLevelCount) - index = mLevelCount-1; - } - return mColorBuffer.at(index); + // If you change something here, make sure to also adapt ::colorize() + if (mColorBufferInvalidated) { + updateColorBuffer(); + } + int index = 0; + if (!logarithmic) { + index = (position - range.lower) * (mLevelCount - 1) / range.size(); + } else { + index = qLn(position / range.lower) / qLn(range.upper / range.lower) * (mLevelCount - 1); + } + if (mPeriodic) { + index = index % mLevelCount; + if (index < 0) { + index += mLevelCount; + } + } else { + if (index < 0) { + index = 0; + } else if (index >= mLevelCount) { + index = mLevelCount - 1; + } + } + return mColorBuffer.at(index); } /*! Clears the current color stops and loads the specified \a preset. A preset consists of predefined color stops and the corresponding color interpolation method. - + The available presets are: \image html QCPColorGradient.png */ void QCPColorGradient::loadPreset(GradientPreset preset) { - clearColorStops(); - switch (preset) - { - case gpGrayscale: - setColorInterpolation(ciRGB); - setColorStopAt(0, Qt::black); - setColorStopAt(1, Qt::white); - break; - case gpHot: - setColorInterpolation(ciRGB); - setColorStopAt(0, QColor(50, 0, 0)); - setColorStopAt(0.2, QColor(180, 10, 0)); - setColorStopAt(0.4, QColor(245, 50, 0)); - setColorStopAt(0.6, QColor(255, 150, 10)); - setColorStopAt(0.8, QColor(255, 255, 50)); - setColorStopAt(1, QColor(255, 255, 255)); - break; - case gpCold: - setColorInterpolation(ciRGB); - setColorStopAt(0, QColor(0, 0, 50)); - setColorStopAt(0.2, QColor(0, 10, 180)); - setColorStopAt(0.4, QColor(0, 50, 245)); - setColorStopAt(0.6, QColor(10, 150, 255)); - setColorStopAt(0.8, QColor(50, 255, 255)); - setColorStopAt(1, QColor(255, 255, 255)); - break; - case gpNight: - setColorInterpolation(ciHSV); - setColorStopAt(0, QColor(10, 20, 30)); - setColorStopAt(1, QColor(250, 255, 250)); - break; - case gpCandy: - setColorInterpolation(ciHSV); - setColorStopAt(0, QColor(0, 0, 255)); - setColorStopAt(1, QColor(255, 250, 250)); - break; - case gpGeography: - setColorInterpolation(ciRGB); - setColorStopAt(0, QColor(70, 170, 210)); - setColorStopAt(0.20, QColor(90, 160, 180)); - setColorStopAt(0.25, QColor(45, 130, 175)); - setColorStopAt(0.30, QColor(100, 140, 125)); - setColorStopAt(0.5, QColor(100, 140, 100)); - setColorStopAt(0.6, QColor(130, 145, 120)); - setColorStopAt(0.7, QColor(140, 130, 120)); - setColorStopAt(0.9, QColor(180, 190, 190)); - setColorStopAt(1, QColor(210, 210, 230)); - break; - case gpIon: - setColorInterpolation(ciHSV); - setColorStopAt(0, QColor(50, 10, 10)); - setColorStopAt(0.45, QColor(0, 0, 255)); - setColorStopAt(0.8, QColor(0, 255, 255)); - setColorStopAt(1, QColor(0, 255, 0)); - break; - case gpThermal: - setColorInterpolation(ciRGB); - setColorStopAt(0, QColor(0, 0, 50)); - setColorStopAt(0.15, QColor(20, 0, 120)); - setColorStopAt(0.33, QColor(200, 30, 140)); - setColorStopAt(0.6, QColor(255, 100, 0)); - setColorStopAt(0.85, QColor(255, 255, 40)); - setColorStopAt(1, QColor(255, 255, 255)); - break; - case gpPolar: - setColorInterpolation(ciRGB); - setColorStopAt(0, QColor(50, 255, 255)); - setColorStopAt(0.18, QColor(10, 70, 255)); - setColorStopAt(0.28, QColor(10, 10, 190)); - setColorStopAt(0.5, QColor(0, 0, 0)); - setColorStopAt(0.72, QColor(190, 10, 10)); - setColorStopAt(0.82, QColor(255, 70, 10)); - setColorStopAt(1, QColor(255, 255, 50)); - break; - case gpSpectrum: - setColorInterpolation(ciHSV); - setColorStopAt(0, QColor(50, 0, 50)); - setColorStopAt(0.15, QColor(0, 0, 255)); - setColorStopAt(0.35, QColor(0, 255, 255)); - setColorStopAt(0.6, QColor(255, 255, 0)); - setColorStopAt(0.75, QColor(255, 30, 0)); - setColorStopAt(1, QColor(50, 0, 0)); - break; - case gpJet: - setColorInterpolation(ciRGB); - setColorStopAt(0, QColor(0, 0, 100)); - setColorStopAt(0.15, QColor(0, 50, 255)); - setColorStopAt(0.35, QColor(0, 255, 255)); - setColorStopAt(0.65, QColor(255, 255, 0)); - setColorStopAt(0.85, QColor(255, 30, 0)); - setColorStopAt(1, QColor(100, 0, 0)); - break; - case gpHues: - setColorInterpolation(ciHSV); - setColorStopAt(0, QColor(255, 0, 0)); - setColorStopAt(1.0/3.0, QColor(0, 0, 255)); - setColorStopAt(2.0/3.0, QColor(0, 255, 0)); - setColorStopAt(1, QColor(255, 0, 0)); - break; - } + clearColorStops(); + switch (preset) { + case gpGrayscale: + setColorInterpolation(ciRGB); + setColorStopAt(0, Qt::black); + setColorStopAt(1, Qt::white); + break; + case gpHot: + setColorInterpolation(ciRGB); + setColorStopAt(0, QColor(50, 0, 0)); + setColorStopAt(0.2, QColor(180, 10, 0)); + setColorStopAt(0.4, QColor(245, 50, 0)); + setColorStopAt(0.6, QColor(255, 150, 10)); + setColorStopAt(0.8, QColor(255, 255, 50)); + setColorStopAt(1, QColor(255, 255, 255)); + break; + case gpCold: + setColorInterpolation(ciRGB); + setColorStopAt(0, QColor(0, 0, 50)); + setColorStopAt(0.2, QColor(0, 10, 180)); + setColorStopAt(0.4, QColor(0, 50, 245)); + setColorStopAt(0.6, QColor(10, 150, 255)); + setColorStopAt(0.8, QColor(50, 255, 255)); + setColorStopAt(1, QColor(255, 255, 255)); + break; + case gpNight: + setColorInterpolation(ciHSV); + setColorStopAt(0, QColor(10, 20, 30)); + setColorStopAt(1, QColor(250, 255, 250)); + break; + case gpCandy: + setColorInterpolation(ciHSV); + setColorStopAt(0, QColor(0, 0, 255)); + setColorStopAt(1, QColor(255, 250, 250)); + break; + case gpGeography: + setColorInterpolation(ciRGB); + setColorStopAt(0, QColor(70, 170, 210)); + setColorStopAt(0.20, QColor(90, 160, 180)); + setColorStopAt(0.25, QColor(45, 130, 175)); + setColorStopAt(0.30, QColor(100, 140, 125)); + setColorStopAt(0.5, QColor(100, 140, 100)); + setColorStopAt(0.6, QColor(130, 145, 120)); + setColorStopAt(0.7, QColor(140, 130, 120)); + setColorStopAt(0.9, QColor(180, 190, 190)); + setColorStopAt(1, QColor(210, 210, 230)); + break; + case gpIon: + setColorInterpolation(ciHSV); + setColorStopAt(0, QColor(50, 10, 10)); + setColorStopAt(0.45, QColor(0, 0, 255)); + setColorStopAt(0.8, QColor(0, 255, 255)); + setColorStopAt(1, QColor(0, 255, 0)); + break; + case gpThermal: + setColorInterpolation(ciRGB); + setColorStopAt(0, QColor(0, 0, 50)); + setColorStopAt(0.15, QColor(20, 0, 120)); + setColorStopAt(0.33, QColor(200, 30, 140)); + setColorStopAt(0.6, QColor(255, 100, 0)); + setColorStopAt(0.85, QColor(255, 255, 40)); + setColorStopAt(1, QColor(255, 255, 255)); + break; + case gpPolar: + setColorInterpolation(ciRGB); + setColorStopAt(0, QColor(50, 255, 255)); + setColorStopAt(0.18, QColor(10, 70, 255)); + setColorStopAt(0.28, QColor(10, 10, 190)); + setColorStopAt(0.5, QColor(0, 0, 0)); + setColorStopAt(0.72, QColor(190, 10, 10)); + setColorStopAt(0.82, QColor(255, 70, 10)); + setColorStopAt(1, QColor(255, 255, 50)); + break; + case gpSpectrum: + setColorInterpolation(ciHSV); + setColorStopAt(0, QColor(50, 0, 50)); + setColorStopAt(0.15, QColor(0, 0, 255)); + setColorStopAt(0.35, QColor(0, 255, 255)); + setColorStopAt(0.6, QColor(255, 255, 0)); + setColorStopAt(0.75, QColor(255, 30, 0)); + setColorStopAt(1, QColor(50, 0, 0)); + break; + case gpJet: + setColorInterpolation(ciRGB); + setColorStopAt(0, QColor(0, 0, 100)); + setColorStopAt(0.15, QColor(0, 50, 255)); + setColorStopAt(0.35, QColor(0, 255, 255)); + setColorStopAt(0.65, QColor(255, 255, 0)); + setColorStopAt(0.85, QColor(255, 30, 0)); + setColorStopAt(1, QColor(100, 0, 0)); + break; + case gpHues: + setColorInterpolation(ciHSV); + setColorStopAt(0, QColor(255, 0, 0)); + setColorStopAt(1.0 / 3.0, QColor(0, 0, 255)); + setColorStopAt(2.0 / 3.0, QColor(0, 255, 0)); + setColorStopAt(1, QColor(255, 0, 0)); + break; + } } /*! Clears all color stops. - + \see setColorStops, setColorStopAt */ void QCPColorGradient::clearColorStops() { - mColorStops.clear(); - mColorBufferInvalidated = true; + mColorStops.clear(); + mColorBufferInvalidated = true; } /*! Returns an inverted gradient. The inverted gradient has all properties as this \ref QCPColorGradient, but the order of the color stops is inverted. - + \see setColorStops, setColorStopAt */ QCPColorGradient QCPColorGradient::inverted() const { - QCPColorGradient result(*this); - result.clearColorStops(); - for (QMap::const_iterator it=mColorStops.constBegin(); it!=mColorStops.constEnd(); ++it) - result.setColorStopAt(1.0-it.key(), it.value()); - return result; + QCPColorGradient result(*this); + result.clearColorStops(); + for (QMap::const_iterator it = mColorStops.constBegin(); it != mColorStops.constEnd(); ++it) { + result.setColorStopAt(1.0 - it.key(), it.value()); + } + 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; + 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 convert positions to colors. This is where the interpolation between color stops is calculated. */ void QCPColorGradient::updateColorBuffer() { - if (mColorBuffer.size() != mLevelCount) - mColorBuffer.resize(mLevelCount); - if (mColorStops.size() > 1) - { - double indexToPosFactor = 1.0/(double)(mLevelCount-1); - const bool useAlpha = stopsUseAlpha(); - for (int i=0; i::const_iterator it = mColorStops.lowerBound(position); - if (it == mColorStops.constEnd()) // position is on or after last stop, use color of last stop - { - if (useAlpha) - { - const QColor col = (it-1).value(); - const float alphaPremultiplier = col.alpha()/255.0f; // since we use QImage::Format_ARGB32_Premultiplied - mColorBuffer[i] = qRgba(col.red()*alphaPremultiplier, col.green()*alphaPremultiplier, col.blue()*alphaPremultiplier, col.alpha()); - } else - mColorBuffer[i] = (it-1).value().rgba(); - } else if (it == mColorStops.constBegin()) // position is on or before first stop, use color of first stop - { - if (useAlpha) - { - const QColor col = it.value(); - const float alphaPremultiplier = col.alpha()/255.0f; // since we use QImage::Format_ARGB32_Premultiplied - mColorBuffer[i] = qRgba(col.red()*alphaPremultiplier, col.green()*alphaPremultiplier, col.blue()*alphaPremultiplier, col.alpha()); - } else - mColorBuffer[i] = it.value().rgba(); - } else // position is in between stops (or on an intermediate stop), interpolate color - { - QMap::const_iterator high = it; - QMap::const_iterator low = it-1; - double t = (position-low.key())/(high.key()-low.key()); // interpolation factor 0..1 - switch (mColorInterpolation) - { - case ciRGB: - { - 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: - { - QColor lowHsv = low.value().toHsv(); - QColor highHsv = high.value().toHsv(); - double hue = 0; - double hueDiff = highHsv.hueF()-lowHsv.hueF(); - if (hueDiff > 0.5) - hue = lowHsv.hueF() - t*(1.0-hueDiff); - else if (hueDiff < -0.5) - hue = lowHsv.hueF() + t*(1.0+hueDiff); - else - hue = lowHsv.hueF() + t*hueDiff; - if (hue < 0) hue += 1.0; - else if (hue >= 1.0) hue -= 1.0; - 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; - } - } - } + if (mColorBuffer.size() != mLevelCount) { + mColorBuffer.resize(mLevelCount); } - } else if (mColorStops.size() == 1) - { - 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; + if (mColorStops.size() > 1) { + double indexToPosFactor = 1.0 / (double)(mLevelCount - 1); + const bool useAlpha = stopsUseAlpha(); + for (int i = 0; i < mLevelCount; ++i) { + double position = i * indexToPosFactor; + QMap::const_iterator it = mColorStops.lowerBound(position); + if (it == mColorStops.constEnd()) { // position is on or after last stop, use color of last stop + if (useAlpha) { + const QColor col = (it - 1).value(); + const float alphaPremultiplier = col.alpha() / 255.0f; // since we use QImage::Format_ARGB32_Premultiplied + mColorBuffer[i] = qRgba(col.red() * alphaPremultiplier, col.green() * alphaPremultiplier, col.blue() * alphaPremultiplier, col.alpha()); + } else { + mColorBuffer[i] = (it - 1).value().rgba(); + } + } else if (it == mColorStops.constBegin()) { // position is on or before first stop, use color of first stop + if (useAlpha) { + const QColor col = it.value(); + const float alphaPremultiplier = col.alpha() / 255.0f; // since we use QImage::Format_ARGB32_Premultiplied + mColorBuffer[i] = qRgba(col.red() * alphaPremultiplier, col.green() * alphaPremultiplier, col.blue() * alphaPremultiplier, col.alpha()); + } else { + mColorBuffer[i] = it.value().rgba(); + } + } else { // position is in between stops (or on an intermediate stop), interpolate color + QMap::const_iterator high = it; + QMap::const_iterator low = it - 1; + double t = (position - low.key()) / (high.key() - low.key()); // interpolation factor 0..1 + switch (mColorInterpolation) { + case ciRGB: { + 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: { + QColor lowHsv = low.value().toHsv(); + QColor highHsv = high.value().toHsv(); + double hue = 0; + double hueDiff = highHsv.hueF() - lowHsv.hueF(); + if (hueDiff > 0.5) { + hue = lowHsv.hueF() - t * (1.0 - hueDiff); + } else if (hueDiff < -0.5) { + hue = lowHsv.hueF() + t * (1.0 + hueDiff); + } else { + hue = lowHsv.hueF() + t * hueDiff; + } + if (hue < 0) { + hue += 1.0; + } else if (hue >= 1.0) { + hue -= 1.0; + } + if (useAlpha) { + const QRgb rgb = QColor::fromHsvF(hue, + (1 - t) * lowHsv.saturationF() + t * highHsv.saturationF(), + (1 - t) * lowHsv.valueF() + t * highHsv.valueF()).rgb(); + const float alpha = (1 - t) * lowHsv.alphaF() + t * highHsv.alphaF(); + mColorBuffer[i] = qRgba(qRed(rgb) * alpha, qGreen(rgb) * alpha, qBlue(rgb) * alpha, 255 * alpha); + } else { + mColorBuffer[i] = QColor::fromHsvF(hue, + (1 - t) * lowHsv.saturationF() + t * highHsv.saturationF(), + (1 - t) * lowHsv.valueF() + t * highHsv.valueF()).rgb(); + } + break; + } + } + } + } + } else if (mColorStops.size() == 1) { + 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' */ @@ -16406,15 +16423,15 @@ void QCPColorGradient::updateColorBuffer() /*! \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. @@ -16424,15 +16441,15 @@ void QCPColorGradient::updateColorBuffer() 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) + mBracketPen(QPen(Qt::black)), + mBracketBrush(Qt::NoBrush), + mBracketWidth(5), + mBracketHeight(50), + mBracketStyle(bsSquareBracket), + mTangentToData(false), + mTangentAverage(2) { - + } QCPSelectionDecoratorBracket::~QCPSelectionDecoratorBracket() @@ -16445,7 +16462,7 @@ QCPSelectionDecoratorBracket::~QCPSelectionDecoratorBracket() */ void QCPSelectionDecoratorBracket::setBracketPen(const QPen &pen) { - mBracketPen = pen; + mBracketPen = pen; } /*! @@ -16454,7 +16471,7 @@ void QCPSelectionDecoratorBracket::setBracketPen(const QPen &pen) */ void QCPSelectionDecoratorBracket::setBracketBrush(const QBrush &brush) { - mBracketBrush = brush; + mBracketBrush = brush; } /*! @@ -16464,7 +16481,7 @@ void QCPSelectionDecoratorBracket::setBracketBrush(const QBrush &brush) */ void QCPSelectionDecoratorBracket::setBracketWidth(int width) { - mBracketWidth = width; + mBracketWidth = width; } /*! @@ -16474,211 +16491,209 @@ void QCPSelectionDecoratorBracket::setBracketWidth(int width) */ void QCPSelectionDecoratorBracket::setBracketHeight(int height) { - mBracketHeight = height; + mBracketHeight = height; } /*! Sets the shape that the bracket/marker will have. - + \see setBracketWidth, setBracketHeight */ void QCPSelectionDecoratorBracket::setBracketStyle(QCPSelectionDecoratorBracket::BracketStyle style) { - mBracketStyle = 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; + 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; + 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; + 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; + } } - 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); + 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; i= 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; i < averageCount; ++i) { + points[i] = getPixelCoordinates(interface1d, currentIndex); + pointsAverage += points[i]; + currentIndex += direction; + } + pointsAverage /= (double)averageCount; + + // calculate slope of linear regression through points: + double numSum = 0; + double denomSum = 0; + for (int i = 0; i < averageCount; ++i) { + const double dx = points.at(i).x() - pointsAverage.x(); + const double dy = points.at(i).y() - pointsAverage.y(); + numSum += dx * dy; + denomSum += dx * dx; + } + if (!qFuzzyIsNull(denomSum) && !qFuzzyIsNull(numSum)) { + return qAtan2(numSum, denomSum); + } else { // undetermined angle, probably mTangentAverage == 1, so using only one data point + return 0; + } } /*! \internal - + Returns the pixel coordinates of the data point at \a dataIndex, using \a interface1d to access the data points. */ QPointF QCPSelectionDecoratorBracket::getPixelCoordinates(const QCPPlottableInterface1D *interface1d, int dataIndex) const { - QCPAxis *keyAxis = mPlottable->keyAxis(); - QCPAxis *valueAxis = mPlottable->valueAxis(); - if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPointF(0, 0); } - - if (keyAxis->orientation() == Qt::Horizontal) - return QPointF(keyAxis->coordToPixel(interface1d->dataMainKey(dataIndex)), valueAxis->coordToPixel(interface1d->dataMainValue(dataIndex))); - else - return QPointF(valueAxis->coordToPixel(interface1d->dataMainValue(dataIndex)), keyAxis->coordToPixel(interface1d->dataMainKey(dataIndex))); + QCPAxis *keyAxis = mPlottable->keyAxis(); + QCPAxis *valueAxis = mPlottable->valueAxis(); + if (!keyAxis || !valueAxis) { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + return QPointF(0, 0); + } + + if (keyAxis->orientation() == Qt::Horizontal) { + return QPointF(keyAxis->coordToPixel(interface1d->dataMainKey(dataIndex)), valueAxis->coordToPixel(interface1d->dataMainValue(dataIndex))); + } else { + return QPointF(valueAxis->coordToPixel(interface1d->dataMainValue(dataIndex)), keyAxis->coordToPixel(interface1d->dataMainKey(dataIndex))); + } } /* end of 'src/selectiondecorator-bracket.cpp' */ @@ -16693,36 +16708,36 @@ QPointF QCPSelectionDecoratorBracket::getPixelCoordinates(const QCPPlottableInte /*! \class QCPAxisRect \brief Holds multiple axes and arranges them in a rectangular shape. - + This class represents an axis rect, a rectangular area that is bounded on all sides with an arbitrary number of axes. - + Initially QCustomPlot has one axis rect, accessible via QCustomPlot::axisRect(). However, the layout system allows to have multiple axis rects, e.g. arranged in a grid layout (QCustomPlot::plotLayout). - + By default, QCPAxisRect comes with four axes, at bottom, top, left and right. They can be accessed via \ref axis by providing the respective axis type (\ref QCPAxis::AxisType) and index. If you need all axes in the axis rect, use \ref axes. The top and right axes are set to be invisible initially (QCPAxis::setVisible). To add more axes to a side, use \ref addAxis or \ref addAxes. To remove an axis, use \ref removeAxis. - + The axis rect layerable itself only draws a background pixmap or color, if specified (\ref setBackground). It is placed on the "background" layer initially (see \ref QCPLayer for an explanation of the QCustomPlot layer system). The axes that are held by the axis rect can be placed on other layers, independently of the axis rect. - + Every axis rect has a child layout of type \ref QCPLayoutInset. It is accessible via \ref insetLayout and can be used to have other layout elements (or even other layouts with multiple elements) hovering inside the axis rect. - + If an axis rect is clicked and dragged, it processes this by moving certain axis ranges. The behaviour can be controlled with \ref setRangeDrag and \ref setRangeDragAxes. If the mouse wheel is scrolled while the cursor is on the axis rect, certain axes are scaled. This is controllable via \ref setRangeZoom, \ref setRangeZoomAxes and \ref setRangeZoomFactor. These interactions are only enabled if \ref QCustomPlot::setInteractions contains \ref QCP::iRangeDrag and \ref QCP::iRangeZoom. - + \image html AxisRectSpacingOverview.png
Overview of the spacings and paddings that define the geometry of an axis. The dashed line on the far left indicates the viewport/widget border.
@@ -16731,81 +16746,81 @@ QPointF QCPSelectionDecoratorBracket::getPixelCoordinates(const QCPPlottableInte /* start documentation of inline functions */ /*! \fn QCPLayoutInset *QCPAxisRect::insetLayout() const - + Returns the inset layout of this axis rect. It can be used to place other layout elements (or even layouts with multiple other elements) inside/on top of an axis rect. - + \see QCPLayoutInset */ /*! \fn int QCPAxisRect::left() const - + Returns the pixel position of the left border of this axis rect. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn int QCPAxisRect::right() const - + Returns the pixel position of the right border of this axis rect. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn int QCPAxisRect::top() const - + Returns the pixel position of the top border of this axis rect. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn int QCPAxisRect::bottom() const - + Returns the pixel position of the bottom border of this axis rect. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn int QCPAxisRect::width() const - + Returns the pixel width of this axis rect. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn int QCPAxisRect::height() const - + Returns the pixel height of this axis rect. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn QSize QCPAxisRect::size() const - + Returns the pixel size of this axis rect. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn QPoint QCPAxisRect::topLeft() const - + Returns the top left corner of this axis rect in pixels. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn QPoint QCPAxisRect::topRight() const - + Returns the top right corner of this axis rect in pixels. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn QPoint QCPAxisRect::bottomLeft() const - + Returns the bottom left corner of this axis rect in pixels. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn QPoint QCPAxisRect::bottomRight() const - + Returns the bottom right corner of this axis rect in pixels. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn QPoint QCPAxisRect::center() const - + Returns the center of this axis rect in pixels. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ @@ -16817,123 +16832,124 @@ QPointF QCPSelectionDecoratorBracket::getPixelCoordinates(const QCPPlottableInte sides, the top and right axes are set invisible initially. */ QCPAxisRect::QCPAxisRect(QCustomPlot *parentPlot, bool setupDefaultAxes) : - QCPLayoutElement(parentPlot), - mBackgroundBrush(Qt::NoBrush), - mBackgroundScaled(true), - mBackgroundScaledMode(Qt::KeepAspectRatioByExpanding), - mInsetLayout(new QCPLayoutInset), - mRangeDrag(Qt::Horizontal|Qt::Vertical), - mRangeZoom(Qt::Horizontal|Qt::Vertical), - mRangeZoomFactorHorz(0.85), - mRangeZoomFactorVert(0.85), - mDragging(false) + QCPLayoutElement(parentPlot), + mBackgroundBrush(Qt::NoBrush), + mBackgroundScaled(true), + mBackgroundScaledMode(Qt::KeepAspectRatioByExpanding), + mInsetLayout(new QCPLayoutInset), + mRangeDrag(Qt::Horizontal | Qt::Vertical), + mRangeZoom(Qt::Horizontal | Qt::Vertical), + mRangeZoomFactorHorz(0.85), + mRangeZoomFactorVert(0.85), + mDragging(false) { - mInsetLayout->initializeParentPlot(mParentPlot); - mInsetLayout->setParentLayerable(this); - mInsetLayout->setParent(this); - - setMinimumSize(50, 50); - setMinimumMargins(QMargins(15, 15, 15, 15)); - mAxes.insert(QCPAxis::atLeft, QList()); - mAxes.insert(QCPAxis::atRight, QList()); - mAxes.insert(QCPAxis::atTop, QList()); - mAxes.insert(QCPAxis::atBottom, QList()); - - if (setupDefaultAxes) - { - QCPAxis *xAxis = addAxis(QCPAxis::atBottom); - QCPAxis *yAxis = addAxis(QCPAxis::atLeft); - QCPAxis *xAxis2 = addAxis(QCPAxis::atTop); - QCPAxis *yAxis2 = addAxis(QCPAxis::atRight); - setRangeDragAxes(xAxis, yAxis); - setRangeZoomAxes(xAxis, yAxis); - xAxis2->setVisible(false); - yAxis2->setVisible(false); - xAxis->grid()->setVisible(true); - yAxis->grid()->setVisible(true); - xAxis2->grid()->setVisible(false); - yAxis2->grid()->setVisible(false); - xAxis2->grid()->setZeroLinePen(Qt::NoPen); - yAxis2->grid()->setZeroLinePen(Qt::NoPen); - xAxis2->grid()->setVisible(false); - yAxis2->grid()->setVisible(false); - } + mInsetLayout->initializeParentPlot(mParentPlot); + mInsetLayout->setParentLayerable(this); + mInsetLayout->setParent(this); + + setMinimumSize(50, 50); + setMinimumMargins(QMargins(15, 15, 15, 15)); + mAxes.insert(QCPAxis::atLeft, QList()); + mAxes.insert(QCPAxis::atRight, QList()); + mAxes.insert(QCPAxis::atTop, QList()); + mAxes.insert(QCPAxis::atBottom, QList()); + + if (setupDefaultAxes) { + QCPAxis *xAxis = addAxis(QCPAxis::atBottom); + QCPAxis *yAxis = addAxis(QCPAxis::atLeft); + QCPAxis *xAxis2 = addAxis(QCPAxis::atTop); + QCPAxis *yAxis2 = addAxis(QCPAxis::atRight); + setRangeDragAxes(xAxis, yAxis); + setRangeZoomAxes(xAxis, yAxis); + xAxis2->setVisible(false); + yAxis2->setVisible(false); + xAxis->grid()->setVisible(true); + yAxis->grid()->setVisible(true); + xAxis2->grid()->setVisible(false); + yAxis2->grid()->setVisible(false); + xAxis2->grid()->setZeroLinePen(Qt::NoPen); + yAxis2->grid()->setZeroLinePen(Qt::NoPen); + xAxis2->grid()->setVisible(false); + yAxis2->grid()->setVisible(false); + } } QCPAxisRect::~QCPAxisRect() { - delete mInsetLayout; - mInsetLayout = 0; - - QList axesList = axes(); - for (int i=0; i axesList = axes(); + for (int i = 0; i < axesList.size(); ++i) { + removeAxis(axesList.at(i)); + } } /*! Returns the number of axes on the axis rect side specified with \a type. - + \see axis */ int QCPAxisRect::axisCount(QCPAxis::AxisType type) const { - return mAxes.value(type).size(); + return mAxes.value(type).size(); } /*! Returns the axis with the given \a index on the axis rect side specified with \a type. - + \see axisCount, axes */ QCPAxis *QCPAxisRect::axis(QCPAxis::AxisType type, int index) const { - QList ax(mAxes.value(type)); - if (index >= 0 && index < ax.size()) - { - return ax.at(index); - } else - { - qDebug() << Q_FUNC_INFO << "Axis index out of bounds:" << index; - return 0; - } + QList ax(mAxes.value(type)); + if (index >= 0 && index < ax.size()) { + return ax.at(index); + } else { + qDebug() << Q_FUNC_INFO << "Axis index out of bounds:" << index; + return 0; + } } /*! Returns all axes on the axis rect sides specified with \a types. - + \a types may be a single \ref QCPAxis::AxisType or an or-combination, to get the axes of multiple sides. - + \see axis */ -QList QCPAxisRect::axes(QCPAxis::AxisTypes types) const +QList QCPAxisRect::axes(QCPAxis::AxisTypes types) const { - QList result; - if (types.testFlag(QCPAxis::atLeft)) - result << mAxes.value(QCPAxis::atLeft); - if (types.testFlag(QCPAxis::atRight)) - result << mAxes.value(QCPAxis::atRight); - if (types.testFlag(QCPAxis::atTop)) - result << mAxes.value(QCPAxis::atTop); - if (types.testFlag(QCPAxis::atBottom)) - result << mAxes.value(QCPAxis::atBottom); - return result; + QList result; + if (types.testFlag(QCPAxis::atLeft)) { + result << mAxes.value(QCPAxis::atLeft); + } + if (types.testFlag(QCPAxis::atRight)) { + result << mAxes.value(QCPAxis::atRight); + } + if (types.testFlag(QCPAxis::atTop)) { + result << mAxes.value(QCPAxis::atTop); + } + if (types.testFlag(QCPAxis::atBottom)) { + result << mAxes.value(QCPAxis::atBottom); + } + return result; } /*! \overload - + Returns all axes of this axis rect. */ -QList QCPAxisRect::axes() const +QList QCPAxisRect::axes() const { - QList result; - QHashIterator > it(mAxes); - while (it.hasNext()) - { - it.next(); - result << it.value(); - } - return result; + QList result; + QHashIterator > it(mAxes); + while (it.hasNext()) { + it.next(); + result << it.value(); + } + return result; } /*! @@ -16958,100 +16974,116 @@ QList QCPAxisRect::axes() const */ QCPAxis *QCPAxisRect::addAxis(QCPAxis::AxisType type, QCPAxis *axis) { - QCPAxis *newAxis = axis; - if (!newAxis) - { - newAxis = new QCPAxis(this, type); - } else // user provided existing axis instance, do some sanity checks - { - if (newAxis->axisType() != type) - { - qDebug() << Q_FUNC_INFO << "passed axis has different axis type than specified in type parameter"; - return 0; + QCPAxis *newAxis = axis; + if (!newAxis) { + newAxis = new QCPAxis(this, type); + } else { // user provided existing axis instance, do some sanity checks + if (newAxis->axisType() != type) { + qDebug() << Q_FUNC_INFO << "passed axis has different axis type than specified in type parameter"; + return 0; + } + if (newAxis->axisRect() != this) { + qDebug() << Q_FUNC_INFO << "passed axis doesn't have this axis rect as parent axis rect"; + return 0; + } + if (axes().contains(newAxis)) { + qDebug() << Q_FUNC_INFO << "passed axis is already owned by this axis rect"; + return 0; + } } - if (newAxis->axisRect() != this) - { - qDebug() << Q_FUNC_INFO << "passed axis doesn't have this axis rect as parent axis rect"; - return 0; + if (mAxes[type].size() > 0) { // multiple axes on one side, add half-bar axis ending to additional axes with offset + bool invert = (type == QCPAxis::atRight) || (type == QCPAxis::atBottom); + newAxis->setLowerEnding(QCPLineEnding(QCPLineEnding::esHalfBar, 6, 10, !invert)); + newAxis->setUpperEnding(QCPLineEnding(QCPLineEnding::esHalfBar, 6, 10, invert)); } - if (axes().contains(newAxis)) - { - qDebug() << Q_FUNC_INFO << "passed axis is already owned by this axis rect"; - return 0; + 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; + } + } } - } - if (mAxes[type].size() > 0) // multiple axes on one side, add half-bar axis ending to additional axes with offset - { - bool invert = (type == QCPAxis::atRight) || (type == QCPAxis::atBottom); - newAxis->setLowerEnding(QCPLineEnding(QCPLineEnding::esHalfBar, 6, 10, !invert)); - 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; + + return newAxis; } /*! Adds a new axis with \ref addAxis to each axis rect side specified in \a types. This may be an or-combination of QCPAxis::AxisType, so axes can be added to multiple sides at once. - + Returns a list of the added axes. - + \see addAxis, setupFullAxesBox */ -QList QCPAxisRect::addAxes(QCPAxis::AxisTypes types) +QList QCPAxisRect::addAxes(QCPAxis::AxisTypes types) { - QList result; - if (types.testFlag(QCPAxis::atLeft)) - result << addAxis(QCPAxis::atLeft); - if (types.testFlag(QCPAxis::atRight)) - result << addAxis(QCPAxis::atRight); - if (types.testFlag(QCPAxis::atTop)) - result << addAxis(QCPAxis::atTop); - if (types.testFlag(QCPAxis::atBottom)) - result << addAxis(QCPAxis::atBottom); - return result; + QList result; + if (types.testFlag(QCPAxis::atLeft)) { + result << addAxis(QCPAxis::atLeft); + } + if (types.testFlag(QCPAxis::atRight)) { + result << addAxis(QCPAxis::atRight); + } + if (types.testFlag(QCPAxis::atTop)) { + result << addAxis(QCPAxis::atTop); + } + if (types.testFlag(QCPAxis::atBottom)) { + result << addAxis(QCPAxis::atBottom); + } + return result; } /*! Removes the specified \a axis from the axis rect and deletes it. - + Returns true on success, i.e. if \a axis was a valid axis in this axis rect. - + \see addAxis */ bool QCPAxisRect::removeAxis(QCPAxis *axis) { - // don't access axis->axisType() to provide safety when axis is an invalid pointer, rather go through all axis containers: - QHashIterator > it(mAxes); - while (it.hasNext()) - { - it.next(); - if (it.value().contains(axis)) - { - if (it.value().first() == axis && it.value().size() > 1) // if removing first axis, transfer axis offset to the new first axis (which at this point is the second axis, if it exists) - it.value()[1]->setOffset(axis->offset()); - mAxes[it.key()].removeOne(axis); - if (qobject_cast(parentPlot())) // make sure this isn't called from QObject dtor when QCustomPlot is already destructed (happens when the axis rect is not in any layout and thus QObject-child of QCustomPlot) - parentPlot()->axisRemoved(axis); - delete axis; - return true; + // don't access axis->axisType() to provide safety when axis is an invalid pointer, rather go through all axis containers: + QHashIterator > it(mAxes); + while (it.hasNext()) { + it.next(); + if (it.value().contains(axis)) { + if (it.value().first() == axis && it.value().size() > 1) { // if removing first axis, transfer axis offset to the new first axis (which at this point is the second axis, if it exists) + it.value()[1]->setOffset(axis->offset()); + } + mAxes[it.key()].removeOne(axis); + if (qobject_cast(parentPlot())) { // make sure this isn't called from QObject dtor when QCustomPlot is already destructed (happens when the axis rect is not in any layout and thus QObject-child of QCustomPlot) + parentPlot()->axisRemoved(axis); + } + delete axis; + return true; + } } - } - qDebug() << Q_FUNC_INFO << "Axis isn't in axis rect:" << reinterpret_cast(axis); - return false; + qDebug() << Q_FUNC_INFO << "Axis isn't in axis rect:" << reinterpret_cast(axis); + return false; } /*! @@ -17059,38 +17091,37 @@ bool QCPAxisRect::removeAxis(QCPAxis *axis) 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()); + 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) +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; + 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)); } - 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)); - } } /*! @@ -17114,194 +17145,192 @@ void QCPAxisRect::zoom(const QRectF &pixelRect, const QList &affectedA */ void QCPAxisRect::setupFullAxesBox(bool connectRanges) { - QCPAxis *xAxis, *yAxis, *xAxis2, *yAxis2; - if (axisCount(QCPAxis::atBottom) == 0) - xAxis = addAxis(QCPAxis::atBottom); - else - xAxis = axis(QCPAxis::atBottom); - - if (axisCount(QCPAxis::atLeft) == 0) - yAxis = addAxis(QCPAxis::atLeft); - else - yAxis = axis(QCPAxis::atLeft); - - if (axisCount(QCPAxis::atTop) == 0) - xAxis2 = addAxis(QCPAxis::atTop); - else - xAxis2 = axis(QCPAxis::atTop); - - if (axisCount(QCPAxis::atRight) == 0) - yAxis2 = addAxis(QCPAxis::atRight); - else - yAxis2 = axis(QCPAxis::atRight); - - xAxis->setVisible(true); - yAxis->setVisible(true); - xAxis2->setVisible(true); - yAxis2->setVisible(true); - xAxis2->setTickLabels(false); - yAxis2->setTickLabels(false); - - xAxis2->setRange(xAxis->range()); - xAxis2->setRangeReversed(xAxis->rangeReversed()); - xAxis2->setScaleType(xAxis->scaleType()); - xAxis2->setTicks(xAxis->ticks()); - xAxis2->setNumberFormat(xAxis->numberFormat()); - xAxis2->setNumberPrecision(xAxis->numberPrecision()); - 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->setTicks(yAxis->ticks()); - yAxis2->setNumberFormat(yAxis->numberFormat()); - yAxis2->setNumberPrecision(yAxis->numberPrecision()); - yAxis2->ticker()->setTickCount(yAxis->ticker()->tickCount()); - yAxis2->ticker()->setTickOrigin(yAxis->ticker()->tickOrigin()); - - if (connectRanges) - { - connect(xAxis, SIGNAL(rangeChanged(QCPRange)), xAxis2, SLOT(setRange(QCPRange))); - connect(yAxis, SIGNAL(rangeChanged(QCPRange)), yAxis2, SLOT(setRange(QCPRange))); - } + QCPAxis *xAxis, *yAxis, *xAxis2, *yAxis2; + if (axisCount(QCPAxis::atBottom) == 0) { + xAxis = addAxis(QCPAxis::atBottom); + } else { + xAxis = axis(QCPAxis::atBottom); + } + + if (axisCount(QCPAxis::atLeft) == 0) { + yAxis = addAxis(QCPAxis::atLeft); + } else { + yAxis = axis(QCPAxis::atLeft); + } + + if (axisCount(QCPAxis::atTop) == 0) { + xAxis2 = addAxis(QCPAxis::atTop); + } else { + xAxis2 = axis(QCPAxis::atTop); + } + + if (axisCount(QCPAxis::atRight) == 0) { + yAxis2 = addAxis(QCPAxis::atRight); + } else { + yAxis2 = axis(QCPAxis::atRight); + } + + xAxis->setVisible(true); + yAxis->setVisible(true); + xAxis2->setVisible(true); + yAxis2->setVisible(true); + xAxis2->setTickLabels(false); + yAxis2->setTickLabels(false); + + xAxis2->setRange(xAxis->range()); + xAxis2->setRangeReversed(xAxis->rangeReversed()); + xAxis2->setScaleType(xAxis->scaleType()); + xAxis2->setTicks(xAxis->ticks()); + xAxis2->setNumberFormat(xAxis->numberFormat()); + xAxis2->setNumberPrecision(xAxis->numberPrecision()); + 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->setTicks(yAxis->ticks()); + yAxis2->setNumberFormat(yAxis->numberFormat()); + yAxis2->setNumberPrecision(yAxis->numberPrecision()); + yAxis2->ticker()->setTickCount(yAxis->ticker()->tickCount()); + yAxis2->ticker()->setTickOrigin(yAxis->ticker()->tickOrigin()); + + if (connectRanges) { + connect(xAxis, SIGNAL(rangeChanged(QCPRange)), xAxis2, SLOT(setRange(QCPRange))); + connect(yAxis, SIGNAL(rangeChanged(QCPRange)), yAxis2, SLOT(setRange(QCPRange))); + } } /*! Returns a list of all the plottables that are associated with this axis rect. - + A plottable is considered associated with an axis rect if its key or value axis (or both) is in this axis rect. - + \see graphs, items */ -QList QCPAxisRect::plottables() const +QList QCPAxisRect::plottables() const { - // Note: don't append all QCPAxis::plottables() into a list, because we might get duplicate entries - QList result; - for (int i=0; imPlottables.size(); ++i) - { - if (mParentPlot->mPlottables.at(i)->keyAxis()->axisRect() == this || mParentPlot->mPlottables.at(i)->valueAxis()->axisRect() == this) - result.append(mParentPlot->mPlottables.at(i)); - } - return result; + // Note: don't append all QCPAxis::plottables() into a list, because we might get duplicate entries + QList result; + for (int i = 0; i < mParentPlot->mPlottables.size(); ++i) { + if (mParentPlot->mPlottables.at(i)->keyAxis()->axisRect() == this || mParentPlot->mPlottables.at(i)->valueAxis()->axisRect() == this) { + result.append(mParentPlot->mPlottables.at(i)); + } + } + return result; } /*! Returns a list of all the graphs that are associated with this axis rect. - + A graph is considered associated with an axis rect if its key or value axis (or both) is in this axis rect. - + \see plottables, items */ -QList QCPAxisRect::graphs() const +QList QCPAxisRect::graphs() const { - // Note: don't append all QCPAxis::graphs() into a list, because we might get duplicate entries - QList result; - for (int i=0; imGraphs.size(); ++i) - { - if (mParentPlot->mGraphs.at(i)->keyAxis()->axisRect() == this || mParentPlot->mGraphs.at(i)->valueAxis()->axisRect() == this) - result.append(mParentPlot->mGraphs.at(i)); - } - return result; + // Note: don't append all QCPAxis::graphs() into a list, because we might get duplicate entries + QList result; + for (int i = 0; i < mParentPlot->mGraphs.size(); ++i) { + if (mParentPlot->mGraphs.at(i)->keyAxis()->axisRect() == this || mParentPlot->mGraphs.at(i)->valueAxis()->axisRect() == this) { + result.append(mParentPlot->mGraphs.at(i)); + } + } + return result; } /*! Returns a list of all the items that are associated with this axis rect. - + An item is considered associated with an axis rect if any of its positions has key or value axis set to an axis that is in this axis rect, or if any of its positions has \ref QCPItemPosition::setAxisRect set to the axis rect, or if the clip axis rect (\ref QCPAbstractItem::setClipAxisRect) is set to this axis rect. - + \see plottables, graphs */ QList QCPAxisRect::items() const { - // Note: don't just append all QCPAxis::items() into a list, because we might get duplicate entries - // and miss those items that have this axis rect as clipAxisRect. - QList result; - for (int itemId=0; itemIdmItems.size(); ++itemId) - { - if (mParentPlot->mItems.at(itemId)->clipAxisRect() == this) - { - result.append(mParentPlot->mItems.at(itemId)); - continue; + // Note: don't just append all QCPAxis::items() into a list, because we might get duplicate entries + // and miss those items that have this axis rect as clipAxisRect. + QList result; + for (int itemId = 0; itemId < mParentPlot->mItems.size(); ++itemId) { + if (mParentPlot->mItems.at(itemId)->clipAxisRect() == this) { + result.append(mParentPlot->mItems.at(itemId)); + continue; + } + QList positions = mParentPlot->mItems.at(itemId)->positions(); + for (int posId = 0; posId < positions.size(); ++posId) { + if (positions.at(posId)->axisRect() == this || + positions.at(posId)->keyAxis()->axisRect() == this || + positions.at(posId)->valueAxis()->axisRect() == this) { + result.append(mParentPlot->mItems.at(itemId)); + break; + } + } } - QList positions = mParentPlot->mItems.at(itemId)->positions(); - for (int posId=0; posIdaxisRect() == this || - positions.at(posId)->keyAxis()->axisRect() == this || - positions.at(posId)->valueAxis()->axisRect() == this) - { - result.append(mParentPlot->mItems.at(itemId)); - break; - } - } - } - return result; + return result; } /*! This method is called automatically upon replot and doesn't need to be called by users of QCPAxisRect. - + 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) { - QCPLayoutElement::update(phase); - - switch (phase) - { - case upPreparation: - { - QList allAxes = axes(); - for (int i=0; isetupTickVectors(); - break; + QCPLayoutElement::update(phase); + + switch (phase) { + case upPreparation: { + QList allAxes = axes(); + for (int i = 0; i < allAxes.size(); ++i) { + allAxes.at(i)->setupTickVectors(); + } + break; + } + case upLayout: { + mInsetLayout->setOuterRect(rect()); + break; + } + default: + break; } - case upLayout: - { - mInsetLayout->setOuterRect(rect()); - break; - } - default: break; - } - - // pass update call on to inset layout (doesn't happen automatically, because QCPAxisRect doesn't derive from QCPLayout): - mInsetLayout->update(phase); + + // pass update call on to inset layout (doesn't happen automatically, because QCPAxisRect doesn't derive from QCPLayout): + mInsetLayout->update(phase); } /* inherits documentation from base class */ -QList QCPAxisRect::elements(bool recursive) const +QList QCPAxisRect::elements(bool recursive) const { - QList result; - if (mInsetLayout) - { - result << mInsetLayout; - if (recursive) - result << mInsetLayout->elements(recursive); - } - return result; + QList result; + if (mInsetLayout) { + result << mInsetLayout; + if (recursive) { + result << mInsetLayout->elements(recursive); + } + } + return result; } /* inherits documentation from base class */ void QCPAxisRect::applyDefaultAntialiasingHint(QCPPainter *painter) const { - painter->setAntialiasing(false); + painter->setAntialiasing(false); } /* inherits documentation from base class */ void QCPAxisRect::draw(QCPPainter *painter) { - drawBackground(painter); + drawBackground(painter); } /*! @@ -17316,17 +17345,17 @@ void QCPAxisRect::draw(QCPPainter *painter) Below the pixmap, the axis rect may be optionally filled with a brush, if specified with \ref setBackground(const QBrush &brush). - + \see setBackgroundScaled, setBackgroundScaledMode, setBackground(const QBrush &brush) */ void QCPAxisRect::setBackground(const QPixmap &pm) { - mBackgroundPixmap = pm; - mScaledBackgroundPixmap = QPixmap(); + mBackgroundPixmap = pm; + mScaledBackgroundPixmap = QPixmap(); } /*! \overload - + Sets \a brush as the background brush. The axis rect background will be filled with this brush. Since axis rects place themselves on the "background" layer by default, the axis rect backgrounds are usually drawn below everything else. @@ -17335,16 +17364,16 @@ void QCPAxisRect::setBackground(const QPixmap &pm) setBackground(const QPixmap &pm). To disable drawing of a background brush, set \a brush to Qt::NoBrush. - + \see setBackground(const QPixmap &pm) */ void QCPAxisRect::setBackground(const QBrush &brush) { - mBackgroundBrush = brush; + mBackgroundBrush = brush; } /*! \overload - + Allows setting the background pixmap of the axis rect, whether it shall be scaled and how it shall be scaled in one call. @@ -17352,25 +17381,25 @@ void QCPAxisRect::setBackground(const QBrush &brush) */ void QCPAxisRect::setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode) { - mBackgroundPixmap = pm; - mScaledBackgroundPixmap = QPixmap(); - mBackgroundScaled = scaled; - mBackgroundScaledMode = mode; + mBackgroundPixmap = pm; + mScaledBackgroundPixmap = QPixmap(); + mBackgroundScaled = scaled; + mBackgroundScaledMode = mode; } /*! Sets whether the axis background pixmap shall be scaled to fit the axis rect or not. If \a scaled is set to true, you may control whether and how the aspect ratio of the original pixmap is preserved with \ref setBackgroundScaledMode. - + Note that the scaled version of the original pixmap is buffered, so there is no performance penalty on replots. (Except when the axis rect dimensions are changed continuously.) - + \see setBackground, setBackgroundScaledMode */ void QCPAxisRect::setBackgroundScaled(bool scaled) { - mBackgroundScaled = scaled; + mBackgroundScaled = scaled; } /*! @@ -17380,7 +17409,7 @@ void QCPAxisRect::setBackgroundScaled(bool scaled) */ void QCPAxisRect::setBackgroundScaledMode(Qt::AspectRatioMode mode) { - mBackgroundScaledMode = mode; + mBackgroundScaledMode = mode; } /*! @@ -17391,10 +17420,11 @@ void QCPAxisRect::setBackgroundScaledMode(Qt::AspectRatioMode mode) */ QCPAxis *QCPAxisRect::rangeDragAxis(Qt::Orientation orientation) { - if (orientation == Qt::Horizontal) - return mRangeDragHorzAxis.isEmpty() ? 0 : mRangeDragHorzAxis.first().data(); - else - return mRangeDragVertAxis.isEmpty() ? 0 : mRangeDragVertAxis.first().data(); + if (orientation == Qt::Horizontal) { + return mRangeDragHorzAxis.isEmpty() ? 0 : mRangeDragHorzAxis.first().data(); + } else { + return mRangeDragVertAxis.isEmpty() ? 0 : mRangeDragVertAxis.first().data(); + } } /*! @@ -17405,10 +17435,11 @@ QCPAxis *QCPAxisRect::rangeDragAxis(Qt::Orientation orientation) */ QCPAxis *QCPAxisRect::rangeZoomAxis(Qt::Orientation orientation) { - if (orientation == Qt::Horizontal) - return mRangeZoomHorzAxis.isEmpty() ? 0 : mRangeZoomHorzAxis.first().data(); - else - return mRangeZoomVertAxis.isEmpty() ? 0 : mRangeZoomVertAxis.first().data(); + if (orientation == Qt::Horizontal) { + return mRangeZoomHorzAxis.isEmpty() ? 0 : mRangeZoomHorzAxis.first().data(); + } else { + return mRangeZoomVertAxis.isEmpty() ? 0 : mRangeZoomVertAxis.first().data(); + } } /*! @@ -17416,25 +17447,23 @@ QCPAxis *QCPAxisRect::rangeZoomAxis(Qt::Orientation orientation) \see rangeZoomAxis, setRangeZoomAxes */ -QList QCPAxisRect::rangeDragAxes(Qt::Orientation orientation) +QList QCPAxisRect::rangeDragAxes(Qt::Orientation orientation) { - QList result; - if (orientation == Qt::Horizontal) - { - for (int i=0; i result; + if (orientation == Qt::Horizontal) { + for (int i = 0; i < mRangeDragHorzAxis.size(); ++i) { + if (!mRangeDragHorzAxis.at(i).isNull()) { + result.append(mRangeDragHorzAxis.at(i).data()); + } + } + } else { + for (int i = 0; i < mRangeDragVertAxis.size(); ++i) { + if (!mRangeDragVertAxis.at(i).isNull()) { + result.append(mRangeDragVertAxis.at(i).data()); + } + } } - } else - { - for (int i=0; i QCPAxisRect::rangeDragAxes(Qt::Orientation orientation) \see rangeDragAxis, setRangeDragAxes */ -QList QCPAxisRect::rangeZoomAxes(Qt::Orientation orientation) +QList QCPAxisRect::rangeZoomAxes(Qt::Orientation orientation) { - QList result; - if (orientation == Qt::Horizontal) - { - for (int i=0; i result; + if (orientation == Qt::Horizontal) { + for (int i = 0; i < mRangeZoomHorzAxis.size(); ++i) { + if (!mRangeZoomHorzAxis.at(i).isNull()) { + result.append(mRangeZoomHorzAxis.at(i).data()); + } + } + } else { + for (int i = 0; i < mRangeZoomVertAxis.size(); ++i) { + if (!mRangeZoomVertAxis.at(i).isNull()) { + result.append(mRangeZoomVertAxis.at(i).data()); + } + } } - } else - { - for (int i=0; iQt::Horizontal | Qt::Vertical as \a orientations. - + In addition to setting \a orientations to a non-zero value, make sure \ref QCustomPlot::setInteractions contains \ref QCP::iRangeDrag to enable the range dragging interaction. - + \see setRangeZoom, setRangeDragAxes, QCustomPlot::setNoAntialiasingOnDrag */ void QCPAxisRect::setRangeDrag(Qt::Orientations orientations) { - mRangeDrag = orientations; + mRangeDrag = orientations; } /*! @@ -17503,19 +17530,19 @@ void QCPAxisRect::setRangeDrag(Qt::Orientations orientations) To disable range zooming entirely, pass 0 as \a orientations or remove \ref QCP::iRangeZoom from \ref QCustomPlot::setInteractions. To enable range zooming for both directions, pass Qt::Horizontal | Qt::Vertical as \a orientations. - + In addition to setting \a orientations to a non-zero value, make sure \ref QCustomPlot::setInteractions contains \ref QCP::iRangeZoom to enable the range zooming interaction. - + \see setRangeZoomFactor, setRangeZoomAxes, setRangeDrag */ void QCPAxisRect::setRangeZoom(Qt::Orientations orientations) { - mRangeZoom = orientations; + mRangeZoom = orientations; } /*! \overload - + Sets the axes whose range will be dragged when \ref setRangeDrag enables mouse range dragging on the QCustomPlot widget. Pass 0 if no axis shall be dragged in the respective orientation. @@ -17526,12 +17553,14 @@ void QCPAxisRect::setRangeZoom(Qt::Orientations orientations) */ void QCPAxisRect::setRangeDragAxes(QCPAxis *horizontal, QCPAxis *vertical) { - QList horz, vert; - if (horizontal) - horz.append(horizontal); - if (vertical) - vert.append(vertical); - setRangeDragAxes(horz, vert); + QList horz, vert; + if (horizontal) { + horz.append(horizontal); + } + if (vertical) { + vert.append(vertical); + } + setRangeDragAxes(horz, vert); } /*! \overload @@ -17543,17 +17572,17 @@ void QCPAxisRect::setRangeDragAxes(QCPAxis *horizontal, QCPAxis *vertical) 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) +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); + QList horz, vert; + foreach (QCPAxis *ax, axes) { + if (ax->orientation() == Qt::Horizontal) { + horz.append(ax); + } else { + vert.append(ax); + } + } + setRangeDragAxes(horz, vert); } /*! \overload @@ -17562,26 +17591,26 @@ void QCPAxisRect::setRangeDragAxes(QList axes) define specifically which axis reacts to which drag orientation (irrespective of the axis orientation). */ -void QCPAxisRect::setRangeDragAxes(QList horizontal, QList vertical) +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); - } + 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); + } + } } /*! @@ -17598,12 +17627,14 @@ void QCPAxisRect::setRangeDragAxes(QList horizontal, QList v */ void QCPAxisRect::setRangeZoomAxes(QCPAxis *horizontal, QCPAxis *vertical) { - QList horz, vert; - if (horizontal) - horz.append(horizontal); - if (vertical) - vert.append(vertical); - setRangeZoomAxes(horz, vert); + QList horz, vert; + if (horizontal) { + horz.append(horizontal); + } + if (vertical) { + vert.append(vertical); + } + setRangeZoomAxes(horz, vert); } /*! \overload @@ -17615,17 +17646,17 @@ void QCPAxisRect::setRangeZoomAxes(QCPAxis *horizontal, QCPAxis *vertical) 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) +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); + QList horz, vert; + foreach (QCPAxis *ax, axes) { + if (ax->orientation() == Qt::Horizontal) { + horz.append(ax); + } else { + vert.append(ax); + } + } + setRangeZoomAxes(horz, vert); } /*! \overload @@ -17634,26 +17665,26 @@ void QCPAxisRect::setRangeZoomAxes(QList axes) define specifically which axis reacts to which zoom orientation (irrespective of the axis orientation). */ -void QCPAxisRect::setRangeZoomAxes(QList horizontal, QList vertical) +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); - } + 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); + } + } } /*! @@ -17668,28 +17699,28 @@ void QCPAxisRect::setRangeZoomAxes(QList horizontal, QList v */ void QCPAxisRect::setRangeZoomFactor(double horizontalFactor, double verticalFactor) { - mRangeZoomFactorHorz = horizontalFactor; - mRangeZoomFactorVert = verticalFactor; + mRangeZoomFactorHorz = horizontalFactor; + mRangeZoomFactorVert = verticalFactor; } /*! \overload - + Sets both the horizontal and vertical zoom \a factor. */ void QCPAxisRect::setRangeZoomFactor(double factor) { - mRangeZoomFactorHorz = factor; - mRangeZoomFactorVert = factor; + mRangeZoomFactorHorz = factor; + mRangeZoomFactorVert = factor; } /*! \internal - + Draws the background of this axis rect. It may consist of a background fill (a QBrush) and a pixmap. - + If a brush was given via \ref setBackground(const QBrush &brush), this function first draws an according filling inside the axis rect with the provided \a painter. - + Then, if a pixmap was provided via \ref setBackground, this function buffers the scaled version depending on \ref setBackgroundScaled and \ref setBackgroundScaledMode and then draws it inside the axis rect with the provided \a painter. The scaled version is buffered in @@ -17697,227 +17728,224 @@ void QCPAxisRect::setRangeZoomFactor(double factor) the axis rect has changed in a way that requires a rescale of the background pixmap (this is dependent on the \ref setBackgroundScaledMode), or when a differend axis background pixmap was set. - + \see setBackground, setBackgroundScaled, setBackgroundScaledMode */ void QCPAxisRect::drawBackground(QCPPainter *painter) { - // draw background fill: - if (mBackgroundBrush != Qt::NoBrush) - painter->fillRect(mRect, mBackgroundBrush); - - // draw background pixmap (on top of fill, if brush specified): - if (!mBackgroundPixmap.isNull()) - { - if (mBackgroundScaled) - { - // check whether mScaledBackground needs to be updated: - QSize scaledSize(mBackgroundPixmap.size()); - scaledSize.scale(mRect.size(), mBackgroundScaledMode); - if (mScaledBackgroundPixmap.size() != scaledSize) - mScaledBackgroundPixmap = mBackgroundPixmap.scaled(mRect.size(), mBackgroundScaledMode, Qt::SmoothTransformation); - painter->drawPixmap(mRect.topLeft()+QPoint(0, -1), mScaledBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height()) & mScaledBackgroundPixmap.rect()); - } else - { - painter->drawPixmap(mRect.topLeft()+QPoint(0, -1), mBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height())); + // draw background fill: + if (mBackgroundBrush != Qt::NoBrush) { + painter->fillRect(mRect, mBackgroundBrush); + } + + // draw background pixmap (on top of fill, if brush specified): + if (!mBackgroundPixmap.isNull()) { + if (mBackgroundScaled) { + // check whether mScaledBackground needs to be updated: + QSize scaledSize(mBackgroundPixmap.size()); + scaledSize.scale(mRect.size(), mBackgroundScaledMode); + if (mScaledBackgroundPixmap.size() != scaledSize) { + mScaledBackgroundPixmap = mBackgroundPixmap.scaled(mRect.size(), mBackgroundScaledMode, Qt::SmoothTransformation); + } + painter->drawPixmap(mRect.topLeft() + QPoint(0, -1), mScaledBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height()) & mScaledBackgroundPixmap.rect()); + } else { + painter->drawPixmap(mRect.topLeft() + QPoint(0, -1), mBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height())); + } } - } } /*! \internal - + This function makes sure multiple axes on the side specified with \a type don't collide, but are distributed according to their respective space requirement (QCPAxis::calculateMargin). - + It does this by setting an appropriate offset (\ref QCPAxis::setOffset) on all axes except the one with index zero. - + This function is called by \ref calculateAutoMargin. */ void QCPAxisRect::updateAxesOffset(QCPAxis::AxisType type) { - const QList axesList = mAxes.value(type); - if (axesList.isEmpty()) - return; - - bool isFirstVisible = !axesList.first()->visible(); // if the first axis is visible, the second axis (which is where the loop starts) isn't the first visible axis, so initialize with false - for (int i=1; ioffset() + axesList.at(i-1)->calculateMargin(); - if (axesList.at(i)->visible()) // only add inner tick length to offset if this axis is visible and it's not the first visible one (might happen if true first axis is invisible) - { - if (!isFirstVisible) - offset += axesList.at(i)->tickLengthIn(); - isFirstVisible = false; + const QList axesList = mAxes.value(type); + if (axesList.isEmpty()) { + return; + } + + bool isFirstVisible = !axesList.first()->visible(); // if the first axis is visible, the second axis (which is where the loop starts) isn't the first visible axis, so initialize with false + for (int i = 1; i < axesList.size(); ++i) { + int offset = axesList.at(i - 1)->offset() + axesList.at(i - 1)->calculateMargin(); + if (axesList.at(i)->visible()) { // only add inner tick length to offset if this axis is visible and it's not the first visible one (might happen if true first axis is invisible) + if (!isFirstVisible) { + offset += axesList.at(i)->tickLengthIn(); + } + isFirstVisible = false; + } + axesList.at(i)->setOffset(offset); } - axesList.at(i)->setOffset(offset); - } } /* inherits documentation from base class */ int QCPAxisRect::calculateAutoMargin(QCP::MarginSide side) { - if (!mAutoMargins.testFlag(side)) - qDebug() << Q_FUNC_INFO << "Called with side that isn't specified as auto margin"; - - updateAxesOffset(QCPAxis::marginSideToAxisType(side)); - - // note: only need to look at the last (outer most) axis to determine the total margin, due to updateAxisOffset call - const QList axesList = mAxes.value(QCPAxis::marginSideToAxisType(side)); - if (axesList.size() > 0) - return axesList.last()->offset() + axesList.last()->calculateMargin(); - else - return 0; + if (!mAutoMargins.testFlag(side)) { + qDebug() << Q_FUNC_INFO << "Called with side that isn't specified as auto margin"; + } + + updateAxesOffset(QCPAxis::marginSideToAxisType(side)); + + // note: only need to look at the last (outer most) axis to determine the total margin, due to updateAxisOffset call + const QList axesList = mAxes.value(QCPAxis::marginSideToAxisType(side)); + if (axesList.size() > 0) { + return axesList.last()->offset() + axesList.last()->calculateMargin(); + } else { + 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); - } + if (mParentPlot && mParentPlot->axisRectCount() > 0 && mParentPlot->axisRect(0) == this) { + if (axisCount(QCPAxis::atBottom) > 0 && !mParentPlot->xAxis) { + mParentPlot->xAxis = axis(QCPAxis::atBottom); + } + if (axisCount(QCPAxis::atLeft) > 0 && !mParentPlot->yAxis) { + mParentPlot->yAxis = axis(QCPAxis::atLeft); + } + if (axisCount(QCPAxis::atTop) > 0 && !mParentPlot->xAxis2) { + mParentPlot->xAxis2 = axis(QCPAxis::atTop); + } + if (axisCount(QCPAxis::atRight) > 0 && !mParentPlot->yAxis2) { + mParentPlot->yAxis2 = axis(QCPAxis::atRight); + } + } } /*! \internal - + Event handler for when a mouse button is pressed on the axis rect. If the left mouse button is pressed, the range dragging interaction is initialized (the actual range manipulation happens in the \ref mouseMoveEvent). The mDragging flag is set to true and some anchor points are set that are needed to determine the distance the mouse was dragged in the mouse move/release events later. - + \see mouseMoveEvent, mouseReleaseEvent */ void QCPAxisRect::mousePressEvent(QMouseEvent *event, const QVariant &details) { - Q_UNUSED(details) - if (event->buttons() & Qt::LeftButton) - { - mDragging = true; - // initialize antialiasing backup in case we start dragging: - if (mParentPlot->noAntialiasingOnDrag()) - { - mAADragBackup = mParentPlot->antialiasedElements(); - mNotAADragBackup = mParentPlot->notAntialiasedElements(); + Q_UNUSED(details) + if (event->buttons() & Qt::LeftButton) { + mDragging = true; + // initialize antialiasing backup in case we start dragging: + if (mParentPlot->noAntialiasingOnDrag()) { + mAADragBackup = mParentPlot->antialiasedElements(); + mNotAADragBackup = mParentPlot->notAntialiasedElements(); + } + // Mouse range dragging interaction: + if (mParentPlot->interactions().testFlag(QCP::iRangeDrag)) { + mDragStartHorzRange.clear(); + for (int i = 0; i < mRangeDragHorzAxis.size(); ++i) { + mDragStartHorzRange.append(mRangeDragHorzAxis.at(i).isNull() ? QCPRange() : mRangeDragHorzAxis.at(i)->range()); + } + mDragStartVertRange.clear(); + for (int i = 0; i < mRangeDragVertAxis.size(); ++i) { + mDragStartVertRange.append(mRangeDragVertAxis.at(i).isNull() ? QCPRange() : mRangeDragVertAxis.at(i)->range()); + } + } } - // Mouse range dragging interaction: - if (mParentPlot->interactions().testFlag(QCP::iRangeDrag)) - { - mDragStartHorzRange.clear(); - for (int i=0; irange()); - mDragStartVertRange.clear(); - for (int i=0; irange()); - } - } } /*! \internal - + Event handler for when the mouse is moved on the axis rect. If range dragging was activated in a preceding \ref mousePressEvent, the range is moved accordingly. - + \see mousePressEvent, mouseReleaseEvent */ 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)) - { - for (int i=0; i= mDragStartHorzRange.size()) - break; - if (ax->mScaleType == QCPAxis::stLinear) - { - double diff = ax->pixelToCoord(startPos.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 = ax->pixelToCoord(startPos.x()) / ax->pixelToCoord(event->pos().x()); - ax->setRange(mDragStartHorzRange.at(i).lower*diff, mDragStartHorzRange.at(i).upper*diff); + Q_UNUSED(startPos) + // Mouse range dragging interaction: + if (mDragging && mParentPlot->interactions().testFlag(QCP::iRangeDrag)) { + + if (mRangeDrag.testFlag(Qt::Horizontal)) { + for (int i = 0; i < mRangeDragHorzAxis.size(); ++i) { + QCPAxis *ax = mRangeDragHorzAxis.at(i).data(); + if (!ax) { + continue; + } + if (i >= mDragStartHorzRange.size()) { + break; + } + if (ax->mScaleType == QCPAxis::stLinear) { + double diff = ax->pixelToCoord(startPos.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 = ax->pixelToCoord(startPos.x()) / ax->pixelToCoord(event->pos().x()); + ax->setRange(mDragStartHorzRange.at(i).lower * diff, mDragStartHorzRange.at(i).upper * diff); + } + } } - } - } - - if (mRangeDrag.testFlag(Qt::Vertical)) - { - for (int i=0; i= mDragStartVertRange.size()) - break; - if (ax->mScaleType == QCPAxis::stLinear) - { - double diff = ax->pixelToCoord(startPos.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 = ax->pixelToCoord(startPos.y()) / ax->pixelToCoord(event->pos().y()); - ax->setRange(mDragStartVertRange.at(i).lower*diff, mDragStartVertRange.at(i).upper*diff); + + if (mRangeDrag.testFlag(Qt::Vertical)) { + for (int i = 0; i < mRangeDragVertAxis.size(); ++i) { + QCPAxis *ax = mRangeDragVertAxis.at(i).data(); + if (!ax) { + continue; + } + if (i >= mDragStartVertRange.size()) { + break; + } + if (ax->mScaleType == QCPAxis::stLinear) { + double diff = ax->pixelToCoord(startPos.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 = ax->pixelToCoord(startPos.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(QCustomPlot::rpQueuedReplot); + } + } - - if (mRangeDrag != 0) // if either vertical or horizontal drag was enabled, do a replot - { - if (mParentPlot->noAntialiasingOnDrag()) - mParentPlot->setNotAntialiasedElements(QCP::aeAll); - mParentPlot->replot(QCustomPlot::rpQueuedReplot); - } - - } } /* inherits documentation from base class */ void QCPAxisRect::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos) { - Q_UNUSED(event) - Q_UNUSED(startPos) - mDragging = false; - if (mParentPlot->noAntialiasingOnDrag()) - { - mParentPlot->setAntialiasedElements(mAADragBackup); - mParentPlot->setNotAntialiasedElements(mNotAADragBackup); - } + Q_UNUSED(event) + Q_UNUSED(startPos) + mDragging = false; + if (mParentPlot->noAntialiasingOnDrag()) { + mParentPlot->setAntialiasedElements(mAADragBackup); + mParentPlot->setNotAntialiasedElements(mNotAADragBackup); + } } /*! \internal - + 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 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 wheel is turned rapidly, many steps may bunch up to one event, so the event->delta() may then be multiples of 120. This is taken into account here, by calculating \a wheelSteps and using it as @@ -17926,34 +17954,30 @@ void QCPAxisRect::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos) */ void QCPAxisRect::wheelEvent(QWheelEvent *event) { - // Mouse range zooming interaction: - if (mParentPlot->interactions().testFlag(QCP::iRangeZoom)) - { - if (mRangeZoom != 0) - { - double factor; - double wheelSteps = event->delta()/120.0; // a single step delta is +/-120 usually - if (mRangeZoom.testFlag(Qt::Horizontal)) - { - factor = qPow(mRangeZoomFactorHorz, wheelSteps); - for (int i=0; iscaleRange(factor, mRangeZoomHorzAxis.at(i)->pixelToCoord(event->pos().x())); + // Mouse range zooming interaction: + if (mParentPlot->interactions().testFlag(QCP::iRangeZoom)) { + if (mRangeZoom != 0) { + double factor; + double wheelSteps = event->delta() / 120.0; // a single step delta is +/-120 usually + if (mRangeZoom.testFlag(Qt::Horizontal)) { + factor = qPow(mRangeZoomFactorHorz, wheelSteps); + for (int i = 0; i < mRangeZoomHorzAxis.size(); ++i) { + if (!mRangeZoomHorzAxis.at(i).isNull()) { + mRangeZoomHorzAxis.at(i)->scaleRange(factor, mRangeZoomHorzAxis.at(i)->pixelToCoord(event->pos().x())); + } + } + } + if (mRangeZoom.testFlag(Qt::Vertical)) { + factor = qPow(mRangeZoomFactorVert, wheelSteps); + for (int i = 0; i < mRangeZoomVertAxis.size(); ++i) { + if (!mRangeZoomVertAxis.at(i).isNull()) { + mRangeZoomVertAxis.at(i)->scaleRange(factor, mRangeZoomVertAxis.at(i)->pixelToCoord(event->pos().y())); + } + } + } + mParentPlot->replot(); } - } - if (mRangeZoom.testFlag(Qt::Vertical)) - { - factor = qPow(mRangeZoomFactorVert, wheelSteps); - for (int i=0; iscaleRange(factor, mRangeZoomVertAxis.at(i)->pixelToCoord(event->pos().y())); - } - } - mParentPlot->replot(); } - } } /* end of 'src/layoutelements/layoutelement-axisrect.cpp' */ @@ -17967,16 +17991,16 @@ void QCPAxisRect::wheelEvent(QWheelEvent *event) /*! \class QCPAbstractLegendItem \brief The abstract base class for all entries in a QCPLegend. - + It defines a very basic interface for entries in a QCPLegend. For representing plottables in the legend, the subclass \ref QCPPlottableLegendItem is more suitable. - + Only derive directly from this class when you need absolute freedom (e.g. a custom legend entry that's not even associated with a plottable). You must implement the following pure virtual functions: \li \ref draw (from QCPLayerable) - + You inherit the following members you may use: @@ -17992,7 +18016,7 @@ void QCPAxisRect::wheelEvent(QWheelEvent *event) /* start of documentation of signals */ /*! \fn void QCPAbstractLegendItem::selectionChanged(bool selected) - + This signal is emitted when the selection state of this legend item has changed, either by user interaction or by a direct call to \ref setSelected. */ @@ -18004,142 +18028,144 @@ void QCPAxisRect::wheelEvent(QWheelEvent *event) cause the item to be added to \a parent, so \ref QCPLegend::addItem must be called separately. */ QCPAbstractLegendItem::QCPAbstractLegendItem(QCPLegend *parent) : - QCPLayoutElement(parent->parentPlot()), - mParentLegend(parent), - mFont(parent->font()), - mTextColor(parent->textColor()), - mSelectedFont(parent->selectedFont()), - mSelectedTextColor(parent->selectedTextColor()), - mSelectable(true), - mSelected(false) + QCPLayoutElement(parent->parentPlot()), + mParentLegend(parent), + mFont(parent->font()), + mTextColor(parent->textColor()), + mSelectedFont(parent->selectedFont()), + mSelectedTextColor(parent->selectedTextColor()), + mSelectable(true), + mSelected(false) { - setLayer(QLatin1String("legend")); - setMargins(QMargins(0, 0, 0, 0)); + setLayer(QLatin1String("legend")); + setMargins(QMargins(0, 0, 0, 0)); } /*! Sets the default font of this specific legend item to \a font. - + \see setTextColor, QCPLegend::setFont */ void QCPAbstractLegendItem::setFont(const QFont &font) { - mFont = font; + mFont = font; } /*! Sets the default text color of this specific legend item to \a color. - + \see setFont, QCPLegend::setTextColor */ void QCPAbstractLegendItem::setTextColor(const QColor &color) { - mTextColor = color; + mTextColor = color; } /*! When this legend item is selected, \a font is used to draw generic text, instead of the normal font set with \ref setFont. - + \see setFont, QCPLegend::setSelectedFont */ void QCPAbstractLegendItem::setSelectedFont(const QFont &font) { - mSelectedFont = font; + mSelectedFont = font; } /*! When this legend item is selected, \a color is used to draw generic text, instead of the normal color set with \ref setTextColor. - + \see setTextColor, QCPLegend::setSelectedTextColor */ void QCPAbstractLegendItem::setSelectedTextColor(const QColor &color) { - mSelectedTextColor = color; + mSelectedTextColor = color; } /*! Sets whether this specific legend item is selectable. - + \see setSelectedParts, QCustomPlot::setInteractions */ void QCPAbstractLegendItem::setSelectable(bool selectable) { - if (mSelectable != selectable) - { - mSelectable = selectable; - emit selectableChanged(mSelectable); - } + if (mSelectable != selectable) { + mSelectable = selectable; + emit selectableChanged(mSelectable); + } } /*! Sets whether this specific legend item is selected. - + It is possible to set the selection state of this item by calling this function directly, even if setSelectable is set to false. - + \see setSelectableParts, QCustomPlot::setInteractions */ void QCPAbstractLegendItem::setSelected(bool selected) { - if (mSelected != selected) - { - mSelected = selected; - emit selectionChanged(mSelected); - } + if (mSelected != selected) { + mSelected = selected; + emit selectionChanged(mSelected); + } } /* inherits documentation from base class */ double QCPAbstractLegendItem::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { - Q_UNUSED(details) - if (!mParentPlot) return -1; - if (onlySelectable && (!mSelectable || !mParentLegend->selectableParts().testFlag(QCPLegend::spItems))) - return -1; - - if (mRect.contains(pos.toPoint())) - return mParentPlot->selectionTolerance()*0.99; - else - return -1; + Q_UNUSED(details) + if (!mParentPlot) { + return -1; + } + if (onlySelectable && (!mSelectable || !mParentLegend->selectableParts().testFlag(QCPLegend::spItems))) { + return -1; + } + + if (mRect.contains(pos.toPoint())) { + return mParentPlot->selectionTolerance() * 0.99; + } else { + return -1; + } } /* inherits documentation from base class */ void QCPAbstractLegendItem::applyDefaultAntialiasingHint(QCPPainter *painter) const { - applyAntialiasingHint(painter, mAntialiased, QCP::aeLegendItems); + applyAntialiasingHint(painter, mAntialiased, QCP::aeLegendItems); } /* inherits documentation from base class */ QRect QCPAbstractLegendItem::clipRect() const { - return mOuterRect; + return mOuterRect; } /* inherits documentation from base class */ void QCPAbstractLegendItem::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) { - Q_UNUSED(event) - Q_UNUSED(details) - if (mSelectable && mParentLegend->selectableParts().testFlag(QCPLegend::spItems)) - { - bool selBefore = mSelected; - setSelected(additive ? !mSelected : true); - if (selectionStateChanged) - *selectionStateChanged = mSelected != selBefore; - } + Q_UNUSED(event) + Q_UNUSED(details) + if (mSelectable && mParentLegend->selectableParts().testFlag(QCPLegend::spItems)) { + bool selBefore = mSelected; + setSelected(additive ? !mSelected : true); + if (selectionStateChanged) { + *selectionStateChanged = mSelected != selBefore; + } + } } /* inherits documentation from base class */ void QCPAbstractLegendItem::deselectEvent(bool *selectionStateChanged) { - if (mSelectable && mParentLegend->selectableParts().testFlag(QCPLegend::spItems)) - { - bool selBefore = mSelected; - setSelected(false); - if (selectionStateChanged) - *selectionStateChanged = mSelected != selBefore; - } + if (mSelectable && mParentLegend->selectableParts().testFlag(QCPLegend::spItems)) { + bool selBefore = mSelected; + setSelected(false); + if (selectionStateChanged) { + *selectionStateChanged = mSelected != selBefore; + } + } } //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -18148,13 +18174,13 @@ void QCPAbstractLegendItem::deselectEvent(bool *selectionStateChanged) /*! \class QCPPlottableLegendItem \brief A legend item representing a plottable with an icon and the plottable name. - + This is the standard legend item for plottables. It displays an icon of the plottable next to the plottable name. The icon is drawn by the respective plottable itself (\ref QCPAbstractPlottable::drawLegendIcon), and tries to give an intuitive symbol for the plottable. For example, the QCPGraph draws a centered horizontal line and/or a single scatter point in the middle. - + Legend items of this type are always associated with one plottable (retrievable via the plottable() function and settable with the constructor). You may change the font of the plottable name with \ref setFont. Icon padding and border pen is taken from the parent QCPLegend, see \ref @@ -18162,7 +18188,7 @@ void QCPAbstractLegendItem::deselectEvent(bool *selectionStateChanged) The function \ref QCPAbstractPlottable::addToLegend/\ref QCPAbstractPlottable::removeFromLegend creates/removes legend items of this type. - + Since QCPLegend is based on QCPLayoutGrid, a legend item itself is just a subclass of QCPLayoutElement. While it could be added to a legend (or any other layout) via the normal layout interface, QCPLegend has specialized functions for handling legend items conveniently, see the @@ -18171,101 +18197,104 @@ void QCPAbstractLegendItem::deselectEvent(bool *selectionStateChanged) /*! Creates a new legend item associated with \a plottable. - + Once it's created, it can be added to the legend via \ref QCPLegend::addItem. - + A more convenient way of adding/removing a plottable to/from the legend is via the functions \ref QCPAbstractPlottable::addToLegend and \ref QCPAbstractPlottable::removeFromLegend. */ QCPPlottableLegendItem::QCPPlottableLegendItem(QCPLegend *parent, QCPAbstractPlottable *plottable) : - QCPAbstractLegendItem(parent), - mPlottable(plottable) + QCPAbstractLegendItem(parent), + mPlottable(plottable) { - setAntialiased(false); + setAntialiased(false); } /*! \internal - + Returns the pen that shall be used to draw the icon border, taking into account the selection state of this item. */ QPen QCPPlottableLegendItem::getIconBorderPen() const { - return mSelected ? mParentLegend->selectedIconBorderPen() : mParentLegend->iconBorderPen(); + return mSelected ? mParentLegend->selectedIconBorderPen() : mParentLegend->iconBorderPen(); } /*! \internal - + Returns the text color that shall be used to draw text, taking into account the selection state of this item. */ QColor QCPPlottableLegendItem::getTextColor() const { - return mSelected ? mSelectedTextColor : mTextColor; + return mSelected ? mSelectedTextColor : mTextColor; } /*! \internal - + Returns the font that shall be used to draw text, taking into account the selection state of this item. */ QFont QCPPlottableLegendItem::getFont() const { - return mSelected ? mSelectedFont : mFont; + return mSelected ? mSelectedFont : mFont; } /*! \internal - + Draws the item with \a painter. The size and position of the drawn legend item is defined by the parent layout (typically a \ref QCPLegend) and the \ref minimumOuterSizeHint and \ref maximumOuterSizeHint of this legend item. */ void QCPPlottableLegendItem::draw(QCPPainter *painter) { - if (!mPlottable) return; - painter->setFont(getFont()); - painter->setPen(QPen(getTextColor())); - QSizeF iconSize = mParentLegend->iconSize(); - QRectF textRect = painter->fontMetrics().boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPlottable->name()); - QRectF iconRect(mRect.topLeft(), iconSize); - int textHeight = qMax(textRect.height(), iconSize.height()); // if text has smaller height than icon, center text vertically in icon height, else align tops - painter->drawText(mRect.x()+iconSize.width()+mParentLegend->iconTextPadding(), mRect.y(), textRect.width(), textHeight, Qt::TextDontClip, mPlottable->name()); - // draw icon: - painter->save(); - painter->setClipRect(iconRect, Qt::IntersectClip); - mPlottable->drawLegendIcon(painter, iconRect); - painter->restore(); - // draw icon border: - if (getIconBorderPen().style() != Qt::NoPen) - { - 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); - } + if (!mPlottable) { + return; + } + painter->setFont(getFont()); + painter->setPen(QPen(getTextColor())); + QSizeF iconSize = mParentLegend->iconSize(); + QRectF textRect = painter->fontMetrics().boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPlottable->name()); + QRectF iconRect(mRect.topLeft(), iconSize); + int textHeight = qMax(textRect.height(), iconSize.height()); // if text has smaller height than icon, center text vertically in icon height, else align tops + painter->drawText(mRect.x() + iconSize.width() + mParentLegend->iconTextPadding(), mRect.y(), textRect.width(), textHeight, Qt::TextDontClip, mPlottable->name()); + // draw icon: + painter->save(); + painter->setClipRect(iconRect, Qt::IntersectClip); + mPlottable->drawLegendIcon(painter, iconRect); + painter->restore(); + // draw icon border: + if (getIconBorderPen().style() != Qt::NoPen) { + 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); + } } /*! \internal - + Calculates and returns the size of this item. This includes the icon, the text and the padding in between. - + \seebaseclassmethod */ QSize QCPPlottableLegendItem::minimumOuterSizeHint() const { - if (!mPlottable) return QSize(); - QSize result(0, 0); - QRect textRect; - QFontMetrics fontMetrics(getFont()); - QSize iconSize = mParentLegend->iconSize(); - textRect = fontMetrics.boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPlottable->name()); - result.setWidth(iconSize.width() + mParentLegend->iconTextPadding() + textRect.width()); - result.setHeight(qMax(textRect.height(), iconSize.height())); - result.rwidth() += mMargins.left()+mMargins.right(); - result.rheight() += mMargins.top()+mMargins.bottom(); - return result; + if (!mPlottable) { + return QSize(); + } + QSize result(0, 0); + QRect textRect; + QFontMetrics fontMetrics(getFont()); + QSize iconSize = mParentLegend->iconSize(); + textRect = fontMetrics.boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPlottable->name()); + result.setWidth(iconSize.width() + mParentLegend->iconTextPadding() + textRect.width()); + result.setHeight(qMax(textRect.height(), iconSize.height())); + result.rwidth() += mMargins.left() + mMargins.right(); + result.rheight() += mMargins.top() + mMargins.bottom(); + return result; } @@ -18312,7 +18341,7 @@ QSize QCPPlottableLegendItem::minimumOuterSizeHint() const /*! \fn void QCPLegend::selectionChanged(QCPLegend::SelectableParts selection); This signal is emitted when the selection state of this legend has changed. - + \see setSelectedParts, setSelectableParts */ @@ -18320,60 +18349,60 @@ QSize QCPPlottableLegendItem::minimumOuterSizeHint() const /*! Constructs a new QCPLegend instance with default values. - + Note that by default, QCustomPlot already contains a legend ready to be used as \ref QCustomPlot::legend */ QCPLegend::QCPLegend() { - setFillOrder(QCPLayoutGrid::foRowsFirst); - setWrap(0); - - setRowSpacing(3); - setColumnSpacing(8); - setMargins(QMargins(7, 5, 7, 4)); - setAntialiased(false); - setIconSize(32, 18); - - setIconTextPadding(7); - - setSelectableParts(spLegendBox | spItems); - setSelectedParts(spNone); - - setBorderPen(QPen(Qt::black, 0)); - setSelectedBorderPen(QPen(Qt::blue, 2)); - setIconBorderPen(Qt::NoPen); - setSelectedIconBorderPen(QPen(Qt::blue, 2)); - setBrush(Qt::white); - setSelectedBrush(Qt::white); - setTextColor(Qt::black); - setSelectedTextColor(Qt::blue); + setFillOrder(QCPLayoutGrid::foRowsFirst); + setWrap(0); + + setRowSpacing(3); + setColumnSpacing(8); + setMargins(QMargins(7, 5, 7, 4)); + setAntialiased(false); + setIconSize(32, 18); + + setIconTextPadding(7); + + setSelectableParts(spLegendBox | spItems); + setSelectedParts(spNone); + + setBorderPen(QPen(Qt::black, 0)); + setSelectedBorderPen(QPen(Qt::blue, 2)); + setIconBorderPen(Qt::NoPen); + setSelectedIconBorderPen(QPen(Qt::blue, 2)); + setBrush(Qt::white); + setSelectedBrush(Qt::white); + setTextColor(Qt::black); + setSelectedTextColor(Qt::blue); } QCPLegend::~QCPLegend() { - clearItems(); - if (qobject_cast(mParentPlot)) // make sure this isn't called from QObject dtor when QCustomPlot is already destructed (happens when the legend is not in any layout and thus QObject-child of QCustomPlot) - mParentPlot->legendRemoved(this); + clearItems(); + if (qobject_cast(mParentPlot)) { // make sure this isn't called from QObject dtor when QCustomPlot is already destructed (happens when the legend is not in any layout and thus QObject-child of QCustomPlot) + mParentPlot->legendRemoved(this); + } } /* no doc for getter, see setSelectedParts */ QCPLegend::SelectableParts QCPLegend::selectedParts() const { - // check whether any legend elements selected, if yes, add spItems to return value - bool hasSelectedItems = false; - for (int i=0; iselected()) - { - hasSelectedItems = true; - break; + // check whether any legend elements selected, if yes, add spItems to return value + bool hasSelectedItems = false; + for (int i = 0; i < itemCount(); ++i) { + if (item(i) && item(i)->selected()) { + hasSelectedItems = true; + break; + } + } + if (hasSelectedItems) { + return mSelectedParts | spItems; + } else { + return mSelectedParts & ~spItems; } - } - if (hasSelectedItems) - return mSelectedParts | spItems; - else - return mSelectedParts & ~spItems; } /*! @@ -18381,7 +18410,7 @@ QCPLegend::SelectableParts QCPLegend::selectedParts() const */ void QCPLegend::setBorderPen(const QPen &pen) { - mBorderPen = pen; + mBorderPen = pen; } /*! @@ -18389,45 +18418,45 @@ void QCPLegend::setBorderPen(const QPen &pen) */ void QCPLegend::setBrush(const QBrush &brush) { - mBrush = brush; + mBrush = brush; } /*! Sets the default font of legend text. Legend items that draw text (e.g. the name of a graph) will use this font by default. However, a different font can be specified on a per-item-basis by accessing the specific legend item. - + This function will also set \a font on all already existing legend items. - + \see QCPAbstractLegendItem::setFont */ void QCPLegend::setFont(const QFont &font) { - mFont = font; - for (int i=0; isetFont(mFont); - } + mFont = font; + for (int i = 0; i < itemCount(); ++i) { + if (item(i)) { + item(i)->setFont(mFont); + } + } } /*! Sets the default color of legend text. Legend items that draw text (e.g. the name of a graph) will use this color by default. However, a different colors can be specified on a per-item-basis by accessing the specific legend item. - + This function will also set \a color on all already existing legend items. - + \see QCPAbstractLegendItem::setTextColor */ void QCPLegend::setTextColor(const QColor &color) { - mTextColor = color; - for (int i=0; isetTextColor(color); - } + mTextColor = color; + for (int i = 0; i < itemCount(); ++i) { + if (item(i)) { + item(i)->setTextColor(color); + } + } } /*! @@ -18436,15 +18465,15 @@ void QCPLegend::setTextColor(const QColor &color) */ void QCPLegend::setIconSize(const QSize &size) { - mIconSize = size; + mIconSize = size; } /*! \overload */ void QCPLegend::setIconSize(int width, int height) { - mIconSize.setWidth(width); - mIconSize.setHeight(height); + mIconSize.setWidth(width); + mIconSize.setHeight(height); } /*! @@ -18454,83 +18483,79 @@ void QCPLegend::setIconSize(int width, int height) */ void QCPLegend::setIconTextPadding(int padding) { - mIconTextPadding = padding; + mIconTextPadding = padding; } /*! Sets the pen used to draw a border around each legend icon. Legend items that draw an icon (e.g. a visual representation of the graph) will use this pen by default. - + If no border is wanted, set this to \a Qt::NoPen. */ void QCPLegend::setIconBorderPen(const QPen &pen) { - mIconBorderPen = pen; + mIconBorderPen = pen; } /*! Sets whether the user can (de-)select the parts in \a selectable by clicking on the QCustomPlot surface. (When \ref QCustomPlot::setInteractions contains \ref QCP::iSelectLegend.) - + However, even when \a selectable is set to a value not allowing the selection of a specific part, it is still possible to set the selection of this part manually, by calling \ref setSelectedParts directly. - + \see SelectablePart, setSelectedParts */ void QCPLegend::setSelectableParts(const SelectableParts &selectable) { - if (mSelectableParts != selectable) - { - mSelectableParts = selectable; - emit selectableChanged(mSelectableParts); - } + if (mSelectableParts != selectable) { + mSelectableParts = selectable; + emit selectableChanged(mSelectableParts); + } } /*! Sets the selected state of the respective legend parts described by \ref SelectablePart. When a part is selected, it uses a different pen/font and brush. If some legend items are selected and \a selected doesn't contain \ref spItems, those items become deselected. - + The entire selection mechanism is handled automatically when \ref QCustomPlot::setInteractions contains iSelectLegend. You only need to call this function when you wish to change the selection state manually. - + This function can change the selection state of a part even when \ref setSelectableParts was set to a value that actually excludes the part. - + emits the \ref selectionChanged signal when \a selected is different from the previous selection state. - + Note that it doesn't make sense to set the selected state \ref spItems here when it wasn't set before, because there's no way to specify which exact items to newly select. Do this by calling \ref QCPAbstractLegendItem::setSelected directly on the legend item you wish to select. - + \see SelectablePart, setSelectableParts, selectTest, setSelectedBorderPen, setSelectedIconBorderPen, setSelectedBrush, setSelectedFont */ void QCPLegend::setSelectedParts(const SelectableParts &selected) { - SelectableParts newSelected = selected; - mSelectedParts = this->selectedParts(); // update mSelectedParts in case item selection changed + SelectableParts newSelected = selected; + mSelectedParts = this->selectedParts(); // update mSelectedParts in case item selection changed - if (mSelectedParts != newSelected) - { - if (!mSelectedParts.testFlag(spItems) && newSelected.testFlag(spItems)) // attempt to set spItems flag (can't do that) - { - qDebug() << Q_FUNC_INFO << "spItems flag can not be set, it can only be unset with this function"; - newSelected &= ~spItems; + if (mSelectedParts != newSelected) { + if (!mSelectedParts.testFlag(spItems) && newSelected.testFlag(spItems)) { // attempt to set spItems flag (can't do that) + qDebug() << Q_FUNC_INFO << "spItems flag can not be set, it can only be unset with this function"; + newSelected &= ~spItems; + } + if (mSelectedParts.testFlag(spItems) && !newSelected.testFlag(spItems)) { // spItems flag was unset, so clear item selection + for (int i = 0; i < itemCount(); ++i) { + if (item(i)) { + item(i)->setSelected(false); + } + } + } + mSelectedParts = newSelected; + emit selectionChanged(mSelectedParts); } - if (mSelectedParts.testFlag(spItems) && !newSelected.testFlag(spItems)) // spItems flag was unset, so clear item selection - { - for (int i=0; isetSelected(false); - } - } - mSelectedParts = newSelected; - emit selectionChanged(mSelectedParts); - } } /*! @@ -18541,7 +18566,7 @@ void QCPLegend::setSelectedParts(const SelectableParts &selected) */ void QCPLegend::setSelectedBorderPen(const QPen &pen) { - mSelectedBorderPen = pen; + mSelectedBorderPen = pen; } /*! @@ -18551,7 +18576,7 @@ void QCPLegend::setSelectedBorderPen(const QPen &pen) */ void QCPLegend::setSelectedIconBorderPen(const QPen &pen) { - mSelectedIconBorderPen = pen; + mSelectedIconBorderPen = pen; } /*! @@ -18562,41 +18587,41 @@ void QCPLegend::setSelectedIconBorderPen(const QPen &pen) */ void QCPLegend::setSelectedBrush(const QBrush &brush) { - mSelectedBrush = brush; + mSelectedBrush = brush; } /*! Sets the default font that is used by legend items when they are selected. - + This function will also set \a font on all already existing legend items. \see setFont, QCPAbstractLegendItem::setSelectedFont */ void QCPLegend::setSelectedFont(const QFont &font) { - mSelectedFont = font; - for (int i=0; isetSelectedFont(font); - } + mSelectedFont = font; + for (int i = 0; i < itemCount(); ++i) { + if (item(i)) { + item(i)->setSelectedFont(font); + } + } } /*! Sets the default text color that is used by legend items when they are selected. - + This function will also set \a color on all already existing legend items. \see setTextColor, QCPAbstractLegendItem::setSelectedTextColor */ void QCPLegend::setSelectedTextColor(const QColor &color) { - mSelectedTextColor = color; - for (int i=0; isetSelectedTextColor(color); - } + mSelectedTextColor = color; + for (int i = 0; i < itemCount(); ++i) { + if (item(i)) { + item(i)->setSelectedTextColor(color); + } + } } /*! @@ -18608,26 +18633,25 @@ void QCPLegend::setSelectedTextColor(const QColor &color) */ QCPAbstractLegendItem *QCPLegend::item(int index) const { - return qobject_cast(elementAt(index)); + return qobject_cast(elementAt(index)); } /*! Returns the QCPPlottableLegendItem which is associated with \a plottable (e.g. a \ref QCPGraph*). If such an item isn't in the legend, returns 0. - + \see hasItemWithPlottable */ QCPPlottableLegendItem *QCPLegend::itemWithPlottable(const QCPAbstractPlottable *plottable) const { - for (int i=0; i(item(i))) - { - if (pli->plottable() == plottable) - return pli; + for (int i = 0; i < itemCount(); ++i) { + if (QCPPlottableLegendItem *pli = qobject_cast(item(i))) { + if (pli->plottable() == plottable) { + return pli; + } + } } - } - return 0; + return 0; } /*! @@ -18640,33 +18664,33 @@ QCPPlottableLegendItem *QCPLegend::itemWithPlottable(const QCPAbstractPlottable */ int QCPLegend::itemCount() const { - return elementCount(); + return elementCount(); } /*! Returns whether the legend contains \a item. - + \see hasItemWithPlottable */ bool QCPLegend::hasItem(QCPAbstractLegendItem *item) const { - for (int i=0; iitem(i)) - return true; - } - return false; + for (int i = 0; i < itemCount(); ++i) { + if (item == this->item(i)) { + return true; + } + } + return false; } /*! Returns whether the legend contains a QCPPlottableLegendItem which is associated with \a plottable (e.g. a \ref QCPGraph*). If such an item isn't in the legend, returns false. - + \see itemWithPlottable */ bool QCPLegend::hasItemWithPlottable(const QCPAbstractPlottable *plottable) const { - return itemWithPlottable(plottable); + return itemWithPlottable(plottable); } /*! @@ -18681,7 +18705,7 @@ bool QCPLegend::hasItemWithPlottable(const QCPAbstractPlottable *plottable) cons */ bool QCPLegend::addItem(QCPAbstractLegendItem *item) { - return addElement(item); + return addElement(item); } /*! \overload @@ -18699,14 +18723,15 @@ bool QCPLegend::addItem(QCPAbstractLegendItem *item) */ bool QCPLegend::removeItem(int index) { - if (QCPAbstractLegendItem *ali = item(index)) - { - bool success = remove(ali); - if (success) - setFillOrder(fillOrder(), true); // gets rid of empty cell by reordering - return success; - } else - return false; + if (QCPAbstractLegendItem *ali = item(index)) { + bool success = remove(ali); + if (success) { + setFillOrder(fillOrder(), true); // gets rid of empty cell by reordering + } + return success; + } else { + return false; + } } /*! \overload @@ -18723,10 +18748,11 @@ bool QCPLegend::removeItem(int index) */ bool QCPLegend::removeItem(QCPAbstractLegendItem *item) { - bool success = remove(item); - if (success) - setFillOrder(fillOrder(), true); // gets rid of empty cell by reordering - return success; + bool success = remove(item); + if (success) { + setFillOrder(fillOrder(), true); // gets rid of empty cell by reordering + } + return success; } /*! @@ -18734,28 +18760,28 @@ bool QCPLegend::removeItem(QCPAbstractLegendItem *item) */ void QCPLegend::clearItems() { - for (int i=itemCount()-1; i>=0; --i) - removeItem(i); + for (int i = itemCount() - 1; i >= 0; --i) { + removeItem(i); + } } /*! Returns the legend items that are currently selected. If no items are selected, the list is empty. - + \see QCPAbstractLegendItem::setSelected, setSelectable */ QList QCPLegend::selectedItems() const { - QList result; - for (int i=0; iselected()) - result.append(ali); + QList result; + for (int i = 0; i < itemCount(); ++i) { + if (QCPAbstractLegendItem *ali = item(i)) { + if (ali->selected()) { + result.append(ali); + } + } } - } - return result; + return result; } /*! \internal @@ -18764,112 +18790,117 @@ QList QCPLegend::selectedItems() const before drawing main legend elements. This is the antialiasing state the painter passed to the \ref draw method is in by default. - + 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. - + \seebaseclassmethod - + \see setAntialiased */ void QCPLegend::applyDefaultAntialiasingHint(QCPPainter *painter) const { - applyAntialiasingHint(painter, mAntialiased, QCP::aeLegend); + applyAntialiasingHint(painter, mAntialiased, QCP::aeLegend); } /*! \internal - + Returns the pen used to paint the border of the legend, taking into account the selection state of the legend box. */ QPen QCPLegend::getBorderPen() const { - return mSelectedParts.testFlag(spLegendBox) ? mSelectedBorderPen : mBorderPen; + return mSelectedParts.testFlag(spLegendBox) ? mSelectedBorderPen : mBorderPen; } /*! \internal - + Returns the brush used to paint the background of the legend, taking into account the selection state of the legend box. */ QBrush QCPLegend::getBrush() const { - return mSelectedParts.testFlag(spLegendBox) ? mSelectedBrush : mBrush; + return mSelectedParts.testFlag(spLegendBox) ? mSelectedBrush : mBrush; } /*! \internal - + Draws the legend box with the provided \a painter. The individual legend items are layerables themselves, thus are drawn independently. */ void QCPLegend::draw(QCPPainter *painter) { - // draw background rect: - painter->setBrush(getBrush()); - painter->setPen(getBorderPen()); - painter->drawRect(mOuterRect); + // draw background rect: + painter->setBrush(getBrush()); + painter->setPen(getBorderPen()); + painter->drawRect(mOuterRect); } /* inherits documentation from base class */ double QCPLegend::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { - if (!mParentPlot) return -1; - if (onlySelectable && !mSelectableParts.testFlag(spLegendBox)) + if (!mParentPlot) { + return -1; + } + if (onlySelectable && !mSelectableParts.testFlag(spLegendBox)) { + return -1; + } + + if (mOuterRect.contains(pos.toPoint())) { + if (details) { + details->setValue(spLegendBox); + } + return mParentPlot->selectionTolerance() * 0.99; + } return -1; - - if (mOuterRect.contains(pos.toPoint())) - { - if (details) details->setValue(spLegendBox); - return mParentPlot->selectionTolerance()*0.99; - } - return -1; } /* inherits documentation from base class */ void QCPLegend::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) { - Q_UNUSED(event) - mSelectedParts = selectedParts(); // in case item selection has changed - if (details.value() == spLegendBox && mSelectableParts.testFlag(spLegendBox)) - { - SelectableParts selBefore = mSelectedParts; - setSelectedParts(additive ? mSelectedParts^spLegendBox : mSelectedParts|spLegendBox); // no need to unset spItems in !additive case, because they will be deselected by QCustomPlot (they're normal QCPLayerables with own deselectEvent) - if (selectionStateChanged) - *selectionStateChanged = mSelectedParts != selBefore; - } + Q_UNUSED(event) + mSelectedParts = selectedParts(); // in case item selection has changed + if (details.value() == spLegendBox && mSelectableParts.testFlag(spLegendBox)) { + SelectableParts selBefore = mSelectedParts; + setSelectedParts(additive ? mSelectedParts ^spLegendBox : mSelectedParts | spLegendBox); // no need to unset spItems in !additive case, because they will be deselected by QCustomPlot (they're normal QCPLayerables with own deselectEvent) + if (selectionStateChanged) { + *selectionStateChanged = mSelectedParts != selBefore; + } + } } /* inherits documentation from base class */ void QCPLegend::deselectEvent(bool *selectionStateChanged) { - mSelectedParts = selectedParts(); // in case item selection has changed - if (mSelectableParts.testFlag(spLegendBox)) - { - SelectableParts selBefore = mSelectedParts; - setSelectedParts(selectedParts() & ~spLegendBox); - if (selectionStateChanged) - *selectionStateChanged = mSelectedParts != selBefore; - } + mSelectedParts = selectedParts(); // in case item selection has changed + if (mSelectableParts.testFlag(spLegendBox)) { + SelectableParts selBefore = mSelectedParts; + setSelectedParts(selectedParts() & ~spLegendBox); + if (selectionStateChanged) { + *selectionStateChanged = mSelectedParts != selBefore; + } + } } /* inherits documentation from base class */ QCP::Interaction QCPLegend::selectionCategory() const { - return QCP::iSelectLegend; + return QCP::iSelectLegend; } /* inherits documentation from base class */ QCP::Interaction QCPAbstractLegendItem::selectionCategory() const { - return QCP::iSelectLegend; + return QCP::iSelectLegend; } /* inherits documentation from base class */ void QCPLegend::parentPlotInitialized(QCustomPlot *parentPlot) { - if (parentPlot && !parentPlot->legend) - parentPlot->legend = this; + if (parentPlot && !parentPlot->legend) { + parentPlot->legend = this; + } } /* end of 'src/layoutelements/layoutelement-legend.cpp' */ @@ -18894,10 +18925,10 @@ void QCPLegend::parentPlotInitialized(QCustomPlot *parentPlot) /* start documentation of signals */ /*! \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. - + \see setSelected, setSelectable */ @@ -18918,135 +18949,132 @@ void QCPLegend::parentPlotInitialized(QCustomPlot *parentPlot) /* end documentation of signals */ /*! \overload - + Creates a new QCPTextElement instance and sets default values. The initial text is empty (\ref setText). */ QCPTextElement::QCPTextElement(QCustomPlot *parentPlot) : - QCPLayoutElement(parentPlot), - 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"), 12)), // will be taken from parentPlot if available, see below - mSelectedTextColor(Qt::blue), - mSelectable(false), - mSelected(false) + QCPLayoutElement(parentPlot), + 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"), 12)), // will be taken from parentPlot if available, see below + mSelectedTextColor(Qt::blue), + mSelectable(false), + mSelected(false) { - if (parentPlot) - { - mFont = parentPlot->font(); - mSelectedFont = parentPlot->font(); - } - setMargins(QMargins(2, 2, 2, 2)); + 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. */ QCPTextElement::QCPTextElement(QCustomPlot *parentPlot, const QString &text) : - QCPLayoutElement(parentPlot), - mText(text), - 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"), 12)), // will be taken from parentPlot if available, see below - mSelectedTextColor(Qt::blue), - mSelectable(false), - mSelected(false) + QCPLayoutElement(parentPlot), + mText(text), + 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"), 12)), // will be taken from parentPlot if available, see below + mSelectedTextColor(Qt::blue), + mSelectable(false), + mSelected(false) { - if (parentPlot) - { - mFont = parentPlot->font(); - mSelectedFont = parentPlot->font(); - } - setMargins(QMargins(2, 2, 2, 2)); + 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) + 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)); + 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) + 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)); + 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) + 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)); + 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, setTextFlags */ void QCPTextElement::setText(const QString &text) { - mText = text; + mText = 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 @@ -19065,47 +19093,47 @@ void QCPTextElement::setText(const QString &text) */ void QCPTextElement::setTextFlags(int flags) { - mTextFlags = flags; + mTextFlags = flags; } /*! Sets the \a font of the text. - + \see setTextColor, setSelectedFont */ void QCPTextElement::setFont(const QFont &font) { - mFont = font; + mFont = font; } /*! Sets the \a color of the text. - + \see setFont, setSelectedTextColor */ void QCPTextElement::setTextColor(const QColor &color) { - mTextColor = color; + mTextColor = color; } /*! Sets the \a font of the text that will be used if the text element is selected (\ref setSelected). - + \see setFont */ void QCPTextElement::setSelectedFont(const QFont &font) { - mSelectedFont = font; + mSelectedFont = font; } /*! Sets the \a color of the text that will be used if the text element is selected (\ref setSelected). - + \see setTextColor */ void QCPTextElement::setSelectedTextColor(const QColor &color) { - mSelectedTextColor = color; + mSelectedTextColor = color; } /*! @@ -19116,87 +19144,85 @@ void QCPTextElement::setSelectedTextColor(const QColor &color) */ void QCPTextElement::setSelectable(bool selectable) { - if (mSelectable != selectable) - { - mSelectable = selectable; - emit selectableChanged(mSelectable); - } + if (mSelectable != selectable) { + mSelectable = selectable; + emit selectableChanged(mSelectable); + } } /*! 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 QCPTextElement::setSelected(bool selected) { - if (mSelected != selected) - { - mSelected = selected; - emit selectionChanged(mSelected); - } + if (mSelected != selected) { + mSelected = selected; + emit selectionChanged(mSelected); + } } /* inherits documentation from base class */ void QCPTextElement::applyDefaultAntialiasingHint(QCPPainter *painter) const { - applyAntialiasingHint(painter, mAntialiased, QCP::aeOther); + applyAntialiasingHint(painter, mAntialiased, QCP::aeOther); } /* inherits documentation from base class */ void QCPTextElement::draw(QCPPainter *painter) { - painter->setFont(mainFont()); - painter->setPen(QPen(mainTextColor())); - painter->drawText(mRect, Qt::AlignCenter, mText, &mTextBoundingRect); + painter->setFont(mainFont()); + painter->setPen(QPen(mainTextColor())); + painter->drawText(mRect, Qt::AlignCenter, mText, &mTextBoundingRect); } /* inherits documentation from base class */ QSize QCPTextElement::minimumOuterSizeHint() const { - QFontMetrics metrics(mFont); - QSize result(metrics.boundingRect(0, 0, 0, 0, Qt::AlignCenter, mText).size()); - result.rwidth() += mMargins.left()+mMargins.right(); - result.rheight() += mMargins.top()+mMargins.bottom(); - return result; + QFontMetrics metrics(mFont); + QSize result(metrics.boundingRect(0, 0, 0, 0, Qt::AlignCenter, mText).size()); + result.rwidth() += mMargins.left() + mMargins.right(); + result.rheight() += mMargins.top() + mMargins.bottom(); + return result; } /* inherits documentation from base class */ QSize QCPTextElement::maximumOuterSizeHint() const { - QFontMetrics metrics(mFont); - QSize result(metrics.boundingRect(0, 0, 0, 0, Qt::AlignCenter, mText).size()); - result.setWidth(QWIDGETSIZE_MAX); - result.rheight() += mMargins.top()+mMargins.bottom(); - return result; + QFontMetrics metrics(mFont); + QSize result(metrics.boundingRect(0, 0, 0, 0, Qt::AlignCenter, mText).size()); + result.setWidth(QWIDGETSIZE_MAX); + result.rheight() += mMargins.top() + mMargins.bottom(); + return result; } /* inherits documentation from base class */ void QCPTextElement::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) { - Q_UNUSED(event) - Q_UNUSED(details) - if (mSelectable) - { - bool selBefore = mSelected; - setSelected(additive ? !mSelected : true); - if (selectionStateChanged) - *selectionStateChanged = mSelected != selBefore; - } + Q_UNUSED(event) + Q_UNUSED(details) + if (mSelectable) { + bool selBefore = mSelected; + setSelected(additive ? !mSelected : true); + if (selectionStateChanged) { + *selectionStateChanged = mSelected != selBefore; + } + } } /* inherits documentation from base class */ void QCPTextElement::deselectEvent(bool *selectionStateChanged) { - if (mSelectable) - { - bool selBefore = mSelected; - setSelected(false); - if (selectionStateChanged) - *selectionStateChanged = mSelected != selBefore; - } + if (mSelectable) { + bool selBefore = mSelected; + setSelected(false); + if (selectionStateChanged) { + *selectionStateChanged = mSelected != selBefore; + } + } } /*! @@ -19211,14 +19237,16 @@ void QCPTextElement::deselectEvent(bool *selectionStateChanged) */ double QCPTextElement::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { - Q_UNUSED(details) - if (onlySelectable && !mSelectable) - return -1; - - if (mTextBoundingRect.contains(pos.toPoint())) - return mParentPlot->selectionTolerance()*0.99; - else - return -1; + Q_UNUSED(details) + if (onlySelectable && !mSelectable) { + return -1; + } + + if (mTextBoundingRect.contains(pos.toPoint())) { + return mParentPlot->selectionTolerance() * 0.99; + } else { + return -1; + } } /*! @@ -19229,8 +19257,8 @@ double QCPTextElement::selectTest(const QPointF &pos, bool onlySelectable, QVari */ void QCPTextElement::mousePressEvent(QMouseEvent *event, const QVariant &details) { - Q_UNUSED(details) - event->accept(); + Q_UNUSED(details) + event->accept(); } /*! @@ -19241,8 +19269,9 @@ void QCPTextElement::mousePressEvent(QMouseEvent *event, const QVariant &details */ void QCPTextElement::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos) { - if ((QPointF(event->pos())-startPos).manhattanLength() <= 3) - emit clicked(event); + if ((QPointF(event->pos()) - startPos).manhattanLength() <= 3) { + emit clicked(event); + } } /*! @@ -19252,28 +19281,28 @@ void QCPTextElement::mouseReleaseEvent(QMouseEvent *event, const QPointF &startP */ void QCPTextElement::mouseDoubleClickEvent(QMouseEvent *event, const QVariant &details) { - Q_UNUSED(details) - emit doubleClicked(event); + 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 QCPTextElement::mainFont() const { - return mSelected ? mSelectedFont : mFont; + return mSelected ? mSelectedFont : mFont; } /*! \internal - + Returns the main color to be used. This is mSelectedTextColor if \ref setSelected is set to true, else mTextColor is returned. */ QColor QCPTextElement::mainTextColor() const { - return mSelected ? mSelectedTextColor : mTextColor; + return mSelected ? mSelectedTextColor : mTextColor; } /* end of 'src/layoutelements/layoutelement-textelement.cpp' */ @@ -19288,35 +19317,35 @@ QColor QCPTextElement::mainTextColor() const /*! \class QCPColorScale \brief A color scale for use with color coding data such as QCPColorMap - + This layout element can be placed on the plot to correlate a color gradient with data values. It is usually used in combination with one or multiple \ref QCPColorMap "QCPColorMaps". \image html QCPColorScale.png - + The color scale can be either horizontal or vertical, as shown in the image above. The orientation and the side where the numbers appear is controlled with \ref setType. - + Use \ref QCPColorMap::setColorScale to connect a color map with a color scale. Once they are connected, they share their gradient, data range and data scale type (\ref setGradient, \ref setDataRange, \ref setDataScaleType). Multiple color maps may be associated with a single color scale, to make them all synchronize these properties. - + 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-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 In this case we have placed it to the right of the default axis rect, so it wasn't necessary to call \ref setType, since \ref QCPAxis::atRight is already the default. The text next to the color scale can be set with \ref setLabel. - + For optimum appearance (like in the image above), it may be desirable to line up the axis rect and the borders of the color scale. Use a \ref QCPMarginGroup to achieve this: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolorscale-margingroup - + Color scales are initialized with a non-zero minimum top and bottom margin (\ref setMinimumMargins), because vertical color scales are most common and the minimum top/bottom margin makes sure it keeps some distance to the top/bottom widget border. So if you change to a @@ -19327,14 +19356,14 @@ QColor QCPTextElement::mainTextColor() const /* start documentation of inline functions */ /*! \fn QCPAxis *QCPColorScale::axis() const - + Returns the internal \ref QCPAxis instance of this color scale. You can access it to alter the appearance and behaviour of the axis. \ref QCPColorScale duplicates some properties in its interface for convenience. Those are \ref setDataRange (\ref QCPAxis::setRange), \ref setDataScaleType (\ref QCPAxis::setScaleType), and the method \ref setLabel (\ref QCPAxis::setLabel). As they each are connected, it does not matter whether you use the method on the QCPColorScale or on its QCPAxis. - + If the type of the color scale is changed with \ref setType, the axis returned by this method will change, too, to either the left, right, bottom or top axis, depending on which type was set. */ @@ -19343,23 +19372,23 @@ QColor QCPTextElement::mainTextColor() const /* start documentation of signals */ /*! \fn void QCPColorScale::dataRangeChanged(const QCPRange &newRange); - + This signal is emitted when the data range changes. - + \see setDataRange */ /*! \fn void QCPColorScale::dataScaleTypeChanged(QCPAxis::ScaleType scaleType); - + This signal is emitted when the data scale type changes. - + \see setDataScaleType */ /*! \fn void QCPColorScale::gradientChanged(const QCPColorGradient &newGradient); - + This signal is emitted when the gradient changes. - + \see setGradient */ @@ -19369,182 +19398,175 @@ QColor QCPTextElement::mainTextColor() const Constructs a new QCPColorScale. */ QCPColorScale::QCPColorScale(QCustomPlot *parentPlot) : - QCPLayoutElement(parentPlot), - mType(QCPAxis::atTop), // set to atTop such that setType(QCPAxis::atRight) below doesn't skip work because it thinks it's already atRight - mDataScaleType(QCPAxis::stLinear), - mBarWidth(20), - mAxisRect(new QCPColorScaleAxisRectPrivate(this)) + QCPLayoutElement(parentPlot), + mType(QCPAxis::atTop), // set to atTop such that setType(QCPAxis::atRight) below doesn't skip work because it thinks it's already atRight + mDataScaleType(QCPAxis::stLinear), + mBarWidth(20), + mAxisRect(new QCPColorScaleAxisRectPrivate(this)) { - setMinimumMargins(QMargins(0, 6, 0, 6)); // for default right color scale types, keep some room at bottom and top (important if no margin group is used) - setType(QCPAxis::atRight); - setDataRange(QCPRange(0, 6)); + setMinimumMargins(QMargins(0, 6, 0, 6)); // for default right color scale types, keep some room at bottom and top (important if no margin group is used) + setType(QCPAxis::atRight); + setDataRange(QCPRange(0, 6)); } QCPColorScale::~QCPColorScale() { - delete mAxisRect; + delete mAxisRect; } /* undocumented getter */ QString QCPColorScale::label() const { - if (!mColorAxis) - { - qDebug() << Q_FUNC_INFO << "internal color axis undefined"; - return QString(); - } - - return mColorAxis.data()->label(); + if (!mColorAxis) { + qDebug() << Q_FUNC_INFO << "internal color axis undefined"; + return QString(); + } + + return mColorAxis.data()->label(); } /* undocumented getter */ bool QCPColorScale::rangeDrag() const { - if (!mAxisRect) - { - qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; - return false; - } - - return mAxisRect.data()->rangeDrag().testFlag(QCPAxis::orientation(mType)) && - mAxisRect.data()->rangeDragAxis(QCPAxis::orientation(mType)) && - mAxisRect.data()->rangeDragAxis(QCPAxis::orientation(mType))->orientation() == QCPAxis::orientation(mType); + if (!mAxisRect) { + qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; + return false; + } + + return mAxisRect.data()->rangeDrag().testFlag(QCPAxis::orientation(mType)) && + mAxisRect.data()->rangeDragAxis(QCPAxis::orientation(mType)) && + mAxisRect.data()->rangeDragAxis(QCPAxis::orientation(mType))->orientation() == QCPAxis::orientation(mType); } /* undocumented getter */ bool QCPColorScale::rangeZoom() const { - if (!mAxisRect) - { - qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; - return false; - } - - return mAxisRect.data()->rangeZoom().testFlag(QCPAxis::orientation(mType)) && - mAxisRect.data()->rangeZoomAxis(QCPAxis::orientation(mType)) && - mAxisRect.data()->rangeZoomAxis(QCPAxis::orientation(mType))->orientation() == QCPAxis::orientation(mType); + if (!mAxisRect) { + qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; + return false; + } + + return mAxisRect.data()->rangeZoom().testFlag(QCPAxis::orientation(mType)) && + mAxisRect.data()->rangeZoomAxis(QCPAxis::orientation(mType)) && + mAxisRect.data()->rangeZoomAxis(QCPAxis::orientation(mType))->orientation() == QCPAxis::orientation(mType); } /*! Sets at which side of the color scale the axis is placed, and thus also its orientation. - + 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, label and ticker (the latter will be shared and not copied). */ void QCPColorScale::setType(QCPAxis::AxisType type) { - if (!mAxisRect) - { - qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; - return; - } - if (mType != type) - { - mType = type; - QCPRange rangeTransfer(0, 6); - QString labelTransfer; - 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(); - 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))); + if (!mAxisRect) { + qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; + return; } - QList allAxisTypes = QList() << QCPAxis::atLeft << QCPAxis::atRight << QCPAxis::atBottom << QCPAxis::atTop; - foreach (QCPAxis::AxisType atype, allAxisTypes) - { - mAxisRect.data()->axis(atype)->setTicks(atype == mType); - mAxisRect.data()->axis(atype)->setTickLabels(atype== mType); + if (mType != type) { + mType = type; + QCPRange rangeTransfer(0, 6); + QString labelTransfer; + 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(); + 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))); + } + QList allAxisTypes = QList() << QCPAxis::atLeft << QCPAxis::atRight << QCPAxis::atBottom << QCPAxis::atTop; + foreach (QCPAxis::AxisType atype, allAxisTypes) { + mAxisRect.data()->axis(atype)->setTicks(atype == mType); + mAxisRect.data()->axis(atype)->setTickLabels(atype == mType); + } + // set new mColorAxis pointer: + mColorAxis = mAxisRect.data()->axis(mType); + // transfer settings to new axis: + 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(QList() << mColorAxis.data()); } - // set new mColorAxis pointer: - mColorAxis = mAxisRect.data()->axis(mType); - // transfer settings to new axis: - 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(QList() << mColorAxis.data()); - } } /*! Sets the range spanned by the color gradient and that is shown by the axis in the color scale. - + It is equivalent to calling QCPColorMap::setDataRange on any of the connected color maps. It is also equivalent to directly accessing the \ref axis and setting its range with \ref QCPAxis::setRange. - + \see setDataScaleType, setGradient, rescaleDataRange */ void QCPColorScale::setDataRange(const QCPRange &dataRange) { - if (mDataRange.lower != dataRange.lower || mDataRange.upper != dataRange.upper) - { - mDataRange = dataRange; - if (mColorAxis) - mColorAxis.data()->setRange(mDataRange); - emit dataRangeChanged(mDataRange); - } + if (mDataRange.lower != dataRange.lower || mDataRange.upper != dataRange.upper) { + mDataRange = dataRange; + if (mColorAxis) { + mColorAxis.data()->setRange(mDataRange); + } + emit dataRangeChanged(mDataRange); + } } /*! Sets the scale type of the color scale, i.e. whether values are associated with colors linearly or logarithmically. - + It is equivalent to calling QCPColorMap::setDataScaleType on any of the connected color maps. It is also equivalent to directly accessing the \ref axis and setting its scale type with \ref QCPAxis::setScaleType. - + Note that this method controls the coordinate transformation. For logarithmic scales, you will likely also want to use a logarithmic tick spacing and labeling, which can be achieved by setting the color scale's \ref axis ticker to an instance of \ref QCPAxisTickerLog : - + \snippet documentation/doc-code-snippets/mainwindow.cpp qcpaxisticker-log-colorscale - + See the documentation of \ref QCPAxisTickerLog about the details of logarithmic axis tick creation. - + \see setDataRange, setGradient */ void QCPColorScale::setDataScaleType(QCPAxis::ScaleType scaleType) { - if (mDataScaleType != scaleType) - { - mDataScaleType = scaleType; - if (mColorAxis) - mColorAxis.data()->setScaleType(mDataScaleType); - if (mDataScaleType == QCPAxis::stLogarithmic) - setDataRange(mDataRange.sanitizedForLogScale()); - emit dataScaleTypeChanged(mDataScaleType); - } + if (mDataScaleType != scaleType) { + mDataScaleType = scaleType; + if (mColorAxis) { + mColorAxis.data()->setScaleType(mDataScaleType); + } + if (mDataScaleType == QCPAxis::stLogarithmic) { + setDataRange(mDataRange.sanitizedForLogScale()); + } + emit dataScaleTypeChanged(mDataScaleType); + } } /*! Sets the color gradient that will be used to represent data values. - + It is equivalent to calling QCPColorMap::setGradient on any of the connected color maps. - + \see setDataRange, setDataScaleType */ void QCPColorScale::setGradient(const QCPColorGradient &gradient) { - if (mGradient != gradient) - { - mGradient = gradient; - if (mAxisRect) - mAxisRect.data()->mGradientImageInvalidated = true; - emit gradientChanged(mGradient); - } + if (mGradient != gradient) { + mGradient = gradient; + if (mAxisRect) { + mAxisRect.data()->mGradientImageInvalidated = true; + } + emit gradientChanged(mGradient); + } } /*! @@ -19553,13 +19575,12 @@ void QCPColorScale::setGradient(const QCPColorGradient &gradient) */ void QCPColorScale::setLabel(const QString &str) { - if (!mColorAxis) - { - qDebug() << Q_FUNC_INFO << "internal color axis undefined"; - return; - } - - mColorAxis.data()->setLabel(str); + if (!mColorAxis) { + qDebug() << Q_FUNC_INFO << "internal color axis undefined"; + return; + } + + mColorAxis.data()->setLabel(str); } /*! @@ -19568,213 +19589,200 @@ void QCPColorScale::setLabel(const QString &str) */ void QCPColorScale::setBarWidth(int width) { - mBarWidth = width; + mBarWidth = width; } /*! Sets whether the user can drag the data range (\ref setDataRange). - + Note that \ref QCP::iRangeDrag must be in the QCustomPlot's interactions (\ref QCustomPlot::setInteractions) to allow range dragging. */ void QCPColorScale::setRangeDrag(bool enabled) { - if (!mAxisRect) - { - qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; - return; - } - - if (enabled) - mAxisRect.data()->setRangeDrag(QCPAxis::orientation(mType)); - else - mAxisRect.data()->setRangeDrag(0); + if (!mAxisRect) { + qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; + return; + } + + if (enabled) { + mAxisRect.data()->setRangeDrag(QCPAxis::orientation(mType)); + } else { + mAxisRect.data()->setRangeDrag(0); + } } /*! Sets whether the user can zoom the data range (\ref setDataRange) by scrolling the mouse wheel. - + Note that \ref QCP::iRangeZoom must be in the QCustomPlot's interactions (\ref QCustomPlot::setInteractions) to allow range dragging. */ void QCPColorScale::setRangeZoom(bool enabled) { - if (!mAxisRect) - { - qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; - return; - } - - if (enabled) - mAxisRect.data()->setRangeZoom(QCPAxis::orientation(mType)); - else - mAxisRect.data()->setRangeZoom(0); + if (!mAxisRect) { + qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; + return; + } + + if (enabled) { + mAxisRect.data()->setRangeZoom(QCPAxis::orientation(mType)); + } else { + mAxisRect.data()->setRangeZoom(0); + } } /*! Returns a list of all the color maps associated with this color scale. */ -QList QCPColorScale::colorMaps() const +QList QCPColorScale::colorMaps() const { - QList result; - for (int i=0; iplottableCount(); ++i) - { - if (QCPColorMap *cm = qobject_cast(mParentPlot->plottable(i))) - if (cm->colorScale() == this) - result.append(cm); - } - return result; + QList result; + for (int i = 0; i < mParentPlot->plottableCount(); ++i) { + if (QCPColorMap *cm = qobject_cast(mParentPlot->plottable(i))) + if (cm->colorScale() == this) { + result.append(cm); + } + } + return result; } /*! Changes the data range such that all color maps associated with this color scale are fully mapped to the gradient in the data dimension. - + \see setDataRange */ void QCPColorScale::rescaleDataRange(bool onlyVisibleMaps) { - QList maps = colorMaps(); - QCPRange newRange; - bool haveRange = false; - QCP::SignDomain sign = QCP::sdBoth; - if (mDataScaleType == QCPAxis::stLogarithmic) - sign = (mDataRange.upper < 0 ? QCP::sdNegative : QCP::sdPositive); - for (int i=0; irealVisibility() && onlyVisibleMaps) - continue; - QCPRange mapRange; - if (maps.at(i)->colorScale() == this) - { - bool currentFoundRange = true; - mapRange = maps.at(i)->data()->dataBounds(); - 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 == QCP::sdNegative) - { - if (mapRange.upper >= 0 && mapRange.lower < 0) - mapRange.upper = mapRange.lower*1e-3; - else if (mapRange.upper >= 0 && mapRange.lower >= 0) - currentFoundRange = false; - } - if (currentFoundRange) - { - if (!haveRange) - newRange = mapRange; - else - newRange.expand(mapRange); - haveRange = true; - } + QList maps = colorMaps(); + QCPRange newRange; + bool haveRange = false; + QCP::SignDomain sign = QCP::sdBoth; + if (mDataScaleType == QCPAxis::stLogarithmic) { + sign = (mDataRange.upper < 0 ? QCP::sdNegative : QCP::sdPositive); } - } - if (haveRange) - { - if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this dimension), shift current range to at least center the data - { - double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason - if (mDataScaleType == QCPAxis::stLinear) - { - newRange.lower = center-mDataRange.size()/2.0; - newRange.upper = center+mDataRange.size()/2.0; - } else // mScaleType == stLogarithmic - { - newRange.lower = center/qSqrt(mDataRange.upper/mDataRange.lower); - newRange.upper = center*qSqrt(mDataRange.upper/mDataRange.lower); - } + for (int i = 0; i < maps.size(); ++i) { + if (!maps.at(i)->realVisibility() && onlyVisibleMaps) { + continue; + } + QCPRange mapRange; + if (maps.at(i)->colorScale() == this) { + bool currentFoundRange = true; + mapRange = maps.at(i)->data()->dataBounds(); + 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 == QCP::sdNegative) { + if (mapRange.upper >= 0 && mapRange.lower < 0) { + mapRange.upper = mapRange.lower * 1e-3; + } else if (mapRange.upper >= 0 && mapRange.lower >= 0) { + currentFoundRange = false; + } + } + if (currentFoundRange) { + if (!haveRange) { + newRange = mapRange; + } else { + newRange.expand(mapRange); + } + haveRange = true; + } + } + } + if (haveRange) { + if (!QCPRange::validRange(newRange)) { // likely due to range being zero (plottable has only constant data in this dimension), shift current range to at least center the data + double center = (newRange.lower + newRange.upper) * 0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason + if (mDataScaleType == QCPAxis::stLinear) { + newRange.lower = center - mDataRange.size() / 2.0; + newRange.upper = center + mDataRange.size() / 2.0; + } else { // mScaleType == stLogarithmic + newRange.lower = center / qSqrt(mDataRange.upper / mDataRange.lower); + newRange.upper = center * qSqrt(mDataRange.upper / mDataRange.lower); + } + } + setDataRange(newRange); } - setDataRange(newRange); - } } /* inherits documentation from base class */ void QCPColorScale::update(UpdatePhase phase) { - QCPLayoutElement::update(phase); - if (!mAxisRect) - { - qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; - return; - } - - mAxisRect.data()->update(phase); - - switch (phase) - { - case upMargins: - { - if (mType == QCPAxis::atBottom || mType == QCPAxis::atTop) - { - setMaximumSize(QWIDGETSIZE_MAX, mBarWidth+mAxisRect.data()->margins().top()+mAxisRect.data()->margins().bottom()); - setMinimumSize(0, mBarWidth+mAxisRect.data()->margins().top()+mAxisRect.data()->margins().bottom()); - } else - { - setMaximumSize(mBarWidth+mAxisRect.data()->margins().left()+mAxisRect.data()->margins().right(), QWIDGETSIZE_MAX); - setMinimumSize(mBarWidth+mAxisRect.data()->margins().left()+mAxisRect.data()->margins().right(), 0); - } - break; + QCPLayoutElement::update(phase); + if (!mAxisRect) { + qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; + return; } - case upLayout: - { - mAxisRect.data()->setOuterRect(rect()); - break; + + mAxisRect.data()->update(phase); + + switch (phase) { + case upMargins: { + if (mType == QCPAxis::atBottom || mType == QCPAxis::atTop) { + setMaximumSize(QWIDGETSIZE_MAX, mBarWidth + mAxisRect.data()->margins().top() + mAxisRect.data()->margins().bottom()); + setMinimumSize(0, mBarWidth + mAxisRect.data()->margins().top() + mAxisRect.data()->margins().bottom()); + } else { + setMaximumSize(mBarWidth + mAxisRect.data()->margins().left() + mAxisRect.data()->margins().right(), QWIDGETSIZE_MAX); + setMinimumSize(mBarWidth + mAxisRect.data()->margins().left() + mAxisRect.data()->margins().right(), 0); + } + break; + } + case upLayout: { + mAxisRect.data()->setOuterRect(rect()); + break; + } + default: + break; } - default: break; - } } /* inherits documentation from base class */ void QCPColorScale::applyDefaultAntialiasingHint(QCPPainter *painter) const { - painter->setAntialiasing(false); + painter->setAntialiasing(false); } /* inherits documentation from base class */ void QCPColorScale::mousePressEvent(QMouseEvent *event, const QVariant &details) { - if (!mAxisRect) - { - qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; - return; - } - mAxisRect.data()->mousePressEvent(event, details); + if (!mAxisRect) { + qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; + return; + } + mAxisRect.data()->mousePressEvent(event, details); } /* inherits documentation from base class */ void QCPColorScale::mouseMoveEvent(QMouseEvent *event, const QPointF &startPos) { - if (!mAxisRect) - { - qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; - return; - } - mAxisRect.data()->mouseMoveEvent(event, startPos); + if (!mAxisRect) { + qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; + return; + } + mAxisRect.data()->mouseMoveEvent(event, startPos); } /* inherits documentation from base class */ void QCPColorScale::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos) { - if (!mAxisRect) - { - qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; - return; - } - mAxisRect.data()->mouseReleaseEvent(event, startPos); + if (!mAxisRect) { + qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; + return; + } + mAxisRect.data()->mouseReleaseEvent(event, startPos); } /* inherits documentation from base class */ void QCPColorScale::wheelEvent(QWheelEvent *event) { - if (!mAxisRect) - { - qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; - return; - } - mAxisRect.data()->wheelEvent(event); + if (!mAxisRect) { + qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; + return; + } + mAxisRect.data()->wheelEvent(event); } //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -19785,9 +19793,9 @@ void QCPColorScale::wheelEvent(QWheelEvent *event) \internal \brief An axis rect subclass for use in a QCPColorScale - + This is a private class and not part of the public QCustomPlot interface. - + It provides the axis rect functionality for the QCPColorScale class. */ @@ -19796,60 +19804,60 @@ void QCPColorScale::wheelEvent(QWheelEvent *event) Creates a new instance, as a child of \a parentColorScale. */ QCPColorScaleAxisRectPrivate::QCPColorScaleAxisRectPrivate(QCPColorScale *parentColorScale) : - QCPAxisRect(parentColorScale->parentPlot(), true), - mParentColorScale(parentColorScale), - mGradientImageInvalidated(true) + QCPAxisRect(parentColorScale->parentPlot(), true), + mParentColorScale(parentColorScale), + mGradientImageInvalidated(true) { - setParentLayerable(parentColorScale); - setMinimumMargins(QMargins(0, 0, 0, 0)); - QList allAxisTypes = QList() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight; - foreach (QCPAxis::AxisType type, allAxisTypes) - { - axis(type)->setVisible(true); - axis(type)->grid()->setVisible(false); - axis(type)->setPadding(0); - connect(axis(type), SIGNAL(selectionChanged(QCPAxis::SelectableParts)), this, SLOT(axisSelectionChanged(QCPAxis::SelectableParts))); - connect(axis(type), SIGNAL(selectableChanged(QCPAxis::SelectableParts)), this, SLOT(axisSelectableChanged(QCPAxis::SelectableParts))); - } + setParentLayerable(parentColorScale); + setMinimumMargins(QMargins(0, 0, 0, 0)); + QList allAxisTypes = QList() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight; + foreach (QCPAxis::AxisType type, allAxisTypes) { + axis(type)->setVisible(true); + axis(type)->grid()->setVisible(false); + axis(type)->setPadding(0); + connect(axis(type), SIGNAL(selectionChanged(QCPAxis::SelectableParts)), this, SLOT(axisSelectionChanged(QCPAxis::SelectableParts))); + connect(axis(type), SIGNAL(selectableChanged(QCPAxis::SelectableParts)), this, SLOT(axisSelectableChanged(QCPAxis::SelectableParts))); + } - connect(axis(QCPAxis::atLeft), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atRight), SLOT(setRange(QCPRange))); - connect(axis(QCPAxis::atRight), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atLeft), SLOT(setRange(QCPRange))); - connect(axis(QCPAxis::atBottom), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atTop), SLOT(setRange(QCPRange))); - connect(axis(QCPAxis::atTop), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atBottom), SLOT(setRange(QCPRange))); - connect(axis(QCPAxis::atLeft), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atRight), SLOT(setScaleType(QCPAxis::ScaleType))); - connect(axis(QCPAxis::atRight), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atLeft), SLOT(setScaleType(QCPAxis::ScaleType))); - connect(axis(QCPAxis::atBottom), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atTop), SLOT(setScaleType(QCPAxis::ScaleType))); - connect(axis(QCPAxis::atTop), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atBottom), SLOT(setScaleType(QCPAxis::ScaleType))); - - // make layer transfers of color scale transfer to axis rect and axes - // the axes must be set after axis rect, such that they appear above color gradient drawn by axis rect: - connect(parentColorScale, SIGNAL(layerChanged(QCPLayer*)), this, SLOT(setLayer(QCPLayer*))); - foreach (QCPAxis::AxisType type, allAxisTypes) - connect(parentColorScale, SIGNAL(layerChanged(QCPLayer*)), axis(type), SLOT(setLayer(QCPLayer*))); + connect(axis(QCPAxis::atLeft), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atRight), SLOT(setRange(QCPRange))); + connect(axis(QCPAxis::atRight), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atLeft), SLOT(setRange(QCPRange))); + connect(axis(QCPAxis::atBottom), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atTop), SLOT(setRange(QCPRange))); + connect(axis(QCPAxis::atTop), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atBottom), SLOT(setRange(QCPRange))); + connect(axis(QCPAxis::atLeft), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atRight), SLOT(setScaleType(QCPAxis::ScaleType))); + connect(axis(QCPAxis::atRight), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atLeft), SLOT(setScaleType(QCPAxis::ScaleType))); + connect(axis(QCPAxis::atBottom), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atTop), SLOT(setScaleType(QCPAxis::ScaleType))); + connect(axis(QCPAxis::atTop), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atBottom), SLOT(setScaleType(QCPAxis::ScaleType))); + + // make layer transfers of color scale transfer to axis rect and axes + // the axes must be set after axis rect, such that they appear above color gradient drawn by axis rect: + connect(parentColorScale, SIGNAL(layerChanged(QCPLayer *)), this, SLOT(setLayer(QCPLayer *))); + foreach (QCPAxis::AxisType type, allAxisTypes) { + connect(parentColorScale, SIGNAL(layerChanged(QCPLayer *)), axis(type), SLOT(setLayer(QCPLayer *))); + } } /*! \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) { - if (mGradientImageInvalidated) - updateGradientImage(); - - bool mirrorHorz = false; - bool mirrorVert = false; - if (mParentColorScale->mColorAxis) - { - mirrorHorz = mParentColorScale->mColorAxis.data()->rangeReversed() && (mParentColorScale->type() == QCPAxis::atBottom || mParentColorScale->type() == QCPAxis::atTop); - mirrorVert = mParentColorScale->mColorAxis.data()->rangeReversed() && (mParentColorScale->type() == QCPAxis::atLeft || mParentColorScale->type() == QCPAxis::atRight); - } - - painter->drawImage(rect().adjusted(0, -1, 0, -1), mGradientImage.mirrored(mirrorHorz, mirrorVert)); - QCPAxisRect::draw(painter); + if (mGradientImageInvalidated) { + updateGradientImage(); + } + + bool mirrorHorz = false; + bool mirrorVert = false; + if (mParentColorScale->mColorAxis) { + mirrorHorz = mParentColorScale->mColorAxis.data()->rangeReversed() && (mParentColorScale->type() == QCPAxis::atBottom || mParentColorScale->type() == QCPAxis::atTop); + mirrorVert = mParentColorScale->mColorAxis.data()->rangeReversed() && (mParentColorScale->type() == QCPAxis::atLeft || mParentColorScale->type() == QCPAxis::atRight); + } + + painter->drawImage(rect().adjusted(0, -1, 0, -1), mGradientImage.mirrored(mirrorHorz, mirrorVert)); + QCPAxisRect::draw(painter); } /*! \internal @@ -19859,40 +19867,42 @@ void QCPColorScaleAxisRectPrivate::draw(QCPPainter *painter) */ 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); - for (int i=0; imType == QCPAxis::atBottom || mParentColorScale->mType == QCPAxis::atTop) - { - w = n; - h = rect().height(); - mGradientImage = QImage(w, h, format); - QVector pixels; - for (int y=0; y(mGradientImage.scanLine(y))); - mParentColorScale->mGradient.colorize(data.constData(), QCPRange(0, n-1), pixels.first(), n); - for (int y=1; y(mGradientImage.scanLine(y)); - const QRgb lineColor = mParentColorScale->mGradient.color(data[h-1-y], QCPRange(0, n-1)); - for (int x=0; xmGradient.levelCount(); + int w, h; + QVector data(n); + for (int i = 0; i < n; ++i) { + data[i] = i; + } + if (mParentColorScale->mType == QCPAxis::atBottom || mParentColorScale->mType == QCPAxis::atTop) { + w = n; + h = rect().height(); + mGradientImage = QImage(w, h, format); + QVector pixels; + for (int y = 0; y < h; ++y) { + pixels.append(reinterpret_cast(mGradientImage.scanLine(y))); + } + mParentColorScale->mGradient.colorize(data.constData(), QCPRange(0, n - 1), pixels.first(), n); + for (int y = 1; y < h; ++y) { + memcpy(pixels.at(y), pixels.first(), n * sizeof(QRgb)); + } + } else { + w = rect().width(); + h = n; + mGradientImage = QImage(w, h, format); + for (int y = 0; y < h; ++y) { + QRgb *pixels = reinterpret_cast(mGradientImage.scanLine(y)); + const QRgb lineColor = mParentColorScale->mGradient.color(data[h - 1 - y], QCPRange(0, n - 1)); + for (int x = 0; x < w; ++x) { + pixels[x] = lineColor; + } + } + } + mGradientImageInvalidated = false; } /*! \internal @@ -19902,22 +19912,22 @@ void QCPColorScaleAxisRectPrivate::updateGradientImage() */ void QCPColorScaleAxisRectPrivate::axisSelectionChanged(QCPAxis::SelectableParts selectedParts) { - // axis bases of four axes shall always (de-)selected synchronously: - QList allAxisTypes = QList() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight; - foreach (QCPAxis::AxisType type, allAxisTypes) - { - if (QCPAxis *senderAxis = qobject_cast(sender())) - if (senderAxis->axisType() == type) - continue; - - if (axis(type)->selectableParts().testFlag(QCPAxis::spAxis)) - { - if (selectedParts.testFlag(QCPAxis::spAxis)) - axis(type)->setSelectedParts(axis(type)->selectedParts() | QCPAxis::spAxis); - else - axis(type)->setSelectedParts(axis(type)->selectedParts() & ~QCPAxis::spAxis); + // axis bases of four axes shall always (de-)selected synchronously: + QList allAxisTypes = QList() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight; + foreach (QCPAxis::AxisType type, allAxisTypes) { + if (QCPAxis *senderAxis = qobject_cast(sender())) + if (senderAxis->axisType() == type) { + continue; + } + + if (axis(type)->selectableParts().testFlag(QCPAxis::spAxis)) { + if (selectedParts.testFlag(QCPAxis::spAxis)) { + axis(type)->setSelectedParts(axis(type)->selectedParts() | QCPAxis::spAxis); + } else { + axis(type)->setSelectedParts(axis(type)->selectedParts() & ~QCPAxis::spAxis); + } + } } - } } /*! \internal @@ -19927,22 +19937,22 @@ void QCPColorScaleAxisRectPrivate::axisSelectionChanged(QCPAxis::SelectableParts */ void QCPColorScaleAxisRectPrivate::axisSelectableChanged(QCPAxis::SelectableParts selectableParts) { - // synchronize axis base selectability: - QList allAxisTypes = QList() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight; - foreach (QCPAxis::AxisType type, allAxisTypes) - { - if (QCPAxis *senderAxis = qobject_cast(sender())) - if (senderAxis->axisType() == type) - continue; - - if (axis(type)->selectableParts().testFlag(QCPAxis::spAxis)) - { - if (selectableParts.testFlag(QCPAxis::spAxis)) - axis(type)->setSelectableParts(axis(type)->selectableParts() | QCPAxis::spAxis); - else - axis(type)->setSelectableParts(axis(type)->selectableParts() & ~QCPAxis::spAxis); + // synchronize axis base selectability: + QList allAxisTypes = QList() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight; + foreach (QCPAxis::AxisType type, allAxisTypes) { + if (QCPAxis *senderAxis = qobject_cast(sender())) + if (senderAxis->axisType() == type) { + continue; + } + + if (axis(type)->selectableParts().testFlag(QCPAxis::spAxis)) { + if (selectableParts.testFlag(QCPAxis::spAxis)) { + axis(type)->setSelectableParts(axis(type)->selectableParts() | QCPAxis::spAxis); + } else { + axis(type)->setSelectableParts(axis(type)->selectableParts() & ~QCPAxis::spAxis); + } + } } - } } /* end of 'src/layoutelements/layoutelement-colorscale.cpp' */ @@ -19956,65 +19966,65 @@ void QCPColorScaleAxisRectPrivate::axisSelectableChanged(QCPAxis::SelectablePart /*! \class QCPGraphData \brief Holds the data of one single data point for QCPGraph. - + 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 value: coordinate on the value axis of this data point (this is the \a mainValue) - + The container for storing multiple data points is \ref QCPGraphDataContainer. It is a typedef for \ref QCPDataContainer with \ref QCPGraphData as the DataType template parameter. See the documentation there for an explanation regarding the data type's generic methods. - + \see QCPGraphDataContainer */ /* start documentation of inline functions */ /*! \fn double QCPGraphData::sortKey() const - + Returns the \a key member of this data point. - + For a general explanation of what this method is good for in the context of the data container, see the documentation of \ref QCPDataContainer. */ /*! \fn static QCPGraphData QCPGraphData::fromSortKey(double sortKey) - + Returns a data point with the specified \a sortKey. All other members are set to zero. - + For a general explanation of what this method is good for in the context of the data container, see the documentation of \ref QCPDataContainer. */ /*! \fn static static bool QCPGraphData::sortKeyIsMainKey() - + Since the member \a key is both the data point key coordinate and the data ordering parameter, this method returns true. - + For a general explanation of what this method is good for in the context of the data container, see the documentation of \ref QCPDataContainer. */ /*! \fn double QCPGraphData::mainKey() const - + Returns the \a key member of this data point. - + For a general explanation of what this method is good for in the context of the data container, see the documentation of \ref QCPDataContainer. */ /*! \fn double QCPGraphData::mainValue() const - + Returns the \a value member of this data point. - + For a general explanation of what this method is good for in the context of the data container, see the documentation of \ref QCPDataContainer. */ /*! \fn QCPRange QCPGraphData::valueRange() const - + Returns a QCPRange with both lower and upper boundary set to \a value of this data point. - + For a general explanation of what this method is good for in the context of the data container, see the documentation of \ref QCPDataContainer. */ @@ -20025,8 +20035,8 @@ void QCPColorScaleAxisRectPrivate::axisSelectableChanged(QCPAxis::SelectablePart Constructs a data point with key and value set to zero. */ QCPGraphData::QCPGraphData() : - key(0), - value(0) + key(0), + value(0) { } @@ -20034,8 +20044,8 @@ QCPGraphData::QCPGraphData() : Constructs a data point with the specified \a key and \a value. */ QCPGraphData::QCPGraphData(double key, double value) : - key(key), - value(value) + key(key), + value(value) { } @@ -20048,33 +20058,33 @@ QCPGraphData::QCPGraphData(double key, double value) : \brief A plottable representing a graph in a plot. \image html QCPGraph.png - + 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 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 want to plot non-single-valued curves, rather use the QCPCurve plottable. - + Gaps in the graph line can be created by adding data points with NaN as value (qQNaN() or std::numeric_limits::quiet_NaN()) in between the two data points that shall be separated. - + \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). - + \subsection filling Filling under or between graphs - + QCPGraph knows two types of fills: Normal graph fills towards the zero-value-line parallel to the key axis of the graph, and fills between two graphs, called channel fills. To enable a fill, just set a brush with \ref setBrush which is neither Qt::NoBrush nor fully transparent. - + By default, a normal fill towards the zero-value-line will be drawn. To set up a channel fill between this graph and another one, call \ref setChannelFillGraph with the other graph as parameter. @@ -20085,7 +20095,7 @@ QCPGraphData::QCPGraphData(double key, double value) : /* start of documentation of inline functions */ /*! \fn QSharedPointer QCPGraph::data() const - + 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. @@ -20098,26 +20108,26 @@ QCPGraphData::QCPGraphData(double key, double 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 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) : - QCPAbstractPlottable1D(keyAxis, valueAxis) + QCPAbstractPlottable1D(keyAxis, valueAxis) { - // special handling for QCPGraphs to maintain the simple graph interface: - mParentPlot->registerGraph(this); + // special handling for QCPGraphs to maintain the simple graph interface: + mParentPlot->registerGraph(this); - setPen(QPen(Qt::blue, 0)); - setBrush(Qt::NoBrush); - - setLineStyle(lsLine); - setScatterSkip(0); - setChannelFillGraph(0); - setAdaptiveSampling(true); + setPen(QPen(Qt::blue, 0)); + setBrush(Qt::NoBrush); + + setLineStyle(lsLine); + setScatterSkip(0); + setChannelFillGraph(0); + setAdaptiveSampling(true); } QCPGraph::~QCPGraph() @@ -20125,62 +20135,62 @@ QCPGraph::~QCPGraph() } /*! \overload - + 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; + 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 QCPGraph::setData(const QVector &keys, const QVector &values, bool alreadySorted) { - mDataContainer->clear(); - addData(keys, values, alreadySorted); + mDataContainer->clear(); + addData(keys, values, alreadySorted); } /*! Sets how the single data points are connected in the plot. For scatter-only plots, set \a ls to \ref lsNone and \ref setScatterStyle to the desired scatter style. - + \see setScatterStyle */ void QCPGraph::setLineStyle(LineStyle ls) { - mLineStyle = ls; + mLineStyle = ls; } /*! Sets the visual appearance of single data points in the plot. If set to \ref QCPScatterStyle::ssNone, no scatter points are drawn (e.g. for line-only-plots with appropriate line style). - + \see QCPScatterStyle, setLineStyle */ void QCPGraph::setScatterStyle(const QCPScatterStyle &style) { - mScatterStyle = style; + mScatterStyle = style; } /*! @@ -20196,13 +20206,13 @@ void QCPGraph::setScatterStyle(const QCPScatterStyle &style) */ void QCPGraph::setScatterSkip(int skip) { - mScatterSkip = qMax(0, skip); + mScatterSkip = qMax(0, skip); } /*! Sets the target graph for filling the area between this graph and \a targetGraph with the current brush (\ref setBrush). - + When \a targetGraph is set to 0, a normal graph fill to the zero-value-line will be shown. To disable any filling, set the brush to Qt::NoBrush. @@ -20210,41 +20220,39 @@ void QCPGraph::setScatterSkip(int skip) */ void QCPGraph::setChannelFillGraph(QCPGraph *targetGraph) { - // prevent setting channel target to this graph itself: - if (targetGraph == this) - { - qDebug() << Q_FUNC_INFO << "targetGraph is this graph itself"; - mChannelFillGraph = 0; - return; - } - // prevent setting channel target to a graph not in the plot: - if (targetGraph && targetGraph->mParentPlot != mParentPlot) - { - qDebug() << Q_FUNC_INFO << "targetGraph not in same plot"; - mChannelFillGraph = 0; - return; - } - - mChannelFillGraph = targetGraph; + // prevent setting channel target to this graph itself: + if (targetGraph == this) { + qDebug() << Q_FUNC_INFO << "targetGraph is this graph itself"; + mChannelFillGraph = 0; + return; + } + // prevent setting channel target to a graph not in the plot: + if (targetGraph && targetGraph->mParentPlot != mParentPlot) { + qDebug() << Q_FUNC_INFO << "targetGraph not in same plot"; + mChannelFillGraph = 0; + return; + } + + mChannelFillGraph = targetGraph; } /*! Sets whether adaptive sampling shall be used when plotting this graph. QCustomPlot's adaptive sampling technique can drastically improve the replot performance for graphs with a larger number of points (e.g. above 10,000), without notably changing the appearance of the graph. - + By default, adaptive sampling is enabled. Even if enabled, QCustomPlot decides whether adaptive sampling shall actually be used on a per-graph basis. So leaving adaptive sampling enabled has no disadvantage in almost all cases. - + \image html adaptive-sampling-line.png "A line plot of 500,000 points without and with adaptive sampling" - + As can be seen, line plots experience no visual degradation from adaptive sampling. Outliers are reproduced reliably, as well as the overall shape of the data set. The replot time reduces dramatically though. This allows QCustomPlot to display large amounts of data in realtime. - + \image html adaptive-sampling-scatter.png "A scatter plot of 100,000 points without and with adaptive sampling" - + Care must be taken when using high-density scatter plots in combination with adaptive sampling. The adaptive sampling algorithm treats scatter plots more carefully than line plots which still gives a significant reduction of replot times, but not quite as much as for line plots. This is @@ -20253,7 +20261,7 @@ void QCPGraph::setChannelFillGraph(QCPGraph *targetGraph) identical, as banding occurs for the outer data points. This is in fact intentional, such that the boundaries of the data cloud stay visible to the viewer. How strong the banding appears, depends on the point density, i.e. the number of points in the plot. - + For some situations with scatter plots it might thus be desirable to manually turn adaptive sampling off. For example, when saving the plot to disk. This can be achieved by setting \a enabled to false before issuing a command like \ref QCustomPlot::savePng, and setting \a enabled @@ -20261,50 +20269,50 @@ void QCPGraph::setChannelFillGraph(QCPGraph *targetGraph) */ void QCPGraph::setAdaptiveSampling(bool enabled) { - mAdaptiveSampling = enabled; + mAdaptiveSampling = enabled; } /*! \overload - + 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 QCPGraph::addData(const QVector &keys, const QVector &values, bool alreadySorted) { - 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 + 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 data point as \a key and \a value to the current data. - + Alternatively, you can also access and modify the data directly via the \ref data method, which returns a pointer to the internal data container. */ void QCPGraph::addData(double key, double value) { - mDataContainer->add(QCPGraphData(key, value)); + mDataContainer->add(QCPGraphData(key, value)); } /*! @@ -20312,143 +20320,148 @@ void QCPGraph::addData(double key, double value) If \a details is not 0, it will be set to a \ref QCPDataSelection, describing the closest data point to \a pos. - + \seebaseclassmethod \ref QCPAbstractPlottable::selectTest */ double QCPGraph::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { - if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty()) - return -1; - if (!mKeyAxis || !mValueAxis) - return -1; - - if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint())) - { - 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))); + if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty()) { + return -1; + } + if (!mKeyAxis || !mValueAxis) { + return -1; + } + + if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint())) { + 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; } - return result; - } else - return -1; } /* inherits documentation from base class */ QCPRange QCPGraph::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const { - return mDataContainer->keyRange(foundRange, inSignDomain); + return mDataContainer->keyRange(foundRange, inSignDomain); } /* inherits documentation from base class */ QCPRange QCPGraph::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const { - return mDataContainer->valueRange(foundRange, inSignDomain, inKeyRange); + 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 || mDataContainer->isEmpty()) return; - if (mLineStyle == lsNone && mScatterStyle.isNone()) return; - - QVector lines, scatters; // line and (if necessary) scatter pixel coordinates will be stored here while iterating over segments - - // 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: + if (!mKeyAxis || !mValueAxis) { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + return; + } + if (mKeyAxis.data()->range().size() <= 0 || mDataContainer->isEmpty()) { + return; + } + if (mLineStyle == lsNone && mScatterStyle.isNone()) { + return; + } + + QVector lines, scatters; // line and (if necessary) scatter pixel coordinates will be stored here while iterating over segments + + // loop over and draw segments of unselected/selected data: + QList selectedSegments, unselectedSegments, allSegments; + getDataSegments(selectedSegments, unselectedSegments); + allSegments << unselectedSegments << selectedSegments; + for (int i = 0; i < allSegments.size(); ++i) { + bool isSelectedSegment = i >= unselectedSegments.size(); + // get line pixel points appropriate to line style: + QCPDataRange lineDataRange = isSelectedSegment ? allSegments.at(i) : allSegments.at(i).adjusted(-1, 1); // unselected segments extend lines to bordering selected data point (safe to exceed total data bounds in first/last segment, getLines takes care) + getLines(&lines, lineDataRange); + + // check data validity if flag set: #ifdef QCUSTOMPLOT_CHECK_DATA - QCPGraphDataContainer::const_iterator it; - for (it = mDataContainer->constBegin(); it != mDataContainer->constEnd(); ++it) - { - if (QCP::isInvalidData(it->key, it->value)) - qDebug() << Q_FUNC_INFO << "Data point at" << it->key << "invalid." << "Plottable name:" << name(); - } + 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: - 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 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 scatters: - QCPScatterStyle finalScatterStyle = mScatterStyle; - if (isSelectedSegment && mSelectionDecorator) - finalScatterStyle = mSelectionDecorator->getFinalScatterStyle(mScatterStyle); - if (!finalScatterStyle.isNone()) - { - getScatters(&scatters, allSegments.at(i)); - drawScatterPlot(painter, scatters, finalScatterStyle); + + // draw other selection decoration that isn't just line/scatter pens and brushes: + if (mSelectionDecorator) { + mSelectionDecorator->drawDecoration(painter, selection()); } - } - - // 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 QCPGraph::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const { - // draw fill: - if (mBrush.style() != Qt::NoBrush) - { - applyFillAntialiasingHint(painter); - painter->fillRect(QRectF(rect.left(), rect.top()+rect.height()/2.0, rect.width(), rect.height()/3.0), mBrush); - } - // draw line vertically centered: - if (mLineStyle != lsNone) - { - applyDefaultAntialiasingHint(painter); - painter->setPen(mPen); - painter->drawLine(QLineF(rect.left(), rect.top()+rect.height()/2.0, rect.right()+5, rect.top()+rect.height()/2.0)); // +5 on x2 else last segment is missing from dashed/dotted pens - } - // draw scatter symbol: - if (!mScatterStyle.isNone()) - { - applyScattersAntialiasingHint(painter); - // scale scatter pixmap if it's too large to fit in legend icon rect: - if (mScatterStyle.shape() == QCPScatterStyle::ssPixmap && (mScatterStyle.pixmap().size().width() > rect.width() || mScatterStyle.pixmap().size().height() > rect.height())) - { - QCPScatterStyle scaledStyle(mScatterStyle); - scaledStyle.setPixmap(scaledStyle.pixmap().scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation)); - scaledStyle.applyTo(painter, mPen); - scaledStyle.drawShape(painter, QRectF(rect).center()); - } else - { - mScatterStyle.applyTo(painter, mPen); - mScatterStyle.drawShape(painter, QRectF(rect).center()); + // draw fill: + if (mBrush.style() != Qt::NoBrush) { + applyFillAntialiasingHint(painter); + painter->fillRect(QRectF(rect.left(), rect.top() + rect.height() / 2.0, rect.width(), rect.height() / 3.0), mBrush); + } + // draw line vertically centered: + if (mLineStyle != lsNone) { + applyDefaultAntialiasingHint(painter); + painter->setPen(mPen); + painter->drawLine(QLineF(rect.left(), rect.top() + rect.height() / 2.0, rect.right() + 5, rect.top() + rect.height() / 2.0)); // +5 on x2 else last segment is missing from dashed/dotted pens + } + // draw scatter symbol: + if (!mScatterStyle.isNone()) { + applyScattersAntialiasingHint(painter); + // scale scatter pixmap if it's too large to fit in legend icon rect: + if (mScatterStyle.shape() == QCPScatterStyle::ssPixmap && (mScatterStyle.pixmap().size().width() > rect.width() || mScatterStyle.pixmap().size().height() > rect.height())) { + QCPScatterStyle scaledStyle(mScatterStyle); + scaledStyle.setPixmap(scaledStyle.pixmap().scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation)); + scaledStyle.applyTo(painter, mPen); + scaledStyle.drawShape(painter, QRectF(rect).center()); + } else { + mScatterStyle.applyTo(painter, mPen); + mScatterStyle.drawShape(painter, QRectF(rect).center()); + } } - } } /*! \internal @@ -20473,31 +20486,45 @@ void QCPGraph::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const */ void QCPGraph::getLines(QVector *lines, const QCPDataRange &dataRange) const { - if (!lines) return; - QCPGraphDataContainer::const_iterator begin, end; - getVisibleDataBounds(begin, end, dataRange); - if (begin == end) - { - lines->clear(); - return; - } - - QVector lineData; - if (mLineStyle != lsNone) - getOptimizedLineData(&lineData, begin, end); - - if (mKeyAxis->rangeReversed() != (mKeyAxis->orientation() == Qt::Vertical)) // make sure key pixels are sorted ascending in lineData (significantly simplifies following processing) - std::reverse(lineData.begin(), lineData.end()); + if (!lines) { + return; + } + QCPGraphDataContainer::const_iterator begin, end; + getVisibleDataBounds(begin, end, dataRange); + if (begin == end) { + lines->clear(); + return; + } - 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; - } + QVector lineData; + if (mLineStyle != lsNone) { + getOptimizedLineData(&lineData, begin, end); + } + + if (mKeyAxis->rangeReversed() != (mKeyAxis->orientation() == Qt::Vertical)) { // make sure key pixels are sorted ascending in lineData (significantly simplifies following processing) + std::reverse(lineData.begin(), lineData.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 @@ -20514,54 +20541,54 @@ void QCPGraph::getLines(QVector *lines, const QCPDataRange &dataRange) */ 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"; scatters->clear(); return; } - - QCPGraphDataContainer::const_iterator begin, end; - getVisibleDataBounds(begin, end, dataRange); - if (begin == end) - { - scatters->clear(); - return; - } - - QVector data; - getOptimizedScatterData(&data, begin, end); - - if (mKeyAxis->rangeReversed() != (mKeyAxis->orientation() == Qt::Vertical)) // make sure key pixels are sorted ascending in data (significantly simplifies following processing) - std::reverse(data.begin(), data.end()); - - scatters->resize(data.size()); - if (keyAxis->orientation() == Qt::Vertical) - { - for (int i=0; icoordToPixel(data.at(i).value)); - (*scatters)[i].setY(keyAxis->coordToPixel(data.at(i).key)); - } + if (!scatters) { + return; } - } else - { - for (int i=0; icoordToPixel(data.at(i).key)); - (*scatters)[i].setY(valueAxis->coordToPixel(data.at(i).value)); - } + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + scatters->clear(); + return; + } + + QCPGraphDataContainer::const_iterator begin, end; + getVisibleDataBounds(begin, end, dataRange); + if (begin == end) { + scatters->clear(); + return; + } + + QVector data; + getOptimizedScatterData(&data, begin, end); + + if (mKeyAxis->rangeReversed() != (mKeyAxis->orientation() == Qt::Vertical)) { // make sure key pixels are sorted ascending in data (significantly simplifies following processing) + std::reverse(data.begin(), data.end()); + } + + scatters->resize(data.size()); + if (keyAxis->orientation() == Qt::Vertical) { + for (int i = 0; i < data.size(); ++i) { + if (!qIsNaN(data.at(i).value)) { + (*scatters)[i].setX(valueAxis->coordToPixel(data.at(i).value)); + (*scatters)[i].setY(keyAxis->coordToPixel(data.at(i).key)); + } + } + } else { + for (int i = 0; i < data.size(); ++i) { + if (!qIsNaN(data.at(i).value)) { + (*scatters)[i].setX(keyAxis->coordToPixel(data.at(i).key)); + (*scatters)[i].setY(valueAxis->coordToPixel(data.at(i).value)); + } + } } - } } /*! \internal 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. - + The source of \a data is usually \ref getOptimizedLineData, and this method is called in \a getLines if the line style is set accordingly. @@ -20569,37 +20596,36 @@ void QCPGraph::getScatters(QVector *scatters, const QCPDataRange &dataR */ 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; } + 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()); - - // 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)); + result.resize(data.size()); + + // transform data points to pixels: + if (keyAxis->orientation() == Qt::Vertical) { + for (int i = 0; i < data.size(); ++i) { + result[i].setX(valueAxis->coordToPixel(data.at(i).value)); + result[i].setY(keyAxis->coordToPixel(data.at(i).key)); + } + } else { // key axis is horizontal + for (int i = 0; i < data.size(); ++i) { + result[i].setX(keyAxis->coordToPixel(data.at(i).key)); + result[i].setY(valueAxis->coordToPixel(data.at(i).value)); + } } - } 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; + 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. @@ -20607,47 +20633,46 @@ QVector QCPGraph::dataToLines(const QVector &data) const */ 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.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); + QVector result; + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + return result; } - } 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); + + 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; i < data.size(); ++i) { + const double key = keyAxis->coordToPixel(data.at(i).key); + result[i * 2 + 0].setX(lastValue); + result[i * 2 + 0].setY(key); + lastValue = valueAxis->coordToPixel(data.at(i).value); + result[i * 2 + 1].setX(lastValue); + result[i * 2 + 1].setY(key); + } + } else { // key axis is horizontal + double lastValue = valueAxis->coordToPixel(data.first().value); + for (int i = 0; i < data.size(); ++i) { + const double key = keyAxis->coordToPixel(data.at(i).key); + result[i * 2 + 0].setX(key); + result[i * 2 + 0].setY(lastValue); + lastValue = valueAxis->coordToPixel(data.at(i).value); + result[i * 2 + 1].setX(key); + result[i * 2 + 1].setY(lastValue); + } } - } - return result; + 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. @@ -20655,47 +20680,46 @@ QVector QCPGraph::dataToStepLeftLines(const QVector &data */ 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.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); + QVector result; + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + return result; } - } 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); + + 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; i < data.size(); ++i) { + const double value = valueAxis->coordToPixel(data.at(i).value); + result[i * 2 + 0].setX(value); + result[i * 2 + 0].setY(lastKey); + lastKey = keyAxis->coordToPixel(data.at(i).key); + result[i * 2 + 1].setX(value); + result[i * 2 + 1].setY(lastKey); + } + } else { // key axis is horizontal + double lastKey = keyAxis->coordToPixel(data.first().key); + for (int i = 0; i < data.size(); ++i) { + const double value = valueAxis->coordToPixel(data.at(i).value); + result[i * 2 + 0].setX(lastKey); + result[i * 2 + 0].setY(value); + lastKey = keyAxis->coordToPixel(data.at(i).key); + result[i * 2 + 1].setX(lastKey); + result[i * 2 + 1].setY(value); + } } - } - return result; + 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. @@ -20703,59 +20727,58 @@ QVector QCPGraph::dataToStepRightLines(const QVector &dat */ 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.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); + 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[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.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; i < data.size(); ++i) { + const double key = (keyAxis->coordToPixel(data.at(i).key) + lastKey) * 0.5; + result[i * 2 - 1].setX(lastValue); + result[i * 2 - 1].setY(key); + lastValue = valueAxis->coordToPixel(data.at(i).value); + lastKey = keyAxis->coordToPixel(data.at(i).key); + result[i * 2 + 0].setX(lastValue); + result[i * 2 + 0].setY(key); + } + result[data.size() * 2 - 1].setX(lastValue); + result[data.size() * 2 - 1].setY(lastKey); + } else { // key axis is horizontal + double lastKey = keyAxis->coordToPixel(data.first().key); + double lastValue = valueAxis->coordToPixel(data.first().value); + result[0].setX(lastKey); + result[0].setY(lastValue); + for (int i = 1; i < data.size(); ++i) { + const double key = (keyAxis->coordToPixel(data.at(i).key) + lastKey) * 0.5; + result[i * 2 - 1].setX(key); + result[i * 2 - 1].setY(lastValue); + lastValue = valueAxis->coordToPixel(data.at(i).value); + lastKey = keyAxis->coordToPixel(data.at(i).key); + result[i * 2 + 0].setX(key); + result[i * 2 + 0].setY(lastValue); + } + result[data.size() * 2 - 1].setX(lastKey); + result[data.size() * 2 - 1].setY(lastValue); } - result[data.size()*2-1].setX(lastKey); - result[data.size()*2-1].setY(lastValue); - } - return result; + 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. @@ -20763,80 +20786,91 @@ QVector QCPGraph::dataToStepCenterLines(const QVector &da */ 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); - - // 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); + QVector result; + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + return result; } - } 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)); + + result.resize(data.size() * 2); + + // transform data points to pixels: + if (keyAxis->orientation() == Qt::Vertical) { + for (int i = 0; i < data.size(); ++i) { + const double key = keyAxis->coordToPixel(data.at(i).key); + result[i * 2 + 0].setX(valueAxis->coordToPixel(0)); + result[i * 2 + 0].setY(key); + result[i * 2 + 1].setX(valueAxis->coordToPixel(data.at(i).value)); + result[i * 2 + 1].setY(key); + } + } else { // key axis is horizontal + for (int i = 0; i < data.size(); ++i) { + const double key = keyAxis->coordToPixel(data.at(i).key); + result[i * 2 + 0].setX(key); + result[i * 2 + 0].setY(valueAxis->coordToPixel(0)); + result[i * 2 + 1].setX(key); + result[i * 2 + 1].setY(valueAxis->coordToPixel(data.at(i).value)); + } } - } - return result; + return result; +} + +void QCPGraph::setSmooth(int smooth) +{ + this->smooth = smooth; } /*! \internal - + Draws the fill of the graph using the specified \a painter, with the currently set brush. - + Depending on whether a normal fill or a channel fill (\ref setChannelFillGraph) is needed, \ref getFillPolygon or \ref getChannelFillPolygon are used to find the according fill polygons. - + In order to handle NaN Data points correctly (the fill needs to be split into disjoint areas), this method first determines a list of non-NaN segments with \ref getNonNanSegments, on which to operate. In the channel fill case, \ref getOverlappingSegments is used to consolidate the non-NaN segments of the two involved graphs, before passing the overlapping pairs to \ref getChannelFillPolygon. - + Pass the points of this graph's line as \a lines, in pixel coordinates. \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 (painter->brush().style() == Qt::NoBrush || painter->brush().color().alpha() == 0) return; - - applyFillAntialiasingHint(painter); - QVector segments = getNonNanSegments(lines, keyAxis()->orientation()); - if (!mChannelFillGraph) - { - // draw base fill under graph, fill goes all the way to the zero-value-line: - for (int i=0; idrawPolygon(getFillPolygon(lines, segments.at(i))); - } else - { - // draw fill between this graph and mChannelFillGraph: - QVector otherLines; - mChannelFillGraph->getLines(&otherLines, QCPDataRange(0, mChannelFillGraph->dataCount())); - if (!otherLines.isEmpty()) - { - QVector otherSegments = getNonNanSegments(&otherLines, mChannelFillGraph->keyAxis()->orientation()); - QVector > segmentPairs = getOverlappingSegments(segments, lines, otherSegments, &otherLines); - for (int i=0; idrawPolygon(getChannelFillPolygon(lines, segmentPairs.at(i).first, &otherLines, segmentPairs.at(i).second)); + if (mLineStyle == lsImpulse) { + return; // fill doesn't make sense for impulse plot + } + if (painter->brush().style() == Qt::NoBrush || painter->brush().color().alpha() == 0) { + return; + } + + applyFillAntialiasingHint(painter); + QVector segments = getNonNanSegments(lines, keyAxis()->orientation()); + if (!mChannelFillGraph) { + // draw base fill under graph, fill goes all the way to the zero-value-line: + for (int i = 0; i < segments.size(); ++i) { + if (smooth > 0) { + painter->drawPath(getFillPath(lines, segments.at(i))); + } else { + painter->drawPolygon(getFillPolygon(lines, segments.at(i))); + } + } + } else { + // draw fill between this graph and mChannelFillGraph: + QVector otherLines; + mChannelFillGraph->getLines(&otherLines, QCPDataRange(0, mChannelFillGraph->dataCount())); + if (!otherLines.isEmpty()) { + QVector otherSegments = getNonNanSegments(&otherLines, mChannelFillGraph->keyAxis()->orientation()); + QVector > segmentPairs = getOverlappingSegments(segments, lines, otherSegments, &otherLines); + for (int i = 0; i < segmentPairs.size(); ++i) { + painter->drawPolygon(getChannelFillPolygon(lines, segmentPairs.at(i).first, &otherLines, segmentPairs.at(i).second)); + } + } } - } } /*! \internal @@ -20848,25 +20882,35 @@ void QCPGraph::drawFill(QCPPainter *painter, QVector *lines) const */ void QCPGraph::drawScatterPlot(QCPPainter *painter, const QVector &scatters, const QCPScatterStyle &style) const { - applyScattersAntialiasingHint(painter); - style.applyTo(painter, mPen); - for (int i=0; i &lines) const { - if (painter->pen().style() != Qt::NoPen && painter->pen().color().alpha() != 0) - { - applyDefaultAntialiasingHint(painter); - drawPolyline(painter, lines); - } + if (painter->pen().style() != Qt::NoPen && painter->pen().color().alpha() != 0) { + applyDefaultAntialiasingHint(painter); + //开启了平滑曲线则应用对应算法绘制平滑路径 + if (mLineStyle == lsLine) { + if (smooth == 1) { + painter->drawPath(SmoothCurve::createSmoothCurve(lines)); + return; + } else if (smooth == 2) { + painter->drawPath(SmoothCurve::createSmoothCurve2(lines)); + return; + } + } + drawPolyline(painter, lines); + } } /*! \internal @@ -20879,16 +20923,15 @@ void QCPGraph::drawLinePlot(QCPPainter *painter, const QVector &lines) */ void QCPGraph::drawImpulsePlot(QCPPainter *painter, const QVector &lines) const { - if (painter->pen().style() != Qt::NoPen && painter->pen().color().alpha() != 0) - { - applyDefaultAntialiasingHint(painter); - 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); - } + if (painter->pen().style() != Qt::NoPen && painter->pen().color().alpha() != 0) { + applyDefaultAntialiasingHint(painter); + 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 @@ -20905,82 +20948,89 @@ void QCPGraph::drawImpulsePlot(QCPPainter *painter, const QVector &line */ 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; } - if (begin == end) return; - - int dataCount = end-begin; - int maxCount = (std::numeric_limits::max)(); - if (mAdaptiveSampling) - { - double keyPixelSpan = qAbs(keyAxis->coordToPixel(begin->key)-keyAxis->coordToPixel((end-1)->key)); - if (2*keyPixelSpan+2 < static_cast((std::numeric_limits::max)())) - maxCount = 2*keyPixelSpan+2; - } - - if (mAdaptiveSampling && dataCount >= maxCount) // use adaptive sampling only if there are at least two points per pixel on average - { - QCPGraphDataContainer::const_iterator it = begin; - double minValue = it->value; - double maxValue = it->value; - QCPGraphDataContainer::const_iterator currentIntervalFirstPoint = it; - int reversedFactor = keyAxis->pixelOrientation(); // is used to calculate keyEpsilon pixel into the correct direction - int reversedRound = reversedFactor==-1 ? 1 : 0; // is used to switch between floor (normal) and ceil (reversed) rounding of currentIntervalStartKey - double currentIntervalStartKey = keyAxis->pixelToCoord((int)(keyAxis->coordToPixel(begin->key)+reversedRound)); - double lastIntervalEndKey = currentIntervalStartKey; - double keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor)); // interval of one pixel on screen when mapped to plot key coordinates - bool keyEpsilonVariable = keyAxis->scaleType() == QCPAxis::stLogarithmic; // indicates whether keyEpsilon needs to be updated after every interval (for log axes) - int intervalDataCount = 1; - ++it; // advance iterator to second data point because adaptive sampling works in 1 point retrospect - while (it != end) - { - if (it->key < currentIntervalStartKey+keyEpsilon) // data point is still within same pixel, so skip it and expand value span of this cluster if necessary - { - if (it->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 (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; - } - ++it; + if (!lineData) { + return; + } + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + return; + } + if (begin == end) { + return; + } + + int dataCount = end - begin; + int maxCount = (std::numeric_limits::max)(); + if (mAdaptiveSampling) { + double keyPixelSpan = qAbs(keyAxis->coordToPixel(begin->key) - keyAxis->coordToPixel((end - 1)->key)); + if (2 * keyPixelSpan + 2 < static_cast((std::numeric_limits::max)())) { + maxCount = 2 * keyPixelSpan + 2; + } + } + + if (mAdaptiveSampling && dataCount >= maxCount) { // use adaptive sampling only if there are at least two points per pixel on average + QCPGraphDataContainer::const_iterator it = begin; + double minValue = it->value; + double maxValue = it->value; + QCPGraphDataContainer::const_iterator currentIntervalFirstPoint = it; + int reversedFactor = keyAxis->pixelOrientation(); // is used to calculate keyEpsilon pixel into the correct direction + int reversedRound = reversedFactor == -1 ? 1 : 0; // is used to switch between floor (normal) and ceil (reversed) rounding of currentIntervalStartKey + double currentIntervalStartKey = keyAxis->pixelToCoord((int)(keyAxis->coordToPixel(begin->key) + reversedRound)); + double lastIntervalEndKey = currentIntervalStartKey; + double keyEpsilon = qAbs(currentIntervalStartKey - keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey) + 1.0 * reversedFactor)); // interval of one pixel on screen when mapped to plot key coordinates + bool keyEpsilonVariable = keyAxis->scaleType() == QCPAxis::stLogarithmic; // indicates whether keyEpsilon needs to be updated after every interval (for log axes) + int intervalDataCount = 1; + ++it; // advance iterator to second data point because adaptive sampling works in 1 point retrospect + while (it != end) { + if (it->key < currentIntervalStartKey + keyEpsilon) { // data point is still within same pixel, so skip it and expand value span of this cluster if necessary + if (it->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 (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; + } + ++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)); + } + + } else { // don't use adaptive sampling algorithm, transfer points one-to-one from the data container into the output + lineData->resize(dataCount); + std::copy(begin, end, lineData->begin()); } - // 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)); - - } else // don't use adaptive sampling algorithm, transfer points one-to-one from the data container into the output - { - lineData->resize(dataCount); - std::copy(begin, end, lineData->begin()); - } } /*! \internal @@ -20997,174 +21047,165 @@ void QCPGraph::getOptimizedLineData(QVector *lineData, const QCPGr */ void QCPGraph::getOptimizedScatterData(QVector *scatterData, QCPGraphDataContainer::const_iterator begin, QCPGraphDataContainer::const_iterator end) const { - if (!scatterData) return; - QCPAxis *keyAxis = mKeyAxis.data(); - QCPAxis *valueAxis = mValueAxis.data(); - if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } - - const int scatterModulo = mScatterSkip+1; - const bool doScatterSkip = mScatterSkip > 0; - int beginIndex = begin-mDataContainer->constBegin(); - int endIndex = end-mDataContainer->constBegin(); - while (doScatterSkip && begin != end && beginIndex % scatterModulo != 0) // advance begin iterator to first non-skipped scatter - { - ++beginIndex; - ++begin; - } - if (begin == end) return; - int dataCount = end-begin; - int maxCount = (std::numeric_limits::max)(); - if (mAdaptiveSampling) - { - int keyPixelSpan = qAbs(keyAxis->coordToPixel(begin->key)-keyAxis->coordToPixel((end-1)->key)); - maxCount = 2*keyPixelSpan+2; - } - - if (mAdaptiveSampling && dataCount >= maxCount) // use adaptive sampling only if there are at least two points per pixel on average - { - 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 - { - itIndex += scatterModulo; - if (itIndex < endIndex) // make sure we didn't jump over end - it += scatterModulo; - else - { - it = end; - itIndex = endIndex; - } + if (!scatterData) { + return; } - // main loop over data points: - while (it != end) - { - if (it->key < currentIntervalStartKey+keyEpsilon) // data point is still within same pixel, so skip it and expand value span of this pixel if necessary - { - if (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; - } - } + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + return; } - // 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; - } - } + + const int scatterModulo = mScatterSkip + 1; + const bool doScatterSkip = mScatterSkip > 0; + int beginIndex = begin - mDataContainer->constBegin(); + int endIndex = end - mDataContainer->constBegin(); + while (doScatterSkip && begin != end && beginIndex % scatterModulo != 0) { // advance begin iterator to first non-skipped scatter + ++beginIndex; + ++begin; + } + if (begin == end) { + return; + } + int dataCount = end - begin; + int maxCount = (std::numeric_limits::max)(); + if (mAdaptiveSampling) { + int keyPixelSpan = qAbs(keyAxis->coordToPixel(begin->key) - keyAxis->coordToPixel((end - 1)->key)); + maxCount = 2 * keyPixelSpan + 2; + } + + if (mAdaptiveSampling && dataCount >= maxCount) { // use adaptive sampling only if there are at least two points per pixel on average + 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 { + itIndex += scatterModulo; + if (itIndex < endIndex) { // make sure we didn't jump over end + it += scatterModulo; + } else { + it = end; + itIndex = endIndex; + } + } + // main loop over data points: + while (it != end) { + if (it->key < currentIntervalStartKey + keyEpsilon) { // data point is still within same pixel, so skip it and expand value span of this pixel if necessary + if (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; + } + } + } } - } } /*! @@ -21178,179 +21219,178 @@ void QCPGraph::getOptimizedScatterData(QVector *scatterData, QCPGr */ void QCPGraph::getVisibleDataBounds(QCPGraphDataContainer::const_iterator &begin, QCPGraphDataContainer::const_iterator &end, const QCPDataRange &rangeRestriction) const { - if (rangeRestriction.isEmpty()) - { - 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 - } + if (rangeRestriction.isEmpty()) { + 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 + } } /*! \internal - + This method goes through the passed points in \a lineData and returns a list of the segments which don't contain NaN data points. - + \a keyOrientation defines whether the \a x or \a y member of the passed QPointF is used to check for NaN. If \a keyOrientation is \c Qt::Horizontal, the \a y member is checked, if it is \c Qt::Vertical, the \a x member is checked. - + \see getOverlappingSegments, drawFill */ QVector QCPGraph::getNonNanSegments(const QVector *lineData, Qt::Orientation keyOrientation) const { - QVector result; - const int n = lineData->size(); - - QCPDataRange currentSegment(-1, -1); - int i = 0; - - if (keyOrientation == Qt::Horizontal) - { - while (i < n) - { - while (i < n && qIsNaN(lineData->at(i).y())) // seek next non-NaN data point - ++i; - if (i == n) - break; - currentSegment.setBegin(i++); - while (i < n && !qIsNaN(lineData->at(i).y())) // seek next NaN data point or end of data - ++i; - currentSegment.setEnd(i++); - result.append(currentSegment); + QVector result; + const int n = lineData->size(); + + QCPDataRange currentSegment(-1, -1); + int i = 0; + + if (keyOrientation == Qt::Horizontal) { + while (i < n) { + while (i < n && qIsNaN(lineData->at(i).y())) { // seek next non-NaN data point + ++i; + } + if (i == n) { + break; + } + currentSegment.setBegin(i++); + while (i < n && !qIsNaN(lineData->at(i).y())) { // seek next NaN data point or end of data + ++i; + } + currentSegment.setEnd(i++); + result.append(currentSegment); + } + } else { // keyOrientation == Qt::Vertical + while (i < n) { + while (i < n && qIsNaN(lineData->at(i).x())) { // seek next non-NaN data point + ++i; + } + if (i == n) { + break; + } + currentSegment.setBegin(i++); + while (i < n && !qIsNaN(lineData->at(i).x())) { // seek next NaN data point or end of data + ++i; + } + currentSegment.setEnd(i++); + result.append(currentSegment); + } } - } else // keyOrientation == Qt::Vertical - { - while (i < n) - { - while (i < n && qIsNaN(lineData->at(i).x())) // seek next non-NaN data point - ++i; - if (i == n) - break; - currentSegment.setBegin(i++); - while (i < n && !qIsNaN(lineData->at(i).x())) // seek next NaN data point or end of data - ++i; - currentSegment.setEnd(i++); - result.append(currentSegment); - } - } - return result; + return result; } /*! \internal - + This method takes two segment lists (e.g. created by \ref getNonNanSegments) \a thisSegments and \a otherSegments, and their associated point data \a thisData and \a otherData. It returns all pairs of segments (the first from \a thisSegments, the second from \a otherSegments), which overlap in plot coordinates. - + This method is useful in the case of a channel fill between two graphs, when only those non-NaN segments which actually overlap in their key coordinate shall be considered for drawing a channel fill polygon. - + It is assumed that the passed segments in \a thisSegments are ordered ascending by index, and that the segments don't overlap themselves. The same is assumed for the segments in \a otherSegments. This is fulfilled when the segments are obtained via \ref getNonNanSegments. - + \see getNonNanSegments, segmentsIntersect, drawFill, getChannelFillPolygon */ QVector > QCPGraph::getOverlappingSegments(QVector thisSegments, const QVector *thisData, QVector otherSegments, const QVector *otherData) const { - QVector > result; - if (thisData->isEmpty() || otherData->isEmpty() || thisSegments.isEmpty() || otherSegments.isEmpty()) + QVector > result; + if (thisData->isEmpty() || otherData->isEmpty() || thisSegments.isEmpty() || otherSegments.isEmpty()) { + return result; + } + + int thisIndex = 0; + int otherIndex = 0; + const bool verticalKey = mKeyAxis->orientation() == Qt::Vertical; + while (thisIndex < thisSegments.size() && otherIndex < otherSegments.size()) { + if (thisSegments.at(thisIndex).size() < 2) { // segments with fewer than two points won't have a fill anyhow + ++thisIndex; + continue; + } + if (otherSegments.at(otherIndex).size() < 2) { // segments with fewer than two points won't have a fill anyhow + ++otherIndex; + continue; + } + double thisLower, thisUpper, otherLower, otherUpper; + if (!verticalKey) { + thisLower = thisData->at(thisSegments.at(thisIndex).begin()).x(); + thisUpper = thisData->at(thisSegments.at(thisIndex).end() - 1).x(); + otherLower = otherData->at(otherSegments.at(otherIndex).begin()).x(); + otherUpper = otherData->at(otherSegments.at(otherIndex).end() - 1).x(); + } else { + thisLower = thisData->at(thisSegments.at(thisIndex).begin()).y(); + thisUpper = thisData->at(thisSegments.at(thisIndex).end() - 1).y(); + otherLower = otherData->at(otherSegments.at(otherIndex).begin()).y(); + otherUpper = otherData->at(otherSegments.at(otherIndex).end() - 1).y(); + } + + int bPrecedence; + if (segmentsIntersect(thisLower, thisUpper, otherLower, otherUpper, bPrecedence)) { + result.append(QPair(thisSegments.at(thisIndex), otherSegments.at(otherIndex))); + } + + if (bPrecedence <= 0) { // otherSegment doesn't reach as far as thisSegment, so continue with next otherSegment, keeping current thisSegment + ++otherIndex; + } else { // otherSegment reaches further than thisSegment, so continue with next thisSegment, keeping current otherSegment + ++thisIndex; + } + } + return result; - - int thisIndex = 0; - int otherIndex = 0; - const bool verticalKey = mKeyAxis->orientation() == Qt::Vertical; - while (thisIndex < thisSegments.size() && otherIndex < otherSegments.size()) - { - if (thisSegments.at(thisIndex).size() < 2) // segments with fewer than two points won't have a fill anyhow - { - ++thisIndex; - continue; - } - if (otherSegments.at(otherIndex).size() < 2) // segments with fewer than two points won't have a fill anyhow - { - ++otherIndex; - continue; - } - double thisLower, thisUpper, otherLower, otherUpper; - if (!verticalKey) - { - thisLower = thisData->at(thisSegments.at(thisIndex).begin()).x(); - thisUpper = thisData->at(thisSegments.at(thisIndex).end()-1).x(); - otherLower = otherData->at(otherSegments.at(otherIndex).begin()).x(); - otherUpper = otherData->at(otherSegments.at(otherIndex).end()-1).x(); - } else - { - thisLower = thisData->at(thisSegments.at(thisIndex).begin()).y(); - thisUpper = thisData->at(thisSegments.at(thisIndex).end()-1).y(); - otherLower = otherData->at(otherSegments.at(otherIndex).begin()).y(); - otherUpper = otherData->at(otherSegments.at(otherIndex).end()-1).y(); - } - - int bPrecedence; - if (segmentsIntersect(thisLower, thisUpper, otherLower, otherUpper, bPrecedence)) - result.append(QPair(thisSegments.at(thisIndex), otherSegments.at(otherIndex))); - - if (bPrecedence <= 0) // otherSegment doesn't reach as far as thisSegment, so continue with next otherSegment, keeping current thisSegment - ++otherIndex; - else // otherSegment reaches further than thisSegment, so continue with next thisSegment, keeping current otherSegment - ++thisIndex; - } - - return result; } /*! \internal - + Returns whether the segments defined by the coordinates (aLower, aUpper) and (bLower, bUpper) have overlap. - + The output parameter \a bPrecedence indicates whether the \a b segment reaches farther than the \a a segment or not. If \a bPrecedence returns 1, segment \a b reaches the farthest to higher coordinates (i.e. bUpper > aUpper). If it returns -1, segment \a a reaches the farthest. Only if both segment's upper bounds are identical, 0 is returned as \a bPrecedence. - + It is assumed that the lower bounds always have smaller or equal values than the upper bounds. - + \see getOverlappingSegments */ bool QCPGraph::segmentsIntersect(double aLower, double aUpper, double bLower, double bUpper, int &bPrecedence) const { - bPrecedence = 0; - if (aLower > bUpper) - { - bPrecedence = -1; - return false; - } else if (bLower > aUpper) - { - bPrecedence = 1; - return false; - } else - { - if (aUpper > bUpper) - bPrecedence = -1; - else if (aUpper < bUpper) - bPrecedence = 1; - - return true; - } + bPrecedence = 0; + if (aLower > bUpper) { + bPrecedence = -1; + return false; + } else if (bLower > aUpper) { + bPrecedence = 1; + return false; + } else { + if (aUpper > bUpper) { + bPrecedence = -1; + } else if (aUpper < bUpper) { + bPrecedence = 1; + } + + return true; + } } /*! \internal - + Returns the point which closes the fill polygon on the zero-value-line parallel to the key axis. The logarithmic axis scale case is a bit special, since the zero-value-line in pixel coordinates is in positive or negative infinity. So this case is handled separately by just closing the fill @@ -21362,195 +21402,250 @@ bool QCPGraph::segmentsIntersect(double aLower, double aUpper, double bLower, do */ QPointF QCPGraph::getFillBasePoint(QPointF matchingDataPoint) const { - QCPAxis *keyAxis = mKeyAxis.data(); - QCPAxis *valueAxis = mValueAxis.data(); - if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPointF(); } - - QPointF result; - if (valueAxis->scaleType() == QCPAxis::stLinear) - { - if (keyAxis->orientation() == Qt::Horizontal) - { - result.setX(matchingDataPoint.x()); - result.setY(valueAxis->coordToPixel(0)); - } else // keyAxis->orientation() == Qt::Vertical - { - result.setX(valueAxis->coordToPixel(0)); - result.setY(matchingDataPoint.y()); + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + return QPointF(); } - } else // valueAxis->mScaleType == QCPAxis::stLogarithmic - { - // In logarithmic scaling we can't just draw to value 0 so we just fill all the way - // to the axis which is in the direction towards 0 - if (keyAxis->orientation() == Qt::Vertical) - { - if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) || - (valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis - result.setX(keyAxis->axisRect()->right()); - else - result.setX(keyAxis->axisRect()->left()); - result.setY(matchingDataPoint.y()); - } else if (keyAxis->axisType() == QCPAxis::atTop || keyAxis->axisType() == QCPAxis::atBottom) - { - result.setX(matchingDataPoint.x()); - if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) || - (valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis - result.setY(keyAxis->axisRect()->top()); - else - result.setY(keyAxis->axisRect()->bottom()); + + QPointF result; + if (valueAxis->scaleType() == QCPAxis::stLinear) { + if (keyAxis->orientation() == Qt::Horizontal) { + result.setX(matchingDataPoint.x()); + result.setY(valueAxis->coordToPixel(0)); + } else { // keyAxis->orientation() == Qt::Vertical + result.setX(valueAxis->coordToPixel(0)); + result.setY(matchingDataPoint.y()); + } + } else { // valueAxis->mScaleType == QCPAxis::stLogarithmic + // In logarithmic scaling we can't just draw to value 0 so we just fill all the way + // to the axis which is in the direction towards 0 + if (keyAxis->orientation() == Qt::Vertical) { + if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) || + (valueAxis->range().upper > 0 && valueAxis->rangeReversed())) { // if range is negative, zero is on opposite side of key axis + result.setX(keyAxis->axisRect()->right()); + } else { + result.setX(keyAxis->axisRect()->left()); + } + result.setY(matchingDataPoint.y()); + } else if (keyAxis->axisType() == QCPAxis::atTop || keyAxis->axisType() == QCPAxis::atBottom) { + result.setX(matchingDataPoint.x()); + if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) || + (valueAxis->range().upper > 0 && valueAxis->rangeReversed())) { // if range is negative, zero is on opposite side of key axis + result.setY(keyAxis->axisRect()->top()); + } else { + result.setY(keyAxis->axisRect()->bottom()); + } + } } - } - return result; + return result; } /*! \internal - + Returns the polygon needed for drawing normal fills between this graph and the key axis. - + Pass the graph's data points (in pixel coordinates) as \a lineData, and specify the \a segment which shall be used for the fill. The collection of \a lineData points described by \a segment must not contain NaN data points (see \ref getNonNanSegments). - + The returned fill polygon will be closed at the key axis (the zero-value line) for linear value axes. For logarithmic value axes the polygon will reach just beyond the corresponding axis rect side (see \ref getFillBasePoint). For increased performance (due to implicit sharing), keep the returned QPolygonF const. - + \see drawFill, getNonNanSegments */ const QPolygonF QCPGraph::getFillPolygon(const QVector *lineData, QCPDataRange segment) const { - if (segment.size() < 2) - return QPolygonF(); - QPolygonF result(segment.size()+2); - - result[0] = getFillBasePoint(lineData->at(segment.begin())); - std::copy(lineData->constBegin()+segment.begin(), lineData->constBegin()+segment.end(), result.begin()+1); - result[result.size()-1] = getFillBasePoint(lineData->at(segment.end()-1)); - - return result; + if (segment.size() < 2) { + return QPolygonF(); + } + QPolygonF result(segment.size() + 2); + + result[0] = getFillBasePoint(lineData->at(segment.begin())); + std::copy(lineData->constBegin() + segment.begin(), lineData->constBegin() + segment.end(), result.begin() + 1); + result[result.size() - 1] = getFillBasePoint(lineData->at(segment.end() - 1)); + + return result; +} + +const QPainterPath QCPGraph::getFillPath(const QVector *lineData, QCPDataRange segment) const +{ + if (segment.size() < 2) { + return QPainterPath(); + } + + QPointF start = getFillBasePoint(lineData->at(segment.begin())); + QPointF end = getFillBasePoint(lineData->at(segment.end() - 1)); + + QPainterPath path; + if (smooth == 1) { + path = SmoothCurve::createSmoothCurve(*lineData); + } else if (smooth == 2) { + path = SmoothCurve::createSmoothCurve2(*lineData); + } + + path.lineTo(end); + path.lineTo(start); + path.lineTo(lineData->at(segment.begin())); + return path; } /*! \internal - + Returns the polygon needed for drawing (partial) channel fills between this graph and the graph specified by \ref setChannelFillGraph. - + The data points of this graph are passed as pixel coordinates via \a thisData, the data of the other graph as \a otherData. The returned polygon will be calculated for the specified data segments \a thisSegment and \a otherSegment, pertaining to the respective \a thisData and \a otherData, respectively. - + The passed \a thisSegment and \a otherSegment should correspond to the segment pairs returned by \ref getOverlappingSegments, to make sure only segments that actually have key coordinate overlap need to be processed here. - + For increased performance due to implicit sharing, keep the returned QPolygonF const. - + \see drawFill, getOverlappingSegments, getNonNanSegments */ const QPolygonF QCPGraph::getChannelFillPolygon(const QVector *thisData, QCPDataRange thisSegment, const QVector *otherData, QCPDataRange otherSegment) const { - if (!mChannelFillGraph) - return QPolygonF(); - - QCPAxis *keyAxis = mKeyAxis.data(); - QCPAxis *valueAxis = mValueAxis.data(); - if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPolygonF(); } - if (!mChannelFillGraph.data()->mKeyAxis) { qDebug() << Q_FUNC_INFO << "channel fill target key axis invalid"; return QPolygonF(); } - - 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 (thisData->isEmpty()) return QPolygonF(); - QVector thisSegmentData(thisSegment.size()); - QVector otherSegmentData(otherSegment.size()); - std::copy(thisData->constBegin()+thisSegment.begin(), thisData->constBegin()+thisSegment.end(), thisSegmentData.begin()); - std::copy(otherData->constBegin()+otherSegment.begin(), otherData->constBegin()+otherSegment.end(), otherSegmentData.begin()); - // pointers to be able to swap them, depending which data range needs cropping: - QVector *staticData = &thisSegmentData; - QVector *croppedData = &otherSegmentData; - - // crop both vectors to ranges in which the keys overlap (which coord is key, depends on axisType): - if (keyAxis->orientation() == Qt::Horizontal) - { - // x is key - // crop lower bound: - if (staticData->first().x() < croppedData->first().x()) // other one must be cropped - qSwap(staticData, croppedData); - const int lowBound = findIndexBelowX(croppedData, staticData->first().x()); - if (lowBound == -1) return QPolygonF(); // key ranges have no overlap - croppedData->remove(0, lowBound); - // set lowest point of cropped data to fit exactly key position of first static data point via linear interpolation: - if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation - double slope; - if (!qFuzzyCompare(croppedData->at(1).x(), croppedData->at(0).x())) - slope = (croppedData->at(1).y()-croppedData->at(0).y())/(croppedData->at(1).x()-croppedData->at(0).x()); - else - slope = 0; - (*croppedData)[0].setY(croppedData->at(0).y()+slope*(staticData->first().x()-croppedData->at(0).x())); - (*croppedData)[0].setX(staticData->first().x()); - - // crop upper bound: - if (staticData->last().x() > croppedData->last().x()) // other one must be cropped - qSwap(staticData, croppedData); - int highBound = findIndexAboveX(croppedData, staticData->last().x()); - if (highBound == -1) return QPolygonF(); // key ranges have no overlap - croppedData->remove(highBound+1, croppedData->size()-(highBound+1)); - // set highest point of cropped data to fit exactly key position of last static data point via linear interpolation: - if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation - const int li = croppedData->size()-1; // last index - if (!qFuzzyCompare(croppedData->at(li).x(), croppedData->at(li-1).x())) - slope = (croppedData->at(li).y()-croppedData->at(li-1).y())/(croppedData->at(li).x()-croppedData->at(li-1).x()); - else - slope = 0; - (*croppedData)[li].setY(croppedData->at(li-1).y()+slope*(staticData->last().x()-croppedData->at(li-1).x())); - (*croppedData)[li].setX(staticData->last().x()); - } else // mKeyAxis->orientation() == Qt::Vertical - { - // y is key - // crop lower bound: - if (staticData->first().y() < croppedData->first().y()) // other one must be cropped - qSwap(staticData, croppedData); - int lowBound = findIndexBelowY(croppedData, staticData->first().y()); - if (lowBound == -1) return QPolygonF(); // key ranges have no overlap - croppedData->remove(0, lowBound); - // set lowest point of cropped data to fit exactly key position of first static data point via linear interpolation: - if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation - double slope; - if (!qFuzzyCompare(croppedData->at(1).y(), croppedData->at(0).y())) // avoid division by zero in step plots - slope = (croppedData->at(1).x()-croppedData->at(0).x())/(croppedData->at(1).y()-croppedData->at(0).y()); - else - slope = 0; - (*croppedData)[0].setX(croppedData->at(0).x()+slope*(staticData->first().y()-croppedData->at(0).y())); - (*croppedData)[0].setY(staticData->first().y()); - - // crop upper bound: - if (staticData->last().y() > croppedData->last().y()) // other one must be cropped - qSwap(staticData, croppedData); - int highBound = findIndexAboveY(croppedData, staticData->last().y()); - if (highBound == -1) return QPolygonF(); // key ranges have no overlap - croppedData->remove(highBound+1, croppedData->size()-(highBound+1)); - // set highest point of cropped data to fit exactly key position of last static data point via linear interpolation: - if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation - int li = croppedData->size()-1; // last index - if (!qFuzzyCompare(croppedData->at(li).y(), croppedData->at(li-1).y())) // avoid division by zero in step plots - slope = (croppedData->at(li).x()-croppedData->at(li-1).x())/(croppedData->at(li).y()-croppedData->at(li-1).y()); - else - slope = 0; - (*croppedData)[li].setX(croppedData->at(li-1).x()+slope*(staticData->last().y()-croppedData->at(li-1).y())); - (*croppedData)[li].setY(staticData->last().y()); - } - - // return joined: - for (int i=otherSegmentData.size()-1; i>=0; --i) // insert reversed, otherwise the polygon will be twisted - thisSegmentData << otherSegmentData.at(i); - return QPolygonF(thisSegmentData); + if (!mChannelFillGraph) { + return QPolygonF(); + } + + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + return QPolygonF(); + } + if (!mChannelFillGraph.data()->mKeyAxis) { + qDebug() << Q_FUNC_INFO << "channel fill target key axis invalid"; + return QPolygonF(); + } + + 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 (thisData->isEmpty()) { + return QPolygonF(); + } + QVector thisSegmentData(thisSegment.size()); + QVector otherSegmentData(otherSegment.size()); + std::copy(thisData->constBegin() + thisSegment.begin(), thisData->constBegin() + thisSegment.end(), thisSegmentData.begin()); + std::copy(otherData->constBegin() + otherSegment.begin(), otherData->constBegin() + otherSegment.end(), otherSegmentData.begin()); + // pointers to be able to swap them, depending which data range needs cropping: + QVector *staticData = &thisSegmentData; + QVector *croppedData = &otherSegmentData; + + // crop both vectors to ranges in which the keys overlap (which coord is key, depends on axisType): + if (keyAxis->orientation() == Qt::Horizontal) { + // x is key + // crop lower bound: + if (staticData->first().x() < croppedData->first().x()) { // other one must be cropped + qSwap(staticData, croppedData); + } + const int lowBound = findIndexBelowX(croppedData, staticData->first().x()); + if (lowBound == -1) { + return QPolygonF(); // key ranges have no overlap + } + croppedData->remove(0, lowBound); + // set lowest point of cropped data to fit exactly key position of first static data point via linear interpolation: + if (croppedData->size() < 2) { + return QPolygonF(); // need at least two points for interpolation + } + double slope; + if (!qFuzzyCompare(croppedData->at(1).x(), croppedData->at(0).x())) { + slope = (croppedData->at(1).y() - croppedData->at(0).y()) / (croppedData->at(1).x() - croppedData->at(0).x()); + } else { + slope = 0; + } + (*croppedData)[0].setY(croppedData->at(0).y() + slope * (staticData->first().x() - croppedData->at(0).x())); + (*croppedData)[0].setX(staticData->first().x()); + + // crop upper bound: + if (staticData->last().x() > croppedData->last().x()) { // other one must be cropped + qSwap(staticData, croppedData); + } + int highBound = findIndexAboveX(croppedData, staticData->last().x()); + if (highBound == -1) { + return QPolygonF(); // key ranges have no overlap + } + croppedData->remove(highBound + 1, croppedData->size() - (highBound + 1)); + // set highest point of cropped data to fit exactly key position of last static data point via linear interpolation: + if (croppedData->size() < 2) { + return QPolygonF(); // need at least two points for interpolation + } + const int li = croppedData->size() - 1; // last index + if (!qFuzzyCompare(croppedData->at(li).x(), croppedData->at(li - 1).x())) { + slope = (croppedData->at(li).y() - croppedData->at(li - 1).y()) / (croppedData->at(li).x() - croppedData->at(li - 1).x()); + } else { + slope = 0; + } + (*croppedData)[li].setY(croppedData->at(li - 1).y() + slope * (staticData->last().x() - croppedData->at(li - 1).x())); + (*croppedData)[li].setX(staticData->last().x()); + } else { // mKeyAxis->orientation() == Qt::Vertical + // y is key + // crop lower bound: + if (staticData->first().y() < croppedData->first().y()) { // other one must be cropped + qSwap(staticData, croppedData); + } + int lowBound = findIndexBelowY(croppedData, staticData->first().y()); + if (lowBound == -1) { + return QPolygonF(); // key ranges have no overlap + } + croppedData->remove(0, lowBound); + // set lowest point of cropped data to fit exactly key position of first static data point via linear interpolation: + if (croppedData->size() < 2) { + return QPolygonF(); // need at least two points for interpolation + } + double slope; + if (!qFuzzyCompare(croppedData->at(1).y(), croppedData->at(0).y())) { // avoid division by zero in step plots + slope = (croppedData->at(1).x() - croppedData->at(0).x()) / (croppedData->at(1).y() - croppedData->at(0).y()); + } else { + slope = 0; + } + (*croppedData)[0].setX(croppedData->at(0).x() + slope * (staticData->first().y() - croppedData->at(0).y())); + (*croppedData)[0].setY(staticData->first().y()); + + // crop upper bound: + if (staticData->last().y() > croppedData->last().y()) { // other one must be cropped + qSwap(staticData, croppedData); + } + int highBound = findIndexAboveY(croppedData, staticData->last().y()); + if (highBound == -1) { + return QPolygonF(); // key ranges have no overlap + } + croppedData->remove(highBound + 1, croppedData->size() - (highBound + 1)); + // set highest point of cropped data to fit exactly key position of last static data point via linear interpolation: + if (croppedData->size() < 2) { + return QPolygonF(); // need at least two points for interpolation + } + int li = croppedData->size() - 1; // last index + if (!qFuzzyCompare(croppedData->at(li).y(), croppedData->at(li - 1).y())) { // avoid division by zero in step plots + slope = (croppedData->at(li).x() - croppedData->at(li - 1).x()) / (croppedData->at(li).y() - croppedData->at(li - 1).y()); + } else { + slope = 0; + } + (*croppedData)[li].setX(croppedData->at(li - 1).x() + slope * (staticData->last().y() - croppedData->at(li - 1).y())); + (*croppedData)[li].setY(staticData->last().y()); + } + + // return joined: + for (int i = otherSegmentData.size() - 1; i >= 0; --i) { // insert reversed, otherwise the polygon will be twisted + thisSegmentData << otherSegmentData.at(i); + } + return QPolygonF(thisSegmentData); } /*! \internal - + Finds the smallest index of \a data, whose points x value is just above \a x. Assumes x values in \a data points are ordered ascending, as is ensured by \ref getLines/\ref getScatters if the key axis is horizontal. @@ -21559,126 +21654,123 @@ const QPolygonF QCPGraph::getChannelFillPolygon(const QVector *thisData */ int QCPGraph::findIndexAboveX(const QVector *data, double x) const { - for (int i=data->size()-1; i>=0; --i) - { - if (data->at(i).x() < x) - { - if (isize()-1) - return i+1; - else - return data->size()-1; + for (int i = data->size() - 1; i >= 0; --i) { + if (data->at(i).x() < x) { + if (i < data->size() - 1) { + return i + 1; + } else { + return data->size() - 1; + } + } } - } - return -1; + return -1; } /*! \internal - + Finds the highest index of \a data, whose points x value is just below \a x. Assumes x values in \a data points are ordered ascending, as is ensured by \ref getLines/\ref getScatters if the key axis is horizontal. - + Used to calculate the channel fill polygon, see \ref getChannelFillPolygon. */ int QCPGraph::findIndexBelowX(const QVector *data, double x) const { - for (int i=0; isize(); ++i) - { - if (data->at(i).x() > x) - { - if (i>0) - return i-1; - else - return 0; + for (int i = 0; i < data->size(); ++i) { + if (data->at(i).x() > x) { + if (i > 0) { + return i - 1; + } else { + return 0; + } + } } - } - return -1; + return -1; } /*! \internal - + Finds the smallest index of \a data, whose points y value is just above \a y. Assumes y values in \a data points are ordered ascending, as is ensured by \ref getLines/\ref getScatters if the key axis is vertical. - + Used to calculate the channel fill polygon, see \ref getChannelFillPolygon. */ int QCPGraph::findIndexAboveY(const QVector *data, double y) const { - for (int i=data->size()-1; i>=0; --i) - { - if (data->at(i).y() < y) - { - if (isize()-1) - return i+1; - else - return data->size()-1; + for (int i = data->size() - 1; i >= 0; --i) { + if (data->at(i).y() < y) { + if (i < data->size() - 1) { + return i + 1; + } else { + return data->size() - 1; + } + } } - } - return -1; + return -1; } /*! \internal - + 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, QCPGraphDataContainer::const_iterator &closestData) const { - closestData = mDataContainer->constEnd(); - if (mDataContainer->isEmpty()) - return -1.0; - if (mLineStyle == lsNone && mScatterStyle.isNone()) - return -1.0; - - // 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) - { - const double currentDistSqr = QCPVector2D(coordsToPixels(it->key, it->value)-pixelPoint).lengthSquared(); - if (currentDistSqr < minDistSqr) - { - minDistSqr = currentDistSqr; - closestData = it; + closestData = mDataContainer->constEnd(); + if (mDataContainer->isEmpty()) { + return -1.0; } - } - - // calculate distance to graph line if there is one (if so, will probably be smaller than distance to closest data point): - if (mLineStyle != lsNone) - { - // line displayed, calculate distance to line segments: - QVector lineData; - 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)(); + // determine which key range comes into question, taking selection tolerance around pos into account: + double posKeyMin, posKeyMax, dummy; + pixelsToCoords(pixelPoint - QPointF(mParentPlot->selectionTolerance(), mParentPlot->selectionTolerance()), posKeyMin, dummy); + pixelsToCoords(pixelPoint + QPointF(mParentPlot->selectionTolerance(), mParentPlot->selectionTolerance()), posKeyMax, dummy); + if (posKeyMin > posKeyMax) { + qSwap(posKeyMin, posKeyMax); + } + // iterate over found data points and then choose the one with the shortest distance to pos: + QCPGraphDataContainer::const_iterator begin = mDataContainer->findBegin(posKeyMin, true); + QCPGraphDataContainer::const_iterator end = mDataContainer->findEnd(posKeyMax, true); + for (QCPGraphDataContainer::const_iterator it = begin; it != end; ++it) { + const double currentDistSqr = QCPVector2D(coordsToPixels(it->key, it->value) - pixelPoint).lengthSquared(); + if (currentDistSqr < minDistSqr) { + minDistSqr = currentDistSqr; + closestData = it; + } + } + + // calculate distance to graph line if there is one (if so, will probably be smaller than distance to closest data point): + if (mLineStyle != lsNone) { + // line displayed, calculate distance to line segments: + QVector lineData; + getLines(&lineData, QCPDataRange(0, dataCount())); + QCPVector2D p(pixelPoint); + const int step = mLineStyle == lsImpulse ? 2 : 1; // impulse plot differs from other line styles in that the lineData points are only pairwise connected + for (int i = 0; i < lineData.size() - 1; i += step) { + const double currentDistSqr = p.distanceSquaredToLine(lineData.at(i), lineData.at(i + 1)); + if (currentDistSqr < minDistSqr) { + minDistSqr = currentDistSqr; + } + } + } + + return qSqrt(minDistSqr); } /*! \internal - + Finds the highest index of \a data, whose points y value is just below \a y. Assumes y values in \a data points are ordered ascending, as is ensured by \ref getLines/\ref getScatters if the key axis is vertical. @@ -21687,17 +21779,16 @@ double QCPGraph::pointDistance(const QPointF &pixelPoint, QCPGraphDataContainer: */ int QCPGraph::findIndexBelowY(const QVector *data, double y) const { - for (int i=0; isize(); ++i) - { - if (data->at(i).y() > y) - { - if (i>0) - return i-1; - else - return 0; + for (int i = 0; i < data->size(); ++i) { + if (data->at(i).y() > y) { + if (i > 0) { + return i - 1; + } else { + return 0; + } + } } - } - return -1; + return -1; } /* end of 'src/plottables/plottable-graph.cpp' */ @@ -21711,67 +21802,67 @@ int QCPGraph::findIndexBelowY(const QVector *data, double y) const /*! \class QCPCurveData \brief Holds the data of one single data point for QCPCurve. - + The stored data is: \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) - + 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. */ @@ -21782,9 +21873,9 @@ int QCPGraph::findIndexBelowY(const QVector *data, double y) const Constructs a curve data point with t, key and value set to zero. */ QCPCurveData::QCPCurveData() : - t(0), - key(0), - value(0) + t(0), + key(0), + value(0) { } @@ -21792,9 +21883,9 @@ QCPCurveData::QCPCurveData() : Constructs a curve data point with the specified \a t, \a key and \a value. */ QCPCurveData::QCPCurveData(double t, double key, double value) : - t(t), - key(key), - value(value) + t(t), + key(key), + value(value) { } @@ -21805,9 +21896,9 @@ QCPCurveData::QCPCurveData(double t, double key, double value) : /*! \class QCPCurve \brief A plottable representing a parametric curve in a plot. - + \image html QCPCurve.png - + Unlike QCPGraph, plottables of this type may have multiple points with the same key coordinate, so their visual representation can have \a loops. This is realized by introducing a third coordinate \a t, which defines the order of the points described by the other two coordinates \a @@ -21816,21 +21907,21 @@ QCPCurveData::QCPCurveData(double t, double key, double value) : 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 qcpcurve-appearance Changing the appearance - + The appearance of the curve is determined by the pen and the brush (\ref setPen, \ref setBrush). - + \section qcpcurve-usage Usage - + Like all data representing objects in QCustomPlot, the QCPCurve is a plottable (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies (QCustomPlot::plottable, QCustomPlot::removePlottable, etc.) - + Usually, you first create an instance: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcurve-creation-1 which registers it with the QCustomPlot instance of the passed axes. Note that this QCustomPlot instance takes @@ -21842,7 +21933,7 @@ QCPCurveData::QCPCurveData(double t, double key, double value) : /* 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. @@ -21855,21 +21946,21 @@ QCPCurveData::QCPCurveData(double t, double key, double 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 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) : - QCPAbstractPlottable1D(keyAxis, valueAxis) + QCPAbstractPlottable1D(keyAxis, valueAxis) { - // modify inherited properties from abstract plottable: - setPen(QPen(Qt::blue, 0)); - setBrush(Qt::NoBrush); - - setScatterStyle(QCPScatterStyle()); - setLineStyle(lsLine); - setScatterSkip(0); + // modify inherited properties from abstract plottable: + setPen(QPen(Qt::blue, 0)); + setBrush(Qt::NoBrush); + + setScatterStyle(QCPScatterStyle()); + setLineStyle(lsLine); + setScatterSkip(0); } QCPCurve::~QCPCurve() @@ -21877,70 +21968,70 @@ QCPCurve::~QCPCurve() } /*! \overload - + 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(QSharedPointer data) { - mDataContainer = data; + mDataContainer = data; } /*! \overload - + 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 &t, const QVector &keys, const QVector &values, bool alreadySorted) { - mDataContainer->clear(); - addData(t, keys, values, alreadySorted); + 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); + mDataContainer->clear(); + addData(keys, values); } /*! Sets the visual appearance of single data points in the plot. If set to \ref QCPScatterStyle::ssNone, no scatter points are drawn (e.g. for line-only plots with appropriate line style). - + \see QCPScatterStyle, setLineStyle */ void QCPCurve::setScatterStyle(const QCPScatterStyle &style) { - mScatterStyle = style; + mScatterStyle = style; } /*! @@ -21956,117 +22047,119 @@ void QCPCurve::setScatterStyle(const QCPScatterStyle &style) */ void QCPCurve::setScatterSkip(int skip) { - mScatterSkip = qMax(0, skip); + mScatterSkip = qMax(0, skip); } /*! Sets how the single data points are connected in the plot or how they are represented visually apart from the scatter symbol. For scatter-only plots, set \a style to \ref lsNone and \ref setScatterStyle to the desired scatter style. - + \see setScatterStyle */ void QCPCurve::setLineStyle(QCPCurve::LineStyle style) { - mLineStyle = style; + mLineStyle = style; } /*! \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 QVector &t, const QVector &keys, const QVector &values, bool alreadySorted) { - 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 + 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 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 QVector &keys, const QVector &values) { - 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 + 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 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) { - mDataContainer->add(QCPCurveData(t, key, value)); + mDataContainer->add(QCPCurveData(t, key, value)); } /*! \overload - + Adds the provided data point as \a key and \a value to the current data. - + 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) { - if (!mDataContainer->isEmpty()) - mDataContainer->add(QCPCurveData((mDataContainer->constEnd()-1)->t + 1.0, key, value)); - else - mDataContainer->add(QCPCurveData(0.0, key, value)); + if (!mDataContainer->isEmpty()) { + mDataContainer->add(QCPCurveData((mDataContainer->constEnd() - 1)->t + 1.0, key, value)); + } else { + mDataContainer->add(QCPCurveData(0.0, key, value)); + } } /*! @@ -22074,143 +22167,143 @@ void QCPCurve::addData(double key, double value) If \a details is not 0, it will be set to a \ref QCPDataSelection, describing the closest data point to \a pos. - + \seebaseclassmethod \ref QCPAbstractPlottable::selectTest */ double QCPCurve::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { - if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty()) - return -1; - if (!mKeyAxis || !mValueAxis) - return -1; - - if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint())) - { - 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))); + if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty()) { + return -1; + } + if (!mKeyAxis || !mValueAxis) { + return -1; + } + + if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint())) { + 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; } - return result; - } else - return -1; } /* inherits documentation from base class */ QCPRange QCPCurve::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const { - return mDataContainer->keyRange(foundRange, inSignDomain); + 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); + return mDataContainer->valueRange(foundRange, inSignDomain, inKeyRange); } /* inherits documentation from base class */ void QCPCurve::draw(QCPPainter *painter) { - if (mDataContainer->isEmpty()) return; - - // allocate line vector: - QVector lines, scatters; - - // 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(); + if (mDataContainer->isEmpty()) { + return; } - #endif - - // draw curve fill: - applyFillAntialiasingHint(painter); - if (isSelectedSegment && mSelectionDecorator) - mSelectionDecorator->applyBrush(painter); - else - painter->setBrush(mBrush); - painter->setPen(Qt::NoPen); - if (painter->brush().style() != Qt::NoBrush && painter->brush().color().alpha() != 0) - painter->drawPolygon(QPolygonF(lines)); - - // draw curve line: - if (mLineStyle != lsNone) - { - painter->setPen(finalCurvePen); - painter->setBrush(Qt::NoBrush); - drawCurveLine(painter, lines); + + // allocate line vector: + QVector lines, scatters; + + // loop over and draw segments of unselected/selected data: + QList selectedSegments, unselectedSegments, allSegments; + getDataSegments(selectedSegments, unselectedSegments); + allSegments << unselectedSegments << selectedSegments; + for (int i = 0; i < allSegments.size(); ++i) { + bool isSelectedSegment = i >= unselectedSegments.size(); + + // fill with curve data: + QPen finalCurvePen = mPen; // determine the final pen already here, because the line optimization depends on its stroke width + if (isSelectedSegment && mSelectionDecorator) { + finalCurvePen = mSelectionDecorator->pen(); + } + + QCPDataRange lineDataRange = isSelectedSegment ? allSegments.at(i) : allSegments.at(i).adjusted(-1, 1); // unselected segments extend lines to bordering selected data point (safe to exceed total data bounds in first/last segment, getCurveLines takes care) + getCurveLines(&lines, lineDataRange, finalCurvePen.widthF()); + + // check data validity if flag set: +#ifdef QCUSTOMPLOT_CHECK_DATA + for (QCPCurveDataContainer::const_iterator it = mDataContainer->constBegin(); it != mDataContainer->constEnd(); ++it) { + if (QCP::isInvalidData(it->t) || + QCP::isInvalidData(it->key, it->value)) { + qDebug() << Q_FUNC_INFO << "Data point at" << it->key << "invalid." << "Plottable name:" << name(); + } + } +#endif + + // draw curve fill: + applyFillAntialiasingHint(painter); + if (isSelectedSegment && mSelectionDecorator) { + mSelectionDecorator->applyBrush(painter); + } else { + painter->setBrush(mBrush); + } + painter->setPen(Qt::NoPen); + if (painter->brush().style() != Qt::NoBrush && painter->brush().color().alpha() != 0) { + painter->drawPolygon(QPolygonF(lines)); + } + + // draw curve line: + if (mLineStyle != lsNone) { + painter->setPen(finalCurvePen); + painter->setBrush(Qt::NoBrush); + drawCurveLine(painter, lines); + } + + // draw scatters: + QCPScatterStyle finalScatterStyle = mScatterStyle; + if (isSelectedSegment && mSelectionDecorator) { + finalScatterStyle = mSelectionDecorator->getFinalScatterStyle(mScatterStyle); + } + if (!finalScatterStyle.isNone()) { + getScatters(&scatters, allSegments.at(i), finalScatterStyle.size()); + drawScatterPlot(painter, scatters, finalScatterStyle); + } } - - // draw scatters: - QCPScatterStyle finalScatterStyle = mScatterStyle; - if (isSelectedSegment && mSelectionDecorator) - finalScatterStyle = mSelectionDecorator->getFinalScatterStyle(mScatterStyle); - if (!finalScatterStyle.isNone()) - { - getScatters(&scatters, allSegments.at(i), finalScatterStyle.size()); - drawScatterPlot(painter, scatters, finalScatterStyle); + + // draw other selection decoration that isn't just line/scatter pens and brushes: + if (mSelectionDecorator) { + mSelectionDecorator->drawDecoration(painter, selection()); } - } - - // 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 QCPCurve::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const { - // draw fill: - if (mBrush.style() != Qt::NoBrush) - { - applyFillAntialiasingHint(painter); - painter->fillRect(QRectF(rect.left(), rect.top()+rect.height()/2.0, rect.width(), rect.height()/3.0), mBrush); - } - // draw line vertically centered: - if (mLineStyle != lsNone) - { - applyDefaultAntialiasingHint(painter); - painter->setPen(mPen); - painter->drawLine(QLineF(rect.left(), rect.top()+rect.height()/2.0, rect.right()+5, rect.top()+rect.height()/2.0)); // +5 on x2 else last segment is missing from dashed/dotted pens - } - // draw scatter symbol: - if (!mScatterStyle.isNone()) - { - applyScattersAntialiasingHint(painter); - // scale scatter pixmap if it's too large to fit in legend icon rect: - if (mScatterStyle.shape() == QCPScatterStyle::ssPixmap && (mScatterStyle.pixmap().size().width() > rect.width() || mScatterStyle.pixmap().size().height() > rect.height())) - { - QCPScatterStyle scaledStyle(mScatterStyle); - scaledStyle.setPixmap(scaledStyle.pixmap().scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation)); - scaledStyle.applyTo(painter, mPen); - scaledStyle.drawShape(painter, QRectF(rect).center()); - } else - { - mScatterStyle.applyTo(painter, mPen); - mScatterStyle.drawShape(painter, QRectF(rect).center()); + // draw fill: + if (mBrush.style() != Qt::NoBrush) { + applyFillAntialiasingHint(painter); + painter->fillRect(QRectF(rect.left(), rect.top() + rect.height() / 2.0, rect.width(), rect.height() / 3.0), mBrush); + } + // draw line vertically centered: + if (mLineStyle != lsNone) { + applyDefaultAntialiasingHint(painter); + painter->setPen(mPen); + painter->drawLine(QLineF(rect.left(), rect.top() + rect.height() / 2.0, rect.right() + 5, rect.top() + rect.height() / 2.0)); // +5 on x2 else last segment is missing from dashed/dotted pens + } + // draw scatter symbol: + if (!mScatterStyle.isNone()) { + applyScattersAntialiasingHint(painter); + // scale scatter pixmap if it's too large to fit in legend icon rect: + if (mScatterStyle.shape() == QCPScatterStyle::ssPixmap && (mScatterStyle.pixmap().size().width() > rect.width() || mScatterStyle.pixmap().size().height() > rect.height())) { + QCPScatterStyle scaledStyle(mScatterStyle); + scaledStyle.setPixmap(scaledStyle.pixmap().scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation)); + scaledStyle.applyTo(painter, mPen); + scaledStyle.drawShape(painter, QRectF(rect).center()); + } else { + mScatterStyle.applyTo(painter, mPen); + mScatterStyle.drawShape(painter, QRectF(rect).center()); + } } - } } /*! \internal @@ -22221,11 +22314,10 @@ void QCPCurve::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const */ void QCPCurve::drawCurveLine(QCPPainter *painter, const QVector &lines) const { - if (painter->pen().style() != Qt::NoPen && painter->pen().color().alpha() != 0) - { - applyDefaultAntialiasingHint(painter); - drawPolyline(painter, lines); - } + if (painter->pen().style() != Qt::NoPen && painter->pen().color().alpha() != 0) { + applyDefaultAntialiasingHint(painter); + drawPolyline(painter, lines); + } } /*! \internal @@ -22237,12 +22329,13 @@ void QCPCurve::drawCurveLine(QCPPainter *painter, const QVector &lines) */ 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 &poin */ 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 - 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 != itEnd) - { - 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 - { - QPointF crossA, crossB; - if (prevRegion == 5) // we're coming from R, so add this point optimized - { - 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 - *lines << getOptimizedCornerPoints(prevRegion, currentRegion, prevIt->key, prevIt->value, it->key, it->value, keyMin, valueMax, keyMax, valueMin); - } else if (mayTraverse(prevRegion, currentRegion) && - 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, keyMin, valueMax, keyMax, valueMin, beforeTraverseCornerPoints, afterTraverseCornerPoints); - if (it != itBegin) - { - *lines << beforeTraverseCornerPoints; - lines->append(crossA); - lines->append(crossB); - *lines << afterTraverseCornerPoints; - } else - { - 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) - { - *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 == 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 - 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 - { - 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... - } + if (!lines) { + return; } - prevIt = it; - prevRegion = currentRegion; - ++it; - } - *lines << trailingPoints; + 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 + 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 != itEnd) { + 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 + QPointF crossA, crossB; + if (prevRegion == 5) { // we're coming from R, so add this point optimized + 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 + *lines << getOptimizedCornerPoints(prevRegion, currentRegion, prevIt->key, prevIt->value, it->key, it->value, keyMin, valueMax, keyMax, valueMin); + } else if (mayTraverse(prevRegion, currentRegion) && + 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, keyMin, valueMax, keyMax, valueMin, beforeTraverseCornerPoints, afterTraverseCornerPoints); + if (it != itBegin) { + *lines << beforeTraverseCornerPoints; + lines->append(crossA); + lines->append(crossB); + *lines << afterTraverseCornerPoints; + } else { + 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) + *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 == 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 { + 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 + 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... + } + } + prevIt = it; + prevRegion = currentRegion; + ++it; + } + *lines << trailingPoints; } /*! \internal @@ -22378,81 +22466,80 @@ void QCPCurve::getCurveLines(QVector *lines, const QCPDataRange &dataRa */ 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; } - - 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(); - - 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; - } - } + if (!scatters) { + return; } - } 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; - } - } + scatters->clear(); + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + return; + } + + 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(); + + 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 @@ -22476,43 +22563,43 @@ void QCPCurve::getScatters(QVector *scatters, const QCPDataRange &dataR */ int QCPCurve::getRegion(double key, double value, double keyMin, double valueMax, double keyMax, double valueMin) const { - if (key < keyMin) // region 123 - { - if (value > valueMax) - return 1; - else if (value < valueMin) - return 3; - else - return 2; - } else if (key > keyMax) // region 789 - { - if (value > valueMax) - return 7; - else if (value < valueMin) - return 9; - else - return 8; - } else // region 456 - { - if (value > valueMax) - return 4; - else if (value < valueMin) - return 6; - else - return 5; - } + if (key < keyMin) { // region 123 + if (value > valueMax) { + return 1; + } else if (value < valueMin) { + return 3; + } else { + return 2; + } + } else if (key > keyMax) { // region 789 + if (value > valueMax) { + return 7; + } else if (value < valueMin) { + return 9; + } else { + return 8; + } + } else { // region 456 + if (value > valueMax) { + return 4; + } else if (value < valueMin) { + return 6; + } else { + return 5; + } + } } /*! \internal - + 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 the line connecting (\a key, \a value) with (\a otherKey, \a otherValue). - + It returns the intersection point of the segment with the border of region 5. - + For this function it doesn't matter whether (\a key, \a value) is the point inside region 5 or whether it's (\a otherKey, \a otherValue), i.e. whether the segment is coming from region 5 or leaving it. It is important though that \a otherRegion correctly identifies the other region not @@ -22520,113 +22607,100 @@ int QCPCurve::getRegion(double key, double value, double keyMin, double valueMax */ QPointF QCPCurve::getOptimizedPoint(int otherRegion, double otherKey, double otherValue, double key, double value, double keyMin, double valueMax, double keyMax, double valueMin) const { - // The intersection point interpolation here is done in pixel coordinates, so we don't need to - // differentiate between different axis scale types. Note that the nomenclature - // top/left/bottom/right/min/max is with respect to the rect in plot coordinates, wich may be - // different in pixel coordinates (horz/vert key axes, reversed ranges) - - const double keyMinPx = mKeyAxis->coordToPixel(keyMin); - const double keyMaxPx = mKeyAxis->coordToPixel(keyMax); - const double valueMinPx = mValueAxis->coordToPixel(valueMin); - const double valueMaxPx = mValueAxis->coordToPixel(valueMax); - const double otherValuePx = mValueAxis->coordToPixel(otherValue); - const double valuePx = mValueAxis->coordToPixel(value); - const double otherKeyPx = mKeyAxis->coordToPixel(otherKey); - const double keyPx = mKeyAxis->coordToPixel(key); - double intersectKeyPx = keyMinPx; // initial key just a fail-safe - double intersectValuePx = valueMinPx; // initial value just a fail-safe - switch (otherRegion) - { - case 1: // top and left edge - { - intersectValuePx = valueMaxPx; - intersectKeyPx = otherKeyPx + (keyPx-otherKeyPx)/(valuePx-otherValuePx)*(intersectValuePx-otherValuePx); - if (intersectKeyPx < qMin(keyMinPx, keyMaxPx) || intersectKeyPx > qMax(keyMinPx, keyMaxPx)) // check whether top edge is not intersected, then it must be left edge (qMin/qMax necessary since axes may be reversed) - { - intersectKeyPx = keyMinPx; - intersectValuePx = otherValuePx + (valuePx-otherValuePx)/(keyPx-otherKeyPx)*(intersectKeyPx-otherKeyPx); - } - break; + // The intersection point interpolation here is done in pixel coordinates, so we don't need to + // differentiate between different axis scale types. Note that the nomenclature + // top/left/bottom/right/min/max is with respect to the rect in plot coordinates, wich may be + // different in pixel coordinates (horz/vert key axes, reversed ranges) + + const double keyMinPx = mKeyAxis->coordToPixel(keyMin); + const double keyMaxPx = mKeyAxis->coordToPixel(keyMax); + const double valueMinPx = mValueAxis->coordToPixel(valueMin); + const double valueMaxPx = mValueAxis->coordToPixel(valueMax); + const double otherValuePx = mValueAxis->coordToPixel(otherValue); + const double valuePx = mValueAxis->coordToPixel(value); + const double otherKeyPx = mKeyAxis->coordToPixel(otherKey); + const double keyPx = mKeyAxis->coordToPixel(key); + double intersectKeyPx = keyMinPx; // initial key just a fail-safe + double intersectValuePx = valueMinPx; // initial value just a fail-safe + switch (otherRegion) { + case 1: { // top and left edge + intersectValuePx = valueMaxPx; + intersectKeyPx = otherKeyPx + (keyPx - otherKeyPx) / (valuePx - otherValuePx) * (intersectValuePx - otherValuePx); + if (intersectKeyPx < qMin(keyMinPx, keyMaxPx) || intersectKeyPx > qMax(keyMinPx, keyMaxPx)) { // check whether top edge is not intersected, then it must be left edge (qMin/qMax necessary since axes may be reversed) + intersectKeyPx = keyMinPx; + intersectValuePx = otherValuePx + (valuePx - otherValuePx) / (keyPx - otherKeyPx) * (intersectKeyPx - otherKeyPx); + } + break; + } + case 2: { // left edge + intersectKeyPx = keyMinPx; + intersectValuePx = otherValuePx + (valuePx - otherValuePx) / (keyPx - otherKeyPx) * (intersectKeyPx - otherKeyPx); + break; + } + case 3: { // bottom and left edge + intersectValuePx = valueMinPx; + intersectKeyPx = otherKeyPx + (keyPx - otherKeyPx) / (valuePx - otherValuePx) * (intersectValuePx - otherValuePx); + if (intersectKeyPx < qMin(keyMinPx, keyMaxPx) || intersectKeyPx > qMax(keyMinPx, keyMaxPx)) { // check whether bottom edge is not intersected, then it must be left edge (qMin/qMax necessary since axes may be reversed) + intersectKeyPx = keyMinPx; + intersectValuePx = otherValuePx + (valuePx - otherValuePx) / (keyPx - otherKeyPx) * (intersectKeyPx - otherKeyPx); + } + break; + } + case 4: { // top edge + intersectValuePx = valueMaxPx; + intersectKeyPx = otherKeyPx + (keyPx - otherKeyPx) / (valuePx - otherValuePx) * (intersectValuePx - otherValuePx); + break; + } + case 5: { + break; // case 5 shouldn't happen for this function but we add it anyway to prevent potential discontinuity in branch table + } + case 6: { // bottom edge + intersectValuePx = valueMinPx; + intersectKeyPx = otherKeyPx + (keyPx - otherKeyPx) / (valuePx - otherValuePx) * (intersectValuePx - otherValuePx); + break; + } + case 7: { // top and right edge + intersectValuePx = valueMaxPx; + intersectKeyPx = otherKeyPx + (keyPx - otherKeyPx) / (valuePx - otherValuePx) * (intersectValuePx - otherValuePx); + if (intersectKeyPx < qMin(keyMinPx, keyMaxPx) || intersectKeyPx > qMax(keyMinPx, keyMaxPx)) { // check whether top edge is not intersected, then it must be right edge (qMin/qMax necessary since axes may be reversed) + intersectKeyPx = keyMaxPx; + intersectValuePx = otherValuePx + (valuePx - otherValuePx) / (keyPx - otherKeyPx) * (intersectKeyPx - otherKeyPx); + } + break; + } + case 8: { // right edge + intersectKeyPx = keyMaxPx; + intersectValuePx = otherValuePx + (valuePx - otherValuePx) / (keyPx - otherKeyPx) * (intersectKeyPx - otherKeyPx); + break; + } + case 9: { // bottom and right edge + intersectValuePx = valueMinPx; + intersectKeyPx = otherKeyPx + (keyPx - otherKeyPx) / (valuePx - otherValuePx) * (intersectValuePx - otherValuePx); + if (intersectKeyPx < qMin(keyMinPx, keyMaxPx) || intersectKeyPx > qMax(keyMinPx, keyMaxPx)) { // check whether bottom edge is not intersected, then it must be right edge (qMin/qMax necessary since axes may be reversed) + intersectKeyPx = keyMaxPx; + intersectValuePx = otherValuePx + (valuePx - otherValuePx) / (keyPx - otherKeyPx) * (intersectKeyPx - otherKeyPx); + } + break; + } } - case 2: // left edge - { - intersectKeyPx = keyMinPx; - intersectValuePx = otherValuePx + (valuePx-otherValuePx)/(keyPx-otherKeyPx)*(intersectKeyPx-otherKeyPx); - break; + if (mKeyAxis->orientation() == Qt::Horizontal) { + return QPointF(intersectKeyPx, intersectValuePx); + } else { + return QPointF(intersectValuePx, intersectKeyPx); } - case 3: // bottom and left edge - { - intersectValuePx = valueMinPx; - intersectKeyPx = otherKeyPx + (keyPx-otherKeyPx)/(valuePx-otherValuePx)*(intersectValuePx-otherValuePx); - if (intersectKeyPx < qMin(keyMinPx, keyMaxPx) || intersectKeyPx > qMax(keyMinPx, keyMaxPx)) // check whether bottom edge is not intersected, then it must be left edge (qMin/qMax necessary since axes may be reversed) - { - intersectKeyPx = keyMinPx; - intersectValuePx = otherValuePx + (valuePx-otherValuePx)/(keyPx-otherKeyPx)*(intersectKeyPx-otherKeyPx); - } - break; - } - case 4: // top edge - { - intersectValuePx = valueMaxPx; - intersectKeyPx = otherKeyPx + (keyPx-otherKeyPx)/(valuePx-otherValuePx)*(intersectValuePx-otherValuePx); - break; - } - case 5: - { - break; // case 5 shouldn't happen for this function but we add it anyway to prevent potential discontinuity in branch table - } - case 6: // bottom edge - { - intersectValuePx = valueMinPx; - intersectKeyPx = otherKeyPx + (keyPx-otherKeyPx)/(valuePx-otherValuePx)*(intersectValuePx-otherValuePx); - break; - } - case 7: // top and right edge - { - intersectValuePx = valueMaxPx; - intersectKeyPx = otherKeyPx + (keyPx-otherKeyPx)/(valuePx-otherValuePx)*(intersectValuePx-otherValuePx); - if (intersectKeyPx < qMin(keyMinPx, keyMaxPx) || intersectKeyPx > qMax(keyMinPx, keyMaxPx)) // check whether top edge is not intersected, then it must be right edge (qMin/qMax necessary since axes may be reversed) - { - intersectKeyPx = keyMaxPx; - intersectValuePx = otherValuePx + (valuePx-otherValuePx)/(keyPx-otherKeyPx)*(intersectKeyPx-otherKeyPx); - } - break; - } - case 8: // right edge - { - intersectKeyPx = keyMaxPx; - intersectValuePx = otherValuePx + (valuePx-otherValuePx)/(keyPx-otherKeyPx)*(intersectKeyPx-otherKeyPx); - break; - } - case 9: // bottom and right edge - { - intersectValuePx = valueMinPx; - intersectKeyPx = otherKeyPx + (keyPx-otherKeyPx)/(valuePx-otherValuePx)*(intersectValuePx-otherValuePx); - if (intersectKeyPx < qMin(keyMinPx, keyMaxPx) || intersectKeyPx > qMax(keyMinPx, keyMaxPx)) // check whether bottom edge is not intersected, then it must be right edge (qMin/qMax necessary since axes may be reversed) - { - intersectKeyPx = keyMaxPx; - intersectValuePx = otherValuePx + (valuePx-otherValuePx)/(keyPx-otherKeyPx)*(intersectKeyPx-otherKeyPx); - } - break; - } - } - if (mKeyAxis->orientation() == Qt::Horizontal) - return QPointF(intersectKeyPx, intersectValuePx); - else - return QPointF(intersectValuePx, intersectKeyPx); } /*! \internal - + 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 doesn't unintentionally cut through the visible area of the axis rect and create plot artifacts. This method provides these points that must be added, assuming the original segment doesn't start, end, or traverse region 5. (Corner points where region 5 is traversed are calculated by \ref getTraverseCornerPoints.) - + For example, consider a segment which directly goes from region 4 to 2 but originally is far out to the top left such that it doesn't cross region 5. Naively optimizing these points by projecting them on the top and left borders of region 5 will create a segment that surely crosses @@ -22636,524 +22710,759 @@ QPointF QCPCurve::getOptimizedPoint(int otherRegion, double otherKey, double oth */ 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) - { - case 1: - { - switch (currentRegion) - { - 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)*(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(keyMin, valueMax) << coordsToPixels(keyMax, valueMax); result.append(result.last()); result << coordsToPixels(keyMax, valueMin); } - break; + QVector result; + switch (prevRegion) { + case 1: { + switch (currentRegion) { + 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) * (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(keyMin, valueMax) << coordsToPixels(keyMax, valueMax); + result.append(result.last()); + result << coordsToPixels(keyMax, valueMin); + } + break; + } + } + break; } - } - break; - } - case 2: - { - switch (currentRegion) - { - 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; - } - case 3: - { - switch (currentRegion) - { - 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)*(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(keyMin, valueMin) << coordsToPixels(keyMin, valueMax); result.append(result.last()); result << coordsToPixels(keyMax, valueMax); } - break; + case 2: { + switch (currentRegion) { + 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; } - } - break; - } - case 4: - { - switch (currentRegion) - { - 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; - } - case 5: - { - switch (currentRegion) - { - 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; - } - case 6: - { - switch (currentRegion) - { - 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; - } - case 7: - { - switch (currentRegion) - { - 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)*(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(keyMax, valueMax) << coordsToPixels(keyMin, valueMax); result.append(result.last()); result << coordsToPixels(keyMin, valueMin); } - break; + case 3: { + switch (currentRegion) { + 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) * (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(keyMin, valueMin) << coordsToPixels(keyMin, valueMax); + result.append(result.last()); + result << coordsToPixels(keyMax, valueMax); + } + break; + } + } + break; } - } - break; - } - case 8: - { - switch (currentRegion) - { - 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; - } - case 9: - { - switch (currentRegion) - { - 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)*(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(keyMax, valueMin) << coordsToPixels(keyMax, valueMax); result.append(result.last()); result << coordsToPixels(keyMin, valueMax); } - break; + case 4: { + switch (currentRegion) { + 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; + } + case 5: { + switch (currentRegion) { + 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; + } + case 6: { + switch (currentRegion) { + 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; + } + case 7: { + switch (currentRegion) { + 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) * (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(keyMax, valueMax) << coordsToPixels(keyMin, valueMax); + result.append(result.last()); + result << coordsToPixels(keyMin, valueMin); + } + break; + } + } + break; + } + case 8: { + switch (currentRegion) { + 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; + } + case 9: { + switch (currentRegion) { + 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) * (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(keyMax, valueMin) << coordsToPixels(keyMax, valueMax); + result.append(result.last()); + result << coordsToPixels(keyMin, valueMax); + } + break; + } + } + break; } - } - break; } - } - return result; + return result; } /*! \internal - + 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 nor \a currentRegion is 5 itself. - + If this method returns false, the segment for sure doesn't pass region 5. If it returns true, the segment may or may not pass region 5 and a more fine-grained calculation must be used (\ref getTraverse). */ bool QCPCurve::mayTraverse(int prevRegion, int currentRegion) const { - switch (prevRegion) - { - case 1: - { - switch (currentRegion) - { - case 4: - case 7: - case 2: - case 3: return false; - default: return true; - } + switch (prevRegion) { + case 1: { + switch (currentRegion) { + case 4: + case 7: + case 2: + case 3: + return false; + default: + return true; + } + } + case 2: { + switch (currentRegion) { + case 1: + case 3: + return false; + default: + return true; + } + } + case 3: { + switch (currentRegion) { + case 1: + case 2: + case 6: + case 9: + return false; + default: + return true; + } + } + case 4: { + switch (currentRegion) { + case 1: + case 7: + return false; + default: + return true; + } + } + case 5: + return false; // should never occur + case 6: { + switch (currentRegion) { + case 3: + case 9: + return false; + default: + return true; + } + } + case 7: { + switch (currentRegion) { + case 1: + case 4: + case 8: + case 9: + return false; + default: + return true; + } + } + case 8: { + switch (currentRegion) { + case 7: + case 9: + return false; + default: + return true; + } + } + case 9: { + switch (currentRegion) { + case 3: + case 6: + case 8: + case 7: + return false; + default: + return true; + } + } + default: + return true; } - case 2: - { - switch (currentRegion) - { - case 1: - case 3: return false; - default: return true; - } - } - case 3: - { - switch (currentRegion) - { - case 1: - case 2: - case 6: - case 9: return false; - default: return true; - } - } - case 4: - { - switch (currentRegion) - { - case 1: - case 7: return false; - default: return true; - } - } - case 5: return false; // should never occur - case 6: - { - switch (currentRegion) - { - case 3: - case 9: return false; - default: return true; - } - } - case 7: - { - switch (currentRegion) - { - case 1: - case 4: - case 8: - case 9: return false; - default: return true; - } - } - case 8: - { - switch (currentRegion) - { - case 7: - case 9: return false; - default: return true; - } - } - case 9: - { - switch (currentRegion) - { - case 3: - case 6: - case 8: - case 7: return false; - default: return true; - } - } - default: return true; - } } /*! \internal - + 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 region 5. - + The return value of this method indicates whether the segment actually traverses region 5 or not. - + 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 keyMin, double valueMax, double keyMax, double valueMin, QPointF &crossA, QPointF &crossB) const { - // The intersection point interpolation here is done in pixel coordinates, so we don't need to - // differentiate between different axis scale types. Note that the nomenclature - // top/left/bottom/right/min/max is with respect to the rect in plot coordinates, wich may be - // different in pixel coordinates (horz/vert key axes, reversed ranges) - - QList intersections; - const double valueMinPx = mValueAxis->coordToPixel(valueMin); - const double valueMaxPx = mValueAxis->coordToPixel(valueMax); - const double keyMinPx = mKeyAxis->coordToPixel(keyMin); - const double keyMaxPx = mKeyAxis->coordToPixel(keyMax); - const double keyPx = mKeyAxis->coordToPixel(key); - const double valuePx = mValueAxis->coordToPixel(value); - const double prevKeyPx = mKeyAxis->coordToPixel(prevKey); - const double prevValuePx = mValueAxis->coordToPixel(prevValue); - if (qFuzzyIsNull(key-prevKey)) // line is parallel to value axis - { - // due to region filter in mayTraverse(), if line is parallel to value or key axis, region 5 is traversed here - intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyPx, valueMinPx) : QPointF(valueMinPx, keyPx)); // direction will be taken care of at end of method - intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyPx, valueMaxPx) : QPointF(valueMaxPx, keyPx)); - } else if (qFuzzyIsNull(value-prevValue)) // line is parallel to key axis - { - // due to region filter in mayTraverse(), if line is parallel to value or key axis, region 5 is traversed here - intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyMinPx, valuePx) : QPointF(valuePx, keyMinPx)); // direction will be taken care of at end of method - intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyMaxPx, valuePx) : QPointF(valuePx, keyMaxPx)); - } else // line is skewed - { - double gamma; - double keyPerValuePx = (keyPx-prevKeyPx)/(valuePx-prevValuePx); - // check top of rect: - gamma = prevKeyPx + (valueMaxPx-prevValuePx)*keyPerValuePx; - if (gamma >= qMin(keyMinPx, keyMaxPx) && gamma <= qMax(keyMinPx, keyMaxPx)) // qMin/qMax necessary since axes may be reversed - intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(gamma, valueMaxPx) : QPointF(valueMaxPx, gamma)); - // check bottom of rect: - gamma = prevKeyPx + (valueMinPx-prevValuePx)*keyPerValuePx; - if (gamma >= qMin(keyMinPx, keyMaxPx) && gamma <= qMax(keyMinPx, keyMaxPx)) // qMin/qMax necessary since axes may be reversed - intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(gamma, valueMinPx) : QPointF(valueMinPx, gamma)); - const double valuePerKeyPx = 1.0/keyPerValuePx; - // check left of rect: - gamma = prevValuePx + (keyMinPx-prevKeyPx)*valuePerKeyPx; - if (gamma >= qMin(valueMinPx, valueMaxPx) && gamma <= qMax(valueMinPx, valueMaxPx)) // qMin/qMax necessary since axes may be reversed - intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyMinPx, gamma) : QPointF(gamma, keyMinPx)); - // check right of rect: - gamma = prevValuePx + (keyMaxPx-prevKeyPx)*valuePerKeyPx; - if (gamma >= qMin(valueMinPx, valueMaxPx) && gamma <= qMax(valueMinPx, valueMaxPx)) // qMin/qMax necessary since axes may be reversed - intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyMaxPx, gamma) : QPointF(gamma, keyMaxPx)); - } - - // handle cases where found points isn't exactly 2: - if (intersections.size() > 2) - { - // line probably goes through corner of rect, and we got duplicate points there. single out the point pair with greatest distance in between: - double distSqrMax = 0; - QPointF pv1, pv2; - for (int i=0; i distSqrMax) - { - pv1 = intersections.at(i); - pv2 = intersections.at(k); - distSqrMax = distSqr; + // The intersection point interpolation here is done in pixel coordinates, so we don't need to + // differentiate between different axis scale types. Note that the nomenclature + // top/left/bottom/right/min/max is with respect to the rect in plot coordinates, wich may be + // different in pixel coordinates (horz/vert key axes, reversed ranges) + + QList intersections; + const double valueMinPx = mValueAxis->coordToPixel(valueMin); + const double valueMaxPx = mValueAxis->coordToPixel(valueMax); + const double keyMinPx = mKeyAxis->coordToPixel(keyMin); + const double keyMaxPx = mKeyAxis->coordToPixel(keyMax); + const double keyPx = mKeyAxis->coordToPixel(key); + const double valuePx = mValueAxis->coordToPixel(value); + const double prevKeyPx = mKeyAxis->coordToPixel(prevKey); + const double prevValuePx = mValueAxis->coordToPixel(prevValue); + if (qFuzzyIsNull(key - prevKey)) { // line is parallel to value axis + // due to region filter in mayTraverse(), if line is parallel to value or key axis, region 5 is traversed here + intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyPx, valueMinPx) : QPointF(valueMinPx, keyPx)); // direction will be taken care of at end of method + intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyPx, valueMaxPx) : QPointF(valueMaxPx, keyPx)); + } else if (qFuzzyIsNull(value - prevValue)) { // line is parallel to key axis + // due to region filter in mayTraverse(), if line is parallel to value or key axis, region 5 is traversed here + intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyMinPx, valuePx) : QPointF(valuePx, keyMinPx)); // direction will be taken care of at end of method + intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyMaxPx, valuePx) : QPointF(valuePx, keyMaxPx)); + } else { // line is skewed + double gamma; + double keyPerValuePx = (keyPx - prevKeyPx) / (valuePx - prevValuePx); + // check top of rect: + gamma = prevKeyPx + (valueMaxPx - prevValuePx) * keyPerValuePx; + if (gamma >= qMin(keyMinPx, keyMaxPx) && gamma <= qMax(keyMinPx, keyMaxPx)) { // qMin/qMax necessary since axes may be reversed + intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(gamma, valueMaxPx) : QPointF(valueMaxPx, gamma)); + } + // check bottom of rect: + gamma = prevKeyPx + (valueMinPx - prevValuePx) * keyPerValuePx; + if (gamma >= qMin(keyMinPx, keyMaxPx) && gamma <= qMax(keyMinPx, keyMaxPx)) { // qMin/qMax necessary since axes may be reversed + intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(gamma, valueMinPx) : QPointF(valueMinPx, gamma)); + } + const double valuePerKeyPx = 1.0 / keyPerValuePx; + // check left of rect: + gamma = prevValuePx + (keyMinPx - prevKeyPx) * valuePerKeyPx; + if (gamma >= qMin(valueMinPx, valueMaxPx) && gamma <= qMax(valueMinPx, valueMaxPx)) { // qMin/qMax necessary since axes may be reversed + intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyMinPx, gamma) : QPointF(gamma, keyMinPx)); + } + // check right of rect: + gamma = prevValuePx + (keyMaxPx - prevKeyPx) * valuePerKeyPx; + if (gamma >= qMin(valueMinPx, valueMaxPx) && gamma <= qMax(valueMinPx, valueMaxPx)) { // qMin/qMax necessary since axes may be reversed + intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyMaxPx, gamma) : QPointF(gamma, keyMaxPx)); } - } } - intersections = QList() << pv1 << pv2; - } else if (intersections.size() != 2) - { - // one or even zero points found (shouldn't happen unless line perfectly tangent to corner), no need to draw segment - return false; - } - - // possibly re-sort points so optimized point segment has same direction as original segment: - double xDelta = keyPx-prevKeyPx; - double yDelta = valuePx-prevValuePx; - if (mKeyAxis->orientation() != Qt::Horizontal) - qSwap(xDelta, yDelta); - if (xDelta*(intersections.at(1).x()-intersections.at(0).x()) + yDelta*(intersections.at(1).y()-intersections.at(0).y()) < 0) // scalar product of both segments < 0 -> opposite direction - intersections.move(0, 1); - crossA = intersections.at(0); - crossB = intersections.at(1); - return true; + + // handle cases where found points isn't exactly 2: + if (intersections.size() > 2) { + // line probably goes through corner of rect, and we got duplicate points there. single out the point pair with greatest distance in between: + double distSqrMax = 0; + QPointF pv1, pv2; + for (int i = 0; i < intersections.size() - 1; ++i) { + for (int k = i + 1; k < intersections.size(); ++k) { + QPointF distPoint = intersections.at(i) - intersections.at(k); + double distSqr = distPoint.x() * distPoint.x() + distPoint.y() + distPoint.y(); + if (distSqr > distSqrMax) { + pv1 = intersections.at(i); + pv2 = intersections.at(k); + distSqrMax = distSqr; + } + } + } + intersections = QList() << pv1 << pv2; + } else if (intersections.size() != 2) { + // one or even zero points found (shouldn't happen unless line perfectly tangent to corner), no need to draw segment + return false; + } + + // possibly re-sort points so optimized point segment has same direction as original segment: + double xDelta = keyPx - prevKeyPx; + double yDelta = valuePx - prevValuePx; + if (mKeyAxis->orientation() != Qt::Horizontal) { + qSwap(xDelta, yDelta); + } + if (xDelta * (intersections.at(1).x() - intersections.at(0).x()) + yDelta * (intersections.at(1).y() - intersections.at(0).y()) < 0) { // scalar product of both segments < 0 -> opposite direction + intersections.move(0, 1); + } + crossA = intersections.at(0); + crossB = intersections.at(1); + return true; } /*! \internal - + 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. - + In certain situations it is not sufficient to merely generate the entry and exit points of the segment into/out of region 5, as \ref getTraverse provides. It may happen that a single segment, in addition to traversing region 5, skips another region outside of region 5, which makes it necessary to add an optimized corner point there (very similar to the job \ref getOptimizedCornerPoints does for segments that are completely in outside regions and don't traverse 5). - + As an example, consider a segment going from region 1 to region 6, traversing the lower left corner of region 5. In this configuration, the segment additionally crosses the border between region 1 and 2 before entering region 5. This makes it necessary to add an additional point in the top left corner, before adding the optimized traverse points. So in this case, the output parameter \a beforeTraverse will contain the top left corner point, and \a afterTraverse will be empty. - + In some cases, such as when going from region 1 to 9, it may even be necessary to add additional 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 keyMin, double valueMax, double keyMax, double valueMin, QVector &beforeTraverse, QVector &afterTraverse) const { - switch (prevRegion) - { - case 1: - { - switch (currentRegion) - { - 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; + switch (prevRegion) { + case 1: { + switch (currentRegion) { + 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; + } + case 2: { + switch (currentRegion) { + case 7: { + afterTraverse << coordsToPixels(keyMax, valueMax); + break; + } + case 9: { + afterTraverse << coordsToPixels(keyMax, valueMin); + break; + } + } + break; + } + case 3: { + switch (currentRegion) { + 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; + } + case 4: { + switch (currentRegion) { + case 3: { + afterTraverse << coordsToPixels(keyMin, valueMin); + break; + } + case 9: { + afterTraverse << coordsToPixels(keyMax, valueMin); + break; + } + } + break; + } + case 5: { + break; // shouldn't happen because this method only handles full traverses + } + case 6: { + switch (currentRegion) { + case 1: { + afterTraverse << coordsToPixels(keyMin, valueMax); + break; + } + case 7: { + afterTraverse << coordsToPixels(keyMax, valueMax); + break; + } + } + break; + } + case 7: { + switch (currentRegion) { + 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; + } + case 8: { + switch (currentRegion) { + case 1: { + afterTraverse << coordsToPixels(keyMin, valueMax); + break; + } + case 3: { + afterTraverse << coordsToPixels(keyMin, valueMin); + break; + } + } + break; + } + case 9: { + switch (currentRegion) { + 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; + } } - case 2: - { - switch (currentRegion) - { - case 7: { afterTraverse << coordsToPixels(keyMax, valueMax); break; } - case 9: { afterTraverse << coordsToPixels(keyMax, valueMin); break; } - } - break; - } - case 3: - { - switch (currentRegion) - { - 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; - } - case 4: - { - switch (currentRegion) - { - case 3: { afterTraverse << coordsToPixels(keyMin, valueMin); break; } - case 9: { afterTraverse << coordsToPixels(keyMax, valueMin); break; } - } - break; - } - case 5: { break; } // shouldn't happen because this method only handles full traverses - case 6: - { - switch (currentRegion) - { - case 1: { afterTraverse << coordsToPixels(keyMin, valueMax); break; } - case 7: { afterTraverse << coordsToPixels(keyMax, valueMax); break; } - } - break; - } - case 7: - { - switch (currentRegion) - { - 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; - } - case 8: - { - switch (currentRegion) - { - case 1: { afterTraverse << coordsToPixels(keyMin, valueMax); break; } - case 3: { afterTraverse << coordsToPixels(keyMin, valueMin); break; } - } - break; - } - case 9: - { - switch (currentRegion) - { - 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; - } - } } /*! \internal - + 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. 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, QCPCurveDataContainer::const_iterator &closestData) const { - closestData = mDataContainer->constEnd(); - if (mDataContainer->isEmpty()) - return -1.0; - if (mLineStyle == lsNone && mScatterStyle.isNone()) - return -1.0; - - if (mDataContainer->size() == 1) - { - QPointF dataPoint = coordsToPixels(mDataContainer->constBegin()->key, mDataContainer->constBegin()->value); - closestData = mDataContainer->constBegin(); - return QCPVector2D(dataPoint-pixelPoint).length(); - } - - // calculate minimum distances to curve data points and find closestData iterator: - double minDistSqr = (std::numeric_limits::max)(); - // 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) - { - const double currentDistSqr = QCPVector2D(coordsToPixels(it->key, it->value)-pixelPoint).lengthSquared(); - if (currentDistSqr < minDistSqr) - { - minDistSqr = currentDistSqr; - closestData = it; + closestData = mDataContainer->constEnd(); + if (mDataContainer->isEmpty()) { + return -1.0; } - } - - // 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; isize() == 1) { + QPointF dataPoint = coordsToPixels(mDataContainer->constBegin()->key, mDataContainer->constBegin()->value); + closestData = mDataContainer->constBegin(); + return QCPVector2D(dataPoint - pixelPoint).length(); + } + + // calculate minimum distances to curve data points and find closestData iterator: + double minDistSqr = (std::numeric_limits::max)(); + // 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) { + const double currentDistSqr = QCPVector2D(coordsToPixels(it->key, it->value) - pixelPoint).lengthSquared(); + if (currentDistSqr < minDistSqr) { + minDistSqr = currentDistSqr; + closestData = it; + } + } + + // 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; i < lines.size() - 1; ++i) { + double currentDistSqr = QCPVector2D(pixelPoint).distanceSquaredToLine(lines.at(i), lines.at(i + 1)); + if (currentDistSqr < minDistSqr) { + minDistSqr = currentDistSqr; + } + } + } + + return qSqrt(minDistSqr); } /* end of 'src/plottables/plottable-curve.cpp' */ @@ -23168,34 +23477,34 @@ double QCPCurve::pointDistance(const QPointF &pixelPoint, QCPCurveDataContainer: /*! \class QCPBarsGroup \brief Groups multiple QCPBars together so they appear side by side - + \image html QCPBarsGroup.png - + When showing multiple QCPBars in one plot which have bars at identical keys, it may be desirable to have them appearing next to each other at each key. This is what adding the respective QCPBars plottables to a QCPBarsGroup achieves. (An alternative approach is to stack them on top of each other, see \ref QCPBars::moveAbove.) - + \section qcpbarsgroup-usage Usage - + To add a QCPBars plottable to the group, create a new group and then add the respective bars intances: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpbarsgroup-creation Alternatively to appending to the group like shown above, you can also set the group on the QCPBars plottable via \ref QCPBars::setBarsGroup. - + The spacing between the bars can be configured via \ref setSpacingType and \ref setSpacing. The bars in this group appear in the plot in the order they were appended. To insert a bars plottable at a certain index position, or to reposition a bars plottable which is already in the group, use \ref insert. - + To remove specific bars from the group, use either \ref remove or call \ref QCPBars::setBarsGroup "QCPBars::setBarsGroup(0)" on the respective bars plottable. - + To clear the entire group, call \ref clear, or simply delete the group. - + \section qcpbarsgroup-example Example - + The image above is generated with the following code: \snippet documentation/doc-image-generator/mainwindow.cpp qcpbarsgroup-example */ @@ -23203,29 +23512,29 @@ double QCPCurve::pointDistance(const QPointF &pixelPoint, QCPCurveDataContainer: /* start of documentation of inline functions */ /*! \fn QList QCPBarsGroup::bars() const - + Returns all bars currently in this group. - + \see bars(int index) */ /*! \fn int QCPBarsGroup::size() const - + Returns the number of QCPBars plottables that are part of this group. - + */ /*! \fn bool QCPBarsGroup::isEmpty() const - + Returns whether this bars group is empty. - + \see size */ /*! \fn bool QCPBarsGroup::contains(QCPBars *bars) - + Returns whether the specified \a bars plottable is part of this group. - + */ /* end of documentation of inline functions */ @@ -23234,28 +23543,28 @@ double QCPCurve::pointDistance(const QPointF &pixelPoint, QCPCurveDataContainer: Constructs a new bars group for the specified QCustomPlot instance. */ QCPBarsGroup::QCPBarsGroup(QCustomPlot *parentPlot) : - QObject(parentPlot), - mParentPlot(parentPlot), - mSpacingType(stAbsolute), - mSpacing(4) + QObject(parentPlot), + mParentPlot(parentPlot), + mSpacingType(stAbsolute), + mSpacing(4) { } QCPBarsGroup::~QCPBarsGroup() { - clear(); + clear(); } /*! Sets how the spacing between adjacent bars is interpreted. See \ref SpacingType. - + The actual spacing can then be specified with \ref setSpacing. \see setSpacing */ void QCPBarsGroup::setSpacingType(SpacingType spacingType) { - mSpacingType = spacingType; + mSpacingType = spacingType; } /*! @@ -23266,7 +23575,7 @@ void QCPBarsGroup::setSpacingType(SpacingType spacingType) */ void QCPBarsGroup::setSpacing(double spacing) { - mSpacing = spacing; + mSpacing = spacing; } /*! @@ -23277,14 +23586,12 @@ void QCPBarsGroup::setSpacing(double spacing) */ QCPBars *QCPBarsGroup::bars(int index) const { - if (index >= 0 && index < mBars.size()) - { - return mBars.at(index); - } else - { - qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; - return 0; - } + if (index >= 0 && index < mBars.size()) { + return mBars.at(index); + } else { + qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; + return 0; + } } /*! @@ -23294,8 +23601,9 @@ QCPBars *QCPBarsGroup::bars(int index) const */ void QCPBarsGroup::clear() { - foreach (QCPBars *bars, mBars) // since foreach takes a copy, removing bars in the loop is okay - bars->setBarsGroup(0); // removes itself via removeBars + foreach (QCPBars *bars, mBars) { // since foreach takes a copy, removing bars in the loop is okay + bars->setBarsGroup(0); // removes itself via removeBars + } } /*! @@ -23306,22 +23614,22 @@ void QCPBarsGroup::clear() */ void QCPBarsGroup::append(QCPBars *bars) { - if (!bars) - { - qDebug() << Q_FUNC_INFO << "bars is 0"; - return; - } - - if (!mBars.contains(bars)) - bars->setBarsGroup(this); - else - qDebug() << Q_FUNC_INFO << "bars plottable is already in this bars group:" << reinterpret_cast(bars); + if (!bars) { + qDebug() << Q_FUNC_INFO << "bars is 0"; + return; + } + + if (!mBars.contains(bars)) { + bars->setBarsGroup(this); + } else { + qDebug() << Q_FUNC_INFO << "bars plottable is already in this bars group:" << reinterpret_cast(bars); + } } /*! Inserts the specified \a bars plottable into this group at the specified index position \a i. This gives you full control over the ordering of the bars. - + \a bars may already be part of this group. In that case, \a bars is just moved to the new index position. @@ -23329,130 +23637,127 @@ void QCPBarsGroup::append(QCPBars *bars) */ void QCPBarsGroup::insert(int i, QCPBars *bars) { - if (!bars) - { - qDebug() << Q_FUNC_INFO << "bars is 0"; - return; - } - - // first append to bars list normally: - if (!mBars.contains(bars)) - bars->setBarsGroup(this); - // then move to according position: - mBars.move(mBars.indexOf(bars), qBound(0, i, mBars.size()-1)); + if (!bars) { + qDebug() << Q_FUNC_INFO << "bars is 0"; + return; + } + + // first append to bars list normally: + if (!mBars.contains(bars)) { + bars->setBarsGroup(this); + } + // then move to according position: + mBars.move(mBars.indexOf(bars), qBound(0, i, mBars.size() - 1)); } /*! Removes the specified \a bars plottable from this group. - + \see contains, clear */ void QCPBarsGroup::remove(QCPBars *bars) { - if (!bars) - { - qDebug() << Q_FUNC_INFO << "bars is 0"; - return; - } - - if (mBars.contains(bars)) - bars->setBarsGroup(0); - else - qDebug() << Q_FUNC_INFO << "bars plottable is not in this bars group:" << reinterpret_cast(bars); + if (!bars) { + qDebug() << Q_FUNC_INFO << "bars is 0"; + return; + } + + if (mBars.contains(bars)) { + bars->setBarsGroup(0); + } else { + qDebug() << Q_FUNC_INFO << "bars plottable is not in this bars group:" << reinterpret_cast(bars); + } } /*! \internal - + Adds the specified \a bars to the internal mBars list of bars. This method does not change the barsGroup property on \a bars. - + \see unregisterBars */ void QCPBarsGroup::registerBars(QCPBars *bars) { - if (!mBars.contains(bars)) - mBars.append(bars); + if (!mBars.contains(bars)) { + mBars.append(bars); + } } /*! \internal - + Removes the specified \a bars from the internal mBars list of bars. This method does not change the barsGroup property on \a bars. - + \see registerBars */ void QCPBarsGroup::unregisterBars(QCPBars *bars) { - mBars.removeOne(bars); + mBars.removeOne(bars); } /*! \internal - + Returns the pixel offset in the key dimension the specified \a bars plottable should have at the given key coordinate \a keyCoord. The offset is relative to the pixel position of the key coordinate \a keyCoord. */ double QCPBarsGroup::keyPixelOffset(const QCPBars *bars, double keyCoord) { - // find list of all base bars in case some mBars are stacked: - QList baseBars; - foreach (const QCPBars *b, mBars) - { - while (b->barBelow()) - b = b->barBelow(); - if (!baseBars.contains(b)) - baseBars.append(b); - } - // find base bar this "bars" is stacked on: - const QCPBars *thisBase = bars; - while (thisBase->barBelow()) - thisBase = thisBase->barBelow(); - - // determine key pixel offset of this base bars considering all other base bars in this barsgroup: - double result = 0; - int index = baseBars.indexOf(thisBase); - if (index >= 0) - { - if (baseBars.size() % 2 == 1 && index == (baseBars.size()-1)/2) // is center bar (int division on purpose) - { - return result; - } 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 + (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+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; i != index; i += dir) // 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; - // correct sign of result depending on orientation and direction of key axis: - result *= dir*thisBase->keyAxis()->pixelOrientation(); + // find list of all base bars in case some mBars are stacked: + QList baseBars; + foreach (const QCPBars *b, mBars) { + while (b->barBelow()) { + b = b->barBelow(); + } + if (!baseBars.contains(b)) { + baseBars.append(b); + } } - } - return result; + // find base bar this "bars" is stacked on: + const QCPBars *thisBase = bars; + while (thisBase->barBelow()) { + thisBase = thisBase->barBelow(); + } + + // determine key pixel offset of this base bars considering all other base bars in this barsgroup: + double result = 0; + int index = baseBars.indexOf(thisBase); + if (index >= 0) { + if (baseBars.size() % 2 == 1 && index == (baseBars.size() - 1) / 2) { // is center bar (int division on purpose) + return result; + } 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 + (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 + 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; i != index; i += dir) { // 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; + // correct sign of result depending on orientation and direction of key axis: + result *= dir * thisBase->keyAxis()->pixelOrientation(); + } + } + return result; } /*! \internal - + Returns the spacing in pixels which is between this \a bars and the following one, both at the 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 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 @@ -23460,26 +23765,23 @@ double QCPBarsGroup::keyPixelOffset(const QCPBars *bars, double keyCoord) */ double QCPBarsGroup::getPixelSpacing(const QCPBars *bars, double keyCoord) { - switch (mSpacingType) - { - case stAbsolute: - { - return mSpacing; + switch (mSpacingType) { + case stAbsolute: { + return mSpacing; + } + case stAxisRectRatio: { + if (bars->keyAxis()->orientation() == Qt::Horizontal) { + return bars->keyAxis()->axisRect()->width() * mSpacing; + } else { + return bars->keyAxis()->axisRect()->height() * mSpacing; + } + } + case stPlotCoords: { + double keyPixel = bars->keyAxis()->coordToPixel(keyCoord); + return qAbs(bars->keyAxis()->coordToPixel(keyCoord + mSpacing) - keyPixel); + } } - case stAxisRectRatio: - { - if (bars->keyAxis()->orientation() == Qt::Horizontal) - return bars->keyAxis()->axisRect()->width()*mSpacing; - else - return bars->keyAxis()->axisRect()->height()*mSpacing; - } - case stPlotCoords: - { - double keyPixel = bars->keyAxis()->coordToPixel(keyCoord); - return qAbs(bars->keyAxis()->coordToPixel(keyCoord+mSpacing)-keyPixel); - } - } - return 0; + return 0; } @@ -23489,65 +23791,65 @@ double QCPBarsGroup::getPixelSpacing(const QCPBars *bars, double keyCoord) /*! \class QCPBarsData \brief Holds the data of one single data point (one bar) for QCPBars. - + The stored data is: \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) - + 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. */ @@ -23558,8 +23860,8 @@ double QCPBarsGroup::getPixelSpacing(const QCPBars *bars, double keyCoord) Constructs a bar data point with key and value set to zero. */ QCPBarsData::QCPBarsData() : - key(0), - value(0) + key(0), + value(0) { } @@ -23567,8 +23869,8 @@ QCPBarsData::QCPBarsData() : Constructs a bar data point with the specified \a key and \a value. */ QCPBarsData::QCPBarsData(double key, double value) : - key(key), - value(value) + key(key), + value(value) { } @@ -23581,29 +23883,29 @@ QCPBarsData::QCPBarsData(double key, double value) : \brief A plottable representing a bar chart in a plot. \image html QCPBars.png - + To plot data, assign it with the \ref setData or \ref addData functions. - + \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. - + Bar charts are stackable. This means, two QCPBars plottables can be placed on top of each other (see \ref QCPBars::moveAbove). So when two bars are at the same key position, they will appear stacked. - + If you would like to group multiple QCPBars plottables together so they appear side by side as shown below, use QCPBarsGroup. - + \image html QCPBarsGroup.png - + \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::removePlottable, etc.) - + Usually, you first create an instance: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpbars-creation-1 which registers it with the QCustomPlot instance of the passed axes. Note that this QCustomPlot instance takes @@ -23615,7 +23917,7 @@ QCPBarsData::QCPBarsData(double key, double value) : /* 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. @@ -23624,14 +23926,14 @@ QCPBarsData::QCPBarsData(double key, double value) : /*! \fn QCPBars *QCPBars::barBelow() const Returns the bars plottable that is directly below this bars plottable. If there is no such plottable, returns 0. - + \see barAbove, moveBelow, moveAbove */ /*! \fn QCPBars *QCPBars::barAbove() const Returns the bars plottable that is directly above this bars plottable. If there is no such plottable, returns 0. - + \see barBelow, moveBelow, moveAbove */ @@ -23642,69 +23944,70 @@ QCPBarsData::QCPBarsData(double key, double 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 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) : - QCPAbstractPlottable1D(keyAxis, valueAxis), - mWidth(0.75), - mWidthType(wtPlotCoords), - mBarsGroup(0), - mBaseValue(0), - mStackingGap(0) + QCPAbstractPlottable1D(keyAxis, valueAxis), + mWidth(0.75), + mWidthType(wtPlotCoords), + mBarsGroup(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); - mSelectionDecorator->setBrush(QBrush(QColor(160, 160, 255))); + // 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); + mSelectionDecorator->setBrush(QBrush(QColor(160, 160, 255))); } QCPBars::~QCPBars() { - setBarsGroup(0); - if (mBarBelow || mBarAbove) - connectBars(mBarBelow.data(), mBarAbove.data()); // take this bar out of any stacking + setBarsGroup(0); + if (mBarBelow || mBarAbove) { + connectBars(mBarBelow.data(), mBarAbove.data()); // take this bar out of any stacking + } } /*! \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; + 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); + mDataContainer->clear(); + addData(keys, values, alreadySorted); } /*! @@ -23715,37 +24018,39 @@ void QCPBars::setData(const QVector &keys, const QVector &values */ void QCPBars::setWidth(double width) { - mWidth = width; + mWidth = width; } /*! Sets how the width of the 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 QCPBars::setWidthType(QCPBars::WidthType widthType) { - mWidthType = widthType; + mWidthType = widthType; } /*! Sets to which QCPBarsGroup this QCPBars instance belongs to. Alternatively, you can also use \ref QCPBarsGroup::append. - + To remove this QCPBars from any group, set \a barsGroup to 0. */ void QCPBars::setBarsGroup(QCPBarsGroup *barsGroup) { - // deregister at old group: - if (mBarsGroup) - mBarsGroup->unregisterBars(this); - mBarsGroup = barsGroup; - // register at new group: - if (mBarsGroup) - mBarsGroup->registerBars(this); + // deregister at old group: + if (mBarsGroup) { + mBarsGroup->unregisterBars(this); + } + mBarsGroup = barsGroup; + // register at new group: + if (mBarsGroup) { + mBarsGroup->registerBars(this); + } } /*! @@ -23755,14 +24060,14 @@ void QCPBars::setBarsGroup(QCPBarsGroup *barsGroup) the base value is given by their individual value data. For example, if the base value is set to 1, a bar with data value 2 will have its lowest point at value coordinate 1 and highest point at 3. - + For stacked bars, only the base value of the bottom-most QCPBars has meaning. - + The default base value is 0. */ void QCPBars::setBaseValue(double baseValue) { - mBaseValue = baseValue; + mBaseValue = baseValue; } /*! @@ -23772,115 +24077,117 @@ void QCPBars::setBaseValue(double baseValue) */ void QCPBars::setStackingGap(double pixels) { - mStackingGap = pixels; + mStackingGap = pixels; } /*! \overload - + 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::addData(const QVector &keys, const QVector &values, bool alreadySorted) { - 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 + 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 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)); + mDataContainer->add(QCPBarsData(key, value)); } /*! Moves this bars plottable below \a bars. In other words, the bars of this plottable will appear below the bars of \a bars. The move target \a bars must use the same key and value axis as this 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 is already between two other bars, the two other bars will be stacked on top of each other after the operation. - + To remove this bars plottable from any stacking, set \a bars to 0. - + \see moveBelow, barAbove, barBelow */ void QCPBars::moveBelow(QCPBars *bars) { - if (bars == this) return; - if (bars && (bars->keyAxis() != mKeyAxis.data() || bars->valueAxis() != mValueAxis.data())) - { - qDebug() << Q_FUNC_INFO << "passed QCPBars* doesn't have same key and value axis as this QCPBars"; - return; - } - // remove from stacking: - connectBars(mBarBelow.data(), mBarAbove.data()); // Note: also works if one (or both) of them is 0 - // if new bar given, insert this bar below it: - if (bars) - { - if (bars->mBarBelow) - connectBars(bars->mBarBelow.data(), this); - connectBars(this, bars); - } + if (bars == this) { + return; + } + if (bars && (bars->keyAxis() != mKeyAxis.data() || bars->valueAxis() != mValueAxis.data())) { + qDebug() << Q_FUNC_INFO << "passed QCPBars* doesn't have same key and value axis as this QCPBars"; + return; + } + // remove from stacking: + connectBars(mBarBelow.data(), mBarAbove.data()); // Note: also works if one (or both) of them is 0 + // if new bar given, insert this bar below it: + if (bars) { + if (bars->mBarBelow) { + connectBars(bars->mBarBelow.data(), this); + } + connectBars(this, bars); + } } /*! Moves this bars plottable above \a bars. In other words, the bars of this plottable will appear above the bars of \a bars. The move target \a bars must use the same key and value axis as this plottable. - + Inserting into and removing from existing bar stacking is handled gracefully. If \a bars already 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. - + To remove this bars plottable from any stacking, set \a bars to 0. - + \see moveBelow, barBelow, barAbove */ void QCPBars::moveAbove(QCPBars *bars) { - if (bars == this) return; - if (bars && (bars->keyAxis() != mKeyAxis.data() || bars->valueAxis() != mValueAxis.data())) - { - qDebug() << Q_FUNC_INFO << "passed QCPBars* doesn't have same key and value axis as this QCPBars"; - return; - } - // remove from stacking: - connectBars(mBarBelow.data(), mBarAbove.data()); // Note: also works if one (or both) of them is 0 - // if new bar given, insert this bar above it: - if (bars) - { - if (bars->mBarAbove) - connectBars(this, bars->mBarAbove.data()); - connectBars(bars, this); - } + if (bars == this) { + return; + } + if (bars && (bars->keyAxis() != mKeyAxis.data() || bars->valueAxis() != mValueAxis.data())) { + qDebug() << Q_FUNC_INFO << "passed QCPBars* doesn't have same key and value axis as this QCPBars"; + return; + } + // remove from stacking: + connectBars(mBarBelow.data(), mBarAbove.data()); // Note: also works if one (or both) of them is 0 + // if new bar given, insert this bar above it: + if (bars) { + if (bars->mBarAbove) { + connectBars(this, bars->mBarAbove.data()); + } + connectBars(bars, this); + } } /*! @@ -23888,22 +24195,24 @@ void QCPBars::moveAbove(QCPBars *bars) */ QCPDataSelection QCPBars::selectTestRect(const QRectF &rect, bool onlySelectable) const { - QCPDataSelection result; - if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty()) + QCPDataSelection result; + if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty()) { + return result; + } + if (!mKeyAxis || !mValueAxis) { + return result; + } + + QCPBarsDataContainer::const_iterator visibleBegin, visibleEnd; + getVisibleDataBounds(visibleBegin, visibleEnd); + + for (QCPBarsDataContainer::const_iterator it = visibleBegin; it != visibleEnd; ++it) { + if (rect.intersects(getBarRect(it->key, it->value))) { + result.addDataRange(QCPDataRange(it - mDataContainer->constBegin(), it - mDataContainer->constBegin() + 1), false); + } + } + result.simplify(); return result; - if (!mKeyAxis || !mValueAxis) - return result; - - QCPBarsDataContainer::const_iterator visibleBegin, visibleEnd; - getVisibleDataBounds(visibleBegin, visibleEnd); - - for (QCPBarsDataContainer::const_iterator it=visibleBegin; it!=visibleEnd; ++it) - { - if (rect.intersects(getBarRect(it->key, it->value))) - result.addDataRange(QCPDataRange(it-mDataContainer->constBegin(), it-mDataContainer->constBegin()+1), false); - } - result.simplify(); - return result; } /*! @@ -23911,424 +24220,431 @@ QCPDataSelection QCPBars::selectTestRect(const QRectF &rect, bool onlySelectable If \a details is not 0, it will be set to a \ref QCPDataSelection, describing the closest data point to \a pos. - + \seebaseclassmethod \ref QCPAbstractPlottable::selectTest */ double QCPBars::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { - Q_UNUSED(details) - if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty()) - return -1; - if (!mKeyAxis || !mValueAxis) - return -1; - - if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint())) - { - // get visible data range: - QCPBarsDataContainer::const_iterator visibleBegin, visibleEnd; - getVisibleDataBounds(visibleBegin, visibleEnd); - for (QCPBarsDataContainer::const_iterator it=visibleBegin; it!=visibleEnd; ++it) - { - 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; - } + Q_UNUSED(details) + if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty()) { + return -1; } - } - return -1; + if (!mKeyAxis || !mValueAxis) { + return -1; + } + + if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint())) { + // get visible data range: + QCPBarsDataContainer::const_iterator visibleBegin, visibleEnd; + getVisibleDataBounds(visibleBegin, visibleEnd); + for (QCPBarsDataContainer::const_iterator it = visibleBegin; it != visibleEnd; ++it) { + 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; + /* 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; - } + // 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); } - } - - foundRange = true; // return true because bar charts always have the 0-line visible - return range; + 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(); - } + 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 (mDataContainer->isEmpty()) return; - - 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->key, it->value)) - qDebug() << Q_FUNC_INFO << "Data point at" << it->key << "of drawn range invalid." << "Plottable name:" << name(); -#endif - // draw bar: - if (isSelectedSegment && mSelectionDecorator) - { - mSelectionDecorator->applyBrush(painter); - mSelectionDecorator->applyPen(painter); - } else - { - painter->setBrush(mBrush); - painter->setPen(mPen); - } - applyDefaultAntialiasingHint(painter); - painter->drawPolygon(getBarRect(it->key, it->value)); + if (!mKeyAxis || !mValueAxis) { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + return; + } + if (mDataContainer->isEmpty()) { + return; + } + + 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 < allSegments.size(); ++i) { + bool isSelectedSegment = 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->key, it->value)) { + qDebug() << Q_FUNC_INFO << "Data point at" << it->key << "of drawn range invalid." << "Plottable name:" << name(); + } +#endif + // draw bar: + if (isSelectedSegment && mSelectionDecorator) { + mSelectionDecorator->applyBrush(painter); + mSelectionDecorator->applyPen(painter); + } else { + painter->setBrush(mBrush); + painter->setPen(mPen); + } + applyDefaultAntialiasingHint(painter); + 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()); } - } - - // 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 QCPBars::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const { - // draw filled rect: - applyDefaultAntialiasingHint(painter); - painter->setBrush(mBrush); - painter->setPen(mPen); - QRectF r = QRectF(0, 0, rect.width()*0.67, rect.height()*0.67); - r.moveCenter(rect.center()); - painter->drawRect(r); + // draw filled rect: + applyDefaultAntialiasingHint(painter); + painter->setBrush(mBrush); + painter->setPen(mPen); + QRectF r = QRectF(0, 0, rect.width() * 0.67, rect.height() * 0.67); + r.moveCenter(rect.center()); + painter->drawRect(r); } /*! \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 QCPBars::getVisibleDataBounds(QCPBarsDataContainer::const_iterator &begin, QCPBarsDataContainer::const_iterator &end) const { - if (!mKeyAxis) - { - 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 - 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 begin to find lower bar that actually is completely outside visible pixel range: - QCPBarsDataContainer::const_iterator it = begin; - while (it != mDataContainer->constBegin()) - { - --it; - const QRectF barRect = getBarRect(it->key, it->value); - if (mKeyAxis.data()->orientation() == Qt::Horizontal) - isVisible = ((!mKeyAxis.data()->rangeReversed() && barRect.right() >= lowerPixelBound) || (mKeyAxis.data()->rangeReversed() && barRect.left() <= lowerPixelBound)); - else // keyaxis is vertical - isVisible = ((!mKeyAxis.data()->rangeReversed() && barRect.top() <= lowerPixelBound) || (mKeyAxis.data()->rangeReversed() && barRect.bottom() >= lowerPixelBound)); - if (isVisible) - begin = it; - else - break; - } - // walk right from ubound to find upper bar that actually is completely outside visible pixel range: - it = end; - while (it != mDataContainer->constEnd()) - { - const QRectF barRect = getBarRect(it->key, it->value); - if (mKeyAxis.data()->orientation() == Qt::Horizontal) - isVisible = ((!mKeyAxis.data()->rangeReversed() && barRect.left() <= upperPixelBound) || (mKeyAxis.data()->rangeReversed() && barRect.right() >= upperPixelBound)); - else // keyaxis is vertical - isVisible = ((!mKeyAxis.data()->rangeReversed() && barRect.bottom() >= upperPixelBound) || (mKeyAxis.data()->rangeReversed() && barRect.top() <= upperPixelBound)); - if (isVisible) - end = it+1; - else - break; - ++it; - } + if (!mKeyAxis) { + 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 + 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 begin to find lower bar that actually is completely outside visible pixel range: + QCPBarsDataContainer::const_iterator it = begin; + while (it != mDataContainer->constBegin()) { + --it; + const QRectF barRect = getBarRect(it->key, it->value); + if (mKeyAxis.data()->orientation() == Qt::Horizontal) { + isVisible = ((!mKeyAxis.data()->rangeReversed() && barRect.right() >= lowerPixelBound) || (mKeyAxis.data()->rangeReversed() && barRect.left() <= lowerPixelBound)); + } else { // keyaxis is vertical + isVisible = ((!mKeyAxis.data()->rangeReversed() && barRect.top() <= lowerPixelBound) || (mKeyAxis.data()->rangeReversed() && barRect.bottom() >= lowerPixelBound)); + } + if (isVisible) { + begin = it; + } else { + break; + } + } + // walk right from ubound to find upper bar that actually is completely outside visible pixel range: + it = end; + while (it != mDataContainer->constEnd()) { + const QRectF barRect = getBarRect(it->key, it->value); + if (mKeyAxis.data()->orientation() == Qt::Horizontal) { + isVisible = ((!mKeyAxis.data()->rangeReversed() && barRect.left() <= upperPixelBound) || (mKeyAxis.data()->rangeReversed() && barRect.right() >= upperPixelBound)); + } else { // keyaxis is vertical + isVisible = ((!mKeyAxis.data()->rangeReversed() && barRect.bottom() >= upperPixelBound) || (mKeyAxis.data()->rangeReversed() && barRect.top() <= upperPixelBound)); + } + if (isVisible) { + end = it + 1; + } else { + break; + } + ++it; + } } /*! \internal - + 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. */ 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 QRectF(); } - - double lowerPixelWidth, upperPixelWidth; - getPixelWidth(key, lowerPixelWidth, upperPixelWidth); - double base = getStackedBaseValue(key, value >= 0); - double basePixel = valueAxis->coordToPixel(base); - double valuePixel = valueAxis->coordToPixel(base+value); - 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) - { - return QRectF(QPointF(keyPixel+lowerPixelWidth, valuePixel), QPointF(keyPixel+upperPixelWidth, basePixel+bottomOffset)).normalized(); - } else - { - return QRectF(QPointF(basePixel+bottomOffset, keyPixel+lowerPixelWidth), QPointF(valuePixel, keyPixel+upperPixelWidth)).normalized(); - } + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + return QRectF(); + } + + double lowerPixelWidth, upperPixelWidth; + getPixelWidth(key, lowerPixelWidth, upperPixelWidth); + double base = getStackedBaseValue(key, value >= 0); + double basePixel = valueAxis->coordToPixel(base); + double valuePixel = valueAxis->coordToPixel(base + value); + 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) { + return QRectF(QPointF(keyPixel + lowerPixelWidth, valuePixel), QPointF(keyPixel + upperPixelWidth, basePixel + bottomOffset)).normalized(); + } else { + return QRectF(QPointF(basePixel + bottomOffset, keyPixel + lowerPixelWidth), QPointF(valuePixel, keyPixel + upperPixelWidth)).normalized(); + } } /*! \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). - + The output parameters \a lower and \a upper return the number of pixels the bar extends to lower and higher keys, relative to the \a key coordinate (so with a non-reversed horizontal axis, \a lower is negative and \a upper positive). */ void QCPBars::getPixelWidth(double key, double &lower, double &upper) const { - lower = 0; - upper = 0; - switch (mWidthType) - { - case wtAbsolute: - { - upper = mWidth*0.5*mKeyAxis.data()->pixelOrientation(); - lower = -upper; - break; + lower = 0; + upper = 0; + switch (mWidthType) { + case wtAbsolute: { + upper = mWidth * 0.5 * mKeyAxis.data()->pixelOrientation(); + lower = -upper; + break; + } + case wtAxisRectRatio: { + if (mKeyAxis && mKeyAxis.data()->axisRect()) { + if (mKeyAxis.data()->orientation() == Qt::Horizontal) { + upper = mKeyAxis.data()->axisRect()->width() * mWidth * 0.5 * mKeyAxis.data()->pixelOrientation(); + } else { + upper = mKeyAxis.data()->axisRect()->height() * mWidth * 0.5 * mKeyAxis.data()->pixelOrientation(); + } + lower = -upper; + } else { + qDebug() << Q_FUNC_INFO << "No key axis or axis rect defined"; + } + break; + } + case wtPlotCoords: { + if (mKeyAxis) { + double keyPixel = mKeyAxis.data()->coordToPixel(key); + upper = mKeyAxis.data()->coordToPixel(key + mWidth * 0.5) - keyPixel; + lower = mKeyAxis.data()->coordToPixel(key - mWidth * 0.5) - keyPixel; + // no need to qSwap(lower, higher) when range reversed, because higher/lower are gained by + // coordinate transform which includes range direction + } else { + qDebug() << Q_FUNC_INFO << "No key axis defined"; + } + break; + } } - case wtAxisRectRatio: - { - if (mKeyAxis && mKeyAxis.data()->axisRect()) - { - if (mKeyAxis.data()->orientation() == Qt::Horizontal) - upper = mKeyAxis.data()->axisRect()->width()*mWidth*0.5*mKeyAxis.data()->pixelOrientation(); - else - upper = mKeyAxis.data()->axisRect()->height()*mWidth*0.5*mKeyAxis.data()->pixelOrientation(); - lower = -upper; - } else - qDebug() << Q_FUNC_INFO << "No key axis or axis rect defined"; - break; - } - case wtPlotCoords: - { - if (mKeyAxis) - { - double keyPixel = mKeyAxis.data()->coordToPixel(key); - upper = mKeyAxis.data()->coordToPixel(key+mWidth*0.5)-keyPixel; - lower = mKeyAxis.data()->coordToPixel(key-mWidth*0.5)-keyPixel; - // no need to qSwap(lower, higher) when range reversed, because higher/lower are gained by - // coordinate transform which includes range direction - } else - qDebug() << Q_FUNC_INFO << "No key axis defined"; - break; - } - } } /*! \internal - + This function is called to find at which value to start drawing the base of a bar at \a key, when it is stacked on top of another QCPBars (e.g. with \ref moveAbove). - + positive and negative bars are separated per stack (positive are stacked above baseValue upwards, negative are stacked below baseValue downwards). This can be indicated with \a positive. So if the bar for which we need the base value is negative, set \a positive to false. */ double QCPBars::getStackedBaseValue(double key, bool positive) const { - if (mBarBelow) - { - 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)*(sizeof(key)==4 ? 1e-6 : 1e-14); // should be safe even when changed to use float at some point - if (key == 0) - 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 (it->key > key-epsilon && it->key < key+epsilon) - { - if ((positive && it->value > max) || - (!positive && it->value < max)) - max = it->value; - } - ++it; + if (mBarBelow) { + 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) * (sizeof(key) == 4 ? 1e-6 : 1e-14); // should be safe even when changed to use float at some point + if (key == 0) { + 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 (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: + return max + mBarBelow.data()->getStackedBaseValue(key, positive); + } else { + return mBaseValue; } - // recurse down the bar-stack to find the total height: - return max + mBarBelow.data()->getStackedBaseValue(key, positive); - } else - return mBaseValue; } /*! \internal Connects \a below and \a above to each other via their mBarAbove/mBarBelow properties. The bar(s) currently above lower and below upper will become disconnected to lower/upper. - + If lower is zero, upper will be disconnected at the bottom. If upper is zero, lower will be disconnected at the top. */ void QCPBars::connectBars(QCPBars *lower, QCPBars *upper) { - if (!lower && !upper) return; - - if (!lower) // disconnect upper at bottom - { - // disconnect old bar below upper: - if (upper->mBarBelow && upper->mBarBelow.data()->mBarAbove.data() == upper) - upper->mBarBelow.data()->mBarAbove = 0; - upper->mBarBelow = 0; - } else if (!upper) // disconnect lower at top - { - // disconnect old bar above lower: - if (lower->mBarAbove && lower->mBarAbove.data()->mBarBelow.data() == lower) - lower->mBarAbove.data()->mBarBelow = 0; - lower->mBarAbove = 0; - } else // connect lower and upper - { - // disconnect old bar above lower: - if (lower->mBarAbove && lower->mBarAbove.data()->mBarBelow.data() == lower) - lower->mBarAbove.data()->mBarBelow = 0; - // disconnect old bar below upper: - if (upper->mBarBelow && upper->mBarBelow.data()->mBarAbove.data() == upper) - upper->mBarBelow.data()->mBarAbove = 0; - lower->mBarAbove = upper; - upper->mBarBelow = lower; - } + if (!lower && !upper) { + return; + } + + if (!lower) { // disconnect upper at bottom + // disconnect old bar below upper: + if (upper->mBarBelow && upper->mBarBelow.data()->mBarAbove.data() == upper) { + upper->mBarBelow.data()->mBarAbove = 0; + } + upper->mBarBelow = 0; + } else if (!upper) { // disconnect lower at top + // disconnect old bar above lower: + if (lower->mBarAbove && lower->mBarAbove.data()->mBarBelow.data() == lower) { + lower->mBarAbove.data()->mBarBelow = 0; + } + lower->mBarAbove = 0; + } else { // connect lower and upper + // disconnect old bar above lower: + if (lower->mBarAbove && lower->mBarAbove.data()->mBarBelow.data() == lower) { + lower->mBarAbove.data()->mBarBelow = 0; + } + // disconnect old bar below upper: + if (upper->mBarBelow && upper->mBarBelow.data()->mBarAbove.data() == upper) { + upper->mBarBelow.data()->mBarAbove = 0; + } + lower->mBarAbove = upper; + upper->mBarBelow = lower; + } } /* end of 'src/plottables/plottable-bars.cpp' */ @@ -24342,87 +24658,87 @@ void QCPBars::connectBars(QCPBars *lower, QCPBars *upper) /*! \class QCPStatisticalBoxData \brief Holds the data of one single data point for QCPStatisticalBox. - + 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. */ @@ -24433,12 +24749,12 @@ void QCPBars::connectBars(QCPBars *lower, QCPBars *upper) 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) + key(0), + minimum(0), + lowerQuartile(0), + median(0), + upperQuartile(0), + maximum(0) { } @@ -24447,13 +24763,13 @@ QCPStatisticalBoxData::QCPStatisticalBoxData() : 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) + key(key), + minimum(minimum), + lowerQuartile(lowerQuartile), + median(median), + upperQuartile(upperQuartile), + maximum(maximum), + outliers(outliers) { } @@ -24466,19 +24782,19 @@ QCPStatisticalBoxData::QCPStatisticalBoxData(double key, double minimum, double \brief A plottable representing a single statistical box in a plot. \image html QCPStatisticalBox.png - + 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 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 qcpstatisticalbox-appearance Changing the appearance - + 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. @@ -24490,18 +24806,18 @@ QCPStatisticalBoxData::QCPStatisticalBoxData(double key, double minimum, double 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 inside the box has its own pen, \ref setMedianPen. - + The outlier data points are drawn as normal scatter points. Their look can be controlled with \ref setOutlierStyle - + \section qcpstatisticalbox-usage Usage - + 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 which registers it with the QCustomPlot instance of the passed axes. Note that this QCustomPlot instance takes @@ -24513,7 +24829,7 @@ QCPStatisticalBoxData::QCPStatisticalBoxData(double key, double minimum, double /* 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. @@ -24526,113 +24842,113 @@ QCPStatisticalBoxData::QCPStatisticalBoxData(double key, double minimum, double 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 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) : - 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) + 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) { - setPen(QPen(Qt::black)); - setBrush(Qt::NoBrush); + setPen(QPen(Qt::black)); + setBrush(Qt::NoBrush); } /*! \overload - + Replaces the current data container with the provided \a data container. - + 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 - + 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 addData */ void QCPStatisticalBox::setData(QSharedPointer data) { - mDataContainer = data; + mDataContainer = data; } /*! \overload - + 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. - + 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 QCPStatisticalBox::setData(const QVector &keys, const QVector &minimum, const QVector &lowerQuartile, const QVector &median, const QVector &upperQuartile, const QVector &maximum, bool alreadySorted) { - mDataContainer->clear(); - addData(keys, minimum, lowerQuartile, median, upperQuartile, maximum, alreadySorted); + mDataContainer->clear(); + addData(keys, minimum, lowerQuartile, median, upperQuartile, maximum, alreadySorted); } /*! Sets the width of the boxes in key coordinates. - + \see setWhiskerWidth */ void QCPStatisticalBox::setWidth(double width) { - mWidth = width; + mWidth = width; } /*! 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 */ void QCPStatisticalBox::setWhiskerWidth(double width) { - mWhiskerWidth = width; + mWhiskerWidth = width; } /*! Sets the pen used for drawing the whisker backbone. - + 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 */ void QCPStatisticalBox::setWhiskerPen(const QPen &pen) { - mWhiskerPen = pen; + mWhiskerPen = 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. - + Whiskers are the lines which reach from the upper quartile to the maximum, and from the lower quartile to the minimum. - + \see setWhiskerPen */ void QCPStatisticalBox::setWhiskerBarPen(const QPen &pen) { - mWhiskerBarPen = pen; + mWhiskerBarPen = pen; } /*! @@ -24643,7 +24959,7 @@ void QCPStatisticalBox::setWhiskerBarPen(const QPen &pen) */ void QCPStatisticalBox::setWhiskerAntialiased(bool enabled) { - mWhiskerAntialiased = enabled; + mWhiskerAntialiased = enabled; } /*! @@ -24651,7 +24967,7 @@ void QCPStatisticalBox::setWhiskerAntialiased(bool enabled) */ void QCPStatisticalBox::setMedianPen(const QPen &pen) { - mMedianPen = pen; + mMedianPen = pen; } /*! @@ -24662,57 +24978,56 @@ void QCPStatisticalBox::setMedianPen(const QPen &pen) */ void QCPStatisticalBox::setOutlierStyle(const QCPScatterStyle &style) { - mOutlierStyle = style; + mOutlierStyle = style; } /*! \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) { - 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 + 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)); + mDataContainer->add(QCPStatisticalBoxData(key, minimum, lowerQuartile, median, upperQuartile, maximum, outliers)); } /*! @@ -24720,22 +25035,24 @@ void QCPStatisticalBox::addData(double key, double minimum, double lowerQuartile */ QCPDataSelection QCPStatisticalBox::selectTestRect(const QRectF &rect, bool onlySelectable) const { - QCPDataSelection result; - if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty()) + 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; - 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; } /*! @@ -24743,147 +25060,148 @@ QCPDataSelection QCPStatisticalBox::selectTestRect(const QRectF &rect, bool only If \a details is not 0, it will be set to a \ref QCPDataSelection, describing the closest data point to \a pos. - + \seebaseclassmethod \ref QCPAbstractPlottable::selectTest */ double QCPStatisticalBox::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { - Q_UNUSED(details) - if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty()) - return -1; - if (!mKeyAxis || !mValueAxis) - return -1; - - if (mKeyAxis->axisRect()->rect().contains(pos.toPoint())) - { - // 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; iisEmpty()) { + return -1; } - if (details) - { - int pointIndex = closestDataPoint-mDataContainer->constBegin(); - details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1))); + if (!mKeyAxis || !mValueAxis) { + return -1; } - return qSqrt(minDistSqr); - } - return -1; + + if (mKeyAxis->axisRect()->rect().contains(pos.toPoint())) { + // 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; i < whiskerBackbones.size(); ++i) { + double currentDistSqr = QCPVector2D(pos).distanceSquaredToLine(whiskerBackbones.at(i)); + if (currentDistSqr < minDistSqr) { + minDistSqr = currentDistSqr; + closestDataPoint = it; + } + } + } + } + if (details) { + int pointIndex = closestDataPoint - mDataContainer->constBegin(); + 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; + 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); + return mDataContainer->valueRange(foundRange, inSignDomain, inKeyRange); } /* inherits documentation from base class */ void QCPStatisticalBox::draw(QCPPainter *painter) { - if (mDataContainer->isEmpty()) return; - QCPAxis *keyAxis = mKeyAxis.data(); - QCPAxis *valueAxis = mValueAxis.data(); - if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } - - QCPStatisticalBoxDataContainer::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(); - 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); + if (mDataContainer->isEmpty()) { + return; + } + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + return; + } + + QCPStatisticalBoxDataContainer::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 < allSegments.size(); ++i) { + bool isSelectedSegment = 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; i < it->outliers.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); + } + } + + // draw other selection decoration that isn't just line/scatter pens and brushes: + if (mSelectionDecorator) { + mSelectionDecorator->drawDecoration(painter, selection()); } - } - - // 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 QCPStatisticalBox::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const { - // draw filled rect: - applyDefaultAntialiasingHint(painter); - painter->setPen(mPen); - painter->setBrush(mBrush); - QRectF r = QRectF(0, 0, rect.width()*0.67, rect.height()*0.67); - r.moveCenter(rect.center()); - painter->drawRect(r); + // draw filled rect: + applyDefaultAntialiasingHint(painter); + painter->setPen(mPen); + painter->setBrush(mBrush); + QRectF r = QRectF(0, 0, rect.width() * 0.67, rect.height() * 0.67); + r.moveCenter(rect.center()); + painter->drawRect(r); } /*! @@ -24896,54 +25214,54 @@ void QCPStatisticalBox::drawLegendIcon(QCPPainter *painter, const QRectF &rect) */ void QCPStatisticalBox::drawStatisticalBox(QCPPainter *painter, QCPStatisticalBoxDataContainer::const_iterator it, const QCPScatterStyle &outlierStyle) const { - // 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(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->drawLines(getWhiskerBackboneLines(it)); - painter->setPen(mWhiskerBarPen); - painter->drawLines(getWhiskerBarLines(it)); - // draw outliers: - applyScattersAntialiasingHint(painter); - outlierStyle.applyTo(painter, mPen); - for (int i=0; ioutliers.size(); ++i) - outlierStyle.drawShape(painter, coordsToPixels(it->key, it->outliers.at(i))); + // 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(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->drawLines(getWhiskerBackboneLines(it)); + painter->setPen(mWhiskerBarPen); + painter->drawLines(getWhiskerBarLines(it)); + // draw outliers: + applyScattersAntialiasingHint(painter); + outlierStyle.applyTo(painter, mPen); + for (int i = 0; i < it->outliers.size(); ++i) { + outlierStyle.drawShape(painter, coordsToPixels(it->key, it->outliers.at(i))); + } } /*! \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 { - if (!mKeyAxis) - { - 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 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 + if (!mKeyAxis) { + 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 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 } /*! \internal @@ -24955,10 +25273,10 @@ void QCPStatisticalBox::getVisibleDataBounds(QCPStatisticalBoxDataContainer::con */ QRectF QCPStatisticalBox::getQuartileBox(QCPStatisticalBoxDataContainer::const_iterator it) const { - QRectF result; - result.setTopLeft(coordsToPixels(it->key-mWidth*0.5, it->upperQuartile)); - result.setBottomRight(coordsToPixels(it->key+mWidth*0.5, it->lowerQuartile)); - return result; + 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 @@ -24971,10 +25289,10 @@ QRectF QCPStatisticalBox::getQuartileBox(QCPStatisticalBoxDataContainer::const_i */ 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; + 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 @@ -24986,10 +25304,10 @@ QVector QCPStatisticalBox::getWhiskerBackboneLines(QCPStatisticalBoxData */ 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; + 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' */ @@ -25003,25 +25321,25 @@ QVector QCPStatisticalBox::getWhiskerBarLines(QCPStatisticalBoxDataConta /*! \class QCPColorMapData \brief Holds the two-dimensional data of a QCPColorMap plottable. - + This class is a data storage for \ref QCPColorMap. It holds a two-dimensional array, which \ref QCPColorMap then displays as a 2D image in the plot, where the array values are represented by a color, depending on the value. - + The size of the array can be controlled via \ref setSize (or \ref setKeySize, \ref setValueSize). Which plot coordinates these cells correspond to can be configured with \ref setRange (or \ref setKeyRange, \ref setValueRange). - + The data cells can be accessed in two ways: They can be directly addressed by an integer index with \ref setCell. This is the fastest method. Alternatively, they can be addressed by their plot 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, @@ -25037,7 +25355,7 @@ QVector QCPStatisticalBox::getWhiskerBarLines(QCPStatisticalBoxDataConta /* start of documentation of inline functions */ /*! \fn bool QCPColorMapData::isEmpty() const - + Returns whether this instance carries no data. This is equivalent to having a size where at least one of the dimensions is 0 (see \ref setSize). */ @@ -25048,43 +25366,45 @@ QVector QCPStatisticalBox::getWhiskerBarLines(QCPStatisticalBoxDataConta Constructs a new QCPColorMapData instance. The instance has \a keySize cells in the key direction and \a valueSize cells in the value direction. These cells will be displayed by the \ref QCPColorMap at the coordinates \a keyRange and \a valueRange. - + \see setSize, setKeySize, setValueSize, setRange, setKeyRange, setValueRange */ QCPColorMapData::QCPColorMapData(int keySize, int valueSize, const QCPRange &keyRange, const QCPRange &valueRange) : - mKeySize(0), - mValueSize(0), - mKeyRange(keyRange), - mValueRange(valueRange), - mIsEmpty(true), - mData(0), - mAlpha(0), - mDataModified(true) + mKeySize(0), + mValueSize(0), + mKeyRange(keyRange), + mValueRange(valueRange), + mIsEmpty(true), + mData(0), + mAlpha(0), + mDataModified(true) { - setSize(keySize, valueSize); - fill(0); + setSize(keySize, valueSize); + fill(0); } QCPColorMapData::~QCPColorMapData() { - if (mData) - delete[] mData; - if (mAlpha) - delete[] mAlpha; + if (mData) { + delete[] mData; + } + if (mAlpha) { + delete[] mAlpha; + } } /*! Constructs a new QCPColorMapData instance copying the data and range of \a other. */ QCPColorMapData::QCPColorMapData(const QCPColorMapData &other) : - mKeySize(0), - mValueSize(0), - mIsEmpty(true), - mData(0), - mAlpha(0), - mDataModified(true) + mKeySize(0), + mValueSize(0), + mIsEmpty(true), + mData(0), + mAlpha(0), + mDataModified(true) { - *this = other; + *this = other; } /*! @@ -25093,46 +25413,49 @@ QCPColorMapData::QCPColorMapData(const QCPColorMapData &other) : */ QCPColorMapData &QCPColorMapData::operator=(const QCPColorMapData &other) { - if (&other != this) - { - 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 (!isEmpty()) - { - memcpy(mData, other.mData, sizeof(mData[0])*keySize*valueSize); - if (mAlpha) - memcpy(mAlpha, other.mAlpha, sizeof(mAlpha[0])*keySize*valueSize); + if (&other != this) { + 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 (!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; } - mDataBounds = other.mDataBounds; - mDataModified = true; - } - return *this; + return *this; } /* undocumented getter */ double QCPColorMapData::data(double key, double value) { - int keyCell = (key-mKeyRange.lower)/(mKeyRange.upper-mKeyRange.lower)*(mKeySize-1)+0.5; - int valueCell = (value-mValueRange.lower)/(mValueRange.upper-mValueRange.lower)*(mValueSize-1)+0.5; - if (keyCell >= 0 && keyCell < mKeySize && valueCell >= 0 && valueCell < mValueSize) - return mData[valueCell*mKeySize + keyCell]; - else - return 0; + int keyCell = (key - mKeyRange.lower) / (mKeyRange.upper - mKeyRange.lower) * (mKeySize - 1) + 0.5; + int valueCell = (value - mValueRange.lower) / (mValueRange.upper - mValueRange.lower) * (mValueSize - 1) + 0.5; + if (keyCell >= 0 && keyCell < mKeySize && valueCell >= 0 && valueCell < mValueSize) { + return mData[valueCell * mKeySize + keyCell]; + } else { + return 0; + } } /* undocumented getter */ double QCPColorMapData::cell(int keyIndex, int valueIndex) { - if (keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize) - return mData[valueIndex*mKeySize + keyIndex]; - else - return 0; + if (keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize) { + return mData[valueIndex * mKeySize + keyIndex]; + } else { + return 0; + } } /*! @@ -25145,10 +25468,11 @@ double QCPColorMapData::cell(int keyIndex, int valueIndex) */ 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; + if (mAlpha && keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize) { + return mAlpha[valueIndex * mKeySize + keyIndex]; + } else { + return 255; + } } /*! @@ -25157,7 +25481,7 @@ unsigned char QCPColorMapData::alpha(int keyIndex, int valueIndex) The current data is discarded and the map cells are set to 0, unless the map had already the requested size. - + Setting at least one of \a keySize or \a valueSize to zero frees the internal data array and \ref isEmpty returns true. @@ -25165,34 +25489,38 @@ unsigned char QCPColorMapData::alpha(int keyIndex, int valueIndex) */ void QCPColorMapData::setSize(int keySize, int valueSize) { - if (keySize != mKeySize || valueSize != mValueSize) - { - mKeySize = keySize; - mValueSize = valueSize; - if (mData) - delete[] mData; - mIsEmpty = mKeySize == 0 || mValueSize == 0; - if (!mIsEmpty) - { + if (keySize != mKeySize || valueSize != mValueSize) { + mKeySize = keySize; + mValueSize = valueSize; + if (mData) { + delete[] mData; + } + mIsEmpty = mKeySize == 0 || mValueSize == 0; + if (!mIsEmpty) { #ifdef __EXCEPTIONS - try { // 2D arrays get memory intensive fast. So if the allocation fails, at least output debug message + try { // 2D arrays get memory intensive fast. So if the allocation fails, at least output debug message #endif - mData = new double[mKeySize*mValueSize]; + mData = new double[mKeySize * mValueSize]; #ifdef __EXCEPTIONS - } catch (...) { mData = 0; } + } catch (...) { + mData = 0; + } #endif - if (mData) - fill(0); - else - 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; - } + if (mData) { + fill(0); + } else { + 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; + } } /*! @@ -25200,14 +25528,14 @@ void QCPColorMapData::setSize(int keySize, int valueSize) The current data is discarded and the map cells are set to 0, unless the map had already the requested size. - + Setting \a keySize to zero frees the internal data array and \ref isEmpty returns true. \see setKeyRange, setSize, setValueSize */ void QCPColorMapData::setKeySize(int keySize) { - setSize(keySize, mValueSize); + setSize(keySize, mValueSize); } /*! @@ -25215,112 +25543,115 @@ void QCPColorMapData::setKeySize(int keySize) The current data is discarded and the map cells are set to 0, unless the map had already the requested size. - + Setting \a valueSize to zero frees the internal data array and \ref isEmpty returns true. \see setValueRange, setSize, setKeySize */ void QCPColorMapData::setValueSize(int valueSize) { - setSize(mKeySize, valueSize); + setSize(mKeySize, valueSize); } /*! Sets the coordinate ranges the data shall be distributed over. This defines the rectangular area covered by the color map in plot coordinates. - + The outer cells will be centered on the range boundaries given to this function. For example, if the key size (\ref setKeySize) is 3 and \a keyRange is set to QCPRange(2, 3) there will be cells centered on the key coordinates 2, 2.5 and 3. - + \see setSize */ void QCPColorMapData::setRange(const QCPRange &keyRange, const QCPRange &valueRange) { - setKeyRange(keyRange); - setValueRange(valueRange); + setKeyRange(keyRange); + setValueRange(valueRange); } /*! Sets the coordinate range the data shall be distributed over in the key dimension. Together with the value range, This defines the rectangular area covered by the color map in plot coordinates. - + The outer cells will be centered on the range boundaries given to this function. For example, if the key size (\ref setKeySize) is 3 and \a keyRange is set to QCPRange(2, 3) there will be cells centered on the key coordinates 2, 2.5 and 3. - + \see setRange, setValueRange, setSize */ void QCPColorMapData::setKeyRange(const QCPRange &keyRange) { - mKeyRange = keyRange; + mKeyRange = keyRange; } /*! Sets the coordinate range the data shall be distributed over in the value dimension. Together with the key range, This defines the rectangular area covered by the color map in plot coordinates. - + The outer cells will be centered on the range boundaries given to this function. For example, if the value size (\ref setValueSize) is 3 and \a valueRange is set to QCPRange(2, 3) there will be cells centered on the value coordinates 2, 2.5 and 3. - + \see setRange, setKeyRange, setSize */ void QCPColorMapData::setValueRange(const QCPRange &valueRange) { - mValueRange = valueRange; + mValueRange = valueRange; } /*! Sets the data of the cell, which lies at the plot coordinates given by \a key and \a value, to \a z. - + \note The QCPColorMap always displays the data at equal key/value intervals, even if the key or value axis is set to a logarithmic scaling. If you want to use QCPColorMap with logarithmic axes, you shouldn't use the \ref QCPColorMapData::setData method as it uses a linear transformation to determine the cell index. Rather directly access the cell index with \ref QCPColorMapData::setCell. - + \see setCell, setRange */ void QCPColorMapData::setData(double key, double value, double z) { - int keyCell = (key-mKeyRange.lower)/(mKeyRange.upper-mKeyRange.lower)*(mKeySize-1)+0.5; - int valueCell = (value-mValueRange.lower)/(mValueRange.upper-mValueRange.lower)*(mValueSize-1)+0.5; - if (keyCell >= 0 && keyCell < mKeySize && valueCell >= 0 && valueCell < mValueSize) - { - mData[valueCell*mKeySize + keyCell] = z; - if (z < mDataBounds.lower) - mDataBounds.lower = z; - if (z > mDataBounds.upper) - mDataBounds.upper = z; - mDataModified = true; - } + int keyCell = (key - mKeyRange.lower) / (mKeyRange.upper - mKeyRange.lower) * (mKeySize - 1) + 0.5; + int valueCell = (value - mValueRange.lower) / (mValueRange.upper - mValueRange.lower) * (mValueSize - 1) + 0.5; + if (keyCell >= 0 && keyCell < mKeySize && valueCell >= 0 && valueCell < mValueSize) { + mData[valueCell * mKeySize + keyCell] = z; + if (z < mDataBounds.lower) { + mDataBounds.lower = z; + } + if (z > mDataBounds.upper) { + mDataBounds.upper = z; + } + mDataModified = true; + } } /*! Sets the data of the cell with indices \a keyIndex and \a valueIndex to \a z. The indices enumerate the cells starting from zero, up to the map's size-1 in the respective dimension (see \ref setSize). - + In the standard plot configuration (horizontal key axis and vertical value axis, both not range-reversed), the cell with indices (0, 0) is in the bottom left corner and the cell with indices (keySize-1, valueSize-1) is in the top right corner of the color map. - + \see setData, setSize */ void QCPColorMapData::setCell(int keyIndex, int valueIndex, double z) { - if (keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize) - { - mData[valueIndex*mKeySize + keyIndex] = z; - if (z < mDataBounds.lower) - mDataBounds.lower = z; - if (z > mDataBounds.upper) - mDataBounds.upper = z; - mDataModified = true; - } else - qDebug() << Q_FUNC_INFO << "index out of bounds:" << keyIndex << valueIndex; + if (keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize) { + mData[valueIndex * mKeySize + keyIndex] = z; + if (z < mDataBounds.lower) { + mDataBounds.lower = z; + } + if (z > mDataBounds.upper) { + mDataBounds.upper = z; + } + mDataModified = true; + } else { + qDebug() << Q_FUNC_INFO << "index out of bounds:" << keyIndex << valueIndex; + } } /*! @@ -25340,57 +25671,56 @@ void QCPColorMapData::setCell(int keyIndex, int valueIndex, double z) */ 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; + 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; } - } else - qDebug() << Q_FUNC_INFO << "index out of bounds:" << keyIndex << valueIndex; } /*! Goes through the data and updates the buffered minimum and maximum data values. - + Calling this method is only advised if you are about to call \ref QCPColorMap::rescaleDataRange and can not guarantee that the cells holding the maximum or minimum data haven't been overwritten with a smaller or larger value respectively, since the buffered maximum/minimum values have been updated the last time. Why this is the case is explained in the class description (\ref QCPColorMapData). - + Note that the method \ref QCPColorMap::rescaleDataRange provides a parameter \a recalculateDataBounds for convenience. Setting this to true will call this method for you, before doing the rescale. */ void QCPColorMapData::recalculateDataBounds() { - if (mKeySize > 0 && mValueSize > 0) - { - double minHeight = mData[0]; - double maxHeight = mData[0]; - const int dataCount = mValueSize*mKeySize; - for (int i=0; i maxHeight) - maxHeight = mData[i]; - if (mData[i] < minHeight) - minHeight = mData[i]; + if (mKeySize > 0 && mValueSize > 0) { + double minHeight = mData[0]; + double maxHeight = mData[0]; + const int dataCount = mValueSize * mKeySize; + for (int i = 0; i < dataCount; ++i) { + if (mData[i] > maxHeight) { + maxHeight = mData[i]; + } + if (mData[i] < minHeight) { + minHeight = mData[i]; + } + } + mDataBounds.lower = minHeight; + mDataBounds.upper = maxHeight; } - mDataBounds.lower = minHeight; - mDataBounds.upper = maxHeight; - } } /*! Frees the internal data memory. - + This is equivalent to calling \ref setSize "setSize(0, 0)". */ void QCPColorMapData::clear() { - setSize(0, 0); + setSize(0, 0); } /*! @@ -25398,12 +25728,11 @@ void QCPColorMapData::clear() */ void QCPColorMapData::clearAlpha() { - if (mAlpha) - { - delete[] mAlpha; - mAlpha = 0; - mDataModified = true; - } + if (mAlpha) { + delete[] mAlpha; + mAlpha = 0; + mDataModified = true; + } } /*! @@ -25411,11 +25740,12 @@ void QCPColorMapData::clearAlpha() */ void QCPColorMapData::fill(double z) { - const int dataCount = mValueSize*mKeySize; - for (int i=0; i(data); - return; - } - if (copy) - { - *mMapData = *data; - } else - { - delete mMapData; - mMapData = data; - } - mMapImageInvalidated = true; + if (mMapData == data) { + qDebug() << Q_FUNC_INFO << "The data pointer is already in (and owned by) this plottable" << reinterpret_cast(data); + return; + } + if (copy) { + *mMapData = *data; + } else { + delete mMapData; + mMapData = data; + } + mMapImageInvalidated = true; } /*! Sets the data range of this color map to \a dataRange. The data range defines which data values are mapped to the color gradient. - + To make the data range span the full range of the data set, use \ref rescaleDataRange. - + \see QCPColorScale::setDataRange */ void QCPColorMap::setDataRange(const QCPRange &dataRange) { - if (!QCPRange::validRange(dataRange)) return; - if (mDataRange.lower != dataRange.lower || mDataRange.upper != dataRange.upper) - { - if (mDataScaleType == QCPAxis::stLogarithmic) - mDataRange = dataRange.sanitizedForLogScale(); - else - mDataRange = dataRange.sanitizedForLinScale(); - mMapImageInvalidated = true; - emit dataRangeChanged(mDataRange); - } + if (!QCPRange::validRange(dataRange)) { + return; + } + if (mDataRange.lower != dataRange.lower || mDataRange.upper != dataRange.upper) { + if (mDataScaleType == QCPAxis::stLogarithmic) { + mDataRange = dataRange.sanitizedForLogScale(); + } else { + mDataRange = dataRange.sanitizedForLinScale(); + } + mMapImageInvalidated = true; + emit dataRangeChanged(mDataRange); + } } /*! Sets whether the data is correlated with the color gradient linearly or logarithmically. - + \see QCPColorScale::setDataScaleType */ void QCPColorMap::setDataScaleType(QCPAxis::ScaleType scaleType) { - if (mDataScaleType != scaleType) - { - mDataScaleType = scaleType; - mMapImageInvalidated = true; - emit dataScaleTypeChanged(mDataScaleType); - if (mDataScaleType == QCPAxis::stLogarithmic) - setDataRange(mDataRange.sanitizedForLogScale()); - } + if (mDataScaleType != scaleType) { + mDataScaleType = scaleType; + mMapImageInvalidated = true; + emit dataScaleTypeChanged(mDataScaleType); + if (mDataScaleType == QCPAxis::stLogarithmic) { + setDataRange(mDataRange.sanitizedForLogScale()); + } + } } /*! Sets the color gradient that is used to represent the data. For more details on how to create an own gradient or use one of the preset gradients, see \ref QCPColorGradient. - + The colors defined by the gradient will be used to represent data values in the currently set data range, see \ref setDataRange. Data points that are outside this data range will either be colored uniformly with the respective gradient boundary color, or the gradient will repeat, depending on \ref QCPColorGradient::setPeriodic. - + \see QCPColorScale::setGradient */ void QCPColorMap::setGradient(const QCPColorGradient &gradient) { - if (mGradient != gradient) - { - mGradient = gradient; - mMapImageInvalidated = true; - emit gradientChanged(mGradient); - } + if (mGradient != gradient) { + mGradient = gradient; + mMapImageInvalidated = true; + emit gradientChanged(mGradient); + } } /*! Sets whether the color map image shall use bicubic interpolation when displaying the color map shrinked or expanded, and not at a 1:1 pixel-to-data scale. - + \image html QCPColorMap-interpolate.png "A 10*10 color map, with interpolation and without interpolation enabled" */ void QCPColorMap::setInterpolate(bool enabled) { - mInterpolate = enabled; - mMapImageInvalidated = true; // because oversampling factors might need to change + mInterpolate = enabled; + mMapImageInvalidated = true; // because oversampling factors might need to change } /*! Sets whether the outer most data rows and columns are clipped to the specified key and value range (see \ref QCPColorMapData::setKeyRange, \ref QCPColorMapData::setValueRange). - + if \a enabled is set to false, the data points at the border of the color map are drawn with the same width and height as all other data points. Since the data points are represented by rectangles of one color centered on the data coordinate, this means that the shown color map extends by half a data point over the specified key/value range in each direction. - + \image html QCPColorMap-tightboundary.png "A color map, with tight boundary enabled and disabled" */ void QCPColorMap::setTightBoundary(bool enabled) { - mTightBoundary = enabled; + mTightBoundary = enabled; } /*! Associates the color scale \a colorScale with this color map. - + This means that both the color scale and the color map synchronize their gradient, data range and data scale type (\ref setGradient, \ref setDataRange, \ref setDataScaleType). Multiple color maps can be associated with one single color scale. This causes the color maps to also synchronize those properties, via the mutual color scale. - + This function causes the color map to adopt the current color gradient, data range and data scale type of \a colorScale. After this call, you may change these properties at either the color map or the color scale, and the setting will be applied to both. - + Pass 0 as \a colorScale to disconnect the color scale from this color map again. */ void QCPColorMap::setColorScale(QCPColorScale *colorScale) { - if (mColorScale) // unconnect signals from old color scale - { - disconnect(this, SIGNAL(dataRangeChanged(QCPRange)), mColorScale.data(), SLOT(setDataRange(QCPRange))); - disconnect(this, SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), mColorScale.data(), SLOT(setDataScaleType(QCPAxis::ScaleType))); - disconnect(this, SIGNAL(gradientChanged(QCPColorGradient)), mColorScale.data(), SLOT(setGradient(QCPColorGradient))); - disconnect(mColorScale.data(), SIGNAL(dataRangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange))); - disconnect(mColorScale.data(), SIGNAL(gradientChanged(QCPColorGradient)), this, SLOT(setGradient(QCPColorGradient))); - disconnect(mColorScale.data(), SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType))); - } - mColorScale = colorScale; - if (mColorScale) // connect signals to new color scale - { - setGradient(mColorScale.data()->gradient()); - setDataRange(mColorScale.data()->dataRange()); - setDataScaleType(mColorScale.data()->dataScaleType()); - connect(this, SIGNAL(dataRangeChanged(QCPRange)), mColorScale.data(), SLOT(setDataRange(QCPRange))); - connect(this, SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), mColorScale.data(), SLOT(setDataScaleType(QCPAxis::ScaleType))); - connect(this, SIGNAL(gradientChanged(QCPColorGradient)), mColorScale.data(), SLOT(setGradient(QCPColorGradient))); - connect(mColorScale.data(), SIGNAL(dataRangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange))); - connect(mColorScale.data(), SIGNAL(gradientChanged(QCPColorGradient)), this, SLOT(setGradient(QCPColorGradient))); - connect(mColorScale.data(), SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType))); - } + if (mColorScale) { // unconnect signals from old color scale + disconnect(this, SIGNAL(dataRangeChanged(QCPRange)), mColorScale.data(), SLOT(setDataRange(QCPRange))); + disconnect(this, SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), mColorScale.data(), SLOT(setDataScaleType(QCPAxis::ScaleType))); + disconnect(this, SIGNAL(gradientChanged(QCPColorGradient)), mColorScale.data(), SLOT(setGradient(QCPColorGradient))); + disconnect(mColorScale.data(), SIGNAL(dataRangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange))); + disconnect(mColorScale.data(), SIGNAL(gradientChanged(QCPColorGradient)), this, SLOT(setGradient(QCPColorGradient))); + disconnect(mColorScale.data(), SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType))); + } + mColorScale = colorScale; + if (mColorScale) { // connect signals to new color scale + setGradient(mColorScale.data()->gradient()); + setDataRange(mColorScale.data()->dataRange()); + setDataScaleType(mColorScale.data()->dataScaleType()); + connect(this, SIGNAL(dataRangeChanged(QCPRange)), mColorScale.data(), SLOT(setDataRange(QCPRange))); + connect(this, SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), mColorScale.data(), SLOT(setDataScaleType(QCPAxis::ScaleType))); + connect(this, SIGNAL(gradientChanged(QCPColorGradient)), mColorScale.data(), SLOT(setGradient(QCPColorGradient))); + connect(mColorScale.data(), SIGNAL(dataRangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange))); + connect(mColorScale.data(), SIGNAL(gradientChanged(QCPColorGradient)), this, SLOT(setGradient(QCPColorGradient))); + connect(mColorScale.data(), SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType))); + } } /*! Sets the data range (\ref setDataRange) to span the minimum and maximum values that occur in the current data set. This corresponds to the \ref rescaleKeyAxis or \ref rescaleValueAxis methods, only for the third data dimension of the color map. - + The minimum and maximum values of the data set are buffered in the internal QCPColorMapData instance (\ref data). As data is updated via its \ref QCPColorMapData::setCell or \ref QCPColorMapData::setData, the buffered minimum and maximum values are updated, too. For @@ -25834,128 +26166,128 @@ void QCPColorMap::setColorScale(QCPColorScale *colorScale) QCPColorMapData::recalculateDataBounds can be used. For convenience, setting the parameter \a recalculateDataBounds calls this method before setting the data range to the buffered minimum and maximum. - + \see setDataRange */ void QCPColorMap::rescaleDataRange(bool recalculateDataBounds) { - if (recalculateDataBounds) - mMapData->recalculateDataBounds(); - setDataRange(mMapData->dataBounds()); + if (recalculateDataBounds) { + mMapData->recalculateDataBounds(); + } + setDataRange(mMapData->dataBounds()); } /*! Takes the current appearance of the color map and updates the legend icon, which is used to represent this color map in the legend (see \ref QCPLegend). - + The \a transformMode specifies whether the rescaling is done by a faster, low quality image scaling algorithm (Qt::FastTransformation) or by a slower, higher quality algorithm (Qt::SmoothTransformation). - + The current color map appearance is scaled down to \a thumbSize. Ideally, this should be equal to the size of the legend icon (see \ref QCPLegend::setIconSize). If it isn't exactly the configured legend icon size, the thumb will be rescaled during drawing of the legend item. - + \see setDataRange */ void QCPColorMap::updateLegendIcon(Qt::TransformationMode transformMode, const QSize &thumbSize) { - if (mMapImage.isNull() && !data()->isEmpty()) - updateMapImage(); // try to update map image if it's null (happens if no draw has happened yet) - - if (!mMapImage.isNull()) // might still be null, e.g. if data is empty, so check here again - { - bool mirrorX = (keyAxis()->orientation() == Qt::Horizontal ? keyAxis() : valueAxis())->rangeReversed(); - bool mirrorY = (valueAxis()->orientation() == Qt::Vertical ? valueAxis() : keyAxis())->rangeReversed(); - mLegendIcon = QPixmap::fromImage(mMapImage.mirrored(mirrorX, mirrorY)).scaled(thumbSize, Qt::KeepAspectRatio, transformMode); - } + if (mMapImage.isNull() && !data()->isEmpty()) { + updateMapImage(); // try to update map image if it's null (happens if no draw has happened yet) + } + + if (!mMapImage.isNull()) { // might still be null, e.g. if data is empty, so check here again + bool mirrorX = (keyAxis()->orientation() == Qt::Horizontal ? keyAxis() : valueAxis())->rangeReversed(); + bool mirrorY = (valueAxis()->orientation() == Qt::Vertical ? valueAxis() : keyAxis())->rangeReversed(); + mLegendIcon = QPixmap::fromImage(mMapImage.mirrored(mirrorX, mirrorY)).scaled(thumbSize, Qt::KeepAspectRatio, transformMode); + } } /* inherits documentation from base class */ double QCPColorMap::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { - Q_UNUSED(details) - if ((onlySelectable && mSelectable == QCP::stNone) || mMapData->isEmpty()) - return -1; - if (!mKeyAxis || !mValueAxis) - 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; + Q_UNUSED(details) + if ((onlySelectable && mSelectable == QCP::stNone) || mMapData->isEmpty()) { + return -1; } - } - return -1; + if (!mKeyAxis || !mValueAxis) { + 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; + 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(); + 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; + + 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 turning the data values into color pixels with \ref QCPColorGradient::colorize. - + This method is called by \ref QCPColorMap::draw if either the data has been modified or the map image has been invalidated for a different reason (e.g. a change of the data range with \ref setDataRange). - + If the map cell count is low, the image created will be oversampled in order to avoid a QPainter::drawImage bug which makes inner pixel boundaries jitter when stretch-drawing images without smooth transform enabled. Accordingly, oversampling isn't performed if \ref @@ -25963,168 +26295,174 @@ QCPRange QCPColorMap::getValueRange(bool &foundRange, QCP::SignDomain inSignDoma */ void QCPColorMap::updateMapImage() { - QCPAxis *keyAxis = mKeyAxis.data(); - 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 - int valueOversamplingFactor = mInterpolate ? 1 : (int)(1.0+100.0/(double)valueSize); // make mMapImage have at least size 100, factor becomes 1 if size > 200 or interpolation is on - - // 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), format); - else if (keyAxis->orientation() == Qt::Vertical && (mMapImage.width() != valueSize*valueOversamplingFactor || mMapImage.height() != keySize*keyOversamplingFactor)) - mMapImage = QImage(QSize(valueSize*valueOversamplingFactor, keySize*keyOversamplingFactor), format); - - if (mMapImage.isNull()) - { - qDebug() << Q_FUNC_INFO << "Couldn't create map image (possibly too large for memory)"; - mMapImage = QImage(QSize(10, 10), format); - mMapImage.fill(Qt::black); - } else - { - 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), format); - else if (keyAxis->orientation() == Qt::Vertical && (mUndersampledMapImage.width() != valueSize || mUndersampledMapImage.height() != keySize)) - 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; - const int rowCount = keySize; - 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) - 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 - { - const int lineCount = keySize; - const int rowCount = valueSize; - 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) - 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); - } + QCPAxis *keyAxis = mKeyAxis.data(); + if (!keyAxis) { + return; } - - if (keyOversamplingFactor > 1 || valueOversamplingFactor > 1) - { - if (keyAxis->orientation() == Qt::Horizontal) - mMapImage = mUndersampledMapImage.scaled(keySize*keyOversamplingFactor, valueSize*valueOversamplingFactor, Qt::IgnoreAspectRatio, Qt::FastTransformation); - else - mMapImage = mUndersampledMapImage.scaled(valueSize*valueOversamplingFactor, keySize*keyOversamplingFactor, Qt::IgnoreAspectRatio, Qt::FastTransformation); + if (mMapData->isEmpty()) { + return; } - } - mMapData->mDataModified = false; - mMapImageInvalidated = false; + + 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 + int valueOversamplingFactor = mInterpolate ? 1 : (int)(1.0 + 100.0 / (double)valueSize); // make mMapImage have at least size 100, factor becomes 1 if size > 200 or interpolation is on + + // 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), format); + } else if (keyAxis->orientation() == Qt::Vertical && (mMapImage.width() != valueSize * valueOversamplingFactor || mMapImage.height() != keySize * keyOversamplingFactor)) { + mMapImage = QImage(QSize(valueSize * valueOversamplingFactor, keySize * keyOversamplingFactor), format); + } + + if (mMapImage.isNull()) { + qDebug() << Q_FUNC_INFO << "Couldn't create map image (possibly too large for memory)"; + mMapImage = QImage(QSize(10, 10), format); + mMapImage.fill(Qt::black); + } else { + 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), format); + } else if (keyAxis->orientation() == Qt::Vertical && (mUndersampledMapImage.width() != valueSize || mUndersampledMapImage.height() != keySize)) { + 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; + const int rowCount = keySize; + for (int line = 0; line < lineCount; ++line) { + QRgb *pixels = reinterpret_cast(localMapImage->scanLine(lineCount - 1 - line)); // invert scanline index because QImage counts scanlines from top, but our vertical index counts from bottom (mathematical coordinate system) + 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 + const int lineCount = keySize; + const int rowCount = valueSize; + for (int line = 0; line < lineCount; ++line) { + QRgb *pixels = reinterpret_cast(localMapImage->scanLine(lineCount - 1 - line)); // invert scanline index because QImage counts scanlines from top, but our vertical index counts from bottom (mathematical coordinate system) + 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); + } + } + } + + if (keyOversamplingFactor > 1 || valueOversamplingFactor > 1) { + if (keyAxis->orientation() == Qt::Horizontal) { + mMapImage = mUndersampledMapImage.scaled(keySize * keyOversamplingFactor, valueSize * valueOversamplingFactor, Qt::IgnoreAspectRatio, Qt::FastTransformation); + } else { + mMapImage = mUndersampledMapImage.scaled(valueSize * valueOversamplingFactor, keySize * keyOversamplingFactor, Qt::IgnoreAspectRatio, Qt::FastTransformation); + } + } + } + mMapData->mDataModified = false; + mMapImageInvalidated = false; } /* inherits documentation from base class */ void QCPColorMap::draw(QCPPainter *painter) { - if (mMapData->isEmpty()) return; - if (!mKeyAxis || !mValueAxis) return; - applyDefaultAntialiasingHint(painter); - - if (mMapData->mDataModified || mMapImageInvalidated) - updateMapImage(); - - // use buffer if painting vectorized (PDF): - 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; - 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); - localPainter = new QCPPainter(&mapBuffer); - localPainter->scale(mapBufferPixelRatio, mapBufferPixelRatio); - localPainter->translate(-mapBufferTarget.topLeft()); - } - - QRectF imageRect = QRectF(coordsToPixels(mMapData->keyRange().lower, mMapData->valueRange().lower), - coordsToPixels(mMapData->keyRange().upper, mMapData->valueRange().upper)).normalized(); - // extend imageRect to contain outer halves/quarters of bordering/cornering pixels (cells are centered on map range boundary): - double halfCellWidth = 0; // in pixels - double halfCellHeight = 0; // in pixels - if (keyAxis()->orientation() == Qt::Horizontal) - { - if (mMapData->keySize() > 1) - halfCellWidth = 0.5*imageRect.width()/(double)(mMapData->keySize()-1); - if (mMapData->valueSize() > 1) - halfCellHeight = 0.5*imageRect.height()/(double)(mMapData->valueSize()-1); - } else // keyAxis orientation is Qt::Vertical - { - if (mMapData->keySize() > 1) - halfCellHeight = 0.5*imageRect.height()/(double)(mMapData->keySize()-1); - if (mMapData->valueSize() > 1) - halfCellWidth = 0.5*imageRect.width()/(double)(mMapData->valueSize()-1); - } - imageRect.adjust(-halfCellWidth, -halfCellHeight, halfCellWidth, halfCellHeight); - 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) - { - clipBackup = localPainter->clipRegion(); - QRectF tightClipRect = QRectF(coordsToPixels(mMapData->keyRange().lower, mMapData->valueRange().lower), - coordsToPixels(mMapData->keyRange().upper, mMapData->valueRange().upper)).normalized(); - localPainter->setClipRect(tightClipRect, Qt::IntersectClip); - } - localPainter->drawImage(imageRect, mMapImage.mirrored(mirrorX, mirrorY)); - if (mTightBoundary) - localPainter->setClipRegion(clipBackup); - localPainter->setRenderHint(QPainter::SmoothPixmapTransform, smoothBackup); - - if (useBuffer) // localPainter painted to mapBuffer, so now draw buffer with original painter - { - delete localPainter; - painter->drawPixmap(mapBufferTarget.toRect(), mapBuffer); - } + if (mMapData->isEmpty()) { + return; + } + if (!mKeyAxis || !mValueAxis) { + return; + } + applyDefaultAntialiasingHint(painter); + + if (mMapData->mDataModified || mMapImageInvalidated) { + updateMapImage(); + } + + // use buffer if painting vectorized (PDF): + 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; + 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); + localPainter = new QCPPainter(&mapBuffer); + localPainter->scale(mapBufferPixelRatio, mapBufferPixelRatio); + localPainter->translate(-mapBufferTarget.topLeft()); + } + + QRectF imageRect = QRectF(coordsToPixels(mMapData->keyRange().lower, mMapData->valueRange().lower), + coordsToPixels(mMapData->keyRange().upper, mMapData->valueRange().upper)).normalized(); + // extend imageRect to contain outer halves/quarters of bordering/cornering pixels (cells are centered on map range boundary): + double halfCellWidth = 0; // in pixels + double halfCellHeight = 0; // in pixels + if (keyAxis()->orientation() == Qt::Horizontal) { + if (mMapData->keySize() > 1) { + halfCellWidth = 0.5 * imageRect.width() / (double)(mMapData->keySize() - 1); + } + if (mMapData->valueSize() > 1) { + halfCellHeight = 0.5 * imageRect.height() / (double)(mMapData->valueSize() - 1); + } + } else { // keyAxis orientation is Qt::Vertical + if (mMapData->keySize() > 1) { + halfCellHeight = 0.5 * imageRect.height() / (double)(mMapData->keySize() - 1); + } + if (mMapData->valueSize() > 1) { + halfCellWidth = 0.5 * imageRect.width() / (double)(mMapData->valueSize() - 1); + } + } + imageRect.adjust(-halfCellWidth, -halfCellHeight, halfCellWidth, halfCellHeight); + 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) { + clipBackup = localPainter->clipRegion(); + QRectF tightClipRect = QRectF(coordsToPixels(mMapData->keyRange().lower, mMapData->valueRange().lower), + coordsToPixels(mMapData->keyRange().upper, mMapData->valueRange().upper)).normalized(); + localPainter->setClipRect(tightClipRect, Qt::IntersectClip); + } + localPainter->drawImage(imageRect, mMapImage.mirrored(mirrorX, mirrorY)); + if (mTightBoundary) { + localPainter->setClipRegion(clipBackup); + } + localPainter->setRenderHint(QPainter::SmoothPixmapTransform, smoothBackup); + + if (useBuffer) { // localPainter painted to mapBuffer, so now draw buffer with original painter + delete localPainter; + painter->drawPixmap(mapBufferTarget.toRect(), mapBuffer); + } } /* inherits documentation from base class */ void QCPColorMap::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const { - applyDefaultAntialiasingHint(painter); - // draw map thumbnail: - if (!mLegendIcon.isNull()) - { - QPixmap scaledIcon = mLegendIcon.scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::FastTransformation); - QRectF iconRect = QRectF(0, 0, scaledIcon.width(), scaledIcon.height()); - iconRect.moveCenter(rect.center()); - painter->drawPixmap(iconRect.topLeft(), scaledIcon); - } - /* - // draw frame: - painter->setBrush(Qt::NoBrush); - painter->setPen(Qt::black); - painter->drawRect(rect.adjusted(1, 1, 0, 0)); - */ + applyDefaultAntialiasingHint(painter); + // draw map thumbnail: + if (!mLegendIcon.isNull()) { + QPixmap scaledIcon = mLegendIcon.scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::FastTransformation); + QRectF iconRect = QRectF(0, 0, scaledIcon.width(), scaledIcon.height()); + iconRect.moveCenter(rect.center()); + painter->drawPixmap(iconRect.topLeft(), scaledIcon); + } + /* + // draw frame: + painter->setBrush(Qt::NoBrush); + painter->setPen(Qt::black); + painter->drawRect(rect.adjusted(1, 1, 0, 0)); + */ } /* end of 'src/plottables/plottable-colormap.cpp' */ @@ -26138,68 +26476,68 @@ void QCPColorMap::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const /*! \class QCPFinancialData \brief Holds the data of one single data point for QCPFinancial. - + 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 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 - + 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. */ @@ -26210,11 +26548,11 @@ void QCPColorMap::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const Constructs a data point with key and all values set to zero. */ QCPFinancialData::QCPFinancialData() : - key(0), - open(0), - high(0), - low(0), - close(0) + key(0), + open(0), + high(0), + low(0), + close(0) { } @@ -26222,11 +26560,11 @@ QCPFinancialData::QCPFinancialData() : Constructs a data point with the specified \a key and OHLC values. */ QCPFinancialData::QCPFinancialData(double key, double open, double high, double low, double close) : - key(key), - open(open), - high(high), - low(low), - close(close) + key(key), + open(open), + high(high), + low(low), + close(close) { } @@ -26287,7 +26625,7 @@ QCPFinancialData::QCPFinancialData(double key, double open, double high, double /* start of documentation of inline functions */ /*! \fn QCPFinancialDataContainer *QCPFinancial::data() const - + 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. @@ -26300,23 +26638,23 @@ QCPFinancialData::QCPFinancialData(double key, double open, double high, double 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 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) : - QCPAbstractPlottable1D(keyAxis, valueAxis), - mChartStyle(csCandlestick), - mWidth(0.5), - 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))) + QCPAbstractPlottable1D(keyAxis, valueAxis), + mChartStyle(csCandlestick), + mWidth(0.5), + 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))) { - mSelectionDecorator->setBrush(QBrush(QColor(160, 160, 255))); + mSelectionDecorator->setBrush(QBrush(QColor(160, 160, 255))); } QCPFinancial::~QCPFinancial() @@ -26324,40 +26662,40 @@ QCPFinancial::~QCPFinancial() } /*! \overload - + Replaces the current data container with the provided \a data container. - + 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(QSharedPointer data) { - mDataContainer = data; + 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); + mDataContainer->clear(); + addData(keys, open, high, low, close, alreadySorted); } /*! @@ -26365,17 +26703,17 @@ void QCPFinancial::setData(const QVector &keys, const QVector &o */ void QCPFinancial::setChartStyle(QCPFinancial::ChartStyle style) { - mChartStyle = style; + mChartStyle = style; } /*! Sets the width of the individual bars/candlesticks to \a width in plot key coordinates. - + A typical choice is to set it to (or slightly less than) one bin interval width. */ void QCPFinancial::setWidth(double width) { - mWidth = width; + mWidth = width; } /*! @@ -26388,128 +26726,128 @@ void QCPFinancial::setWidth(double width) */ void QCPFinancial::setWidthType(QCPFinancial::WidthType widthType) { - mWidthType = 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. - + If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref setBrush). - + \see setPenPositive, setPenNegative, setBrushPositive, setBrushNegative */ void QCPFinancial::setTwoColored(bool twoColored) { - mTwoColored = twoColored; + mTwoColored = twoColored; } /*! If \ref setTwoColored is set to true, this function controls the brush that is used to draw fills of data points with a positive trend (i.e. bars/candlesticks with close >= open). - + If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref setBrush). - + \see setBrushNegative, setPenPositive, setPenNegative */ void QCPFinancial::setBrushPositive(const QBrush &brush) { - mBrushPositive = brush; + mBrushPositive = brush; } /*! If \ref setTwoColored is set to true, this function controls the brush that is used to draw fills of data points with a negative trend (i.e. bars/candlesticks with close < open). - + If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref setBrush). - + \see setBrushPositive, setPenNegative, setPenPositive */ void QCPFinancial::setBrushNegative(const QBrush &brush) { - mBrushNegative = brush; + mBrushNegative = brush; } /*! If \ref setTwoColored is set to true, this function controls the pen that is used to draw outlines of data points with a positive trend (i.e. bars/candlesticks with close >= open). - + If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref setBrush). - + \see setPenNegative, setBrushPositive, setBrushNegative */ void QCPFinancial::setPenPositive(const QPen &pen) { - mPenPositive = pen; + mPenPositive = pen; } /*! If \ref setTwoColored is set to true, this function controls the pen that is used to draw outlines of data points with a negative trend (i.e. bars/candlesticks with close < open). - + If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref setBrush). - + \see setPenPositive, setBrushNegative, setBrushPositive */ void QCPFinancial::setPenNegative(const QPen &pen) { - mPenNegative = pen; + mPenNegative = pen; } /*! \overload - + 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. - + 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 QVector &keys, const QVector &open, const QVector &high, const QVector &low, const QVector &close, bool alreadySorted) { - 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 + 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 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 directly via the \ref data method, which returns a pointer to the internal data container. - + \see timeSeriesToOhlc */ void QCPFinancial::addData(double key, double open, double high, double low, double close) { - mDataContainer->add(QCPFinancialData(key, open, high, low, close)); + mDataContainer->add(QCPFinancialData(key, open, high, low, close)); } /*! @@ -26517,22 +26855,24 @@ void QCPFinancial::addData(double key, double open, double high, double low, dou */ QCPDataSelection QCPFinancial::selectTestRect(const QRectF &rect, bool onlySelectable) const { - QCPDataSelection result; - if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty()) + QCPDataSelection result; + if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty()) { + return result; + } + if (!mKeyAxis || !mValueAxis) { + return result; + } + + QCPFinancialDataContainer::const_iterator visibleBegin, visibleEnd; + getVisibleDataBounds(visibleBegin, visibleEnd); + + for (QCPFinancialDataContainer::const_iterator it = visibleBegin; it != visibleEnd; ++it) { + if (rect.intersects(selectionHitBox(it))) { + result.addDataRange(QCPDataRange(it - mDataContainer->constBegin(), it - mDataContainer->constBegin() + 1), false); + } + } + result.simplify(); return result; - if (!mKeyAxis || !mValueAxis) - return result; - - QCPFinancialDataContainer::const_iterator visibleBegin, visibleEnd; - getVisibleDataBounds(visibleBegin, visibleEnd); - - for (QCPFinancialDataContainer::const_iterator it=visibleBegin; it!=visibleEnd; ++it) - { - if (rect.intersects(selectionHitBox(it))) - result.addDataRange(QCPDataRange(it-mDataContainer->constBegin(), it-mDataContainer->constBegin()+1), false); - } - result.simplify(); - return result; } /*! @@ -26540,73 +26880,75 @@ QCPDataSelection QCPFinancial::selectTestRect(const QRectF &rect, bool onlySelec If \a details is not 0, it will be set to a \ref QCPDataSelection, describing the closest data point to \a pos. - + \seebaseclassmethod \ref QCPAbstractPlottable::selectTest */ double QCPFinancial::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { - Q_UNUSED(details) - if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty()) - return -1; - if (!mKeyAxis || !mValueAxis) - return -1; - - if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint())) - { - // get visible data range: - 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: - result = ohlcSelectTest(pos, visibleBegin, visibleEnd, closestDataPoint); break; - case QCPFinancial::csCandlestick: - result = candlestickSelectTest(pos, visibleBegin, visibleEnd, closestDataPoint); break; + Q_UNUSED(details) + if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty()) { + return -1; } - if (details) - { - int pointIndex = closestDataPoint-mDataContainer->constBegin(); - details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1))); + if (!mKeyAxis || !mValueAxis) { + return -1; } - return result; - } - - return -1; + + if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint())) { + // get visible data range: + 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: + result = ohlcSelectTest(pos, visibleBegin, visibleEnd, closestDataPoint); + break; + case QCPFinancial::csCandlestick: + 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; + 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); + 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 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 each, set \a timeBinSize to 3600. - + \a timeBinOffset allows to control precisely at what \a time coordinate a bin should start. The value passed as \a timeBinOffset doesn't need to be in the range encompassed by the \a time keys. It merely defines the mathematical offset/phase of the bins that will be used to process the @@ -26614,263 +26956,254 @@ QCPRange QCPFinancial::getValueRange(bool &foundRange, QCP::SignDomain inSignDom */ QCPFinancialDataContainer QCPFinancial::timeSeriesToOhlc(const QVector &time, const QVector &value, double timeBinSize, double timeBinOffset) { - QCPFinancialDataContainer data; - int count = qMin(time.size(), value.size()); - if (count == 0) - return QCPFinancialDataContainer(); - - QCPFinancialData currentBinData(0, value.first(), value.first(), value.first(), value.first()); - int currentBinIndex = qFloor((time.first()-timeBinOffset)/timeBinSize+0.5); - for (int i=0; i currentBinData.high) currentBinData.high = value.at(i); - if (i == count-1) // last data point is in current bin, finalize bin: - { - currentBinData.close = value.at(i); - currentBinData.key = timeBinOffset+(index)*timeBinSize; - 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; - data.add(currentBinData); - // start next bin: - currentBinIndex = index; - currentBinData.open = value.at(i); - currentBinData.high = value.at(i); - currentBinData.low = value.at(i); + QCPFinancialDataContainer data; + int count = qMin(time.size(), value.size()); + if (count == 0) { + return QCPFinancialDataContainer(); } - } - - return data; + + QCPFinancialData currentBinData(0, value.first(), value.first(), value.first(), value.first()); + int currentBinIndex = qFloor((time.first() - timeBinOffset) / timeBinSize + 0.5); + for (int i = 0; i < count; ++i) { + int index = qFloor((time.at(i) - timeBinOffset) / timeBinSize + 0.5); + if (currentBinIndex == index) { // data point still in current bin, extend high/low: + if (value.at(i) < currentBinData.low) { + currentBinData.low = value.at(i); + } + if (value.at(i) > currentBinData.high) { + currentBinData.high = value.at(i); + } + if (i == count - 1) { // last data point is in current bin, finalize bin: + currentBinData.close = value.at(i); + currentBinData.key = timeBinOffset + (index) * timeBinSize; + 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; + data.add(currentBinData); + // start next bin: + currentBinIndex = index; + currentBinData.open = value.at(i); + currentBinData.high = value.at(i); + currentBinData.low = value.at(i); + } + } + + return data; } /* inherits documentation from base class */ void QCPFinancial::draw(QCPPainter *painter) { - // get visible data range: - QCPFinancialDataContainer::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(); - 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; + // get visible data range: + QCPFinancialDataContainer::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 < allSegments.size(); ++i) { + bool isSelectedSegment = 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()); } - } - - // 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 QCPFinancial::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const { - painter->setAntialiasing(false); // legend icon especially of csCandlestick looks better without antialiasing - if (mChartStyle == csOhlc) - { - if (mTwoColored) - { - // draw upper left half icon with positive color: - painter->setBrush(mBrushPositive); - painter->setPen(mPenPositive); - painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.topLeft().toPoint())); - 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 half icon with negative color: - painter->setBrush(mBrushNegative); - painter->setPen(mPenNegative); - painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.bottomRight().toPoint())); - 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())); - } else - { - painter->setBrush(mBrush); - painter->setPen(mPen); - 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())); + painter->setAntialiasing(false); // legend icon especially of csCandlestick looks better without antialiasing + if (mChartStyle == csOhlc) { + if (mTwoColored) { + // draw upper left half icon with positive color: + painter->setBrush(mBrushPositive); + painter->setPen(mPenPositive); + painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.topLeft().toPoint())); + 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 half icon with negative color: + painter->setBrush(mBrushNegative); + painter->setPen(mPenNegative); + painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.bottomRight().toPoint())); + 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())); + } else { + painter->setBrush(mBrush); + painter->setPen(mPen); + 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())); + } + } else if (mChartStyle == csCandlestick) { + if (mTwoColored) { + // draw upper left half icon with positive color: + painter->setBrush(mBrushPositive); + painter->setPen(mPenPositive); + painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.topLeft().toPoint())); + 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 half icon with negative color: + painter->setBrush(mBrushNegative); + painter->setPen(mPenNegative); + painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.bottomRight().toPoint())); + 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())); + } else { + painter->setBrush(mBrush); + painter->setPen(mPen); + 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())); + } } - } else if (mChartStyle == csCandlestick) - { - if (mTwoColored) - { - // draw upper left half icon with positive color: - painter->setBrush(mBrushPositive); - painter->setPen(mPenPositive); - painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.topLeft().toPoint())); - 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 half icon with negative color: - painter->setBrush(mBrushNegative); - painter->setPen(mPenNegative); - painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.bottomRight().toPoint())); - 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())); - } else - { - painter->setBrush(mBrush); - painter->setPen(mPen); - 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())); - } - } } /*! \internal - + 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 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; } - - if (keyAxis->orientation() == Qt::Horizontal) - { - for (QCPFinancialDataContainer::const_iterator it = begin; it != end; ++it) - { - if (isSelected && mSelectionDecorator) - mSelectionDecorator->applyPen(painter); - else if (mTwoColored) - painter->setPen(it->close >= it->open ? mPenPositive : mPenNegative); - else - 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->high)), QPointF(keyPixel, valueAxis->coordToPixel(it->low))); - // draw open: - 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+pixelWidth, closePixel)); + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + return; } - } else - { - for (QCPFinancialDataContainer::const_iterator it = begin; it != end; ++it) - { - if (isSelected && mSelectionDecorator) - mSelectionDecorator->applyPen(painter); - else if (mTwoColored) - painter->setPen(it->close >= it->open ? mPenPositive : mPenNegative); - else - 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->high), keyPixel), QPointF(valueAxis->coordToPixel(it->low), keyPixel)); - // draw open: - 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+pixelWidth)); + + if (keyAxis->orientation() == Qt::Horizontal) { + for (QCPFinancialDataContainer::const_iterator it = begin; it != end; ++it) { + if (isSelected && mSelectionDecorator) { + mSelectionDecorator->applyPen(painter); + } else if (mTwoColored) { + painter->setPen(it->close >= it->open ? mPenPositive : mPenNegative); + } else { + 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->high)), QPointF(keyPixel, valueAxis->coordToPixel(it->low))); + // draw open: + 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 + pixelWidth, closePixel)); + } + } else { + for (QCPFinancialDataContainer::const_iterator it = begin; it != end; ++it) { + if (isSelected && mSelectionDecorator) { + mSelectionDecorator->applyPen(painter); + } else if (mTwoColored) { + painter->setPen(it->close >= it->open ? mPenPositive : mPenNegative); + } else { + 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->high), keyPixel), QPointF(valueAxis->coordToPixel(it->low), keyPixel)); + // draw open: + 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 + pixelWidth)); + } } - } } /*! \internal - + 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 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; } - - if (keyAxis->orientation() == Qt::Horizontal) - { - for (QCPFinancialDataContainer::const_iterator it = begin; it != end; ++it) - { - if (isSelected && mSelectionDecorator) - { - mSelectionDecorator->applyPen(painter); - mSelectionDecorator->applyBrush(painter); - } else if (mTwoColored) - { - painter->setPen(it->close >= it->open ? mPenPositive : mPenNegative); - painter->setBrush(it->close >= it->open ? mBrushPositive : mBrushNegative); - } else - { - painter->setPen(mPen); - painter->setBrush(mBrush); - } - 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->high)), QPointF(keyPixel, valueAxis->coordToPixel(qMax(it->open, it->close)))); - // draw low: - painter->drawLine(QPointF(keyPixel, valueAxis->coordToPixel(it->low)), QPointF(keyPixel, valueAxis->coordToPixel(qMin(it->open, it->close)))); - // draw open-close box: - double pixelWidth = getPixelWidth(it->key, keyPixel); - painter->drawRect(QRectF(QPointF(keyPixel-pixelWidth, closePixel), QPointF(keyPixel+pixelWidth, openPixel))); + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + return; } - } else // keyAxis->orientation() == Qt::Vertical - { - for (QCPFinancialDataContainer::const_iterator it = begin; it != end; ++it) - { - if (isSelected && mSelectionDecorator) - { - mSelectionDecorator->applyPen(painter); - mSelectionDecorator->applyBrush(painter); - } else if (mTwoColored) - { - painter->setPen(it->close >= it->open ? mPenPositive : mPenNegative); - painter->setBrush(it->close >= it->open ? mBrushPositive : mBrushNegative); - } else - { - painter->setPen(mPen); - painter->setBrush(mBrush); - } - 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->high), keyPixel), QPointF(valueAxis->coordToPixel(qMax(it->open, it->close)), keyPixel)); - // draw low: - painter->drawLine(QPointF(valueAxis->coordToPixel(it->low), keyPixel), QPointF(valueAxis->coordToPixel(qMin(it->open, it->close)), keyPixel)); - // draw open-close box: - double pixelWidth = getPixelWidth(it->key, keyPixel); - painter->drawRect(QRectF(QPointF(closePixel, keyPixel-pixelWidth), QPointF(openPixel, keyPixel+pixelWidth))); + + if (keyAxis->orientation() == Qt::Horizontal) { + for (QCPFinancialDataContainer::const_iterator it = begin; it != end; ++it) { + if (isSelected && mSelectionDecorator) { + mSelectionDecorator->applyPen(painter); + mSelectionDecorator->applyBrush(painter); + } else if (mTwoColored) { + painter->setPen(it->close >= it->open ? mPenPositive : mPenNegative); + painter->setBrush(it->close >= it->open ? mBrushPositive : mBrushNegative); + } else { + painter->setPen(mPen); + painter->setBrush(mBrush); + } + 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->high)), QPointF(keyPixel, valueAxis->coordToPixel(qMax(it->open, it->close)))); + // draw low: + painter->drawLine(QPointF(keyPixel, valueAxis->coordToPixel(it->low)), QPointF(keyPixel, valueAxis->coordToPixel(qMin(it->open, it->close)))); + // draw open-close box: + double pixelWidth = getPixelWidth(it->key, keyPixel); + painter->drawRect(QRectF(QPointF(keyPixel - pixelWidth, closePixel), QPointF(keyPixel + pixelWidth, openPixel))); + } + } else { // keyAxis->orientation() == Qt::Vertical + for (QCPFinancialDataContainer::const_iterator it = begin; it != end; ++it) { + if (isSelected && mSelectionDecorator) { + mSelectionDecorator->applyPen(painter); + mSelectionDecorator->applyBrush(painter); + } else if (mTwoColored) { + painter->setPen(it->close >= it->open ? mPenPositive : mPenNegative); + painter->setBrush(it->close >= it->open ? mBrushPositive : mBrushNegative); + } else { + painter->setPen(mPen); + painter->setBrush(mBrush); + } + 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->high), keyPixel), QPointF(valueAxis->coordToPixel(qMax(it->open, it->close)), keyPixel)); + // draw low: + painter->drawLine(QPointF(valueAxis->coordToPixel(it->low), keyPixel), QPointF(valueAxis->coordToPixel(qMin(it->open, it->close)), keyPixel)); + // draw open-close box: + double pixelWidth = getPixelWidth(it->key, keyPixel); + painter->drawRect(QRectF(QPointF(closePixel, keyPixel - pixelWidth), QPointF(openPixel, keyPixel + pixelWidth))); + } } - } } /*! \internal @@ -26887,185 +27220,173 @@ void QCPFinancial::drawCandlestickPlot(QCPPainter *painter, const QCPFinancialDa */ 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; + 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; + } } - 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; + 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 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; } + 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)(); - if (keyAxis->orientation() == Qt::Horizontal) - { - for (QCPFinancialDataContainer::const_iterator it=begin; it!=end; ++it) - { - double keyPixel = keyAxis->coordToPixel(it->key); - // calculate distance to backbone: - double currentDistSqr = QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(keyPixel, valueAxis->coordToPixel(it->high)), QCPVector2D(keyPixel, valueAxis->coordToPixel(it->low))); - if (currentDistSqr < minDistSqr) - { - minDistSqr = currentDistSqr; - closestDataPoint = it; - } + double minDistSqr = (std::numeric_limits::max)(); + if (keyAxis->orientation() == Qt::Horizontal) { + for (QCPFinancialDataContainer::const_iterator it = begin; it != end; ++it) { + double keyPixel = keyAxis->coordToPixel(it->key); + // calculate distance to backbone: + 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 (QCPFinancialDataContainer::const_iterator it = begin; it != end; ++it) { + double keyPixel = keyAxis->coordToPixel(it->key); + // calculate distance to backbone: + double currentDistSqr = QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(valueAxis->coordToPixel(it->high), keyPixel), QCPVector2D(valueAxis->coordToPixel(it->low), keyPixel)); + if (currentDistSqr < minDistSqr) { + minDistSqr = currentDistSqr; + closestDataPoint = it; + } + } } - } else // keyAxis->orientation() == Qt::Vertical - { - for (QCPFinancialDataContainer::const_iterator it=begin; it!=end; ++it) - { - double keyPixel = keyAxis->coordToPixel(it->key); - // calculate distance to backbone: - 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); + return qSqrt(minDistSqr); } /*! \internal - + 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 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; } + 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)(); - if (keyAxis->orientation() == Qt::Horizontal) - { - for (QCPFinancialDataContainer::const_iterator it=begin; it!=end; ++it) - { - double currentDistSqr; - // determine whether pos is in open-close-box: - 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 - { - currentDistSqr = mParentPlot->selectionTolerance()*0.99 * mParentPlot->selectionTolerance()*0.99; - } else - { - // calculate distance to high/low lines: - 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; - } + double minDistSqr = (std::numeric_limits::max)(); + if (keyAxis->orientation() == Qt::Horizontal) { + for (QCPFinancialDataContainer::const_iterator it = begin; it != end; ++it) { + double currentDistSqr; + // determine whether pos is in open-close-box: + 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 + currentDistSqr = mParentPlot->selectionTolerance() * 0.99 * mParentPlot->selectionTolerance() * 0.99; + } else { + // calculate distance to high/low lines: + 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 (QCPFinancialDataContainer::const_iterator it = begin; it != end; ++it) { + double currentDistSqr; + // determine whether pos is in open-close-box: + 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 + currentDistSqr = mParentPlot->selectionTolerance() * 0.99 * mParentPlot->selectionTolerance() * 0.99; + } else { + // calculate distance to high/low lines: + 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; + } + } } - } else // keyAxis->orientation() == Qt::Vertical - { - for (QCPFinancialDataContainer::const_iterator it=begin; it!=end; ++it) - { - double currentDistSqr; - // determine whether pos is in open-close-box: - 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 - { - currentDistSqr = mParentPlot->selectionTolerance()*0.99 * mParentPlot->selectionTolerance()*0.99; - } else - { - // calculate distance to high/low lines: - 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); + return qSqrt(minDistSqr); } /*! \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 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 begin may still be just outside 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 begin and \a end point to \c constEnd. */ void QCPFinancial::getVisibleDataBounds(QCPFinancialDataContainer::const_iterator &begin, QCPFinancialDataContainer::const_iterator &end) const { - if (!mKeyAxis) - { - 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 + if (!mKeyAxis) { + 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 @@ -27075,18 +27396,22 @@ void QCPFinancial::getVisibleDataBounds(QCPFinancialDataContainer::const_iterato */ 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(); + 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' */ @@ -27117,8 +27442,8 @@ QRectF QCPFinancial::selectionHitBox(QCPFinancialDataContainer::const_iterator i Constructs an error bar with errors set to zero. */ QCPErrorBarsData::QCPErrorBarsData() : - errorMinus(0), - errorPlus(0) + errorMinus(0), + errorPlus(0) { } @@ -27126,8 +27451,8 @@ QCPErrorBarsData::QCPErrorBarsData() : Constructs an error bar with equal \a error in both negative and positive direction. */ QCPErrorBarsData::QCPErrorBarsData(double error) : - errorMinus(error), - errorPlus(error) + errorMinus(error), + errorPlus(error) { } @@ -27136,8 +27461,8 @@ QCPErrorBarsData::QCPErrorBarsData(double error) : respectively. */ QCPErrorBarsData::QCPErrorBarsData(double errorMinus, double errorPlus) : - errorMinus(errorMinus), - errorPlus(errorPlus) + errorMinus(errorMinus), + errorPlus(errorPlus) { } @@ -27200,14 +27525,14 @@ QCPErrorBarsData::QCPErrorBarsData(double errorMinus, double errorPlus) : 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) + QCPAbstractPlottable(keyAxis, valueAxis), + mDataContainer(new QVector), + mErrorType(etValueError), + mWhiskerWidth(9), + mSymbolGap(10) { - setPen(QPen(Qt::black, 0)); - setBrush(Qt::NoBrush); + setPen(QPen(Qt::black, 0)); + setBrush(Qt::NoBrush); } QCPErrorBars::~QCPErrorBars() @@ -27234,7 +27559,7 @@ QCPErrorBars::~QCPErrorBars() */ void QCPErrorBars::setData(QSharedPointer data) { - mDataContainer = data; + mDataContainer = data; } /*! \overload @@ -27248,8 +27573,8 @@ void QCPErrorBars::setData(QSharedPointer data) */ void QCPErrorBars::setData(const QVector &error) { - mDataContainer->clear(); - addData(error); + mDataContainer->clear(); + addData(error); } /*! \overload @@ -27264,8 +27589,8 @@ void QCPErrorBars::setData(const QVector &error) */ void QCPErrorBars::setData(const QVector &errorMinus, const QVector &errorPlus) { - mDataContainer->clear(); - addData(errorMinus, errorPlus); + mDataContainer->clear(); + addData(errorMinus, errorPlus); } /*! @@ -27284,20 +27609,18 @@ void QCPErrorBars::setData(const QVector &errorMinus, const QVector(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; - } - - mDataPlottable = 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; + } + + mDataPlottable = plottable; } /*! @@ -27306,7 +27629,7 @@ void QCPErrorBars::setDataPlottable(QCPAbstractPlottable *plottable) */ void QCPErrorBars::setErrorType(ErrorType type) { - mErrorType = type; + mErrorType = type; } /*! @@ -27315,7 +27638,7 @@ void QCPErrorBars::setErrorType(ErrorType type) */ void QCPErrorBars::setWhiskerWidth(double pixels) { - mWhiskerWidth = pixels; + mWhiskerWidth = pixels; } /*! @@ -27325,7 +27648,7 @@ void QCPErrorBars::setWhiskerWidth(double pixels) */ void QCPErrorBars::setSymbolGap(double pixels) { - mSymbolGap = pixels; + mSymbolGap = pixels; } /*! \overload @@ -27339,7 +27662,7 @@ void QCPErrorBars::setSymbolGap(double pixels) */ void QCPErrorBars::addData(const QVector &error) { - addData(error, error); + addData(error, error); } /*! \overload @@ -27354,12 +27677,14 @@ void QCPErrorBars::addData(const QVector &error) */ 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))); + 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; i < n; ++i) { + mDataContainer->append(QCPErrorBarsData(errorMinus.at(i), errorPlus.at(i))); + } } /*! \overload @@ -27373,7 +27698,7 @@ void QCPErrorBars::addData(const QVector &errorMinus, const QVectorappend(QCPErrorBarsData(error)); + mDataContainer->append(QCPErrorBarsData(error)); } /*! \overload @@ -27388,83 +27713,84 @@ void QCPErrorBars::addData(double error) */ void QCPErrorBars::addData(double errorMinus, double errorPlus) { - mDataContainer->append(QCPErrorBarsData(errorMinus, errorPlus)); + mDataContainer->append(QCPErrorBarsData(errorMinus, errorPlus)); } /* inherits documentation from base class */ int QCPErrorBars::dataCount() const { - return mDataContainer->size(); + 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; + 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; + 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; + 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(); - } + 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(); + 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; - } + if (mDataPlottable) { + return mDataPlottable->interface1D()->sortKeyIsMainKey(); + } else { + qDebug() << Q_FUNC_INFO << "no data plottable set"; + return true; + } } /*! @@ -27472,66 +27798,70 @@ bool QCPErrorBars::sortKeyIsMainKey() const */ 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; - } + QCPDataSelection result; + if (!mDataPlottable) { + return result; } - } - result.simplify(); - 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; i < backbones.size(); ++i) { + if (rectIntersectsLine(rect, backbones.at(i))) { + result.addDataRange(QCPDataRange(it - mDataContainer->constBegin(), 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; + 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; + 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; } /*! @@ -27539,271 +27869,261 @@ int QCPErrorBars::findEnd(double sortKey, bool expandedRange) const If \a details is not 0, it will be set to a \ref QCPDataSelection, describing the closest data point to \a pos. - + \seebaseclassmethod \ref QCPAbstractPlottable::selectTest */ 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))); + 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; } - 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(); - + 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(); - } + 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); + + 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 < allSegments.size(); ++i) { + QCPErrorBarsDataContainer::const_iterator begin, end; + getVisibleDataBounds(begin, end, allSegments.at(i)); + if (begin == end) { + continue; + } + + bool isSelectedSegment = 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); } - backbones.clear(); - whiskers.clear(); - for (QCPErrorBarsDataContainer::const_iterator it=begin; it!=end; ++it) - { - if (!checkPointVisibility || errorBarVisible(it-mDataContainer->constBegin())) - getErrorBarLines(it, backbones, whiskers); + + // draw other selection decoration that isn't just line/scatter pens and brushes: + if (mSelectionDecorator) { + mSelectionDecorator->drawDecoration(painter, selection()); } - 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)); - } + 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 (!mDataPlottable) { + foundRange = false; + return QCPRange(); } - } - - if (haveUpper && !haveLower) - { - range.lower = range.upper; - haveLower = true; - } else if (haveLower && !haveUpper) - { - range.upper = range.lower; - haveUpper = true; - } - - foundRange = haveLower && haveUpper; - return range; + + 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 (!mDataPlottable) { + foundRange = false; + return QCPRange(); } - 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; - } - } + + 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); } - } - - if (haveUpper && !haveLower) - { - range.lower = range.upper; - haveLower = true; - } else if (haveLower && !haveUpper) - { - range.upper = range.lower; - haveUpper = true; - } - - foundRange = haveLower && haveUpper; - return range; + 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 @@ -27819,53 +28139,54 @@ QCPRange QCPErrorBars::getValueRange(bool &foundRange, QCP::SignDomain inSignDom */ 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.data() : mKeyAxis.data(); - QCPAxis *orthoAxis = mErrorType == etValueError ? mKeyAxis.data() : mValueAxis.data(); - 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)); + if (!mDataPlottable) { + return; } - } - // 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)); + + int index = it - mDataContainer->constBegin(); + QPointF centerPixel = mDataPlottable->interface1D()->dataPixelPosition(index); + if (qIsNaN(centerPixel.x()) || qIsNaN(centerPixel.y())) { + return; + } + QCPAxis *errorAxis = mErrorType == etValueError ? mValueAxis.data() : mKeyAxis.data(); + QCPAxis *orthoAxis = mErrorType == etValueError ? mKeyAxis.data() : mValueAxis.data(); + 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 @@ -27888,55 +28209,52 @@ void QCPErrorBars::getErrorBarLines(QCPErrorBarsDataContainer::const_iterator it */ 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(); + 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 @@ -27947,35 +28265,32 @@ void QCPErrorBars::getVisibleDataBounds(QCPErrorBarsDataContainer::const_iterato */ double QCPErrorBars::pointDistance(const QPointF &pixelPoint, QCPErrorBarsDataContainer::const_iterator &closestData) const { - closestData = mDataContainer->constEnd(); - if (!mDataPlottable || mDataContainer->isEmpty()) - return -1.0; - if (!mKeyAxis || !mValueAxis) - { - qDebug() << Q_FUNC_INFO << "invalid key or value axis"; - 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; iconstEnd(); + if (!mDataPlottable || mDataContainer->isEmpty()) { + return -1.0; } - } - return qSqrt(minDistSqr); + if (!mKeyAxis || !mValueAxis) { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + 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 < backbones.size(); ++i) { + const double currentDistSqr = QCPVector2D(pixelPoint).distanceSquaredToLine(backbones.at(i)); + if (currentDistSqr < minDistSqr) { + minDistSqr = currentDistSqr; + closestData = it; + } + } + } + return qSqrt(minDistSqr); } /*! \internal @@ -27987,21 +28302,20 @@ double QCPErrorBars::pointDistance(const QPointF &pixelPoint, QCPErrorBarsDataCo */ void QCPErrorBars::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(); - } + 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 @@ -28015,25 +28329,24 @@ void QCPErrorBars::getDataSegments(QList &selectedSegments, QList< */ 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)); + 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 @@ -28045,16 +28358,17 @@ bool QCPErrorBars::errorBarVisible(int index) const */ 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; + 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' */ @@ -28076,20 +28390,20 @@ bool QCPErrorBars::rectIntersectsLine(const QRectF &pixelRect, const QLineF &lin /*! Creates a straight line item and sets default values. - + 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), - point1(createPosition(QLatin1String("point1"))), - point2(createPosition(QLatin1String("point2"))) + QCPAbstractItem(parentPlot), + point1(createPosition(QLatin1String("point1"))), + point2(createPosition(QLatin1String("point2"))) { - point1->setCoords(0, 0); - point2->setCoords(1, 1); - - setPen(QPen(Qt::black)); - setSelectedPen(QPen(Qt::blue,2)); + point1->setCoords(0, 0); + point2->setCoords(1, 1); + + setPen(QPen(Qt::black)); + setSelectedPen(QPen(Qt::blue, 2)); } QCPItemStraightLine::~QCPItemStraightLine() @@ -28098,134 +28412,133 @@ QCPItemStraightLine::~QCPItemStraightLine() /*! Sets the pen that will be used to draw the line - + \see setSelectedPen */ void QCPItemStraightLine::setPen(const QPen &pen) { - mPen = pen; + mPen = pen; } /*! Sets the pen that will be used to draw the line when selected - + \see setPen, setSelected */ void QCPItemStraightLine::setSelectedPen(const QPen &pen) { - mSelectedPen = pen; + mSelectedPen = pen; } /* inherits documentation from base class */ double QCPItemStraightLine::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { - Q_UNUSED(details) - if (onlySelectable && !mSelectable) - return -1; - - return QCPVector2D(pos).distanceToStraightLine(point1->pixelPosition(), point2->pixelPosition()-point1->pixelPosition()); + Q_UNUSED(details) + if (onlySelectable && !mSelectable) { + return -1; + } + + return QCPVector2D(pos).distanceToStraightLine(point1->pixelPosition(), point2->pixelPosition() - point1->pixelPosition()); } /* inherits documentation from base class */ void QCPItemStraightLine::draw(QCPPainter *painter) { - 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)); - // paint visible segment, if existent: - if (!line.isNull()) - { - painter->setPen(mainPen()); - painter->drawLine(line); - } + 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)); + // paint visible segment, if existent: + if (!line.isNull()) { + painter->setPen(mainPen()); + painter->drawLine(line); + } } /*! \internal Returns the section of the straight line defined by \a base and direction vector \a vec, that is visible in the specified \a rect. - + This is a helper function for \ref draw. */ QLineF QCPItemStraightLine::getRectClippedStraightLine(const QCPVector2D &base, const QCPVector2D &vec, const QRect &rect) const { - double bx, by; - double gamma; - QLineF result; - if (vec.x() == 0 && vec.y() == 0) - return result; - if (qFuzzyIsNull(vec.x())) // line is vertical - { - // 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()) - result.setLine(bx+gamma, rect.top(), bx+gamma, rect.bottom()); // no need to check bottom because we know line is vertical - } else if (qFuzzyIsNull(vec.y())) // line is horizontal - { - // 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()) - 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; - // 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(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(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(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(QCPVector2D(bx, by+gamma)); - - // evaluate points: - if (pointVectors.size() == 2) - { - result.setPoints(pointVectors.at(0).toPointF(), pointVectors.at(1).toPointF()); - } else if (pointVectors.size() > 2) - { - // line probably goes through corner of rect, and we got two points there. single out the point pair with greatest distance: - double distSqrMax = 0; - QCPVector2D pv1, pv2; - for (int i=0; i distSqrMax) - { - pv1 = pointVectors.at(i); - pv2 = pointVectors.at(k); - distSqrMax = distSqr; - } - } - } - result.setPoints(pv1.toPointF(), pv2.toPointF()); + double bx, by; + double gamma; + QLineF result; + if (vec.x() == 0 && vec.y() == 0) { + return result; } - } - return result; + if (qFuzzyIsNull(vec.x())) { // line is vertical + // 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()) { + result.setLine(bx + gamma, rect.top(), bx + gamma, rect.bottom()); // no need to check bottom because we know line is vertical + } + } else if (qFuzzyIsNull(vec.y())) { // line is horizontal + // 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()) { + 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; + // 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(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(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(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(QCPVector2D(bx, by + gamma)); + } + + // evaluate points: + if (pointVectors.size() == 2) { + result.setPoints(pointVectors.at(0).toPointF(), pointVectors.at(1).toPointF()); + } else if (pointVectors.size() > 2) { + // line probably goes through corner of rect, and we got two points there. single out the point pair with greatest distance: + double distSqrMax = 0; + QCPVector2D pv1, pv2; + for (int i = 0; i < pointVectors.size() - 1; ++i) { + for (int k = i + 1; k < pointVectors.size(); ++k) { + double distSqr = (pointVectors.at(i) - pointVectors.at(k)).lengthSquared(); + if (distSqr > distSqrMax) { + pv1 = pointVectors.at(i); + pv2 = pointVectors.at(k); + distSqrMax = distSqr; + } + } + } + result.setPoints(pv1.toPointF(), pv2.toPointF()); + } + } + return result; } /*! \internal @@ -28235,7 +28548,7 @@ QLineF QCPItemStraightLine::getRectClippedStraightLine(const QCPVector2D &base, */ QPen QCPItemStraightLine::mainPen() const { - return mSelected ? mSelectedPen : mPen; + return mSelected ? mSelectedPen : mPen; } /* end of 'src/items/item-straightline.cpp' */ @@ -28253,26 +28566,26 @@ QPen QCPItemStraightLine::mainPen() const \image html QCPItemLine.png "Line example. Blue dotted circles are anchors, solid blue discs are positions." It has two positions, \a start and \a end, which define the end points of the line. - + With \ref setHead and \ref setTail you may set different line ending styles, e.g. to create an arrow. */ /*! Creates a line item and sets default values. - + 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. */ QCPItemLine::QCPItemLine(QCustomPlot *parentPlot) : - QCPAbstractItem(parentPlot), - start(createPosition(QLatin1String("start"))), - end(createPosition(QLatin1String("end"))) + QCPAbstractItem(parentPlot), + start(createPosition(QLatin1String("start"))), + end(createPosition(QLatin1String("end"))) { - start->setCoords(0, 0); - end->setCoords(1, 1); - - setPen(QPen(Qt::black)); - setSelectedPen(QPen(Qt::blue,2)); + start->setCoords(0, 0); + end->setCoords(1, 1); + + setPen(QPen(Qt::black)); + setSelectedPen(QPen(Qt::blue, 2)); } QCPItemLine::~QCPItemLine() @@ -28281,182 +28594,181 @@ QCPItemLine::~QCPItemLine() /*! Sets the pen that will be used to draw the line - + \see setSelectedPen */ void QCPItemLine::setPen(const QPen &pen) { - mPen = pen; + mPen = pen; } /*! Sets the pen that will be used to draw the line when selected - + \see setPen, setSelected */ void QCPItemLine::setSelectedPen(const QPen &pen) { - mSelectedPen = pen; + mSelectedPen = pen; } /*! Sets the line ending style of the head. The head corresponds to the \a end position. - + Note that due to the overloaded QCPLineEnding constructor, you may directly specify a QCPLineEnding::EndingStyle here, e.g. \code setHead(QCPLineEnding::esSpikeArrow) \endcode - + \see setTail */ void QCPItemLine::setHead(const QCPLineEnding &head) { - mHead = head; + mHead = head; } /*! Sets the line ending style of the tail. The tail corresponds to the \a start position. - + Note that due to the overloaded QCPLineEnding constructor, you may directly specify a QCPLineEnding::EndingStyle here, e.g. \code setTail(QCPLineEnding::esSpikeArrow) \endcode - + \see setHead */ void QCPItemLine::setTail(const QCPLineEnding &tail) { - mTail = tail; + mTail = tail; } /* inherits documentation from base class */ double QCPItemLine::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { - Q_UNUSED(details) - if (onlySelectable && !mSelectable) - return -1; - - return qSqrt(QCPVector2D(pos).distanceSquaredToLine(start->pixelPosition(), end->pixelPosition())); + Q_UNUSED(details) + if (onlySelectable && !mSelectable) { + return -1; + } + + return qSqrt(QCPVector2D(pos).distanceSquaredToLine(start->pixelPosition(), end->pixelPosition())); } /* inherits documentation from base class */ void QCPItemLine::draw(QCPPainter *painter) { - 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()); - clipPad = qMax(clipPad, (double)mainPen().widthF()); - QLineF line = getRectClippedLine(startVec, endVec, clipRect().adjusted(-clipPad, -clipPad, clipPad, clipPad)); - // paint visible segment, if existent: - if (!line.isNull()) - { - painter->setPen(mainPen()); - painter->drawLine(line); - painter->setBrush(Qt::SolidPattern); - if (mTail.style() != QCPLineEnding::esNone) - mTail.draw(painter, startVec, startVec-endVec); - if (mHead.style() != QCPLineEnding::esNone) - mHead.draw(painter, endVec, endVec-startVec); - } + 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()); + clipPad = qMax(clipPad, (double)mainPen().widthF()); + QLineF line = getRectClippedLine(startVec, endVec, clipRect().adjusted(-clipPad, -clipPad, clipPad, clipPad)); + // paint visible segment, if existent: + if (!line.isNull()) { + painter->setPen(mainPen()); + painter->drawLine(line); + painter->setBrush(Qt::SolidPattern); + if (mTail.style() != QCPLineEnding::esNone) { + mTail.draw(painter, startVec, startVec - endVec); + } + if (mHead.style() != QCPLineEnding::esNone) { + mHead.draw(painter, endVec, endVec - startVec); + } + } } /*! \internal Returns the section of the line defined by \a start and \a end, that is visible in the specified \a rect. - + This is a helper function for \ref draw. */ 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()); - - QCPVector2D base = start; - QCPVector2D vec = end-start; - double bx, by; - double gamma, mu; - QLineF result; - QList pointVectors; + 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()); + } - if (!qFuzzyIsNull(vec.y())) // line is not horizontal - { - // check top of rect: - bx = rect.left(); - by = rect.top(); - mu = (by-base.y())/vec.y(); - if (mu >= 0 && mu <= 1) - { - gamma = base.x()-bx + mu*vec.x(); - if (gamma >= 0 && gamma <= rect.width()) - pointVectors.append(QCPVector2D(bx+gamma, by)); - } - // check bottom of rect: - bx = rect.left(); - by = rect.bottom(); - mu = (by-base.y())/vec.y(); - if (mu >= 0 && mu <= 1) - { - gamma = base.x()-bx + mu*vec.x(); - if (gamma >= 0 && gamma <= rect.width()) - pointVectors.append(QCPVector2D(bx+gamma, by)); - } - } - if (!qFuzzyIsNull(vec.x())) // line is not vertical - { - // check left of rect: - bx = rect.left(); - by = rect.top(); - mu = (bx-base.x())/vec.x(); - if (mu >= 0 && mu <= 1) - { - gamma = base.y()-by + mu*vec.y(); - if (gamma >= 0 && gamma <= rect.height()) - pointVectors.append(QCPVector2D(bx, by+gamma)); - } - // check right of rect: - bx = rect.right(); - by = rect.top(); - mu = (bx-base.x())/vec.x(); - if (mu >= 0 && mu <= 1) - { - gamma = base.y()-by + mu*vec.y(); - if (gamma >= 0 && gamma <= rect.height()) - pointVectors.append(QCPVector2D(bx, by+gamma)); - } - } - - if (containsStart) - pointVectors.append(start); - if (containsEnd) - pointVectors.append(end); - - // evaluate points: - if (pointVectors.size() == 2) - { - result.setPoints(pointVectors.at(0).toPointF(), pointVectors.at(1).toPointF()); - } else if (pointVectors.size() > 2) - { - // line probably goes through corner of rect, and we got two points there. single out the point pair with greatest distance: - double distSqrMax = 0; - QCPVector2D pv1, pv2; - for (int i=0; i distSqrMax) - { - pv1 = pointVectors.at(i); - pv2 = pointVectors.at(k); - distSqrMax = distSqr; + QCPVector2D base = start; + QCPVector2D vec = end - start; + double bx, by; + double gamma, mu; + QLineF result; + QList pointVectors; + + if (!qFuzzyIsNull(vec.y())) { // line is not horizontal + // check top of rect: + bx = rect.left(); + by = rect.top(); + mu = (by - base.y()) / vec.y(); + if (mu >= 0 && mu <= 1) { + gamma = base.x() - bx + mu * vec.x(); + if (gamma >= 0 && gamma <= rect.width()) { + pointVectors.append(QCPVector2D(bx + gamma, by)); + } + } + // check bottom of rect: + bx = rect.left(); + by = rect.bottom(); + mu = (by - base.y()) / vec.y(); + if (mu >= 0 && mu <= 1) { + gamma = base.x() - bx + mu * vec.x(); + if (gamma >= 0 && gamma <= rect.width()) { + pointVectors.append(QCPVector2D(bx + gamma, by)); + } } - } } - result.setPoints(pv1.toPointF(), pv2.toPointF()); - } - return result; + if (!qFuzzyIsNull(vec.x())) { // line is not vertical + // check left of rect: + bx = rect.left(); + by = rect.top(); + mu = (bx - base.x()) / vec.x(); + if (mu >= 0 && mu <= 1) { + gamma = base.y() - by + mu * vec.y(); + if (gamma >= 0 && gamma <= rect.height()) { + pointVectors.append(QCPVector2D(bx, by + gamma)); + } + } + // check right of rect: + bx = rect.right(); + by = rect.top(); + mu = (bx - base.x()) / vec.x(); + if (mu >= 0 && mu <= 1) { + gamma = base.y() - by + mu * vec.y(); + if (gamma >= 0 && gamma <= rect.height()) { + pointVectors.append(QCPVector2D(bx, by + gamma)); + } + } + } + + if (containsStart) { + pointVectors.append(start); + } + if (containsEnd) { + pointVectors.append(end); + } + + // evaluate points: + if (pointVectors.size() == 2) { + result.setPoints(pointVectors.at(0).toPointF(), pointVectors.at(1).toPointF()); + } else if (pointVectors.size() > 2) { + // line probably goes through corner of rect, and we got two points there. single out the point pair with greatest distance: + double distSqrMax = 0; + QCPVector2D pv1, pv2; + for (int i = 0; i < pointVectors.size() - 1; ++i) { + for (int k = i + 1; k < pointVectors.size(); ++k) { + double distSqr = (pointVectors.at(i) - pointVectors.at(k)).lengthSquared(); + if (distSqr > distSqrMax) { + pv1 = pointVectors.at(i); + pv2 = pointVectors.at(k); + distSqrMax = distSqr; + } + } + } + result.setPoints(pv1.toPointF(), pv2.toPointF()); + } + return result; } /*! \internal @@ -28466,7 +28778,7 @@ QLineF QCPItemLine::getRectClippedLine(const QCPVector2D &start, const QCPVector */ QPen QCPItemLine::mainPen() const { - return mSelected ? mSelectedPen : mPen; + return mSelected ? mSelectedPen : mPen; } /* end of 'src/items/item-line.cpp' */ @@ -28486,10 +28798,10 @@ QPen QCPItemLine::mainPen() const It has four positions, \a start and \a end, which define the end points of the line, and two control points which define the direction the line exits from the start and the direction from which it approaches the end: \a startDir and \a endDir. - + With \ref setHead and \ref setTail you may set different line ending styles, e.g. to create an arrow. - + Often it is desirable for the control points to stay at fixed relative positions to the start/end point. This can be achieved by setting the parent anchor e.g. of \a startDir simply to \a start, and then specify the desired pixel offset with QCPItemPosition::setCoords on \a startDir. @@ -28497,24 +28809,24 @@ QPen QCPItemLine::mainPen() const /*! Creates a curve item and sets default values. - + 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. */ QCPItemCurve::QCPItemCurve(QCustomPlot *parentPlot) : - QCPAbstractItem(parentPlot), - start(createPosition(QLatin1String("start"))), - startDir(createPosition(QLatin1String("startDir"))), - endDir(createPosition(QLatin1String("endDir"))), - end(createPosition(QLatin1String("end"))) + QCPAbstractItem(parentPlot), + start(createPosition(QLatin1String("start"))), + startDir(createPosition(QLatin1String("startDir"))), + endDir(createPosition(QLatin1String("endDir"))), + end(createPosition(QLatin1String("end"))) { - start->setCoords(0, 0); - startDir->setCoords(0.5, 0); - endDir->setCoords(0, 0.5); - end->setCoords(1, 1); - - setPen(QPen(Qt::black)); - setSelectedPen(QPen(Qt::blue,2)); + start->setCoords(0, 0); + startDir->setCoords(0.5, 0); + endDir->setCoords(0, 0.5); + end->setCoords(1, 1); + + setPen(QPen(Qt::black)); + setSelectedPen(QPen(Qt::blue, 2)); } QCPItemCurve::~QCPItemCurve() @@ -28523,108 +28835,113 @@ QCPItemCurve::~QCPItemCurve() /*! Sets the pen that will be used to draw the line - + \see setSelectedPen */ void QCPItemCurve::setPen(const QPen &pen) { - mPen = pen; + mPen = pen; } /*! Sets the pen that will be used to draw the line when selected - + \see setPen, setSelected */ void QCPItemCurve::setSelectedPen(const QPen &pen) { - mSelectedPen = pen; + mSelectedPen = pen; } /*! Sets the line ending style of the head. The head corresponds to the \a end position. - + Note that due to the overloaded QCPLineEnding constructor, you may directly specify a QCPLineEnding::EndingStyle here, e.g. \code setHead(QCPLineEnding::esSpikeArrow) \endcode - + \see setTail */ void QCPItemCurve::setHead(const QCPLineEnding &head) { - mHead = head; + mHead = head; } /*! Sets the line ending style of the tail. The tail corresponds to the \a start position. - + Note that due to the overloaded QCPLineEnding constructor, you may directly specify a QCPLineEnding::EndingStyle here, e.g. \code setTail(QCPLineEnding::esSpikeArrow) \endcode - + \see setHead */ void QCPItemCurve::setTail(const QCPLineEnding &tail) { - mTail = tail; + mTail = tail; } /* inherits documentation from base class */ double QCPItemCurve::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { - Q_UNUSED(details) - if (onlySelectable && !mSelectable) - return -1; - - QPointF startVec(start->pixelPosition()); - QPointF startDirVec(startDir->pixelPosition()); - QPointF endDirVec(endDir->pixelPosition()); - QPointF endVec(end->pixelPosition()); + Q_UNUSED(details) + if (onlySelectable && !mSelectable) { + return -1; + } - QPainterPath cubicPath(startVec); - cubicPath.cubicTo(startDirVec, endDirVec, endVec); - - QList polygons = cubicPath.toSubpathPolygons(); - if (polygons.isEmpty()) - return -1; - const QPolygonF polygon = polygons.first(); - QCPVector2D p(pos); - double minDistSqr = (std::numeric_limits::max)(); - for (int i=1; ipixelPosition()); + QPointF startDirVec(startDir->pixelPosition()); + QPointF endDirVec(endDir->pixelPosition()); + QPointF endVec(end->pixelPosition()); + + QPainterPath cubicPath(startVec); + cubicPath.cubicTo(startDirVec, endDirVec, endVec); + + QList polygons = cubicPath.toSubpathPolygons(); + if (polygons.isEmpty()) { + return -1; + } + const QPolygonF polygon = polygons.first(); + QCPVector2D p(pos); + double minDistSqr = (std::numeric_limits::max)(); + for (int i = 1; i < polygon.size(); ++i) { + double distSqr = p.distanceSquaredToLine(polygon.at(i - 1), polygon.at(i)); + if (distSqr < minDistSqr) { + minDistSqr = distSqr; + } + } + return qSqrt(minDistSqr); } /* inherits documentation from base class */ void QCPItemCurve::draw(QCPPainter *painter) { - 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; + 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.toPointF()); - cubicPath.cubicTo(startDirVec.toPointF(), endDirVec.toPointF(), endVec.toPointF()); + 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()); - QRect cubicRect = cubicPath.controlPointRect().toRect(); - if (cubicRect.isEmpty()) // may happen when start and end exactly on same x or y position - cubicRect.adjust(0, 0, 1, 1); - if (clip.intersects(cubicRect)) - { - painter->setPen(mainPen()); - painter->drawPath(cubicPath); - painter->setBrush(Qt::SolidPattern); - if (mTail.style() != QCPLineEnding::esNone) - mTail.draw(painter, startVec, M_PI-cubicPath.angleAtPercent(0)/180.0*M_PI); - if (mHead.style() != QCPLineEnding::esNone) - mHead.draw(painter, endVec, -cubicPath.angleAtPercent(1)/180.0*M_PI); - } + // paint visible segment, if existent: + QRect clip = clipRect().adjusted(-mainPen().widthF(), -mainPen().widthF(), mainPen().widthF(), mainPen().widthF()); + QRect cubicRect = cubicPath.controlPointRect().toRect(); + if (cubicRect.isEmpty()) { // may happen when start and end exactly on same x or y position + cubicRect.adjust(0, 0, 1, 1); + } + if (clip.intersects(cubicRect)) { + painter->setPen(mainPen()); + painter->drawPath(cubicPath); + painter->setBrush(Qt::SolidPattern); + if (mTail.style() != QCPLineEnding::esNone) { + mTail.draw(painter, startVec, M_PI - cubicPath.angleAtPercent(0) / 180.0 * M_PI); + } + if (mHead.style() != QCPLineEnding::esNone) { + mHead.draw(painter, endVec, -cubicPath.angleAtPercent(1) / 180.0 * M_PI); + } + } } /*! \internal @@ -28634,7 +28951,7 @@ void QCPItemCurve::draw(QCPPainter *painter) */ QPen QCPItemCurve::mainPen() const { - return mSelected ? mSelectedPen : mPen; + return mSelected ? mSelectedPen : mPen; } /* end of 'src/items/item-curve.cpp' */ @@ -28656,28 +28973,28 @@ QPen QCPItemCurve::mainPen() const /*! Creates a rectangle item and sets default values. - + 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), - topLeft(createPosition(QLatin1String("topLeft"))), - bottomRight(createPosition(QLatin1String("bottomRight"))), - top(createAnchor(QLatin1String("top"), aiTop)), - topRight(createAnchor(QLatin1String("topRight"), aiTopRight)), - right(createAnchor(QLatin1String("right"), aiRight)), - bottom(createAnchor(QLatin1String("bottom"), aiBottom)), - bottomLeft(createAnchor(QLatin1String("bottomLeft"), aiBottomLeft)), - left(createAnchor(QLatin1String("left"), aiLeft)) + QCPAbstractItem(parentPlot), + topLeft(createPosition(QLatin1String("topLeft"))), + bottomRight(createPosition(QLatin1String("bottomRight"))), + top(createAnchor(QLatin1String("top"), aiTop)), + topRight(createAnchor(QLatin1String("topRight"), aiTopRight)), + right(createAnchor(QLatin1String("right"), aiRight)), + bottom(createAnchor(QLatin1String("bottom"), aiBottom)), + bottomLeft(createAnchor(QLatin1String("bottomLeft"), aiBottomLeft)), + left(createAnchor(QLatin1String("left"), aiLeft)) { - topLeft->setCoords(0, 1); - bottomRight->setCoords(1, 0); - - setPen(QPen(Qt::black)); - setSelectedPen(QPen(Qt::blue,2)); - setBrush(Qt::NoBrush); - setSelectedBrush(Qt::NoBrush); + topLeft->setCoords(0, 1); + bottomRight->setCoords(1, 0); + + setPen(QPen(Qt::black)); + setSelectedPen(QPen(Qt::blue, 2)); + setBrush(Qt::NoBrush); + setSelectedBrush(Qt::NoBrush); } QCPItemRect::~QCPItemRect() @@ -28686,92 +29003,98 @@ QCPItemRect::~QCPItemRect() /*! Sets the pen that will be used to draw the line of the rectangle - + \see setSelectedPen, setBrush */ void QCPItemRect::setPen(const QPen &pen) { - mPen = pen; + mPen = pen; } /*! Sets the pen that will be used to draw the line of the rectangle when selected - + \see setPen, setSelected */ void QCPItemRect::setSelectedPen(const QPen &pen) { - mSelectedPen = pen; + mSelectedPen = pen; } /*! Sets the brush that will be used to fill the rectangle. To disable filling, set \a brush to Qt::NoBrush. - + \see setSelectedBrush, setPen */ void QCPItemRect::setBrush(const QBrush &brush) { - mBrush = brush; + mBrush = brush; } /*! Sets the brush that will be used to fill the rectangle when selected. To disable filling, set \a brush to Qt::NoBrush. - + \see setBrush */ void QCPItemRect::setSelectedBrush(const QBrush &brush) { - mSelectedBrush = brush; + mSelectedBrush = brush; } /* inherits documentation from base class */ double QCPItemRect::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { - Q_UNUSED(details) - if (onlySelectable && !mSelectable) - return -1; - - QRectF rect = QRectF(topLeft->pixelPosition(), bottomRight->pixelPosition()).normalized(); - bool filledRect = mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0; - return rectDistance(rect, pos, filledRect); + Q_UNUSED(details) + if (onlySelectable && !mSelectable) { + return -1; + } + + QRectF rect = QRectF(topLeft->pixelPosition(), bottomRight->pixelPosition()).normalized(); + bool filledRect = mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0; + return rectDistance(rect, pos, filledRect); } /* inherits documentation from base class */ void QCPItemRect::draw(QCPPainter *painter) { - QPointF p1 = topLeft->pixelPosition(); - QPointF p2 = bottomRight->pixelPosition(); - if (p1.toPoint() == p2.toPoint()) - return; - QRectF rect = QRectF(p1, p2).normalized(); - double clipPad = mainPen().widthF(); - QRectF boundingRect = rect.adjusted(-clipPad, -clipPad, clipPad, clipPad); - if (boundingRect.intersects(clipRect())) // only draw if bounding rect of rect item is visible in cliprect - { - painter->setPen(mainPen()); - painter->setBrush(mainBrush()); - painter->drawRect(rect); - } + QPointF p1 = topLeft->pixelPosition(); + QPointF p2 = bottomRight->pixelPosition(); + if (p1.toPoint() == p2.toPoint()) { + return; + } + QRectF rect = QRectF(p1, p2).normalized(); + double clipPad = mainPen().widthF(); + QRectF boundingRect = rect.adjusted(-clipPad, -clipPad, clipPad, clipPad); + if (boundingRect.intersects(clipRect())) { // only draw if bounding rect of rect item is visible in cliprect + painter->setPen(mainPen()); + painter->setBrush(mainBrush()); + painter->drawRect(rect); + } } /* inherits documentation from base class */ QPointF QCPItemRect::anchorPixelPosition(int anchorId) const { - QRectF rect = QRectF(topLeft->pixelPosition(), bottomRight->pixelPosition()); - switch (anchorId) - { - case aiTop: return (rect.topLeft()+rect.topRight())*0.5; - case aiTopRight: return rect.topRight(); - case aiRight: return (rect.topRight()+rect.bottomRight())*0.5; - case aiBottom: return (rect.bottomLeft()+rect.bottomRight())*0.5; - case aiBottomLeft: return rect.bottomLeft(); - case aiLeft: return (rect.topLeft()+rect.bottomLeft())*0.5; - } - - qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId; - return QPointF(); + QRectF rect = QRectF(topLeft->pixelPosition(), bottomRight->pixelPosition()); + switch (anchorId) { + case aiTop: + return (rect.topLeft() + rect.topRight()) * 0.5; + case aiTopRight: + return rect.topRight(); + case aiRight: + return (rect.topRight() + rect.bottomRight()) * 0.5; + case aiBottom: + return (rect.bottomLeft() + rect.bottomRight()) * 0.5; + case aiBottomLeft: + return rect.bottomLeft(); + case aiLeft: + return (rect.topLeft() + rect.bottomLeft()) * 0.5; + } + + qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId; + return QPointF(); } /*! \internal @@ -28781,7 +29104,7 @@ QPointF QCPItemRect::anchorPixelPosition(int anchorId) const */ QPen QCPItemRect::mainPen() const { - return mSelected ? mSelectedPen : mPen; + return mSelected ? mSelectedPen : mPen; } /*! \internal @@ -28791,7 +29114,7 @@ QPen QCPItemRect::mainPen() const */ QBrush QCPItemRect::mainBrush() const { - return mSelected ? mSelectedBrush : mBrush; + return mSelected ? mSelectedBrush : mBrush; } /* end of 'src/items/item-rect.cpp' */ @@ -28810,43 +29133,43 @@ QBrush QCPItemRect::mainBrush() const Its position is defined by the member \a position and the setting of \ref setPositionAlignment. The latter controls which part of the text rect shall be aligned with \a position. - + The text alignment itself (i.e. left, center, right) can be controlled with \ref setTextAlignment. - + The text may be rotated around the \a position point with \ref setRotation. */ /*! Creates a text item and sets default values. - + 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), - position(createPosition(QLatin1String("position"))), - topLeft(createAnchor(QLatin1String("topLeft"), aiTopLeft)), - top(createAnchor(QLatin1String("top"), aiTop)), - topRight(createAnchor(QLatin1String("topRight"), aiTopRight)), - right(createAnchor(QLatin1String("right"), aiRight)), - bottomRight(createAnchor(QLatin1String("bottomRight"), aiBottomRight)), - bottom(createAnchor(QLatin1String("bottom"), aiBottom)), - bottomLeft(createAnchor(QLatin1String("bottomLeft"), aiBottomLeft)), - left(createAnchor(QLatin1String("left"), aiLeft)), - mText(QLatin1String("text")), - mPositionAlignment(Qt::AlignCenter), - mTextAlignment(Qt::AlignTop|Qt::AlignHCenter), - mRotation(0) + QCPAbstractItem(parentPlot), + position(createPosition(QLatin1String("position"))), + topLeft(createAnchor(QLatin1String("topLeft"), aiTopLeft)), + top(createAnchor(QLatin1String("top"), aiTop)), + topRight(createAnchor(QLatin1String("topRight"), aiTopRight)), + right(createAnchor(QLatin1String("right"), aiRight)), + bottomRight(createAnchor(QLatin1String("bottomRight"), aiBottomRight)), + bottom(createAnchor(QLatin1String("bottom"), aiBottom)), + bottomLeft(createAnchor(QLatin1String("bottomLeft"), aiBottomLeft)), + left(createAnchor(QLatin1String("left"), aiLeft)), + mText(QLatin1String("text")), + mPositionAlignment(Qt::AlignCenter), + mTextAlignment(Qt::AlignTop | Qt::AlignHCenter), + mRotation(0) { - position->setCoords(0, 0); - - setPen(Qt::NoPen); - setSelectedPen(Qt::NoPen); - setBrush(Qt::NoBrush); - setSelectedBrush(Qt::NoBrush); - setColor(Qt::black); - setSelectedColor(Qt::blue); + position->setCoords(0, 0); + + setPen(Qt::NoPen); + setSelectedPen(Qt::NoPen); + setBrush(Qt::NoBrush); + setSelectedBrush(Qt::NoBrush); + setColor(Qt::black); + setSelectedColor(Qt::blue); } QCPItemText::~QCPItemText() @@ -28858,7 +29181,7 @@ QCPItemText::~QCPItemText() */ void QCPItemText::setColor(const QColor &color) { - mColor = color; + mColor = color; } /*! @@ -28866,99 +29189,99 @@ void QCPItemText::setColor(const QColor &color) */ void QCPItemText::setSelectedColor(const QColor &color) { - mSelectedColor = color; + mSelectedColor = color; } /*! Sets the pen that will be used do draw a rectangular border around the text. To disable the border, set \a pen to Qt::NoPen. - + \see setSelectedPen, setBrush, setPadding */ void QCPItemText::setPen(const QPen &pen) { - mPen = pen; + mPen = pen; } /*! Sets the pen that will be used do draw a rectangular border around the text, when the item is selected. To disable the border, set \a pen to Qt::NoPen. - + \see setPen */ void QCPItemText::setSelectedPen(const QPen &pen) { - mSelectedPen = pen; + mSelectedPen = pen; } /*! Sets the brush that will be used do fill the background of the text. To disable the background, set \a brush to Qt::NoBrush. - + \see setSelectedBrush, setPen, setPadding */ void QCPItemText::setBrush(const QBrush &brush) { - mBrush = brush; + mBrush = brush; } /*! Sets the brush that will be used do fill the background of the text, when the item is selected. To disable the background, set \a brush to Qt::NoBrush. - + \see setBrush */ void QCPItemText::setSelectedBrush(const QBrush &brush) { - mSelectedBrush = brush; + mSelectedBrush = brush; } /*! Sets the font of the text. - + \see setSelectedFont, setColor */ void QCPItemText::setFont(const QFont &font) { - mFont = font; + mFont = font; } /*! Sets the font of the text that will be used when the item is selected. - + \see setFont */ void QCPItemText::setSelectedFont(const QFont &font) { - mSelectedFont = font; + mSelectedFont = font; } /*! Sets the text that will be displayed. Multi-line texts are supported by inserting a line break character, e.g. '\n'. - + \see setFont, setColor, setTextAlignment */ void QCPItemText::setText(const QString &text) { - mText = text; + mText = text; } /*! Sets which point of the text rect shall be aligned with \a position. - + Examples: \li If \a alignment is Qt::AlignHCenter | Qt::AlignTop, the text will be positioned such that the top of the text rect will be horizontally centered on \a position. \li If \a alignment is Qt::AlignLeft | Qt::AlignBottom, \a position will indicate the bottom left corner of the text rect. - + If you want to control the alignment of (multi-lined) text within the text rect, use \ref setTextAlignment. */ void QCPItemText::setPositionAlignment(Qt::Alignment alignment) { - mPositionAlignment = alignment; + mPositionAlignment = alignment; } /*! @@ -28966,7 +29289,7 @@ void QCPItemText::setPositionAlignment(Qt::Alignment alignment) */ void QCPItemText::setTextAlignment(Qt::Alignment alignment) { - mTextAlignment = alignment; + mTextAlignment = alignment; } /*! @@ -28975,7 +29298,7 @@ void QCPItemText::setTextAlignment(Qt::Alignment alignment) */ void QCPItemText::setRotation(double degrees) { - mRotation = degrees; + mRotation = degrees; } /*! @@ -28984,122 +29307,133 @@ void QCPItemText::setRotation(double degrees) */ void QCPItemText::setPadding(const QMargins &padding) { - mPadding = padding; + mPadding = padding; } /* inherits documentation from base class */ double QCPItemText::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { - Q_UNUSED(details) - if (onlySelectable && !mSelectable) - 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 rectDistance function for non-rotated rects: - QPointF positionPixels(position->pixelPosition()); - QTransform inputTransform; - inputTransform.translate(positionPixels.x(), positionPixels.y()); - inputTransform.rotate(-mRotation); - inputTransform.translate(-positionPixels.x(), -positionPixels.y()); - QPointF rotatedPos = inputTransform.map(pos); - QFontMetrics fontMetrics(mFont); - QRect textRect = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip|mTextAlignment, mText); - QRect textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom()); - QPointF textPos = getTextDrawPoint(positionPixels, textBoxRect, mPositionAlignment); - textBoxRect.moveTopLeft(textPos.toPoint()); + Q_UNUSED(details) + if (onlySelectable && !mSelectable) { + return -1; + } - return rectDistance(textBoxRect, rotatedPos, true); + // The rect may be rotated, so we transform the actual clicked pos to the rotated + // 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); + inputTransform.translate(-positionPixels.x(), -positionPixels.y()); + QPointF rotatedPos = inputTransform.map(pos); + QFontMetrics fontMetrics(mFont); + QRect textRect = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip | mTextAlignment, mText); + QRect textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom()); + QPointF textPos = getTextDrawPoint(positionPixels, textBoxRect, mPositionAlignment); + textBoxRect.moveTopLeft(textPos.toPoint()); + + return rectDistance(textBoxRect, rotatedPos, true); } /* inherits documentation from base class */ void QCPItemText::draw(QCPPainter *painter) { - QPointF pos(position->pixelPosition()); - QTransform transform = painter->transform(); - transform.translate(pos.x(), pos.y()); - if (!qFuzzyIsNull(mRotation)) - transform.rotate(mRotation); - painter->setFont(mainFont()); - QRect textRect = painter->fontMetrics().boundingRect(0, 0, 0, 0, Qt::TextDontClip|mTextAlignment, mText); - QRect textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom()); - QPointF textPos = getTextDrawPoint(QPointF(0, 0), textBoxRect, mPositionAlignment); // 0, 0 because the transform does the translation - textRect.moveTopLeft(textPos.toPoint()+QPoint(mPadding.left(), mPadding.top())); - textBoxRect.moveTopLeft(textPos.toPoint()); - double clipPad = mainPen().widthF(); - QRect boundingRect = textBoxRect.adjusted(-clipPad, -clipPad, clipPad, clipPad); - if (transform.mapRect(boundingRect).intersects(painter->transform().mapRect(clipRect()))) - { - painter->setTransform(transform); - if ((mainBrush().style() != Qt::NoBrush && mainBrush().color().alpha() != 0) || - (mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0)) - { - painter->setPen(mainPen()); - painter->setBrush(mainBrush()); - painter->drawRect(textBoxRect); + QPointF pos(position->pixelPosition()); + QTransform transform = painter->transform(); + transform.translate(pos.x(), pos.y()); + if (!qFuzzyIsNull(mRotation)) { + transform.rotate(mRotation); + } + painter->setFont(mainFont()); + QRect textRect = painter->fontMetrics().boundingRect(0, 0, 0, 0, Qt::TextDontClip | mTextAlignment, mText); + QRect textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom()); + QPointF textPos = getTextDrawPoint(QPointF(0, 0), textBoxRect, mPositionAlignment); // 0, 0 because the transform does the translation + textRect.moveTopLeft(textPos.toPoint() + QPoint(mPadding.left(), mPadding.top())); + textBoxRect.moveTopLeft(textPos.toPoint()); + double clipPad = mainPen().widthF(); + QRect boundingRect = textBoxRect.adjusted(-clipPad, -clipPad, clipPad, clipPad); + if (transform.mapRect(boundingRect).intersects(painter->transform().mapRect(clipRect()))) { + painter->setTransform(transform); + if ((mainBrush().style() != Qt::NoBrush && mainBrush().color().alpha() != 0) || + (mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0)) { + painter->setPen(mainPen()); + painter->setBrush(mainBrush()); + painter->drawRect(textBoxRect); + } + painter->setBrush(Qt::NoBrush); + painter->setPen(QPen(mainColor())); + painter->drawText(textRect, Qt::TextDontClip | mTextAlignment, mText); } - painter->setBrush(Qt::NoBrush); - painter->setPen(QPen(mainColor())); - painter->drawText(textRect, Qt::TextDontClip|mTextAlignment, mText); - } } /* inherits documentation from base class */ QPointF QCPItemText::anchorPixelPosition(int anchorId) const { - // get actual rect points (pretty much copied from draw function): - QPointF pos(position->pixelPosition()); - QTransform transform; - transform.translate(pos.x(), pos.y()); - if (!qFuzzyIsNull(mRotation)) - transform.rotate(mRotation); - QFontMetrics fontMetrics(mainFont()); - QRect textRect = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip|mTextAlignment, mText); - QRectF textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom()); - QPointF textPos = getTextDrawPoint(QPointF(0, 0), textBoxRect, mPositionAlignment); // 0, 0 because the transform does the translation - textBoxRect.moveTopLeft(textPos.toPoint()); - QPolygonF rectPoly = transform.map(QPolygonF(textBoxRect)); - - switch (anchorId) - { - case aiTopLeft: return rectPoly.at(0); - case aiTop: return (rectPoly.at(0)+rectPoly.at(1))*0.5; - case aiTopRight: return rectPoly.at(1); - case aiRight: return (rectPoly.at(1)+rectPoly.at(2))*0.5; - case aiBottomRight: return rectPoly.at(2); - case aiBottom: return (rectPoly.at(2)+rectPoly.at(3))*0.5; - case aiBottomLeft: return rectPoly.at(3); - case aiLeft: return (rectPoly.at(3)+rectPoly.at(0))*0.5; - } - - qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId; - return QPointF(); + // get actual rect points (pretty much copied from draw function): + QPointF pos(position->pixelPosition()); + QTransform transform; + transform.translate(pos.x(), pos.y()); + if (!qFuzzyIsNull(mRotation)) { + transform.rotate(mRotation); + } + QFontMetrics fontMetrics(mainFont()); + QRect textRect = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip | mTextAlignment, mText); + QRectF textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom()); + QPointF textPos = getTextDrawPoint(QPointF(0, 0), textBoxRect, mPositionAlignment); // 0, 0 because the transform does the translation + textBoxRect.moveTopLeft(textPos.toPoint()); + QPolygonF rectPoly = transform.map(QPolygonF(textBoxRect)); + + switch (anchorId) { + case aiTopLeft: + return rectPoly.at(0); + case aiTop: + return (rectPoly.at(0) + rectPoly.at(1)) * 0.5; + case aiTopRight: + return rectPoly.at(1); + case aiRight: + return (rectPoly.at(1) + rectPoly.at(2)) * 0.5; + case aiBottomRight: + return rectPoly.at(2); + case aiBottom: + return (rectPoly.at(2) + rectPoly.at(3)) * 0.5; + case aiBottomLeft: + return rectPoly.at(3); + case aiLeft: + return (rectPoly.at(3) + rectPoly.at(0)) * 0.5; + } + + qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId; + return QPointF(); } /*! \internal - + Returns the point that must be given to the QPainter::drawText function (which expects the top left point of the text rect), according to the position \a pos, the text bounding box \a rect and the requested \a positionAlignment. - + For example, if \a positionAlignment is Qt::AlignLeft | Qt::AlignBottom the returned point will be shifted upward by the height of \a rect, starting from \a pos. So if the text is finally drawn at that point, the lower left corner of the resulting text rect is at \a pos. */ QPointF QCPItemText::getTextDrawPoint(const QPointF &pos, const QRectF &rect, Qt::Alignment positionAlignment) const { - if (positionAlignment == 0 || positionAlignment == (Qt::AlignLeft|Qt::AlignTop)) - return pos; - - QPointF result = pos; // start at top left - if (positionAlignment.testFlag(Qt::AlignHCenter)) - result.rx() -= rect.width()/2.0; - else if (positionAlignment.testFlag(Qt::AlignRight)) - result.rx() -= rect.width(); - if (positionAlignment.testFlag(Qt::AlignVCenter)) - result.ry() -= rect.height()/2.0; - else if (positionAlignment.testFlag(Qt::AlignBottom)) - result.ry() -= rect.height(); - return result; + if (positionAlignment == 0 || positionAlignment == (Qt::AlignLeft | Qt::AlignTop)) { + return pos; + } + + QPointF result = pos; // start at top left + if (positionAlignment.testFlag(Qt::AlignHCenter)) { + result.rx() -= rect.width() / 2.0; + } else if (positionAlignment.testFlag(Qt::AlignRight)) { + result.rx() -= rect.width(); + } + if (positionAlignment.testFlag(Qt::AlignVCenter)) { + result.ry() -= rect.height() / 2.0; + } else if (positionAlignment.testFlag(Qt::AlignBottom)) { + result.ry() -= rect.height(); + } + return result; } /*! \internal @@ -29109,7 +29443,7 @@ QPointF QCPItemText::getTextDrawPoint(const QPointF &pos, const QRectF &rect, Qt */ QFont QCPItemText::mainFont() const { - return mSelected ? mSelectedFont : mFont; + return mSelected ? mSelectedFont : mFont; } /*! \internal @@ -29119,7 +29453,7 @@ QFont QCPItemText::mainFont() const */ QColor QCPItemText::mainColor() const { - return mSelected ? mSelectedColor : mColor; + return mSelected ? mSelectedColor : mColor; } /*! \internal @@ -29129,7 +29463,7 @@ QColor QCPItemText::mainColor() const */ QPen QCPItemText::mainPen() const { - return mSelected ? mSelectedPen : mPen; + return mSelected ? mSelectedPen : mPen; } /*! \internal @@ -29139,7 +29473,7 @@ QPen QCPItemText::mainPen() const */ QBrush QCPItemText::mainBrush() const { - return mSelected ? mSelectedBrush : mBrush; + return mSelected ? mSelectedBrush : mBrush; } /* end of 'src/items/item-text.cpp' */ @@ -29161,31 +29495,31 @@ QBrush QCPItemText::mainBrush() const /*! Creates an ellipse item and sets default values. - + 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), - topLeft(createPosition(QLatin1String("topLeft"))), - bottomRight(createPosition(QLatin1String("bottomRight"))), - topLeftRim(createAnchor(QLatin1String("topLeftRim"), aiTopLeftRim)), - top(createAnchor(QLatin1String("top"), aiTop)), - topRightRim(createAnchor(QLatin1String("topRightRim"), aiTopRightRim)), - right(createAnchor(QLatin1String("right"), aiRight)), - bottomRightRim(createAnchor(QLatin1String("bottomRightRim"), aiBottomRightRim)), - bottom(createAnchor(QLatin1String("bottom"), aiBottom)), - bottomLeftRim(createAnchor(QLatin1String("bottomLeftRim"), aiBottomLeftRim)), - left(createAnchor(QLatin1String("left"), aiLeft)), - center(createAnchor(QLatin1String("center"), aiCenter)) + QCPAbstractItem(parentPlot), + topLeft(createPosition(QLatin1String("topLeft"))), + bottomRight(createPosition(QLatin1String("bottomRight"))), + topLeftRim(createAnchor(QLatin1String("topLeftRim"), aiTopLeftRim)), + top(createAnchor(QLatin1String("top"), aiTop)), + topRightRim(createAnchor(QLatin1String("topRightRim"), aiTopRightRim)), + right(createAnchor(QLatin1String("right"), aiRight)), + bottomRightRim(createAnchor(QLatin1String("bottomRightRim"), aiBottomRightRim)), + bottom(createAnchor(QLatin1String("bottom"), aiBottom)), + bottomLeftRim(createAnchor(QLatin1String("bottomLeftRim"), aiBottomLeftRim)), + left(createAnchor(QLatin1String("left"), aiLeft)), + center(createAnchor(QLatin1String("center"), aiCenter)) { - topLeft->setCoords(0, 1); - bottomRight->setCoords(1, 0); - - setPen(QPen(Qt::black)); - setSelectedPen(QPen(Qt::blue, 2)); - setBrush(Qt::NoBrush); - setSelectedBrush(Qt::NoBrush); + topLeft->setCoords(0, 1); + bottomRight->setCoords(1, 0); + + setPen(QPen(Qt::black)); + setSelectedPen(QPen(Qt::blue, 2)); + setBrush(Qt::NoBrush); + setSelectedBrush(Qt::NoBrush); } QCPItemEllipse::~QCPItemEllipse() @@ -29194,120 +29528,127 @@ QCPItemEllipse::~QCPItemEllipse() /*! Sets the pen that will be used to draw the line of the ellipse - + \see setSelectedPen, setBrush */ void QCPItemEllipse::setPen(const QPen &pen) { - mPen = pen; + mPen = pen; } /*! Sets the pen that will be used to draw the line of the ellipse when selected - + \see setPen, setSelected */ void QCPItemEllipse::setSelectedPen(const QPen &pen) { - mSelectedPen = pen; + mSelectedPen = pen; } /*! Sets the brush that will be used to fill the ellipse. To disable filling, set \a brush to Qt::NoBrush. - + \see setSelectedBrush, setPen */ void QCPItemEllipse::setBrush(const QBrush &brush) { - mBrush = brush; + mBrush = brush; } /*! Sets the brush that will be used to fill the ellipse when selected. To disable filling, set \a brush to Qt::NoBrush. - + \see setBrush */ void QCPItemEllipse::setSelectedBrush(const QBrush &brush) { - mSelectedBrush = brush; + mSelectedBrush = brush; } /* inherits documentation from base class */ double QCPItemEllipse::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { - Q_UNUSED(details) - if (onlySelectable && !mSelectable) - return -1; - - 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; - double x = pos.x()-center.x(); - double y = pos.y()-center.y(); - - // distance to border: - double c = 1.0/qSqrt(x*x/(a*a)+y*y/(b*b)); - 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) - { - if (x*x/(a*a) + y*y/(b*b) <= 1) - result = mParentPlot->selectionTolerance()*0.99; - } - return result; + Q_UNUSED(details) + if (onlySelectable && !mSelectable) { + return -1; + } + + 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; + double x = pos.x() - center.x(); + double y = pos.y() - center.y(); + + // distance to border: + double c = 1.0 / qSqrt(x * x / (a * a) + y * y / (b * b)); + 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) { + if (x * x / (a * a) + y * y / (b * b) <= 1) { + result = mParentPlot->selectionTolerance() * 0.99; + } + } + return result; } /* inherits documentation from base class */ void QCPItemEllipse::draw(QCPPainter *painter) { - QPointF p1 = topLeft->pixelPosition(); - QPointF p2 = bottomRight->pixelPosition(); - if (p1.toPoint() == p2.toPoint()) - return; - QRectF ellipseRect = QRectF(p1, p2).normalized(); - QRect clip = clipRect().adjusted(-mainPen().widthF(), -mainPen().widthF(), mainPen().widthF(), mainPen().widthF()); - if (ellipseRect.intersects(clip)) // only draw if bounding rect of ellipse is visible in cliprect - { - painter->setPen(mainPen()); - painter->setBrush(mainBrush()); -#ifdef __EXCEPTIONS - try // drawEllipse sometimes throws exceptions if ellipse is too big - { -#endif - painter->drawEllipse(ellipseRect); -#ifdef __EXCEPTIONS - } catch (...) - { - qDebug() << Q_FUNC_INFO << "Item too large for memory, setting invisible"; - setVisible(false); + QPointF p1 = topLeft->pixelPosition(); + QPointF p2 = bottomRight->pixelPosition(); + if (p1.toPoint() == p2.toPoint()) { + return; } + QRectF ellipseRect = QRectF(p1, p2).normalized(); + QRect clip = clipRect().adjusted(-mainPen().widthF(), -mainPen().widthF(), mainPen().widthF(), mainPen().widthF()); + if (ellipseRect.intersects(clip)) { // only draw if bounding rect of ellipse is visible in cliprect + painter->setPen(mainPen()); + painter->setBrush(mainBrush()); +#ifdef __EXCEPTIONS + try { // drawEllipse sometimes throws exceptions if ellipse is too big #endif - } + painter->drawEllipse(ellipseRect); +#ifdef __EXCEPTIONS + } catch (...) { + qDebug() << Q_FUNC_INFO << "Item too large for memory, setting invisible"; + setVisible(false); + } +#endif + } } /* inherits documentation from base class */ QPointF QCPItemEllipse::anchorPixelPosition(int anchorId) const { - QRectF rect = QRectF(topLeft->pixelPosition(), bottomRight->pixelPosition()); - switch (anchorId) - { - case aiTopLeftRim: return rect.center()+(rect.topLeft()-rect.center())*1/qSqrt(2); - case aiTop: return (rect.topLeft()+rect.topRight())*0.5; - case aiTopRightRim: return rect.center()+(rect.topRight()-rect.center())*1/qSqrt(2); - case aiRight: return (rect.topRight()+rect.bottomRight())*0.5; - case aiBottomRightRim: return rect.center()+(rect.bottomRight()-rect.center())*1/qSqrt(2); - case aiBottom: return (rect.bottomLeft()+rect.bottomRight())*0.5; - case aiBottomLeftRim: return rect.center()+(rect.bottomLeft()-rect.center())*1/qSqrt(2); - case aiLeft: return (rect.topLeft()+rect.bottomLeft())*0.5; - case aiCenter: return (rect.topLeft()+rect.bottomRight())*0.5; - } - - qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId; - return QPointF(); + QRectF rect = QRectF(topLeft->pixelPosition(), bottomRight->pixelPosition()); + switch (anchorId) { + case aiTopLeftRim: + return rect.center() + (rect.topLeft() - rect.center()) * 1 / qSqrt(2); + case aiTop: + return (rect.topLeft() + rect.topRight()) * 0.5; + case aiTopRightRim: + return rect.center() + (rect.topRight() - rect.center()) * 1 / qSqrt(2); + case aiRight: + return (rect.topRight() + rect.bottomRight()) * 0.5; + case aiBottomRightRim: + return rect.center() + (rect.bottomRight() - rect.center()) * 1 / qSqrt(2); + case aiBottom: + return (rect.bottomLeft() + rect.bottomRight()) * 0.5; + case aiBottomLeftRim: + return rect.center() + (rect.bottomLeft() - rect.center()) * 1 / qSqrt(2); + case aiLeft: + return (rect.topLeft() + rect.bottomLeft()) * 0.5; + case aiCenter: + return (rect.topLeft() + rect.bottomRight()) * 0.5; + } + + qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId; + return QPointF(); } /*! \internal @@ -29317,7 +29658,7 @@ QPointF QCPItemEllipse::anchorPixelPosition(int anchorId) const */ QPen QCPItemEllipse::mainPen() const { - return mSelected ? mSelectedPen : mPen; + return mSelected ? mSelectedPen : mPen; } /*! \internal @@ -29327,7 +29668,7 @@ QPen QCPItemEllipse::mainPen() const */ QBrush QCPItemEllipse::mainBrush() const { - return mSelected ? mSelectedBrush : mBrush; + return mSelected ? mSelectedBrush : mBrush; } /* end of 'src/items/item-ellipse.cpp' */ @@ -29347,7 +29688,7 @@ QBrush QCPItemEllipse::mainBrush() const It has two positions, \a topLeft and \a bottomRight, which define the rectangle the pixmap will be drawn in. Depending on the scale setting (\ref setScaled), the pixmap will be either scaled to fit the rectangle or be drawn aligned to the topLeft position. - + If scaling is enabled and \a topLeft is further to the bottom/right than \a bottomRight (as shown on the right side of the example image), the pixmap will be flipped in the respective orientations. @@ -29355,30 +29696,30 @@ QBrush QCPItemEllipse::mainBrush() const /*! Creates a rectangle item and sets default values. - + 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), - topLeft(createPosition(QLatin1String("topLeft"))), - bottomRight(createPosition(QLatin1String("bottomRight"))), - top(createAnchor(QLatin1String("top"), aiTop)), - topRight(createAnchor(QLatin1String("topRight"), aiTopRight)), - right(createAnchor(QLatin1String("right"), aiRight)), - bottom(createAnchor(QLatin1String("bottom"), aiBottom)), - bottomLeft(createAnchor(QLatin1String("bottomLeft"), aiBottomLeft)), - left(createAnchor(QLatin1String("left"), aiLeft)), - mScaled(false), - mScaledPixmapInvalidated(true), - mAspectRatioMode(Qt::KeepAspectRatio), - mTransformationMode(Qt::SmoothTransformation) + QCPAbstractItem(parentPlot), + topLeft(createPosition(QLatin1String("topLeft"))), + bottomRight(createPosition(QLatin1String("bottomRight"))), + top(createAnchor(QLatin1String("top"), aiTop)), + topRight(createAnchor(QLatin1String("topRight"), aiTopRight)), + right(createAnchor(QLatin1String("right"), aiRight)), + bottom(createAnchor(QLatin1String("bottom"), aiBottom)), + bottomLeft(createAnchor(QLatin1String("bottomLeft"), aiBottomLeft)), + 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)); + topLeft->setCoords(0, 1); + bottomRight->setCoords(1, 0); + + setPen(Qt::NoPen); + setSelectedPen(QPen(Qt::blue)); } QCPItemPixmap::~QCPItemPixmap() @@ -29390,10 +29731,11 @@ QCPItemPixmap::~QCPItemPixmap() */ void QCPItemPixmap::setPixmap(const QPixmap &pixmap) { - mPixmap = pixmap; - mScaledPixmapInvalidated = true; - if (mPixmap.isNull()) - qDebug() << Q_FUNC_INFO << "pixmap is null"; + mPixmap = pixmap; + mScaledPixmapInvalidated = true; + if (mPixmap.isNull()) { + qDebug() << Q_FUNC_INFO << "pixmap is null"; + } } /*! @@ -29402,192 +29744,199 @@ void QCPItemPixmap::setPixmap(const QPixmap &pixmap) */ void QCPItemPixmap::setScaled(bool scaled, Qt::AspectRatioMode aspectRatioMode, Qt::TransformationMode transformationMode) { - mScaled = scaled; - mAspectRatioMode = aspectRatioMode; - mTransformationMode = transformationMode; - mScaledPixmapInvalidated = true; + mScaled = scaled; + mAspectRatioMode = aspectRatioMode; + mTransformationMode = transformationMode; + mScaledPixmapInvalidated = true; } /*! Sets the pen that will be used to draw a border around the pixmap. - + \see setSelectedPen, setBrush */ void QCPItemPixmap::setPen(const QPen &pen) { - mPen = pen; + mPen = pen; } /*! Sets the pen that will be used to draw a border around the pixmap when selected - + \see setPen, setSelected */ void QCPItemPixmap::setSelectedPen(const QPen &pen) { - mSelectedPen = pen; + mSelectedPen = pen; } /* inherits documentation from base class */ double QCPItemPixmap::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { - Q_UNUSED(details) - if (onlySelectable && !mSelectable) - return -1; - - return rectDistance(getFinalRect(), pos, true); + Q_UNUSED(details) + if (onlySelectable && !mSelectable) { + return -1; + } + + return rectDistance(getFinalRect(), pos, true); } /* inherits documentation from base class */ void QCPItemPixmap::draw(QCPPainter *painter) { - bool flipHorz = false; - bool flipVert = false; - QRect rect = getFinalRect(&flipHorz, &flipVert); - double clipPad = mainPen().style() == Qt::NoPen ? 0 : mainPen().widthF(); - QRect boundingRect = rect.adjusted(-clipPad, -clipPad, clipPad, clipPad); - if (boundingRect.intersects(clipRect())) - { - updateScaledPixmap(rect, flipHorz, flipVert); - painter->drawPixmap(rect.topLeft(), mScaled ? mScaledPixmap : mPixmap); - QPen pen = mainPen(); - if (pen.style() != Qt::NoPen) - { - painter->setPen(pen); - painter->setBrush(Qt::NoBrush); - painter->drawRect(rect); + bool flipHorz = false; + bool flipVert = false; + QRect rect = getFinalRect(&flipHorz, &flipVert); + double clipPad = mainPen().style() == Qt::NoPen ? 0 : mainPen().widthF(); + QRect boundingRect = rect.adjusted(-clipPad, -clipPad, clipPad, clipPad); + if (boundingRect.intersects(clipRect())) { + updateScaledPixmap(rect, flipHorz, flipVert); + painter->drawPixmap(rect.topLeft(), mScaled ? mScaledPixmap : mPixmap); + QPen pen = mainPen(); + if (pen.style() != Qt::NoPen) { + painter->setPen(pen); + painter->setBrush(Qt::NoBrush); + painter->drawRect(rect); + } } - } } /* inherits documentation from base class */ QPointF QCPItemPixmap::anchorPixelPosition(int anchorId) const { - bool flipHorz; - bool flipVert; - QRect rect = getFinalRect(&flipHorz, &flipVert); - // we actually want denormal rects (negative width/height) here, so restore - // the flipped state: - if (flipHorz) - rect.adjust(rect.width(), 0, -rect.width(), 0); - if (flipVert) - rect.adjust(0, rect.height(), 0, -rect.height()); - - switch (anchorId) - { - case aiTop: return (rect.topLeft()+rect.topRight())*0.5; - case aiTopRight: return rect.topRight(); - case aiRight: return (rect.topRight()+rect.bottomRight())*0.5; - case aiBottom: return (rect.bottomLeft()+rect.bottomRight())*0.5; - case aiBottomLeft: return rect.bottomLeft(); - case aiLeft: return (rect.topLeft()+rect.bottomLeft())*0.5; - } - - qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId; - return QPointF(); + bool flipHorz; + bool flipVert; + QRect rect = getFinalRect(&flipHorz, &flipVert); + // we actually want denormal rects (negative width/height) here, so restore + // the flipped state: + if (flipHorz) { + rect.adjust(rect.width(), 0, -rect.width(), 0); + } + if (flipVert) { + rect.adjust(0, rect.height(), 0, -rect.height()); + } + + switch (anchorId) { + case aiTop: + return (rect.topLeft() + rect.topRight()) * 0.5; + case aiTopRight: + return rect.topRight(); + case aiRight: + return (rect.topRight() + rect.bottomRight()) * 0.5; + case aiBottom: + return (rect.bottomLeft() + rect.bottomRight()) * 0.5; + case aiBottomLeft: + return rect.bottomLeft(); + case aiLeft: + return (rect.topLeft() + rect.bottomLeft()) * 0.5; + } + + qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId; + return QPointF(); } /*! \internal - + Creates the buffered scaled image (\a mScaledPixmap) to fit the specified \a finalRect. The parameters \a flipHorz and \a flipVert control whether the resulting image shall be flipped horizontally or vertically. (This is used when \a topLeft is further to the bottom/right than \a bottomRight.) - + This function only creates the scaled pixmap when the buffered pixmap has a different size than the expected result, so calling this function repeatedly, e.g. in the \ref draw function, does not cause expensive rescaling every time. - + If scaling is disabled, sets mScaledPixmap to a null QPixmap. */ void QCPItemPixmap::updateScaledPixmap(QRect finalRect, bool flipHorz, bool flipVert) { - if (mPixmap.isNull()) - return; - - if (mScaled) - { -#ifdef QCP_DEVICEPIXELRATIO_SUPPORTED - double devicePixelRatio = mPixmap.devicePixelRatio(); -#else - double devicePixelRatio = 1.0; -#endif - if (finalRect.isNull()) - finalRect = getFinalRect(&flipHorz, &flipVert); - if (mScaledPixmapInvalidated || finalRect.size() != mScaledPixmap.size()/devicePixelRatio) - { - 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 + if (mPixmap.isNull()) { + return; } - } else if (!mScaledPixmap.isNull()) - mScaledPixmap = QPixmap(); - mScaledPixmapInvalidated = false; + + if (mScaled) { +#ifdef QCP_DEVICEPIXELRATIO_SUPPORTED + double devicePixelRatio = mPixmap.devicePixelRatio(); +#else + double devicePixelRatio = 1.0; +#endif + if (finalRect.isNull()) { + finalRect = getFinalRect(&flipHorz, &flipVert); + } + if (mScaledPixmapInvalidated || finalRect.size() != mScaledPixmap.size() / devicePixelRatio) { + 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 - + Returns the final (tight) rect the pixmap is drawn in, depending on the current item positions and scaling settings. - + The output parameters \a flippedHorz and \a flippedVert return whether the pixmap should be drawn flipped horizontally or vertically in the returned rect. (The returned rect itself is always normalized, i.e. the top left corner of the rect is actually further to the top/left than the bottom right corner). This is the case when the item position \a topLeft is further to the bottom/right than \a bottomRight. - + If scaling is disabled, returns a rect with size of the original pixmap and the top left corner aligned with the item position \a topLeft. The position \a bottomRight is ignored. */ QRect QCPItemPixmap::getFinalRect(bool *flippedHorz, bool *flippedVert) const { - QRect result; - bool flipHorz = false; - bool flipVert = false; - QPoint p1 = topLeft->pixelPosition().toPoint(); - QPoint p2 = bottomRight->pixelPosition().toPoint(); - if (p1 == p2) - return QRect(p1, QSize(0, 0)); - if (mScaled) - { - QSize newSize = QSize(p2.x()-p1.x(), p2.y()-p1.y()); - QPoint topLeft = p1; - if (newSize.width() < 0) - { - flipHorz = true; - newSize.rwidth() *= -1; - topLeft.setX(p2.x()); + QRect result; + bool flipHorz = false; + bool flipVert = false; + QPoint p1 = topLeft->pixelPosition().toPoint(); + QPoint p2 = bottomRight->pixelPosition().toPoint(); + if (p1 == p2) { + return QRect(p1, QSize(0, 0)); } - if (newSize.height() < 0) - { - flipVert = true; - newSize.rheight() *= -1; - topLeft.setY(p2.y()); + if (mScaled) { + QSize newSize = QSize(p2.x() - p1.x(), p2.y() - p1.y()); + QPoint topLeft = p1; + if (newSize.width() < 0) { + flipHorz = true; + newSize.rwidth() *= -1; + topLeft.setX(p2.x()); + } + if (newSize.height() < 0) { + flipVert = true; + newSize.rheight() *= -1; + 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 } - 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; - if (flippedVert) - *flippedVert = flipVert; - return result; + if (flippedHorz) { + *flippedHorz = flipHorz; + } + if (flippedVert) { + *flippedVert = flipVert; + } + return result; } /*! \internal @@ -29597,7 +29946,7 @@ QRect QCPItemPixmap::getFinalRect(bool *flippedHorz, bool *flippedVert) const */ QPen QCPItemPixmap::mainPen() const { - return mSelected ? mSelectedPen : mPen; + return mSelected ? mSelectedPen : mPen; } /* end of 'src/items/item-pixmap.cpp' */ @@ -29620,19 +29969,19 @@ QPen QCPItemPixmap::mainPen() const QCPGraph is connected, note that setting the coordinates of the tracer item directly via \a position will have no effect because they will be overriden in the next redraw (this is when the coordinate update happens). - + If the specified key in \ref setGraphKey is outside the key bounds of the graph, the tracer will stay at the corresponding end of the graph. - + With \ref setInterpolating you may specify whether the tracer may only stay exactly on data points or whether it interpolates data points linearly, if given a key that lies between two data points of the graph. - + The tracer has different visual styles, see \ref setStyle. It is also possible to make the tracer have no own visual appearance (set the style to \ref tsNone), and just connect other item positions to the tracer \a position (used as an anchor) via \ref 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 position coordinates of the tracer are retrieved, they will not reflect the updated data of the graph. In this case \ref @@ -29641,25 +29990,25 @@ QPen QCPItemPixmap::mainPen() const /*! Creates a tracer item and sets default values. - + 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"))), - mSize(6), - mStyle(tsCrosshair), - mGraph(0), - mGraphKey(0), - mInterpolating(false) + QCPAbstractItem(parentPlot), + position(createPosition(QLatin1String("position"))), + mSize(6), + mStyle(tsCrosshair), + mGraph(0), + mGraphKey(0), + mInterpolating(false) { - position->setCoords(0, 0); + position->setCoords(0, 0); - setBrush(Qt::NoBrush); - setSelectedBrush(Qt::NoBrush); - setPen(QPen(Qt::black)); - setSelectedPen(QPen(Qt::blue, 2)); + setBrush(Qt::NoBrush); + setSelectedBrush(Qt::NoBrush); + setPen(QPen(Qt::black)); + setSelectedPen(QPen(Qt::blue, 2)); } QCPItemTracer::~QCPItemTracer() @@ -29668,42 +30017,42 @@ QCPItemTracer::~QCPItemTracer() /*! Sets the pen that will be used to draw the line of the tracer - + \see setSelectedPen, setBrush */ void QCPItemTracer::setPen(const QPen &pen) { - mPen = pen; + mPen = pen; } /*! Sets the pen that will be used to draw the line of the tracer when selected - + \see setPen, setSelected */ void QCPItemTracer::setSelectedPen(const QPen &pen) { - mSelectedPen = pen; + mSelectedPen = pen; } /*! Sets the brush that will be used to draw any fills of the tracer - + \see setSelectedBrush, setPen */ void QCPItemTracer::setBrush(const QBrush &brush) { - mBrush = brush; + mBrush = brush; } /*! Sets the brush that will be used to draw any fills of the tracer, when selected. - + \see setBrush, setSelected */ void QCPItemTracer::setSelectedBrush(const QBrush &brush) { - mSelectedBrush = brush; + mSelectedBrush = brush; } /*! @@ -29712,242 +30061,232 @@ void QCPItemTracer::setSelectedBrush(const QBrush &brush) */ void QCPItemTracer::setSize(double size) { - mSize = size; + mSize = size; } /*! Sets the style/visual appearance of the tracer. - + If you only want to use the tracer \a position as an anchor for other items, set \a style to \ref tsNone. */ void QCPItemTracer::setStyle(QCPItemTracer::TracerStyle style) { - mStyle = style; + mStyle = style; } /*! Sets the QCPGraph this tracer sticks to. The tracer \a position will be set to type QCPItemPosition::ptPlotCoords and the axes will be set to the axes of \a graph. - + To free the tracer from any graph, set \a graph to 0. The tracer \a position can then be placed freely like any other item position. This is the state the tracer will assume when its graph gets deleted while still attached to it. - + \see setGraphKey */ void QCPItemTracer::setGraph(QCPGraph *graph) { - if (graph) - { - if (graph->parentPlot() == mParentPlot) - { - position->setType(QCPItemPosition::ptPlotCoords); - position->setAxes(graph->keyAxis(), graph->valueAxis()); - mGraph = graph; - updatePosition(); - } else - qDebug() << Q_FUNC_INFO << "graph isn't in same QCustomPlot instance as this item"; - } else - { - mGraph = 0; - } + if (graph) { + if (graph->parentPlot() == mParentPlot) { + position->setType(QCPItemPosition::ptPlotCoords); + position->setAxes(graph->keyAxis(), graph->valueAxis()); + mGraph = graph; + updatePosition(); + } else { + qDebug() << Q_FUNC_INFO << "graph isn't in same QCustomPlot instance as this item"; + } + } else { + mGraph = 0; + } } /*! Sets the key of the graph's data point the tracer will be positioned at. This is the only free coordinate of a tracer when attached to a graph. - + Depending on \ref setInterpolating, the tracer will be either positioned on the data point closest to \a key, or will stay exactly at \a key and interpolate the value linearly. - + \see setGraph, setInterpolating */ void QCPItemTracer::setGraphKey(double key) { - mGraphKey = key; + mGraphKey = key; } /*! Sets whether the value of the graph's data points shall be interpolated, when positioning the tracer. - + If \a enabled is set to false and a key is given with \ref setGraphKey, the tracer is placed on the data point of the graph which is closest to the key, but which is not necessarily exactly there. If \a enabled is true, the tracer will be positioned exactly at the specified key, and the appropriate value will be interpolated from the graph's data points linearly. - + \see setGraph, setGraphKey */ void QCPItemTracer::setInterpolating(bool enabled) { - mInterpolating = enabled; + mInterpolating = enabled; } /* inherits documentation from base class */ double QCPItemTracer::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { - Q_UNUSED(details) - if (onlySelectable && !mSelectable) - return -1; + Q_UNUSED(details) + if (onlySelectable && !mSelectable) { + return -1; + } - QPointF center(position->pixelPosition()); - double w = mSize/2.0; - QRect clip = clipRect(); - switch (mStyle) - { - case tsNone: return -1; - case tsPlus: - { - if (clipRect().intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect())) - 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(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 = QCPVector2D(center-pos).length(); - double circleLine = w; - double result = qAbs(centerDist-circleLine); - // filled ellipse, allow click inside to count as hit: - if (result > mParentPlot->selectionTolerance()*0.99 && mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0) - { - if (centerDist <= circleLine) - result = mParentPlot->selectionTolerance()*0.99; + QPointF center(position->pixelPosition()); + double w = mSize / 2.0; + QRect clip = clipRect(); + switch (mStyle) { + case tsNone: + return -1; + case tsPlus: { + if (clipRect().intersects(QRectF(center - QPointF(w, w), center + QPointF(w, w)).toRect())) + 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(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 = QCPVector2D(center - pos).length(); + double circleLine = w; + double result = qAbs(centerDist - circleLine); + // filled ellipse, allow click inside to count as hit: + if (result > mParentPlot->selectionTolerance() * 0.99 && mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0) { + if (centerDist <= circleLine) { + result = mParentPlot->selectionTolerance() * 0.99; + } + } + return result; + } + break; + } + case tsSquare: { + if (clip.intersects(QRectF(center - QPointF(w, w), center + QPointF(w, w)).toRect())) { + QRectF rect = QRectF(center - QPointF(w, w), center + QPointF(w, w)); + bool filledRect = mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0; + return rectDistance(rect, pos, filledRect); + } + break; } - return result; - } - break; } - case tsSquare: - { - if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect())) - { - QRectF rect = QRectF(center-QPointF(w, w), center+QPointF(w, w)); - bool filledRect = mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0; - return rectDistance(rect, pos, filledRect); - } - break; - } - } - return -1; + return -1; } /* inherits documentation from base class */ void QCPItemTracer::draw(QCPPainter *painter) { - updatePosition(); - if (mStyle == tsNone) - return; + updatePosition(); + if (mStyle == tsNone) { + return; + } - painter->setPen(mainPen()); - painter->setBrush(mainBrush()); - QPointF center(position->pixelPosition()); - double w = mSize/2.0; - QRect clip = clipRect(); - switch (mStyle) - { - case tsNone: return; - case tsPlus: - { - if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect())) - { - painter->drawLine(QLineF(center+QPointF(-w, 0), center+QPointF(w, 0))); - painter->drawLine(QLineF(center+QPointF(0, -w), center+QPointF(0, w))); - } - break; + painter->setPen(mainPen()); + painter->setBrush(mainBrush()); + QPointF center(position->pixelPosition()); + double w = mSize / 2.0; + QRect clip = clipRect(); + switch (mStyle) { + case tsNone: + return; + case tsPlus: { + if (clip.intersects(QRectF(center - QPointF(w, w), center + QPointF(w, w)).toRect())) { + painter->drawLine(QLineF(center + QPointF(-w, 0), center + QPointF(w, 0))); + painter->drawLine(QLineF(center + QPointF(0, -w), center + QPointF(0, w))); + } + break; + } + case tsCrosshair: { + if (center.y() > clip.top() && center.y() < clip.bottom()) { + painter->drawLine(QLineF(clip.left(), center.y(), clip.right(), center.y())); + } + if (center.x() > clip.left() && center.x() < clip.right()) { + painter->drawLine(QLineF(center.x(), clip.top(), center.x(), clip.bottom())); + } + break; + } + case tsCircle: { + if (clip.intersects(QRectF(center - QPointF(w, w), center + QPointF(w, w)).toRect())) { + painter->drawEllipse(center, w, w); + } + break; + } + case tsSquare: { + if (clip.intersects(QRectF(center - QPointF(w, w), center + QPointF(w, w)).toRect())) { + painter->drawRect(QRectF(center - QPointF(w, w), center + QPointF(w, w))); + } + break; + } } - case tsCrosshair: - { - if (center.y() > clip.top() && center.y() < clip.bottom()) - painter->drawLine(QLineF(clip.left(), center.y(), clip.right(), center.y())); - if (center.x() > clip.left() && center.x() < clip.right()) - painter->drawLine(QLineF(center.x(), clip.top(), center.x(), clip.bottom())); - break; - } - case tsCircle: - { - if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect())) - painter->drawEllipse(center, w, w); - break; - } - case tsSquare: - { - if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect())) - painter->drawRect(QRectF(center-QPointF(w, w), center+QPointF(w, w))); - break; - } - } } /*! If the tracer is connected with a graph (\ref setGraph), this function updates the tracer's \a position to reside on the graph data, depending on the configured key (\ref setGraphKey). - + It is called automatically on every redraw and normally doesn't need to be called manually. One exception is when you want to read the tracer coordinates via \a position and are not sure that the graph's data (or the tracer key with \ref setGraphKey) hasn't changed since the last redraw. In that situation, call this function before accessing \a position, to make sure you don't get out-of-date coordinates. - + If there is no graph set on this tracer, this function does nothing. */ void QCPItemTracer::updatePosition() { - if (mGraph) - { - if (mParentPlot->hasPlottable(mGraph)) - { - if (mGraph->data()->size() > 1) - { - 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 - { - QCPGraphDataContainer::const_iterator it = mGraph->data()->findBegin(mGraphKey); - if (it != mGraph->data()->constEnd()) // mGraphKey is not exactly on last iterator, but somewhere between iterators - { - 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-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) - position->setCoords(prevIt->key, prevIt->value); - else + if (mGraph) { + if (mParentPlot->hasPlottable(mGraph)) { + if (mGraph->data()->size() > 1) { + 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 { + QCPGraphDataContainer::const_iterator it = mGraph->data()->findBegin(mGraphKey); + if (it != mGraph->data()->constEnd()) { // mGraphKey is not exactly on last iterator, but somewhere between iterators + 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 - 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) { + position->setCoords(prevIt->key, prevIt->value); + } else { + position->setCoords(it->key, it->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) { + QCPGraphDataContainer::const_iterator it = mGraph->data()->constBegin(); position->setCoords(it->key, it->value); + } else { + qDebug() << Q_FUNC_INFO << "graph has no data"; } - } 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 { + qDebug() << Q_FUNC_INFO << "graph not contained in QCustomPlot instance (anymore)"; } - } else if (mGraph->data()->size() == 1) - { - QCPGraphDataContainer::const_iterator it = mGraph->data()->constBegin(); - position->setCoords(it->key, it->value); - } else - qDebug() << Q_FUNC_INFO << "graph has no data"; - } else - qDebug() << Q_FUNC_INFO << "graph not contained in QCustomPlot instance (anymore)"; - } + } } /*! \internal @@ -29957,7 +30296,7 @@ void QCPItemTracer::updatePosition() */ QPen QCPItemTracer::mainPen() const { - return mSelected ? mSelectedPen : mPen; + return mSelected ? mSelectedPen : mPen; } /*! \internal @@ -29967,7 +30306,7 @@ QPen QCPItemTracer::mainPen() const */ QBrush QCPItemTracer::mainBrush() const { - return mSelected ? mSelectedBrush : mBrush; + return mSelected ? mSelectedBrush : mBrush; } /* end of 'src/items/item-tracer.cpp' */ @@ -29987,37 +30326,37 @@ QBrush QCPItemTracer::mainBrush() const It has two positions, \a left and \a right, which define the span of the bracket. If \a left is actually farther to the left than \a right, the bracket is opened to the bottom, as shown in the example image. - + The bracket supports multiple styles via \ref setStyle. The length, i.e. how far the bracket stretches away from the embraced span, can be controlled with \ref setLength. - + \image html QCPItemBracket-length.png
Demonstrating the effect of different values for \ref setLength, for styles \ref bsCalligraphic and \ref bsSquare. Anchors and positions are displayed for reference.
- + It provides an anchor \a center, to allow connection of other items, e.g. an arrow (QCPItemLine or QCPItemCurve) or a text label (QCPItemText), to the bracket. */ /*! Creates a bracket item and sets default values. - + 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)), - mLength(8), - mStyle(bsCalligraphic) + QCPAbstractItem(parentPlot), + left(createPosition(QLatin1String("left"))), + right(createPosition(QLatin1String("right"))), + 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)); + left->setCoords(0, 0); + right->setCoords(1, 1); + + setPen(QPen(Qt::black)); + setSelectedPen(QPen(Qt::blue, 2)); } QCPItemBracket::~QCPItemBracket() @@ -30026,178 +30365,172 @@ QCPItemBracket::~QCPItemBracket() /*! Sets the pen that will be used to draw the bracket. - + Note that when the style is \ref bsCalligraphic, only the color will be taken from the pen, the stroke and width are ignored. To change the apparent stroke width of a calligraphic bracket, use \ref setLength, which has a similar effect. - + \see setSelectedPen */ void QCPItemBracket::setPen(const QPen &pen) { - mPen = pen; + mPen = pen; } /*! Sets the pen that will be used to draw the bracket when selected - + \see setPen, setSelected */ void QCPItemBracket::setSelectedPen(const QPen &pen) { - mSelectedPen = pen; + mSelectedPen = pen; } /*! Sets the \a length in pixels how far the bracket extends in the direction towards the embraced span of the bracket (i.e. perpendicular to the left-right-direction) - + \image html QCPItemBracket-length.png
Demonstrating the effect of different values for \ref setLength, for styles \ref bsCalligraphic and \ref bsSquare. Anchors and positions are displayed for reference.
*/ void QCPItemBracket::setLength(double length) { - mLength = length; + mLength = length; } /*! Sets the style of the bracket, i.e. the shape/visual appearance. - + \see setPen */ void QCPItemBracket::setStyle(QCPItemBracket::BracketStyle style) { - mStyle = style; + mStyle = style; } /* inherits documentation from base class */ double QCPItemBracket::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { - Q_UNUSED(details) - if (onlySelectable && !mSelectable) - return -1; - - QCPVector2D p(pos); - QCPVector2D leftVec(left->pixelPosition()); - QCPVector2D rightVec(right->pixelPosition()); - if (leftVec.toPoint() == rightVec.toPoint()) - return -1; - - 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 = 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)); + Q_UNUSED(details) + if (onlySelectable && !mSelectable) { + return -1; } - case QCPItemBracket::bsCurly: - case QCPItemBracket::bsCalligraphic: - { - 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))); + + QCPVector2D p(pos); + QCPVector2D leftVec(left->pixelPosition()); + QCPVector2D rightVec(right->pixelPosition()); + if (leftVec.toPoint() == rightVec.toPoint()) { + return -1; } - } - return -1; + + 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 = 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 = 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))); + } + } + return -1; } /* inherits documentation from base class */ void QCPItemBracket::draw(QCPPainter *painter) { - QCPVector2D leftVec(left->pixelPosition()); - QCPVector2D rightVec(right->pixelPosition()); - if (leftVec.toPoint() == rightVec.toPoint()) - return; - - 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() - << (rightVec-lengthVec).toPoint() << (leftVec-lengthVec).toPoint(); - QRect clip = clipRect().adjusted(-mainPen().widthF(), -mainPen().widthF(), mainPen().widthF(), mainPen().widthF()); - if (clip.intersects(boundingPoly.boundingRect())) - { - painter->setPen(mainPen()); - switch (mStyle) - { - case bsSquare: - { - painter->drawLine((centerVec+widthVec).toPointF(), (centerVec-widthVec).toPointF()); - painter->drawLine((centerVec+widthVec).toPointF(), (centerVec+widthVec+lengthVec).toPointF()); - painter->drawLine((centerVec-widthVec).toPointF(), (centerVec-widthVec+lengthVec).toPointF()); - break; - } - case bsRound: - { - painter->setBrush(Qt::NoBrush); - QPainterPath path; - path.moveTo((centerVec+widthVec+lengthVec).toPointF()); - path.cubicTo((centerVec+widthVec).toPointF(), (centerVec+widthVec).toPointF(), centerVec.toPointF()); - path.cubicTo((centerVec-widthVec).toPointF(), (centerVec-widthVec).toPointF(), (centerVec-widthVec+lengthVec).toPointF()); - painter->drawPath(path); - break; - } - case bsCurly: - { - painter->setBrush(Qt::NoBrush); - QPainterPath path; - path.moveTo((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; - } - case bsCalligraphic: - { - painter->setPen(Qt::NoPen); - painter->setBrush(QBrush(mainPen().color())); - QPainterPath path; - path.moveTo((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.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; - } + QCPVector2D leftVec(left->pixelPosition()); + QCPVector2D rightVec(right->pixelPosition()); + if (leftVec.toPoint() == rightVec.toPoint()) { + return; + } + + 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() + << (rightVec - lengthVec).toPoint() << (leftVec - lengthVec).toPoint(); + QRect clip = clipRect().adjusted(-mainPen().widthF(), -mainPen().widthF(), mainPen().widthF(), mainPen().widthF()); + if (clip.intersects(boundingPoly.boundingRect())) { + painter->setPen(mainPen()); + switch (mStyle) { + case bsSquare: { + painter->drawLine((centerVec + widthVec).toPointF(), (centerVec - widthVec).toPointF()); + painter->drawLine((centerVec + widthVec).toPointF(), (centerVec + widthVec + lengthVec).toPointF()); + painter->drawLine((centerVec - widthVec).toPointF(), (centerVec - widthVec + lengthVec).toPointF()); + break; + } + case bsRound: { + painter->setBrush(Qt::NoBrush); + QPainterPath path; + path.moveTo((centerVec + widthVec + lengthVec).toPointF()); + path.cubicTo((centerVec + widthVec).toPointF(), (centerVec + widthVec).toPointF(), centerVec.toPointF()); + path.cubicTo((centerVec - widthVec).toPointF(), (centerVec - widthVec).toPointF(), (centerVec - widthVec + lengthVec).toPointF()); + painter->drawPath(path); + break; + } + case bsCurly: { + painter->setBrush(Qt::NoBrush); + QPainterPath path; + path.moveTo((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; + } + case bsCalligraphic: { + painter->setPen(Qt::NoPen); + painter->setBrush(QBrush(mainPen().color())); + QPainterPath path; + path.moveTo((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.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; + } + } } - } } /* inherits documentation from base class */ QPointF QCPItemBracket::anchorPixelPosition(int anchorId) const { - QCPVector2D leftVec(left->pixelPosition()); - QCPVector2D rightVec(right->pixelPosition()); - if (leftVec.toPoint() == rightVec.toPoint()) - return leftVec.toPointF(); - - QCPVector2D widthVec = (rightVec-leftVec)*0.5; - QCPVector2D lengthVec = widthVec.perpendicular().normalized()*mLength; - QCPVector2D centerVec = (rightVec+leftVec)*0.5-lengthVec; - - switch (anchorId) - { - case aiCenter: - return centerVec.toPointF(); - } - qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId; - return QPointF(); + QCPVector2D leftVec(left->pixelPosition()); + QCPVector2D rightVec(right->pixelPosition()); + if (leftVec.toPoint() == rightVec.toPoint()) { + return leftVec.toPointF(); + } + + QCPVector2D widthVec = (rightVec - leftVec) * 0.5; + QCPVector2D lengthVec = widthVec.perpendicular().normalized() * mLength; + QCPVector2D centerVec = (rightVec + leftVec) * 0.5 - lengthVec; + + switch (anchorId) { + case aiCenter: + return centerVec.toPointF(); + } + qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId; + return QPointF(); } /*! \internal diff --git a/third/3rd_qcustomplot/v2_0/qcustomplot.h b/third/3rd_qcustomplot/v2_0/qcustomplot.h index 3b046e5..7196296 100644 --- a/third/3rd_qcustomplot/v2_0/qcustomplot.h +++ b/third/3rd_qcustomplot/v2_0/qcustomplot.h @@ -1,4 +1,4 @@ -/*************************************************************************** +/*************************************************************************** ** ** ** QCustomPlot, an easy to use, modern plotting widget for Qt ** ** Copyright (C) 2011-2018 Emanuel Eichhammer ** @@ -137,27 +137,28 @@ class QCPBars; /*! 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. */ #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) +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 @@ -168,8 +169,8 @@ public: \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) +, ruDotsPerCentimeter ///< Resolution is given in dots per centimeter (dpcm) +, ruDotsPerInch ///< Resolution is given in dots per inch (DPI/PPI) }; /*! @@ -178,32 +179,32 @@ enum ResolutionUnit { ruDotsPerMeter ///< Resolution is given in dots per \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) +, 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 +, 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. - + \see QCPLayoutElement::setAutoMargins, QCPAxisRect::setAutoMargins */ enum MarginSide { msLeft = 0x01 ///< 0x01 left margin - ,msRight = 0x02 ///< 0x02 right margin - ,msTop = 0x04 ///< 0x04 top margin - ,msBottom = 0x08 ///< 0x08 bottom margin - ,msAll = 0xFF ///< 0xFF all margins - ,msNone = 0x00 ///< 0x00 no margin +, msRight = 0x02 ///< 0x02 right margin +, msTop = 0x04 ///< 0x04 top margin +, msBottom = 0x08 ///< 0x08 bottom margin +, msAll = 0xFF ///< 0xFF all margins +, msNone = 0x00 ///< 0x00 no margin }; Q_DECLARE_FLAGS(MarginSides, MarginSide) @@ -211,74 +212,74 @@ Q_DECLARE_FLAGS(MarginSides, MarginSide) Defines what objects of a plot can be forcibly drawn antialiased/not antialiased. If an object is neither forcibly drawn antialiased nor forcibly drawn not antialiased, it is up to the respective element how it is drawn. Typically it provides a \a setAntialiased function for this. - + \c AntialiasedElements is a flag of or-combined elements of this enum type. - + \see QCustomPlot::setAntialiasedElements, QCustomPlot::setNotAntialiasedElements */ enum AntialiasedElement { aeAxes = 0x0001 ///< 0x0001 Axis base line and tick marks - ,aeGrid = 0x0002 ///< 0x0002 Grid lines - ,aeSubGrid = 0x0004 ///< 0x0004 Sub grid lines - ,aeLegend = 0x0008 ///< 0x0008 Legend box - ,aeLegendItems = 0x0010 ///< 0x0010 Legend items - ,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) - ,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 +, aeGrid = 0x0002 ///< 0x0002 Grid lines +, aeSubGrid = 0x0004 ///< 0x0004 Sub grid lines +, aeLegend = 0x0008 ///< 0x0008 Legend box +, aeLegendItems = 0x0010 ///< 0x0010 Legend items +, 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) +, 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 }; Q_DECLARE_FLAGS(AntialiasedElements, AntialiasedElement) /*! Defines plotting hints that control various aspects of the quality and speed of plotting. - + \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, 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. +, 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) /*! Defines the mouse interactions possible with QCustomPlot. - + \c Interactions is a flag of or-combined elements of this enum type. - + \see QCustomPlot::setInteractions */ enum Interaction { iRangeDrag = 0x001 ///< 0x001 Axis ranges are draggable (see \ref QCPAxisRect::setRangeDrag, \ref QCPAxisRect::setRangeDragAxes) - ,iRangeZoom = 0x002 ///< 0x002 Axis ranges are zoomable with the mouse wheel (see \ref QCPAxisRect::setRangeZoom, \ref QCPAxisRect::setRangeZoomAxes) - ,iMultiSelect = 0x004 ///< 0x004 The user can select multiple objects by holding the modifier set by \ref QCustomPlot::setMultiSelectModifier while clicking - ,iSelectPlottables = 0x008 ///< 0x008 Plottables are selectable (e.g. graphs, curves, bars,... see QCPAbstractPlottable) - ,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, other layout elements,...) +, iRangeZoom = 0x002 ///< 0x002 Axis ranges are zoomable with the mouse wheel (see \ref QCPAxisRect::setRangeZoom, \ref QCPAxisRect::setRangeZoomAxes) +, iMultiSelect = 0x004 ///< 0x004 The user can select multiple objects by holding the modifier set by \ref QCustomPlot::setMultiSelectModifier while clicking +, iSelectPlottables = 0x008 ///< 0x008 Plottables are selectable (e.g. graphs, curves, bars,... see QCPAbstractPlottable) +, 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, 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. +, 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: - +
@@ -290,74 +291,84 @@ enum SelectionRectMode { srmNone ///< The selection rect is disabled, and all
- + \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 - }; +, 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. is \e nan or \e +/-inf). This function is used to check data validity upon replots, when the compiler flag \c QCUSTOMPLOT_CHECK_DATA is set. */ -inline bool isInvalidData(double value) -{ - return qIsNaN(value) || qIsInf(value); +inline bool isInvalidData(double value) { + return qIsNaN(value) || qIsInf(value); } /*! \internal \overload - + Checks two arguments instead of one. */ -inline bool isInvalidData(double value1, double value2) -{ - return isInvalidData(value1) || isInvalidData(value2); +inline bool isInvalidData(double value1, double value2) { + return isInvalidData(value1) || isInvalidData(value2); } /*! \internal - + Sets the specified \a side of \a margins to \a value - + \see getMarginValue */ -inline void setMarginValue(QMargins &margins, QCP::MarginSide side, int value) -{ - switch (side) - { - case QCP::msLeft: margins.setLeft(value); break; - case QCP::msRight: margins.setRight(value); break; - case QCP::msTop: margins.setTop(value); break; - case QCP::msBottom: margins.setBottom(value); break; - case QCP::msAll: margins = QMargins(value, value, value, value); break; - default: break; - } +inline void setMarginValue(QMargins &margins, QCP::MarginSide side, int value) { + switch (side) { + case QCP::msLeft: + margins.setLeft(value); + break; + case QCP::msRight: + margins.setRight(value); + break; + case QCP::msTop: + margins.setTop(value); + break; + case QCP::msBottom: + margins.setBottom(value); + break; + case QCP::msAll: + margins = QMargins(value, value, value, value); + break; + default: + break; + } } /*! \internal - + Returns the value of the specified \a side of \a margins. If \a side is \ref QCP::msNone or \ref QCP::msAll, returns 0. - + \see setMarginValue */ -inline int getMarginValue(const QMargins &margins, QCP::MarginSide side) -{ - switch (side) - { - case QCP::msLeft: return margins.left(); - case QCP::msRight: return margins.right(); - case QCP::msTop: return margins.top(); - case QCP::msBottom: return margins.bottom(); - default: break; - } - return 0; +inline int getMarginValue(const QMargins &margins, QCP::MarginSide side) { + switch (side) { + case QCP::msLeft: + return margins.left(); + case QCP::msRight: + return margins.right(); + case QCP::msTop: + return margins.top(); + case QCP::msBottom: + return margins.bottom(); + default: + break; + } + return 0; } @@ -387,60 +398,104 @@ Q_DECLARE_METATYPE(QCP::SelectionType) class QCP_LIB_DECL QCPVector2D { public: - QCPVector2D(); - QCPVector2D(double x, double y); - QCPVector2D(const QPoint &point); - QCPVector2D(const QPointF &point); - - // getters: - double x() const { return mX; } - double y() const { return mY; } - double &rx() { return mX; } - double &ry() { return mY; } - - // 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); - + QCPVector2D(); + QCPVector2D(double x, double y); + QCPVector2D(const QPoint &point); + QCPVector2D(const QPointF &point); + + // getters: + double x() const { + return mX; + } + double y() const { + return mY; + } + double &rx() { + return mX; + } + double &ry() { + return mY; + } + + // 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); + // 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(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); } +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 @@ -460,53 +515,59 @@ inline QDebug operator<< (QDebug d, const QCPVector2D &vec) class QCP_LIB_DECL QCPPainter : public QPainter { - Q_GADGET + Q_GADGET public: - /*! - Defines special modes the painter can operate in. They disable or enable certain subsets of features/fixes/workarounds, - depending on whether they are wanted on the respective output device. - */ - enum PainterMode { pmDefault = 0x00 ///< 0x00 Default mode for painting on screen devices - ,pmVectorized = 0x01 ///< 0x01 Mode for vectorized painting (e.g. PDF export). For example, this prevents some antialiasing fixes. - ,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_ENUMS(PainterMode) - Q_FLAGS(PainterModes) - Q_DECLARE_FLAGS(PainterModes, PainterMode) - - QCPPainter(); - explicit QCPPainter(QPaintDevice *device); - - // getters: - bool antialiasing() const { return testRenderHint(QPainter::Antialiasing); } - PainterModes modes() const { return mModes; } + /*! + Defines special modes the painter can operate in. They disable or enable certain subsets of features/fixes/workarounds, + depending on whether they are wanted on the respective output device. + */ + enum PainterMode { pmDefault = 0x00 ///< 0x00 Default mode for painting on screen devices + , pmVectorized = 0x01 ///< 0x01 Mode for vectorized painting (e.g. PDF export). For example, this prevents some antialiasing fixes. + , 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_ENUMS(PainterMode) + Q_FLAGS(PainterModes) + Q_DECLARE_FLAGS(PainterModes, PainterMode) - // setters: - void setAntialiasing(bool enabled); - void setMode(PainterMode mode, bool enabled=true); - void setModes(PainterModes modes); + QCPPainter(); + explicit QCPPainter(QPaintDevice *device); + + // getters: + bool antialiasing() const { + return testRenderHint(QPainter::Antialiasing); + } + PainterModes modes() const { + return mModes; + } + + // setters: + void setAntialiasing(bool enabled); + void setMode(PainterMode mode, bool enabled = true); + void setModes(PainterModes modes); + + // methods hiding non-virtual base class functions (QPainter bug workarounds): + bool begin(QPaintDevice *device); + void setPen(const QPen &pen); + void setPen(const QColor &color); + void setPen(Qt::PenStyle penStyle); + void drawLine(const QLineF &line); + void drawLine(const QPointF &p1, const QPointF &p2) { + drawLine(QLineF(p1, p2)); + } + void save(); + void restore(); + + // non-virtual methods: + void makeNonCosmetic(); - // methods hiding non-virtual base class functions (QPainter bug workarounds): - bool begin(QPaintDevice *device); - void setPen(const QPen &pen); - void setPen(const QColor &color); - void setPen(Qt::PenStyle penStyle); - void drawLine(const QLineF &line); - void drawLine(const QPointF &p1, const QPointF &p2) {drawLine(QLineF(p1, p2));} - void save(); - void restore(); - - // non-virtual methods: - void makeNonCosmetic(); - protected: - // property members: - PainterModes mModes; - bool mIsAntialiasing; - - // non-property members: - QStack mAntialiasingStack; + // property members: + PainterModes mModes; + bool mIsAntialiasing; + + // non-property members: + QStack mAntialiasingStack; }; Q_DECLARE_OPERATORS_FOR_FLAGS(QCPPainter::PainterModes) Q_DECLARE_METATYPE(QCPPainter::PainterMode) @@ -520,55 +581,61 @@ Q_DECLARE_METATYPE(QCPPainter::PainterMode) 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; - + 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; + // 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; - + 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; + // non-property members: + QPixmap mBuffer; + + // reimplemented virtual methods: + virtual void reallocateBuffer() Q_DECL_OVERRIDE; }; @@ -576,21 +643,21 @@ protected: 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; - + 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; + // non-property members: + QGLPixelBuffer *mGlPBuffer; + int mMultisamples; + + // reimplemented virtual methods: + virtual void reallocateBuffer() Q_DECL_OVERRIDE; }; #endif // QCP_OPENGL_PBUFFER @@ -599,23 +666,23 @@ protected: 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; - + 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; + // non-property members: + QWeakPointer mGlContext; + QWeakPointer mGlPaintDevice; + QOpenGLFramebufferObject *mGlFrameBuffer; + + // reimplemented virtual methods: + virtual void reallocateBuffer() Q_DECL_OVERRIDE; }; #endif // QCP_OPENGL_FBO @@ -627,145 +694,165 @@ protected: class QCP_LIB_DECL QCPLayer : public QObject { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QCustomPlot* parentPlot READ parentPlot) - Q_PROPERTY(QString name READ name) - 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 + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(QCustomPlot *parentPlot READ parentPlot) + Q_PROPERTY(QString name READ name) + 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); - virtual ~QCPLayer(); - - // getters: - QCustomPlot *parentPlot() const { return mParentPlot; } - QString name() const { return mName; } - 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(); - + /*! + 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); + virtual ~QCPLayer(); + + // getters: + QCustomPlot *parentPlot() const { + return mParentPlot; + } + QString name() const { + return mName; + } + 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: - QCustomPlot *mParentPlot; - QString mName; - 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); - + // property members: + QCustomPlot *mParentPlot; + QString mName; + 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); + private: - Q_DISABLE_COPY(QCPLayer) - - friend class QCustomPlot; - friend class QCPLayerable; + Q_DISABLE_COPY(QCPLayer) + + friend class QCustomPlot; + friend class QCPLayerable; }; Q_DECLARE_METATYPE(QCPLayer::LayerMode) class QCP_LIB_DECL QCPLayerable : public QObject { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(bool visible READ visible WRITE setVisible) - Q_PROPERTY(QCustomPlot* parentPlot READ parentPlot) - Q_PROPERTY(QCPLayerable* parentLayerable READ parentLayerable) - Q_PROPERTY(QCPLayer* layer READ layer WRITE setLayer NOTIFY layerChanged) - Q_PROPERTY(bool antialiased READ antialiased WRITE setAntialiased) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(bool visible READ visible WRITE setVisible) Q_PROPERTY(QCustomPlot *parentPlot READ parentPlot) + Q_PROPERTY(QCPLayerable *parentLayerable READ parentLayerable) + Q_PROPERTY(QCPLayer *layer READ layer WRITE setLayer NOTIFY layerChanged) + Q_PROPERTY(bool antialiased READ antialiased WRITE setAntialiased) + /// \endcond public: - QCPLayerable(QCustomPlot *plot, QString targetLayer=QString(), QCPLayerable *parentLayerable=0); - virtual ~QCPLayerable(); - - // getters: - bool visible() const { return mVisible; } - QCustomPlot *parentPlot() const { return mParentPlot; } - QCPLayerable *parentLayerable() const { return mParentLayerable.data(); } - QCPLayer *layer() const { return mLayer; } - bool antialiased() const { return mAntialiased; } - - // setters: - void setVisible(bool on); - Q_SLOT bool setLayer(QCPLayer *layer); - bool setLayer(const QString &layerName); - void setAntialiased(bool enabled); - - // introduced virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; + QCPLayerable(QCustomPlot *plot, QString targetLayer = QString(), QCPLayerable *parentLayerable = 0); + virtual ~QCPLayerable(); + + // getters: + bool visible() const { + return mVisible; + } + QCustomPlot *parentPlot() const { + return mParentPlot; + } + QCPLayerable *parentLayerable() const { + return mParentLayerable.data(); + } + QCPLayer *layer() const { + return mLayer; + } + bool antialiased() const { + return mAntialiased; + } + + // setters: + void setVisible(bool on); + Q_SLOT bool setLayer(QCPLayer *layer); + bool setLayer(const QString &layerName); + void setAntialiased(bool enabled); + + // introduced virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = 0) const; + + // non-property methods: + bool realVisibility() const; - // non-property methods: - bool realVisibility() const; - signals: - void layerChanged(QCPLayer *newLayer); - + void layerChanged(QCPLayer *newLayer); + protected: - // property members: - bool mVisible; - QCustomPlot *mParentPlot; - QPointer mParentLayerable; - QCPLayer *mLayer; - bool mAntialiased; - - // introduced virtual methods: - virtual void parentPlotInitialized(QCustomPlot *parentPlot); - virtual QCP::Interaction selectionCategory() const; - virtual QRect clipRect() const; - virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const = 0; - virtual void draw(QCPPainter *painter) = 0; - // 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); - void setParentLayerable(QCPLayerable* parentLayerable); - bool moveToLayer(QCPLayer *layer, bool prepend); - void applyAntialiasingHint(QCPPainter *painter, bool localAntialiased, QCP::AntialiasedElement overrideElement) const; - + // property members: + bool mVisible; + QCustomPlot *mParentPlot; + QPointer mParentLayerable; + QCPLayer *mLayer; + bool mAntialiased; + + // introduced virtual methods: + virtual void parentPlotInitialized(QCustomPlot *parentPlot); + virtual QCP::Interaction selectionCategory() const; + virtual QRect clipRect() const; + virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const = 0; + virtual void draw(QCPPainter *painter) = 0; + // 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); + void setParentLayerable(QCPLayerable *parentLayerable); + bool moveToLayer(QCPLayer *layer, bool prepend); + void applyAntialiasingHint(QCPPainter *painter, bool localAntialiased, QCP::AntialiasedElement overrideElement) const; + private: - Q_DISABLE_COPY(QCPLayerable) - - friend class QCustomPlot; - friend class QCPLayer; - friend class QCPAxisRect; + Q_DISABLE_COPY(QCPLayerable) + + friend class QCustomPlot; + friend class QCPLayer; + friend class QCPAxisRect; }; /* end of 'src/layer.h' */ @@ -777,42 +864,72 @@ private: class QCP_LIB_DECL QCPRange { public: - double lower, upper; - - QCPRange(); - QCPRange(double lower, double upper); - - bool operator==(const QCPRange& other) const { return lower == other.lower && upper == other.upper; } - bool operator!=(const QCPRange& other) const { return !(*this == other); } - - QCPRange &operator+=(const double& value) { lower+=value; upper+=value; return *this; } - QCPRange &operator-=(const double& value) { lower-=value; upper-=value; return *this; } - QCPRange &operator*=(const double& value) { lower*=value; upper*=value; return *this; } - QCPRange &operator/=(const double& value) { lower/=value; upper/=value; return *this; } - friend inline const QCPRange operator+(const QCPRange&, double); - friend inline const QCPRange operator+(double, const QCPRange&); - friend inline const QCPRange operator-(const QCPRange& range, double value); - friend inline const QCPRange operator*(const QCPRange& range, double value); - friend inline const QCPRange operator*(double value, const QCPRange& range); - friend inline const QCPRange operator/(const QCPRange& range, double value); - - 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 { return value >= lower && value <= upper; } - - static bool validRange(double lower, double upper); - static bool validRange(const QCPRange &range); - static const double minRange; - static const double maxRange; - + double lower, upper; + + QCPRange(); + QCPRange(double lower, double upper); + + bool operator==(const QCPRange &other) const { + return lower == other.lower && upper == other.upper; + } + bool operator!=(const QCPRange &other) const { + return !(*this == other); + } + + QCPRange &operator+=(const double &value) { + lower += value; + upper += value; + return *this; + } + QCPRange &operator-=(const double &value) { + lower -= value; + upper -= value; + return *this; + } + QCPRange &operator*=(const double &value) { + lower *= value; + upper *= value; + return *this; + } + QCPRange &operator/=(const double &value) { + lower /= value; + upper /= value; + return *this; + } + friend inline const QCPRange operator+(const QCPRange &, double); + friend inline const QCPRange operator+(double, const QCPRange &); + friend inline const QCPRange operator-(const QCPRange &range, double value); + friend inline const QCPRange operator*(const QCPRange &range, double value); + friend inline const QCPRange operator*(double value, const QCPRange &range); + friend inline const QCPRange operator/(const QCPRange &range, double value); + + 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 { + return value >= lower && value <= upper; + } + + static bool validRange(double lower, double upper); + static bool validRange(const QCPRange &range); + static const double minRange; + static const double maxRange; + }; Q_DECLARE_TYPEINFO(QCPRange, Q_MOVABLE_TYPE); @@ -829,61 +946,61 @@ inline QDebug operator<< (QDebug d, const QCPRange &range) /*! Adds \a value to both boundaries of the range. */ -inline const QCPRange operator+(const QCPRange& range, double value) +inline const QCPRange operator+(const QCPRange &range, double value) { - QCPRange result(range); - result += value; - return result; + QCPRange result(range); + result += value; + return result; } /*! Adds \a value to both boundaries of the range. */ -inline const QCPRange operator+(double value, const QCPRange& range) +inline const QCPRange operator+(double value, const QCPRange &range) { - QCPRange result(range); - result += value; - return result; + QCPRange result(range); + result += value; + return result; } /*! Subtracts \a value from both boundaries of the range. */ -inline const QCPRange operator-(const QCPRange& range, double value) +inline const QCPRange operator-(const QCPRange &range, double value) { - QCPRange result(range); - result -= value; - return result; + QCPRange result(range); + result -= value; + return result; } /*! Multiplies both boundaries of the range by \a value. */ -inline const QCPRange operator*(const QCPRange& range, double value) +inline const QCPRange operator*(const QCPRange &range, double value) { - QCPRange result(range); - result *= value; - return result; + QCPRange result(range); + result *= value; + return result; } /*! Multiplies both boundaries of the range by \a value. */ -inline const QCPRange operator*(double value, const QCPRange& range) +inline const QCPRange operator*(double value, const QCPRange &range) { - QCPRange result(range); - result *= value; - return result; + QCPRange result(range); + result *= value; + return result; } /*! Divides both boundaries of the range by \a value. */ -inline const QCPRange operator/(const QCPRange& range, double value) +inline const QCPRange operator/(const QCPRange &range, double value) { - QCPRange result(range); - result /= value; - return result; + QCPRange result(range); + result /= value; + return result; } /* end of 'src/axis/range.h' */ @@ -895,35 +1012,57 @@ inline const QCPRange operator/(const QCPRange& range, double value) 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; - + 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; + // property members: + int mBegin, mEnd; }; Q_DECLARE_TYPEINFO(QCPDataRange, Q_MOVABLE_TYPE); @@ -932,47 +1071,57 @@ 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; - + 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(); } + // property members: + QList mDataRanges; + + inline static bool lessThanDataRangeBegin(const QCPDataRange &a, const QCPDataRange &b) { + return a.begin() < b.begin(); + } }; Q_DECLARE_METATYPE(QCPDataSelection) @@ -981,84 +1130,84 @@ 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) +inline const QCPDataSelection operator+(const QCPDataSelection &a, const QCPDataSelection &b) { - QCPDataSelection result(a); - result += b; - return result; + 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) +inline const QCPDataSelection operator+(const QCPDataRange &a, const QCPDataSelection &b) { - QCPDataSelection result(a); - result += b; - return result; + 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) +inline const QCPDataSelection operator+(const QCPDataSelection &a, const QCPDataRange &b) { - QCPDataSelection result(a); - result += b; - return result; + 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) +inline const QCPDataSelection operator+(const QCPDataRange &a, const QCPDataRange &b) { - QCPDataSelection result(a); - result += b; - return result; + 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) +inline const QCPDataSelection operator-(const QCPDataSelection &a, const QCPDataSelection &b) { - QCPDataSelection result(a); - result -= b; - return result; + 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) +inline const QCPDataSelection operator-(const QCPDataRange &a, const QCPDataSelection &b) { - QCPDataSelection result(a); - result -= b; - return result; + 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) +inline const QCPDataSelection operator-(const QCPDataSelection &a, const QCPDataRange &b) { - QCPDataSelection result(a); - result -= b; - return result; + 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) +inline const QCPDataSelection operator-(const QCPDataRange &a, const QCPDataRange &b) { - QCPDataSelection result(a); - result -= b; - return result; + QCPDataSelection result(a); + result -= b; + return result; } /*! \relates QCPDataRange @@ -1067,8 +1216,8 @@ inline const QCPDataSelection operator-(const QCPDataRange& a, const QCPDataRang */ inline QDebug operator<< (QDebug d, const QCPDataRange &dataRange) { - d.nospace() << "QCPDataRange(" << dataRange.begin() << ", " << dataRange.end() << ")"; - return d; + d.nospace() << "QCPDataRange(" << dataRange.begin() << ", " << dataRange.end() << ")"; + return d; } /*! \relates QCPDataSelection @@ -1078,11 +1227,11 @@ inline QDebug operator<< (QDebug d, const QCPDataRange &dataRange) 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); } - bool isEmpty() const; - void clear(); - + explicit QCPMarginGroup(QCustomPlot *parentPlot); + virtual ~QCPMarginGroup(); + + // non-virtual methods: + QList elements(QCP::MarginSide side) const { + return mChildren.value(side); + } + bool isEmpty() const; + void clear(); + protected: - // non-property members: - QCustomPlot *mParentPlot; - QHash > mChildren; - - // introduced virtual methods: - virtual int commonMargin(QCP::MarginSide side) const; - - // non-virtual methods: - void addChild(QCP::MarginSide side, QCPLayoutElement *element); - void removeChild(QCP::MarginSide side, QCPLayoutElement *element); - + // non-property members: + QCustomPlot *mParentPlot; + QHash > mChildren; + + // introduced virtual methods: + virtual int commonMargin(QCP::MarginSide side) const; + + // non-virtual methods: + void addChild(QCP::MarginSide side, QCPLayoutElement *element); + void removeChild(QCP::MarginSide side, QCPLayoutElement *element); + private: - Q_DISABLE_COPY(QCPMarginGroup) - - friend class QCPLayoutElement; + Q_DISABLE_COPY(QCPMarginGroup) + + friend class QCPLayoutElement; }; class QCP_LIB_DECL QCPLayoutElement : public QCPLayerable { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QCPLayout* layout READ layout) - Q_PROPERTY(QRect rect READ rect) - Q_PROPERTY(QRect outerRect READ outerRect WRITE setOuterRect) - Q_PROPERTY(QMargins margins READ margins WRITE setMargins) - Q_PROPERTY(QMargins minimumMargins READ minimumMargins WRITE setMinimumMargins) - Q_PROPERTY(QSize minimumSize READ minimumSize WRITE setMinimumSize) - Q_PROPERTY(QSize maximumSize READ maximumSize WRITE setMaximumSize) - Q_PROPERTY(SizeConstraintRect sizeConstraintRect READ sizeConstraintRect WRITE setSizeConstraintRect) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(QCPLayout *layout READ layout) + Q_PROPERTY(QRect rect READ rect) + Q_PROPERTY(QRect outerRect READ outerRect WRITE setOuterRect) + Q_PROPERTY(QMargins margins READ margins WRITE setMargins) + Q_PROPERTY(QMargins minimumMargins READ minimumMargins WRITE setMinimumMargins) + Q_PROPERTY(QSize minimumSize READ minimumSize WRITE setMinimumSize) + Q_PROPERTY(QSize maximumSize READ maximumSize WRITE setMaximumSize) + Q_PROPERTY(SizeConstraintRect sizeConstraintRect READ sizeConstraintRect WRITE setSizeConstraintRect) + /// \endcond public: - /*! - Defines the phases of the update process, that happens just before a replot. At each phase, - \ref update is called with the according UpdatePhase value. - */ - enum UpdatePhase { upPreparation ///< Phase used for any type of preparation that needs to be done before margin calculation and layout - ,upMargins ///< Phase in which the margins are calculated and set - ,upLayout ///< Final phase in which the layout system places the rects of the elements - }; - Q_ENUMS(UpdatePhase) - - /*! - Defines to which rect of a layout element the size constraints that can be set via \ref - setMinimumSize and \ref setMaximumSize apply. The outer rect (\ref outerRect) includes the - margins (e.g. in the case of a QCPAxisRect the axis labels), whereas the inner rect (\ref rect) - does not. - - \see setSizeConstraintRect - */ - enum SizeConstraintRect { scrInnerRect ///< Minimum/Maximum size constraints apply to inner rect - , scrOuterRect ///< Minimum/Maximum size constraints apply to outer rect, thus include layout element margins - }; - Q_ENUMS(SizeConstraintRect) + /*! + Defines the phases of the update process, that happens just before a replot. At each phase, + \ref update is called with the according UpdatePhase value. + */ + enum UpdatePhase { upPreparation ///< Phase used for any type of preparation that needs to be done before margin calculation and layout + , upMargins ///< Phase in which the margins are calculated and set + , upLayout ///< Final phase in which the layout system places the rects of the elements + }; + Q_ENUMS(UpdatePhase) + + /*! + Defines to which rect of a layout element the size constraints that can be set via \ref + setMinimumSize and \ref setMaximumSize apply. The outer rect (\ref outerRect) includes the + margins (e.g. in the case of a QCPAxisRect the axis labels), whereas the inner rect (\ref rect) + does not. + + \see setSizeConstraintRect + */ + enum SizeConstraintRect { scrInnerRect ///< Minimum/Maximum size constraints apply to inner rect + , scrOuterRect ///< Minimum/Maximum size constraints apply to outer rect, thus include layout element margins + }; + Q_ENUMS(SizeConstraintRect) + + explicit QCPLayoutElement(QCustomPlot *parentPlot = 0); + virtual ~QCPLayoutElement(); + + // getters: + QCPLayout *layout() const { + return mParentLayout; + } + QRect rect() const { + return mRect; + } + QRect outerRect() const { + return mOuterRect; + } + QMargins margins() const { + return mMargins; + } + QMargins minimumMargins() const { + return mMinimumMargins; + } + QCP::MarginSides autoMargins() const { + return mAutoMargins; + } + QSize minimumSize() const { + return mMinimumSize; + } + QSize maximumSize() const { + return mMaximumSize; + } + SizeConstraintRect sizeConstraintRect() const { + return mSizeConstraintRect; + } + QCPMarginGroup *marginGroup(QCP::MarginSide side) const { + return mMarginGroups.value(side, (QCPMarginGroup *)0); + } + QHash marginGroups() const { + return mMarginGroups; + } + + // setters: + void setOuterRect(const QRect &rect); + void setMargins(const QMargins &margins); + void setMinimumMargins(const QMargins &margins); + void setAutoMargins(QCP::MarginSides sides); + void setMinimumSize(const QSize &size); + void setMinimumSize(int width, int height); + void setMaximumSize(const QSize &size); + void setMaximumSize(int width, int height); + void setSizeConstraintRect(SizeConstraintRect constraintRect); + void setMarginGroup(QCP::MarginSides sides, QCPMarginGroup *group); + + // introduced virtual methods: + virtual void update(UpdatePhase phase); + virtual QSize minimumOuterSizeHint() const; + virtual QSize maximumOuterSizeHint() const; + virtual QList elements(bool recursive) const; + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = 0) const Q_DECL_OVERRIDE; - explicit QCPLayoutElement(QCustomPlot *parentPlot=0); - virtual ~QCPLayoutElement(); - - // getters: - QCPLayout *layout() const { return mParentLayout; } - QRect rect() const { return mRect; } - QRect outerRect() const { return mOuterRect; } - QMargins margins() const { return mMargins; } - QMargins minimumMargins() const { return mMinimumMargins; } - QCP::MarginSides autoMargins() const { return mAutoMargins; } - QSize minimumSize() const { return mMinimumSize; } - QSize maximumSize() const { return mMaximumSize; } - SizeConstraintRect sizeConstraintRect() const { return mSizeConstraintRect; } - QCPMarginGroup *marginGroup(QCP::MarginSide side) const { return mMarginGroups.value(side, (QCPMarginGroup*)0); } - QHash marginGroups() const { return mMarginGroups; } - - // setters: - void setOuterRect(const QRect &rect); - void setMargins(const QMargins &margins); - void setMinimumMargins(const QMargins &margins); - void setAutoMargins(QCP::MarginSides sides); - void setMinimumSize(const QSize &size); - void setMinimumSize(int width, int height); - void setMaximumSize(const QSize &size); - void setMaximumSize(int width, int height); - void setSizeConstraintRect(SizeConstraintRect constraintRect); - void setMarginGroup(QCP::MarginSides sides, QCPMarginGroup *group); - - // introduced virtual methods: - virtual void update(UpdatePhase phase); - virtual QSize minimumOuterSizeHint() const; - virtual QSize maximumOuterSizeHint() const; - virtual QList elements(bool recursive) const; - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const Q_DECL_OVERRIDE; - protected: - // property members: - QCPLayout *mParentLayout; - QSize mMinimumSize, mMaximumSize; - SizeConstraintRect mSizeConstraintRect; - QRect mRect, mOuterRect; - QMargins mMargins, mMinimumMargins; - QCP::MarginSides mAutoMargins; - QHash mMarginGroups; - - // introduced virtual methods: - virtual int calculateAutoMargin(QCP::MarginSide side); - virtual void layoutChanged(); - - // reimplemented virtual methods: - 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; + // property members: + QCPLayout *mParentLayout; + QSize mMinimumSize, mMaximumSize; + SizeConstraintRect mSizeConstraintRect; + QRect mRect, mOuterRect; + QMargins mMargins, mMinimumMargins; + QCP::MarginSides mAutoMargins; + QHash mMarginGroups; + + // introduced virtual methods: + virtual int calculateAutoMargin(QCP::MarginSide side); + virtual void layoutChanged(); + + // reimplemented virtual methods: + 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) - - friend class QCustomPlot; - friend class QCPLayout; - friend class QCPMarginGroup; + Q_DISABLE_COPY(QCPLayoutElement) + + friend class QCustomPlot; + friend class QCPLayout; + friend class QCPMarginGroup; }; Q_DECLARE_METATYPE(QCPLayoutElement::UpdatePhase) class QCP_LIB_DECL QCPLayout : public QCPLayoutElement { - Q_OBJECT + Q_OBJECT public: - explicit QCPLayout(); - - // reimplemented virtual methods: - 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; - virtual QCPLayoutElement* elementAt(int index) const = 0; - virtual QCPLayoutElement* takeAt(int index) = 0; - virtual bool take(QCPLayoutElement* element) = 0; - virtual void simplify(); - - // non-virtual methods: - bool removeAt(int index); - bool remove(QCPLayoutElement* element); - void clear(); - + explicit QCPLayout(); + + // reimplemented virtual methods: + 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; + virtual QCPLayoutElement *elementAt(int index) const = 0; + virtual QCPLayoutElement *takeAt(int index) = 0; + virtual bool take(QCPLayoutElement *element) = 0; + virtual void simplify(); + + // non-virtual methods: + bool removeAt(int index); + bool remove(QCPLayoutElement *element); + void clear(); + protected: - // introduced virtual methods: - virtual void updateLayout(); - - // non-virtual methods: - void sizeConstraintsChanged() const; - void adoptElement(QCPLayoutElement *el); - void releaseElement(QCPLayoutElement *el); - QVector getSectionSizes(QVector maxSizes, QVector minSizes, QVector stretchFactors, int totalSize) const; - static QSize getFinalMinimumOuterSize(const QCPLayoutElement *el); - static QSize getFinalMaximumOuterSize(const QCPLayoutElement *el); - + // introduced virtual methods: + virtual void updateLayout(); + + // non-virtual methods: + void sizeConstraintsChanged() const; + void adoptElement(QCPLayoutElement *el); + void releaseElement(QCPLayoutElement *el); + QVector getSectionSizes(QVector maxSizes, QVector minSizes, QVector stretchFactors, int totalSize) const; + static QSize getFinalMinimumOuterSize(const QCPLayoutElement *el); + static QSize getFinalMaximumOuterSize(const QCPLayoutElement *el); + private: - Q_DISABLE_COPY(QCPLayout) - friend class QCPLayoutElement; + Q_DISABLE_COPY(QCPLayout) + friend class QCPLayoutElement; }; class QCP_LIB_DECL QCPLayoutGrid : public QCPLayout { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(int rowCount READ rowCount) - Q_PROPERTY(int columnCount READ columnCount) - Q_PROPERTY(QList columnStretchFactors READ columnStretchFactors WRITE setColumnStretchFactors) - 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 + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(int rowCount READ rowCount) + Q_PROPERTY(int columnCount READ columnCount) + Q_PROPERTY(QList columnStretchFactors READ columnStretchFactors WRITE setColumnStretchFactors) + 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 { 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); - void setColumnStretchFactors(const QList &factors); - void setRowStretchFactor(int row, double factor); - 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() 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 minimumOuterSizeHint() const Q_DECL_OVERRIDE; - virtual QSize maximumOuterSizeHint() 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; - + /*! + 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 { + 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); + void setColumnStretchFactors(const QList &factors); + void setRowStretchFactor(int row, double factor); + 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() 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 minimumOuterSizeHint() const Q_DECL_OVERRIDE; + virtual QSize maximumOuterSizeHint() 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: - QList > mElements; - QList mColumnStretchFactors; - QList mRowStretchFactors; - int mColumnSpacing, mRowSpacing; - int mWrap; - FillOrder mFillOrder; - - // non-virtual methods: - void getMinimumRowColSizes(QVector *minColWidths, QVector *minRowHeights) const; - void getMaximumRowColSizes(QVector *maxColWidths, QVector *maxRowHeights) const; - + // property members: + QList > mElements; + QList mColumnStretchFactors; + QList mRowStretchFactors; + int mColumnSpacing, mRowSpacing; + int mWrap; + FillOrder mFillOrder; + + // non-virtual methods: + void getMinimumRowColSizes(QVector *minColWidths, QVector *minRowHeights) const; + void getMaximumRowColSizes(QVector *maxColWidths, QVector *maxRowHeights) const; + private: - Q_DISABLE_COPY(QCPLayoutGrid) + Q_DISABLE_COPY(QCPLayoutGrid) }; Q_DECLARE_METATYPE(QCPLayoutGrid::FillOrder) class QCP_LIB_DECL QCPLayoutInset : public QCPLayout { - Q_OBJECT + Q_OBJECT public: - /*! - Defines how the placement and sizing is handled for a certain element in a QCPLayoutInset. - */ - 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(); - - // getters: - InsetPlacement insetPlacement(int index) const; - Qt::Alignment insetAlignment(int index) const; - QRectF insetRect(int index) const; - - // setters: - void setInsetPlacement(int index, InsetPlacement placement); - void setInsetAlignment(int index, Qt::Alignment alignment); - void setInsetRect(int index, const QRectF &rect); - - // reimplemented virtual methods: - 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); - void addElement(QCPLayoutElement *element, const QRectF &rect); - + /*! + Defines how the placement and sizing is handled for a certain element in a QCPLayoutInset. + */ + 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(); + + // getters: + InsetPlacement insetPlacement(int index) const; + Qt::Alignment insetAlignment(int index) const; + QRectF insetRect(int index) const; + + // setters: + void setInsetPlacement(int index, InsetPlacement placement); + void setInsetAlignment(int index, Qt::Alignment alignment); + void setInsetRect(int index, const QRectF &rect); + + // reimplemented virtual methods: + 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); + void addElement(QCPLayoutElement *element, const QRectF &rect); + protected: - // property members: - QList mElements; - QList mInsetPlacement; - QList mInsetAlignment; - QList mInsetRect; - + // property members: + QList mElements; + QList mInsetPlacement; + QList mInsetAlignment; + QList mInsetRect; + private: - Q_DISABLE_COPY(QCPLayoutInset) + Q_DISABLE_COPY(QCPLayoutInset) }; Q_DECLARE_METATYPE(QCPLayoutInset::InsetPlacement) @@ -1473,58 +1674,66 @@ Q_DECLARE_METATYPE(QCPLayoutInset::InsetPlacement) class QCP_LIB_DECL QCPLineEnding { - Q_GADGET + Q_GADGET public: - /*! - Defines the type of ending decoration for line-like items, e.g. an arrow. - - \image html QCPLineEnding.png - - The width and length of these decorations can be controlled with the functions \ref setWidth - and \ref setLength. Some decorations like \ref esDisc, \ref esSquare, \ref esDiamond and \ref esBar only - support a width, the length property is ignored. - - \see QCPItemLine::setHead, QCPItemLine::setTail, QCPItemCurve::setHead, QCPItemCurve::setTail, QCPAxis::setLowerEnding, QCPAxis::setUpperEnding - */ - 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 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); - - // getters: - EndingStyle style() const { return mStyle; } - double width() const { return mWidth; } - double length() const { return mLength; } - bool inverted() const { return mInverted; } - - // setters: - void setStyle(EndingStyle style); - void setWidth(double width); - void setLength(double length); - void setInverted(bool inverted); - - // non-property methods: - double boundingDistance() const; - double realLength() const; - void draw(QCPPainter *painter, const QCPVector2D &pos, const QCPVector2D &dir) const; - void draw(QCPPainter *painter, const QCPVector2D &pos, double angle) const; - + /*! + Defines the type of ending decoration for line-like items, e.g. an arrow. + + \image html QCPLineEnding.png + + The width and length of these decorations can be controlled with the functions \ref setWidth + and \ref setLength. Some decorations like \ref esDisc, \ref esSquare, \ref esDiamond and \ref esBar only + support a width, the length property is ignored. + + \see QCPItemLine::setHead, QCPItemLine::setTail, QCPItemCurve::setHead, QCPItemCurve::setTail, QCPAxis::setLowerEnding, QCPAxis::setUpperEnding + */ + 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 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); + + // getters: + EndingStyle style() const { + return mStyle; + } + double width() const { + return mWidth; + } + double length() const { + return mLength; + } + bool inverted() const { + return mInverted; + } + + // setters: + void setStyle(EndingStyle style); + void setWidth(double width); + void setLength(double length); + void setInverted(bool inverted); + + // non-property methods: + double boundingDistance() const; + double realLength() 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: - EndingStyle mStyle; - double mWidth, mLength; - bool mInverted; + // property members: + EndingStyle mStyle; + double mWidth, mLength; + bool mInverted; }; Q_DECLARE_TYPEINFO(QCPLineEnding, Q_MOVABLE_TYPE); Q_DECLARE_METATYPE(QCPLineEnding::EndingStyle) @@ -1537,59 +1746,64 @@ Q_DECLARE_METATYPE(QCPLineEnding::EndingStyle) class QCP_LIB_DECL QCPAxisTicker { - Q_GADGET + 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); - + /*! + 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; - + // 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; + private: - Q_DISABLE_COPY(QCPAxisTicker) - + Q_DISABLE_COPY(QCPAxisTicker) + }; Q_DECLARE_METATYPE(QCPAxisTicker::TickStepStrategy) Q_DECLARE_METATYPE(QSharedPointer) @@ -1603,36 +1817,40 @@ Q_DECLARE_METATYPE(QSharedPointer) 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); - + 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; + // 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' */ @@ -1643,47 +1861,51 @@ protected: class QCP_LIB_DECL QCPAxisTickerTime : public QCPAxisTicker { - Q_GADGET + Q_GADGET public: - /*! - Defines the logical units in which fractions of time spans can be expressed. - - \see setFieldWidth, setTimeFormat - */ - enum TimeUnit { tuMilliseconds ///< Milliseconds, one thousandth of a second (%%z in \ref setTimeFormat) - ,tuSeconds ///< Seconds (%%s in \ref setTimeFormat) - ,tuMinutes ///< Minutes (%%m in \ref setTimeFormat) - ,tuHours ///< Hours (%%h in \ref setTimeFormat) - ,tuDays ///< Days (%%d in \ref setTimeFormat) - }; - Q_ENUMS(TimeUnit) - - QCPAxisTickerTime(); + /*! + Defines the logical units in which fractions of time spans can be expressed. + + \see setFieldWidth, setTimeFormat + */ + enum TimeUnit { tuMilliseconds ///< Milliseconds, one thousandth of a second (%%z in \ref setTimeFormat) + , tuSeconds ///< Seconds (%%s in \ref setTimeFormat) + , tuMinutes ///< Minutes (%%m in \ref setTimeFormat) + , tuHours ///< Hours (%%h in \ref setTimeFormat) + , tuDays ///< Days (%%d in \ref setTimeFormat) + }; + 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); - // 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; + // 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) @@ -1695,37 +1917,41 @@ Q_DECLARE_METATYPE(QCPAxisTickerTime::TimeUnit) class QCP_LIB_DECL QCPAxisTickerFixed : public QCPAxisTicker { - Q_GADGET + 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); - + /*! + 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; + // property members: + double mTickStep; + ScaleStrategy mScaleStrategy; + + // reimplemented virtual methods: + virtual double getTickStep(const QCPRange &range) Q_DECL_OVERRIDE; }; Q_DECLARE_METATYPE(QCPAxisTickerFixed::ScaleStrategy) @@ -1738,33 +1964,37 @@ Q_DECLARE_METATYPE(QCPAxisTickerFixed::ScaleStrategy) 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, const QString &label); - void addTicks(const QMap &ticks); - void addTicks(const QVector &positions, const QVector &labels); - + 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, const 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; + // 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' */ @@ -1775,54 +2005,62 @@ protected: class QCP_LIB_DECL QCPAxisTickerPi : public QCPAxisTicker { - Q_GADGET + 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); - + /*! + 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; + // 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) @@ -1835,28 +2073,32 @@ Q_DECLARE_METATYPE(QCPAxisTickerPi::FractionStyle) 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); - + 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; + // 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' */ @@ -1865,353 +2107,431 @@ protected: /* including file 'src/axis/axis.h', size 20698 */ /* commit ce344b3f96a62e5f652585e55f1ae7c7883cd45b 2018-06-25 01:03:39 +0200 */ -class QCP_LIB_DECL QCPGrid :public QCPLayerable +class QCP_LIB_DECL QCPGrid : public QCPLayerable { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(bool subGridVisible READ subGridVisible WRITE setSubGridVisible) - Q_PROPERTY(bool antialiasedSubGrid READ antialiasedSubGrid WRITE setAntialiasedSubGrid) - Q_PROPERTY(bool antialiasedZeroLine READ antialiasedZeroLine WRITE setAntialiasedZeroLine) - Q_PROPERTY(QPen pen READ pen WRITE setPen) - Q_PROPERTY(QPen subGridPen READ subGridPen WRITE setSubGridPen) - Q_PROPERTY(QPen zeroLinePen READ zeroLinePen WRITE setZeroLinePen) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(bool subGridVisible READ subGridVisible WRITE setSubGridVisible) Q_PROPERTY(bool antialiasedSubGrid READ antialiasedSubGrid WRITE setAntialiasedSubGrid) + Q_PROPERTY(bool antialiasedZeroLine READ antialiasedZeroLine WRITE setAntialiasedZeroLine) + Q_PROPERTY(QPen pen READ pen WRITE setPen) + Q_PROPERTY(QPen subGridPen READ subGridPen WRITE setSubGridPen) + Q_PROPERTY(QPen zeroLinePen READ zeroLinePen WRITE setZeroLinePen) + /// \endcond public: - explicit QCPGrid(QCPAxis *parentAxis); - - // getters: - bool subGridVisible() const { return mSubGridVisible; } - bool antialiasedSubGrid() const { return mAntialiasedSubGrid; } - bool antialiasedZeroLine() const { return mAntialiasedZeroLine; } - QPen pen() const { return mPen; } - QPen subGridPen() const { return mSubGridPen; } - QPen zeroLinePen() const { return mZeroLinePen; } - - // setters: - void setSubGridVisible(bool visible); - void setAntialiasedSubGrid(bool enabled); - void setAntialiasedZeroLine(bool enabled); - void setPen(const QPen &pen); - void setSubGridPen(const QPen &pen); - void setZeroLinePen(const QPen &pen); - + explicit QCPGrid(QCPAxis *parentAxis); + + // getters: + bool subGridVisible() const { + return mSubGridVisible; + } + bool antialiasedSubGrid() const { + return mAntialiasedSubGrid; + } + bool antialiasedZeroLine() const { + return mAntialiasedZeroLine; + } + QPen pen() const { + return mPen; + } + QPen subGridPen() const { + return mSubGridPen; + } + QPen zeroLinePen() const { + return mZeroLinePen; + } + + // setters: + void setSubGridVisible(bool visible); + void setAntialiasedSubGrid(bool enabled); + void setAntialiasedZeroLine(bool enabled); + void setPen(const QPen &pen); + void setSubGridPen(const QPen &pen); + void setZeroLinePen(const QPen &pen); + protected: - // property members: - bool mSubGridVisible; - bool mAntialiasedSubGrid, mAntialiasedZeroLine; - QPen mPen, mSubGridPen, mZeroLinePen; - - // non-property members: - QCPAxis *mParentAxis; - - // reimplemented virtual methods: - 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; - void drawSubGridLines(QCPPainter *painter) const; - - friend class QCPAxis; + // property members: + bool mSubGridVisible; + bool mAntialiasedSubGrid, mAntialiasedZeroLine; + QPen mPen, mSubGridPen, mZeroLinePen; + + // non-property members: + QCPAxis *mParentAxis; + + // reimplemented virtual methods: + 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; + void drawSubGridLines(QCPPainter *painter) const; + + friend class QCPAxis; }; class QCP_LIB_DECL QCPAxis : public QCPLayerable { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(AxisType axisType READ axisType) - Q_PROPERTY(QCPAxisRect* axisRect READ axisRect) - Q_PROPERTY(ScaleType scaleType READ scaleType WRITE setScaleType NOTIFY scaleTypeChanged) - Q_PROPERTY(QCPRange range READ range WRITE setRange NOTIFY rangeChanged) - Q_PROPERTY(bool rangeReversed READ rangeReversed WRITE setRangeReversed) - 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(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 numberFormat READ numberFormat WRITE setNumberFormat) - Q_PROPERTY(int numberPrecision READ numberPrecision WRITE setNumberPrecision) - 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(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) - Q_PROPERTY(QPen tickPen READ tickPen WRITE setTickPen) - Q_PROPERTY(QPen subTickPen READ subTickPen WRITE setSubTickPen) - Q_PROPERTY(QFont labelFont READ labelFont WRITE setLabelFont) - Q_PROPERTY(QColor labelColor READ labelColor WRITE setLabelColor) - Q_PROPERTY(QString label READ label WRITE setLabel) - Q_PROPERTY(int labelPadding READ labelPadding WRITE setLabelPadding) - Q_PROPERTY(int padding READ padding WRITE setPadding) - Q_PROPERTY(int offset READ offset WRITE setOffset) - Q_PROPERTY(SelectableParts selectedParts READ selectedParts WRITE setSelectedParts NOTIFY selectionChanged) - Q_PROPERTY(SelectableParts selectableParts READ selectableParts WRITE setSelectableParts NOTIFY selectableChanged) - Q_PROPERTY(QFont selectedTickLabelFont READ selectedTickLabelFont WRITE setSelectedTickLabelFont) - Q_PROPERTY(QFont selectedLabelFont READ selectedLabelFont WRITE setSelectedLabelFont) - Q_PROPERTY(QColor selectedTickLabelColor READ selectedTickLabelColor WRITE setSelectedTickLabelColor) - Q_PROPERTY(QColor selectedLabelColor READ selectedLabelColor WRITE setSelectedLabelColor) - Q_PROPERTY(QPen selectedBasePen READ selectedBasePen WRITE setSelectedBasePen) - Q_PROPERTY(QPen selectedTickPen READ selectedTickPen WRITE setSelectedTickPen) - Q_PROPERTY(QPen selectedSubTickPen READ selectedSubTickPen WRITE setSelectedSubTickPen) - Q_PROPERTY(QCPLineEnding lowerEnding READ lowerEnding WRITE setLowerEnding) - Q_PROPERTY(QCPLineEnding upperEnding READ upperEnding WRITE setUpperEnding) - Q_PROPERTY(QCPGrid* grid READ grid) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(AxisType axisType READ axisType) + Q_PROPERTY(QCPAxisRect *axisRect READ axisRect) + Q_PROPERTY(ScaleType scaleType READ scaleType WRITE setScaleType NOTIFY scaleTypeChanged) + Q_PROPERTY(QCPRange range READ range WRITE setRange NOTIFY rangeChanged) + Q_PROPERTY(bool rangeReversed READ rangeReversed WRITE setRangeReversed) + 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(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 numberFormat READ numberFormat WRITE setNumberFormat) + Q_PROPERTY(int numberPrecision READ numberPrecision WRITE setNumberPrecision) + 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(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) + Q_PROPERTY(QPen tickPen READ tickPen WRITE setTickPen) + Q_PROPERTY(QPen subTickPen READ subTickPen WRITE setSubTickPen) + Q_PROPERTY(QFont labelFont READ labelFont WRITE setLabelFont) + Q_PROPERTY(QColor labelColor READ labelColor WRITE setLabelColor) + Q_PROPERTY(QString label READ label WRITE setLabel) + Q_PROPERTY(int labelPadding READ labelPadding WRITE setLabelPadding) + Q_PROPERTY(int padding READ padding WRITE setPadding) + Q_PROPERTY(int offset READ offset WRITE setOffset) + Q_PROPERTY(SelectableParts selectedParts READ selectedParts WRITE setSelectedParts NOTIFY selectionChanged) + Q_PROPERTY(SelectableParts selectableParts READ selectableParts WRITE setSelectableParts NOTIFY selectableChanged) + Q_PROPERTY(QFont selectedTickLabelFont READ selectedTickLabelFont WRITE setSelectedTickLabelFont) + Q_PROPERTY(QFont selectedLabelFont READ selectedLabelFont WRITE setSelectedLabelFont) + Q_PROPERTY(QColor selectedTickLabelColor READ selectedTickLabelColor WRITE setSelectedTickLabelColor) + Q_PROPERTY(QColor selectedLabelColor READ selectedLabelColor WRITE setSelectedLabelColor) + Q_PROPERTY(QPen selectedBasePen READ selectedBasePen WRITE setSelectedBasePen) + Q_PROPERTY(QPen selectedTickPen READ selectedTickPen WRITE setSelectedTickPen) + Q_PROPERTY(QPen selectedSubTickPen READ selectedSubTickPen WRITE setSelectedSubTickPen) + Q_PROPERTY(QCPLineEnding lowerEnding READ lowerEnding WRITE setLowerEnding) + Q_PROPERTY(QCPLineEnding upperEnding READ upperEnding WRITE setUpperEnding) + Q_PROPERTY(QCPGrid *grid READ grid) + /// \endcond public: - /*! - Defines at which side of the axis rect the axis will appear. This also affects how the tick - marks are drawn, on which side the labels are placed etc. - */ - enum AxisType { atLeft = 0x01 ///< 0x01 Axis is vertical and on the left side of the axis rect - ,atRight = 0x02 ///< 0x02 Axis is vertical and on the right side of the axis rect - ,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_ENUMS(AxisType) - Q_FLAGS(AxisTypes) - Q_DECLARE_FLAGS(AxisTypes, AxisType) - /*! - Defines on which side of the axis the tick labels (numbers) shall appear. - - \see setTickLabelSide - */ - enum LabelSide { lsInside ///< Tick labels will be displayed inside the axis rect and clipped to the inner axis rect - ,lsOutside ///< Tick labels will be displayed outside the axis rect - }; - Q_ENUMS(LabelSide) - /*! - Defines the scale of an axis. - \see setScaleType - */ - enum ScaleType { stLinear ///< Linear scaling - ,stLogarithmic ///< Logarithmic scaling with correspondingly transformed axis coordinates (possibly also \ref setTicker to a \ref QCPAxisTickerLog instance). - }; - Q_ENUMS(ScaleType) - /*! - Defines the selectable parts of an axis. - \see setSelectableParts, setSelectedParts - */ - enum SelectablePart { spNone = 0 ///< None of the selectable parts - ,spAxis = 0x001 ///< The axis backbone and tick marks - ,spTickLabels = 0x002 ///< Tick labels (numbers) of this axis (as a whole, not individually) - ,spAxisLabel = 0x004 ///< The axis label - }; - Q_ENUMS(SelectablePart) - Q_FLAGS(SelectableParts) - Q_DECLARE_FLAGS(SelectableParts, SelectablePart) - - explicit QCPAxis(QCPAxisRect *parent, AxisType type); - virtual ~QCPAxis(); - - // getters: - AxisType axisType() const { return mAxisType; } - QCPAxisRect *axisRect() const { return mAxisRect; } - ScaleType scaleType() const { return mScaleType; } - const QCPRange range() const { return mRange; } - bool rangeReversed() const { return mRangeReversed; } - QSharedPointer ticker() const { return mTicker; } - bool ticks() const { return mTicks; } - bool tickLabels() const { return mTickLabels; } - int tickLabelPadding() const; - QFont tickLabelFont() const { return mTickLabelFont; } - QColor tickLabelColor() const { return mTickLabelColor; } - double tickLabelRotation() const; - LabelSide tickLabelSide() const; - QString numberFormat() const; - int numberPrecision() const { return mNumberPrecision; } - QVector tickVector() const { return mTickVector; } - QVector tickVectorLabels() const { return mTickVectorLabels; } - int tickLengthIn() const; - int tickLengthOut() const; - bool subTicks() const { return mSubTicks; } - int subTickLengthIn() const; - int subTickLengthOut() const; - QPen basePen() const { return mBasePen; } - QPen tickPen() const { return mTickPen; } - QPen subTickPen() const { return mSubTickPen; } - QFont labelFont() const { return mLabelFont; } - QColor labelColor() const { return mLabelColor; } - QString label() const { return mLabel; } - int labelPadding() const; - int padding() const { return mPadding; } - int offset() const; - SelectableParts selectedParts() const { return mSelectedParts; } - SelectableParts selectableParts() const { return mSelectableParts; } - QFont selectedTickLabelFont() const { return mSelectedTickLabelFont; } - QFont selectedLabelFont() const { return mSelectedLabelFont; } - QColor selectedTickLabelColor() const { return mSelectedTickLabelColor; } - QColor selectedLabelColor() const { return mSelectedLabelColor; } - QPen selectedBasePen() const { return mSelectedBasePen; } - QPen selectedTickPen() const { return mSelectedTickPen; } - QPen selectedSubTickPen() const { return mSelectedSubTickPen; } - QCPLineEnding lowerEnding() const; - QCPLineEnding upperEnding() const; - QCPGrid *grid() const { return mGrid; } - - // setters: - Q_SLOT void setScaleType(QCPAxis::ScaleType type); - 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 setTicker(QSharedPointer ticker); - void setTicks(bool show); - void setTickLabels(bool show); - void setTickLabelPadding(int padding); - void setTickLabelFont(const QFont &font); - void setTickLabelColor(const QColor &color); - void setTickLabelRotation(double degrees); - void setTickLabelSide(LabelSide side); - void setNumberFormat(const QString &formatCode); - void setNumberPrecision(int precision); - void setTickLength(int inside, int outside=0); - void setTickLengthIn(int inside); - void setTickLengthOut(int outside); - void setSubTicks(bool show); - void setSubTickLength(int inside, int outside=0); - void setSubTickLengthIn(int inside); - void setSubTickLengthOut(int outside); - void setBasePen(const QPen &pen); - void setTickPen(const QPen &pen); - void setSubTickPen(const QPen &pen); - void setLabelFont(const QFont &font); - void setLabelColor(const QColor &color); - void setLabel(const QString &str); - void setLabelPadding(int padding); - void setPadding(int padding); - void setOffset(int offset); - void setSelectedTickLabelFont(const QFont &font); - void setSelectedLabelFont(const QFont &font); - void setSelectedTickLabelColor(const QColor &color); - void setSelectedLabelColor(const QColor &color); - void setSelectedBasePen(const QPen &pen); - void setSelectedTickPen(const QPen &pen); - void setSelectedSubTickPen(const QPen &pen); - Q_SLOT void setSelectableParts(const QCPAxis::SelectableParts &selectableParts); - Q_SLOT void setSelectedParts(const QCPAxis::SelectableParts &selectedParts); - void setLowerEnding(const QCPLineEnding &ending); - void setUpperEnding(const QCPLineEnding &ending); - - // reimplemented virtual methods: - 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); - double pixelToCoord(double value) const; - double coordToPixel(double value) const; - SelectablePart getPartAt(const QPointF &pos) const; - QList plottables() const; - QList graphs() const; - QList items() const; - - static AxisType marginSideToAxisType(QCP::MarginSide side); - static Qt::Orientation orientation(AxisType type) { return type==atBottom||type==atTop ? Qt::Horizontal : Qt::Vertical; } - static AxisType opposite(AxisType type); - + /*! + Defines at which side of the axis rect the axis will appear. This also affects how the tick + marks are drawn, on which side the labels are placed etc. + */ + enum AxisType { atLeft = 0x01 ///< 0x01 Axis is vertical and on the left side of the axis rect + , atRight = 0x02 ///< 0x02 Axis is vertical and on the right side of the axis rect + , 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_ENUMS(AxisType) + Q_FLAGS(AxisTypes) + Q_DECLARE_FLAGS(AxisTypes, AxisType) + /*! + Defines on which side of the axis the tick labels (numbers) shall appear. + + \see setTickLabelSide + */ + enum LabelSide { lsInside ///< Tick labels will be displayed inside the axis rect and clipped to the inner axis rect + , lsOutside ///< Tick labels will be displayed outside the axis rect + }; + Q_ENUMS(LabelSide) + /*! + Defines the scale of an axis. + \see setScaleType + */ + enum ScaleType { stLinear ///< Linear scaling + , stLogarithmic ///< Logarithmic scaling with correspondingly transformed axis coordinates (possibly also \ref setTicker to a \ref QCPAxisTickerLog instance). + }; + Q_ENUMS(ScaleType) + /*! + Defines the selectable parts of an axis. + \see setSelectableParts, setSelectedParts + */ + enum SelectablePart { spNone = 0 ///< None of the selectable parts + , spAxis = 0x001 ///< The axis backbone and tick marks + , spTickLabels = 0x002 ///< Tick labels (numbers) of this axis (as a whole, not individually) + , spAxisLabel = 0x004 ///< The axis label + }; + Q_ENUMS(SelectablePart) + Q_FLAGS(SelectableParts) + Q_DECLARE_FLAGS(SelectableParts, SelectablePart) + + explicit QCPAxis(QCPAxisRect *parent, AxisType type); + virtual ~QCPAxis(); + + // getters: + AxisType axisType() const { + return mAxisType; + } + QCPAxisRect *axisRect() const { + return mAxisRect; + } + ScaleType scaleType() const { + return mScaleType; + } + const QCPRange range() const { + return mRange; + } + bool rangeReversed() const { + return mRangeReversed; + } + QSharedPointer ticker() const { + return mTicker; + } + bool ticks() const { + return mTicks; + } + bool tickLabels() const { + return mTickLabels; + } + int tickLabelPadding() const; + QFont tickLabelFont() const { + return mTickLabelFont; + } + QColor tickLabelColor() const { + return mTickLabelColor; + } + double tickLabelRotation() const; + LabelSide tickLabelSide() const; + QString numberFormat() const; + int numberPrecision() const { + return mNumberPrecision; + } + QVector tickVector() const { + return mTickVector; + } + QVector tickVectorLabels() const { + return mTickVectorLabels; + } + int tickLengthIn() const; + int tickLengthOut() const; + bool subTicks() const { + return mSubTicks; + } + int subTickLengthIn() const; + int subTickLengthOut() const; + QPen basePen() const { + return mBasePen; + } + QPen tickPen() const { + return mTickPen; + } + QPen subTickPen() const { + return mSubTickPen; + } + QFont labelFont() const { + return mLabelFont; + } + QColor labelColor() const { + return mLabelColor; + } + QString label() const { + return mLabel; + } + int labelPadding() const; + int padding() const { + return mPadding; + } + int offset() const; + SelectableParts selectedParts() const { + return mSelectedParts; + } + SelectableParts selectableParts() const { + return mSelectableParts; + } + QFont selectedTickLabelFont() const { + return mSelectedTickLabelFont; + } + QFont selectedLabelFont() const { + return mSelectedLabelFont; + } + QColor selectedTickLabelColor() const { + return mSelectedTickLabelColor; + } + QColor selectedLabelColor() const { + return mSelectedLabelColor; + } + QPen selectedBasePen() const { + return mSelectedBasePen; + } + QPen selectedTickPen() const { + return mSelectedTickPen; + } + QPen selectedSubTickPen() const { + return mSelectedSubTickPen; + } + QCPLineEnding lowerEnding() const; + QCPLineEnding upperEnding() const; + QCPGrid *grid() const { + return mGrid; + } + + // setters: + Q_SLOT void setScaleType(QCPAxis::ScaleType type); + 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 setTicker(QSharedPointer ticker); + void setTicks(bool show); + void setTickLabels(bool show); + void setTickLabelPadding(int padding); + void setTickLabelFont(const QFont &font); + void setTickLabelColor(const QColor &color); + void setTickLabelRotation(double degrees); + void setTickLabelSide(LabelSide side); + void setNumberFormat(const QString &formatCode); + void setNumberPrecision(int precision); + void setTickLength(int inside, int outside = 0); + void setTickLengthIn(int inside); + void setTickLengthOut(int outside); + void setSubTicks(bool show); + void setSubTickLength(int inside, int outside = 0); + void setSubTickLengthIn(int inside); + void setSubTickLengthOut(int outside); + void setBasePen(const QPen &pen); + void setTickPen(const QPen &pen); + void setSubTickPen(const QPen &pen); + void setLabelFont(const QFont &font); + void setLabelColor(const QColor &color); + void setLabel(const QString &str); + void setLabelPadding(int padding); + void setPadding(int padding); + void setOffset(int offset); + void setSelectedTickLabelFont(const QFont &font); + void setSelectedLabelFont(const QFont &font); + void setSelectedTickLabelColor(const QColor &color); + void setSelectedLabelColor(const QColor &color); + void setSelectedBasePen(const QPen &pen); + void setSelectedTickPen(const QPen &pen); + void setSelectedSubTickPen(const QPen &pen); + Q_SLOT void setSelectableParts(const QCPAxis::SelectableParts &selectableParts); + Q_SLOT void setSelectedParts(const QCPAxis::SelectableParts &selectedParts); + void setLowerEnding(const QCPLineEnding &ending); + void setUpperEnding(const QCPLineEnding &ending); + + // reimplemented virtual methods: + 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); + double pixelToCoord(double value) const; + double coordToPixel(double value) const; + SelectablePart getPartAt(const QPointF &pos) const; + QList plottables() const; + QList graphs() const; + QList items() const; + + static AxisType marginSideToAxisType(QCP::MarginSide side); + static Qt::Orientation orientation(AxisType type) { + return type == atBottom || type == atTop ? Qt::Horizontal : Qt::Vertical; + } + static AxisType opposite(AxisType type); + signals: - void rangeChanged(const QCPRange &newRange); - void rangeChanged(const QCPRange &newRange, const QCPRange &oldRange); - void scaleTypeChanged(QCPAxis::ScaleType scaleType); - void selectionChanged(const QCPAxis::SelectableParts &parts); - void selectableChanged(const QCPAxis::SelectableParts &parts); + void rangeChanged(const QCPRange &newRange); + void rangeChanged(const QCPRange &newRange, const QCPRange &oldRange); + void scaleTypeChanged(QCPAxis::ScaleType scaleType); + void selectionChanged(const QCPAxis::SelectableParts &parts); + void selectableChanged(const QCPAxis::SelectableParts &parts); protected: - // property members: - // axis base: - AxisType mAxisType; - QCPAxisRect *mAxisRect; - //int mOffset; // in QCPAxisPainter - int mPadding; - Qt::Orientation mOrientation; - SelectableParts mSelectableParts, mSelectedParts; - QPen mBasePen, mSelectedBasePen; - //QCPLineEnding mLowerEnding, mUpperEnding; // in QCPAxisPainter - // axis label: - //int mLabelPadding; // in QCPAxisPainter - QString mLabel; - QFont mLabelFont, mSelectedLabelFont; - QColor mLabelColor, mSelectedLabelColor; - // tick labels: - //int mTickLabelPadding; // in QCPAxisPainter - bool mTickLabels; - //double mTickLabelRotation; // in QCPAxisPainter - QFont mTickLabelFont, mSelectedTickLabelFont; - QColor mTickLabelColor, mSelectedTickLabelColor; - int mNumberPrecision; - QLatin1Char mNumberFormatChar; - bool mNumberBeautifulPowers; - //bool mNumberMultiplyCross; // QCPAxisPainter - // ticks and subticks: - bool mTicks; - bool mSubTicks; - //int mTickLengthIn, mTickLengthOut, mSubTickLengthIn, mSubTickLengthOut; // QCPAxisPainter - QPen mTickPen, mSelectedTickPen; - QPen mSubTickPen, mSelectedSubTickPen; - // scale and range: - QCPRange mRange; - bool mRangeReversed; - ScaleType mScaleType; - - // non-property members: - QCPGrid *mGrid; - QCPAxisPainterPrivate *mAxisPainter; - QSharedPointer mTicker; - QVector mTickVector; - QVector mTickVectorLabels; - QVector mSubTickVector; - bool mCachedMarginValid; - int mCachedMargin; - bool mDragging; - QCPRange mDragStartRange; - QCP::AntialiasedElements mAADragBackup, mNotAADragBackup; - - // introduced virtual methods: - virtual int calculateMargin(); - - // reimplemented virtual methods: - 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) Q_DECL_OVERRIDE; - virtual void deselectEvent(bool *selectionStateChanged) Q_DECL_OVERRIDE; - // mouse events: - 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-virtual methods: - void setupTickVectors(); - QPen getBasePen() const; - QPen getTickPen() const; - QPen getSubTickPen() const; - QFont getTickLabelFont() const; - QFont getLabelFont() const; - QColor getTickLabelColor() const; - QColor getLabelColor() const; - + // property members: + // axis base: + AxisType mAxisType; + QCPAxisRect *mAxisRect; + //int mOffset; // in QCPAxisPainter + int mPadding; + Qt::Orientation mOrientation; + SelectableParts mSelectableParts, mSelectedParts; + QPen mBasePen, mSelectedBasePen; + //QCPLineEnding mLowerEnding, mUpperEnding; // in QCPAxisPainter + // axis label: + //int mLabelPadding; // in QCPAxisPainter + QString mLabel; + QFont mLabelFont, mSelectedLabelFont; + QColor mLabelColor, mSelectedLabelColor; + // tick labels: + //int mTickLabelPadding; // in QCPAxisPainter + bool mTickLabels; + //double mTickLabelRotation; // in QCPAxisPainter + QFont mTickLabelFont, mSelectedTickLabelFont; + QColor mTickLabelColor, mSelectedTickLabelColor; + int mNumberPrecision; + QLatin1Char mNumberFormatChar; + bool mNumberBeautifulPowers; + //bool mNumberMultiplyCross; // QCPAxisPainter + // ticks and subticks: + bool mTicks; + bool mSubTicks; + //int mTickLengthIn, mTickLengthOut, mSubTickLengthIn, mSubTickLengthOut; // QCPAxisPainter + QPen mTickPen, mSelectedTickPen; + QPen mSubTickPen, mSelectedSubTickPen; + // scale and range: + QCPRange mRange; + bool mRangeReversed; + ScaleType mScaleType; + + // non-property members: + QCPGrid *mGrid; + QCPAxisPainterPrivate *mAxisPainter; + QSharedPointer mTicker; + QVector mTickVector; + QVector mTickVectorLabels; + QVector mSubTickVector; + bool mCachedMarginValid; + int mCachedMargin; + bool mDragging; + QCPRange mDragStartRange; + QCP::AntialiasedElements mAADragBackup, mNotAADragBackup; + + // introduced virtual methods: + virtual int calculateMargin(); + + // reimplemented virtual methods: + 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) Q_DECL_OVERRIDE; + virtual void deselectEvent(bool *selectionStateChanged) Q_DECL_OVERRIDE; + // mouse events: + 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-virtual methods: + void setupTickVectors(); + QPen getBasePen() const; + QPen getTickPen() const; + QPen getSubTickPen() const; + QFont getTickLabelFont() const; + QFont getLabelFont() const; + QColor getTickLabelColor() const; + QColor getLabelColor() const; + private: - Q_DISABLE_COPY(QCPAxis) - - friend class QCustomPlot; - friend class QCPGrid; - friend class QCPAxisRect; + Q_DISABLE_COPY(QCPAxis) + + friend class QCustomPlot; + friend class QCPGrid; + friend class QCPAxisRect; }; Q_DECLARE_OPERATORS_FOR_FLAGS(QCPAxis::SelectableParts) Q_DECLARE_OPERATORS_FOR_FLAGS(QCPAxis::AxisTypes) @@ -2224,67 +2544,71 @@ Q_DECLARE_METATYPE(QCPAxis::SelectablePart) class QCPAxisPainterPrivate { public: - explicit QCPAxisPainterPrivate(QCustomPlot *parentPlot); - virtual ~QCPAxisPainterPrivate(); - - virtual void draw(QCPPainter *painter); - virtual int size() const; - void clearCache(); - - QRect axisSelectionBox() const { return mAxisSelectionBox; } - QRect tickLabelsSelectionBox() const { return mTickLabelsSelectionBox; } - QRect labelSelectionBox() const { return mLabelSelectionBox; } - - // public property members: - QCPAxis::AxisType type; - QPen basePen; - QCPLineEnding lowerEnding, upperEnding; // directly accessed by QCPAxis setters/getters - int labelPadding; // directly accessed by QCPAxis setters/getters - QFont labelFont; - QColor labelColor; - QString label; - int tickLabelPadding; // directly accessed by QCPAxis setters/getters - double tickLabelRotation; // directly accessed by QCPAxis setters/getters - QCPAxis::LabelSide tickLabelSide; // directly accessed by QCPAxis setters/getters - bool substituteExponent; - bool numberMultiplyCross; // directly accessed by QCPAxis setters/getters - int tickLengthIn, tickLengthOut, subTickLengthIn, subTickLengthOut; // directly accessed by QCPAxis setters/getters - QPen tickPen, subTickPen; - QFont tickLabelFont; - QColor tickLabelColor; - QRect axisRect, viewportRect; - double offset; // directly accessed by QCPAxis setters/getters - bool abbreviateDecimalPowers; - bool reversedEndings; - - QVector subTickPositions; - QVector tickPositions; - QVector tickLabels; - + explicit QCPAxisPainterPrivate(QCustomPlot *parentPlot); + virtual ~QCPAxisPainterPrivate(); + + virtual void draw(QCPPainter *painter); + virtual int size() const; + void clearCache(); + + QRect axisSelectionBox() const { + return mAxisSelectionBox; + } + QRect tickLabelsSelectionBox() const { + return mTickLabelsSelectionBox; + } + QRect labelSelectionBox() const { + return mLabelSelectionBox; + } + + // public property members: + QCPAxis::AxisType type; + QPen basePen; + QCPLineEnding lowerEnding, upperEnding; // directly accessed by QCPAxis setters/getters + int labelPadding; // directly accessed by QCPAxis setters/getters + QFont labelFont; + QColor labelColor; + QString label; + int tickLabelPadding; // directly accessed by QCPAxis setters/getters + double tickLabelRotation; // directly accessed by QCPAxis setters/getters + QCPAxis::LabelSide tickLabelSide; // directly accessed by QCPAxis setters/getters + bool substituteExponent; + bool numberMultiplyCross; // directly accessed by QCPAxis setters/getters + int tickLengthIn, tickLengthOut, subTickLengthIn, subTickLengthOut; // directly accessed by QCPAxis setters/getters + QPen tickPen, subTickPen; + QFont tickLabelFont; + QColor tickLabelColor; + QRect axisRect, viewportRect; + double offset; // directly accessed by QCPAxis setters/getters + bool abbreviateDecimalPowers; + bool reversedEndings; + + QVector subTickPositions; + QVector tickPositions; + QVector tickLabels; + protected: - struct CachedLabel - { - QPointF offset; - QPixmap pixmap; - }; - struct TickLabelData - { - QString basePart, expPart, suffixPart; - QRect baseBounds, expBounds, suffixBounds, totalBounds, rotatedTotalBounds; - QFont baseFont, expFont; - }; - QCustomPlot *mParentPlot; - QByteArray mLabelParameterHash; // to determine whether mLabelCache needs to be cleared due to changed parameters - QCache mLabelCache; - QRect mAxisSelectionBox, mTickLabelsSelectionBox, mLabelSelectionBox; - - virtual QByteArray generateLabelParameterHash() const; - - virtual void placeTickLabel(QCPPainter *painter, double position, int distanceToAxis, const QString &text, QSize *tickLabelsSize); - virtual void drawTickLabel(QCPPainter *painter, double x, double y, const TickLabelData &labelData) const; - virtual TickLabelData getTickLabelData(const QFont &font, const QString &text) const; - virtual QPointF getTickLabelDrawOffset(const TickLabelData &labelData) const; - virtual void getMaxTickLabelSize(const QFont &font, const QString &text, QSize *tickLabelsSize) const; + struct CachedLabel { + QPointF offset; + QPixmap pixmap; + }; + struct TickLabelData { + QString basePart, expPart, suffixPart; + QRect baseBounds, expBounds, suffixBounds, totalBounds, rotatedTotalBounds; + QFont baseFont, expFont; + }; + QCustomPlot *mParentPlot; + QByteArray mLabelParameterHash; // to determine whether mLabelCache needs to be cleared due to changed parameters + QCache mLabelCache; + QRect mAxisSelectionBox, mTickLabelsSelectionBox, mLabelSelectionBox; + + virtual QByteArray generateLabelParameterHash() const; + + virtual void placeTickLabel(QCPPainter *painter, double position, int distanceToAxis, const QString &text, QSize *tickLabelsSize); + virtual void drawTickLabel(QCPPainter *painter, double x, double y, const TickLabelData &labelData) const; + virtual TickLabelData getTickLabelData(const QFont &font, const QString &text) const; + virtual QPointF getTickLabelDrawOffset(const TickLabelData &labelData) const; + virtual void getMaxTickLabelSize(const QFont &font, const QString &text, QSize *tickLabelsSize) const; }; /* end of 'src/axis/axis.h' */ @@ -2295,99 +2619,115 @@ protected: class QCP_LIB_DECL QCPScatterStyle { - Q_GADGET + 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. + /*! + 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) + 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. + /*! + 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) + 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; } + 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); - // 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); + // 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; + } - // 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; + // 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; + // 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) @@ -2406,63 +2746,84 @@ Q_DECLARE_METATYPE(QCPScatterStyle::ScatterShape) \see QCPDataContainer::sort */ template -inline bool qcpLessThanSortKey(const DataType &a, const DataType &b) { return a.sortKey() < b.sortKey(); } +inline bool qcpLessThanSortKey(const DataType &a, const DataType &b) +{ + return a.sortKey() < b.sortKey(); +} template class QCPDataContainer // no QCP_LIB_DECL, template class ends up in header (cpp included below) { 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; - + 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(); + // 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: @@ -2544,27 +2905,27 @@ protected: /* 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 @@ -2573,9 +2934,9 @@ protected: */ /*! \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. @@ -2605,9 +2966,9 @@ protected: */ template QCPDataContainer::QCPDataContainer() : - mAutoSqueeze(true), - mPreallocSize(0), - mPreallocIteration(0) + mAutoSqueeze(true), + mPreallocSize(0), + mPreallocIteration(0) { } @@ -2615,160 +2976,162 @@ QCPDataContainer::QCPDataContainer() : 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(); - } + 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); + 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(); + 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); - } + 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); - } + 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); - } + 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(); + 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(); + } } /*! @@ -2779,68 +3142,72 @@ void QCPDataContainer::removeBefore(double sortKey) 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(); + 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(); + 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(); + 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; + mData.clear(); + mPreallocIteration = 0; + mPreallocSize = 0; } /*! @@ -2857,34 +3224,33 @@ void QCPDataContainer::clear() template void QCPDataContainer::sort() { - std::sort(begin(), end(), qcpLessThanSortKey); + 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; + if (preAllocation) { + if (mPreallocSize > 0) { + std::copy(begin(), end(), mData.begin()); + mData.resize(size()); + mPreallocSize = 0; + } + mPreallocIteration = 0; + } + if (postAllocation) { + mData.squeeze(); } - mPreallocIteration = 0; - } - if (postAllocation) - mData.squeeze(); } /*! @@ -2905,13 +3271,15 @@ void QCPDataContainer::squeeze(bool preAllocation, bool postAllocation 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; + 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; } /*! @@ -2932,13 +3300,15 @@ typename QCPDataContainer::const_iterator QCPDataContainer:: 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; + if (isEmpty()) { + return constEnd(); + } + + QCPDataContainer::const_iterator it = std::upper_bound(constBegin(), constEnd(), DataType::fromSortKey(sortKey), qcpLessThanSortKey); + if (expandedRange && it != constEnd()) { + ++it; + } + return it; } /*! @@ -2946,121 +3316,99 @@ typename QCPDataContainer::const_iterator QCPDataContainer:: 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; - } + if (isEmpty()) { + foundRange = false; + return QCPRange(); } - } 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; + 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; + } } - if ((current > range.upper || !haveUpper) && current < 0) - { - range.upper = current; - haveUpper = true; + } 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; } - } - ++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; + + foundRange = haveLower && haveUpper; + return range; } /*! @@ -3082,134 +3430,124 @@ QCPRange QCPDataContainer::keyRange(bool &foundRange, QCP::SignDomain 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; - } + if (isEmpty()) { + foundRange = false; + return QCPRange(); } - } 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; - } + 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); } - } 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; - } + 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; + + 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. The initial range described by the passed iterators \a begin and \a end is never expanded, only contracted if necessary. - + 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(); + 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<::preallocateGrow(int minimumPreallocSize) template 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); + 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' */ @@ -3247,152 +3584,182 @@ void QCPDataContainer::performAutoSqueeze() class QCP_LIB_DECL QCPSelectionDecorator { - Q_GADGET + 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); - + 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); - + // 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_DISABLE_COPY(QCPSelectionDecorator) + friend class QCPAbstractPlottable; }; -Q_DECLARE_METATYPE(QCPSelectionDecorator*) +Q_DECLARE_METATYPE(QCPSelectionDecorator *) class QCP_LIB_DECL QCPAbstractPlottable : public QCPLayerable { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - 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(QPen pen READ pen WRITE setPen) - Q_PROPERTY(QBrush brush READ brush WRITE setBrush) - Q_PROPERTY(QCPAxis* keyAxis READ keyAxis WRITE setKeyAxis) - Q_PROPERTY(QCPAxis* valueAxis READ valueAxis WRITE setValueAxis) - 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 + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES 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(QPen pen READ pen WRITE setPen) + Q_PROPERTY(QBrush brush READ brush WRITE setBrush) + Q_PROPERTY(QCPAxis *keyAxis READ keyAxis WRITE setKeyAxis) + Q_PROPERTY(QCPAxis *valueAxis READ valueAxis WRITE setValueAxis) + 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; } - QPen pen() const { return mPen; } - QBrush brush() const { return mBrush; } - QCPAxis *keyAxis() const { return mKeyAxis.data(); } - QCPAxis *valueAxis() const { return mValueAxis.data(); } - 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 setPen(const QPen &pen); - void setBrush(const QBrush &brush); - void setKeyAxis(QCPAxis *axis); - void setValueAxis(QCPAxis *axis); - Q_SLOT void setSelectable(QCP::SelectionType selectable); - Q_SLOT void setSelection(QCPDataSelection selection); - void setSelectionDecorator(QCPSelectionDecorator *decorator); + QCPAbstractPlottable(QCPAxis *keyAxis, QCPAxis *valueAxis); + virtual ~QCPAbstractPlottable(); + + // getters: + QString name() const { + return mName; + } + bool antialiasedFill() const { + return mAntialiasedFill; + } + bool antialiasedScatters() const { + return mAntialiasedScatters; + } + QPen pen() const { + return mPen; + } + QBrush brush() const { + return mBrush; + } + QCPAxis *keyAxis() const { + return mKeyAxis.data(); + } + QCPAxis *valueAxis() const { + return mValueAxis.data(); + } + 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 setPen(const QPen &pen); + void setBrush(const QBrush &brush); + void setKeyAxis(QCPAxis *axis); + void setValueAxis(QCPAxis *axis); + Q_SLOT void setSelectable(QCP::SelectionType selectable); + Q_SLOT void setSelection(QCPDataSelection selection); + void setSelectionDecorator(QCPSelectionDecorator *decorator); + + // introduced virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = 0) const Q_DECL_OVERRIDE = 0; // actually introduced in QCPLayerable as non-pure, but we want to force reimplementation for plottables + 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 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; + 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; - // introduced virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const Q_DECL_OVERRIDE = 0; // actually introduced in QCPLayerable as non-pure, but we want to force reimplementation for plottables - 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 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; - 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); - + 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; + // 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; private: - Q_DISABLE_COPY(QCPAbstractPlottable) - - friend class QCustomPlot; - friend class QCPAxis; - friend class QCPPlottableLegendItem; + Q_DISABLE_COPY(QCPAbstractPlottable) + + friend class QCustomPlot; + friend class QCPAxis; + friend class QCPPlottableLegendItem; }; @@ -3404,181 +3771,215 @@ private: class QCP_LIB_DECL QCPItemAnchor { - Q_GADGET + Q_GADGET public: - QCPItemAnchor(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString &name, int anchorId=-1); - virtual ~QCPItemAnchor(); - - // getters: - QString name() const { return mName; } - virtual QPointF pixelPosition() const; - + QCPItemAnchor(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString &name, int anchorId = -1); + virtual ~QCPItemAnchor(); + + // getters: + QString name() const { + return mName; + } + virtual QPointF pixelPosition() const; + protected: - // property members: - QString mName; - - // non-property members: - QCustomPlot *mParentPlot; - QCPAbstractItem *mParentItem; - int mAnchorId; - QSet mChildrenX, mChildrenY; - - // introduced virtual methods: - virtual QCPItemPosition *toQCPItemPosition() { return 0; } - - // non-virtual methods: - void addChildX(QCPItemPosition* pos); // called from pos when this anchor is set as parent - void removeChildX(QCPItemPosition *pos); // called from pos when its parent anchor is reset or pos deleted - void addChildY(QCPItemPosition* pos); // called from pos when this anchor is set as parent - void removeChildY(QCPItemPosition *pos); // called from pos when its parent anchor is reset or pos deleted - + // property members: + QString mName; + + // non-property members: + QCustomPlot *mParentPlot; + QCPAbstractItem *mParentItem; + int mAnchorId; + QSet mChildrenX, mChildrenY; + + // introduced virtual methods: + virtual QCPItemPosition *toQCPItemPosition() { + return 0; + } + + // non-virtual methods: + void addChildX(QCPItemPosition *pos); // called from pos when this anchor is set as parent + void removeChildX(QCPItemPosition *pos); // called from pos when its parent anchor is reset or pos deleted + void addChildY(QCPItemPosition *pos); // called from pos when this anchor is set as parent + void removeChildY(QCPItemPosition *pos); // called from pos when its parent anchor is reset or pos deleted + private: - Q_DISABLE_COPY(QCPItemAnchor) - - friend class QCPItemPosition; + Q_DISABLE_COPY(QCPItemAnchor) + + friend class QCPItemPosition; }; class QCP_LIB_DECL QCPItemPosition : public QCPItemAnchor { - Q_GADGET + Q_GADGET public: - /*! - Defines the ways an item position can be specified. Thus it defines what the numbers passed to - \ref setCoords actually mean. - - \see setType - */ - enum PositionType { ptAbsolute ///< Static positioning in pixels, starting from the top left corner of the viewport/widget. - ,ptViewportRatio ///< Static positioning given by a fraction of the viewport size. For example, if you call setCoords(0, 0), the position will be at the top - ///< left corner of the viewport/widget. setCoords(1, 1) will be at the bottom right corner, setCoords(0.5, 0) will be horizontally centered and - ///< vertically at the top of the viewport/widget, etc. - ,ptAxisRectRatio ///< Static positioning given by a fraction of the axis rect size (see \ref setAxisRect). For example, if you call setCoords(0, 0), the position will be at the top - ///< left corner of the axis rect. setCoords(1, 1) will be at the bottom right corner, setCoords(0.5, 0) will be horizontally centered and - ///< 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); - virtual ~QCPItemPosition(); - - // getters: - PositionType type() const { return typeX(); } - PositionType typeX() const { return mPositionTypeX; } - PositionType typeY() const { return mPositionTypeY; } - QCPItemAnchor *parentAnchor() const { return parentAnchorX(); } - QCPItemAnchor *parentAnchorX() const { return mParentAnchorX; } - QCPItemAnchor *parentAnchorY() const { return mParentAnchorY; } - double key() const { return mKey; } - double value() const { return mValue; } - QPointF coords() const { return QPointF(mKey, mValue); } - QCPAxis *keyAxis() const { return mKeyAxis.data(); } - QCPAxis *valueAxis() const { return mValueAxis.data(); } - QCPAxisRect *axisRect() const; - virtual QPointF pixelPosition() const Q_DECL_OVERRIDE; - - // setters: - void setType(PositionType type); - void setTypeX(PositionType type); - void setTypeY(PositionType type); - bool setParentAnchor(QCPItemAnchor *parentAnchor, bool keepPixelPosition=false); - bool setParentAnchorX(QCPItemAnchor *parentAnchor, bool keepPixelPosition=false); - bool setParentAnchorY(QCPItemAnchor *parentAnchor, bool keepPixelPosition=false); - void setCoords(double key, double value); - void setCoords(const QPointF &coords); - void setAxes(QCPAxis* keyAxis, QCPAxis* valueAxis); - void setAxisRect(QCPAxisRect *axisRect); - void setPixelPosition(const QPointF &pixelPosition); - + /*! + Defines the ways an item position can be specified. Thus it defines what the numbers passed to + \ref setCoords actually mean. + + \see setType + */ + enum PositionType { ptAbsolute ///< Static positioning in pixels, starting from the top left corner of the viewport/widget. + , ptViewportRatio ///< Static positioning given by a fraction of the viewport size. For example, if you call setCoords(0, 0), the position will be at the top + ///< left corner of the viewport/widget. setCoords(1, 1) will be at the bottom right corner, setCoords(0.5, 0) will be horizontally centered and + ///< vertically at the top of the viewport/widget, etc. + , ptAxisRectRatio ///< Static positioning given by a fraction of the axis rect size (see \ref setAxisRect). For example, if you call setCoords(0, 0), the position will be at the top + ///< left corner of the axis rect. setCoords(1, 1) will be at the bottom right corner, setCoords(0.5, 0) will be horizontally centered and + ///< 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); + virtual ~QCPItemPosition(); + + // getters: + PositionType type() const { + return typeX(); + } + PositionType typeX() const { + return mPositionTypeX; + } + PositionType typeY() const { + return mPositionTypeY; + } + QCPItemAnchor *parentAnchor() const { + return parentAnchorX(); + } + QCPItemAnchor *parentAnchorX() const { + return mParentAnchorX; + } + QCPItemAnchor *parentAnchorY() const { + return mParentAnchorY; + } + double key() const { + return mKey; + } + double value() const { + return mValue; + } + QPointF coords() const { + return QPointF(mKey, mValue); + } + QCPAxis *keyAxis() const { + return mKeyAxis.data(); + } + QCPAxis *valueAxis() const { + return mValueAxis.data(); + } + QCPAxisRect *axisRect() const; + virtual QPointF pixelPosition() const Q_DECL_OVERRIDE; + + // setters: + void setType(PositionType type); + void setTypeX(PositionType type); + void setTypeY(PositionType type); + bool setParentAnchor(QCPItemAnchor *parentAnchor, bool keepPixelPosition = false); + bool setParentAnchorX(QCPItemAnchor *parentAnchor, bool keepPixelPosition = false); + bool setParentAnchorY(QCPItemAnchor *parentAnchor, bool keepPixelPosition = false); + void setCoords(double key, double value); + void setCoords(const QPointF &coords); + void setAxes(QCPAxis *keyAxis, QCPAxis *valueAxis); + void setAxisRect(QCPAxisRect *axisRect); + void setPixelPosition(const QPointF &pixelPosition); + protected: - // property members: - PositionType mPositionTypeX, mPositionTypeY; - QPointer mKeyAxis, mValueAxis; - QPointer mAxisRect; - double mKey, mValue; - QCPItemAnchor *mParentAnchorX, *mParentAnchorY; - - // reimplemented virtual methods: - virtual QCPItemPosition *toQCPItemPosition() Q_DECL_OVERRIDE { return this; } - + // property members: + PositionType mPositionTypeX, mPositionTypeY; + QPointer mKeyAxis, mValueAxis; + QPointer mAxisRect; + double mKey, mValue; + QCPItemAnchor *mParentAnchorX, *mParentAnchorY; + + // reimplemented virtual methods: + virtual QCPItemPosition *toQCPItemPosition() Q_DECL_OVERRIDE { return this; } + private: - Q_DISABLE_COPY(QCPItemPosition) - + Q_DISABLE_COPY(QCPItemPosition) + }; Q_DECLARE_METATYPE(QCPItemPosition::PositionType) class QCP_LIB_DECL QCPAbstractItem : public QCPLayerable { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(bool clipToAxisRect READ clipToAxisRect WRITE setClipToAxisRect) - Q_PROPERTY(QCPAxisRect* clipAxisRect READ clipAxisRect WRITE setClipAxisRect) - Q_PROPERTY(bool selectable READ selectable WRITE setSelectable NOTIFY selectableChanged) - Q_PROPERTY(bool selected READ selected WRITE setSelected NOTIFY selectionChanged) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(bool clipToAxisRect READ clipToAxisRect WRITE setClipToAxisRect) Q_PROPERTY(QCPAxisRect *clipAxisRect READ clipAxisRect WRITE setClipAxisRect) + Q_PROPERTY(bool selectable READ selectable WRITE setSelectable NOTIFY selectableChanged) + Q_PROPERTY(bool selected READ selected WRITE setSelected NOTIFY selectionChanged) + /// \endcond public: - explicit QCPAbstractItem(QCustomPlot *parentPlot); - virtual ~QCPAbstractItem(); - - // getters: - bool clipToAxisRect() const { return mClipToAxisRect; } - QCPAxisRect *clipAxisRect() const; - bool selectable() const { return mSelectable; } - bool selected() const { return mSelected; } - - // setters: - void setClipToAxisRect(bool clip); - void setClipAxisRect(QCPAxisRect *rect); - Q_SLOT void setSelectable(bool selectable); - Q_SLOT void setSelected(bool selected); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const Q_DECL_OVERRIDE = 0; - - // non-virtual methods: - QList positions() const { return mPositions; } - QList anchors() const { return mAnchors; } - QCPItemPosition *position(const QString &name) const; - QCPItemAnchor *anchor(const QString &name) const; - bool hasAnchor(const QString &name) const; - + explicit QCPAbstractItem(QCustomPlot *parentPlot); + virtual ~QCPAbstractItem(); + + // getters: + bool clipToAxisRect() const { + return mClipToAxisRect; + } + QCPAxisRect *clipAxisRect() const; + bool selectable() const { + return mSelectable; + } + bool selected() const { + return mSelected; + } + + // setters: + void setClipToAxisRect(bool clip); + void setClipAxisRect(QCPAxisRect *rect); + Q_SLOT void setSelectable(bool selectable); + Q_SLOT void setSelected(bool selected); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = 0) const Q_DECL_OVERRIDE = 0; + + // non-virtual methods: + QList positions() const { + return mPositions; + } + QList anchors() const { + return mAnchors; + } + QCPItemPosition *position(const QString &name) const; + QCPItemAnchor *anchor(const QString &name) const; + bool hasAnchor(const QString &name) const; + signals: - void selectionChanged(bool selected); - void selectableChanged(bool selectable); - + void selectionChanged(bool selected); + void selectableChanged(bool selectable); + protected: - // property members: - bool mClipToAxisRect; - QPointer mClipAxisRect; - QList mPositions; - QList mAnchors; - bool mSelectable, mSelected; - - // reimplemented virtual methods: - 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) Q_DECL_OVERRIDE; - virtual void deselectEvent(bool *selectionStateChanged) Q_DECL_OVERRIDE; - - // introduced virtual methods: - virtual QPointF anchorPixelPosition(int anchorId) const; - - // non-virtual methods: - double rectDistance(const QRectF &rect, const QPointF &pos, bool filledRect) const; - QCPItemPosition *createPosition(const QString &name); - QCPItemAnchor *createAnchor(const QString &name, int anchorId); - + // property members: + bool mClipToAxisRect; + QPointer mClipAxisRect; + QList mPositions; + QList mAnchors; + bool mSelectable, mSelected; + + // reimplemented virtual methods: + 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) Q_DECL_OVERRIDE; + virtual void deselectEvent(bool *selectionStateChanged) Q_DECL_OVERRIDE; + + // introduced virtual methods: + virtual QPointF anchorPixelPosition(int anchorId) const; + + // non-virtual methods: + double rectDistance(const QRectF &rect, const QPointF &pos, bool filledRect) const; + QCPItemPosition *createPosition(const QString &name); + QCPItemAnchor *createAnchor(const QString &name, int anchorId); + private: - Q_DISABLE_COPY(QCPAbstractItem) - - friend class QCustomPlot; - friend class QCPItemAnchor; + Q_DISABLE_COPY(QCPAbstractItem) + + friend class QCustomPlot; + friend class QCPItemAnchor; }; /* end of 'src/item.h' */ @@ -3589,262 +3990,296 @@ private: class QCP_LIB_DECL QCustomPlot : public QWidget { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QRect viewport READ viewport WRITE setViewport) - Q_PROPERTY(QPixmap background READ background WRITE setBackground) - Q_PROPERTY(bool backgroundScaled READ backgroundScaled WRITE setBackgroundScaled) - Q_PROPERTY(Qt::AspectRatioMode backgroundScaledMode READ backgroundScaledMode WRITE setBackgroundScaledMode) - Q_PROPERTY(QCPLayoutGrid* plotLayout READ plotLayout) - Q_PROPERTY(bool autoAddPlottableToLegend READ autoAddPlottableToLegend WRITE setAutoAddPlottableToLegend) - 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 + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(QRect viewport READ viewport WRITE setViewport) + Q_PROPERTY(QPixmap background READ background WRITE setBackground) + Q_PROPERTY(bool backgroundScaled READ backgroundScaled WRITE setBackgroundScaled) + Q_PROPERTY(Qt::AspectRatioMode backgroundScaledMode READ backgroundScaledMode WRITE setBackgroundScaledMode) + Q_PROPERTY(QCPLayoutGrid *plotLayout READ plotLayout) + Q_PROPERTY(bool autoAddPlottableToLegend READ autoAddPlottableToLegend WRITE setAutoAddPlottableToLegend) + 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: - /*! - Defines how a layer should be inserted relative to an other layer. + /*! + Defines how a layer should be inserted relative to an other layer. - \see addLayer, moveLayer - */ - enum LayerInsertMode { limBelow ///< Layer is inserted below other layer - ,limAbove ///< Layer is inserted above other layer - }; - Q_ENUMS(LayerInsertMode) - - /*! - Defines with what timing the QCustomPlot surface is refreshed after a replot. + \see addLayer, moveLayer + */ + enum LayerInsertMode { limBelow ///< Layer is inserted below other layer + , limAbove ///< Layer is inserted above other layer + }; + Q_ENUMS(LayerInsertMode) - \see replot - */ - 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; } - QCPLayoutGrid *plotLayout() const { return mPlotLayout; } - QCP::AntialiasedElements antialiasedElements() const { return mAntialiasedElements; } - QCP::AntialiasedElements notAntialiasedElements() const { return mNotAntialiasedElements; } - bool autoAddPlottableToLegend() const { return mAutoAddPlottableToLegend; } - const QCP::Interactions interactions() const { return mInteractions; } - int selectionTolerance() const { return mSelectionTolerance; } - 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); - void setBackgroundScaled(bool scaled); - void setBackgroundScaledMode(Qt::AspectRatioMode mode); - void setAntialiasedElements(const QCP::AntialiasedElements &antialiasedElements); - void setAntialiasedElement(QCP::AntialiasedElement antialiasedElement, bool enabled=true); - void setNotAntialiasedElements(const QCP::AntialiasedElements ¬AntialiasedElements); - void setNotAntialiasedElement(QCP::AntialiasedElement notAntialiasedElement, bool enabled=true); - void setAutoAddPlottableToLegend(bool on); - void setInteractions(const QCP::Interactions &interactions); - void setInteraction(const QCP::Interaction &interaction, bool enabled=true); - void setSelectionTolerance(int pixels); - void setNoAntialiasingOnDrag(bool enabled); - 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 removePlottable(QCPAbstractPlottable *plottable); - bool removePlottable(int index); - int clearPlottables(); - int plottableCount() const; - QList selectedPlottables() const; - QCPAbstractPlottable *plottableAt(const QPointF &pos, bool onlySelectable=false) const; - bool hasPlottable(QCPAbstractPlottable *plottable) const; - - // specialized interface for QCPGraph: - QCPGraph *graph(int index) const; - QCPGraph *graph() const; - QCPGraph *addGraph(QCPAxis *keyAxis=0, QCPAxis *valueAxis=0); - bool removeGraph(QCPGraph *graph); - bool removeGraph(int index); - int clearGraphs(); - int graphCount() const; - QList selectedGraphs() const; + /*! + Defines with what timing the QCustomPlot surface is refreshed after a replot. + + \see replot + */ + 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; + } + QCPLayoutGrid *plotLayout() const { + return mPlotLayout; + } + QCP::AntialiasedElements antialiasedElements() const { + return mAntialiasedElements; + } + QCP::AntialiasedElements notAntialiasedElements() const { + return mNotAntialiasedElements; + } + bool autoAddPlottableToLegend() const { + return mAutoAddPlottableToLegend; + } + const QCP::Interactions interactions() const { + return mInteractions; + } + int selectionTolerance() const { + return mSelectionTolerance; + } + 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); + void setBackgroundScaled(bool scaled); + void setBackgroundScaledMode(Qt::AspectRatioMode mode); + void setAntialiasedElements(const QCP::AntialiasedElements &antialiasedElements); + void setAntialiasedElement(QCP::AntialiasedElement antialiasedElement, bool enabled = true); + void setNotAntialiasedElements(const QCP::AntialiasedElements ¬AntialiasedElements); + void setNotAntialiasedElement(QCP::AntialiasedElement notAntialiasedElement, bool enabled = true); + void setAutoAddPlottableToLegend(bool on); + void setInteractions(const QCP::Interactions &interactions); + void setInteraction(const QCP::Interaction &interaction, bool enabled = true); + void setSelectionTolerance(int pixels); + void setNoAntialiasingOnDrag(bool enabled); + 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 removePlottable(QCPAbstractPlottable *plottable); + bool removePlottable(int index); + int clearPlottables(); + int plottableCount() const; + QList selectedPlottables() const; + QCPAbstractPlottable *plottableAt(const QPointF &pos, bool onlySelectable = false) const; + bool hasPlottable(QCPAbstractPlottable *plottable) const; + + // specialized interface for QCPGraph: + QCPGraph *graph(int index) const; + QCPGraph *graph() const; + QCPGraph *addGraph(QCPAxis *keyAxis = 0, QCPAxis *valueAxis = 0); + bool removeGraph(QCPGraph *graph); + bool removeGraph(int index); + int clearGraphs(); + int graphCount() const; + QList selectedGraphs() const; + + // item interface: + QCPAbstractItem *item(int index) const; + QCPAbstractItem *item() const; + bool removeItem(QCPAbstractItem *item); + bool removeItem(int index); + int clearItems(); + int itemCount() const; + QList selectedItems() const; + QCPAbstractItem *itemAt(const QPointF &pos, bool onlySelectable = false) const; + bool hasItem(QCPAbstractItem *item) const; + + // layer interface: + QCPLayer *layer(const QString &name) const; + QCPLayer *layer(int index) const; + QCPLayer *currentLayer() const; + bool setCurrentLayer(const QString &name); + bool setCurrentLayer(QCPLayer *layer); + int layerCount() const; + bool addLayer(const QString &name, QCPLayer *otherLayer = 0, LayerInsertMode insertMode = limAbove); + bool removeLayer(QCPLayer *layer); + bool moveLayer(QCPLayer *layer, QCPLayer *otherLayer, LayerInsertMode insertMode = limAbove); + + // axis rect/layout interface: + int axisRectCount() const; + 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, 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::rpRefreshHint); + + QCPAxis *xAxis, *yAxis, *xAxis2, *yAxis2; + QCPLegend *legend; - // item interface: - QCPAbstractItem *item(int index) const; - QCPAbstractItem *item() const; - bool removeItem(QCPAbstractItem *item); - bool removeItem(int index); - int clearItems(); - int itemCount() const; - QList selectedItems() const; - QCPAbstractItem *itemAt(const QPointF &pos, bool onlySelectable=false) const; - bool hasItem(QCPAbstractItem *item) const; - - // layer interface: - QCPLayer *layer(const QString &name) const; - QCPLayer *layer(int index) const; - QCPLayer *currentLayer() const; - bool setCurrentLayer(const QString &name); - bool setCurrentLayer(QCPLayer *layer); - int layerCount() const; - bool addLayer(const QString &name, QCPLayer *otherLayer=0, LayerInsertMode insertMode=limAbove); - bool removeLayer(QCPLayer *layer); - bool moveLayer(QCPLayer *layer, QCPLayer *otherLayer, LayerInsertMode insertMode=limAbove); - - // axis rect/layout interface: - int axisRectCount() const; - 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, 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::rpRefreshHint); - - QCPAxis *xAxis, *yAxis, *xAxis2, *yAxis2; - QCPLegend *legend; - signals: - void mouseDoubleClick(QMouseEvent *event); - void mousePress(QMouseEvent *event); - void mouseMove(QMouseEvent *event); - void mouseRelease(QMouseEvent *event); - void mouseWheel(QWheelEvent *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 selectionChangedByUser(); - void beforeReplot(); - void afterReplot(); - + void mouseDoubleClick(QMouseEvent *event); + void mousePress(QMouseEvent *event); + void mouseMove(QMouseEvent *event); + void mouseRelease(QMouseEvent *event); + void mouseWheel(QWheelEvent *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 selectionChangedByUser(); + void beforeReplot(); + void afterReplot(); + protected: - // property members: - QRect mViewport; - double mBufferDevicePixelRatio; - QCPLayoutGrid *mPlotLayout; - bool mAutoAddPlottableToLegend; - QList mPlottables; - QList mGraphs; // extra list of plottables also in mPlottables that are of type QCPGraph - QList mItems; - QList mLayers; - QCP::AntialiasedElements mAntialiasedElements, mNotAntialiasedElements; - QCP::Interactions mInteractions; - int mSelectionTolerance; - bool mNoAntialiasingOnDrag; - QBrush mBackgroundBrush; - QPixmap mBackgroundPixmap; - QPixmap mScaledBackgroundPixmap; - bool mBackgroundScaled; - Qt::AspectRatioMode mBackgroundScaledMode; - QCPLayer *mCurrentLayer; - QCP::PlottingHints mPlottingHints; - Qt::KeyboardModifier mMultiSelectModifier; - QCP::SelectionRectMode mSelectionRectMode; - QCPSelectionRect *mSelectionRect; - bool mOpenGl; - - // non-property members: - QList > mPaintBuffers; - QPoint mMousePressPos; - bool mMouseHasMoved; - QPointer mMouseEventLayerable; - QPointer mMouseSignalLayerable; - QVariant mMouseEventLayerableDetails; - QVariant mMouseSignalLayerableDetails; - bool mReplotting; - bool mReplotQueued; - int mOpenGlMultisamples; - QCP::AntialiasedElements mOpenGlAntialiasedElementsBackup; - bool mOpenGlCacheLabelsBackup; + // property members: + QRect mViewport; + double mBufferDevicePixelRatio; + QCPLayoutGrid *mPlotLayout; + bool mAutoAddPlottableToLegend; + QList mPlottables; + QList mGraphs; // extra list of plottables also in mPlottables that are of type QCPGraph + QList mItems; + QList mLayers; + QCP::AntialiasedElements mAntialiasedElements, mNotAntialiasedElements; + QCP::Interactions mInteractions; + int mSelectionTolerance; + bool mNoAntialiasingOnDrag; + QBrush mBackgroundBrush; + QPixmap mBackgroundPixmap; + QPixmap mScaledBackgroundPixmap; + bool mBackgroundScaled; + Qt::AspectRatioMode mBackgroundScaledMode; + QCPLayer *mCurrentLayer; + QCP::PlottingHints mPlottingHints; + Qt::KeyboardModifier mMultiSelectModifier; + QCP::SelectionRectMode mSelectionRectMode; + QCPSelectionRect *mSelectionRect; + bool mOpenGl; + + // non-property members: + QList > mPaintBuffers; + QPoint mMousePressPos; + bool mMouseHasMoved; + QPointer mMouseEventLayerable; + QPointer mMouseSignalLayerable; + QVariant mMouseEventLayerableDetails; + QVariant mMouseSignalLayerableDetails; + bool mReplotting; + bool mReplotQueued; + int mOpenGlMultisamples; + QCP::AntialiasedElements mOpenGlAntialiasedElementsBackup; + bool mOpenGlCacheLabelsBackup; #ifdef QCP_OPENGL_FBO - QSharedPointer mGlContext; - QSharedPointer mGlSurface; - QSharedPointer mGlPaintDevice; + QSharedPointer mGlContext; + QSharedPointer mGlSurface; + QSharedPointer mGlPaintDevice; #endif - - // reimplemented virtual methods: - 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; + + // reimplemented virtual methods: + 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) @@ -3858,56 +4293,56 @@ Q_DECLARE_METATYPE(QCustomPlot::RefreshPriority) class QCPPlottableInterface1D { public: - virtual ~QCPPlottableInterface1D() {} - // 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; + virtual ~QCPPlottableInterface1D() {} + // 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 QCPAbstractPlottable1D : public QCPAbstractPlottable, public QCPPlottableInterface1D // no QCP_LIB_DECL, template class ends up in header (cpp included below) { - // No Q_OBJECT macro due to template class - + // 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 Q_DECL_OVERRIDE; - virtual double dataMainKey(int index) const Q_DECL_OVERRIDE; - virtual double dataSortKey(int index) const Q_DECL_OVERRIDE; - virtual double dataMainValue(int index) const Q_DECL_OVERRIDE; - virtual QCPRange dataValueRange(int index) const Q_DECL_OVERRIDE; - virtual QPointF dataPixelPosition(int index) const Q_DECL_OVERRIDE; - virtual bool sortKeyIsMainKey() const Q_DECL_OVERRIDE; - virtual QCPDataSelection selectTestRect(const QRectF &rect, bool onlySelectable) const Q_DECL_OVERRIDE; - virtual int findBegin(double sortKey, bool expandedRange=true) const Q_DECL_OVERRIDE; - virtual int findEnd(double sortKey, bool expandedRange=true) const Q_DECL_OVERRIDE; - - // 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; } - + QCPAbstractPlottable1D(QCPAxis *keyAxis, QCPAxis *valueAxis); + virtual ~QCPAbstractPlottable1D(); + + // virtual methods of 1d plottable interface: + virtual int dataCount() const Q_DECL_OVERRIDE; + virtual double dataMainKey(int index) const Q_DECL_OVERRIDE; + virtual double dataSortKey(int index) const Q_DECL_OVERRIDE; + virtual double dataMainValue(int index) const Q_DECL_OVERRIDE; + virtual QCPRange dataValueRange(int index) const Q_DECL_OVERRIDE; + virtual QPointF dataPixelPosition(int index) const Q_DECL_OVERRIDE; + virtual bool sortKeyIsMainKey() const Q_DECL_OVERRIDE; + virtual QCPDataSelection selectTestRect(const QRectF &rect, bool onlySelectable) const Q_DECL_OVERRIDE; + virtual int findBegin(double sortKey, bool expandedRange = true) const Q_DECL_OVERRIDE; + virtual int findEnd(double sortKey, bool expandedRange = true) const Q_DECL_OVERRIDE; + + // 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; - - // helpers for subclasses: - void getDataSegments(QList &selectedSegments, QList &unselectedSegments) const; - void drawPolyline(QCPPainter *painter, const QVector &lineData) const; + // 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) - + Q_DISABLE_COPY(QCPAbstractPlottable1D) + }; // include implementation in header since it is a class template: @@ -3945,55 +4380,55 @@ private: /* 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. @@ -4087,10 +4522,10 @@ private: /* start documentation of inline functions */ /*! \fn QCPPlottableInterface1D *QCPAbstractPlottable1D::interface1D() - + Returns a \ref QCPPlottableInterface1D pointer to this plottable, providing access to its 1D interface. - + \seebaseclassmethod */ @@ -4102,8 +4537,8 @@ private: */ template QCPAbstractPlottable1D::QCPAbstractPlottable1D(QCPAxis *keyAxis, QCPAxis *valueAxis) : - QCPAbstractPlottable(keyAxis, valueAxis), - mDataContainer(new QCPDataContainer) + QCPAbstractPlottable(keyAxis, valueAxis), + mDataContainer(new QCPDataContainer) { } @@ -4118,7 +4553,7 @@ QCPAbstractPlottable1D::~QCPAbstractPlottable1D() template int QCPAbstractPlottable1D::dataCount() const { - return mDataContainer->size(); + return mDataContainer->size(); } /*! @@ -4127,14 +4562,12 @@ int QCPAbstractPlottable1D::dataCount() const 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; - } + if (index >= 0 && index < mDataContainer->size()) { + return (mDataContainer->constBegin() + index)->mainKey(); + } else { + qDebug() << Q_FUNC_INFO << "Index out of bounds" << index; + return 0; + } } /*! @@ -4143,14 +4576,12 @@ double QCPAbstractPlottable1D::dataMainKey(int index) const 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; - } + if (index >= 0 && index < mDataContainer->size()) { + return (mDataContainer->constBegin() + index)->sortKey(); + } else { + qDebug() << Q_FUNC_INFO << "Index out of bounds" << index; + return 0; + } } /*! @@ -4159,14 +4590,12 @@ double QCPAbstractPlottable1D::dataSortKey(int index) const 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; - } + if (index >= 0 && index < mDataContainer->size()) { + return (mDataContainer->constBegin() + index)->mainValue(); + } else { + qDebug() << Q_FUNC_INFO << "Index out of bounds" << index; + return 0; + } } /*! @@ -4175,14 +4604,12 @@ double QCPAbstractPlottable1D::dataMainValue(int index) const 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); - } + 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); + } } /*! @@ -4191,15 +4618,13 @@ QCPRange QCPAbstractPlottable1D::dataValueRange(int index) const 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(); - } + 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(); + } } /*! @@ -4208,7 +4633,7 @@ QPointF QCPAbstractPlottable1D::dataPixelPosition(int index) const template bool QCPAbstractPlottable1D::sortKeyIsMainKey() const { - return DataType::sortKeyIsMainKey(); + return DataType::sortKeyIsMainKey(); } /*! @@ -4221,47 +4646,48 @@ bool QCPAbstractPlottable1D::sortKeyIsMainKey() const 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; + QCPDataSelection result; + if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty()) { + return result; } - } - // process potential last segment: - if (currentSegmentBegin != -1) - result.addDataRange(QCPDataRange(currentSegmentBegin, end-mDataContainer->constBegin()), false); - - result.simplify(); - 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; } /*! @@ -4270,7 +4696,7 @@ QCPDataSelection QCPAbstractPlottable1D::selectTestRect(const QRectF & template int QCPAbstractPlottable1D::findBegin(double sortKey, bool expandedRange) const { - return mDataContainer->findBegin(sortKey, expandedRange)-mDataContainer->constBegin(); + return mDataContainer->findBegin(sortKey, expandedRange) - mDataContainer->constBegin(); } /*! @@ -4279,7 +4705,7 @@ int QCPAbstractPlottable1D::findBegin(double sortKey, bool expandedRan template int QCPAbstractPlottable1D::findEnd(double sortKey, bool expandedRange) const { - return mDataContainer->findEnd(sortKey, expandedRange)-mDataContainer->constBegin(); + return mDataContainer->findEnd(sortKey, expandedRange) - mDataContainer->constBegin(); } /*! @@ -4289,59 +4715,61 @@ int QCPAbstractPlottable1D::findEnd(double sortKey, bool expandedRange If \a details is not 0, it will be set to a \ref QCPDataSelection, describing the closest data point to \a pos. - + \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 ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty()) { + return -1; } - } - if (minDistIndex != mDataContainer->size()) - selectionResult.addDataRange(QCPDataRange(minDistIndex, minDistIndex+1), false); - - selectionResult.simplify(); - if (details) - details->setValue(selectionResult); - return qSqrt(minDistSqr); + 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); } /*! @@ -4357,21 +4785,20 @@ double QCPAbstractPlottable1D::selectTest(const QPointF &pos, bool onl 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(); - } + 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(); + } } /*! @@ -4387,47 +4814,44 @@ void QCPAbstractPlottable1D::getDataSegments(QList &sele 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; + // 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); } - } 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' */ @@ -4440,77 +4864,87 @@ void QCPAbstractPlottable1D::drawPolyline(QCPPainter *painter, const Q class QCP_LIB_DECL QCPColorGradient { - Q_GADGET + Q_GADGET public: - /*! - Defines the color spaces in which color interpolation between gradient stops can be performed. - - \see setColorInterpolation - */ - enum ColorInterpolation { ciRGB ///< Color channels red, green and blue are linearly interpolated - ,ciHSV ///< Color channels hue, saturation and value are linearly interpolated (The hue is interpolated over the shortest angle distance) - }; - Q_ENUMS(ColorInterpolation) - - /*! - Defines the available presets that can be loaded with \ref loadPreset. See the documentation - there for an image of the presets. - */ - enum GradientPreset { gpGrayscale ///< Continuous lightness from black to white (suited for non-biased data representation) - ,gpHot ///< Continuous lightness from black over firey colors to white (suited for non-biased data representation) - ,gpCold ///< Continuous lightness from black over icey colors to white (suited for non-biased data representation) - ,gpNight ///< Continuous lightness from black over weak blueish colors to white (suited for non-biased data representation) - ,gpCandy ///< Blue over pink to white - ,gpGeography ///< Colors suitable to represent different elevations on geographical maps - ,gpIon ///< Half hue spectrum from black over purple to blue and finally green (creates banding illusion but allows more precise magnitude estimates) - ,gpThermal ///< Colors suitable for thermal imaging, ranging from dark blue over purple to orange, yellow and white - ,gpPolar ///< Colors suitable to emphasize polarity around the center, with blue for negative, black in the middle and red for positive values - ,gpSpectrum ///< An approximation of the visible light spectrum (creates banding illusion but allows more precise magnitude estimates) - ,gpJet ///< Hue variation similar to a spectrum, often used in numerical visualization (creates banding illusion but allows more precise magnitude estimates) - ,gpHues ///< Full hue cycle, with highest and lowest color red (suitable for periodic data, such as angles and phases, see \ref setPeriodic) - }; - Q_ENUMS(GradientPreset) - - QCPColorGradient(); - QCPColorGradient(GradientPreset preset); - bool operator==(const QCPColorGradient &other) const; - bool operator!=(const QCPColorGradient &other) const { return !(*this == other); } - - // getters: - int levelCount() const { return mLevelCount; } - QMap colorStops() const { return mColorStops; } - ColorInterpolation colorInterpolation() const { return mColorInterpolation; } - bool periodic() const { return mPeriodic; } - - // setters: - void setLevelCount(int n); - void setColorStops(const QMap &colorStops); - void setColorStopAt(double position, const QColor &color); - void setColorInterpolation(ColorInterpolation interpolation); - void setPeriodic(bool enabled); - - // 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; - + /*! + Defines the color spaces in which color interpolation between gradient stops can be performed. + + \see setColorInterpolation + */ + enum ColorInterpolation { ciRGB ///< Color channels red, green and blue are linearly interpolated + , ciHSV ///< Color channels hue, saturation and value are linearly interpolated (The hue is interpolated over the shortest angle distance) + }; + Q_ENUMS(ColorInterpolation) + + /*! + Defines the available presets that can be loaded with \ref loadPreset. See the documentation + there for an image of the presets. + */ + enum GradientPreset { gpGrayscale ///< Continuous lightness from black to white (suited for non-biased data representation) + , gpHot ///< Continuous lightness from black over firey colors to white (suited for non-biased data representation) + , gpCold ///< Continuous lightness from black over icey colors to white (suited for non-biased data representation) + , gpNight ///< Continuous lightness from black over weak blueish colors to white (suited for non-biased data representation) + , gpCandy ///< Blue over pink to white + , gpGeography ///< Colors suitable to represent different elevations on geographical maps + , gpIon ///< Half hue spectrum from black over purple to blue and finally green (creates banding illusion but allows more precise magnitude estimates) + , gpThermal ///< Colors suitable for thermal imaging, ranging from dark blue over purple to orange, yellow and white + , gpPolar ///< Colors suitable to emphasize polarity around the center, with blue for negative, black in the middle and red for positive values + , gpSpectrum ///< An approximation of the visible light spectrum (creates banding illusion but allows more precise magnitude estimates) + , gpJet ///< Hue variation similar to a spectrum, often used in numerical visualization (creates banding illusion but allows more precise magnitude estimates) + , gpHues ///< Full hue cycle, with highest and lowest color red (suitable for periodic data, such as angles and phases, see \ref setPeriodic) + }; + Q_ENUMS(GradientPreset) + + QCPColorGradient(); + QCPColorGradient(GradientPreset preset); + bool operator==(const QCPColorGradient &other) const; + bool operator!=(const QCPColorGradient &other) const { + return !(*this == other); + } + + // getters: + int levelCount() const { + return mLevelCount; + } + QMap colorStops() const { + return mColorStops; + } + ColorInterpolation colorInterpolation() const { + return mColorInterpolation; + } + bool periodic() const { + return mPeriodic; + } + + // setters: + void setLevelCount(int n); + void setColorStops(const QMap &colorStops); + void setColorStopAt(double position, const QColor &color); + void setColorInterpolation(ColorInterpolation interpolation); + void setPeriodic(bool enabled); + + // 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: - // property members: - int mLevelCount; - QMap mColorStops; - ColorInterpolation mColorInterpolation; - bool mPeriodic; - - // non-property members: - QVector mColorBuffer; // have colors premultiplied with alpha (for usage with QImage::Format_ARGB32_Premultiplied) - bool mColorBufferInvalidated; - - // non-virtual methods: - bool stopsUseAlpha() const; - void updateColorBuffer(); + // property members: + int mLevelCount; + QMap mColorStops; + ColorInterpolation mColorInterpolation; + bool mPeriodic; + + // non-property members: + 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) @@ -4523,64 +4957,78 @@ Q_DECLARE_METATYPE(QCPColorGradient::GradientPreset) class QCP_LIB_DECL QCPSelectionDecoratorBracket : public QCPSelectionDecorator { - Q_GADGET + 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) Q_DECL_OVERRIDE; - + + /*! + 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) Q_DECL_OVERRIDE; + 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; - + // 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) @@ -4592,121 +5040,157 @@ Q_DECLARE_METATYPE(QCPSelectionDecoratorBracket::BracketStyle) class QCP_LIB_DECL QCPAxisRect : public QCPLayoutElement { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QPixmap background READ background WRITE setBackground) - Q_PROPERTY(bool backgroundScaled READ backgroundScaled WRITE setBackgroundScaled) - Q_PROPERTY(Qt::AspectRatioMode backgroundScaledMode READ backgroundScaledMode WRITE setBackgroundScaledMode) - Q_PROPERTY(Qt::Orientations rangeDrag READ rangeDrag WRITE setRangeDrag) - Q_PROPERTY(Qt::Orientations rangeZoom READ rangeZoom WRITE setRangeZoom) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QPixmap background READ background WRITE setBackground) Q_PROPERTY(bool backgroundScaled READ backgroundScaled WRITE setBackgroundScaled) + Q_PROPERTY(Qt::AspectRatioMode backgroundScaledMode READ backgroundScaledMode WRITE setBackgroundScaledMode) + Q_PROPERTY(Qt::Orientations rangeDrag READ rangeDrag WRITE setRangeDrag) + Q_PROPERTY(Qt::Orientations rangeZoom READ rangeZoom WRITE setRangeZoom) + /// \endcond public: - explicit QCPAxisRect(QCustomPlot *parentPlot, bool setupDefaultAxes=true); - virtual ~QCPAxisRect(); - - // 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: - void setBackground(const QPixmap &pm); - void setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode=Qt::KeepAspectRatioByExpanding); - void setBackground(const QBrush &brush); - void setBackgroundScaled(bool scaled); - void setBackgroundScaledMode(Qt::AspectRatioMode mode); - 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); - - // non-property methods: - int axisCount(QCPAxis::AxisType type) const; - QCPAxis *axis(QCPAxis::AxisType type, int index=0) const; - QList axes(QCPAxis::AxisTypes types) const; - QList axes() const; - QCPAxis *addAxis(QCPAxis::AxisType type, QCPAxis *axis=0); - QList addAxes(QCPAxis::AxisTypes types); - 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; - QList items() const; - - // read-only interface imitating a QRect: - int left() const { return mRect.left(); } - int right() const { return mRect.right(); } - int top() const { return mRect.top(); } - int bottom() const { return mRect.bottom(); } - int width() const { return mRect.width(); } - int height() const { return mRect.height(); } - QSize size() const { return mRect.size(); } - QPoint topLeft() const { return mRect.topLeft(); } - QPoint topRight() const { return mRect.topRight(); } - QPoint bottomLeft() const { return mRect.bottomLeft(); } - QPoint bottomRight() const { return mRect.bottomRight(); } - QPoint center() const { return mRect.center(); } - - // reimplemented virtual methods: - virtual void update(UpdatePhase phase) Q_DECL_OVERRIDE; - virtual QList elements(bool recursive) const Q_DECL_OVERRIDE; + explicit QCPAxisRect(QCustomPlot *parentPlot, bool setupDefaultAxes = true); + virtual ~QCPAxisRect(); + + // 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: + void setBackground(const QPixmap &pm); + void setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode = Qt::KeepAspectRatioByExpanding); + void setBackground(const QBrush &brush); + void setBackgroundScaled(bool scaled); + void setBackgroundScaledMode(Qt::AspectRatioMode mode); + 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); + + // non-property methods: + int axisCount(QCPAxis::AxisType type) const; + QCPAxis *axis(QCPAxis::AxisType type, int index = 0) const; + QList axes(QCPAxis::AxisTypes types) const; + QList axes() const; + QCPAxis *addAxis(QCPAxis::AxisType type, QCPAxis *axis = 0); + QList addAxes(QCPAxis::AxisTypes types); + 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; + QList items() const; + + // read-only interface imitating a QRect: + int left() const { + return mRect.left(); + } + int right() const { + return mRect.right(); + } + int top() const { + return mRect.top(); + } + int bottom() const { + return mRect.bottom(); + } + int width() const { + return mRect.width(); + } + int height() const { + return mRect.height(); + } + QSize size() const { + return mRect.size(); + } + QPoint topLeft() const { + return mRect.topLeft(); + } + QPoint topRight() const { + return mRect.topRight(); + } + QPoint bottomLeft() const { + return mRect.bottomLeft(); + } + QPoint bottomRight() const { + return mRect.bottomRight(); + } + QPoint center() const { + return mRect.center(); + } + + // reimplemented virtual methods: + virtual void update(UpdatePhase phase) Q_DECL_OVERRIDE; + virtual QList elements(bool recursive) const Q_DECL_OVERRIDE; protected: - // property members: - QBrush mBackgroundBrush; - QPixmap mBackgroundPixmap; - QPixmap mScaledBackgroundPixmap; - bool mBackgroundScaled; - Qt::AspectRatioMode mBackgroundScaledMode; - QCPLayoutInset *mInsetLayout; - Qt::Orientations mRangeDrag, mRangeZoom; - QList > mRangeDragHorzAxis, mRangeDragVertAxis; - QList > mRangeZoomHorzAxis, mRangeZoomVertAxis; - double mRangeZoomFactorHorz, mRangeZoomFactorVert; - - // non-property members: - QList mDragStartHorzRange, mDragStartVertRange; - QCP::AntialiasedElements mAADragBackup, mNotAADragBackup; - bool mDragging; - QHash > mAxes; - - // reimplemented virtual methods: - 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, 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); - void updateAxesOffset(QCPAxis::AxisType type); - + // property members: + QBrush mBackgroundBrush; + QPixmap mBackgroundPixmap; + QPixmap mScaledBackgroundPixmap; + bool mBackgroundScaled; + Qt::AspectRatioMode mBackgroundScaledMode; + QCPLayoutInset *mInsetLayout; + Qt::Orientations mRangeDrag, mRangeZoom; + QList > mRangeDragHorzAxis, mRangeDragVertAxis; + QList > mRangeZoomHorzAxis, mRangeZoomVertAxis; + double mRangeZoomFactorHorz, mRangeZoomFactorVert; + + // non-property members: + QList mDragStartHorzRange, mDragStartVertRange; + QCP::AntialiasedElements mAADragBackup, mNotAADragBackup; + bool mDragging; + QHash > mAxes; + + // reimplemented virtual methods: + 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, 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); + void updateAxesOffset(QCPAxis::AxisType type); + private: - Q_DISABLE_COPY(QCPAxisRect) - - friend class QCustomPlot; + Q_DISABLE_COPY(QCPAxisRect) + + friend class QCustomPlot; }; @@ -4718,212 +5202,252 @@ private: class QCP_LIB_DECL QCPAbstractLegendItem : public QCPLayoutElement { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QCPLegend* parentLegend READ parentLegend) - Q_PROPERTY(QFont font READ font WRITE setFont) - Q_PROPERTY(QColor textColor READ textColor WRITE setTextColor) - Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont) - Q_PROPERTY(QColor selectedTextColor READ selectedTextColor WRITE setSelectedTextColor) - Q_PROPERTY(bool selectable READ selectable WRITE setSelectable NOTIFY selectionChanged) - Q_PROPERTY(bool selected READ selected WRITE setSelected NOTIFY selectableChanged) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QCPLegend* parentLegend READ parentLegend) Q_PROPERTY(QFont font READ font WRITE setFont) + Q_PROPERTY(QColor textColor READ textColor WRITE setTextColor) + Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont) + Q_PROPERTY(QColor selectedTextColor READ selectedTextColor WRITE setSelectedTextColor) + Q_PROPERTY(bool selectable READ selectable WRITE setSelectable NOTIFY selectionChanged) + Q_PROPERTY(bool selected READ selected WRITE setSelected NOTIFY selectableChanged) + /// \endcond public: - explicit QCPAbstractLegendItem(QCPLegend *parent); - - // getters: - QCPLegend *parentLegend() const { return mParentLegend; } - QFont font() const { return mFont; } - QColor textColor() const { return mTextColor; } - QFont selectedFont() const { return mSelectedFont; } - QColor selectedTextColor() const { return mSelectedTextColor; } - bool selectable() const { return mSelectable; } - bool selected() const { return mSelected; } - - // setters: - void setFont(const QFont &font); - void setTextColor(const QColor &color); - void setSelectedFont(const QFont &font); - void setSelectedTextColor(const QColor &color); - Q_SLOT void setSelectable(bool selectable); - Q_SLOT void setSelected(bool selected); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const Q_DECL_OVERRIDE; - + explicit QCPAbstractLegendItem(QCPLegend *parent); + + // getters: + QCPLegend *parentLegend() const { + return mParentLegend; + } + QFont font() const { + return mFont; + } + QColor textColor() const { + return mTextColor; + } + QFont selectedFont() const { + return mSelectedFont; + } + QColor selectedTextColor() const { + return mSelectedTextColor; + } + bool selectable() const { + return mSelectable; + } + bool selected() const { + return mSelected; + } + + // setters: + void setFont(const QFont &font); + void setTextColor(const QColor &color); + void setSelectedFont(const QFont &font); + void setSelectedTextColor(const QColor &color); + Q_SLOT void setSelectable(bool selectable); + Q_SLOT void setSelected(bool selected); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = 0) const Q_DECL_OVERRIDE; + signals: - void selectionChanged(bool selected); - void selectableChanged(bool selectable); - + void selectionChanged(bool selected); + void selectableChanged(bool selectable); + protected: - // property members: - QCPLegend *mParentLegend; - QFont mFont; - QColor mTextColor; - QFont mSelectedFont; - QColor mSelectedTextColor; - bool mSelectable, mSelected; - - // reimplemented virtual methods: - 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) Q_DECL_OVERRIDE; - virtual void deselectEvent(bool *selectionStateChanged) Q_DECL_OVERRIDE; - + // property members: + QCPLegend *mParentLegend; + QFont mFont; + QColor mTextColor; + QFont mSelectedFont; + QColor mSelectedTextColor; + bool mSelectable, mSelected; + + // reimplemented virtual methods: + 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) Q_DECL_OVERRIDE; + virtual void deselectEvent(bool *selectionStateChanged) Q_DECL_OVERRIDE; + private: - Q_DISABLE_COPY(QCPAbstractLegendItem) - - friend class QCPLegend; + Q_DISABLE_COPY(QCPAbstractLegendItem) + + friend class QCPLegend; }; class QCP_LIB_DECL QCPPlottableLegendItem : public QCPAbstractLegendItem { - Q_OBJECT + Q_OBJECT public: - QCPPlottableLegendItem(QCPLegend *parent, QCPAbstractPlottable *plottable); - - // getters: - QCPAbstractPlottable *plottable() { return mPlottable; } - + QCPPlottableLegendItem(QCPLegend *parent, QCPAbstractPlottable *plottable); + + // getters: + QCPAbstractPlottable *plottable() { + return mPlottable; + } + protected: - // property members: - QCPAbstractPlottable *mPlottable; - - // reimplemented virtual methods: - virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; - virtual QSize minimumOuterSizeHint() const Q_DECL_OVERRIDE; - - // non-virtual methods: - QPen getIconBorderPen() const; - QColor getTextColor() const; - QFont getFont() const; + // property members: + QCPAbstractPlottable *mPlottable; + + // reimplemented virtual methods: + virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; + virtual QSize minimumOuterSizeHint() const Q_DECL_OVERRIDE; + + // non-virtual methods: + QPen getIconBorderPen() const; + QColor getTextColor() const; + QFont getFont() const; }; class QCP_LIB_DECL QCPLegend : public QCPLayoutGrid { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QPen borderPen READ borderPen WRITE setBorderPen) - Q_PROPERTY(QBrush brush READ brush WRITE setBrush) - Q_PROPERTY(QFont font READ font WRITE setFont) - Q_PROPERTY(QColor textColor READ textColor WRITE setTextColor) - Q_PROPERTY(QSize iconSize READ iconSize WRITE setIconSize) - Q_PROPERTY(int iconTextPadding READ iconTextPadding WRITE setIconTextPadding) - Q_PROPERTY(QPen iconBorderPen READ iconBorderPen WRITE setIconBorderPen) - Q_PROPERTY(SelectableParts selectableParts READ selectableParts WRITE setSelectableParts NOTIFY selectionChanged) - Q_PROPERTY(SelectableParts selectedParts READ selectedParts WRITE setSelectedParts NOTIFY selectableChanged) - Q_PROPERTY(QPen selectedBorderPen READ selectedBorderPen WRITE setSelectedBorderPen) - Q_PROPERTY(QPen selectedIconBorderPen READ selectedIconBorderPen WRITE setSelectedIconBorderPen) - Q_PROPERTY(QBrush selectedBrush READ selectedBrush WRITE setSelectedBrush) - Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont) - Q_PROPERTY(QColor selectedTextColor READ selectedTextColor WRITE setSelectedTextColor) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(QPen borderPen READ borderPen WRITE setBorderPen) + Q_PROPERTY(QBrush brush READ brush WRITE setBrush) + Q_PROPERTY(QFont font READ font WRITE setFont) + Q_PROPERTY(QColor textColor READ textColor WRITE setTextColor) + Q_PROPERTY(QSize iconSize READ iconSize WRITE setIconSize) + Q_PROPERTY(int iconTextPadding READ iconTextPadding WRITE setIconTextPadding) + Q_PROPERTY(QPen iconBorderPen READ iconBorderPen WRITE setIconBorderPen) + Q_PROPERTY(SelectableParts selectableParts READ selectableParts WRITE setSelectableParts NOTIFY selectionChanged) + Q_PROPERTY(SelectableParts selectedParts READ selectedParts WRITE setSelectedParts NOTIFY selectableChanged) + Q_PROPERTY(QPen selectedBorderPen READ selectedBorderPen WRITE setSelectedBorderPen) + Q_PROPERTY(QPen selectedIconBorderPen READ selectedIconBorderPen WRITE setSelectedIconBorderPen) + Q_PROPERTY(QBrush selectedBrush READ selectedBrush WRITE setSelectedBrush) + Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont) + Q_PROPERTY(QColor selectedTextColor READ selectedTextColor WRITE setSelectedTextColor) + /// \endcond public: - /*! - Defines the selectable parts of a legend - - \see setSelectedParts, setSelectableParts - */ - enum SelectablePart { spNone = 0x000 ///< 0x000 None - ,spLegendBox = 0x001 ///< 0x001 The legend box (frame) - ,spItems = 0x002 ///< 0x002 Legend items individually (see \ref selectedItems) - }; - Q_ENUMS(SelectablePart) - Q_FLAGS(SelectableParts) - Q_DECLARE_FLAGS(SelectableParts, SelectablePart) - - explicit QCPLegend(); - virtual ~QCPLegend(); - - // getters: - QPen borderPen() const { return mBorderPen; } - QBrush brush() const { return mBrush; } - QFont font() const { return mFont; } - QColor textColor() const { return mTextColor; } - QSize iconSize() const { return mIconSize; } - int iconTextPadding() const { return mIconTextPadding; } - QPen iconBorderPen() const { return mIconBorderPen; } - SelectableParts selectableParts() const { return mSelectableParts; } - SelectableParts selectedParts() const; - QPen selectedBorderPen() const { return mSelectedBorderPen; } - QPen selectedIconBorderPen() const { return mSelectedIconBorderPen; } - QBrush selectedBrush() const { return mSelectedBrush; } - QFont selectedFont() const { return mSelectedFont; } - QColor selectedTextColor() const { return mSelectedTextColor; } - - // setters: - void setBorderPen(const QPen &pen); - void setBrush(const QBrush &brush); - void setFont(const QFont &font); - void setTextColor(const QColor &color); - void setIconSize(const QSize &size); - void setIconSize(int width, int height); - void setIconTextPadding(int padding); - void setIconBorderPen(const QPen &pen); - Q_SLOT void setSelectableParts(const SelectableParts &selectableParts); - Q_SLOT void setSelectedParts(const SelectableParts &selectedParts); - void setSelectedBorderPen(const QPen &pen); - void setSelectedIconBorderPen(const QPen &pen); - void setSelectedBrush(const QBrush &brush); - void setSelectedFont(const QFont &font); - void setSelectedTextColor(const QColor &color); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const Q_DECL_OVERRIDE; - - // non-virtual methods: - QCPAbstractLegendItem *item(int index) const; - QCPPlottableLegendItem *itemWithPlottable(const QCPAbstractPlottable *plottable) const; - int itemCount() const; - bool hasItem(QCPAbstractLegendItem *item) const; - bool hasItemWithPlottable(const QCPAbstractPlottable *plottable) const; - bool addItem(QCPAbstractLegendItem *item); - bool removeItem(int index); - bool removeItem(QCPAbstractLegendItem *item); - void clearItems(); - QList selectedItems() const; - + /*! + Defines the selectable parts of a legend + + \see setSelectedParts, setSelectableParts + */ + enum SelectablePart { spNone = 0x000 ///< 0x000 None + , spLegendBox = 0x001 ///< 0x001 The legend box (frame) + , spItems = 0x002 ///< 0x002 Legend items individually (see \ref selectedItems) + }; + Q_ENUMS(SelectablePart) + Q_FLAGS(SelectableParts) + Q_DECLARE_FLAGS(SelectableParts, SelectablePart) + + explicit QCPLegend(); + virtual ~QCPLegend(); + + // getters: + QPen borderPen() const { + return mBorderPen; + } + QBrush brush() const { + return mBrush; + } + QFont font() const { + return mFont; + } + QColor textColor() const { + return mTextColor; + } + QSize iconSize() const { + return mIconSize; + } + int iconTextPadding() const { + return mIconTextPadding; + } + QPen iconBorderPen() const { + return mIconBorderPen; + } + SelectableParts selectableParts() const { + return mSelectableParts; + } + SelectableParts selectedParts() const; + QPen selectedBorderPen() const { + return mSelectedBorderPen; + } + QPen selectedIconBorderPen() const { + return mSelectedIconBorderPen; + } + QBrush selectedBrush() const { + return mSelectedBrush; + } + QFont selectedFont() const { + return mSelectedFont; + } + QColor selectedTextColor() const { + return mSelectedTextColor; + } + + // setters: + void setBorderPen(const QPen &pen); + void setBrush(const QBrush &brush); + void setFont(const QFont &font); + void setTextColor(const QColor &color); + void setIconSize(const QSize &size); + void setIconSize(int width, int height); + void setIconTextPadding(int padding); + void setIconBorderPen(const QPen &pen); + Q_SLOT void setSelectableParts(const SelectableParts &selectableParts); + Q_SLOT void setSelectedParts(const SelectableParts &selectedParts); + void setSelectedBorderPen(const QPen &pen); + void setSelectedIconBorderPen(const QPen &pen); + void setSelectedBrush(const QBrush &brush); + void setSelectedFont(const QFont &font); + void setSelectedTextColor(const QColor &color); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = 0) const Q_DECL_OVERRIDE; + + // non-virtual methods: + QCPAbstractLegendItem *item(int index) const; + QCPPlottableLegendItem *itemWithPlottable(const QCPAbstractPlottable *plottable) const; + int itemCount() const; + bool hasItem(QCPAbstractLegendItem *item) const; + bool hasItemWithPlottable(const QCPAbstractPlottable *plottable) const; + bool addItem(QCPAbstractLegendItem *item); + bool removeItem(int index); + bool removeItem(QCPAbstractLegendItem *item); + void clearItems(); + QList selectedItems() const; + signals: - void selectionChanged(QCPLegend::SelectableParts parts); - void selectableChanged(QCPLegend::SelectableParts parts); - + void selectionChanged(QCPLegend::SelectableParts parts); + void selectableChanged(QCPLegend::SelectableParts parts); + protected: - // property members: - QPen mBorderPen, mIconBorderPen; - QBrush mBrush; - QFont mFont; - QColor mTextColor; - QSize mIconSize; - int mIconTextPadding; - SelectableParts mSelectedParts, mSelectableParts; - QPen mSelectedBorderPen, mSelectedIconBorderPen; - QBrush mSelectedBrush; - QFont mSelectedFont; - QColor mSelectedTextColor; - - // reimplemented virtual methods: - 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) Q_DECL_OVERRIDE; - virtual void deselectEvent(bool *selectionStateChanged) Q_DECL_OVERRIDE; - - // non-virtual methods: - QPen getBorderPen() const; - QBrush getBrush() const; - + // property members: + QPen mBorderPen, mIconBorderPen; + QBrush mBrush; + QFont mFont; + QColor mTextColor; + QSize mIconSize; + int mIconTextPadding; + SelectableParts mSelectedParts, mSelectableParts; + QPen mSelectedBorderPen, mSelectedIconBorderPen; + QBrush mSelectedBrush; + QFont mSelectedFont; + QColor mSelectedTextColor; + + // reimplemented virtual methods: + 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) Q_DECL_OVERRIDE; + virtual void deselectEvent(bool *selectionStateChanged) Q_DECL_OVERRIDE; + + // non-virtual methods: + QPen getBorderPen() const; + QBrush getBrush() const; + private: - Q_DISABLE_COPY(QCPLegend) - - friend class QCustomPlot; - friend class QCPAbstractLegendItem; + Q_DISABLE_COPY(QCPLegend) + + friend class QCustomPlot; + friend class QCPAbstractLegendItem; }; Q_DECLARE_OPERATORS_FOR_FLAGS(QCPLegend::SelectableParts) Q_DECLARE_METATYPE(QCPLegend::SelectablePart) @@ -4936,81 +5460,95 @@ Q_DECLARE_METATYPE(QCPLegend::SelectablePart) class QCP_LIB_DECL QCPTextElement : public QCPLayoutElement { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QString text READ text WRITE setText) - Q_PROPERTY(QFont font READ font WRITE setFont) - Q_PROPERTY(QColor textColor READ textColor WRITE setTextColor) - Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont) - Q_PROPERTY(QColor selectedTextColor READ selectedTextColor WRITE setSelectedTextColor) - Q_PROPERTY(bool selectable READ selectable WRITE setSelectable NOTIFY selectableChanged) - Q_PROPERTY(bool selected READ selected WRITE setSelected NOTIFY selectionChanged) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QString text READ text WRITE setText) Q_PROPERTY(QFont font READ font WRITE setFont) + Q_PROPERTY(QColor textColor READ textColor WRITE setTextColor) + Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont) + Q_PROPERTY(QColor selectedTextColor READ selectedTextColor WRITE setSelectedTextColor) + Q_PROPERTY(bool selectable READ selectable WRITE setSelectable NOTIFY selectableChanged) + Q_PROPERTY(bool selected READ selected WRITE setSelected NOTIFY selectionChanged) + /// \endcond public: - 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; } - QColor selectedTextColor() const { return mSelectedTextColor; } - bool selectable() const { return mSelectable; } - bool selected() const { return mSelected; } - - // 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); - void setSelectedTextColor(const QColor &color); - Q_SLOT void setSelectable(bool selectable); - Q_SLOT void setSelected(bool selected); - - // reimplemented virtual methods: - 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; - + 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; + } + QColor selectedTextColor() const { + return mSelectedTextColor; + } + bool selectable() const { + return mSelectable; + } + bool selected() const { + return mSelected; + } + + // 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); + void setSelectedTextColor(const QColor &color); + Q_SLOT void setSelectable(bool selectable); + Q_SLOT void setSelected(bool selected); + + // reimplemented virtual methods: + 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); - + 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; - QColor mSelectedTextColor; - QRect mTextBoundingRect; - bool mSelectable, mSelected; - - // reimplemented virtual methods: - virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const Q_DECL_OVERRIDE; - virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; - virtual QSize minimumOuterSizeHint() const Q_DECL_OVERRIDE; - virtual QSize maximumOuterSizeHint() 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; - - // non-virtual methods: - QFont mainFont() const; - QColor mainTextColor() const; - + // property members: + QString mText; + int mTextFlags; + QFont mFont; + QColor mTextColor; + QFont mSelectedFont; + QColor mSelectedTextColor; + QRect mTextBoundingRect; + bool mSelectable, mSelected; + + // reimplemented virtual methods: + virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const Q_DECL_OVERRIDE; + virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; + virtual QSize minimumOuterSizeHint() const Q_DECL_OVERRIDE; + virtual QSize maximumOuterSizeHint() 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; + + // non-virtual methods: + QFont mainFont() const; + QColor mainTextColor() const; + private: - Q_DISABLE_COPY(QCPTextElement) + Q_DISABLE_COPY(QCPTextElement) }; @@ -5024,102 +5562,112 @@ private: class QCPColorScaleAxisRectPrivate : public QCPAxisRect { - Q_OBJECT + Q_OBJECT public: - explicit QCPColorScaleAxisRectPrivate(QCPColorScale *parentColorScale); + explicit QCPColorScaleAxisRectPrivate(QCPColorScale *parentColorScale); protected: - QCPColorScale *mParentColorScale; - QImage mGradientImage; - bool mGradientImageInvalidated; - // re-using some methods of QCPAxisRect to make them available to friend class QCPColorScale - using QCPAxisRect::calculateAutoMargin; - using QCPAxisRect::mousePressEvent; - using QCPAxisRect::mouseMoveEvent; - using QCPAxisRect::mouseReleaseEvent; - using QCPAxisRect::wheelEvent; - using QCPAxisRect::update; - virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; - void updateGradientImage(); - Q_SLOT void axisSelectionChanged(QCPAxis::SelectableParts selectedParts); - Q_SLOT void axisSelectableChanged(QCPAxis::SelectableParts selectableParts); - friend class QCPColorScale; + QCPColorScale *mParentColorScale; + QImage mGradientImage; + bool mGradientImageInvalidated; + // re-using some methods of QCPAxisRect to make them available to friend class QCPColorScale + using QCPAxisRect::calculateAutoMargin; + using QCPAxisRect::mousePressEvent; + using QCPAxisRect::mouseMoveEvent; + using QCPAxisRect::mouseReleaseEvent; + using QCPAxisRect::wheelEvent; + using QCPAxisRect::update; + virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; + void updateGradientImage(); + Q_SLOT void axisSelectionChanged(QCPAxis::SelectableParts selectedParts); + Q_SLOT void axisSelectableChanged(QCPAxis::SelectableParts selectableParts); + friend class QCPColorScale; }; class QCP_LIB_DECL QCPColorScale : public QCPLayoutElement { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QCPAxis::AxisType type READ type WRITE setType) - Q_PROPERTY(QCPRange dataRange READ dataRange WRITE setDataRange NOTIFY dataRangeChanged) - Q_PROPERTY(QCPAxis::ScaleType dataScaleType READ dataScaleType WRITE setDataScaleType NOTIFY dataScaleTypeChanged) - Q_PROPERTY(QCPColorGradient gradient READ gradient WRITE setGradient NOTIFY gradientChanged) - Q_PROPERTY(QString label READ label WRITE setLabel) - Q_PROPERTY(int barWidth READ barWidth WRITE setBarWidth) - Q_PROPERTY(bool rangeDrag READ rangeDrag WRITE setRangeDrag) - Q_PROPERTY(bool rangeZoom READ rangeZoom WRITE setRangeZoom) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QCPAxis::AxisType type READ type WRITE setType) Q_PROPERTY(QCPRange dataRange READ dataRange WRITE setDataRange NOTIFY dataRangeChanged) + Q_PROPERTY(QCPAxis::ScaleType dataScaleType READ dataScaleType WRITE setDataScaleType NOTIFY dataScaleTypeChanged) + Q_PROPERTY(QCPColorGradient gradient READ gradient WRITE setGradient NOTIFY gradientChanged) + Q_PROPERTY(QString label READ label WRITE setLabel) + Q_PROPERTY(int barWidth READ barWidth WRITE setBarWidth) + Q_PROPERTY(bool rangeDrag READ rangeDrag WRITE setRangeDrag) + Q_PROPERTY(bool rangeZoom READ rangeZoom WRITE setRangeZoom) + /// \endcond public: - explicit QCPColorScale(QCustomPlot *parentPlot); - virtual ~QCPColorScale(); - - // getters: - QCPAxis *axis() const { return mColorAxis.data(); } - QCPAxis::AxisType type() const { return mType; } - QCPRange dataRange() const { return mDataRange; } - QCPAxis::ScaleType dataScaleType() const { return mDataScaleType; } - QCPColorGradient gradient() const { return mGradient; } - QString label() const; - int barWidth () const { return mBarWidth; } - bool rangeDrag() const; - bool rangeZoom() const; - - // setters: - void setType(QCPAxis::AxisType type); - Q_SLOT void setDataRange(const QCPRange &dataRange); - Q_SLOT void setDataScaleType(QCPAxis::ScaleType scaleType); - Q_SLOT void setGradient(const QCPColorGradient &gradient); - void setLabel(const QString &str); - void setBarWidth(int width); - void setRangeDrag(bool enabled); - void setRangeZoom(bool enabled); - - // non-property methods: - QList colorMaps() const; - void rescaleDataRange(bool onlyVisibleMaps); - - // reimplemented virtual methods: - virtual void update(UpdatePhase phase) Q_DECL_OVERRIDE; - + explicit QCPColorScale(QCustomPlot *parentPlot); + virtual ~QCPColorScale(); + + // getters: + QCPAxis *axis() const { + return mColorAxis.data(); + } + QCPAxis::AxisType type() const { + return mType; + } + QCPRange dataRange() const { + return mDataRange; + } + QCPAxis::ScaleType dataScaleType() const { + return mDataScaleType; + } + QCPColorGradient gradient() const { + return mGradient; + } + QString label() const; + int barWidth() const { + return mBarWidth; + } + bool rangeDrag() const; + bool rangeZoom() const; + + // setters: + void setType(QCPAxis::AxisType type); + Q_SLOT void setDataRange(const QCPRange &dataRange); + Q_SLOT void setDataScaleType(QCPAxis::ScaleType scaleType); + Q_SLOT void setGradient(const QCPColorGradient &gradient); + void setLabel(const QString &str); + void setBarWidth(int width); + void setRangeDrag(bool enabled); + void setRangeZoom(bool enabled); + + // non-property methods: + QList colorMaps() const; + void rescaleDataRange(bool onlyVisibleMaps); + + // reimplemented virtual methods: + virtual void update(UpdatePhase phase) Q_DECL_OVERRIDE; + signals: - void dataRangeChanged(const QCPRange &newRange); - void dataScaleTypeChanged(QCPAxis::ScaleType scaleType); - void gradientChanged(const QCPColorGradient &newGradient); + void dataRangeChanged(const QCPRange &newRange); + void dataScaleTypeChanged(QCPAxis::ScaleType scaleType); + void gradientChanged(const QCPColorGradient &newGradient); protected: - // property members: - QCPAxis::AxisType mType; - QCPRange mDataRange; - QCPAxis::ScaleType mDataScaleType; - QCPColorGradient mGradient; - int mBarWidth; - - // non-property members: - QPointer mAxisRect; - QPointer mColorAxis; - - // reimplemented virtual methods: - virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const Q_DECL_OVERRIDE; - // events: - 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; - + // property members: + QCPAxis::AxisType mType; + QCPRange mDataRange; + QCPAxis::ScaleType mDataScaleType; + QCPColorGradient mGradient; + int mBarWidth; + + // non-property members: + QPointer mAxisRect; + QPointer mColorAxis; + + // reimplemented virtual methods: + virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const Q_DECL_OVERRIDE; + // events: + 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) - - friend class QCPColorScaleAxisRectPrivate; + Q_DISABLE_COPY(QCPColorScale) + + friend class QCPColorScaleAxisRectPrivate; }; @@ -5132,133 +5680,166 @@ private: class QCP_LIB_DECL QCPGraphData { public: - QCPGraphData(); - QCPGraphData(double key, double value); - - 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; + QCPGraphData(); + QCPGraphData(double key, double value); + + 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 QCPDataContainer QCPGraphDataContainer; 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(int scatterSkip READ scatterSkip WRITE setScatterSkip) - Q_PROPERTY(QCPGraph* channelFillGraph READ channelFillGraph WRITE setChannelFillGraph) - Q_PROPERTY(bool adaptiveSampling READ adaptiveSampling WRITE setAdaptiveSampling) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(LineStyle lineStyle READ lineStyle WRITE setLineStyle) + Q_PROPERTY(QCPScatterStyle scatterStyle READ scatterStyle WRITE setScatterStyle) + 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 public: - /*! - Defines how the graph's line is represented visually in the plot. The line is drawn with the - current pen of the graph (\ref setPen). - \see setLineStyle - */ - enum LineStyle { lsNone ///< data points are not connected with any lines (e.g. data only represented - ///< with symbols according to the scatter style, see \ref setScatterStyle) - ,lsLine ///< data points are connected by a straight line - ,lsStepLeft ///< line is drawn as steps where the step height is the value of the left data point - ,lsStepRight ///< line is drawn as steps where the step height is the value of the right data point - ,lsStepCenter ///< line is drawn as steps where the step is in between two data points - ,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) - - explicit QCPGraph(QCPAxis *keyAxis, QCPAxis *valueAxis); - virtual ~QCPGraph(); - - // getters: - QSharedPointer data() const { return mDataContainer; } - LineStyle lineStyle() const { return mLineStyle; } - QCPScatterStyle scatterStyle() const { return mScatterStyle; } - int scatterSkip() const { return mScatterSkip; } - QCPGraph *channelFillGraph() const { return mChannelFillGraph.data(); } - bool adaptiveSampling() const { return mAdaptiveSampling; } - - // setters: - 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 setScatterSkip(int skip); - void setChannelFillGraph(QCPGraph *targetGraph); - void setAdaptiveSampling(bool enabled); - - // non-property methods: - void addData(const QVector &keys, const QVector &values, bool alreadySorted=false); - void addData(double key, double value); - - // reimplemented virtual methods: - 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; - + /*! + Defines how the graph's line is represented visually in the plot. The line is drawn with the + current pen of the graph (\ref setPen). + \see setLineStyle + */ + enum LineStyle { lsNone ///< data points are not connected with any lines (e.g. data only represented + ///< with symbols according to the scatter style, see \ref setScatterStyle) + , lsLine ///< data points are connected by a straight line + , lsStepLeft ///< line is drawn as steps where the step height is the value of the left data point + , lsStepRight ///< line is drawn as steps where the step height is the value of the right data point + , lsStepCenter ///< line is drawn as steps where the step is in between two data points + , 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) + + explicit QCPGraph(QCPAxis *keyAxis, QCPAxis *valueAxis); + virtual ~QCPGraph(); + + // getters: + QSharedPointer data() const { + return mDataContainer; + } + LineStyle lineStyle() const { + return mLineStyle; + } + QCPScatterStyle scatterStyle() const { + return mScatterStyle; + } + int scatterSkip() const { + return mScatterSkip; + } + QCPGraph *channelFillGraph() const { + return mChannelFillGraph.data(); + } + bool adaptiveSampling() const { + return mAdaptiveSampling; + } + + // setters: + 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 setScatterSkip(int skip); + void setChannelFillGraph(QCPGraph *targetGraph); + void setAdaptiveSampling(bool enabled); + + // non-property methods: + void addData(const QVector &keys, const QVector &values, bool alreadySorted = false); + void addData(double key, double value); + + // reimplemented virtual methods: + 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: - LineStyle mLineStyle; - QCPScatterStyle mScatterStyle; - int mScatterSkip; - QPointer mChannelFillGraph; - bool mAdaptiveSampling; - - // reimplemented virtual methods: - 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 *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 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; - QVector getNonNanSegments(const QVector *lineData, Qt::Orientation keyOrientation) const; - QVector > getOverlappingSegments(QVector thisSegments, const QVector *thisData, QVector otherSegments, const QVector *otherData) const; - bool segmentsIntersect(double aLower, double aUpper, double bLower, double bUpper, int &bPrecedence) const; - QPointF getFillBasePoint(QPointF matchingDataPoint) const; - const QPolygonF getFillPolygon(const QVector *lineData, QCPDataRange segment) const; - const QPolygonF getChannelFillPolygon(const QVector *lineData, QCPDataRange thisSegment, const QVector *otherData, QCPDataRange otherSegment) 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, QCPGraphDataContainer::const_iterator &closestData) const; - - friend class QCustomPlot; - friend class QCPLegend; + // property members: + LineStyle mLineStyle; + QCPScatterStyle mScatterStyle; + int mScatterSkip; + QPointer mChannelFillGraph; + bool mAdaptiveSampling; + + // reimplemented virtual methods: + virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; + virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const Q_DECL_OVERRIDE; + + int smooth; +public: + void setSmooth(int smooth); + +protected: + // introduced virtual methods: + 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 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; + QVector getNonNanSegments(const QVector *lineData, Qt::Orientation keyOrientation) const; + QVector > getOverlappingSegments(QVector thisSegments, const QVector *thisData, QVector otherSegments, const QVector *otherData) const; + bool segmentsIntersect(double aLower, double aUpper, double bLower, double bUpper, int &bPrecedence) const; + QPointF getFillBasePoint(QPointF matchingDataPoint) const; + + const QPolygonF getFillPolygon(const QVector *lineData, QCPDataRange segment) const; + const QPainterPath getFillPath(const QVector *lineData, QCPDataRange segment) const; + const QPolygonF getChannelFillPolygon(const QVector *lineData, QCPDataRange thisSegment, const QVector *otherData, QCPDataRange otherSegment) const; + //const QPainterPath getChannelFillPath(const QVector *lineData, QCPDataRange thisSegment, const QVector *otherData, QCPDataRange otherSegment) 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, QCPGraphDataContainer::const_iterator &closestData) const; + + friend class QCustomPlot; + friend class QCPLegend; }; Q_DECLARE_METATYPE(QCPGraph::LineStyle) @@ -5271,109 +5852,129 @@ Q_DECLARE_METATYPE(QCPGraph::LineStyle) 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; + 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_PRIMITIVE_TYPE); /*! \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. - + \see QCPCurveData, QCPCurve::setData */ typedef QCPDataContainer QCPCurveDataContainer; 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 + 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: - /*! - Defines how the curve's line is represented visually in the plot. The line is drawn with the - current pen of the curve (\ref setPen). - \see setLineStyle - */ - 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: - QSharedPointer data() const { return mDataContainer; } - QCPScatterStyle scatterStyle() const { return mScatterStyle; } - int scatterSkip() const { return mScatterSkip; } - LineStyle lineStyle() const { return mLineStyle; } - - // setters: - 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 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); - - // reimplemented virtual methods: - 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; - + /*! + Defines how the curve's line is represented visually in the plot. The line is drawn with the + current pen of the curve (\ref setPen). + \see setLineStyle + */ + 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: + QSharedPointer data() const { + return mDataContainer; + } + QCPScatterStyle scatterStyle() const { + return mScatterStyle; + } + int scatterSkip() const { + return mScatterSkip; + } + LineStyle lineStyle() const { + return mLineStyle; + } + + // setters: + 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 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); + + // reimplemented virtual methods: + 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: - QCPScatterStyle mScatterStyle; - int mScatterSkip; - LineStyle mLineStyle; - - // reimplemented virtual methods: - 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 drawCurveLine(QCPPainter *painter, const QVector &lines) const; - virtual void drawScatterPlot(QCPPainter *painter, const QVector &points, const QCPScatterStyle &style) const; - - // non-virtual methods: - 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 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; + // property members: + QCPScatterStyle mScatterStyle; + int mScatterSkip; + LineStyle mLineStyle; + + // reimplemented virtual methods: + 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 drawCurveLine(QCPPainter *painter, const QVector &lines) const; + virtual void drawScatterPlot(QCPPainter *painter, const QVector &points, const QCPScatterStyle &style) const; + + // non-virtual methods: + 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 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) @@ -5385,65 +5986,77 @@ Q_DECLARE_METATYPE(QCPCurve::LineStyle) class QCP_LIB_DECL QCPBarsGroup : public QObject { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(SpacingType spacingType READ spacingType WRITE setSpacingType) - Q_PROPERTY(double spacing READ spacing WRITE setSpacing) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(SpacingType spacingType READ spacingType WRITE setSpacingType) + Q_PROPERTY(double spacing READ spacing WRITE setSpacing) + /// \endcond public: - /*! - Defines the ways the spacing between bars in the group can be specified. Thus it defines what - the number passed to \ref setSpacing actually means. - - \see setSpacingType, setSpacing - */ - 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) - - explicit QCPBarsGroup(QCustomPlot *parentPlot); - virtual ~QCPBarsGroup(); - - // getters: - SpacingType spacingType() const { return mSpacingType; } - double spacing() const { return mSpacing; } - - // setters: - void setSpacingType(SpacingType spacingType); - void setSpacing(double spacing); - - // non-virtual methods: - QList bars() const { return mBars; } - QCPBars* bars(int index) const; - int size() const { return mBars.size(); } - bool isEmpty() const { return mBars.isEmpty(); } - void clear(); - bool contains(QCPBars *bars) const { return mBars.contains(bars); } - void append(QCPBars *bars); - void insert(int i, QCPBars *bars); - void remove(QCPBars *bars); - + /*! + Defines the ways the spacing between bars in the group can be specified. Thus it defines what + the number passed to \ref setSpacing actually means. + + \see setSpacingType, setSpacing + */ + 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) + + explicit QCPBarsGroup(QCustomPlot *parentPlot); + virtual ~QCPBarsGroup(); + + // getters: + SpacingType spacingType() const { + return mSpacingType; + } + double spacing() const { + return mSpacing; + } + + // setters: + void setSpacingType(SpacingType spacingType); + void setSpacing(double spacing); + + // non-virtual methods: + QList bars() const { + return mBars; + } + QCPBars *bars(int index) const; + int size() const { + return mBars.size(); + } + bool isEmpty() const { + return mBars.isEmpty(); + } + void clear(); + bool contains(QCPBars *bars) const { + return mBars.contains(bars); + } + void append(QCPBars *bars); + void insert(int i, QCPBars *bars); + void remove(QCPBars *bars); + protected: - // non-property members: - QCustomPlot *mParentPlot; - SpacingType mSpacingType; - double mSpacing; - QList mBars; - - // non-virtual methods: - void registerBars(QCPBars *bars); - void unregisterBars(QCPBars *bars); - - // virtual methods: - double keyPixelOffset(const QCPBars *bars, double keyCoord); - double getPixelSpacing(const QCPBars *bars, double keyCoord); - + // non-property members: + QCustomPlot *mParentPlot; + SpacingType mSpacingType; + double mSpacing; + QList mBars; + + // non-virtual methods: + void registerBars(QCPBars *bars); + void unregisterBars(QCPBars *bars); + + // virtual methods: + double keyPixelOffset(const QCPBars *bars, double keyCoord); + double getPixelSpacing(const QCPBars *bars, double keyCoord); + private: - Q_DISABLE_COPY(QCPBarsGroup) - - friend class QCPBars; + Q_DISABLE_COPY(QCPBarsGroup) + + friend class QCPBars; }; Q_DECLARE_METATYPE(QCPBarsGroup::SpacingType) @@ -5451,117 +6064,145 @@ Q_DECLARE_METATYPE(QCPBarsGroup::SpacingType) class QCP_LIB_DECL QCPBarsData { public: - 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; + 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(QCPBarsData, Q_PRIMITIVE_TYPE); /*! \typedef QCPBarsDataContainer - + 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 QCPDataContainer QCPBarsDataContainer; class QCP_LIB_DECL QCPBars : public QCPAbstractPlottable1D { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(double width READ width WRITE setWidth) - 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 + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(double width READ width WRITE setWidth) + 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 public: - /*! - Defines the ways the width of the bar can be specified. Thus it defines what the number passed - to \ref setWidth actually means. - - \see setWidthType, setWidth - */ - enum WidthType { wtAbsolute ///< Bar width is in absolute pixels - ,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) - - explicit QCPBars(QCPAxis *keyAxis, QCPAxis *valueAxis); - virtual ~QCPBars(); - - // getters: - double width() const { return mWidth; } - 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(); } - 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 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); - - // 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; - virtual QPointF dataPixelPosition(int index) const Q_DECL_OVERRIDE; - + /*! + Defines the ways the width of the bar can be specified. Thus it defines what the number passed + to \ref setWidth actually means. + + \see setWidthType, setWidth + */ + enum WidthType { wtAbsolute ///< Bar width is in absolute pixels + , 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) + + explicit QCPBars(QCPAxis *keyAxis, QCPAxis *valueAxis); + virtual ~QCPBars(); + + // getters: + double width() const { + return mWidth; + } + 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(); + } + 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 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); + + // 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; + virtual QPointF dataPixelPosition(int index) const Q_DECL_OVERRIDE; + protected: - // property members: - double mWidth; - WidthType mWidthType; - QCPBarsGroup *mBarsGroup; - double mBaseValue; - double mStackingGap; - QPointer mBarBelow, mBarAbove; - - // reimplemented virtual methods: - 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(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); - - friend class QCustomPlot; - friend class QCPLegend; - friend class QCPBarsGroup; + // property members: + double mWidth; + WidthType mWidthType; + QCPBarsGroup *mBarsGroup; + double mBaseValue; + double mStackingGap; + QPointer mBarBelow, mBarAbove; + + // reimplemented virtual methods: + 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(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); + + friend class QCustomPlot; + friend class QCPLegend; + friend class QCPBarsGroup; }; Q_DECLARE_METATYPE(QCPBars::WidthType) @@ -5574,112 +6215,136 @@ Q_DECLARE_METATYPE(QCPBars::WidthType) 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; + 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 QCPAbstractPlottable1D { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - 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 + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES 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 public: - explicit QCPStatisticalBox(QCPAxis *keyAxis, QCPAxis *valueAxis); - - // getters: - 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; } + explicit QCPStatisticalBox(QCPAxis *keyAxis, QCPAxis *valueAxis); + + // getters: + 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 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: + 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; - // setters: - 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: - 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: - double mWidth; - double mWhiskerWidth; - QPen mWhiskerPen, mWhiskerBarPen; - bool mWhiskerAntialiased; - QPen mMedianPen; - QCPScatterStyle mOutlierStyle; - - // reimplemented virtual methods: - 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 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; + // property members: + double mWidth; + double mWhiskerWidth; + QPen mWhiskerPen, mWhiskerBarPen; + bool mWhiskerAntialiased; + QPen mMedianPen; + QCPScatterStyle mOutlierStyle; + + // reimplemented virtual methods: + 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 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' */ @@ -5691,131 +6356,155 @@ protected: class QCP_LIB_DECL QCPColorMapData { public: - QCPColorMapData(int keySize, int valueSize, const QCPRange &keyRange, const QCPRange &valueRange); - ~QCPColorMapData(); - QCPColorMapData(const QCPColorMapData &other); - QCPColorMapData &operator=(const QCPColorMapData &other); - - // getters: - int keySize() const { return mKeySize; } - int valueSize() const { return mValueSize; } - QCPRange keyRange() const { return mKeyRange; } - QCPRange valueRange() const { return mValueRange; } - 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); - void setKeySize(int keySize); - void setValueSize(int valueSize); - void setRange(const QCPRange &keyRange, const QCPRange &valueRange); - void setKeyRange(const QCPRange &keyRange); - 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; - + QCPColorMapData(int keySize, int valueSize, const QCPRange &keyRange, const QCPRange &valueRange); + ~QCPColorMapData(); + QCPColorMapData(const QCPColorMapData &other); + QCPColorMapData &operator=(const QCPColorMapData &other); + + // getters: + int keySize() const { + return mKeySize; + } + int valueSize() const { + return mValueSize; + } + QCPRange keyRange() const { + return mKeyRange; + } + QCPRange valueRange() const { + return mValueRange; + } + 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); + void setKeySize(int keySize); + void setValueSize(int valueSize); + void setRange(const QCPRange &keyRange, const QCPRange &valueRange); + void setKeyRange(const QCPRange &keyRange); + 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; + protected: - // property members: - 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; + // property members: + 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; }; class QCP_LIB_DECL QCPColorMap : public QCPAbstractPlottable { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QCPRange dataRange READ dataRange WRITE setDataRange NOTIFY dataRangeChanged) - Q_PROPERTY(QCPAxis::ScaleType dataScaleType READ dataScaleType WRITE setDataScaleType NOTIFY dataScaleTypeChanged) - Q_PROPERTY(QCPColorGradient gradient READ gradient WRITE setGradient NOTIFY gradientChanged) - Q_PROPERTY(bool interpolate READ interpolate WRITE setInterpolate) - Q_PROPERTY(bool tightBoundary READ tightBoundary WRITE setTightBoundary) - Q_PROPERTY(QCPColorScale* colorScale READ colorScale WRITE setColorScale) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QCPRange dataRange READ dataRange WRITE setDataRange NOTIFY dataRangeChanged) Q_PROPERTY(QCPAxis::ScaleType dataScaleType READ dataScaleType WRITE setDataScaleType NOTIFY dataScaleTypeChanged) + Q_PROPERTY(QCPColorGradient gradient READ gradient WRITE setGradient NOTIFY gradientChanged) + Q_PROPERTY(bool interpolate READ interpolate WRITE setInterpolate) + Q_PROPERTY(bool tightBoundary READ tightBoundary WRITE setTightBoundary) + Q_PROPERTY(QCPColorScale *colorScale READ colorScale WRITE setColorScale) + /// \endcond public: - explicit QCPColorMap(QCPAxis *keyAxis, QCPAxis *valueAxis); - virtual ~QCPColorMap(); - - // getters: - QCPColorMapData *data() const { return mMapData; } - QCPRange dataRange() const { return mDataRange; } - QCPAxis::ScaleType dataScaleType() const { return mDataScaleType; } - bool interpolate() const { return mInterpolate; } - bool tightBoundary() const { return mTightBoundary; } - QCPColorGradient gradient() const { return mGradient; } - QCPColorScale *colorScale() const { return mColorScale.data(); } - - // setters: - void setData(QCPColorMapData *data, bool copy=false); - Q_SLOT void setDataRange(const QCPRange &dataRange); - Q_SLOT void setDataScaleType(QCPAxis::ScaleType scaleType); - Q_SLOT void setGradient(const QCPColorGradient &gradient); - void setInterpolate(bool enabled); - void setTightBoundary(bool enabled); - void setColorScale(QCPColorScale *colorScale); - - // non-property methods: - void rescaleDataRange(bool recalculateDataBounds=false); - Q_SLOT void updateLegendIcon(Qt::TransformationMode transformMode=Qt::SmoothTransformation, const QSize &thumbSize=QSize(32, 18)); - - // reimplemented virtual methods: - 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; - + explicit QCPColorMap(QCPAxis *keyAxis, QCPAxis *valueAxis); + virtual ~QCPColorMap(); + + // getters: + QCPColorMapData *data() const { + return mMapData; + } + QCPRange dataRange() const { + return mDataRange; + } + QCPAxis::ScaleType dataScaleType() const { + return mDataScaleType; + } + bool interpolate() const { + return mInterpolate; + } + bool tightBoundary() const { + return mTightBoundary; + } + QCPColorGradient gradient() const { + return mGradient; + } + QCPColorScale *colorScale() const { + return mColorScale.data(); + } + + // setters: + void setData(QCPColorMapData *data, bool copy = false); + Q_SLOT void setDataRange(const QCPRange &dataRange); + Q_SLOT void setDataScaleType(QCPAxis::ScaleType scaleType); + Q_SLOT void setGradient(const QCPColorGradient &gradient); + void setInterpolate(bool enabled); + void setTightBoundary(bool enabled); + void setColorScale(QCPColorScale *colorScale); + + // non-property methods: + void rescaleDataRange(bool recalculateDataBounds = false); + Q_SLOT void updateLegendIcon(Qt::TransformationMode transformMode = Qt::SmoothTransformation, const QSize &thumbSize = QSize(32, 18)); + + // reimplemented virtual methods: + 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(const QCPRange &newRange); - void dataScaleTypeChanged(QCPAxis::ScaleType scaleType); - void gradientChanged(const QCPColorGradient &newGradient); - + void dataRangeChanged(const QCPRange &newRange); + void dataScaleTypeChanged(QCPAxis::ScaleType scaleType); + void gradientChanged(const QCPColorGradient &newGradient); + protected: - // property members: - QCPRange mDataRange; - QCPAxis::ScaleType mDataScaleType; - QCPColorMapData *mMapData; - QCPColorGradient mGradient; - bool mInterpolate; - bool mTightBoundary; - QPointer mColorScale; - - // non-property members: - QImage mMapImage, mUndersampledMapImage; - QPixmap mLegendIcon; - bool mMapImageInvalidated; - - // introduced virtual methods: - virtual void updateMapImage(); - - // reimplemented virtual methods: - 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; + // property members: + QCPRange mDataRange; + QCPAxis::ScaleType mDataScaleType; + QCPColorMapData *mMapData; + QCPColorGradient mGradient; + bool mInterpolate; + bool mTightBoundary; + QPointer mColorScale; + + // non-property members: + QImage mMapImage, mUndersampledMapImage; + QPixmap mLegendIcon; + bool mMapImageInvalidated; + + // introduced virtual methods: + virtual void updateMapImage(); + + // reimplemented virtual methods: + 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; }; /* end of 'src/plottables/plottable-colormap.h' */ @@ -5827,133 +6516,163 @@ protected: 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; + 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_PRIMITIVE_TYPE); /*! \typedef QCPFinancialDataContainer - + 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 QCPDataContainer QCPFinancialDataContainer; 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) - Q_PROPERTY(QPen penPositive READ penPositive WRITE setPenPositive) - Q_PROPERTY(QPen penNegative READ penNegative WRITE setPenNegative) - /// \endcond + 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) + Q_PROPERTY(QPen penPositive READ penPositive WRITE setPenPositive) + 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. + /*! + 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. + + \see setChartStyle + */ + enum ChartStyle { csOhlc ///< Open-High-Low-Close bar representation + , csCandlestick ///< Candlestick representation + }; + Q_ENUMS(ChartStyle) + + explicit QCPFinancial(QCPAxis *keyAxis, QCPAxis *valueAxis); + virtual ~QCPFinancial(); + + // getters: + 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(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); + void setPenPositive(const QPen &pen); + void setPenNegative(const QPen &pen); + + // non-property methods: + 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); + + // 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; + + // static methods: + static QCPFinancialDataContainer timeSeriesToOhlc(const QVector &time, const QVector &value, double timeBinSize, double timeBinOffset = 0); - \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. - - \see setChartStyle - */ - enum ChartStyle { csOhlc ///< Open-High-Low-Close bar representation - ,csCandlestick ///< Candlestick representation - }; - Q_ENUMS(ChartStyle) - - explicit QCPFinancial(QCPAxis *keyAxis, QCPAxis *valueAxis); - virtual ~QCPFinancial(); - - // getters: - 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(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); - void setPenPositive(const QPen &pen); - void setPenNegative(const QPen &pen); - - // non-property methods: - 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); - - // 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; - - // static methods: - static QCPFinancialDataContainer timeSeriesToOhlc(const QVector &time, const QVector &value, double timeBinSize, double timeBinOffset = 0); - protected: - // property members: - ChartStyle mChartStyle; - double mWidth; - WidthType mWidthType; - bool mTwoColored; - QBrush mBrushPositive, mBrushNegative; - QPen mPenPositive, mPenNegative; - - // reimplemented virtual methods: - 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 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; + // property members: + ChartStyle mChartStyle; + double mWidth; + WidthType mWidthType; + bool mTwoColored; + QBrush mBrushPositive, mBrushNegative; + QPen mPenPositive, mPenNegative; + + // reimplemented virtual methods: + 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 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) @@ -5966,11 +6685,11 @@ Q_DECLARE_METATYPE(QCPFinancial::ChartStyle) class QCP_LIB_DECL QCPErrorBarsData { public: - QCPErrorBarsData(); - explicit QCPErrorBarsData(double error); - QCPErrorBarsData(double errorMinus, double errorPlus); - - double errorMinus, errorPlus; + QCPErrorBarsData(); + explicit QCPErrorBarsData(double error); + QCPErrorBarsData(double errorMinus, double errorPlus); + + double errorMinus, errorPlus; }; Q_DECLARE_TYPEINFO(QCPErrorBarsData, Q_PRIMITIVE_TYPE); @@ -5994,92 +6713,102 @@ 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 + 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 Q_DECL_OVERRIDE; - virtual double dataMainKey(int index) const Q_DECL_OVERRIDE; - virtual double dataSortKey(int index) const Q_DECL_OVERRIDE; - virtual double dataMainValue(int index) const Q_DECL_OVERRIDE; - virtual QCPRange dataValueRange(int index) const Q_DECL_OVERRIDE; - virtual QPointF dataPixelPosition(int index) const Q_DECL_OVERRIDE; - virtual bool sortKeyIsMainKey() const Q_DECL_OVERRIDE; - virtual QCPDataSelection selectTestRect(const QRectF &rect, bool onlySelectable) const Q_DECL_OVERRIDE; - virtual int findBegin(double sortKey, bool expandedRange=true) const Q_DECL_OVERRIDE; - virtual int findEnd(double sortKey, bool expandedRange=true) const Q_DECL_OVERRIDE; - - // 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; } - + /*! + 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 Q_DECL_OVERRIDE; + virtual double dataMainKey(int index) const Q_DECL_OVERRIDE; + virtual double dataSortKey(int index) const Q_DECL_OVERRIDE; + virtual double dataMainValue(int index) const Q_DECL_OVERRIDE; + virtual QCPRange dataValueRange(int index) const Q_DECL_OVERRIDE; + virtual QPointF dataPixelPosition(int index) const Q_DECL_OVERRIDE; + virtual bool sortKeyIsMainKey() const Q_DECL_OVERRIDE; + virtual QCPDataSelection selectTestRect(const QRectF &rect, bool onlySelectable) const Q_DECL_OVERRIDE; + virtual int findBegin(double sortKey, bool expandedRange = true) const Q_DECL_OVERRIDE; + virtual int findEnd(double sortKey, bool expandedRange = true) const Q_DECL_OVERRIDE; + + // 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; + // 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' */ @@ -6090,39 +6819,41 @@ protected: class QCP_LIB_DECL QCPItemStraightLine : public QCPAbstractItem { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QPen pen READ pen WRITE setPen) - Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QPen pen READ pen WRITE setPen) Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) + /// \endcond public: - explicit QCPItemStraightLine(QCustomPlot *parentPlot); - virtual ~QCPItemStraightLine(); - - // getters: - QPen pen() const { return mPen; } - QPen selectedPen() const { return mSelectedPen; } - - // setters; - void setPen(const QPen &pen); - void setSelectedPen(const QPen &pen); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const Q_DECL_OVERRIDE; - - QCPItemPosition * const point1; - QCPItemPosition * const point2; - + explicit QCPItemStraightLine(QCustomPlot *parentPlot); + virtual ~QCPItemStraightLine(); + + // getters: + QPen pen() const { + return mPen; + } + QPen selectedPen() const { + return mSelectedPen; + } + + // setters; + void setPen(const QPen &pen); + void setSelectedPen(const QPen &pen); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = 0) const Q_DECL_OVERRIDE; + + QCPItemPosition *const point1; + QCPItemPosition *const point2; + protected: - // property members: - QPen mPen, mSelectedPen; - - // reimplemented virtual methods: - virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; - - // non-virtual methods: - QLineF getRectClippedStraightLine(const QCPVector2D &point1, const QCPVector2D &vec, const QRect &rect) const; - QPen mainPen() const; + // property members: + QPen mPen, mSelectedPen; + + // reimplemented virtual methods: + virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; + + // non-virtual methods: + QLineF getRectClippedStraightLine(const QCPVector2D &point1, const QCPVector2D &vec, const QRect &rect) const; + QPen mainPen() const; }; /* end of 'src/items/item-straightline.h' */ @@ -6133,46 +6864,52 @@ protected: class QCP_LIB_DECL QCPItemLine : public QCPAbstractItem { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QPen pen READ pen WRITE setPen) - Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) - Q_PROPERTY(QCPLineEnding head READ head WRITE setHead) - Q_PROPERTY(QCPLineEnding tail READ tail WRITE setTail) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QPen pen READ pen WRITE setPen) Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) + Q_PROPERTY(QCPLineEnding head READ head WRITE setHead) + Q_PROPERTY(QCPLineEnding tail READ tail WRITE setTail) + /// \endcond public: - explicit QCPItemLine(QCustomPlot *parentPlot); - virtual ~QCPItemLine(); - - // getters: - QPen pen() const { return mPen; } - QPen selectedPen() const { return mSelectedPen; } - QCPLineEnding head() const { return mHead; } - QCPLineEnding tail() const { return mTail; } - - // setters; - void setPen(const QPen &pen); - void setSelectedPen(const QPen &pen); - void setHead(const QCPLineEnding &head); - void setTail(const QCPLineEnding &tail); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const Q_DECL_OVERRIDE; - - QCPItemPosition * const start; - QCPItemPosition * const end; - + explicit QCPItemLine(QCustomPlot *parentPlot); + virtual ~QCPItemLine(); + + // getters: + QPen pen() const { + return mPen; + } + QPen selectedPen() const { + return mSelectedPen; + } + QCPLineEnding head() const { + return mHead; + } + QCPLineEnding tail() const { + return mTail; + } + + // setters; + void setPen(const QPen &pen); + void setSelectedPen(const QPen &pen); + void setHead(const QCPLineEnding &head); + void setTail(const QCPLineEnding &tail); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = 0) const Q_DECL_OVERRIDE; + + QCPItemPosition *const start; + QCPItemPosition *const end; + protected: - // property members: - QPen mPen, mSelectedPen; - QCPLineEnding mHead, mTail; - - // reimplemented virtual methods: - virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; - - // non-virtual methods: - QLineF getRectClippedLine(const QCPVector2D &start, const QCPVector2D &end, const QRect &rect) const; - QPen mainPen() const; + // property members: + QPen mPen, mSelectedPen; + QCPLineEnding mHead, mTail; + + // reimplemented virtual methods: + virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; + + // non-virtual methods: + QLineF getRectClippedLine(const QCPVector2D &start, const QCPVector2D &end, const QRect &rect) const; + QPen mainPen() const; }; /* end of 'src/items/item-line.h' */ @@ -6183,47 +6920,53 @@ protected: class QCP_LIB_DECL QCPItemCurve : public QCPAbstractItem { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QPen pen READ pen WRITE setPen) - Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) - Q_PROPERTY(QCPLineEnding head READ head WRITE setHead) - Q_PROPERTY(QCPLineEnding tail READ tail WRITE setTail) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QPen pen READ pen WRITE setPen) Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) + Q_PROPERTY(QCPLineEnding head READ head WRITE setHead) + Q_PROPERTY(QCPLineEnding tail READ tail WRITE setTail) + /// \endcond public: - explicit QCPItemCurve(QCustomPlot *parentPlot); - virtual ~QCPItemCurve(); - - // getters: - QPen pen() const { return mPen; } - QPen selectedPen() const { return mSelectedPen; } - QCPLineEnding head() const { return mHead; } - QCPLineEnding tail() const { return mTail; } - - // setters; - void setPen(const QPen &pen); - void setSelectedPen(const QPen &pen); - void setHead(const QCPLineEnding &head); - void setTail(const QCPLineEnding &tail); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const Q_DECL_OVERRIDE; - - QCPItemPosition * const start; - QCPItemPosition * const startDir; - QCPItemPosition * const endDir; - QCPItemPosition * const end; - + explicit QCPItemCurve(QCustomPlot *parentPlot); + virtual ~QCPItemCurve(); + + // getters: + QPen pen() const { + return mPen; + } + QPen selectedPen() const { + return mSelectedPen; + } + QCPLineEnding head() const { + return mHead; + } + QCPLineEnding tail() const { + return mTail; + } + + // setters; + void setPen(const QPen &pen); + void setSelectedPen(const QPen &pen); + void setHead(const QCPLineEnding &head); + void setTail(const QCPLineEnding &tail); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = 0) const Q_DECL_OVERRIDE; + + QCPItemPosition *const start; + QCPItemPosition *const startDir; + QCPItemPosition *const endDir; + QCPItemPosition *const end; + protected: - // property members: - QPen mPen, mSelectedPen; - QCPLineEnding mHead, mTail; - - // reimplemented virtual methods: - virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; - - // non-virtual methods: - QPen mainPen() const; + // property members: + QPen mPen, mSelectedPen; + QCPLineEnding mHead, mTail; + + // reimplemented virtual methods: + virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; + + // non-virtual methods: + QPen mainPen() const; }; /* end of 'src/items/item-curve.h' */ @@ -6234,55 +6977,61 @@ protected: class QCP_LIB_DECL QCPItemRect : public QCPAbstractItem { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - 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) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES 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) + /// \endcond public: - explicit QCPItemRect(QCustomPlot *parentPlot); - virtual ~QCPItemRect(); - - // getters: - QPen pen() const { return mPen; } - QPen selectedPen() const { return mSelectedPen; } - QBrush brush() const { return mBrush; } - QBrush selectedBrush() const { return mSelectedBrush; } - - // setters; - void setPen(const QPen &pen); - void setSelectedPen(const QPen &pen); - void setBrush(const QBrush &brush); - void setSelectedBrush(const QBrush &brush); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const Q_DECL_OVERRIDE; - - QCPItemPosition * const topLeft; - QCPItemPosition * const bottomRight; - QCPItemAnchor * const top; - QCPItemAnchor * const topRight; - QCPItemAnchor * const right; - QCPItemAnchor * const bottom; - QCPItemAnchor * const bottomLeft; - QCPItemAnchor * const left; - + explicit QCPItemRect(QCustomPlot *parentPlot); + virtual ~QCPItemRect(); + + // getters: + QPen pen() const { + return mPen; + } + QPen selectedPen() const { + return mSelectedPen; + } + QBrush brush() const { + return mBrush; + } + QBrush selectedBrush() const { + return mSelectedBrush; + } + + // setters; + void setPen(const QPen &pen); + void setSelectedPen(const QPen &pen); + void setBrush(const QBrush &brush); + void setSelectedBrush(const QBrush &brush); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = 0) const Q_DECL_OVERRIDE; + + QCPItemPosition *const topLeft; + QCPItemPosition *const bottomRight; + QCPItemAnchor *const top; + QCPItemAnchor *const topRight; + QCPItemAnchor *const right; + QCPItemAnchor *const bottom; + QCPItemAnchor *const bottomLeft; + QCPItemAnchor *const left; + protected: - enum AnchorIndex {aiTop, aiTopRight, aiRight, aiBottom, aiBottomLeft, aiLeft}; - - // property members: - QPen mPen, mSelectedPen; - QBrush mBrush, mSelectedBrush; - - // reimplemented virtual methods: - 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; + enum AnchorIndex {aiTop, aiTopRight, aiRight, aiBottom, aiBottomLeft, aiLeft}; + + // property members: + QPen mPen, mSelectedPen; + QBrush mBrush, mSelectedBrush; + + // reimplemented virtual methods: + 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' */ @@ -6293,93 +7042,117 @@ protected: class QCP_LIB_DECL QCPItemText : public QCPAbstractItem { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QColor color READ color WRITE setColor) - Q_PROPERTY(QColor selectedColor READ selectedColor WRITE setSelectedColor) - 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(QFont font READ font WRITE setFont) - Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont) - Q_PROPERTY(QString text READ text WRITE setText) - Q_PROPERTY(Qt::Alignment positionAlignment READ positionAlignment WRITE setPositionAlignment) - Q_PROPERTY(Qt::Alignment textAlignment READ textAlignment WRITE setTextAlignment) - Q_PROPERTY(double rotation READ rotation WRITE setRotation) - Q_PROPERTY(QMargins padding READ padding WRITE setPadding) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QColor color READ color WRITE setColor) Q_PROPERTY(QColor selectedColor READ selectedColor WRITE setSelectedColor) + 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(QFont font READ font WRITE setFont) + Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont) + Q_PROPERTY(QString text READ text WRITE setText) + Q_PROPERTY(Qt::Alignment positionAlignment READ positionAlignment WRITE setPositionAlignment) + Q_PROPERTY(Qt::Alignment textAlignment READ textAlignment WRITE setTextAlignment) + Q_PROPERTY(double rotation READ rotation WRITE setRotation) + Q_PROPERTY(QMargins padding READ padding WRITE setPadding) + /// \endcond public: - explicit QCPItemText(QCustomPlot *parentPlot); - virtual ~QCPItemText(); - - // getters: - QColor color() const { return mColor; } - QColor selectedColor() const { return mSelectedColor; } - QPen pen() const { return mPen; } - QPen selectedPen() const { return mSelectedPen; } - QBrush brush() const { return mBrush; } - QBrush selectedBrush() const { return mSelectedBrush; } - QFont font() const { return mFont; } - QFont selectedFont() const { return mSelectedFont; } - QString text() const { return mText; } - Qt::Alignment positionAlignment() const { return mPositionAlignment; } - Qt::Alignment textAlignment() const { return mTextAlignment; } - double rotation() const { return mRotation; } - QMargins padding() const { return mPadding; } - - // setters; - void setColor(const QColor &color); - void setSelectedColor(const QColor &color); - void setPen(const QPen &pen); - void setSelectedPen(const QPen &pen); - void setBrush(const QBrush &brush); - void setSelectedBrush(const QBrush &brush); - void setFont(const QFont &font); - void setSelectedFont(const QFont &font); - void setText(const QString &text); - void setPositionAlignment(Qt::Alignment alignment); - void setTextAlignment(Qt::Alignment alignment); - void setRotation(double degrees); - void setPadding(const QMargins &padding); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const Q_DECL_OVERRIDE; - - QCPItemPosition * const position; - QCPItemAnchor * const topLeft; - QCPItemAnchor * const top; - QCPItemAnchor * const topRight; - QCPItemAnchor * const right; - QCPItemAnchor * const bottomRight; - QCPItemAnchor * const bottom; - QCPItemAnchor * const bottomLeft; - QCPItemAnchor * const left; - + explicit QCPItemText(QCustomPlot *parentPlot); + virtual ~QCPItemText(); + + // getters: + QColor color() const { + return mColor; + } + QColor selectedColor() const { + return mSelectedColor; + } + QPen pen() const { + return mPen; + } + QPen selectedPen() const { + return mSelectedPen; + } + QBrush brush() const { + return mBrush; + } + QBrush selectedBrush() const { + return mSelectedBrush; + } + QFont font() const { + return mFont; + } + QFont selectedFont() const { + return mSelectedFont; + } + QString text() const { + return mText; + } + Qt::Alignment positionAlignment() const { + return mPositionAlignment; + } + Qt::Alignment textAlignment() const { + return mTextAlignment; + } + double rotation() const { + return mRotation; + } + QMargins padding() const { + return mPadding; + } + + // setters; + void setColor(const QColor &color); + void setSelectedColor(const QColor &color); + void setPen(const QPen &pen); + void setSelectedPen(const QPen &pen); + void setBrush(const QBrush &brush); + void setSelectedBrush(const QBrush &brush); + void setFont(const QFont &font); + void setSelectedFont(const QFont &font); + void setText(const QString &text); + void setPositionAlignment(Qt::Alignment alignment); + void setTextAlignment(Qt::Alignment alignment); + void setRotation(double degrees); + void setPadding(const QMargins &padding); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = 0) const Q_DECL_OVERRIDE; + + QCPItemPosition *const position; + QCPItemAnchor *const topLeft; + QCPItemAnchor *const top; + QCPItemAnchor *const topRight; + QCPItemAnchor *const right; + QCPItemAnchor *const bottomRight; + QCPItemAnchor *const bottom; + QCPItemAnchor *const bottomLeft; + QCPItemAnchor *const left; + protected: - enum AnchorIndex {aiTopLeft, aiTop, aiTopRight, aiRight, aiBottomRight, aiBottom, aiBottomLeft, aiLeft}; - - // property members: - QColor mColor, mSelectedColor; - QPen mPen, mSelectedPen; - QBrush mBrush, mSelectedBrush; - QFont mFont, mSelectedFont; - QString mText; - Qt::Alignment mPositionAlignment; - Qt::Alignment mTextAlignment; - double mRotation; - QMargins mPadding; - - // reimplemented virtual methods: - 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; - QFont mainFont() const; - QColor mainColor() const; - QPen mainPen() const; - QBrush mainBrush() const; + enum AnchorIndex {aiTopLeft, aiTop, aiTopRight, aiRight, aiBottomRight, aiBottom, aiBottomLeft, aiLeft}; + + // property members: + QColor mColor, mSelectedColor; + QPen mPen, mSelectedPen; + QBrush mBrush, mSelectedBrush; + QFont mFont, mSelectedFont; + QString mText; + Qt::Alignment mPositionAlignment; + Qt::Alignment mTextAlignment; + double mRotation; + QMargins mPadding; + + // reimplemented virtual methods: + 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; + QFont mainFont() const; + QColor mainColor() const; + QPen mainPen() const; + QBrush mainBrush() const; }; /* end of 'src/items/item-text.h' */ @@ -6390,58 +7163,64 @@ protected: class QCP_LIB_DECL QCPItemEllipse : public QCPAbstractItem { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - 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) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES 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) + /// \endcond public: - explicit QCPItemEllipse(QCustomPlot *parentPlot); - virtual ~QCPItemEllipse(); - - // getters: - QPen pen() const { return mPen; } - QPen selectedPen() const { return mSelectedPen; } - QBrush brush() const { return mBrush; } - QBrush selectedBrush() const { return mSelectedBrush; } - - // setters; - void setPen(const QPen &pen); - void setSelectedPen(const QPen &pen); - void setBrush(const QBrush &brush); - void setSelectedBrush(const QBrush &brush); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const Q_DECL_OVERRIDE; - - QCPItemPosition * const topLeft; - QCPItemPosition * const bottomRight; - QCPItemAnchor * const topLeftRim; - QCPItemAnchor * const top; - QCPItemAnchor * const topRightRim; - QCPItemAnchor * const right; - QCPItemAnchor * const bottomRightRim; - QCPItemAnchor * const bottom; - QCPItemAnchor * const bottomLeftRim; - QCPItemAnchor * const left; - QCPItemAnchor * const center; - + explicit QCPItemEllipse(QCustomPlot *parentPlot); + virtual ~QCPItemEllipse(); + + // getters: + QPen pen() const { + return mPen; + } + QPen selectedPen() const { + return mSelectedPen; + } + QBrush brush() const { + return mBrush; + } + QBrush selectedBrush() const { + return mSelectedBrush; + } + + // setters; + void setPen(const QPen &pen); + void setSelectedPen(const QPen &pen); + void setBrush(const QBrush &brush); + void setSelectedBrush(const QBrush &brush); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = 0) const Q_DECL_OVERRIDE; + + QCPItemPosition *const topLeft; + QCPItemPosition *const bottomRight; + QCPItemAnchor *const topLeftRim; + QCPItemAnchor *const top; + QCPItemAnchor *const topRightRim; + QCPItemAnchor *const right; + QCPItemAnchor *const bottomRightRim; + QCPItemAnchor *const bottom; + QCPItemAnchor *const bottomLeftRim; + QCPItemAnchor *const left; + QCPItemAnchor *const center; + protected: - enum AnchorIndex {aiTopLeftRim, aiTop, aiTopRightRim, aiRight, aiBottomRightRim, aiBottom, aiBottomLeftRim, aiLeft, aiCenter}; - - // property members: - QPen mPen, mSelectedPen; - QBrush mBrush, mSelectedBrush; - - // reimplemented virtual methods: - 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; + enum AnchorIndex {aiTopLeftRim, aiTop, aiTopRightRim, aiRight, aiBottomRightRim, aiBottom, aiBottomLeftRim, aiLeft, aiCenter}; + + // property members: + QPen mPen, mSelectedPen; + QBrush mBrush, mSelectedBrush; + + // reimplemented virtual methods: + 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' */ @@ -6452,65 +7231,75 @@ protected: class QCP_LIB_DECL QCPItemPixmap : public QCPAbstractItem { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QPixmap pixmap READ pixmap WRITE setPixmap) - Q_PROPERTY(bool scaled READ scaled WRITE setScaled) - Q_PROPERTY(Qt::AspectRatioMode aspectRatioMode READ aspectRatioMode) - Q_PROPERTY(Qt::TransformationMode transformationMode READ transformationMode) - Q_PROPERTY(QPen pen READ pen WRITE setPen) - Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QPixmap pixmap READ pixmap WRITE setPixmap) Q_PROPERTY(bool scaled READ scaled WRITE setScaled) + Q_PROPERTY(Qt::AspectRatioMode aspectRatioMode READ aspectRatioMode) + Q_PROPERTY(Qt::TransformationMode transformationMode READ transformationMode) + Q_PROPERTY(QPen pen READ pen WRITE setPen) + Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) + /// \endcond public: - explicit QCPItemPixmap(QCustomPlot *parentPlot); - virtual ~QCPItemPixmap(); - - // getters: - QPixmap pixmap() const { return mPixmap; } - bool scaled() const { return mScaled; } - Qt::AspectRatioMode aspectRatioMode() const { return mAspectRatioMode; } - Qt::TransformationMode transformationMode() const { return mTransformationMode; } - QPen pen() const { return mPen; } - QPen selectedPen() const { return mSelectedPen; } - - // setters; - void setPixmap(const QPixmap &pixmap); - void setScaled(bool scaled, Qt::AspectRatioMode aspectRatioMode=Qt::KeepAspectRatio, Qt::TransformationMode transformationMode=Qt::SmoothTransformation); - void setPen(const QPen &pen); - void setSelectedPen(const QPen &pen); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const Q_DECL_OVERRIDE; - - QCPItemPosition * const topLeft; - QCPItemPosition * const bottomRight; - QCPItemAnchor * const top; - QCPItemAnchor * const topRight; - QCPItemAnchor * const right; - QCPItemAnchor * const bottom; - QCPItemAnchor * const bottomLeft; - QCPItemAnchor * const left; - + explicit QCPItemPixmap(QCustomPlot *parentPlot); + virtual ~QCPItemPixmap(); + + // getters: + QPixmap pixmap() const { + return mPixmap; + } + bool scaled() const { + return mScaled; + } + Qt::AspectRatioMode aspectRatioMode() const { + return mAspectRatioMode; + } + Qt::TransformationMode transformationMode() const { + return mTransformationMode; + } + QPen pen() const { + return mPen; + } + QPen selectedPen() const { + return mSelectedPen; + } + + // setters; + void setPixmap(const QPixmap &pixmap); + void setScaled(bool scaled, Qt::AspectRatioMode aspectRatioMode = Qt::KeepAspectRatio, Qt::TransformationMode transformationMode = Qt::SmoothTransformation); + void setPen(const QPen &pen); + void setSelectedPen(const QPen &pen); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = 0) const Q_DECL_OVERRIDE; + + QCPItemPosition *const topLeft; + QCPItemPosition *const bottomRight; + QCPItemAnchor *const top; + QCPItemAnchor *const topRight; + QCPItemAnchor *const right; + QCPItemAnchor *const bottom; + QCPItemAnchor *const bottomLeft; + QCPItemAnchor *const left; + protected: - enum AnchorIndex {aiTop, aiTopRight, aiRight, aiBottom, aiBottomLeft, aiLeft}; - - // property members: - 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) 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); - QRect getFinalRect(bool *flippedHorz=0, bool *flippedVert=0) const; - QPen mainPen() const; + enum AnchorIndex {aiTop, aiTopRight, aiRight, aiBottom, aiBottomLeft, aiLeft}; + + // property members: + 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) 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); + QRect getFinalRect(bool *flippedHorz = 0, bool *flippedVert = 0) const; + QPen mainPen() const; }; /* end of 'src/items/item-pixmap.h' */ @@ -6521,81 +7310,99 @@ protected: class QCP_LIB_DECL QCPItemTracer : public QCPAbstractItem { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - 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(double size READ size WRITE setSize) - Q_PROPERTY(TracerStyle style READ style WRITE setStyle) - Q_PROPERTY(QCPGraph* graph READ graph WRITE setGraph) - Q_PROPERTY(double graphKey READ graphKey WRITE setGraphKey) - Q_PROPERTY(bool interpolating READ interpolating WRITE setInterpolating) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + 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(double size READ size WRITE setSize) + Q_PROPERTY(TracerStyle style READ style WRITE setStyle) + Q_PROPERTY(QCPGraph *graph READ graph WRITE setGraph) + Q_PROPERTY(double graphKey READ graphKey WRITE setGraphKey) + Q_PROPERTY(bool interpolating READ interpolating WRITE setInterpolating) + /// \endcond public: - /*! - The different visual appearances a tracer item can have. Some styles size may be controlled with \ref setSize. - - \see setStyle - */ - enum TracerStyle { tsNone ///< The tracer is not visible - ,tsPlus ///< A plus shaped crosshair with limited size - ,tsCrosshair ///< A plus shaped crosshair which spans the complete axis rect - ,tsCircle ///< A circle - ,tsSquare ///< A square - }; - Q_ENUMS(TracerStyle) + /*! + The different visual appearances a tracer item can have. Some styles size may be controlled with \ref setSize. - explicit QCPItemTracer(QCustomPlot *parentPlot); - virtual ~QCPItemTracer(); + \see setStyle + */ + enum TracerStyle { tsNone ///< The tracer is not visible + , tsPlus ///< A plus shaped crosshair with limited size + , tsCrosshair ///< A plus shaped crosshair which spans the complete axis rect + , tsCircle ///< A circle + , tsSquare ///< A square + }; + Q_ENUMS(TracerStyle) - // getters: - QPen pen() const { return mPen; } - QPen selectedPen() const { return mSelectedPen; } - QBrush brush() const { return mBrush; } - QBrush selectedBrush() const { return mSelectedBrush; } - double size() const { return mSize; } - TracerStyle style() const { return mStyle; } - QCPGraph *graph() const { return mGraph; } - double graphKey() const { return mGraphKey; } - bool interpolating() const { return mInterpolating; } + explicit QCPItemTracer(QCustomPlot *parentPlot); + virtual ~QCPItemTracer(); - // setters; - void setPen(const QPen &pen); - void setSelectedPen(const QPen &pen); - void setBrush(const QBrush &brush); - void setSelectedBrush(const QBrush &brush); - void setSize(double size); - void setStyle(TracerStyle style); - void setGraph(QCPGraph *graph); - void setGraphKey(double key); - void setInterpolating(bool enabled); + // getters: + QPen pen() const { + return mPen; + } + QPen selectedPen() const { + return mSelectedPen; + } + QBrush brush() const { + return mBrush; + } + QBrush selectedBrush() const { + return mSelectedBrush; + } + double size() const { + return mSize; + } + TracerStyle style() const { + return mStyle; + } + QCPGraph *graph() const { + return mGraph; + } + double graphKey() const { + return mGraphKey; + } + bool interpolating() const { + return mInterpolating; + } - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const Q_DECL_OVERRIDE; - - // non-virtual methods: - void updatePosition(); + // setters; + void setPen(const QPen &pen); + void setSelectedPen(const QPen &pen); + void setBrush(const QBrush &brush); + void setSelectedBrush(const QBrush &brush); + void setSize(double size); + void setStyle(TracerStyle style); + void setGraph(QCPGraph *graph); + void setGraphKey(double key); + void setInterpolating(bool enabled); - QCPItemPosition * const position; + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = 0) const Q_DECL_OVERRIDE; + + // non-virtual methods: + void updatePosition(); + + QCPItemPosition *const position; protected: - // property members: - QPen mPen, mSelectedPen; - QBrush mBrush, mSelectedBrush; - double mSize; - TracerStyle mStyle; - QCPGraph *mGraph; - double mGraphKey; - bool mInterpolating; + // property members: + QPen mPen, mSelectedPen; + QBrush mBrush, mSelectedBrush; + double mSize; + TracerStyle mStyle; + QCPGraph *mGraph; + double mGraphKey; + bool mInterpolating; - // reimplemented virtual methods: - virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; + // reimplemented virtual methods: + virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; - // non-virtual methods: - QPen mainPen() const; - QBrush mainBrush() const; + // non-virtual methods: + QPen mainPen() const; + QBrush mainBrush() const; }; Q_DECLARE_METATYPE(QCPItemTracer::TracerStyle) @@ -6607,62 +7414,70 @@ Q_DECLARE_METATYPE(QCPItemTracer::TracerStyle) class QCP_LIB_DECL QCPItemBracket : public QCPAbstractItem { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QPen pen READ pen WRITE setPen) - Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) - Q_PROPERTY(double length READ length WRITE setLength) - Q_PROPERTY(BracketStyle style READ style WRITE setStyle) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(QPen pen READ pen WRITE setPen) + Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) + Q_PROPERTY(double length READ length WRITE setLength) + 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) + /*! + 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) + + explicit QCPItemBracket(QCustomPlot *parentPlot); + virtual ~QCPItemBracket(); + + // getters: + QPen pen() const { + return mPen; + } + QPen selectedPen() const { + return mSelectedPen; + } + double length() const { + return mLength; + } + BracketStyle style() const { + return mStyle; + } + + // setters; + void setPen(const QPen &pen); + void setSelectedPen(const QPen &pen); + void setLength(double length); + void setStyle(BracketStyle style); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = 0) const Q_DECL_OVERRIDE; + + QCPItemPosition *const left; + QCPItemPosition *const right; + QCPItemAnchor *const center; - explicit QCPItemBracket(QCustomPlot *parentPlot); - virtual ~QCPItemBracket(); - - // getters: - QPen pen() const { return mPen; } - QPen selectedPen() const { return mSelectedPen; } - double length() const { return mLength; } - BracketStyle style() const { return mStyle; } - - // setters; - void setPen(const QPen &pen); - void setSelectedPen(const QPen &pen); - void setLength(double length); - void setStyle(BracketStyle style); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const Q_DECL_OVERRIDE; - - QCPItemPosition * const left; - QCPItemPosition * const right; - QCPItemAnchor * const center; - protected: - // property members: - enum AnchorIndex {aiCenter}; - QPen mPen, mSelectedPen; - double mLength; - BracketStyle mStyle; - - // reimplemented virtual methods: - virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; - virtual QPointF anchorPixelPosition(int anchorId) const Q_DECL_OVERRIDE; - - // non-virtual methods: - QPen mainPen() const; + // property members: + enum AnchorIndex {aiCenter}; + QPen mPen, mSelectedPen; + double mLength; + BracketStyle mStyle; + + // reimplemented virtual methods: + 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) diff --git a/third/3rd_qcustomplot/v2_1/qcustomplot.cpp b/third/3rd_qcustomplot/v2_1/qcustomplot.cpp index 04f3147..8a6cf1a 100644 --- a/third/3rd_qcustomplot/v2_1/qcustomplot.cpp +++ b/third/3rd_qcustomplot/v2_1/qcustomplot.cpp @@ -1,4 +1,4 @@ -/*************************************************************************** +/*************************************************************************** ** ** ** QCustomPlot, an easy to use, modern plotting widget for Qt ** ** Copyright (C) 2011-2021 Emanuel Eichhammer ** @@ -24,7 +24,7 @@ ****************************************************************************/ #include "qcustomplot.h" - +#include "smoothcurve.h" /* including file 'src/vector2d.cpp' */ /* modified 2021-03-29T02:30:44, size 7973 */ @@ -35,7 +35,7 @@ /*! \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. */ @@ -43,70 +43,70 @@ /* 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 double QCPVector2D::angle() const - + Returns the angle of the vector in radians. The angle is measured between the positive x line and the vector, counter-clockwise in a mathematical coordinate system (y axis upwards positive). In screen/widget coordinates where the y axis is inverted, the angle appears clockwise. */ /*! \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. */ @@ -116,8 +116,8 @@ Creates a QCPVector2D object and initializes the x and y coordinates to 0. */ QCPVector2D::QCPVector2D() : - mX(0), - mY(0) + mX(0), + mY(0) { } @@ -126,8 +126,8 @@ QCPVector2D::QCPVector2D() : values. */ QCPVector2D::QCPVector2D(double x, double y) : - mX(x), - mY(y) + mX(x), + mY(y) { } @@ -136,8 +136,8 @@ QCPVector2D::QCPVector2D(double x, double y) : the specified \a point. */ QCPVector2D::QCPVector2D(const QPoint &point) : - mX(point.x()), - mY(point.y()) + mX(point.x()), + mY(point.y()) { } @@ -146,85 +146,90 @@ QCPVector2D::QCPVector2D(const QPoint &point) : the specified \a point. */ QCPVector2D::QCPVector2D(const QPointF &point) : - mX(point.x()), - mY(point.y()) + mX(point.x()), + mY(point.y()) { } /*! Normalizes this vector. After this operation, the length of the vector is equal to 1. - + If the vector has both entries set to zero, this method does nothing. - + \see normalized, length, lengthSquared */ void QCPVector2D::normalize() { - if (mX == 0.0 && mY == 0.0) return; - const double lenInv = 1.0/length(); - mX *= lenInv; - mY *= lenInv; + if (mX == 0.0 && mY == 0.0) { + return; + } + const double lenInv = 1.0 / length(); + mX *= lenInv; + mY *= lenInv; } /*! Returns a normalized version of this vector. The length of the returned vector is equal to 1. - + If the vector has both entries set to zero, this method returns the vector unmodified. - + \see normalize, length, lengthSquared */ QCPVector2D QCPVector2D::normalized() const { - if (mX == 0.0 && mY == 0.0) return *this; - const double lenInv = 1.0/length(); - return QCPVector2D(mX*lenInv, mY*lenInv); + if (mX == 0.0 && mY == 0.0) { + return *this; + } + const double lenInv = 1.0 / length(); + return QCPVector2D(mX * lenInv, mY * lenInv); } /*! \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 { - const QCPVector2D v(end-start); - const double vLengthSqr = v.lengthSquared(); - if (!qFuzzyIsNull(vLengthSqr)) - { - const 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(); + const QCPVector2D v(end - start); + const double vLengthSqr = v.lengthSquared(); + if (!qFuzzyIsNull(vLengthSqr)) { + const 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())); + 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(); + return qAbs((*this - base).dot(direction.perpendicular())) / direction.length(); } /*! @@ -233,9 +238,9 @@ double QCPVector2D::distanceToStraightLine(const QCPVector2D &base, const QCPVec */ QCPVector2D &QCPVector2D::operator*=(double factor) { - mX *= factor; - mY *= factor; - return *this; + mX *= factor; + mY *= factor; + return *this; } /*! @@ -244,9 +249,9 @@ QCPVector2D &QCPVector2D::operator*=(double factor) */ QCPVector2D &QCPVector2D::operator/=(double divisor) { - mX /= divisor; - mY /= divisor; - return *this; + mX /= divisor; + mY /= divisor; + return *this; } /*! @@ -254,9 +259,9 @@ QCPVector2D &QCPVector2D::operator/=(double divisor) */ QCPVector2D &QCPVector2D::operator+=(const QCPVector2D &vector) { - mX += vector.mX; - mY += vector.mY; - return *this; + mX += vector.mX; + mY += vector.mY; + return *this; } /*! @@ -264,9 +269,9 @@ QCPVector2D &QCPVector2D::operator+=(const QCPVector2D &vector) */ QCPVector2D &QCPVector2D::operator-=(const QCPVector2D &vector) { - mX -= vector.mX; - mY -= vector.mY; - return *this; + mX -= vector.mX; + mY -= vector.mY; + return *this; } /* end of 'src/vector2d.cpp' */ @@ -280,11 +285,11 @@ QCPVector2D &QCPVector2D::operator-=(const QCPVector2D &vector) /*! \class QCPPainter \brief QPainter subclass used internally - + This QPainter subclass is used to provide some extended functionality e.g. for tweaking position consistency between antialiased and non-antialiased painting. Further it provides workarounds for QPainter quirks. - + \warning This class intentionally hides non-virtual functions of QPainter, e.g. setPen, save and restore. So while it is possible to pass a QCPPainter instance to a function that expects a QPainter pointer, some of the workarounds and tweaks will be unavailable to the function (because @@ -295,85 +300,90 @@ QCPVector2D &QCPVector2D::operator-=(const QCPVector2D &vector) Creates a new QCPPainter instance and sets default values */ QCPPainter::QCPPainter() : - mModes(pmDefault), - mIsAntialiasing(false) + mModes(pmDefault), + mIsAntialiasing(false) { - // don't setRenderHint(QPainter::NonCosmeticDefautPen) here, because painter isn't active yet and - // a call to begin() will follow + // don't setRenderHint(QPainter::NonCosmeticDefautPen) here, because painter isn't active yet and + // a call to begin() will follow } /*! Creates a new QCPPainter instance on the specified paint \a device and sets default values. Just like the analogous QPainter constructor, begins painting on \a device immediately. - + Like \ref begin, this method sets QPainter::NonCosmeticDefaultPen in Qt versions before Qt5. */ QCPPainter::QCPPainter(QPaintDevice *device) : - QPainter(device), - mModes(pmDefault), - mIsAntialiasing(false) + QPainter(device), + mModes(pmDefault), + mIsAntialiasing(false) { #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) // before Qt5, default pens used to be cosmetic if NonCosmeticDefaultPen flag isn't set. So we set it to get consistency across Qt versions. - if (isActive()) - setRenderHint(QPainter::NonCosmeticDefaultPen); + if (isActive()) { + setRenderHint(QPainter::NonCosmeticDefaultPen); + } #endif } /*! Sets the pen of the painter and applies certain fixes to it, depending on the mode of this QCPPainter. - + \note this function hides the non-virtual base class implementation. */ void QCPPainter::setPen(const QPen &pen) { - QPainter::setPen(pen); - if (mModes.testFlag(pmNonCosmetic)) - makeNonCosmetic(); + QPainter::setPen(pen); + if (mModes.testFlag(pmNonCosmetic)) { + makeNonCosmetic(); + } } /*! \overload - + Sets the pen (by color) of the painter and applies certain fixes to it, depending on the mode of this QCPPainter. - + \note this function hides the non-virtual base class implementation. */ void QCPPainter::setPen(const QColor &color) { - QPainter::setPen(color); - if (mModes.testFlag(pmNonCosmetic)) - makeNonCosmetic(); + QPainter::setPen(color); + if (mModes.testFlag(pmNonCosmetic)) { + makeNonCosmetic(); + } } /*! \overload - + Sets the pen (by style) of the painter and applies certain fixes to it, depending on the mode of this QCPPainter. - + \note this function hides the non-virtual base class implementation. */ void QCPPainter::setPen(Qt::PenStyle penStyle) { - QPainter::setPen(penStyle); - if (mModes.testFlag(pmNonCosmetic)) - makeNonCosmetic(); + QPainter::setPen(penStyle); + if (mModes.testFlag(pmNonCosmetic)) { + makeNonCosmetic(); + } } /*! \overload - + Works around a Qt bug introduced with Qt 4.8 which makes drawing QLineF unpredictable when antialiasing is disabled. Thus when antialiasing is disabled, it rounds the \a line to integer coordinates and then passes it to the original drawLine. - + \note this function hides the non-virtual base class implementation. */ void QCPPainter::drawLine(const QLineF &line) { - if (mIsAntialiasing || mModes.testFlag(pmVectorized)) - QPainter::drawLine(line); - else - QPainter::drawLine(line.toLine()); + if (mIsAntialiasing || mModes.testFlag(pmVectorized)) { + QPainter::drawLine(line); + } else { + QPainter::drawLine(line.toLine()); + } } /*! @@ -384,18 +394,17 @@ void QCPPainter::drawLine(const QLineF &line) */ void QCPPainter::setAntialiasing(bool enabled) { - setRenderHint(QPainter::Antialiasing, enabled); - if (mIsAntialiasing != enabled) - { - mIsAntialiasing = enabled; - if (!mModes.testFlag(pmVectorized)) // antialiasing half-pixel shift only needed for rasterized outputs - { - if (mIsAntialiasing) - translate(0.5, 0.5); - else - translate(-0.5, -0.5); + setRenderHint(QPainter::Antialiasing, enabled); + if (mIsAntialiasing != enabled) { + mIsAntialiasing = enabled; + if (!mModes.testFlag(pmVectorized)) { // antialiasing half-pixel shift only needed for rasterized outputs + if (mIsAntialiasing) { + translate(0.5, 0.5); + } else { + translate(-0.5, -0.5); + } + } } - } } /*! @@ -404,7 +413,7 @@ void QCPPainter::setAntialiasing(bool enabled) */ void QCPPainter::setModes(QCPPainter::PainterModes modes) { - mModes = modes; + mModes = modes; } /*! @@ -412,64 +421,67 @@ void QCPPainter::setModes(QCPPainter::PainterModes modes) device. This is necessary to get cosmetic pen consistency across Qt versions, because since Qt5, all pens are non-cosmetic by default, and in Qt4 this render hint must be set to get that behaviour. - + The Constructor \ref QCPPainter(QPaintDevice *device) which directly starts painting also sets the render hint as appropriate. - + \note this function hides the non-virtual base class implementation. */ bool QCPPainter::begin(QPaintDevice *device) { - bool result = QPainter::begin(device); + bool result = QPainter::begin(device); #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) // before Qt5, default pens used to be cosmetic if NonCosmeticDefaultPen flag isn't set. So we set it to get consistency across Qt versions. - if (result) - setRenderHint(QPainter::NonCosmeticDefaultPen); + if (result) { + setRenderHint(QPainter::NonCosmeticDefaultPen); + } #endif - return result; + return result; } /*! \overload - + Sets the mode of the painter. This controls whether the painter shall adjust its fixes/workarounds optimized for certain output devices. */ void QCPPainter::setMode(QCPPainter::PainterMode mode, bool enabled) { - if (!enabled && mModes.testFlag(mode)) - mModes &= ~mode; - else if (enabled && !mModes.testFlag(mode)) - mModes |= mode; + if (!enabled && mModes.testFlag(mode)) { + mModes &= ~mode; + } else if (enabled && !mModes.testFlag(mode)) { + mModes |= mode; + } } /*! Saves the painter (see QPainter::save). Since QCPPainter adds some new internal state to QPainter, the save/restore functions are reimplemented to also save/restore those members. - + \note this function hides the non-virtual base class implementation. - + \see restore */ void QCPPainter::save() { - mAntialiasingStack.push(mIsAntialiasing); - QPainter::save(); + mAntialiasingStack.push(mIsAntialiasing); + QPainter::save(); } /*! Restores the painter (see QPainter::restore). Since QCPPainter adds some new internal state to QPainter, the save/restore functions are reimplemented to also save/restore those members. - + \note this function hides the non-virtual base class implementation. - + \see save */ void QCPPainter::restore() { - if (!mAntialiasingStack.isEmpty()) - mIsAntialiasing = mAntialiasingStack.pop(); - else - qDebug() << Q_FUNC_INFO << "Unbalanced save/restore"; - QPainter::restore(); + if (!mAntialiasingStack.isEmpty()) { + mIsAntialiasing = mAntialiasingStack.pop(); + } else { + qDebug() << Q_FUNC_INFO << "Unbalanced save/restore"; + } + QPainter::restore(); } /*! @@ -478,12 +490,11 @@ void QCPPainter::restore() */ void QCPPainter::makeNonCosmetic() { - if (qFuzzyIsNull(pen().widthF())) - { - QPen p = pen(); - p.setWidth(1); - QPainter::setPen(p); - } + if (qFuzzyIsNull(pen().widthF())) { + QPen p = pen(); + p.setWidth(1); + QPainter::setPen(p); + } } /* end of 'src/painter.cpp' */ @@ -579,9 +590,9 @@ void QCPPainter::makeNonCosmetic() Subclasses must call their \ref reallocateBuffer implementation in their respective constructors. */ QCPAbstractPaintBuffer::QCPAbstractPaintBuffer(const QSize &size, double devicePixelRatio) : - mSize(size), - mDevicePixelRatio(devicePixelRatio), - mInvalidated(true) + mSize(size), + mDevicePixelRatio(devicePixelRatio), + mInvalidated(true) { } @@ -599,11 +610,10 @@ QCPAbstractPaintBuffer::~QCPAbstractPaintBuffer() */ void QCPAbstractPaintBuffer::setSize(const QSize &size) { - if (mSize != size) - { - mSize = size; - reallocateBuffer(); - } + if (mSize != size) { + mSize = size; + reallocateBuffer(); + } } /*! @@ -623,7 +633,7 @@ void QCPAbstractPaintBuffer::setSize(const QSize &size) */ void QCPAbstractPaintBuffer::setInvalidated(bool invalidated) { - mInvalidated = invalidated; + mInvalidated = invalidated; } /*! @@ -637,16 +647,15 @@ void QCPAbstractPaintBuffer::setInvalidated(bool invalidated) */ void QCPAbstractPaintBuffer::setDevicePixelRatio(double ratio) { - if (!qFuzzyCompare(ratio, mDevicePixelRatio)) - { + if (!qFuzzyCompare(ratio, mDevicePixelRatio)) { #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED - mDevicePixelRatio = ratio; - reallocateBuffer(); + mDevicePixelRatio = ratio; + reallocateBuffer(); #else - qDebug() << Q_FUNC_INFO << "Device pixel ratios not supported for Qt versions before 5.4"; - mDevicePixelRatio = 1.0; + qDebug() << Q_FUNC_INFO << "Device pixel ratios not supported for Qt versions before 5.4"; + mDevicePixelRatio = 1.0; #endif - } + } } //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -665,9 +674,9 @@ void QCPAbstractPaintBuffer::setDevicePixelRatio(double ratio) applicable. */ QCPPaintBufferPixmap::QCPPaintBufferPixmap(const QSize &size, double devicePixelRatio) : - QCPAbstractPaintBuffer(size, devicePixelRatio) + QCPAbstractPaintBuffer(size, devicePixelRatio) { - QCPPaintBufferPixmap::reallocateBuffer(); + QCPPaintBufferPixmap::reallocateBuffer(); } QCPPaintBufferPixmap::~QCPPaintBufferPixmap() @@ -677,46 +686,45 @@ QCPPaintBufferPixmap::~QCPPaintBufferPixmap() /* inherits documentation from base class */ QCPPainter *QCPPaintBufferPixmap::startPainting() { - QCPPainter *result = new QCPPainter(&mBuffer); + QCPPainter *result = new QCPPainter(&mBuffer); #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) - result->setRenderHint(QPainter::HighQualityAntialiasing); + result->setRenderHint(QPainter::HighQualityAntialiasing); #endif - return result; + 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"; + 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); + mBuffer.fill(color); } /* inherits documentation from base class */ void QCPPaintBufferPixmap::reallocateBuffer() { - setInvalidated(); - if (!qFuzzyCompare(1.0, mDevicePixelRatio)) - { + setInvalidated(); + if (!qFuzzyCompare(1.0, mDevicePixelRatio)) { #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED - mBuffer = QPixmap(mSize*mDevicePixelRatio); - mBuffer.setDevicePixelRatio(mDevicePixelRatio); + 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); + 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); - } + } else { + mBuffer = QPixmap(mSize); + } } @@ -745,72 +753,71 @@ void QCPPaintBufferPixmap::reallocateBuffer() 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)) + QCPAbstractPaintBuffer(size, devicePixelRatio), + mGlPBuffer(0), + mMultisamples(qMax(0, multisamples)) { - QCPPaintBufferGlPbuffer::reallocateBuffer(); + QCPPaintBufferGlPbuffer::reallocateBuffer(); } QCPPaintBufferGlPbuffer::~QCPPaintBufferGlPbuffer() { - if (mGlPBuffer) - delete mGlPBuffer; + 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; + 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()); + 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"; + 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); + if (mGlPBuffer) { + delete mGlPBuffer; + } + + QGLFormat format; + format.setAlpha(true); + format.setSamples(mMultisamples); + mGlPBuffer = new QGLPixelBuffer(mSize, format); } #endif // QCP_OPENGL_PBUFFER @@ -841,134 +848,130 @@ void QCPPaintBufferGlPbuffer::reallocateBuffer() instance. */ QCPPaintBufferGlFbo::QCPPaintBufferGlFbo(const QSize &size, double devicePixelRatio, QWeakPointer glContext, QWeakPointer glPaintDevice) : - QCPAbstractPaintBuffer(size, devicePixelRatio), - mGlContext(glContext), - mGlPaintDevice(glPaintDevice), - mGlFrameBuffer(0) + QCPAbstractPaintBuffer(size, devicePixelRatio), + mGlContext(glContext), + mGlPaintDevice(glPaintDevice), + mGlFrameBuffer(0) { - QCPPaintBufferGlFbo::reallocateBuffer(); + QCPPaintBufferGlFbo::reallocateBuffer(); } QCPPaintBufferGlFbo::~QCPPaintBufferGlFbo() { - if (mGlFrameBuffer) - delete mGlFrameBuffer; + if (mGlFrameBuffer) { + delete mGlFrameBuffer; + } } /* inherits documentation from base class */ QCPPainter *QCPPaintBufferGlFbo::startPainting() { - QSharedPointer paintDevice = mGlPaintDevice.toStrongRef(); - QSharedPointer context = mGlContext.toStrongRef(); - if (!paintDevice) - { - qDebug() << Q_FUNC_INFO << "OpenGL paint device doesn't exist"; - return 0; - } - if (!context) - { - qDebug() << Q_FUNC_INFO << "OpenGL context 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() != context.data()) - context->makeCurrent(context->surface()); - mGlFrameBuffer->bind(); - QCPPainter *result = new QCPPainter(paintDevice.data()); + QSharedPointer paintDevice = mGlPaintDevice.toStrongRef(); + QSharedPointer context = mGlContext.toStrongRef(); + if (!paintDevice) { + qDebug() << Q_FUNC_INFO << "OpenGL paint device doesn't exist"; + return 0; + } + if (!context) { + qDebug() << Q_FUNC_INFO << "OpenGL context 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() != context.data()) { + context->makeCurrent(context->surface()); + } + mGlFrameBuffer->bind(); + QCPPainter *result = new QCPPainter(paintDevice.data()); #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) - result->setRenderHint(QPainter::HighQualityAntialiasing); + result->setRenderHint(QPainter::HighQualityAntialiasing); #endif - return result; + 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"; + 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()); + 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) { - QSharedPointer context = mGlContext.toStrongRef(); - if (!context) - { - 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() != context.data()) - context->makeCurrent(context->surface()); - mGlFrameBuffer->bind(); - glClearColor(color.redF(), color.greenF(), color.blueF(), color.alphaF()); - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - mGlFrameBuffer->release(); + QSharedPointer context = mGlContext.toStrongRef(); + if (!context) { + 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() != context.data()) { + context->makeCurrent(context->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; - } - - QSharedPointer paintDevice = mGlPaintDevice.toStrongRef(); - QSharedPointer context = mGlContext.toStrongRef(); - if (!paintDevice) - { - qDebug() << Q_FUNC_INFO << "OpenGL paint device doesn't exist"; - return; - } - if (!context) - { - qDebug() << Q_FUNC_INFO << "OpenGL context doesn't exist"; - return; - } - - // create new fbo with appropriate size: - context->makeCurrent(context->surface()); - QOpenGLFramebufferObjectFormat frameBufferFormat; - frameBufferFormat.setSamples(context->format().samples()); - frameBufferFormat.setAttachment(QOpenGLFramebufferObject::CombinedDepthStencil); - mGlFrameBuffer = new QOpenGLFramebufferObject(mSize*mDevicePixelRatio, frameBufferFormat); - if (paintDevice->size() != mSize*mDevicePixelRatio) - paintDevice->setSize(mSize*mDevicePixelRatio); + // release and delete possibly existing framebuffer: + if (mGlFrameBuffer) { + if (mGlFrameBuffer->isBound()) { + mGlFrameBuffer->release(); + } + delete mGlFrameBuffer; + mGlFrameBuffer = 0; + } + + QSharedPointer paintDevice = mGlPaintDevice.toStrongRef(); + QSharedPointer context = mGlContext.toStrongRef(); + if (!paintDevice) { + qDebug() << Q_FUNC_INFO << "OpenGL paint device doesn't exist"; + return; + } + if (!context) { + qDebug() << Q_FUNC_INFO << "OpenGL context doesn't exist"; + return; + } + + // create new fbo with appropriate size: + context->makeCurrent(context->surface()); + QOpenGLFramebufferObjectFormat frameBufferFormat; + frameBufferFormat.setSamples(context->format().samples()); + frameBufferFormat.setAttachment(QOpenGLFramebufferObject::CombinedDepthStencil); + mGlFrameBuffer = new QOpenGLFramebufferObject(mSize * mDevicePixelRatio, frameBufferFormat); + if (paintDevice->size() != mSize * mDevicePixelRatio) { + paintDevice->setSize(mSize * mDevicePixelRatio); + } #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED - paintDevice->setDevicePixelRatio(mDevicePixelRatio); + paintDevice->setDevicePixelRatio(mDevicePixelRatio); #endif } #endif // QCP_OPENGL_FBO @@ -1041,16 +1044,16 @@ void QCPPaintBufferGlFbo::reallocateBuffer() /* start documentation of inline functions */ /*! \fn QList QCPLayer::children() const - + Returns a list of all layerables on this layer. The order corresponds to the rendering order: layerables with higher indices are drawn above layerables with lower indices. */ /*! \fn int QCPLayer::index() const - + Returns the index this layer has in the QCustomPlot. The index is the integer number by which this layer can be accessed via \ref QCustomPlot::layer. - + Layers with higher indices will be drawn above layers with lower indices. */ @@ -1058,36 +1061,38 @@ void QCPPaintBufferGlFbo::reallocateBuffer() /*! Creates a new QCPLayer instance. - + Normally you shouldn't directly instantiate layers, use \ref QCustomPlot::addLayer instead. - + \warning It is not checked that \a layerName is actually a unique layer name in \a parentPlot. This check is only performed by \ref QCustomPlot::addLayer. */ QCPLayer::QCPLayer(QCustomPlot *parentPlot, const QString &layerName) : - QObject(parentPlot), - mParentPlot(parentPlot), - mName(layerName), - mIndex(-1), // will be set to a proper value by the QCustomPlot layer creation function - mVisible(true), - mMode(lmLogical) + QObject(parentPlot), + mParentPlot(parentPlot), + mName(layerName), + mIndex(-1), // will be set to a proper value by the QCustomPlot layer creation function + mVisible(true), + mMode(lmLogical) { - // Note: no need to make sure layerName is unique, because layer - // management is done with QCustomPlot functions. + // Note: no need to make sure layerName is unique, because layer + // management is done with QCustomPlot functions. } QCPLayer::~QCPLayer() { - // If child layerables are still on this layer, detach them, so they don't try to reach back to this - // then invalid layer once they get deleted/moved themselves. This only happens when layers are deleted - // directly, like in the QCustomPlot destructor. (The regular layer removal procedure for the user is to - // call QCustomPlot::removeLayer, which moves all layerables off this layer before deleting it.) - - while (!mChildren.isEmpty()) - mChildren.last()->setLayer(nullptr); // removes itself from mChildren via removeChild() - - if (mParentPlot->currentLayer() == this) - qDebug() << Q_FUNC_INFO << "The parent plot's mCurrentLayer will be a dangling pointer. Should have been set to a valid layer or nullptr beforehand."; + // If child layerables are still on this layer, detach them, so they don't try to reach back to this + // then invalid layer once they get deleted/moved themselves. This only happens when layers are deleted + // directly, like in the QCustomPlot destructor. (The regular layer removal procedure for the user is to + // call QCustomPlot::removeLayer, which moves all layerables off this layer before deleting it.) + + while (!mChildren.isEmpty()) { + mChildren.last()->setLayer(nullptr); // removes itself from mChildren via removeChild() + } + + if (mParentPlot->currentLayer() == this) { + qDebug() << Q_FUNC_INFO << "The parent plot's mCurrentLayer will be a dangling pointer. Should have been set to a valid layer or nullptr beforehand."; + } } /*! @@ -1100,7 +1105,7 @@ QCPLayer::~QCPLayer() */ void QCPLayer::setVisible(bool visible) { - mVisible = visible; + mVisible = visible; } /*! @@ -1126,12 +1131,12 @@ void QCPLayer::setVisible(bool visible) */ void QCPLayer::setMode(QCPLayer::LayerMode mode) { - if (mMode != mode) - { - mMode = mode; - if (QSharedPointer pb = mPaintBuffer.toStrongRef()) - pb->setInvalidated(); - } + if (mMode != mode) { + mMode = mode; + if (QSharedPointer pb = mPaintBuffer.toStrongRef()) { + pb->setInvalidated(); + } + } } /*! \internal @@ -1142,17 +1147,15 @@ void QCPLayer::setMode(QCPLayer::LayerMode mode) */ 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(); + 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 @@ -1165,20 +1168,21 @@ void QCPLayer::draw(QCPPainter *painter) */ void QCPLayer::drawToPaintBuffer() { - if (QSharedPointer pb = mPaintBuffer.toStrongRef()) - { - if (QCPPainter *painter = pb->startPainting()) - { - if (painter->isActive()) - draw(painter); - else - qDebug() << Q_FUNC_INFO << "paint buffer returned inactive painter"; - delete painter; - pb->donePainting(); - } else - qDebug() << Q_FUNC_INFO << "paint buffer returned nullptr painter"; - } else - qDebug() << Q_FUNC_INFO << "no valid paint buffer associated with this layer"; + if (QSharedPointer pb = mPaintBuffer.toStrongRef()) { + if (QCPPainter *painter = pb->startPainting()) { + if (painter->isActive()) { + draw(painter); + } else { + qDebug() << Q_FUNC_INFO << "paint buffer returned inactive painter"; + } + delete painter; + pb->donePainting(); + } else { + qDebug() << Q_FUNC_INFO << "paint buffer returned nullptr painter"; + } + } else { + qDebug() << Q_FUNC_INFO << "no valid paint buffer associated with this layer"; + } } /*! @@ -1197,61 +1201,64 @@ void QCPLayer::drawToPaintBuffer() */ void QCPLayer::replot() { - if (mMode == lmBuffered && !mParentPlot->hasInvalidatedPaintBuffers()) - { - if (QSharedPointer pb = mPaintBuffer.toStrongRef()) - { - pb->clear(Qt::transparent); - drawToPaintBuffer(); - pb->setInvalidated(false); // since layer is lmBuffered, we know only this layer is on buffer and we can reset invalidated flag - mParentPlot->update(); - } else - qDebug() << Q_FUNC_INFO << "no valid paint buffer associated with this layer"; - } else - mParentPlot->replot(); + if (mMode == lmBuffered && !mParentPlot->hasInvalidatedPaintBuffers()) { + if (QSharedPointer pb = mPaintBuffer.toStrongRef()) { + pb->clear(Qt::transparent); + drawToPaintBuffer(); + pb->setInvalidated(false); // since layer is lmBuffered, we know only this layer is on buffer and we can reset invalidated flag + mParentPlot->update(); + } else { + qDebug() << Q_FUNC_INFO << "no valid paint buffer associated with this layer"; + } + } else { + mParentPlot->replot(); + } } /*! \internal - + Adds the \a layerable to the list of this layer. If \a prepend is set to true, the layerable will be prepended to the list, i.e. be drawn beneath the other layerables already in the list. - + This function does not change the \a mLayer member of \a layerable to this layer. (Use QCPLayerable::setLayer to change the layer of an object, not this function.) - + \see removeChild */ void QCPLayer::addChild(QCPLayerable *layerable, bool prepend) { - if (!mChildren.contains(layerable)) - { - if (prepend) - mChildren.prepend(layerable); - else - mChildren.append(layerable); - if (QSharedPointer pb = mPaintBuffer.toStrongRef()) - pb->setInvalidated(); - } else - qDebug() << Q_FUNC_INFO << "layerable is already child of this layer" << reinterpret_cast(layerable); + if (!mChildren.contains(layerable)) { + if (prepend) { + mChildren.prepend(layerable); + } else { + mChildren.append(layerable); + } + if (QSharedPointer pb = mPaintBuffer.toStrongRef()) { + pb->setInvalidated(); + } + } else { + qDebug() << Q_FUNC_INFO << "layerable is already child of this layer" << reinterpret_cast(layerable); + } } /*! \internal - + Removes the \a layerable from the list of this layer. - + This function does not change the \a mLayer member of \a layerable. (Use QCPLayerable::setLayer to change the layer of an object, not this function.) - + \see addChild */ void QCPLayer::removeChild(QCPLayerable *layerable) { - if (mChildren.removeOne(layerable)) - { - if (QSharedPointer pb = mPaintBuffer.toStrongRef()) - pb->setInvalidated(); - } else - qDebug() << Q_FUNC_INFO << "layerable is not child of this layer" << reinterpret_cast(layerable); + if (mChildren.removeOne(layerable)) { + if (QSharedPointer pb = mPaintBuffer.toStrongRef()) { + pb->setInvalidated(); + } + } else { + qDebug() << Q_FUNC_INFO << "layerable is not child of this layer" << reinterpret_cast(layerable); + } } @@ -1261,28 +1268,28 @@ void QCPLayer::removeChild(QCPLayerable *layerable) /*! \class QCPLayerable \brief Base class for all drawable objects - + This is the abstract base class most visible objects derive from, e.g. plottables, axes, grid etc. Every layerable is on a layer (QCPLayer) which allows controlling the rendering order by stacking the layers accordingly. - + For details about the layering mechanism, see the QCPLayer documentation. */ /* start documentation of inline functions */ /*! \fn QCPLayerable *QCPLayerable::parentLayerable() const - + Returns the parent layerable of this layerable. The parent layerable is used to provide visibility hierarchies in conjunction with the method \ref realVisibility. This way, layerables only get drawn if their parent layerables are visible, too. - + 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 \c nullptr. - + A parent layerable is set implicitly when placed inside layout elements and doesn't need to be set manually by the user. */ @@ -1292,7 +1299,7 @@ void QCPLayer::removeChild(QCPLayerable *layerable) /*! \fn virtual void QCPLayerable::applyDefaultAntialiasingHint(QCPPainter *painter) const = 0 \internal - + This function applies the default antialiasing setting to the specified \a painter, using the function \ref applyAntialiasingHint. It is the antialiasing state the painter is put in, when \ref draw is called on the layerable. If the layerable has multiple entities whose antialiasing @@ -1300,7 +1307,7 @@ void QCPLayer::removeChild(QCPLayerable *layerable) most prominent entity. In this case however, the \ref draw function usually calls the specialized versions of this function before drawing each entity, effectively overriding the setting of the default antialiasing hint. - + First example: QCPGraph has multiple entities that have an antialiasing setting: The graph line, fills and scatters. Those can be configured via QCPGraph::setAntialiased, QCPGraph::setAntialiasedFill and QCPGraph::setAntialiasedScatters. Consequently, there isn't only @@ -1308,7 +1315,7 @@ void QCPLayer::removeChild(QCPLayerable *layerable) 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. - + Second example: QCPItemLine consists only of a line so there is only one antialiasing setting which can be controlled with QCPItemLine::setAntialiased. (This function is inherited by all layerables. The specialized functions, as seen on QCPGraph, must be added explicitly to the @@ -1321,10 +1328,10 @@ void QCPLayer::removeChild(QCPLayerable *layerable) /*! \fn virtual void QCPLayerable::draw(QCPPainter *painter) const = 0 \internal - + This function draws the layerable with the specified \a painter. It is only called by QCustomPlot, if the layerable is visible (\ref setVisible). - + Before this function is called, the painter's antialiasing state is set via \ref applyDefaultAntialiasingHint, see the documentation there. Further, the clipping rectangle was set to \ref clipRect. @@ -1334,10 +1341,10 @@ void QCPLayer::removeChild(QCPLayerable *layerable) /* start documentation of signals */ /*! \fn void QCPLayerable::layerChanged(QCPLayer *newLayer); - + This signal is emitted when the layer of this layerable changes, i.e. this layerable is moved to a different layer. - + \see setLayer */ @@ -1345,17 +1352,17 @@ void QCPLayer::removeChild(QCPLayerable *layerable) /*! Creates a new QCPLayerable instance. - + Since QCPLayerable is an abstract base class, it can't be instantiated directly. Use one of the derived classes. - + If \a plot is provided, it automatically places itself on the layer named \a targetLayer. If \a targetLayer is an empty string, it places itself on the current layer of the plot (see \ref QCustomPlot::setCurrentLayer). - + It is possible to provide \c nullptr 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 @@ -1364,29 +1371,28 @@ void QCPLayer::removeChild(QCPLayerable *layerable) QCPLayerable subclasses, to guarantee a working destruction hierarchy. */ QCPLayerable::QCPLayerable(QCustomPlot *plot, QString targetLayer, QCPLayerable *parentLayerable) : - QObject(plot), - mVisible(true), - mParentPlot(plot), - mParentLayerable(parentLayerable), - mLayer(nullptr), - mAntialiased(true) + QObject(plot), + mVisible(true), + mParentPlot(plot), + mParentLayerable(parentLayerable), + mLayer(nullptr), + mAntialiased(true) { - if (mParentPlot) - { - if (targetLayer.isEmpty()) - setLayer(mParentPlot->currentLayer()); - else if (!setLayer(targetLayer)) - qDebug() << Q_FUNC_INFO << "setting QCPlayerable initial layer to" << targetLayer << "failed."; - } + if (mParentPlot) { + if (targetLayer.isEmpty()) { + setLayer(mParentPlot->currentLayer()); + } else if (!setLayer(targetLayer)) { + qDebug() << Q_FUNC_INFO << "setting QCPlayerable initial layer to" << targetLayer << "failed."; + } + } } QCPLayerable::~QCPLayerable() { - if (mLayer) - { - mLayer->removeChild(this); - mLayer = nullptr; - } + if (mLayer) { + mLayer->removeChild(this); + mLayer = nullptr; + } } /*! @@ -1396,61 +1402,58 @@ QCPLayerable::~QCPLayerable() */ void QCPLayerable::setVisible(bool on) { - mVisible = on; + mVisible = on; } /*! Sets the \a layer of this layerable object. The object will be placed on top of the other objects already on \a 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) { - return moveToLayer(layer, false); + return moveToLayer(layer, false); } /*! \overload Sets the layer of this layerable object by name - + Returns true on success, i.e. if \a layerName is a valid layer name. */ bool QCPLayerable::setLayer(const QString &layerName) { - if (!mParentPlot) - { - qDebug() << Q_FUNC_INFO << "no parent QCustomPlot set"; - return false; - } - if (QCPLayer *layer = mParentPlot->layer(layerName)) - { - return setLayer(layer); - } else - { - qDebug() << Q_FUNC_INFO << "there is no layer with name" << layerName; - return false; - } + if (!mParentPlot) { + qDebug() << Q_FUNC_INFO << "no parent QCustomPlot set"; + return false; + } + if (QCPLayer *layer = mParentPlot->layer(layerName)) { + return setLayer(layer); + } else { + qDebug() << Q_FUNC_INFO << "there is no layer with name" << layerName; + return false; + } } /*! Sets whether this object will be drawn antialiased or not. - + Note that antialiasing settings may be overridden by QCustomPlot::setAntialiasedElements and QCustomPlot::setNotAntialiasedElements. */ void QCPLayerable::setAntialiased(bool enabled) { - mAntialiased = enabled; + mAntialiased = enabled; } /*! Returns whether this layerable is visible, taking the visibility of the layerable parent and the 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 \ref QCPLayoutElement), this function returns true only if this layerable has its visibility set to true and the parent layerable's \ref realVisibility returns @@ -1458,7 +1461,7 @@ void QCPLayerable::setAntialiased(bool enabled) */ bool QCPLayerable::realVisibility() const { - return mVisible && (!mLayer || mLayer->visible()) && (!mParentLayerable || mParentLayerable.data()->realVisibility()); + return mVisible && (!mLayer || mLayer->visible()) && (!mParentLayerable || mParentLayerable.data()->realVisibility()); } /*! @@ -1473,15 +1476,15 @@ bool QCPLayerable::realVisibility() const bars of a \ref QCPBars plottable, a click inside the area should also be considered a hit. In these cases this function thus returns a constant value greater zero but still below the parent plot's selection tolerance. (typically the selectionTolerance multiplied by 0.99). - + Providing a constant value for area objects allows selecting line objects even when they are obscured by such area objects, by clicking close to the lines (i.e. closer than 0.99*selectionTolerance). - + 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 \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 decides on the basis of this selectTest call, that the object was successfully selected. The @@ -1490,102 +1493,103 @@ bool QCPLayerable::realVisibility() const is only done once in \ref selectTest. The result (i.e. the actually clicked part) can then be placed in \a details. So in the subsequent \ref selectEvent, the decision which part was selected doesn't have to be done a second time for a single selection operation. - + In the case of 1D Plottables (\ref QCPAbstractPlottable1D, like \ref QCPGraph or \ref QCPBars) \a details will be set to a \ref QCPDataSelection, describing the closest data point to \a pos. - + You may pass \c nullptr as \a details to indicate that you are not interested in those selection details. - + \see selectEvent, deselectEvent, mousePressEvent, wheelEvent, QCustomPlot::setInteractions, QCPAbstractPlottable1D::selectTestRect */ double QCPLayerable::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { - Q_UNUSED(pos) - Q_UNUSED(onlySelectable) - Q_UNUSED(details) - return -1.0; + Q_UNUSED(pos) + Q_UNUSED(onlySelectable) + Q_UNUSED(details) + return -1.0; } /*! \internal - + Sets the parent plot of this layerable. Use this function once to set the parent plot if you have passed \c nullptr in the constructor. It can not be used to move a layerable from one QCustomPlot to another one. - + Note that, unlike when passing a non \c nullptr parent plot in the constructor, this function does not make \a parentPlot the QObject-parent of this layerable. If you want this, call QObject::setParent(\a parentPlot) in addition to this function. - + Further, you will probably want to set a layer (\ref setLayer) after calling this function, to make the layerable appear on the QCustomPlot. - + The parent plot change will be propagated to subclasses via a call to \ref parentPlotInitialized so they can react accordingly (e.g. also initialize the parent plot of child layerables, like QCPLayout does). */ void QCPLayerable::initializeParentPlot(QCustomPlot *parentPlot) { - if (mParentPlot) - { - qDebug() << Q_FUNC_INFO << "called with mParentPlot already initialized"; - return; - } - - if (!parentPlot) - qDebug() << Q_FUNC_INFO << "called with parentPlot zero"; - - mParentPlot = parentPlot; - parentPlotInitialized(mParentPlot); + if (mParentPlot) { + qDebug() << Q_FUNC_INFO << "called with mParentPlot already initialized"; + return; + } + + if (!parentPlot) { + qDebug() << Q_FUNC_INFO << "called with parentPlot zero"; + } + + mParentPlot = parentPlot; + parentPlotInitialized(mParentPlot); } /*! \internal - + Sets the parent layerable of this layerable to \a parentLayerable. Note that \a parentLayerable does not become the QObject-parent (for memory management) of this layerable. - + The parent layerable has influence on the return value of the \ref realVisibility method. Only layerables with a fully visible parent tree will return true for \ref realVisibility, and thus be drawn. - + \see realVisibility */ void QCPLayerable::setParentLayerable(QCPLayerable *parentLayerable) { - mParentLayerable = parentLayerable; + mParentLayerable = parentLayerable; } /*! \internal - + Moves this layerable object to \a layer. If \a prepend is true, this object will be prepended to the new layer's list, i.e. it will be drawn below the objects already on the layer. If it is false, the object will be appended. - + Returns true on success, i.e. if \a layer is a valid layer. */ bool QCPLayerable::moveToLayer(QCPLayer *layer, bool prepend) { - if (layer && !mParentPlot) - { - qDebug() << Q_FUNC_INFO << "no parent QCustomPlot set"; - return false; - } - if (layer && layer->parentPlot() != mParentPlot) - { - qDebug() << Q_FUNC_INFO << "layer" << layer->name() << "is not in same QCustomPlot as this layerable"; - return false; - } - - QCPLayer *oldLayer = mLayer; - if (mLayer) - mLayer->removeChild(this); - mLayer = layer; - if (mLayer) - mLayer->addChild(this, prepend); - if (mLayer != oldLayer) - emit layerChanged(mLayer); - return true; + if (layer && !mParentPlot) { + qDebug() << Q_FUNC_INFO << "no parent QCustomPlot set"; + return false; + } + if (layer && layer->parentPlot() != mParentPlot) { + qDebug() << Q_FUNC_INFO << "layer" << layer->name() << "is not in same QCustomPlot as this layerable"; + return false; + } + + QCPLayer *oldLayer = mLayer; + if (mLayer) { + mLayer->removeChild(this); + } + mLayer = layer; + if (mLayer) { + mLayer->addChild(this, prepend); + } + if (mLayer != oldLayer) { + emit layerChanged(mLayer); + } + return true; } /*! \internal @@ -1597,12 +1601,13 @@ bool QCPLayerable::moveToLayer(QCPLayer *layer, bool prepend) */ void QCPLayerable::applyAntialiasingHint(QCPPainter *painter, bool localAntialiased, QCP::AntialiasedElement overrideElement) const { - if (mParentPlot && mParentPlot->notAntialiasedElements().testFlag(overrideElement)) - painter->setAntialiasing(false); - else if (mParentPlot && mParentPlot->antialiasedElements().testFlag(overrideElement)) - painter->setAntialiasing(true); - else - painter->setAntialiasing(localAntialiased); + if (mParentPlot && mParentPlot->notAntialiasedElements().testFlag(overrideElement)) { + painter->setAntialiasing(false); + } else if (mParentPlot && mParentPlot->antialiasedElements().testFlag(overrideElement)) { + painter->setAntialiasing(true); + } else { + painter->setAntialiasing(localAntialiased); + } } /*! \internal @@ -1610,20 +1615,20 @@ void QCPLayerable::applyAntialiasingHint(QCPPainter *painter, bool localAntialia This function is called by \ref initializeParentPlot, to allow subclasses to react on the setting of a parent plot. This is the case when \c nullptr was passed as parent plot in the constructor, and the parent plot is set at a later time. - + For example, QCPLayoutElement/QCPLayout hierarchies may be created independently of any QCustomPlot at first. When they are then added to a layout inside the QCustomPlot, the top level element of the hierarchy gets its parent plot initialized with \ref initializeParentPlot. To propagate the parent plot to all the children of the hierarchy, the top level element then uses this function to pass the parent plot on to its child elements. - + The default implementation does nothing. - + \see initializeParentPlot */ void QCPLayerable::parentPlotInitialized(QCustomPlot *parentPlot) { - Q_UNUSED(parentPlot) + Q_UNUSED(parentPlot) } /*! \internal @@ -1631,45 +1636,45 @@ void QCPLayerable::parentPlotInitialized(QCustomPlot *parentPlot) Returns the selection category this layerable shall belong to. The selection category is used in conjunction with \ref QCustomPlot::setInteractions to control which objects are selectable and which aren't. - + Subclasses that don't fit any of the normal \ref QCP::Interaction values can use \ref QCP::iSelectOther. This is what the default implementation returns. - + \see QCustomPlot::setInteractions */ QCP::Interaction QCPLayerable::selectionCategory() const { - return QCP::iSelectOther; + return QCP::iSelectOther; } /*! \internal - + Returns the clipping rectangle of this layerable object. By default, this is the viewport of the parent QCustomPlot. Specific subclasses may reimplement this function to provide different clipping rects. - + The returned clipping rect is set on the painter before the draw function of the respective object is called. */ QRect QCPLayerable::clipRect() const { - if (mParentPlot) - return mParentPlot->viewport(); - else - return {}; + if (mParentPlot) { + return mParentPlot->viewport(); + } else + return {}; } /*! \internal - + This event is called when the layerable shall be selected, as a consequence of a click by the user. Subclasses should react to it by setting their selection state appropriately. The default implementation does nothing. - + \a event is the mouse event that caused the selection. \a additive indicates, whether the user was holding the multi-select-modifier while performing the selection (see \ref QCustomPlot::setMultiSelectModifier). if \a additive is true, the selection state must be toggled (i.e. become selected when unselected and unselected when selected). - + Every selectEvent is preceded by a call to \ref selectTest, which has returned positively (i.e. returned a value greater than 0 and less than the selection tolerance of the parent QCustomPlot). The \a details data you output from \ref selectTest is fed back via \a details here. You may @@ -1677,39 +1682,39 @@ QRect QCPLayerable::clipRect() const selectEvent. Usually \a details is used to transfer which part was clicked, if it is a layerable that has multiple individually selectable parts (like QCPAxis). This way selectEvent doesn't need to do the calculation again to find out which part was actually clicked. - + \a selectionStateChanged is an output parameter. If the pointer is non-null, this function must set the value either to true or false, depending on whether the selection state of this layerable was actually changed. For layerables that only are selectable as a whole and not in parts, this is simple: if \a additive is true, \a selectionStateChanged must also be set to true, because the selection toggles. If \a additive is false, \a selectionStateChanged is only set to true, if the layerable was previously unselected and now is switched to the selected state. - + \see selectTest, deselectEvent */ void QCPLayerable::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) { - Q_UNUSED(event) - Q_UNUSED(additive) - Q_UNUSED(details) - Q_UNUSED(selectionStateChanged) + Q_UNUSED(event) + Q_UNUSED(additive) + Q_UNUSED(details) + Q_UNUSED(selectionStateChanged) } /*! \internal - + This event is called when the layerable shall be deselected, either as consequence of a user interaction or a call to \ref QCustomPlot::deselectAll. Subclasses should react to it by unsetting their selection appropriately. - + just as in \ref selectEvent, the output parameter \a selectionStateChanged (if non-null), must return true or false when the selection state of this layerable has changed or not changed, respectively. - + \see selectTest, selectEvent */ void QCPLayerable::deselectEvent(bool *selectionStateChanged) { - Q_UNUSED(selectionStateChanged) + Q_UNUSED(selectionStateChanged) } /*! @@ -1739,8 +1744,8 @@ void QCPLayerable::deselectEvent(bool *selectionStateChanged) */ void QCPLayerable::mousePressEvent(QMouseEvent *event, const QVariant &details) { - Q_UNUSED(details) - event->ignore(); + Q_UNUSED(details) + event->ignore(); } /*! @@ -1757,8 +1762,8 @@ void QCPLayerable::mousePressEvent(QMouseEvent *event, const QVariant &details) */ void QCPLayerable::mouseMoveEvent(QMouseEvent *event, const QPointF &startPos) { - Q_UNUSED(startPos) - event->ignore(); + Q_UNUSED(startPos) + event->ignore(); } /*! @@ -1775,8 +1780,8 @@ void QCPLayerable::mouseMoveEvent(QMouseEvent *event, const QPointF &startPos) */ void QCPLayerable::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos) { - Q_UNUSED(startPos) - event->ignore(); + Q_UNUSED(startPos) + event->ignore(); } /*! @@ -1807,8 +1812,8 @@ void QCPLayerable::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos */ void QCPLayerable::mouseDoubleClickEvent(QMouseEvent *event, const QVariant &details) { - Q_UNUSED(details) - event->ignore(); + Q_UNUSED(details) + event->ignore(); } /*! @@ -1830,7 +1835,7 @@ void QCPLayerable::mouseDoubleClickEvent(QMouseEvent *event, const QVariant &det */ void QCPLayerable::wheelEvent(QWheelEvent *event) { - event->ignore(); + event->ignore(); } /* end of 'src/layer.cpp' */ @@ -1843,10 +1848,10 @@ void QCPLayerable::wheelEvent(QWheelEvent *event) //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPRange \brief Represents the range an axis is encompassing. - + contains a \a lower and \a upper double value and provides convenience input, output and modification functions. - + \see QCPAxis::setRange */ @@ -1925,8 +1930,8 @@ const double QCPRange::maxRange = 1e250; Constructs a range with \a lower and \a upper set to zero. */ QCPRange::QCPRange() : - lower(0), - upper(0) + lower(0), + upper(0) { } @@ -1938,10 +1943,10 @@ QCPRange::QCPRange() : smaller than \a upper, they will be swapped. */ QCPRange::QCPRange(double lower, double upper) : - lower(lower), - upper(upper) + lower(lower), + upper(upper) { - normalize(); + normalize(); } /*! \overload @@ -1958,10 +1963,12 @@ QCPRange::QCPRange(double lower, double upper) : */ void QCPRange::expand(const QCPRange &otherRange) { - if (lower > otherRange.lower || qIsNaN(lower)) - lower = otherRange.lower; - if (upper < otherRange.upper || qIsNaN(upper)) - upper = otherRange.upper; + if (lower > otherRange.lower || qIsNaN(lower)) { + lower = otherRange.lower; + } + if (upper < otherRange.upper || qIsNaN(upper)) { + upper = otherRange.upper; + } } /*! \overload @@ -1978,10 +1985,12 @@ void QCPRange::expand(const QCPRange &otherRange) */ void QCPRange::expand(double includeCoord) { - if (lower > includeCoord || qIsNaN(lower)) - lower = includeCoord; - if (upper < includeCoord || qIsNaN(upper)) - upper = includeCoord; + if (lower > includeCoord || qIsNaN(lower)) { + lower = includeCoord; + } + if (upper < includeCoord || qIsNaN(upper)) { + upper = includeCoord; + } } @@ -1997,9 +2006,9 @@ void QCPRange::expand(double includeCoord) */ QCPRange QCPRange::expanded(const QCPRange &otherRange) const { - QCPRange result = *this; - result.expand(otherRange); - return result; + QCPRange result = *this; + result.expand(otherRange); + return result; } /*! \overload @@ -2014,47 +2023,48 @@ QCPRange QCPRange::expanded(const QCPRange &otherRange) const */ QCPRange QCPRange::expanded(double includeCoord) const { - QCPRange result = *this; - result.expand(includeCoord); - return result; + 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; + 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 \a lower will always be numerically smaller (or equal) to \a upper. - + If the original range does span positive and negative sign domains or contains zero, the returned range will try to approximate the original range as good as possible. If the positive interval of the original range is wider than the negative interval, the @@ -2064,47 +2074,46 @@ QCPRange QCPRange::bounded(double lowerBound, double upperBound) const */ QCPRange QCPRange::sanitizedForLogScale() const { - double rangeFac = 1e-3; - QCPRange sanitizedRange(lower, upper); - sanitizedRange.normalize(); - // can't have range spanning negative and positive values in log plot, so change range to fix it - //if (qFuzzyCompare(sanitizedRange.lower+1, 1) && !qFuzzyCompare(sanitizedRange.upper+1, 1)) - if (sanitizedRange.lower == 0.0 && sanitizedRange.upper != 0.0) - { - // case lower is 0 - if (rangeFac < sanitizedRange.upper*rangeFac) - sanitizedRange.lower = rangeFac; - else - sanitizedRange.lower = sanitizedRange.upper*rangeFac; - } //else if (!qFuzzyCompare(lower+1, 1) && qFuzzyCompare(upper+1, 1)) - else if (sanitizedRange.lower != 0.0 && sanitizedRange.upper == 0.0) - { - // case upper is 0 - if (-rangeFac > sanitizedRange.lower*rangeFac) - sanitizedRange.upper = -rangeFac; - else - sanitizedRange.upper = sanitizedRange.lower*rangeFac; - } else if (sanitizedRange.lower < 0 && sanitizedRange.upper > 0) - { - // find out whether negative or positive interval is wider to decide which sign domain will be chosen - if (-sanitizedRange.lower > sanitizedRange.upper) - { - // negative is wider, do same as in case upper is 0 - if (-rangeFac > sanitizedRange.lower*rangeFac) - sanitizedRange.upper = -rangeFac; - else - sanitizedRange.upper = sanitizedRange.lower*rangeFac; - } else - { - // positive is wider, do same as in case lower is 0 - if (rangeFac < sanitizedRange.upper*rangeFac) - sanitizedRange.lower = rangeFac; - else - sanitizedRange.lower = sanitizedRange.upper*rangeFac; + double rangeFac = 1e-3; + QCPRange sanitizedRange(lower, upper); + sanitizedRange.normalize(); + // can't have range spanning negative and positive values in log plot, so change range to fix it + //if (qFuzzyCompare(sanitizedRange.lower+1, 1) && !qFuzzyCompare(sanitizedRange.upper+1, 1)) + if (sanitizedRange.lower == 0.0 && sanitizedRange.upper != 0.0) { + // case lower is 0 + if (rangeFac < sanitizedRange.upper * rangeFac) { + sanitizedRange.lower = rangeFac; + } else { + sanitizedRange.lower = sanitizedRange.upper * rangeFac; + } + } //else if (!qFuzzyCompare(lower+1, 1) && qFuzzyCompare(upper+1, 1)) + else if (sanitizedRange.lower != 0.0 && sanitizedRange.upper == 0.0) { + // case upper is 0 + if (-rangeFac > sanitizedRange.lower * rangeFac) { + sanitizedRange.upper = -rangeFac; + } else { + sanitizedRange.upper = sanitizedRange.lower * rangeFac; + } + } else if (sanitizedRange.lower < 0 && sanitizedRange.upper > 0) { + // find out whether negative or positive interval is wider to decide which sign domain will be chosen + if (-sanitizedRange.lower > sanitizedRange.upper) { + // negative is wider, do same as in case upper is 0 + if (-rangeFac > sanitizedRange.lower * rangeFac) { + sanitizedRange.upper = -rangeFac; + } else { + sanitizedRange.upper = sanitizedRange.lower * rangeFac; + } + } else { + // positive is wider, do same as in case lower is 0 + if (rangeFac < sanitizedRange.upper * rangeFac) { + sanitizedRange.lower = rangeFac; + } else { + sanitizedRange.lower = sanitizedRange.upper * rangeFac; + } + } } - } - // due to normalization, case lower>0 && upper<0 should never occur, because that implies upper0 && upper<0 should never occur, because that implies upper -maxRange && - upper < maxRange && - qAbs(lower-upper) > minRange && - qAbs(lower-upper) < maxRange && - !(lower > 0 && qIsInf(upper/lower)) && - !(upper < 0 && qIsInf(lower/upper))); + return (lower > -maxRange && + upper < maxRange && + qAbs(lower - upper) > minRange && + qAbs(lower - upper) < maxRange && + !(lower > 0 && qIsInf(upper / lower)) && + !(upper < 0 && qIsInf(lower / upper))); } /*! @@ -2147,12 +2156,12 @@ 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 > 0 && qIsInf(range.upper/range.lower)) && - !(range.upper < 0 && qIsInf(range.lower/range.upper))); + 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' */ @@ -2166,7 +2175,7 @@ bool QCPRange::validRange(const QCPRange &range) /*! \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 \a end index corresponds to the data point just after the last data point of the data range, like in standard iterators. @@ -2175,16 +2184,16 @@ bool QCPRange::validRange(const QCPRange &range) 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. */ @@ -2192,43 +2201,43 @@ bool QCPRange::validRange(const QCPRange &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 after 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 @@ -2237,14 +2246,14 @@ bool QCPRange::validRange(const QCPRange &range) */ /*! \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. */ @@ -2255,26 +2264,26 @@ bool QCPRange::validRange(const QCPRange &range) Creates an empty QCPDataRange, with begin and end set to 0. */ QCPDataRange::QCPDataRange() : - mBegin(0), - mEnd(0) + 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) + 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 @@ -2282,15 +2291,15 @@ QCPDataRange::QCPDataRange(int begin, int end) : */ 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; + 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; } /*! @@ -2298,47 +2307,47 @@ QCPDataRange QCPDataRange::bounded(const QCPDataRange &other) const */ QCPDataRange QCPDataRange::expanded(const QCPDataRange &other) const { - return {qMin(mBegin, other.mBegin), qMax(mEnd, other.mEnd)}; + return {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 result(qMax(mBegin, other.mBegin), qMin(mEnd, other.mEnd)); + if (result.isValid()) { + return result; + } else + return {}; } /*! 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) ); + return !((mBegin > other.mBegin && mBegin >= other.mEnd) || + (mEnd <= other.mBegin && mEnd < other.mEnd)); } /*! Returns whether all data points of \a other are also contained inside this data range. - + \see intersects */ bool QCPDataRange::contains(const QCPDataRange &other) const { - return mBegin <= other.mBegin && mEnd >= other.mEnd; + return mBegin <= other.mBegin && mEnd >= other.mEnd; } @@ -2349,14 +2358,14 @@ bool QCPDataRange::contains(const QCPDataRange &other) const /*! \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 @@ -2364,46 +2373,46 @@ bool QCPDataRange::contains(const QCPDataRange &other) const 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 */ @@ -2421,7 +2430,7 @@ QCPDataSelection::QCPDataSelection() */ QCPDataSelection::QCPDataSelection(const QCPDataRange &range) { - mDataRanges.append(range); + mDataRanges.append(range); } /*! @@ -2433,14 +2442,15 @@ QCPDataSelection::QCPDataSelection(const QCPDataRange &range) */ 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 - } - } + if (other.isEmpty() || isEmpty()) { + return *this; } - ++i; - } - - return *this; + + simplify(); + int i = 0; + while (i < mDataRanges.size()) { + const int thisBegin = mDataRanges.at(i).begin(); + const int thisEnd = mDataRanges.at(i).end(); + if (thisBegin >= other.end()) { + break; // since data ranges are sorted after the simplify() call, no ranges which contain other will come after this + } + + if (thisEnd > other.begin()) { // ranges which don't fulfill this are entirely before other and can be ignored + if (thisBegin >= other.begin()) { // range leading segment is encompassed + if (thisEnd <= other.end()) { // range fully encompassed, remove completely + mDataRanges.removeAt(i); + continue; + } else { // only leading segment is encompassed, trim accordingly + mDataRanges[i].setBegin(other.end()); + } + } else { // leading segment is not encompassed + if (thisEnd <= other.end()) { // only trailing segment is encompassed, trim accordingly + mDataRanges[i].setEnd(other.begin()); + } else { // other lies inside this range, so split range + mDataRanges[i].setEnd(other.begin()); + mDataRanges.insert(i + 1, QCPDataRange(other.end(), thisEnd)); + break; // since data ranges are sorted (and don't overlap) after simplify() call, we're done here + } + } + } + ++i; + } + + return *this; } /*! @@ -2527,30 +2534,29 @@ QCPDataSelection &QCPDataSelection::operator-=(const QCPDataRange &other) */ int QCPDataSelection::dataPointCount() const { - int result = 0; - foreach (QCPDataRange dataRange, mDataRanges) - result += dataRange.length(); - return result; + int result = 0; + foreach (QCPDataRange dataRange, mDataRanges) { + result += dataRange.length(); + } + return result; } /*! Returns the data range with the specified \a index. - + If the data selection is simplified (the usual state of the selection, see \ref simplify), the ranges are sorted by ascending data point index. - + \see dataRangeCount */ QCPDataRange QCPDataSelection::dataRange(int index) const { - if (index >= 0 && index < mDataRanges.size()) - { - return mDataRanges.at(index); - } else - { - qDebug() << Q_FUNC_INFO << "index out of range:" << index; - return {}; - } + if (index >= 0 && index < mDataRanges.size()) { + return mDataRanges.at(index); + } else { + qDebug() << Q_FUNC_INFO << "index out of range:" << index; + return {}; + } } /*! @@ -2559,10 +2565,10 @@ QCPDataRange QCPDataSelection::dataRange(int index) const */ QCPDataRange QCPDataSelection::span() const { - if (isEmpty()) - return {}; - else - return {mDataRanges.first().begin(), mDataRanges.last().end()}; + if (isEmpty()) + return {}; + else + return {mDataRanges.first().begin(), mDataRanges.last().end()}; } /*! @@ -2573,19 +2579,20 @@ QCPDataRange QCPDataSelection::span() const */ void QCPDataSelection::addDataRange(const QCPDataRange &dataRange, bool simplify) { - mDataRanges.append(dataRange); - if (simplify) - this->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(); + mDataRanges.clear(); } /*! @@ -2599,102 +2606,100 @@ void QCPDataSelection::clear() */ 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; - } + // 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; + 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: { + if (!isEmpty()) { + mDataRanges = QList() << span(); + } + break; + } + case QCP::stMultipleDataRanges: { + // this is the selection type that allows all concievable combinations of ranges, so do nothing + 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: - { - if (!isEmpty()) - 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 + 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 } /*! @@ -2707,11 +2712,12 @@ bool QCPDataSelection::contains(const QCPDataSelection &other) const */ QCPDataSelection QCPDataSelection::intersection(const QCPDataRange &other) const { - QCPDataSelection result; - foreach (QCPDataRange dataRange, mDataRanges) - result.addDataRange(dataRange.intersection(other), false); - result.simplify(); - return result; + QCPDataSelection result; + foreach (QCPDataRange dataRange, mDataRanges) { + result.addDataRange(dataRange.intersection(other), false); + } + result.simplify(); + return result; } /*! @@ -2720,11 +2726,12 @@ QCPDataSelection QCPDataSelection::intersection(const QCPDataRange &other) const */ QCPDataSelection QCPDataSelection::intersection(const QCPDataSelection &other) const { - QCPDataSelection result; - for (int i=0; iorientation() == Qt::Horizontal) - return {axis->pixelToCoord(mRect.left()), axis->pixelToCoord(mRect.left()+mRect.width())}; - else - return {axis->pixelToCoord(mRect.top()+mRect.height()), axis->pixelToCoord(mRect.top())}; - } else - { - qDebug() << Q_FUNC_INFO << "called with axis zero"; - return {}; - } + if (axis) { + if (axis->orientation() == Qt::Horizontal) + return {axis->pixelToCoord(mRect.left()), axis->pixelToCoord(mRect.left() + mRect.width())}; + else + return {axis->pixelToCoord(mRect.top() + mRect.height()), axis->pixelToCoord(mRect.top())}; + } else { + qDebug() << Q_FUNC_INFO << "called with axis zero"; + return {}; + } } /*! Sets the pen that will be used to draw the selection rect outline. - + \see setBrush */ void QCPSelectionRect::setPen(const QPen &pen) { - mPen = 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; + mBrush = brush; } /*! @@ -2902,87 +2911,84 @@ void QCPSelectionRect::setBrush(const QBrush &brush) */ void QCPSelectionRect::cancel() { - if (mActive) - { - mActive = false; - emit canceled(mRect, nullptr); - } + if (mActive) { + mActive = false; + emit canceled(mRect, nullptr); + } } /*! \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); + 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(); + 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); + 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); - } + 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); + 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); - } + if (mActive) { + painter->setPen(mPen); + painter->setBrush(mBrush); + painter->drawRect(mRect); + } } /* end of 'src/selectionrect.cpp' */ @@ -2996,27 +3002,27 @@ void QCPSelectionRect::draw(QCPPainter *painter) /*! \class QCPMarginGroup \brief A margin group allows synchronization of margin sides if working with multiple layout elements. - + QCPMarginGroup allows you to tie a margin side of two or more layout elements together, such that they will all have the same size, based on the largest required margin in the group. - + \n \image html QCPMarginGroup.png "Demonstration of QCPMarginGroup" \n - + In certain situations it is desirable that margins at specific sides are synchronized across layout elements. For example, if one QCPAxisRect is below another one in a grid layout, it will provide a cleaner look to the user if the left and right margins of the two axis rects are of the same size. The left axis of the top axis rect will then be at the same horizontal position as the left axis of the lower axis rect, making them appear aligned. The same applies for the right axes. This is what QCPMarginGroup makes possible. - + To add/remove a specific side of a layout element to/from a margin group, use the \ref QCPLayoutElement::setMarginGroup method. To completely break apart the margin group, either call \ref clear, or just delete the margin group. - + \section QCPMarginGroup-example Example - + First create a margin group: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpmargingroup-creation-1 Then set this group on the layout element sides: @@ -3028,7 +3034,7 @@ void QCPSelectionRect::draw(QCPPainter *painter) /* start documentation of inline functions */ /*! \fn QList QCPMarginGroup::elements(QCP::MarginSide side) const - + Returns a list of all layout elements that have their margin \a side associated with this margin group. */ @@ -3039,18 +3045,18 @@ void QCPSelectionRect::draw(QCPPainter *painter) Creates a new QCPMarginGroup instance in \a parentPlot. */ QCPMarginGroup::QCPMarginGroup(QCustomPlot *parentPlot) : - QObject(parentPlot), - mParentPlot(parentPlot) + QObject(parentPlot), + mParentPlot(parentPlot) { - mChildren.insert(QCP::msLeft, QList()); - mChildren.insert(QCP::msRight, QList()); - mChildren.insert(QCP::msTop, QList()); - mChildren.insert(QCP::msBottom, QList()); + mChildren.insert(QCP::msLeft, QList()); + mChildren.insert(QCP::msRight, QList()); + mChildren.insert(QCP::msTop, QList()); + mChildren.insert(QCP::msBottom, QList()); } QCPMarginGroup::~QCPMarginGroup() { - clear(); + clear(); } /*! @@ -3059,14 +3065,14 @@ QCPMarginGroup::~QCPMarginGroup() */ bool QCPMarginGroup::isEmpty() const { - QHashIterator > it(mChildren); - while (it.hasNext()) - { - it.next(); - if (!it.value().isEmpty()) - return false; - } - return true; + QHashIterator > it(mChildren); + while (it.hasNext()) { + it.next(); + if (!it.value().isEmpty()) { + return false; + } + } + return true; } /*! @@ -3075,22 +3081,22 @@ bool QCPMarginGroup::isEmpty() const */ void QCPMarginGroup::clear() { - // make all children remove themselves from this margin group: - QHashIterator > it(mChildren); - while (it.hasNext()) - { - it.next(); - const QList elements = it.value(); - for (int i=elements.size()-1; i>=0; --i) - elements.at(i)->setMarginGroup(it.key(), nullptr); // removes itself from mChildren via removeChild - } + // make all children remove themselves from this margin group: + QHashIterator > it(mChildren); + while (it.hasNext()) { + it.next(); + const QList elements = it.value(); + for (int i = elements.size() - 1; i >= 0; --i) { + elements.at(i)->setMarginGroup(it.key(), nullptr); // removes itself from mChildren via removeChild + } + } } /*! \internal - + Returns the synchronized common margin for \a side. This is the margin value that will be used by the layout element on the respective side, if it is part of this margin group. - + The common margin is calculated by requesting the automatic margin (\ref QCPLayoutElement::calculateAutoMargin) of each element associated with \a side in this margin group, and choosing the largest returned value. (QCPLayoutElement::minimumMargins is taken into @@ -3098,43 +3104,46 @@ void QCPMarginGroup::clear() */ int QCPMarginGroup::commonMargin(QCP::MarginSide side) const { - // query all automatic margins of the layout elements in this margin group side and find maximum: - int result = 0; - foreach (QCPLayoutElement *el, mChildren.value(side)) - { - if (!el->autoMargins().testFlag(side)) - continue; - int m = qMax(el->calculateAutoMargin(side), QCP::getMarginValue(el->minimumMargins(), side)); - if (m > result) - result = m; - } - return result; + // query all automatic margins of the layout elements in this margin group side and find maximum: + int result = 0; + foreach (QCPLayoutElement *el, mChildren.value(side)) { + if (!el->autoMargins().testFlag(side)) { + continue; + } + int m = qMax(el->calculateAutoMargin(side), QCP::getMarginValue(el->minimumMargins(), side)); + if (m > result) { + result = m; + } + } + return result; } /*! \internal - + Adds \a element to the internal list of child elements, for the margin \a side. - + This function does not modify the margin group property of \a element. */ void QCPMarginGroup::addChild(QCP::MarginSide side, QCPLayoutElement *element) { - if (!mChildren[side].contains(element)) - mChildren[side].append(element); - else - qDebug() << Q_FUNC_INFO << "element is already child of this margin group side" << reinterpret_cast(element); + if (!mChildren[side].contains(element)) { + mChildren[side].append(element); + } else { + qDebug() << Q_FUNC_INFO << "element is already child of this margin group side" << reinterpret_cast(element); + } } /*! \internal - + Removes \a element from the internal list of child elements, for the margin \a side. - + This function does not modify the margin group property of \a element. */ void QCPMarginGroup::removeChild(QCP::MarginSide side, QCPLayoutElement *element) { - if (!mChildren[side].removeOne(element)) - qDebug() << Q_FUNC_INFO << "element is not child of this margin group side" << reinterpret_cast(element); + if (!mChildren[side].removeOne(element)) { + qDebug() << Q_FUNC_INFO << "element is not child of this margin group side" << reinterpret_cast(element); + } } @@ -3144,20 +3153,20 @@ void QCPMarginGroup::removeChild(QCP::MarginSide side, QCPLayoutElement *element /*! \class QCPLayoutElement \brief The abstract base class for all objects that form \ref thelayoutsystem "the layout system". - + This is an abstract base class. As such, it can't be instantiated directly, rather use one of its subclasses. - + A Layout element is a rectangular object which can be placed in layouts. It has an outer rect (QCPLayoutElement::outerRect) and an inner rect (\ref QCPLayoutElement::rect). The difference between outer and inner rect is called its margin. The margin can either be set to automatic or manual (\ref setAutoMargins) on a per-side basis. If a side is set to manual, that margin can be set explicitly with \ref setMargins and will stay fixed at that value. If it's set to automatic, the layout element subclass will control the value itself (via \ref calculateAutoMargin). - + Layout elements can be placed in layouts (base class QCPLayout) like QCPLayoutGrid. The top level layout is reachable via \ref QCustomPlot::plotLayout, and is a \ref QCPLayoutGrid. Since \ref QCPLayout itself derives from \ref QCPLayoutElement, layouts can be nested. - + Thus in QCustomPlot one can divide layout elements into two categories: The ones that are 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 @@ -3171,31 +3180,31 @@ void QCPMarginGroup::removeChild(QCP::MarginSide side, QCPLayoutElement *element /* start documentation of inline functions */ /*! \fn QCPLayout *QCPLayoutElement::layout() const - + Returns the parent layout of this layout element. */ /*! \fn QRect QCPLayoutElement::rect() const - + Returns the inner rect of this layout element. The inner rect is the outer rect (\ref outerRect, \ref setOuterRect) shrinked by the margins (\ref setMargins, \ref setAutoMargins). - + In some cases, the area between outer and inner rect is left blank. In other cases the margin area is used to display peripheral graphics while the main content is in the inner rect. This is where automatic margin calculation becomes interesting because it allows the layout element to adapt the margins to the peripheral graphics it wants to draw. For example, \ref QCPAxisRect draws the axis labels and tick labels in the margin area, thus needs to adjust the margins (if \ref setAutoMargins is enabled) according to the space required by the labels of the axes. - + \see outerRect */ /*! \fn QRect QCPLayoutElement::outerRect() const - + Returns the outer rect of this layout element. The outer rect is the inner rect expanded by the margins (\ref setMargins, \ref setAutoMargins). The outer rect is used (and set via \ref setOuterRect) by the parent \ref QCPLayout to control the size of this layout element. - + \see rect */ @@ -3205,220 +3214,223 @@ void QCPMarginGroup::removeChild(QCP::MarginSide side, QCPLayoutElement *element Creates an instance of QCPLayoutElement and sets default values. */ QCPLayoutElement::QCPLayoutElement(QCustomPlot *parentPlot) : - QCPLayerable(parentPlot), // parenthood is changed as soon as layout element gets inserted into a layout (except for top level layout) - mParentLayout(nullptr), - mMinimumSize(), - mMaximumSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX), - mSizeConstraintRect(scrInnerRect), - mRect(0, 0, 0, 0), - mOuterRect(0, 0, 0, 0), - mMargins(0, 0, 0, 0), - mMinimumMargins(0, 0, 0, 0), - mAutoMargins(QCP::msAll) + QCPLayerable(parentPlot), // parenthood is changed as soon as layout element gets inserted into a layout (except for top level layout) + mParentLayout(nullptr), + mMinimumSize(), + mMaximumSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX), + mSizeConstraintRect(scrInnerRect), + mRect(0, 0, 0, 0), + mOuterRect(0, 0, 0, 0), + mMargins(0, 0, 0, 0), + mMinimumMargins(0, 0, 0, 0), + mAutoMargins(QCP::msAll) { } QCPLayoutElement::~QCPLayoutElement() { - setMarginGroup(QCP::msAll, nullptr); // unregister at margin groups, if there are any - // unregister at layout: - if (qobject_cast(mParentLayout)) // the qobject_cast is just a safeguard in case the layout forgets to call clear() in its dtor and this dtor is called by QObject dtor - mParentLayout->take(this); + setMarginGroup(QCP::msAll, nullptr); // unregister at margin groups, if there are any + // unregister at layout: + if (qobject_cast(mParentLayout)) { // the qobject_cast is just a safeguard in case the layout forgets to call clear() in its dtor and this dtor is called by QObject dtor + mParentLayout->take(this); + } } /*! Sets the outer rect of this layout element. If the layout element is inside a layout, the layout sets the position and size of this layout element using this function. - + Calling this function externally has no effect, since the layout will overwrite any changes to the outer rect upon the next replot. - + The layout element will adapt its inner \ref rect by applying the margins inward to the outer rect. - + \see rect */ void QCPLayoutElement::setOuterRect(const QRect &rect) { - if (mOuterRect != rect) - { - mOuterRect = rect; - mRect = mOuterRect.adjusted(mMargins.left(), mMargins.top(), -mMargins.right(), -mMargins.bottom()); - } + if (mOuterRect != rect) { + mOuterRect = rect; + mRect = mOuterRect.adjusted(mMargins.left(), mMargins.top(), -mMargins.right(), -mMargins.bottom()); + } } /*! Sets the margins of this layout element. If \ref setAutoMargins is disabled for some or all sides, this function is used to manually set the margin on those sides. Sides that are still set to be handled automatically are ignored and may have any value in \a margins. - + The margin is the distance between the outer rect (controlled by the parent layout via \ref setOuterRect) and the inner \ref rect (which usually contains the main content of this layout element). - + \see setAutoMargins */ void QCPLayoutElement::setMargins(const QMargins &margins) { - if (mMargins != margins) - { - mMargins = margins; - mRect = mOuterRect.adjusted(mMargins.left(), mMargins.top(), -mMargins.right(), -mMargins.bottom()); - } + if (mMargins != margins) { + mMargins = margins; + mRect = mOuterRect.adjusted(mMargins.left(), mMargins.top(), -mMargins.right(), -mMargins.bottom()); + } } /*! If \ref setAutoMargins is enabled on some or all margins, this function is used to provide minimum values for those margins. - + The minimum values are not enforced on margin sides that were set to be under manual control via \ref setAutoMargins. - + \see setAutoMargins */ void QCPLayoutElement::setMinimumMargins(const QMargins &margins) { - if (mMinimumMargins != margins) - { - mMinimumMargins = margins; - } + if (mMinimumMargins != margins) { + mMinimumMargins = margins; + } } /*! Sets on which sides the margin shall be calculated automatically. If a side is calculated automatically, a minimum margin value may be provided with \ref setMinimumMargins. If a side is set to be controlled manually, the value may be specified with \ref setMargins. - + 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, QCP::MarginSide */ void QCPLayoutElement::setAutoMargins(QCP::MarginSides sides) { - mAutoMargins = sides; + mAutoMargins = sides; } /*! Sets the minimum size of this layout element. A parent layout tries to respect the \a size here by changing row/column sizes in the layout accordingly. - + If the parent layout size is not sufficient to satisfy all minimum size constraints of its child layout elements, the layout may set a size that is actually smaller than \a size. QCustomPlot propagates the layout's size constraints to the outside by setting its own minimum QWidget size accordingly, so violations of \a size should be exceptions. - + Whether this constraint applies to the inner or the outer rect can be specified with \ref setSizeConstraintRect (see \ref rect and \ref outerRect). */ void QCPLayoutElement::setMinimumSize(const QSize &size) { - if (mMinimumSize != size) - { - mMinimumSize = size; - if (mParentLayout) - mParentLayout->sizeConstraintsChanged(); - } + if (mMinimumSize != size) { + mMinimumSize = size; + if (mParentLayout) { + mParentLayout->sizeConstraintsChanged(); + } + } } /*! \overload - + Sets the minimum size of this layout element. - + Whether this constraint applies to the inner or the outer rect can be specified with \ref setSizeConstraintRect (see \ref rect and \ref outerRect). */ void QCPLayoutElement::setMinimumSize(int width, int height) { - setMinimumSize(QSize(width, height)); + setMinimumSize(QSize(width, height)); } /*! Sets the maximum size of this layout element. A parent layout tries to respect the \a size here by changing row/column sizes in the layout accordingly. - + Whether this constraint applies to the inner or the outer rect can be specified with \ref setSizeConstraintRect (see \ref rect and \ref outerRect). */ void QCPLayoutElement::setMaximumSize(const QSize &size) { - if (mMaximumSize != size) - { - mMaximumSize = size; - if (mParentLayout) - mParentLayout->sizeConstraintsChanged(); - } + if (mMaximumSize != size) { + mMaximumSize = size; + if (mParentLayout) { + mParentLayout->sizeConstraintsChanged(); + } + } } /*! \overload - + Sets the maximum size of this layout element. - + Whether this constraint applies to the inner or the outer rect can be specified with \ref setSizeConstraintRect (see \ref rect and \ref outerRect). */ void QCPLayoutElement::setMaximumSize(int width, int height) { - setMaximumSize(QSize(width, height)); + setMaximumSize(QSize(width, height)); } /*! Sets to which rect of a layout element the size constraints apply. Size constraints can be set via \ref setMinimumSize and \ref setMaximumSize. - + The outer rect (\ref outerRect) includes the margins (e.g. in the case of a QCPAxisRect the axis labels), whereas the inner rect (\ref rect) does not. - + \see setMinimumSize, setMaximumSize */ void QCPLayoutElement::setSizeConstraintRect(SizeConstraintRect constraintRect) { - if (mSizeConstraintRect != constraintRect) - { - mSizeConstraintRect = constraintRect; - if (mParentLayout) - mParentLayout->sizeConstraintsChanged(); - } + if (mSizeConstraintRect != constraintRect) { + mSizeConstraintRect = constraintRect; + if (mParentLayout) { + mParentLayout->sizeConstraintsChanged(); + } + } } /*! Sets the margin \a group of the specified margin \a sides. - + Margin groups allow synchronizing specified margins across layout elements, see the documentation of \ref QCPMarginGroup. - + To unset the margin group of \a sides, set \a group to \c nullptr. - + 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) { - QVector sideVector; - if (sides.testFlag(QCP::msLeft)) sideVector.append(QCP::msLeft); - if (sides.testFlag(QCP::msRight)) sideVector.append(QCP::msRight); - if (sides.testFlag(QCP::msTop)) sideVector.append(QCP::msTop); - if (sides.testFlag(QCP::msBottom)) sideVector.append(QCP::msBottom); - - foreach (QCP::MarginSide side, sideVector) - { - if (marginGroup(side) != group) - { - QCPMarginGroup *oldGroup = marginGroup(side); - if (oldGroup) // unregister at old group - oldGroup->removeChild(side, this); - - if (!group) // if setting to 0, remove hash entry. Else set hash entry to new group and register there - { - mMarginGroups.remove(side); - } else // setting to a new group - { - mMarginGroups[side] = group; - group->addChild(side, this); - } + QVector sideVector; + if (sides.testFlag(QCP::msLeft)) { + sideVector.append(QCP::msLeft); + } + if (sides.testFlag(QCP::msRight)) { + sideVector.append(QCP::msRight); + } + if (sides.testFlag(QCP::msTop)) { + sideVector.append(QCP::msTop); + } + if (sides.testFlag(QCP::msBottom)) { + sideVector.append(QCP::msBottom); + } + + foreach (QCP::MarginSide side, sideVector) { + if (marginGroup(side) != group) { + QCPMarginGroup *oldGroup = marginGroup(side); + if (oldGroup) { // unregister at old group + oldGroup->removeChild(side, this); + } + + if (!group) { // if setting to 0, remove hash entry. Else set hash entry to new group and register there + mMarginGroups.remove(side); + } else { // setting to a new group + mMarginGroups[side] = group; + group->addChild(side, this); + } + } } - } } /*! @@ -3426,89 +3438,87 @@ void QCPLayoutElement::setMarginGroup(QCP::MarginSides sides, QCPMarginGroup *gr replot by the parent layout element. It is called multiple times, once for every \ref UpdatePhase. The phases are run through in the order of the enum values. For details about what happens at the different phases, see the documentation of \ref UpdatePhase. - + Layout elements that have child elements should call the \ref update method of their child elements, and pass the current \a phase unchanged. - + The default implementation executes the automatic margin mechanism in the \ref upMargins phase. Subclasses should make sure to call the base class implementation. */ void QCPLayoutElement::update(UpdatePhase phase) { - if (phase == upMargins) - { - if (mAutoMargins != QCP::msNone) - { - // set the margins of this layout element according to automatic margin calculation, either directly or via a margin group: - QMargins newMargins = mMargins; - const QList allMarginSides = QList() << QCP::msLeft << QCP::msRight << QCP::msTop << QCP::msBottom; - foreach (QCP::MarginSide side, allMarginSides) - { - if (mAutoMargins.testFlag(side)) // this side's margin shall be calculated automatically - { - if (mMarginGroups.contains(side)) - QCP::setMarginValue(newMargins, side, mMarginGroups[side]->commonMargin(side)); // this side is part of a margin group, so get the margin value from that group - else - QCP::setMarginValue(newMargins, side, calculateAutoMargin(side)); // this side is not part of a group, so calculate the value directly - // apply minimum margin restrictions: - if (QCP::getMarginValue(newMargins, side) < QCP::getMarginValue(mMinimumMargins, side)) - QCP::setMarginValue(newMargins, side, QCP::getMarginValue(mMinimumMargins, side)); + if (phase == upMargins) { + if (mAutoMargins != QCP::msNone) { + // set the margins of this layout element according to automatic margin calculation, either directly or via a margin group: + QMargins newMargins = mMargins; + const QList allMarginSides = QList() << QCP::msLeft << QCP::msRight << QCP::msTop << QCP::msBottom; + foreach (QCP::MarginSide side, allMarginSides) { + if (mAutoMargins.testFlag(side)) { // this side's margin shall be calculated automatically + if (mMarginGroups.contains(side)) { + QCP::setMarginValue(newMargins, side, mMarginGroups[side]->commonMargin(side)); // this side is part of a margin group, so get the margin value from that group + } else { + QCP::setMarginValue(newMargins, side, calculateAutoMargin(side)); // this side is not part of a group, so calculate the value directly + } + // apply minimum margin restrictions: + if (QCP::getMarginValue(newMargins, side) < QCP::getMarginValue(mMinimumMargins, side)) { + QCP::setMarginValue(newMargins, side, QCP::getMarginValue(mMinimumMargins, side)); + } + } + } + setMargins(newMargins); } - } - setMargins(newMargins); } - } } /*! Returns the suggested minimum size this layout element (the \ref outerRect) may be compressed to, if no manual minimum size is set. - + if a minimum size (\ref setMinimumSize) was not set manually, parent layouts use the returned size (usually indirectly through \ref QCPLayout::getFinalMinimumOuterSize) to determine the minimum allowed size of this layout element. A manual minimum size is considered set if it is non-zero. - + The default implementation simply returns the sum of the horizontal margins for the width and the sum of the vertical margins for the height. Reimplementations may use their detailed knowledge about the layout element's content to provide size hints. */ QSize QCPLayoutElement::minimumOuterSizeHint() const { - return {mMargins.left()+mMargins.right(), mMargins.top()+mMargins.bottom()}; + return {mMargins.left() + mMargins.right(), mMargins.top() + mMargins.bottom()}; } /*! Returns the suggested maximum size this layout element (the \ref outerRect) may be expanded to, if no manual maximum size is set. - + if a maximum size (\ref setMaximumSize) was not set manually, parent layouts use the returned size (usually indirectly through \ref QCPLayout::getFinalMaximumOuterSize) to determine the maximum allowed size of this layout element. A manual maximum size is considered set if it is smaller than Qt's \c QWIDGETSIZE_MAX. - + The default implementation simply returns \c QWIDGETSIZE_MAX for both width and height, implying no suggested maximum size. Reimplementations may use their detailed knowledge about the layout element's content to provide size hints. */ QSize QCPLayoutElement::maximumOuterSizeHint() const { - return {QWIDGETSIZE_MAX, QWIDGETSIZE_MAX}; + return {QWIDGETSIZE_MAX, QWIDGETSIZE_MAX}; } /*! Returns a list of all child elements in this layout element. If \a recursive is true, all sub-child elements are included in the list, too. - + \warning There may be \c nullptr entries in the returned list. For example, QCPLayoutGrid may have empty cells which yield \c nullptr at the respective index. */ -QList QCPLayoutElement::elements(bool recursive) const +QList QCPLayoutElement::elements(bool recursive) const { - Q_UNUSED(recursive) - return QList(); + Q_UNUSED(recursive) + return QList(); } /*! @@ -3516,69 +3526,69 @@ QList QCPLayoutElement::elements(bool recursive) const rect, this method returns a value corresponding to 0.99 times the parent plot's selection tolerance. However, layout elements are not selectable by default. So if \a onlySelectable is true, -1.0 is returned. - + See \ref QCPLayerable::selectTest for a general explanation of this virtual method. - + QCPLayoutElement subclasses may reimplement this method to provide more specific selection test behaviour. */ double QCPLayoutElement::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { - Q_UNUSED(details) - - if (onlySelectable) - return -1; - - if (QRectF(mOuterRect).contains(pos)) - { - if (mParentPlot) - return mParentPlot->selectionTolerance()*0.99; - else - { - qDebug() << Q_FUNC_INFO << "parent plot not defined"; - return -1; + Q_UNUSED(details) + + if (onlySelectable) { + return -1; + } + + if (QRectF(mOuterRect).contains(pos)) { + if (mParentPlot) { + return mParentPlot->selectionTolerance() * 0.99; + } else { + qDebug() << Q_FUNC_INFO << "parent plot not defined"; + return -1; + } + } else { + return -1; } - } else - return -1; } /*! \internal - + propagates the parent plot initialization to all child elements, by calling \ref QCPLayerable::initializeParentPlot on them. */ void QCPLayoutElement::parentPlotInitialized(QCustomPlot *parentPlot) { - foreach (QCPLayoutElement *el, elements(false)) - { - if (!el->parentPlot()) - el->initializeParentPlot(parentPlot); - } + foreach (QCPLayoutElement *el, elements(false)) { + if (!el->parentPlot()) { + el->initializeParentPlot(parentPlot); + } + } } /*! \internal - + Returns the margin size for this \a side. It is used if automatic margins is enabled for this \a side (see \ref setAutoMargins). If a minimum margin was set with \ref setMinimumMargins, the returned value will not be smaller than the specified minimum margin. - + The default implementation just returns the respective manual margin (\ref setMargins) or the minimum margin, whichever is larger. */ int QCPLayoutElement::calculateAutoMargin(QCP::MarginSide side) { - return qMax(QCP::getMarginValue(mMargins, side), QCP::getMarginValue(mMinimumMargins, 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() @@ -3591,23 +3601,23 @@ void QCPLayoutElement::layoutChanged() /*! \class QCPLayout \brief The abstract base class for layouts - + This is an abstract base class for layout elements whose main purpose is to define the position and size of other child layout elements. In most cases, layouts don't draw anything themselves (but there are exceptions to this, e.g. QCPLegend). - + QCPLayout derives from QCPLayoutElement, and thus can itself be nested in other layouts. - + QCPLayout introduces a common interface for accessing and manipulating the child elements. Those functions are most notably \ref elementCount, \ref elementAt, \ref takeAt, \ref take, \ref simplify, \ref removeAt, \ref remove and \ref clear. Individual subclasses may add more functions to this interface which are more specialized to the form of the layout. For example, \ref QCPLayoutGrid adds functions that take row and column indices to access cells of the layout grid more conveniently. - + Since this is an abstract base class, you can't instantiate it directly. Rather use one of its subclasses like QCPLayoutGrid or QCPLayoutInset. - + For a general introduction to the layout system, see the dedicated documentation page \ref thelayoutsystem "The Layout System". */ @@ -3615,45 +3625,45 @@ void QCPLayoutElement::layoutChanged() /* start documentation of pure virtual functions */ /*! \fn virtual int QCPLayout::elementCount() const = 0 - + Returns the number of elements/cells in the layout. - + \see elements, elementAt */ /*! \fn virtual QCPLayoutElement* QCPLayout::elementAt(int index) const = 0 - + Returns the element in the cell with the given \a index. If \a index is invalid, returns \c nullptr. - + Note that even if \a index is valid, the respective cell may be empty in some layouts (e.g. QCPLayoutGrid), so this function may return \c nullptr in those cases. You may use this function to check whether a cell is empty or not. - + \see elements, elementCount, takeAt */ /*! \fn virtual QCPLayoutElement* QCPLayout::takeAt(int index) = 0 - + Removes the element with the given \a index from the layout and returns it. - + If the \a index is invalid or the cell with that index is empty, returns \c nullptr. - + Note that some layouts don't remove the respective cell right away but leave an empty cell after successful removal of the layout element. To collapse empty cells, use \ref simplify. - + \see elementAt, take */ /*! \fn virtual bool QCPLayout::take(QCPLayoutElement* element) = 0 - + Removes the specified \a element from the layout and returns true on success. - + If the \a element isn't in this layout, returns false. - + Note that some layouts don't remove the respective cell right away but leave an empty cell after successful removal of the layout element. To collapse empty cells, use \ref simplify. - + \see takeAt */ @@ -3670,54 +3680,55 @@ QCPLayout::QCPLayout() /*! If \a phase is \ref upLayout, calls \ref updateLayout, which subclasses may reimplement to reposition and resize their cells. - + Finally, the call is propagated down to all child \ref QCPLayoutElement "QCPLayoutElements". - + For details about this method and the update phases, see the documentation of \ref QCPLayoutElement::update. */ void QCPLayout::update(UpdatePhase phase) { - QCPLayoutElement::update(phase); - - // set child element rects according to layout: - if (phase == upLayout) - updateLayout(); - - // propagate update call to child elements: - const int elCount = elementCount(); - for (int i=0; iupdate(phase); - } + QCPLayoutElement::update(phase); + + // set child element rects according to layout: + if (phase == upLayout) { + updateLayout(); + } + + // propagate update call to child elements: + const int elCount = elementCount(); + for (int i = 0; i < elCount; ++i) { + if (QCPLayoutElement *el = elementAt(i)) { + el->update(phase); + } + } } /* inherits documentation from base class */ -QList QCPLayout::elements(bool recursive) const +QList QCPLayout::elements(bool recursive) const { - const int c = elementCount(); - QList result; + const int c = elementCount(); + QList result; #if QT_VERSION >= QT_VERSION_CHECK(4, 7, 0) - result.reserve(c); + result.reserve(c); #endif - for (int i=0; ielements(recursive); + for (int i = 0; i < c; ++i) { + result.append(elementAt(i)); } - } - return result; + if (recursive) { + for (int i = 0; i < c; ++i) { + if (result.at(i)) { + result << result.at(i)->elements(recursive); + } + } + } + return result; } /*! Simplifies the layout by collapsing empty cells. The exact behavior depends on subclasses, the default implementation does nothing. - + Not all layouts need simplification. For example, QCPLayoutInset doesn't use explicit simplification while QCPLayoutGrid does. */ @@ -3728,64 +3739,64 @@ void QCPLayout::simplify() /*! Removes and deletes the element at the provided \a index. Returns true on success. If \a index is invalid or points to an empty cell, returns false. - + This function internally uses \ref takeAt to remove the element from the layout and then deletes the returned element. Note that some layouts don't remove the respective cell right away but leave an empty cell after successful removal of the layout element. To collapse empty cells, use \ref simplify. - + \see remove, takeAt */ bool QCPLayout::removeAt(int index) { - if (QCPLayoutElement *el = takeAt(index)) - { - delete el; - return true; - } else - return false; + if (QCPLayoutElement *el = takeAt(index)) { + delete el; + return true; + } else { + return false; + } } /*! Removes and deletes the provided \a element. Returns true on success. If \a element is not in the layout, returns false. - + This function internally uses \ref takeAt to remove the element from the layout and then deletes the element. Note that some layouts don't remove the respective cell right away but leave an empty cell after successful removal of the layout element. To collapse empty cells, use \ref simplify. - + \see removeAt, take */ bool QCPLayout::remove(QCPLayoutElement *element) { - if (take(element)) - { - delete element; - return true; - } else - return false; + if (take(element)) { + delete element; + return true; + } else { + return false; + } } /*! Removes and deletes all layout elements in this layout. Finally calls \ref simplify to make sure all empty cells are collapsed. - + \see remove, removeAt */ void QCPLayout::clear() { - for (int i=elementCount()-1; i>=0; --i) - { - if (elementAt(i)) - removeAt(i); - } - simplify(); + for (int i = elementCount() - 1; i >= 0; --i) { + if (elementAt(i)) { + removeAt(i); + } + } + simplify(); } /*! Subclasses call this method to report changed (minimum/maximum) size constraints. - + If the parent of this layout is again a QCPLayout, forwards the call to the parent's \ref sizeConstraintsChanged. If the parent is a QWidget (i.e. is the \ref QCustomPlot::plotLayout of QCustomPlot), calls QWidget::updateGeometry, so if the QCustomPlot widget is inside a Qt QLayout, @@ -3793,22 +3804,23 @@ void QCPLayout::clear() */ void QCPLayout::sizeConstraintsChanged() const { - if (QWidget *w = qobject_cast(parent())) - w->updateGeometry(); - else if (QCPLayout *l = qobject_cast(parent())) - l->sizeConstraintsChanged(); + if (QWidget *w = qobject_cast(parent())) { + w->updateGeometry(); + } else if (QCPLayout *l = qobject_cast(parent())) { + l->sizeConstraintsChanged(); + } } /*! \internal - + Subclasses reimplement this method to update the position and sizes of the child elements/cells via calling their \ref QCPLayoutElement::setOuterRect. The default implementation does nothing. - + The geometry used as a reference is the inner \ref rect of this layout. Child elements should stay within that rect. - + \ref getSectionSizes may help with the reimplementation of this function. - + \see update */ void QCPLayout::updateLayout() @@ -3817,201 +3829,199 @@ void QCPLayout::updateLayout() /*! \internal - + Associates \a el with this layout. This is done by setting the \ref QCPLayoutElement::layout, the \ref QCPLayerable::parentLayerable and the QObject parent to this layout. - + Further, if \a el didn't previously have a parent plot, calls \ref QCPLayerable::initializeParentPlot on \a el to set the paret plot. - + This method is used by subclass specific methods that add elements to the layout. Note that this method only changes properties in \a el. The removal from the old layout and the insertion into the new layout must be done additionally. */ void QCPLayout::adoptElement(QCPLayoutElement *el) { - if (el) - { - el->mParentLayout = this; - el->setParentLayerable(this); - el->setParent(this); - if (!el->parentPlot()) - el->initializeParentPlot(mParentPlot); - el->layoutChanged(); - } else - qDebug() << Q_FUNC_INFO << "Null element passed"; + if (el) { + el->mParentLayout = this; + el->setParentLayerable(this); + el->setParent(this); + if (!el->parentPlot()) { + el->initializeParentPlot(mParentPlot); + } + el->layoutChanged(); + } else { + qDebug() << Q_FUNC_INFO << "Null element passed"; + } } /*! \internal - + Disassociates \a el from this layout. This is done by setting the \ref QCPLayoutElement::layout and the \ref QCPLayerable::parentLayerable to zero. The QObject parent is set to the parent QCustomPlot. - + This method is used by subclass specific methods that remove elements from the layout (e.g. \ref take or \ref takeAt). Note that this method only changes properties in \a el. The removal from the old layout must be done additionally. */ void QCPLayout::releaseElement(QCPLayoutElement *el) { - if (el) - { - el->mParentLayout = nullptr; - el->setParentLayerable(nullptr); - el->setParent(mParentPlot); - // Note: Don't initializeParentPlot(0) here, because layout element will stay in same parent plot - } else - qDebug() << Q_FUNC_INFO << "Null element passed"; + if (el) { + el->mParentLayout = nullptr; + el->setParentLayerable(nullptr); + el->setParent(mParentPlot); + // Note: Don't initializeParentPlot(0) here, because layout element will stay in same parent plot + } else { + qDebug() << Q_FUNC_INFO << "Null element passed"; + } } /*! \internal - + This is a helper function for the implementation of \ref updateLayout in subclasses. - + It calculates the sizes of one-dimensional sections with provided constraints on maximum section sizes, minimum section sizes, relative stretch factors and the final total size of all sections. - + The QVector entries refer to the sections. Thus all QVectors must have the same size. - + \a maxSizes gives the maximum allowed size of each section. If there shall be no maximum size imposed, set all vector values to Qt's QWIDGETSIZE_MAX. - + \a minSizes gives the minimum allowed size of each section. If there shall be no minimum size imposed, set all vector values to zero. If the \a minSizes entries add up to a value greater than \a totalSize, sections will be scaled smaller than the proposed minimum sizes. (In other words, not exceeding the allowed total size is taken to be more important than not going below minimum section sizes.) - + \a stretchFactors give the relative proportions of the sections to each other. If all sections shall be scaled equally, set all values equal. If the first section shall be double the size of each individual other section, set the first number of \a stretchFactors to double the value of the other individual values (e.g. {2, 1, 1, 1}). - + \a totalSize is the value that the final section sizes will add up to. Due to rounding, the actual sum may differ slightly. If you want the section sizes to sum up to exactly that value, you could distribute the remaining difference on the sections. - + The return value is a QVector containing the section sizes. */ QVector QCPLayout::getSectionSizes(QVector maxSizes, QVector minSizes, QVector stretchFactors, int totalSize) const { - if (maxSizes.size() != minSizes.size() || minSizes.size() != stretchFactors.size()) - { - qDebug() << Q_FUNC_INFO << "Passed vector sizes aren't equal:" << maxSizes << minSizes << stretchFactors; - return QVector(); - } - if (stretchFactors.isEmpty()) - return QVector(); - int sectionCount = stretchFactors.size(); - QVector sectionSizes(sectionCount); - // if provided total size is forced smaller than total minimum size, ignore minimum sizes (squeeze sections): - int minSizeSum = 0; - for (int i=0; i(); } - } - - QList minimumLockedSections; - QList unfinishedSections; - for (int i=0; i(); + } + int sectionCount = stretchFactors.size(); + QVector sectionSizes(sectionCount); + // if provided total size is forced smaller than total minimum size, ignore minimum sizes (squeeze sections): + int minSizeSum = 0; + for (int i = 0; i < sectionCount; ++i) { + minSizeSum += minSizes.at(i); + } + if (totalSize < minSizeSum) { + // new stretch factors are minimum sizes and minimum sizes are set to zero: + for (int i = 0; i < sectionCount; ++i) { + stretchFactors[i] = minSizes.at(i); + minSizes[i] = 0; } - } - // check if that maximum is actually within the bounds of the total size (i.e. can we stretch all remaining sections so far that the found section - // actually hits its maximum, without exceeding the total size when we add up all sections) - double stretchFactorSum = 0; - foreach (int secId, unfinishedSections) - stretchFactorSum += stretchFactors.at(secId); - double nextMaxLimit = freeSize/stretchFactorSum; - if (nextMax < nextMaxLimit) // next maximum is actually hit, move forward to that point and fix the size of that section - { - foreach (int secId, unfinishedSections) - { - sectionSizes[secId] += nextMax*stretchFactors.at(secId); // increment all sections - freeSize -= nextMax*stretchFactors.at(secId); + } + + QList minimumLockedSections; + QList unfinishedSections; + for (int i = 0; i < sectionCount; ++i) { + unfinishedSections.append(i); + } + double freeSize = totalSize; + + int outerIterations = 0; + while (!unfinishedSections.isEmpty() && outerIterations < sectionCount * 2) { // the iteration check ist just a failsafe in case something really strange happens + ++outerIterations; + int innerIterations = 0; + while (!unfinishedSections.isEmpty() && innerIterations < sectionCount * 2) { // the iteration check ist just a failsafe in case something really strange happens + ++innerIterations; + // find section that hits its maximum next: + int nextId = -1; + double nextMax = 1e12; + foreach (int secId, unfinishedSections) { + double hitsMaxAt = (maxSizes.at(secId) - sectionSizes.at(secId)) / stretchFactors.at(secId); + if (hitsMaxAt < nextMax) { + nextMax = hitsMaxAt; + nextId = secId; + } + } + // check if that maximum is actually within the bounds of the total size (i.e. can we stretch all remaining sections so far that the found section + // actually hits its maximum, without exceeding the total size when we add up all sections) + double stretchFactorSum = 0; + foreach (int secId, unfinishedSections) { + stretchFactorSum += stretchFactors.at(secId); + } + double nextMaxLimit = freeSize / stretchFactorSum; + if (nextMax < nextMaxLimit) { // next maximum is actually hit, move forward to that point and fix the size of that section + foreach (int secId, unfinishedSections) { + sectionSizes[secId] += nextMax * stretchFactors.at(secId); // increment all sections + freeSize -= nextMax * stretchFactors.at(secId); + } + unfinishedSections.removeOne(nextId); // exclude the section that is now at maximum from further changes + } else { // next maximum isn't hit, just distribute rest of free space on remaining sections + foreach (int secId, unfinishedSections) { + sectionSizes[secId] += nextMaxLimit * stretchFactors.at(secId); // increment all sections + } + unfinishedSections.clear(); + } + } + if (innerIterations == sectionCount * 2) { + qDebug() << Q_FUNC_INFO << "Exceeded maximum expected inner iteration count, layouting aborted. Input was:" << maxSizes << minSizes << stretchFactors << totalSize; + } + + // now check whether the resulting section sizes violate minimum restrictions: + bool foundMinimumViolation = false; + for (int i = 0; i < sectionSizes.size(); ++i) { + if (minimumLockedSections.contains(i)) { + continue; + } + if (sectionSizes.at(i) < minSizes.at(i)) { // section violates minimum + sectionSizes[i] = minSizes.at(i); // set it to minimum + foundMinimumViolation = true; // make sure we repeat the whole optimization process + minimumLockedSections.append(i); + } + } + if (foundMinimumViolation) { + freeSize = totalSize; + for (int i = 0; i < sectionCount; ++i) { + if (!minimumLockedSections.contains(i)) { // only put sections that haven't hit their minimum back into the pool + unfinishedSections.append(i); + } else { + freeSize -= sectionSizes.at(i); // remove size of minimum locked sections from available space in next round + } + } + // reset all section sizes to zero that are in unfinished sections (all others have been set to their minimum): + foreach (int secId, unfinishedSections) { + sectionSizes[secId] = 0; + } } - unfinishedSections.removeOne(nextId); // exclude the section that is now at maximum from further changes - } else // next maximum isn't hit, just distribute rest of free space on remaining sections - { - foreach (int secId, unfinishedSections) - sectionSizes[secId] += nextMaxLimit*stretchFactors.at(secId); // increment all sections - unfinishedSections.clear(); - } } - if (innerIterations == sectionCount*2) - qDebug() << Q_FUNC_INFO << "Exceeded maximum expected inner iteration count, layouting aborted. Input was:" << maxSizes << minSizes << stretchFactors << totalSize; - - // now check whether the resulting section sizes violate minimum restrictions: - bool foundMinimumViolation = false; - for (int i=0; i result(sectionCount); + for (int i = 0; i < sectionCount; ++i) { + result[i] = qRound(sectionSizes.at(i)); } - } - if (outerIterations == sectionCount*2) - qDebug() << Q_FUNC_INFO << "Exceeded maximum expected outer iteration count, layouting aborted. Input was:" << maxSizes << minSizes << stretchFactors << totalSize; - - QVector result(sectionCount); - for (int i=0; i QCPLayout::getSectionSizes(QVector maxSizes, QVector minS */ QSize QCPLayout::getFinalMinimumOuterSize(const QCPLayoutElement *el) { - QSize minOuterHint = el->minimumOuterSizeHint(); - QSize minOuter = el->minimumSize(); // depending on sizeConstraitRect this might be with respect to inner rect, so possibly add margins in next four lines (preserving unset minimum of 0) - if (minOuter.width() > 0 && el->sizeConstraintRect() == QCPLayoutElement::scrInnerRect) - minOuter.rwidth() += el->margins().left() + el->margins().right(); - if (minOuter.height() > 0 && el->sizeConstraintRect() == QCPLayoutElement::scrInnerRect) - minOuter.rheight() += el->margins().top() + el->margins().bottom(); - - return {minOuter.width() > 0 ? minOuter.width() : minOuterHint.width(), - minOuter.height() > 0 ? minOuter.height() : minOuterHint.height()}; + QSize minOuterHint = el->minimumOuterSizeHint(); + QSize minOuter = el->minimumSize(); // depending on sizeConstraitRect this might be with respect to inner rect, so possibly add margins in next four lines (preserving unset minimum of 0) + if (minOuter.width() > 0 && el->sizeConstraintRect() == QCPLayoutElement::scrInnerRect) { + minOuter.rwidth() += el->margins().left() + el->margins().right(); + } + if (minOuter.height() > 0 && el->sizeConstraintRect() == QCPLayoutElement::scrInnerRect) { + minOuter.rheight() += el->margins().top() + el->margins().bottom(); + } + + return {minOuter.width() > 0 ? minOuter.width() : minOuterHint.width(), + minOuter.height() > 0 ? minOuter.height() : minOuterHint.height()}; } /*! \internal - - This is a helper function for the implementation of subclasses. - - It returns the maximum size that should finally be used for the outer rect of the passed layout - element \a el. - - It takes into account whether a manual maximum size is set (\ref - QCPLayoutElement::setMaximumSize), which size constraint is set (\ref - QCPLayoutElement::setSizeConstraintRect), as well as the maximum size hint, if no manual maximum - size was set (\ref QCPLayoutElement::maximumOuterSizeHint). + +This is a helper function for the implementation of subclasses. + +It returns the maximum size that should finally be used for the outer rect of the passed layout +element \a el. + +It takes into account whether a manual maximum size is set (\ref +QCPLayoutElement::setMaximumSize), which size constraint is set (\ref +QCPLayoutElement::setSizeConstraintRect), as well as the maximum size hint, if no manual maximum +size was set (\ref QCPLayoutElement::maximumOuterSizeHint). */ QSize QCPLayout::getFinalMaximumOuterSize(const QCPLayoutElement *el) { - QSize maxOuterHint = el->maximumOuterSizeHint(); - QSize maxOuter = el->maximumSize(); // depending on sizeConstraitRect this might be with respect to inner rect, so possibly add margins in next four lines (preserving unset maximum of QWIDGETSIZE_MAX) - if (maxOuter.width() < QWIDGETSIZE_MAX && el->sizeConstraintRect() == QCPLayoutElement::scrInnerRect) - maxOuter.rwidth() += el->margins().left() + el->margins().right(); - if (maxOuter.height() < QWIDGETSIZE_MAX && el->sizeConstraintRect() == QCPLayoutElement::scrInnerRect) - maxOuter.rheight() += el->margins().top() + el->margins().bottom(); - - return {maxOuter.width() < QWIDGETSIZE_MAX ? maxOuter.width() : maxOuterHint.width(), - maxOuter.height() < QWIDGETSIZE_MAX ? maxOuter.height() : maxOuterHint.height()}; + QSize maxOuterHint = el->maximumOuterSizeHint(); + QSize maxOuter = el->maximumSize(); // depending on sizeConstraitRect this might be with respect to inner rect, so possibly add margins in next four lines (preserving unset maximum of QWIDGETSIZE_MAX) + if (maxOuter.width() < QWIDGETSIZE_MAX && el->sizeConstraintRect() == QCPLayoutElement::scrInnerRect) { + maxOuter.rwidth() += el->margins().left() + el->margins().right(); + } + if (maxOuter.height() < QWIDGETSIZE_MAX && el->sizeConstraintRect() == QCPLayoutElement::scrInnerRect) { + maxOuter.rheight() += el->margins().top() + el->margins().bottom(); + } + + return {maxOuter.width() < QWIDGETSIZE_MAX ? maxOuter.width() : maxOuterHint.width(), + maxOuter.height() < QWIDGETSIZE_MAX ? maxOuter.height() : maxOuterHint.height()}; } @@ -4061,84 +4075,85 @@ QSize QCPLayout::getFinalMaximumOuterSize(const QCPLayoutElement *el) //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPLayoutGrid - \brief A layout that arranges child elements in a grid +\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 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. +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). +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. +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. +Returns the number of rows in the layout. - \see columnCount +\see columnCount */ /*! \fn int QCPLayoutGrid::columnCount() const - Returns the number of columns in the layout. +Returns the number of columns in the layout. - \see rowCount +\see rowCount */ /* end documentation of inline functions */ /*! - Creates an instance of QCPLayoutGrid and sets default values. +Creates an instance of QCPLayoutGrid and sets default values. */ QCPLayoutGrid::QCPLayoutGrid() : - mColumnSpacing(5), - mRowSpacing(5), - mWrap(0), - mFillOrder(foColumnsFirst) + mColumnSpacing(5), + mRowSpacing(5), + mWrap(0), + mFillOrder(foColumnsFirst) { } QCPLayoutGrid::~QCPLayoutGrid() { - // clear all child layout elements. This is important because only the specific layouts know how - // to handle removing elements (clear calls virtual removeAt method to do that). - clear(); + // clear all child layout elements. This is important because only the specific layouts know how + // to handle removing elements (clear calls virtual removeAt method to do that). + clear(); } /*! Returns the element in the cell in \a row and \a column. - + Returns \c nullptr if either the row/column is invalid or if the cell is empty. In those cases, a qDebug message is printed. To check whether a cell exists and isn't empty, use \ref hasElement. - + \see addElement, hasElement */ QCPLayoutElement *QCPLayoutGrid::element(int row, int column) const { - if (row >= 0 && row < mElements.size()) - { - if (column >= 0 && column < mElements.first().size()) - { - if (QCPLayoutElement *result = mElements.at(row).at(column)) - return result; - else - qDebug() << Q_FUNC_INFO << "Requested cell is empty. Row:" << row << "Column:" << column; - } else - qDebug() << Q_FUNC_INFO << "Invalid column. Row:" << row << "Column:" << column; - } else - qDebug() << Q_FUNC_INFO << "Invalid row. Row:" << row << "Column:" << column; - return nullptr; + if (row >= 0 && row < mElements.size()) { + if (column >= 0 && column < mElements.first().size()) { + if (QCPLayoutElement *result = mElements.at(row).at(column)) { + return result; + } else { + qDebug() << Q_FUNC_INFO << "Requested cell is empty. Row:" << row << "Column:" << column; + } + } else { + qDebug() << Q_FUNC_INFO << "Invalid column. Row:" << row << "Column:" << column; + } + } else { + qDebug() << Q_FUNC_INFO << "Invalid row. Row:" << row << "Column:" << column; + } + return nullptr; } @@ -4158,18 +4173,20 @@ QCPLayoutElement *QCPLayoutGrid::element(int row, int column) const */ bool QCPLayoutGrid::addElement(int row, int column, QCPLayoutElement *element) { - if (!hasElement(row, column)) - { - 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 false; + if (!hasElement(row, column)) { + 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 false; } /*! \overload @@ -4184,172 +4201,165 @@ bool QCPLayoutGrid::addElement(int row, int column, QCPLayoutElement *element) */ 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; - } + 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; + } + } } - } else - { - while (hasElement(rowIndex, colIndex)) - { - ++rowIndex; - if (rowIndex >= mWrap && mWrap > 0) - { - rowIndex = 0; - ++colIndex; - } - } - } - return addElement(rowIndex, colIndex, element); + 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. - + \see element */ bool QCPLayoutGrid::hasElement(int row, int column) { - if (row >= 0 && row < rowCount() && column >= 0 && column < columnCount()) - return mElements.at(row).at(column); - else - return false; + if (row >= 0 && row < rowCount() && column >= 0 && column < columnCount()) { + return mElements.at(row).at(column); + } else { + return false; + } } /*! Sets the stretch \a factor of \a column. - + Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond their minimum and maximum widths/heights, regardless of the stretch factor. (see \ref QCPLayoutElement::setMinimumSize, \ref QCPLayoutElement::setMaximumSize, \ref QCPLayoutElement::setSizeConstraintRect.) - + The default stretch factor of newly created rows/columns is 1. - + \see setColumnStretchFactors, setRowStretchFactor */ void QCPLayoutGrid::setColumnStretchFactor(int column, double factor) { - if (column >= 0 && column < columnCount()) - { - if (factor > 0) - mColumnStretchFactors[column] = factor; - else - qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << factor; - } else - qDebug() << Q_FUNC_INFO << "Invalid column:" << column; + if (column >= 0 && column < columnCount()) { + if (factor > 0) { + mColumnStretchFactors[column] = factor; + } else { + qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << factor; + } + } else { + qDebug() << Q_FUNC_INFO << "Invalid column:" << column; + } } /*! Sets the stretch \a factors of all columns. \a factors must have the size \ref columnCount. - + Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond their minimum and maximum widths/heights, regardless of the stretch factor. (see \ref QCPLayoutElement::setMinimumSize, \ref QCPLayoutElement::setMaximumSize, \ref QCPLayoutElement::setSizeConstraintRect.) - + The default stretch factor of newly created rows/columns is 1. - + \see setColumnStretchFactor, setRowStretchFactors */ void QCPLayoutGrid::setColumnStretchFactors(const QList &factors) { - if (factors.size() == mColumnStretchFactors.size()) - { - mColumnStretchFactors = factors; - for (int i=0; i= 0 && row < rowCount()) - { - if (factor > 0) - mRowStretchFactors[row] = factor; - else - qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << factor; - } else - qDebug() << Q_FUNC_INFO << "Invalid row:" << row; + if (row >= 0 && row < rowCount()) { + if (factor > 0) { + mRowStretchFactors[row] = factor; + } else { + qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << factor; + } + } else { + qDebug() << Q_FUNC_INFO << "Invalid row:" << row; + } } /*! Sets the stretch \a factors of all rows. \a factors must have the size \ref rowCount. - + Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond their minimum and maximum widths/heights, regardless of the stretch factor. (see \ref QCPLayoutElement::setMinimumSize, \ref QCPLayoutElement::setMaximumSize, \ref QCPLayoutElement::setSizeConstraintRect.) - + The default stretch factor of newly created rows/columns is 1. - + \see setRowStretchFactor, setColumnStretchFactors */ void QCPLayoutGrid::setRowStretchFactors(const QList &factors) { - if (factors.size() == mRowStretchFactors.size()) - { - mRowStretchFactors = factors; - for (int i=0; i tempElements; - if (rearrange) - { - tempElements.reserve(elCount); - for (int i=0; i tempElements; + if (rearrange) { + tempElements.reserve(elCount); + for (int i = 0; i < elCount; ++i) { + if (elementAt(i)) { + tempElements.append(takeAt(i)); + } + } + simplify(); + } + // change fill order as requested: + mFillOrder = order; + // if rearranging, re-insert via linear index according to new fill order: + if (rearrange) { + foreach (QCPLayoutElement *tempElement, tempElements) { + addElement(tempElement); + } } - simplify(); - } - // change fill order as requested: - mFillOrder = order; - // if rearranging, re-insert via linear index according to new fill order: - if (rearrange) - { - foreach (QCPLayoutElement *tempElement, tempElements) - addElement(tempElement); - } } /*! Expands the layout to have \a newRowCount rows and \a newColumnCount columns. So the last valid row index will be \a newRowCount-1, the last valid column index will be \a newColumnCount-1. - + If the current column/row count is already larger or equal to \a newColumnCount/\a newRowCount, this function does nothing in that dimension. - + Newly created cells are empty, new rows and columns have the stretch factor 1. - + Note that upon a call to \ref addElement, the layout is expanded automatically to contain the specified row and column, using this function. - + \see simplify */ void QCPLayoutGrid::expandTo(int newRowCount, int newColumnCount) { - // add rows as necessary: - while (rowCount() < newRowCount) - { - mElements.append(QList()); - mRowStretchFactors.append(1); - } - // go through rows and expand columns as necessary: - int newColCount = qMax(columnCount(), newColumnCount); - for (int i=0; i()); + mRowStretchFactors.append(1); + } + // go through rows and expand columns as necessary: + int newColCount = qMax(columnCount(), newColumnCount); + for (int i = 0; i < rowCount(); ++i) { + while (mElements.at(i).size() < newColCount) { + mElements[i].append(nullptr); + } + } + while (mColumnStretchFactors.size() < newColCount) { + mColumnStretchFactors.append(1); + } } /*! Inserts a new row with empty cells at the row index \a newIndex. Valid values for \a newIndex range from 0 (inserts a row at the top) to \a rowCount (appends a row at the bottom). - + \see insertColumn */ void QCPLayoutGrid::insertRow(int newIndex) { - if (mElements.isEmpty() || mElements.first().isEmpty()) // if grid is completely empty, add first cell - { - expandTo(1, 1); - return; - } - - if (newIndex < 0) - newIndex = 0; - if (newIndex > rowCount()) - newIndex = rowCount(); - - mRowStretchFactors.insert(newIndex, 1); - QList newRow; - for (int col=0; col rowCount()) { + newIndex = rowCount(); + } + + mRowStretchFactors.insert(newIndex, 1); + QList newRow; + for (int col = 0; col < columnCount(); ++col) { + newRow.append(nullptr); + } + mElements.insert(newIndex, newRow); } /*! Inserts a new column with empty cells at the column index \a newIndex. Valid values for \a newIndex range from 0 (inserts a column at the left) to \a columnCount (appends a column at the right). - + \see insertRow */ void QCPLayoutGrid::insertColumn(int newIndex) { - if (mElements.isEmpty() || mElements.first().isEmpty()) // if grid is completely empty, add first cell - { - expandTo(1, 1); - return; - } - - if (newIndex < 0) - newIndex = 0; - if (newIndex > columnCount()) - newIndex = columnCount(); - - mColumnStretchFactors.insert(newIndex, 1); - for (int row=0; row columnCount()) { + newIndex = columnCount(); + } + + mColumnStretchFactors.insert(newIndex, 1); + for (int row = 0; row < rowCount(); ++row) { + mElements[row].insert(newIndex, nullptr); + } } /*! @@ -4523,20 +4536,21 @@ void QCPLayoutGrid::insertColumn(int newIndex) */ int QCPLayoutGrid::rowColToIndex(int row, int column) const { - if (row >= 0 && row < rowCount()) - { - if (column >= 0 && column < columnCount()) - { - switch (mFillOrder) - { - case foRowsFirst: return column*rowCount() + row; - case foColumnsFirst: return row*columnCount() + column; - } - } else - qDebug() << Q_FUNC_INFO << "row index out of bounds:" << row; - } else - qDebug() << Q_FUNC_INFO << "column index out of bounds:" << column; - return 0; + if (row >= 0 && row < rowCount()) { + if (column >= 0 && column < columnCount()) { + switch (mFillOrder) { + case foRowsFirst: + return column * rowCount() + row; + case foColumnsFirst: + return row * columnCount() + column; + } + } else { + qDebug() << Q_FUNC_INFO << "row index out of bounds:" << row; + } + } else { + qDebug() << Q_FUNC_INFO << "column index out of bounds:" << column; + } + return 0; } /*! @@ -4556,62 +4570,60 @@ int QCPLayoutGrid::rowColToIndex(int row, int column) const */ void QCPLayoutGrid::indexToRowCol(int index, int &row, int &column) const { - row = -1; - column = -1; - const int nCols = columnCount(); - const int nRows = rowCount(); - if (nCols == 0 || nRows == 0) - return; - if (index < 0 || index >= elementCount()) - { - qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; - return; - } - - switch (mFillOrder) - { - case foRowsFirst: - { - column = index / nRows; - row = index % nRows; - break; + row = -1; + column = -1; + const int nCols = columnCount(); + const int nRows = rowCount(); + if (nCols == 0 || nRows == 0) { + return; } - case foColumnsFirst: - { - row = index / nCols; - column = index % nCols; - break; + if (index < 0 || index >= elementCount()) { + qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; + return; + } + + switch (mFillOrder) { + case foRowsFirst: { + column = index / nRows; + row = index % nRows; + break; + } + case foColumnsFirst: { + row = index / nCols; + column = index % nCols; + break; + } } - } } /* inherits documentation from base class */ void QCPLayoutGrid::updateLayout() { - QVector minColWidths, minRowHeights, maxColWidths, maxRowHeights; - getMinimumRowColSizes(&minColWidths, &minRowHeights); - getMaximumRowColSizes(&maxColWidths, &maxRowHeights); - - int totalRowSpacing = (rowCount()-1) * mRowSpacing; - int totalColSpacing = (columnCount()-1) * mColumnSpacing; - QVector colWidths = getSectionSizes(maxColWidths, minColWidths, mColumnStretchFactors.toVector(), mRect.width()-totalColSpacing); - QVector rowHeights = getSectionSizes(maxRowHeights, minRowHeights, mRowStretchFactors.toVector(), mRect.height()-totalRowSpacing); - - // go through cells and set rects accordingly: - int yOffset = mRect.top(); - for (int row=0; row 0) - yOffset += rowHeights.at(row-1)+mRowSpacing; - int xOffset = mRect.left(); - for (int col=0; col 0) - xOffset += colWidths.at(col-1)+mColumnSpacing; - if (mElements.at(row).at(col)) - mElements.at(row).at(col)->setOuterRect(QRect(xOffset, yOffset, colWidths.at(col), rowHeights.at(row))); + QVector minColWidths, minRowHeights, maxColWidths, maxRowHeights; + getMinimumRowColSizes(&minColWidths, &minRowHeights); + getMaximumRowColSizes(&maxColWidths, &maxRowHeights); + + int totalRowSpacing = (rowCount() - 1) * mRowSpacing; + int totalColSpacing = (columnCount() - 1) * mColumnSpacing; + QVector colWidths = getSectionSizes(maxColWidths, minColWidths, mColumnStretchFactors.toVector(), mRect.width() - totalColSpacing); + QVector rowHeights = getSectionSizes(maxRowHeights, minRowHeights, mRowStretchFactors.toVector(), mRect.height() - totalRowSpacing); + + // go through cells and set rects accordingly: + int yOffset = mRect.top(); + for (int row = 0; row < rowCount(); ++row) { + if (row > 0) { + yOffset += rowHeights.at(row - 1) + mRowSpacing; + } + int xOffset = mRect.left(); + for (int col = 0; col < columnCount(); ++col) { + if (col > 0) { + xOffset += colWidths.at(col - 1) + mColumnSpacing; + } + if (mElements.at(row).at(col)) { + mElements.at(row).at(col)->setOuterRect(QRect(xOffset, yOffset, colWidths.at(col), rowHeights.at(row))); + } + } } - } } /*! @@ -4624,13 +4636,13 @@ void QCPLayoutGrid::updateLayout() */ QCPLayoutElement *QCPLayoutGrid::elementAt(int index) const { - if (index >= 0 && index < elementCount()) - { - int row, col; - indexToRowCol(index, row, col); - return mElements.at(row).at(col); - } else - return nullptr; + if (index >= 0 && index < elementCount()) { + int row, col; + indexToRowCol(index, row, col); + return mElements.at(row).at(col); + } else { + return nullptr; + } } /*! @@ -4643,58 +4655,54 @@ QCPLayoutElement *QCPLayoutGrid::elementAt(int index) const */ QCPLayoutElement *QCPLayoutGrid::takeAt(int index) { - if (QCPLayoutElement *el = elementAt(index)) - { - releaseElement(el); - int row, col; - indexToRowCol(index, row, col); - mElements[row][col] = nullptr; - return el; - } else - { - qDebug() << Q_FUNC_INFO << "Attempt to take invalid index:" << index; - return nullptr; - } + if (QCPLayoutElement *el = elementAt(index)) { + releaseElement(el); + int row, col; + indexToRowCol(index, row, col); + mElements[row][col] = nullptr; + return el; + } else { + qDebug() << Q_FUNC_INFO << "Attempt to take invalid index:" << index; + return nullptr; + } } /* inherits documentation from base class */ bool QCPLayoutGrid::take(QCPLayoutElement *element) { - if (element) - { - for (int i=0; i QCPLayoutGrid::elements(bool recursive) const +QList QCPLayoutGrid::elements(bool recursive) const { - QList result; - const int elCount = elementCount(); + QList result; + const int elCount = elementCount(); #if QT_VERSION >= QT_VERSION_CHECK(4, 7, 0) - result.reserve(elCount); + result.reserve(elCount); #endif - for (int i=0; ielements(recursive); + for (int i = 0; i < elCount; ++i) { + result.append(elementAt(i)); } - } - return result; + if (recursive) { + for (int i = 0; i < elCount; ++i) { + if (result.at(i)) { + result << result.at(i)->elements(recursive); + } + } + } + return result; } /*! @@ -4702,151 +4710,149 @@ QList QCPLayoutGrid::elements(bool recursive) const */ void QCPLayoutGrid::simplify() { - // remove rows with only empty cells: - for (int row=rowCount()-1; row>=0; --row) - { - bool hasElements = false; - for (int col=0; col= 0; --row) { + bool hasElements = false; + for (int col = 0; col < columnCount(); ++col) { + if (mElements.at(row).at(col)) { + hasElements = true; + break; + } + } + if (!hasElements) { + mRowStretchFactors.removeAt(row); + mElements.removeAt(row); + if (mElements.isEmpty()) { // removed last element, also remove stretch factor (wouldn't happen below because also columnCount changed to 0 now) + mColumnStretchFactors.clear(); + } + } } - if (!hasElements) - { - mRowStretchFactors.removeAt(row); - mElements.removeAt(row); - if (mElements.isEmpty()) // removed last element, also remove stretch factor (wouldn't happen below because also columnCount changed to 0 now) - mColumnStretchFactors.clear(); + + // remove columns with only empty cells: + for (int col = columnCount() - 1; col >= 0; --col) { + bool hasElements = false; + for (int row = 0; row < rowCount(); ++row) { + if (mElements.at(row).at(col)) { + hasElements = true; + break; + } + } + if (!hasElements) { + mColumnStretchFactors.removeAt(col); + for (int row = 0; row < rowCount(); ++row) { + mElements[row].removeAt(col); + } + } } - } - - // remove columns with only empty cells: - for (int col=columnCount()-1; col>=0; --col) - { - bool hasElements = false; - for (int row=0; row minColWidths, minRowHeights; - getMinimumRowColSizes(&minColWidths, &minRowHeights); - QSize result(0, 0); - foreach (int w, minColWidths) - result.rwidth() += w; - foreach (int h, minRowHeights) - result.rheight() += h; - result.rwidth() += qMax(0, columnCount()-1) * mColumnSpacing; - result.rheight() += qMax(0, rowCount()-1) * mRowSpacing; - result.rwidth() += mMargins.left()+mMargins.right(); - result.rheight() += mMargins.top()+mMargins.bottom(); - return result; + QVector minColWidths, minRowHeights; + getMinimumRowColSizes(&minColWidths, &minRowHeights); + QSize result(0, 0); + foreach (int w, minColWidths) { + result.rwidth() += w; + } + foreach (int h, minRowHeights) { + result.rheight() += h; + } + result.rwidth() += qMax(0, columnCount() - 1) * mColumnSpacing; + result.rheight() += qMax(0, rowCount() - 1) * mRowSpacing; + result.rwidth() += mMargins.left() + mMargins.right(); + result.rheight() += mMargins.top() + mMargins.bottom(); + return result; } /* inherits documentation from base class */ QSize QCPLayoutGrid::maximumOuterSizeHint() const { - QVector maxColWidths, maxRowHeights; - getMaximumRowColSizes(&maxColWidths, &maxRowHeights); - - QSize result(0, 0); - foreach (int w, maxColWidths) - result.setWidth(qMin(result.width()+w, QWIDGETSIZE_MAX)); - foreach (int h, maxRowHeights) - result.setHeight(qMin(result.height()+h, QWIDGETSIZE_MAX)); - result.rwidth() += qMax(0, columnCount()-1) * mColumnSpacing; - result.rheight() += qMax(0, rowCount()-1) * mRowSpacing; - result.rwidth() += mMargins.left()+mMargins.right(); - result.rheight() += mMargins.top()+mMargins.bottom(); - if (result.height() > QWIDGETSIZE_MAX) - result.setHeight(QWIDGETSIZE_MAX); - if (result.width() > QWIDGETSIZE_MAX) - result.setWidth(QWIDGETSIZE_MAX); - return result; + QVector maxColWidths, maxRowHeights; + getMaximumRowColSizes(&maxColWidths, &maxRowHeights); + + QSize result(0, 0); + foreach (int w, maxColWidths) { + result.setWidth(qMin(result.width() + w, QWIDGETSIZE_MAX)); + } + foreach (int h, maxRowHeights) { + result.setHeight(qMin(result.height() + h, QWIDGETSIZE_MAX)); + } + result.rwidth() += qMax(0, columnCount() - 1) * mColumnSpacing; + result.rheight() += qMax(0, rowCount() - 1) * mRowSpacing; + result.rwidth() += mMargins.left() + mMargins.right(); + result.rheight() += mMargins.top() + mMargins.bottom(); + if (result.height() > QWIDGETSIZE_MAX) { + result.setHeight(QWIDGETSIZE_MAX); + } + if (result.width() > QWIDGETSIZE_MAX) { + result.setWidth(QWIDGETSIZE_MAX); + } + return result; } /*! \internal - + Places the minimum column widths and row heights into \a minColWidths and \a minRowHeights respectively. - + The minimum height of a row is the largest minimum height of any element's outer rect in that row. The minimum width of a column is the largest minimum width of any element's outer rect in that column. - + This is a helper function for \ref updateLayout. - + \see getMaximumRowColSizes */ void QCPLayoutGrid::getMinimumRowColSizes(QVector *minColWidths, QVector *minRowHeights) const { - *minColWidths = QVector(columnCount(), 0); - *minRowHeights = QVector(rowCount(), 0); - for (int row=0; rowat(col) < minSize.width()) - (*minColWidths)[col] = minSize.width(); - if (minRowHeights->at(row) < minSize.height()) - (*minRowHeights)[row] = minSize.height(); - } + *minColWidths = QVector(columnCount(), 0); + *minRowHeights = QVector(rowCount(), 0); + for (int row = 0; row < rowCount(); ++row) { + for (int col = 0; col < columnCount(); ++col) { + if (QCPLayoutElement *el = mElements.at(row).at(col)) { + QSize minSize = getFinalMinimumOuterSize(el); + if (minColWidths->at(col) < minSize.width()) { + (*minColWidths)[col] = minSize.width(); + } + if (minRowHeights->at(row) < minSize.height()) { + (*minRowHeights)[row] = minSize.height(); + } + } + } } - } } /*! \internal - + Places the maximum column widths and row heights into \a maxColWidths and \a maxRowHeights respectively. - + The maximum height of a row is the smallest maximum height of any element's outer rect in that row. The maximum width of a column is the smallest maximum width of any element's outer rect in that column. - + This is a helper function for \ref updateLayout. - + \see getMinimumRowColSizes */ void QCPLayoutGrid::getMaximumRowColSizes(QVector *maxColWidths, QVector *maxRowHeights) const { - *maxColWidths = QVector(columnCount(), QWIDGETSIZE_MAX); - *maxRowHeights = QVector(rowCount(), QWIDGETSIZE_MAX); - for (int row=0; rowat(col) > maxSize.width()) - (*maxColWidths)[col] = maxSize.width(); - if (maxRowHeights->at(row) > maxSize.height()) - (*maxRowHeights)[row] = maxSize.height(); - } + *maxColWidths = QVector(columnCount(), QWIDGETSIZE_MAX); + *maxRowHeights = QVector(rowCount(), QWIDGETSIZE_MAX); + for (int row = 0; row < rowCount(); ++row) { + for (int col = 0; col < columnCount(); ++col) { + if (QCPLayoutElement *el = mElements.at(row).at(col)) { + QSize maxSize = getFinalMaximumOuterSize(el); + if (maxColWidths->at(col) > maxSize.width()) { + (*maxColWidths)[col] = maxSize.width(); + } + if (maxRowHeights->at(row) > maxSize.height()) { + (*maxRowHeights)[row] = maxSize.height(); + } + } + } } - } } @@ -4855,7 +4861,7 @@ void QCPLayoutGrid::getMaximumRowColSizes(QVector *maxColWidths, QVector *maxColWidths, QVector finalMaxSize.width()) - insetRect.setWidth(finalMaxSize.width()); - if (insetRect.size().height() > finalMaxSize.height()) - insetRect.setHeight(finalMaxSize.height()); - } else if (mInsetPlacement.at(i) == ipBorderAligned) - { - insetRect.setSize(finalMinSize); - Qt::Alignment al = mInsetAlignment.at(i); - if (al.testFlag(Qt::AlignLeft)) insetRect.moveLeft(rect().x()); - else if (al.testFlag(Qt::AlignRight)) insetRect.moveRight(rect().x()+rect().width()); - else insetRect.moveLeft(int( rect().x()+rect().width()*0.5-finalMinSize.width()*0.5 )); // default to Qt::AlignHCenter - if (al.testFlag(Qt::AlignTop)) insetRect.moveTop(rect().y()); - else if (al.testFlag(Qt::AlignBottom)) insetRect.moveBottom(rect().y()+rect().height()); - else insetRect.moveTop(int( rect().y()+rect().height()*0.5-finalMinSize.height()*0.5 )); // default to Qt::AlignVCenter + for (int i = 0; i < mElements.size(); ++i) { + QCPLayoutElement *el = mElements.at(i); + QRect insetRect; + QSize finalMinSize = getFinalMinimumOuterSize(el); + QSize finalMaxSize = getFinalMaximumOuterSize(el); + if (mInsetPlacement.at(i) == ipFree) { + insetRect = QRect(int(rect().x() + rect().width() * mInsetRect.at(i).x()), + int(rect().y() + rect().height() * mInsetRect.at(i).y()), + int(rect().width() * mInsetRect.at(i).width()), + int(rect().height() * mInsetRect.at(i).height())); + if (insetRect.size().width() < finalMinSize.width()) { + insetRect.setWidth(finalMinSize.width()); + } + if (insetRect.size().height() < finalMinSize.height()) { + insetRect.setHeight(finalMinSize.height()); + } + if (insetRect.size().width() > finalMaxSize.width()) { + insetRect.setWidth(finalMaxSize.width()); + } + if (insetRect.size().height() > finalMaxSize.height()) { + insetRect.setHeight(finalMaxSize.height()); + } + } else if (mInsetPlacement.at(i) == ipBorderAligned) { + insetRect.setSize(finalMinSize); + Qt::Alignment al = mInsetAlignment.at(i); + if (al.testFlag(Qt::AlignLeft)) { + insetRect.moveLeft(rect().x()); + } else if (al.testFlag(Qt::AlignRight)) { + insetRect.moveRight(rect().x() + rect().width()); + } else { + insetRect.moveLeft(int(rect().x() + rect().width() * 0.5 - finalMinSize.width() * 0.5)); // default to Qt::AlignHCenter + } + if (al.testFlag(Qt::AlignTop)) { + insetRect.moveTop(rect().y()); + } else if (al.testFlag(Qt::AlignBottom)) { + insetRect.moveBottom(rect().y() + rect().height()); + } else { + insetRect.moveTop(int(rect().y() + rect().height() * 0.5 - finalMinSize.height() * 0.5)); // default to Qt::AlignVCenter + } + } + mElements.at(i)->setOuterRect(insetRect); } - mElements.at(i)->setOuterRect(insetRect); - } } /* inherits documentation from base class */ int QCPLayoutInset::elementCount() const { - return mElements.size(); + return mElements.size(); } /* inherits documentation from base class */ QCPLayoutElement *QCPLayoutInset::elementAt(int index) const { - if (index >= 0 && index < mElements.size()) - return mElements.at(index); - else - return nullptr; + if (index >= 0 && index < mElements.size()) { + return mElements.at(index); + } else { + return nullptr; + } } /* inherits documentation from base class */ QCPLayoutElement *QCPLayoutInset::takeAt(int index) { - if (QCPLayoutElement *el = elementAt(index)) - { - releaseElement(el); - mElements.removeAt(index); - mInsetPlacement.removeAt(index); - mInsetAlignment.removeAt(index); - mInsetRect.removeAt(index); - return el; - } else - { - qDebug() << Q_FUNC_INFO << "Attempt to take invalid index:" << index; - return nullptr; - } + if (QCPLayoutElement *el = elementAt(index)) { + releaseElement(el); + mElements.removeAt(index); + mInsetPlacement.removeAt(index); + mInsetAlignment.removeAt(index); + mInsetRect.removeAt(index); + return el; + } else { + qDebug() << Q_FUNC_INFO << "Attempt to take invalid index:" << index; + return nullptr; + } } /* inherits documentation from base class */ bool QCPLayoutInset::take(QCPLayoutElement *element) { - if (element) - { - for (int i=0; irealVisibility() && el->selectTest(pos, onlySelectable) >= 0) { + return mParentPlot->selectionTolerance() * 0.99; + } + } return -1; - - foreach (QCPLayoutElement *el, mElements) - { - // inset layout shall only return positive selectTest, if actually an inset object is at pos - // else it would block the entire underlying QCPAxisRect with its surface. - if (el->realVisibility() && el->selectTest(pos, onlySelectable) >= 0) - return mParentPlot->selectionTolerance()*0.99; - } - return -1; } /*! Adds the specified \a element to the layout as an inset aligned at the border (\ref setInsetAlignment is initialized with \ref ipBorderAligned). The alignment is set to \a alignment. - + \a alignment is an or combination of the following alignment flags: Qt::AlignLeft, Qt::AlignHCenter, Qt::AlighRight, Qt::AlignTop, Qt::AlignVCenter, Qt::AlignBottom. Any other alignment flags will be ignored. - + \see addElement(QCPLayoutElement *element, const QRectF &rect) */ void QCPLayoutInset::addElement(QCPLayoutElement *element, Qt::Alignment alignment) { - if (element) - { - if (element->layout()) // remove from old layout first - element->layout()->take(element); - mElements.append(element); - mInsetPlacement.append(ipBorderAligned); - mInsetAlignment.append(alignment); - mInsetRect.append(QRectF(0.6, 0.6, 0.4, 0.4)); - adoptElement(element); - } else - qDebug() << Q_FUNC_INFO << "Can't add nullptr element"; + if (element) { + if (element->layout()) { // remove from old layout first + element->layout()->take(element); + } + mElements.append(element); + mInsetPlacement.append(ipBorderAligned); + mInsetAlignment.append(alignment); + mInsetRect.append(QRectF(0.6, 0.6, 0.4, 0.4)); + adoptElement(element); + } else { + qDebug() << Q_FUNC_INFO << "Can't add nullptr element"; + } } /*! Adds the specified \a element to the layout as an inset with free positioning/sizing (\ref setInsetAlignment is initialized with \ref ipFree). The position and size is set to \a rect. - + \a rect is given in fractions of the whole inset layout rect. So an inset with rect (0, 0, 1, 1) will span the entire layout. An inset with rect (0.6, 0.1, 0.35, 0.35) will be in the top right corner of the layout, with 35% width and height of the parent layout. - + \see addElement(QCPLayoutElement *element, Qt::Alignment alignment) */ void QCPLayoutInset::addElement(QCPLayoutElement *element, const QRectF &rect) { - if (element) - { - if (element->layout()) // remove from old layout first - element->layout()->take(element); - mElements.append(element); - mInsetPlacement.append(ipFree); - mInsetAlignment.append(Qt::AlignRight|Qt::AlignTop); - mInsetRect.append(rect); - adoptElement(element); - } else - qDebug() << Q_FUNC_INFO << "Can't add nullptr element"; + if (element) { + if (element->layout()) { // remove from old layout first + element->layout()->take(element); + } + mElements.append(element); + mInsetPlacement.append(ipFree); + mInsetAlignment.append(Qt::AlignRight | Qt::AlignTop); + mInsetRect.append(rect); + adoptElement(element); + } else { + qDebug() << Q_FUNC_INFO << "Can't add nullptr element"; + } } /* end of 'src/layout.cpp' */ @@ -5169,19 +5184,19 @@ void QCPLayoutInset::addElement(QCPLayoutElement *element, const QRectF &rect) /*! \class QCPLineEnding \brief Handles the different ending decorations for line-like items - + \image html QCPLineEnding.png "The various ending styles currently supported" - + For every ending a line-like item has, an instance of this class exists. For example, QCPItemLine has two endings which can be set with QCPItemLine::setHead and QCPItemLine::setTail. - + The styles themselves are defined via the enum QCPLineEnding::EndingStyle. Most decorations can be modified regarding width and length, see \ref setWidth and \ref setLength. The direction of the ending decoration (e.g. direction an arrow is pointing) is controlled by the line-like item. For example, when both endings of a QCPItemLine are set to be arrows, they will point to opposite directions, e.g. "outward". This can be changed by \ref setInverted, which would make the respective arrow point inward. - + Note that due to the overloaded QCPLineEnding constructor, you may directly specify a QCPLineEnding::EndingStyle where actually a QCPLineEnding is expected, e.g. \snippet documentation/doc-code-snippets/mainwindow.cpp qcplineending-sethead @@ -5191,10 +5206,10 @@ void QCPLayoutInset::addElement(QCPLayoutElement *element, const QRectF &rect) Creates a QCPLineEnding instance with default values (style \ref esNone). */ QCPLineEnding::QCPLineEnding() : - mStyle(esNone), - mWidth(8), - mLength(10), - mInverted(false) + mStyle(esNone), + mWidth(8), + mLength(10), + mInverted(false) { } @@ -5202,10 +5217,10 @@ QCPLineEnding::QCPLineEnding() : Creates a QCPLineEnding instance with the specified values. */ QCPLineEnding::QCPLineEnding(QCPLineEnding::EndingStyle style, double width, double length, bool inverted) : - mStyle(style), - mWidth(width), - mLength(length), - mInverted(inverted) + mStyle(style), + mWidth(width), + mLength(length), + mInverted(inverted) { } @@ -5214,29 +5229,29 @@ QCPLineEnding::QCPLineEnding(QCPLineEnding::EndingStyle style, double width, dou */ void QCPLineEnding::setStyle(QCPLineEnding::EndingStyle style) { - mStyle = style; + mStyle = style; } /*! Sets the width of the ending decoration, if the style supports it. On arrows, for example, the width defines the size perpendicular to the arrow's pointing direction. - + \see setLength */ void QCPLineEnding::setWidth(double width) { - mWidth = width; + mWidth = width; } /*! Sets the length of the ending decoration, if the style supports it. On arrows, for example, the length defines the size in pointing direction. - + \see setWidth */ void QCPLineEnding::setLength(double length) { - mLength = length; + mLength = length; } /*! @@ -5249,207 +5264,199 @@ void QCPLineEnding::setLength(double length) */ void QCPLineEnding::setInverted(bool inverted) { - mInverted = inverted; + mInverted = inverted; } /*! \internal - + Returns the maximum pixel radius the ending decoration might cover, starting from the position the decoration is drawn at (typically a line ending/\ref QCPItemPosition of an item). - + This is relevant for clipping. Only omit painting of the decoration when the position where the decoration is supposed to be drawn is farther away from the clipping rect than the returned distance. */ double QCPLineEnding::boundingDistance() const { - switch (mStyle) - { - case esNone: - return 0; - - case esFlatArrow: - case esSpikeArrow: - case esLineArrow: - case esSkewedBar: - return qSqrt(mWidth*mWidth+mLength*mLength); // items that have width and length - - case esDisc: - case esSquare: - case esDiamond: - case esBar: - case esHalfBar: - return mWidth*1.42; // items that only have a width -> width*sqrt(2) + switch (mStyle) { + case esNone: + return 0; - } - return 0; + case esFlatArrow: + case esSpikeArrow: + case esLineArrow: + case esSkewedBar: + return qSqrt(mWidth * mWidth + mLength * mLength); // items that have width and length + + case esDisc: + case esSquare: + case esDiamond: + case esBar: + case esHalfBar: + return mWidth * 1.42; // items that only have a width -> width*sqrt(2) + + } + return 0; } /*! Starting from the origin of this line ending (which is style specific), returns the length covered by the line ending symbol, in backward direction. - + For example, the \ref esSpikeArrow has a shorter real length than a \ref esFlatArrow, even if both have the same \ref setLength value, because the spike arrow has an inward curved back, which reduces the length along its center axis (the drawing origin for arrows is at the tip). - + This function is used for precise, style specific placement of line endings, for example in QCPAxes. */ double QCPLineEnding::realLength() const { - switch (mStyle) - { - case esNone: - case esLineArrow: - case esSkewedBar: - case esBar: - case esHalfBar: - return 0; - - case esFlatArrow: - return mLength; - - case esDisc: - case esSquare: - case esDiamond: - return mWidth*0.5; - - case esSpikeArrow: - return mLength*0.8; - } - return 0; + switch (mStyle) { + case esNone: + case esLineArrow: + case esSkewedBar: + case esBar: + case esHalfBar: + return 0; + + case esFlatArrow: + return mLength; + + case esDisc: + case esSquare: + case esDiamond: + return mWidth * 0.5; + + case esSpikeArrow: + return mLength * 0.8; + } + return 0; } /*! \internal - + 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 QCPVector2D &pos, const QCPVector2D &dir) const { - if (mStyle == esNone) - return; - - QCPVector2D lengthVec = dir.normalized() * mLength*(mInverted ? -1 : 1); - if (lengthVec.isNull()) - lengthVec = QCPVector2D(1, 0); - QCPVector2D widthVec = dir.normalized().perpendicular() * mWidth*0.5*(mInverted ? -1 : 1); - - QPen penBackup = painter->pen(); - QBrush brushBackup = painter->brush(); - QPen miterPen = penBackup; - miterPen.setJoinStyle(Qt::MiterJoin); // to make arrow heads spikey - QBrush brush(painter->pen().color(), Qt::SolidPattern); - switch (mStyle) - { - case esNone: break; - case esFlatArrow: - { - QPointF points[3] = {pos.toPointF(), - (pos-lengthVec+widthVec).toPointF(), - (pos-lengthVec-widthVec).toPointF() - }; - painter->setPen(miterPen); - painter->setBrush(brush); - painter->drawConvexPolygon(points, 3); - painter->setBrush(brushBackup); - painter->setPen(penBackup); - break; + if (mStyle == esNone) { + return; } - case esSpikeArrow: - { - QPointF points[4] = {pos.toPointF(), - (pos-lengthVec+widthVec).toPointF(), - (pos-lengthVec*0.8).toPointF(), - (pos-lengthVec-widthVec).toPointF() - }; - painter->setPen(miterPen); - painter->setBrush(brush); - painter->drawConvexPolygon(points, 4); - painter->setBrush(brushBackup); - painter->setPen(penBackup); - break; + + QCPVector2D lengthVec = dir.normalized() * mLength * (mInverted ? -1 : 1); + if (lengthVec.isNull()) { + lengthVec = QCPVector2D(1, 0); } - case esLineArrow: - { - QPointF points[3] = {(pos-lengthVec+widthVec).toPointF(), - pos.toPointF(), - (pos-lengthVec-widthVec).toPointF() - }; - painter->setPen(miterPen); - painter->drawPolyline(points, 3); - painter->setPen(penBackup); - break; + QCPVector2D widthVec = dir.normalized().perpendicular() * mWidth * 0.5 * (mInverted ? -1 : 1); + + QPen penBackup = painter->pen(); + QBrush brushBackup = painter->brush(); + QPen miterPen = penBackup; + miterPen.setJoinStyle(Qt::MiterJoin); // to make arrow heads spikey + QBrush brush(painter->pen().color(), Qt::SolidPattern); + switch (mStyle) { + case esNone: + break; + case esFlatArrow: { + QPointF points[3] = {pos.toPointF(), + (pos - lengthVec + widthVec).toPointF(), + (pos - lengthVec - widthVec).toPointF() + }; + painter->setPen(miterPen); + painter->setBrush(brush); + painter->drawConvexPolygon(points, 3); + painter->setBrush(brushBackup); + painter->setPen(penBackup); + break; + } + case esSpikeArrow: { + QPointF points[4] = {pos.toPointF(), + (pos - lengthVec + widthVec).toPointF(), + (pos - lengthVec * 0.8).toPointF(), + (pos - lengthVec - widthVec).toPointF() + }; + painter->setPen(miterPen); + painter->setBrush(brush); + painter->drawConvexPolygon(points, 4); + painter->setBrush(brushBackup); + painter->setPen(penBackup); + break; + } + case esLineArrow: { + QPointF points[3] = {(pos - lengthVec + widthVec).toPointF(), + pos.toPointF(), + (pos - lengthVec - widthVec).toPointF() + }; + painter->setPen(miterPen); + painter->drawPolyline(points, 3); + painter->setPen(penBackup); + break; + } + case esDisc: { + painter->setBrush(brush); + painter->drawEllipse(pos.toPointF(), mWidth * 0.5, mWidth * 0.5); + painter->setBrush(brushBackup); + break; + } + case esSquare: { + QCPVector2D widthVecPerp = widthVec.perpendicular(); + QPointF points[4] = {(pos - widthVecPerp + widthVec).toPointF(), + (pos - widthVecPerp - widthVec).toPointF(), + (pos + widthVecPerp - widthVec).toPointF(), + (pos + widthVecPerp + widthVec).toPointF() + }; + painter->setPen(miterPen); + painter->setBrush(brush); + painter->drawConvexPolygon(points, 4); + painter->setBrush(brushBackup); + painter->setPen(penBackup); + break; + } + case esDiamond: { + QCPVector2D widthVecPerp = widthVec.perpendicular(); + QPointF points[4] = {(pos - widthVecPerp).toPointF(), + (pos - widthVec).toPointF(), + (pos + widthVecPerp).toPointF(), + (pos + widthVec).toPointF() + }; + painter->setPen(miterPen); + painter->setBrush(brush); + painter->drawConvexPolygon(points, 4); + painter->setBrush(brushBackup); + painter->setPen(penBackup); + break; + } + case esBar: { + painter->drawLine((pos + widthVec).toPointF(), (pos - widthVec).toPointF()); + break; + } + case esHalfBar: { + painter->drawLine((pos + widthVec).toPointF(), pos.toPointF()); + break; + } + case esSkewedBar: { + QCPVector2D shift; + if (!qFuzzyIsNull(painter->pen().widthF()) || painter->modes().testFlag(QCPPainter::pmNonCosmetic)) { + shift = dir.normalized() * qMax(qreal(1.0), painter->pen().widthF()) * qreal(0.5); + } + // 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.2 * (mInverted ? -1 : 1) + shift).toPointF(), + (pos - widthVec - lengthVec * 0.2 * (mInverted ? -1 : 1) + shift).toPointF()); + break; + } } - case esDisc: - { - painter->setBrush(brush); - painter->drawEllipse(pos.toPointF(), mWidth*0.5, mWidth*0.5); - painter->setBrush(brushBackup); - break; - } - case esSquare: - { - QCPVector2D widthVecPerp = widthVec.perpendicular(); - QPointF points[4] = {(pos-widthVecPerp+widthVec).toPointF(), - (pos-widthVecPerp-widthVec).toPointF(), - (pos+widthVecPerp-widthVec).toPointF(), - (pos+widthVecPerp+widthVec).toPointF() - }; - painter->setPen(miterPen); - painter->setBrush(brush); - painter->drawConvexPolygon(points, 4); - painter->setBrush(brushBackup); - painter->setPen(penBackup); - break; - } - case esDiamond: - { - QCPVector2D widthVecPerp = widthVec.perpendicular(); - QPointF points[4] = {(pos-widthVecPerp).toPointF(), - (pos-widthVec).toPointF(), - (pos+widthVecPerp).toPointF(), - (pos+widthVec).toPointF() - }; - painter->setPen(miterPen); - painter->setBrush(brush); - painter->drawConvexPolygon(points, 4); - painter->setBrush(brushBackup); - painter->setPen(penBackup); - break; - } - case esBar: - { - painter->drawLine((pos+widthVec).toPointF(), (pos-widthVec).toPointF()); - break; - } - case esHalfBar: - { - painter->drawLine((pos+widthVec).toPointF(), pos.toPointF()); - break; - } - case esSkewedBar: - { - QCPVector2D shift; - if (!qFuzzyIsNull(painter->pen().widthF()) || painter->modes().testFlag(QCPPainter::pmNonCosmetic)) - shift = dir.normalized()*qMax(qreal(1.0), painter->pen().widthF())*qreal(0.5); - // 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.2*(mInverted?-1:1)+shift).toPointF(), - (pos-widthVec-lengthVec*0.2*(mInverted?-1:1)+shift).toPointF()); - break; - } - } } /*! \internal \overload - + Draws the line ending. The direction is controlled with the \a angle parameter in radians. */ void QCPLineEnding::draw(QCPPainter *painter, const QCPVector2D &pos, double angle) const { - draw(painter, pos, QCPVector2D(qCos(angle), qSin(angle))); + draw(painter, pos, QCPVector2D(qCos(angle), qSin(angle))); } /* end of 'src/lineending.cpp' */ @@ -5466,9 +5473,9 @@ void QCPLineEnding::draw(QCPPainter *painter, const QCPVector2D &pos, double ang \internal \brief (Private) - + This is a private class and not part of the public QCustomPlot interface. - + */ const QChar QCPLabelPainterPrivate::SymbolDot(183); @@ -5477,24 +5484,24 @@ const QChar QCPLabelPainterPrivate::SymbolCross(215); /*! Constructs a QCPLabelPainterPrivate instance. Make sure to not create a new instance on every redraw, to utilize the caching mechanisms. - + the \a parentPlot does not take ownership of the label painter. Make sure to delete it appropriately. */ QCPLabelPainterPrivate::QCPLabelPainterPrivate(QCustomPlot *parentPlot) : - mAnchorMode(amRectangular), - mAnchorSide(asLeft), - mAnchorReferenceType(artNormal), - mColor(Qt::black), - mPadding(0), - mRotation(0), - mSubstituteExponent(true), - mMultiplicationSymbol(QChar(215)), - mAbbreviateDecimalPowers(false), - mParentPlot(parentPlot), - mLabelCache(16) + mAnchorMode(amRectangular), + mAnchorSide(asLeft), + mAnchorReferenceType(artNormal), + mColor(Qt::black), + mPadding(0), + mRotation(0), + mSubstituteExponent(true), + mMultiplicationSymbol(QChar(215)), + mAbbreviateDecimalPowers(false), + mParentPlot(parentPlot), + mLabelCache(16) { - analyzeFontMetrics(); + analyzeFontMetrics(); } QCPLabelPainterPrivate::~QCPLabelPainterPrivate() @@ -5503,96 +5510,96 @@ QCPLabelPainterPrivate::~QCPLabelPainterPrivate() void QCPLabelPainterPrivate::setAnchorSide(AnchorSide side) { - mAnchorSide = side; + mAnchorSide = side; } void QCPLabelPainterPrivate::setAnchorMode(AnchorMode mode) { - mAnchorMode = mode; + mAnchorMode = mode; } void QCPLabelPainterPrivate::setAnchorReference(const QPointF &pixelPoint) { - mAnchorReference = pixelPoint; + mAnchorReference = pixelPoint; } void QCPLabelPainterPrivate::setAnchorReferenceType(AnchorReferenceType type) { - mAnchorReferenceType = type; + mAnchorReferenceType = type; } void QCPLabelPainterPrivate::setFont(const QFont &font) { - if (mFont != font) - { - mFont = font; - analyzeFontMetrics(); - } + if (mFont != font) { + mFont = font; + analyzeFontMetrics(); + } } void QCPLabelPainterPrivate::setColor(const QColor &color) { - mColor = color; + mColor = color; } void QCPLabelPainterPrivate::setPadding(int padding) { - mPadding = padding; + mPadding = padding; } void QCPLabelPainterPrivate::setRotation(double rotation) { - mRotation = qBound(-90.0, rotation, 90.0); + mRotation = qBound(-90.0, rotation, 90.0); } void QCPLabelPainterPrivate::setSubstituteExponent(bool enabled) { - mSubstituteExponent = enabled; + mSubstituteExponent = enabled; } void QCPLabelPainterPrivate::setMultiplicationSymbol(QChar symbol) { - mMultiplicationSymbol = symbol; + mMultiplicationSymbol = symbol; } void QCPLabelPainterPrivate::setAbbreviateDecimalPowers(bool enabled) { - mAbbreviateDecimalPowers = enabled; + mAbbreviateDecimalPowers = enabled; } void QCPLabelPainterPrivate::setCacheSize(int labelCount) { - mLabelCache.setMaxCost(labelCount); + mLabelCache.setMaxCost(labelCount); } int QCPLabelPainterPrivate::cacheSize() const { - return mLabelCache.maxCost(); + return mLabelCache.maxCost(); } void QCPLabelPainterPrivate::drawTickLabel(QCPPainter *painter, const QPointF &tickPos, const QString &text) { - double realRotation = mRotation; - - AnchorSide realSide = mAnchorSide; - // for circular axes, the anchor side is determined depending on the quadrant of tickPos with respect to mCircularReference - if (mAnchorMode == amSkewedUpright) - { - realSide = skewedAnchorSide(tickPos, 0.2, 0.3); - } else if (mAnchorMode == amSkewedRotated) // in this mode every label is individually rotated to match circle tangent - { - realSide = skewedAnchorSide(tickPos, 0, 0); - realRotation += QCPVector2D(tickPos-mAnchorReference).angle()/M_PI*180.0; - if (realRotation > 90) realRotation -= 180; - else if (realRotation < -90) realRotation += 180; - } - - realSide = rotationCorrectedSide(realSide, realRotation); // rotation angles may change the true anchor side of the label - drawLabelMaybeCached(painter, mFont, mColor, getAnchorPos(tickPos), realSide, realRotation, text); + double realRotation = mRotation; + + AnchorSide realSide = mAnchorSide; + // for circular axes, the anchor side is determined depending on the quadrant of tickPos with respect to mCircularReference + if (mAnchorMode == amSkewedUpright) { + realSide = skewedAnchorSide(tickPos, 0.2, 0.3); + } else if (mAnchorMode == amSkewedRotated) { // in this mode every label is individually rotated to match circle tangent + realSide = skewedAnchorSide(tickPos, 0, 0); + realRotation += QCPVector2D(tickPos - mAnchorReference).angle() / M_PI * 180.0; + if (realRotation > 90) { + realRotation -= 180; + } else if (realRotation < -90) { + realRotation += 180; + } + } + + realSide = rotationCorrectedSide(realSide, realRotation); // rotation angles may change the true anchor side of the label + drawLabelMaybeCached(painter, mFont, mColor, getAnchorPos(tickPos), realSide, realRotation, text); } /*! \internal - + Returns the size ("margin" in QCPAxisRect context, so measured perpendicular to the axis backbone direction) needed to fit the axis. */ @@ -5603,7 +5610,7 @@ int QCPLabelPainterPrivate::size() const // get length of tick marks pointing outwards: if (!tickPositions.isEmpty()) result += qMax(0, qMax(tickLengthOut, subTickLengthOut)); - + // calculate size of tick labels: if (tickLabelSide == QCPAxis::lsOutside) { @@ -5616,7 +5623,7 @@ int QCPLabelPainterPrivate::size() const result += tickLabelPadding; } } - + // calculate size of axis label (only height needed, because left/right labels are rotated by 90 degrees): if (!label.isEmpty()) { @@ -5631,18 +5638,18 @@ int QCPLabelPainterPrivate::size() const */ /*! \internal - + Clears the internal label cache. Upon the next \ref draw, all labels will be created new. This method is called automatically if any parameters have changed that invalidate the cached labels, such as font, color, etc. Usually you won't need to call this method manually. */ void QCPLabelPainterPrivate::clearCache() { - mLabelCache.clear(); + mLabelCache.clear(); } /*! \internal - + Returns a hash that allows uniquely identifying whether the label parameters have changed such that the cached labels must be refreshed (\ref clearCache). It is used in \ref draw. If the return value of this method hasn't changed since the last redraw, the respective label parameters @@ -5650,132 +5657,134 @@ void QCPLabelPainterPrivate::clearCache() */ QByteArray QCPLabelPainterPrivate::generateLabelParameterHash() const { - QByteArray result; - result.append(QByteArray::number(mParentPlot->bufferDevicePixelRatio())); - result.append(QByteArray::number(mRotation)); - //result.append(QByteArray::number((int)tickLabelSide)); TODO: check whether this is really a cache-invalidating property - result.append(QByteArray::number((int)mSubstituteExponent)); - result.append(QString(mMultiplicationSymbol).toUtf8()); - result.append(mColor.name().toLatin1()+QByteArray::number(mColor.alpha(), 16)); - result.append(mFont.toString().toLatin1()); - return result; + QByteArray result; + result.append(QByteArray::number(mParentPlot->bufferDevicePixelRatio())); + result.append(QByteArray::number(mRotation)); + //result.append(QByteArray::number((int)tickLabelSide)); TODO: check whether this is really a cache-invalidating property + result.append(QByteArray::number((int)mSubstituteExponent)); + result.append(QString(mMultiplicationSymbol).toUtf8()); + result.append(mColor.name().toLatin1() + QByteArray::number(mColor.alpha(), 16)); + result.append(mFont.toString().toLatin1()); + return result; } /*! \internal - + Draws a single tick label with the provided \a painter, utilizing the internal label cache to significantly speed up drawing of labels that were drawn in previous calls. The tick label is always bound to an axis, the distance to the axis is controllable via \a distanceToAxis in pixels. The pixel position in the axis direction is passed in the \a position parameter. Hence for the bottom axis, \a position would indicate the horizontal pixel position (not coordinate), at which the label should be drawn. - + In order to later draw the axis label in a place that doesn't overlap with the tick labels, the largest tick label size is needed. This is acquired by passing a \a tickLabelsSize to the \ref drawTickLabel calls during the process of drawing all tick labels of one axis. In every call, \a tickLabelsSize is expanded, if the drawn label exceeds the value \a tickLabelsSize currently holds. - + The label is drawn with the font and pen that are currently set on the \a painter. To draw superscripted powers, the font is temporarily made smaller by a fixed factor (see \ref getTickLabelData). */ void QCPLabelPainterPrivate::drawLabelMaybeCached(QCPPainter *painter, const QFont &font, const QColor &color, const QPointF &pos, AnchorSide side, double rotation, const QString &text) { - // warning: if you change anything here, also adapt getMaxTickLabelSize() accordingly! - if (text.isEmpty()) return; - QSize finalSize; + // warning: if you change anything here, also adapt getMaxTickLabelSize() accordingly! + if (text.isEmpty()) { + return; + } + QSize finalSize; - if (mParentPlot->plottingHints().testFlag(QCP::phCacheLabels) && !painter->modes().testFlag(QCPPainter::pmNoCaching)) // label caching enabled - { - QByteArray key = cacheKey(text, color, rotation, side); - CachedLabel *cachedLabel = mLabelCache.take(QString::fromUtf8(key)); // attempt to take label from cache (don't use object() because we want ownership/prevent deletion during our operations, we re-insert it afterwards) - if (!cachedLabel) // no cached label existed, create it - { - LabelData labelData = getTickLabelData(font, color, rotation, side, text); - cachedLabel = createCachedLabel(labelData); - } - // if label would be partly clipped by widget border on sides, don't draw it (only for outside tick labels): - bool labelClippedByBorder = false; - /* - if (tickLabelSide == QCPAxis::lsOutside) - { - if (QCPAxis::orientation(type) == Qt::Horizontal) + if (mParentPlot->plottingHints().testFlag(QCP::phCacheLabels) && !painter->modes().testFlag(QCPPainter::pmNoCaching)) { // label caching enabled + QByteArray key = cacheKey(text, color, rotation, side); + CachedLabel *cachedLabel = mLabelCache.take(QString::fromUtf8(key)); // attempt to take label from cache (don't use object() because we want ownership/prevent deletion during our operations, we re-insert it afterwards) + if (!cachedLabel) { // no cached label existed, create it + LabelData labelData = getTickLabelData(font, color, rotation, side, text); + cachedLabel = createCachedLabel(labelData); + } + // if label would be partly clipped by widget border on sides, don't draw it (only for outside tick labels): + bool labelClippedByBorder = false; + /* + if (tickLabelSide == QCPAxis::lsOutside) + { + if (QCPAxis::orientation(type) == Qt::Horizontal) labelClippedByBorder = labelAnchor.x()+cachedLabel->offset.x()+cachedLabel->pixmap.width()/mParentPlot->bufferDevicePixelRatio() > viewportRect.right() || labelAnchor.x()+cachedLabel->offset.x() < viewportRect.left(); - else + else labelClippedByBorder = labelAnchor.y()+cachedLabel->offset.y()+cachedLabel->pixmap.height()/mParentPlot->bufferDevicePixelRatio() > viewportRect.bottom() || labelAnchor.y()+cachedLabel->offset.y() < viewportRect.top(); - } - */ - if (!labelClippedByBorder) - { - painter->drawPixmap(pos+cachedLabel->offset, cachedLabel->pixmap); - finalSize = cachedLabel->pixmap.size()/mParentPlot->bufferDevicePixelRatio(); // TODO: collect this in a member rect list? - } - mLabelCache.insert(QString::fromUtf8(key), cachedLabel); - } else // label caching disabled, draw text directly on surface: - { - LabelData labelData = getTickLabelData(font, color, rotation, side, text); - // if label would be partly clipped by widget border on sides, don't draw it (only for outside tick labels): - bool labelClippedByBorder = false; - /* - if (tickLabelSide == QCPAxis::lsOutside) - { - if (QCPAxis::orientation(type) == Qt::Horizontal) + } + */ + if (!labelClippedByBorder) { + painter->drawPixmap(pos + cachedLabel->offset, cachedLabel->pixmap); + finalSize = cachedLabel->pixmap.size() / mParentPlot->bufferDevicePixelRatio(); // TODO: collect this in a member rect list? + } + mLabelCache.insert(QString::fromUtf8(key), cachedLabel); + } else { // label caching disabled, draw text directly on surface: + LabelData labelData = getTickLabelData(font, color, rotation, side, text); + // if label would be partly clipped by widget border on sides, don't draw it (only for outside tick labels): + bool labelClippedByBorder = false; + /* + if (tickLabelSide == QCPAxis::lsOutside) + { + if (QCPAxis::orientation(type) == Qt::Horizontal) labelClippedByBorder = finalPosition.x()+(labelData.rotatedTotalBounds.width()+labelData.rotatedTotalBounds.left()) > viewportRect.right() || finalPosition.x()+labelData.rotatedTotalBounds.left() < viewportRect.left(); - else + else labelClippedByBorder = finalPosition.y()+(labelData.rotatedTotalBounds.height()+labelData.rotatedTotalBounds.top()) > viewportRect.bottom() || finalPosition.y()+labelData.rotatedTotalBounds.top() < viewportRect.top(); + } + */ + if (!labelClippedByBorder) { + drawText(painter, pos, labelData); + finalSize = labelData.rotatedTotalBounds.size(); + } } - */ - if (!labelClippedByBorder) - { - drawText(painter, pos, labelData); - finalSize = labelData.rotatedTotalBounds.size(); - } - } - /* - // expand passed tickLabelsSize if current tick label is larger: - if (finalSize.width() > tickLabelsSize->width()) + /* + // expand passed tickLabelsSize if current tick label is larger: + if (finalSize.width() > tickLabelsSize->width()) tickLabelsSize->setWidth(finalSize.width()); - if (finalSize.height() > tickLabelsSize->height()) + if (finalSize.height() > tickLabelsSize->height()) tickLabelsSize->setHeight(finalSize.height()); - */ + */ } QPointF QCPLabelPainterPrivate::getAnchorPos(const QPointF &tickPos) { - switch (mAnchorMode) - { - case amRectangular: - { - switch (mAnchorSide) - { - case asLeft: return tickPos+QPointF(mPadding, 0); - case asRight: return tickPos+QPointF(-mPadding, 0); - case asTop: return tickPos+QPointF(0, mPadding); - case asBottom: return tickPos+QPointF(0, -mPadding); - case asTopLeft: return tickPos+QPointF(mPadding*M_SQRT1_2, mPadding*M_SQRT1_2); - case asTopRight: return tickPos+QPointF(-mPadding*M_SQRT1_2, mPadding*M_SQRT1_2); - case asBottomRight: return tickPos+QPointF(-mPadding*M_SQRT1_2, -mPadding*M_SQRT1_2); - case asBottomLeft: return tickPos+QPointF(mPadding*M_SQRT1_2, -mPadding*M_SQRT1_2); - } + switch (mAnchorMode) { + case amRectangular: { + switch (mAnchorSide) { + case asLeft: + return tickPos + QPointF(mPadding, 0); + case asRight: + return tickPos + QPointF(-mPadding, 0); + case asTop: + return tickPos + QPointF(0, mPadding); + case asBottom: + return tickPos + QPointF(0, -mPadding); + case asTopLeft: + return tickPos + QPointF(mPadding * M_SQRT1_2, mPadding * M_SQRT1_2); + case asTopRight: + return tickPos + QPointF(-mPadding * M_SQRT1_2, mPadding * M_SQRT1_2); + case asBottomRight: + return tickPos + QPointF(-mPadding * M_SQRT1_2, -mPadding * M_SQRT1_2); + case asBottomLeft: + return tickPos + QPointF(mPadding * M_SQRT1_2, -mPadding * M_SQRT1_2); + } + } + case amSkewedUpright: + case amSkewedRotated: { + QCPVector2D anchorNormal(tickPos - mAnchorReference); + if (mAnchorReferenceType == artTangent) { + anchorNormal = anchorNormal.perpendicular(); + } + anchorNormal.normalize(); + return tickPos + (anchorNormal * mPadding).toPointF(); + } } - case amSkewedUpright: - case amSkewedRotated: - { - QCPVector2D anchorNormal(tickPos-mAnchorReference); - if (mAnchorReferenceType == artTangent) - anchorNormal = anchorNormal.perpendicular(); - anchorNormal.normalize(); - return tickPos+(anchorNormal*mPadding).toPointF(); - } - } - return tickPos; + return tickPos; } /*! \internal - + This is a \ref placeTickLabel helper function. - + Draws the tick label specified in \a labelData with \a painter at the pixel positions \a x and \a y. This function is used by \ref placeTickLabel to create new tick labels for the cache, or to directly draw the labels on the QCustomPlot surface when label caching is disabled, i.e. when @@ -5783,148 +5792,155 @@ QPointF QCPLabelPainterPrivate::getAnchorPos(const QPointF &tickPos) */ void QCPLabelPainterPrivate::drawText(QCPPainter *painter, const QPointF &pos, const LabelData &labelData) const { - // backup painter settings that we're about to change: - QTransform oldTransform = painter->transform(); - QFont oldFont = painter->font(); - QPen oldPen = painter->pen(); - - // transform painter to position/rotation: - painter->translate(pos); - painter->setTransform(labelData.transform, true); - - // draw text: - painter->setFont(labelData.baseFont); - painter->setPen(QPen(labelData.color)); - if (!labelData.expPart.isEmpty()) // use superscripted exponent typesetting - { - 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 - { - painter->drawText(0, 0, labelData.totalBounds.width(), labelData.totalBounds.height(), Qt::TextDontClip | Qt::AlignHCenter, labelData.basePart); - } - - /* Debug code to draw label bounding boxes, baseline, and capheight - painter->save(); - painter->setPen(QPen(QColor(0, 0, 0, 150))); - painter->drawRect(labelData.totalBounds); - const int baseline = labelData.totalBounds.height()-mLetterDescent; - painter->setPen(QPen(QColor(255, 0, 0, 150))); - painter->drawLine(QLineF(0, baseline, labelData.totalBounds.width(), baseline)); - painter->setPen(QPen(QColor(0, 0, 255, 150))); - painter->drawLine(QLineF(0, baseline-mLetterCapHeight, labelData.totalBounds.width(), baseline-mLetterCapHeight)); - painter->restore(); - */ - - // reset painter settings to what it was before: - painter->setTransform(oldTransform); - painter->setFont(oldFont); - painter->setPen(oldPen); + // backup painter settings that we're about to change: + QTransform oldTransform = painter->transform(); + QFont oldFont = painter->font(); + QPen oldPen = painter->pen(); + + // transform painter to position/rotation: + painter->translate(pos); + painter->setTransform(labelData.transform, true); + + // draw text: + painter->setFont(labelData.baseFont); + painter->setPen(QPen(labelData.color)); + if (!labelData.expPart.isEmpty()) { // use superscripted exponent typesetting + 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 { + painter->drawText(0, 0, labelData.totalBounds.width(), labelData.totalBounds.height(), Qt::TextDontClip | Qt::AlignHCenter, labelData.basePart); + } + + /* Debug code to draw label bounding boxes, baseline, and capheight + painter->save(); + painter->setPen(QPen(QColor(0, 0, 0, 150))); + painter->drawRect(labelData.totalBounds); + const int baseline = labelData.totalBounds.height()-mLetterDescent; + painter->setPen(QPen(QColor(255, 0, 0, 150))); + painter->drawLine(QLineF(0, baseline, labelData.totalBounds.width(), baseline)); + painter->setPen(QPen(QColor(0, 0, 255, 150))); + painter->drawLine(QLineF(0, baseline-mLetterCapHeight, labelData.totalBounds.width(), baseline-mLetterCapHeight)); + painter->restore(); + */ + + // reset painter settings to what it was before: + painter->setTransform(oldTransform); + painter->setFont(oldFont); + painter->setPen(oldPen); } /*! \internal - + This is a \ref placeTickLabel helper function. - + Transforms the passed \a text and \a font to a tickLabelData structure that can then be further processed by \ref getTickLabelDrawOffset and \ref drawTickLabel. It splits the text into base and exponent if necessary (member substituteExponent) and calculates appropriate bounding boxes. */ QCPLabelPainterPrivate::LabelData QCPLabelPainterPrivate::getTickLabelData(const QFont &font, const QColor &color, double rotation, AnchorSide side, const QString &text) const { - LabelData result; - result.rotation = rotation; - result.side = side; - result.color = color; - - // determine whether beautiful decimal powers should be used - bool useBeautifulPowers = false; - 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 (mSubstituteExponent) - { - ePos = text.indexOf(QLatin1Char('e')); - 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; + LabelData result; + result.rotation = rotation; + result.side = side; + result.color = color; + + // determine whether beautiful decimal powers should be used + bool useBeautifulPowers = false; + 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 (mSubstituteExponent) { + ePos = text.indexOf(QLatin1Char('e')); + 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: - result.baseFont = font; - if (result.baseFont.pointSizeF() > 0) // might return -1 if specified with setPixelSize, in that case we can't do correction in next line - result.baseFont.setPointSizeF(result.baseFont.pointSizeF()+0.05); // QFontMetrics.boundingRect has a bug for exact point sizes that make the results oscillate due to internal rounding - - QFontMetrics baseFontMetrics(result.baseFont); - if (useBeautifulPowers) - { - // 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 (mAbbreviateDecimalPowers && result.basePart == QLatin1String("1")) - result.basePart = QLatin1String("10"); - else - result.basePart += QString(mMultiplicationSymbol) + QLatin1String("10"); - 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); - if (!result.expPart.isEmpty() && result.expPart.at(0) == QLatin1Char('+')) - result.expPart.remove(0, 1); - // prepare smaller font for exponent: - result.expFont = font; - if (result.expFont.pointSize() > 0) - result.expFont.setPointSize(result.expFont.pointSize()*0.75); - else - result.expFont.setPixelSize(result.expFont.pixelSize()*0.75); - // calculate bounding rects of base part(s), exponent part and total one: - result.baseBounds = baseFontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.basePart); - result.expBounds = QFontMetrics(result.expFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.expPart); - 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; - result.totalBounds = baseFontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip | Qt::AlignHCenter, result.basePart); - } - result.totalBounds.moveTopLeft(QPoint(0, 0)); - applyAnchorTransform(result); - result.rotatedTotalBounds = result.transform.mapRect(result.totalBounds); - - return result; + + // calculate text bounding rects and do string preparation for beautiful decimal powers: + result.baseFont = font; + if (result.baseFont.pointSizeF() > 0) { // might return -1 if specified with setPixelSize, in that case we can't do correction in next line + result.baseFont.setPointSizeF(result.baseFont.pointSizeF() + 0.05); // QFontMetrics.boundingRect has a bug for exact point sizes that make the results oscillate due to internal rounding + } + + QFontMetrics baseFontMetrics(result.baseFont); + if (useBeautifulPowers) { + // 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 (mAbbreviateDecimalPowers && result.basePart == QLatin1String("1")) { + result.basePart = QLatin1String("10"); + } else { + result.basePart += QString(mMultiplicationSymbol) + QLatin1String("10"); + } + 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); + } + if (!result.expPart.isEmpty() && result.expPart.at(0) == QLatin1Char('+')) { + result.expPart.remove(0, 1); + } + // prepare smaller font for exponent: + result.expFont = font; + if (result.expFont.pointSize() > 0) { + result.expFont.setPointSize(result.expFont.pointSize() * 0.75); + } else { + result.expFont.setPixelSize(result.expFont.pixelSize() * 0.75); + } + // calculate bounding rects of base part(s), exponent part and total one: + result.baseBounds = baseFontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.basePart); + result.expBounds = QFontMetrics(result.expFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.expPart); + 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; + result.totalBounds = baseFontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip | Qt::AlignHCenter, result.basePart); + } + result.totalBounds.moveTopLeft(QPoint(0, 0)); + applyAnchorTransform(result); + result.rotatedTotalBounds = result.transform.mapRect(result.totalBounds); + + return result; } void QCPLabelPainterPrivate::applyAnchorTransform(LabelData &labelData) const { - if (!qFuzzyIsNull(labelData.rotation)) - labelData.transform.rotate(labelData.rotation); // rotates effectively clockwise (due to flipped y axis of painter vs widget coordinate system) - - // from now on we translate in rotated label-local coordinate system. - // shift origin of coordinate system to appropriate point on label: - labelData.transform.translate(0, -labelData.totalBounds.height()+mLetterDescent+mLetterCapHeight); // shifts origin to true top of capital (or number) characters - - if (labelData.side == asLeft || labelData.side == asRight) // anchor is centered vertically - labelData.transform.translate(0, -mLetterCapHeight/2.0); - else if (labelData.side == asTop || labelData.side == asBottom) // anchor is centered horizontally - labelData.transform.translate(-labelData.totalBounds.width()/2.0, 0); - - if (labelData.side == asTopRight || labelData.side == asRight || labelData.side == asBottomRight) // anchor is at right - labelData.transform.translate(-labelData.totalBounds.width(), 0); - if (labelData.side == asBottomLeft || labelData.side == asBottom || labelData.side == asBottomRight) // anchor is at bottom (no elseif!) - labelData.transform.translate(0, -mLetterCapHeight); + if (!qFuzzyIsNull(labelData.rotation)) { + labelData.transform.rotate(labelData.rotation); // rotates effectively clockwise (due to flipped y axis of painter vs widget coordinate system) + } + + // from now on we translate in rotated label-local coordinate system. + // shift origin of coordinate system to appropriate point on label: + labelData.transform.translate(0, -labelData.totalBounds.height() + mLetterDescent + mLetterCapHeight); // shifts origin to true top of capital (or number) characters + + if (labelData.side == asLeft || labelData.side == asRight) { // anchor is centered vertically + labelData.transform.translate(0, -mLetterCapHeight / 2.0); + } else if (labelData.side == asTop || labelData.side == asBottom) { // anchor is centered horizontally + labelData.transform.translate(-labelData.totalBounds.width() / 2.0, 0); + } + + if (labelData.side == asTopRight || labelData.side == asRight || labelData.side == asBottomRight) { // anchor is at right + labelData.transform.translate(-labelData.totalBounds.width(), 0); + } + if (labelData.side == asBottomLeft || labelData.side == asBottom || labelData.side == asBottomRight) { // anchor is at bottom (no elseif!) + labelData.transform.translate(0, -mLetterCapHeight); + } } /*! \internal - + Simulates the steps done by \ref placeTickLabel by calculating bounding boxes of the text label to be drawn, depending on number format etc. Since only the largest tick label is wanted for the margin calculation, the passed \a tickLabelsSize is only expanded, if it's currently set to a @@ -5944,7 +5960,7 @@ void QCPLabelPainterPrivate::getMaxTickLabelSize(const QFont &font, const QStrin // TODO: LabelData labelData = getTickLabelData(font, text); // TODO: finalSize = labelData.rotatedTotalBounds.size(); } - + // expand passed tickLabelsSize if current tick label is larger: if (finalSize.width() > tickLabelsSize->width()) tickLabelsSize->setWidth(finalSize.width()); @@ -5955,100 +5971,122 @@ void QCPLabelPainterPrivate::getMaxTickLabelSize(const QFont &font, const QStrin QCPLabelPainterPrivate::CachedLabel *QCPLabelPainterPrivate::createCachedLabel(const LabelData &labelData) const { - CachedLabel *result = new CachedLabel; - - // allocate pixmap with the correct size and pixel ratio: - if (!qFuzzyCompare(1.0, mParentPlot->bufferDevicePixelRatio())) - { - result->pixmap = QPixmap(labelData.rotatedTotalBounds.size()*mParentPlot->bufferDevicePixelRatio()); + CachedLabel *result = new CachedLabel; + + // allocate pixmap with the correct size and pixel ratio: + if (!qFuzzyCompare(1.0, mParentPlot->bufferDevicePixelRatio())) { + result->pixmap = QPixmap(labelData.rotatedTotalBounds.size() * mParentPlot->bufferDevicePixelRatio()); #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED # ifdef QCP_DEVICEPIXELRATIO_FLOAT - result->pixmap.setDevicePixelRatio(mParentPlot->devicePixelRatioF()); + result->pixmap.setDevicePixelRatio(mParentPlot->devicePixelRatioF()); # else - result->pixmap.setDevicePixelRatio(mParentPlot->devicePixelRatio()); + result->pixmap.setDevicePixelRatio(mParentPlot->devicePixelRatio()); # endif #endif - } else - result->pixmap = QPixmap(labelData.rotatedTotalBounds.size()); - result->pixmap.fill(Qt::transparent); - - // draw the label into the pixmap - // offset is between label anchor and topleft of cache pixmap, so pixmap can be drawn at pos+offset to make the label anchor appear at pos. - // We use rotatedTotalBounds.topLeft() because rotatedTotalBounds is in a coordinate system where the label anchor is at (0, 0) - result->offset = labelData.rotatedTotalBounds.topLeft(); - QCPPainter cachePainter(&result->pixmap); - drawText(&cachePainter, -result->offset, labelData); - return result; + } else { + result->pixmap = QPixmap(labelData.rotatedTotalBounds.size()); + } + result->pixmap.fill(Qt::transparent); + + // draw the label into the pixmap + // offset is between label anchor and topleft of cache pixmap, so pixmap can be drawn at pos+offset to make the label anchor appear at pos. + // We use rotatedTotalBounds.topLeft() because rotatedTotalBounds is in a coordinate system where the label anchor is at (0, 0) + result->offset = labelData.rotatedTotalBounds.topLeft(); + QCPPainter cachePainter(&result->pixmap); + drawText(&cachePainter, -result->offset, labelData); + return result; } QByteArray QCPLabelPainterPrivate::cacheKey(const QString &text, const QColor &color, double rotation, AnchorSide side) const { - return text.toUtf8()+ - QByteArray::number(color.red()+256*color.green()+65536*color.blue(), 36)+ - QByteArray::number(color.alpha()+256*(int)side, 36)+ - QByteArray::number((int)(rotation*100)%36000, 36); + return text.toUtf8() + + QByteArray::number(color.red() + 256 * color.green() + 65536 * color.blue(), 36) + + QByteArray::number(color.alpha() + 256 * (int)side, 36) + + QByteArray::number((int)(rotation * 100) % 36000, 36); } QCPLabelPainterPrivate::AnchorSide QCPLabelPainterPrivate::skewedAnchorSide(const QPointF &tickPos, double sideExpandHorz, double sideExpandVert) const { - QCPVector2D anchorNormal = QCPVector2D(tickPos-mAnchorReference); - if (mAnchorReferenceType == artTangent) - anchorNormal = anchorNormal.perpendicular(); - const double radius = anchorNormal.length(); - const double sideHorz = sideExpandHorz*radius; - const double sideVert = sideExpandVert*radius; - if (anchorNormal.x() > sideHorz) - { - if (anchorNormal.y() > sideVert) return asTopLeft; - else if (anchorNormal.y() < -sideVert) return asBottomLeft; - else return asLeft; - } else if (anchorNormal.x() < -sideHorz) - { - if (anchorNormal.y() > sideVert) return asTopRight; - else if (anchorNormal.y() < -sideVert) return asBottomRight; - else return asRight; - } else - { - if (anchorNormal.y() > 0) return asTop; - else return asBottom; - } - return asBottom; // should never be reached + QCPVector2D anchorNormal = QCPVector2D(tickPos - mAnchorReference); + if (mAnchorReferenceType == artTangent) { + anchorNormal = anchorNormal.perpendicular(); + } + const double radius = anchorNormal.length(); + const double sideHorz = sideExpandHorz * radius; + const double sideVert = sideExpandVert * radius; + if (anchorNormal.x() > sideHorz) { + if (anchorNormal.y() > sideVert) { + return asTopLeft; + } else if (anchorNormal.y() < -sideVert) { + return asBottomLeft; + } else { + return asLeft; + } + } else if (anchorNormal.x() < -sideHorz) { + if (anchorNormal.y() > sideVert) { + return asTopRight; + } else if (anchorNormal.y() < -sideVert) { + return asBottomRight; + } else { + return asRight; + } + } else { + if (anchorNormal.y() > 0) { + return asTop; + } else { + return asBottom; + } + } + return asBottom; // should never be reached } QCPLabelPainterPrivate::AnchorSide QCPLabelPainterPrivate::rotationCorrectedSide(AnchorSide side, double rotation) const { - AnchorSide result = side; - const bool rotateClockwise = rotation > 0; - if (!qFuzzyIsNull(rotation)) - { - if (!qFuzzyCompare(qAbs(rotation), 90)) // avoid graphical collision with anchor tangent (e.g. axis line) when rotating, so change anchor side appropriately: - { - if (side == asTop) result = rotateClockwise ? asLeft : asRight; - else if (side == asBottom) result = rotateClockwise ? asRight : asLeft; - else if (side == asTopLeft) result = rotateClockwise ? asLeft : asTop; - else if (side == asTopRight) result = rotateClockwise ? asTop : asRight; - else if (side == asBottomLeft) result = rotateClockwise ? asBottom : asLeft; - else if (side == asBottomRight) result = rotateClockwise ? asRight : asBottom; - } else // for full rotation by +/-90 degrees, other sides are more appropriate for centering on anchor: - { - if (side == asLeft) result = rotateClockwise ? asBottom : asTop; - else if (side == asRight) result = rotateClockwise ? asTop : asBottom; - else if (side == asTop) result = rotateClockwise ? asLeft : asRight; - else if (side == asBottom) result = rotateClockwise ? asRight : asLeft; - else if (side == asTopLeft) result = rotateClockwise ? asBottomLeft : asTopRight; - else if (side == asTopRight) result = rotateClockwise ? asTopLeft : asBottomRight; - else if (side == asBottomLeft) result = rotateClockwise ? asBottomRight : asTopLeft; - else if (side == asBottomRight) result = rotateClockwise ? asTopRight : asBottomLeft; + AnchorSide result = side; + const bool rotateClockwise = rotation > 0; + if (!qFuzzyIsNull(rotation)) { + if (!qFuzzyCompare(qAbs(rotation), 90)) { // avoid graphical collision with anchor tangent (e.g. axis line) when rotating, so change anchor side appropriately: + if (side == asTop) { + result = rotateClockwise ? asLeft : asRight; + } else if (side == asBottom) { + result = rotateClockwise ? asRight : asLeft; + } else if (side == asTopLeft) { + result = rotateClockwise ? asLeft : asTop; + } else if (side == asTopRight) { + result = rotateClockwise ? asTop : asRight; + } else if (side == asBottomLeft) { + result = rotateClockwise ? asBottom : asLeft; + } else if (side == asBottomRight) { + result = rotateClockwise ? asRight : asBottom; + } + } else { // for full rotation by +/-90 degrees, other sides are more appropriate for centering on anchor: + if (side == asLeft) { + result = rotateClockwise ? asBottom : asTop; + } else if (side == asRight) { + result = rotateClockwise ? asTop : asBottom; + } else if (side == asTop) { + result = rotateClockwise ? asLeft : asRight; + } else if (side == asBottom) { + result = rotateClockwise ? asRight : asLeft; + } else if (side == asTopLeft) { + result = rotateClockwise ? asBottomLeft : asTopRight; + } else if (side == asTopRight) { + result = rotateClockwise ? asTopLeft : asBottomRight; + } else if (side == asBottomLeft) { + result = rotateClockwise ? asBottomRight : asTopLeft; + } else if (side == asBottomRight) { + result = rotateClockwise ? asTopRight : asBottomLeft; + } + } } - } - return result; + return result; } void QCPLabelPainterPrivate::analyzeFontMetrics() { - const QFontMetrics fm(mFont); - mLetterCapHeight = fm.tightBoundingRect(QLatin1String("8")).height(); // this method is slow, that's why we query it only upon font change - mLetterDescent = fm.descent(); + const QFontMetrics fm(mFont); + mLetterCapHeight = fm.tightBoundingRect(QLatin1String("8")).height(); // this method is slow, that's why we query it only upon font change + mLetterDescent = fm.descent(); } /* end of 'src/axis/labelpainter.cpp' */ @@ -6061,12 +6099,12 @@ void QCPLabelPainterPrivate::analyzeFontMetrics() //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \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. @@ -6074,10 +6112,10 @@ void QCPLabelPainterPrivate::analyzeFontMetrics() 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: - +
@@ -6089,25 +6127,25 @@ void QCPLabelPainterPrivate::analyzeFontMetrics() \image html axisticker-time2.png
QCPAxisTickerFixed\image html axisticker-fixed.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. */ @@ -6117,15 +6155,15 @@ void QCPLabelPainterPrivate::analyzeFontMetrics() managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker. */ QCPAxisTicker::QCPAxisTicker() : - mTickStepStrategy(tssReadability), - mTickCount(5), - mTickOrigin(0) + mTickStepStrategy(tssReadability), + mTickCount(5), + mTickOrigin(0) { } QCPAxisTicker::~QCPAxisTicker() { - + } /*! @@ -6134,7 +6172,7 @@ QCPAxisTicker::~QCPAxisTicker() */ void QCPAxisTicker::setTickStepStrategy(QCPAxisTicker::TickStepStrategy strategy) { - mTickStepStrategy = strategy; + mTickStepStrategy = strategy; } /*! @@ -6147,33 +6185,34 @@ void QCPAxisTicker::setTickStepStrategy(QCPAxisTicker::TickStepStrategy strategy */ void QCPAxisTicker::setTickCount(int count) { - if (count > 0) - mTickCount = count; - else - qDebug() << Q_FUNC_INFO << "tick count must be greater than zero:" << 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; + 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 \c nullptr if not needed) and are respectively filled with sub tick coordinates, and tick label strings belonging @@ -6181,110 +6220,142 @@ void QCPAxisTicker::setTickOrigin(double origin) */ 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.isEmpty()) - { - *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); + // 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.isEmpty()) { + *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); + 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 = int(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 + 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 = int(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 } - } 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; + + 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 @@ -6292,44 +6363,45 @@ int QCPAxisTicker::getSubTickCount(double tickStep) */ QString QCPAxisTicker::getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision) { - return locale.toString(tick, formatChar.toLatin1(), 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) + QVector result; + if (subTickCount <= 0 || ticks.size() < 2) { + return result; + } + + result.reserve((ticks.size() - 1)*subTickCount); + for (int i = 1; i < ticks.size(); ++i) { + double subTickStep = (ticks.at(i) - ticks.at(i - 1)) / double(subTickCount + 1); + for (int k = 1; k <= subTickCount; ++k) { + result.append(ticks.at(i - 1) + k * subTickStep); + } + } return result; - - result.reserve((ticks.size()-1)*subTickCount); - for (int i=1; i QCPAxisTicker::createSubTickVector(int subTickCount, const QVect */ QVector QCPAxisTicker::createTickVector(double tickStep, const QCPRange &range) { - QVector result; - // Generate tick positions according to tickStep: - qint64 firstStep = qint64(floor((range.lower-mTickOrigin)/tickStep)); // do not use qFloor here, or we'll lose 64 bit precision - qint64 lastStep = qint64(ceil((range.upper-mTickOrigin)/tickStep)); // do not use qCeil here, or we'll lose 64 bit precision - int tickcount = int(lastStep-firstStep+1); - if (tickcount < 0) tickcount = 0; - result.resize(tickcount); - for (int i=0; i result; + // Generate tick positions according to tickStep: + qint64 firstStep = qint64(floor((range.lower - mTickOrigin) / tickStep)); // do not use qFloor here, or we'll lose 64 bit precision + qint64 lastStep = qint64(ceil((range.upper - mTickOrigin) / tickStep)); // do not use qCeil here, or we'll lose 64 bit precision + int tickcount = int(lastStep - firstStep + 1); + if (tickcount < 0) { + tickcount = 0; + } + result.resize(tickcount); + for (int i = 0; i < tickcount; ++i) { + result[i] = mTickOrigin + (firstStep + i) * tickStep; + } + return result; } /*! \internal - + Returns a vector containing all tick label strings corresponding to the tick coordinates provided in \a ticks. The default implementation calls \ref getTickLabel to generate the respective strings. - + It is possible but uncommon for QCPAxisTicker subclasses to reimplement this method, as reimplementing \ref getTickLabel often achieves the intended result easier. */ QVector QCPAxisTicker::createLabelVector(const QVector &ticks, const QLocale &locale, QChar formatChar, int precision) { - QVector result; - result.reserve(ticks.size()); - foreach (double tickCoord, ticks) - result.append(getTickLabel(tickCoord, locale, formatChar, precision)); - return result; + QVector result; + result.reserve(ticks.size()); + foreach (double tickCoord, ticks) { + result.append(getTickLabel(tickCoord, locale, formatChar, precision)); + } + return result; } /*! \internal - + Removes tick coordinates from \a ticks which lie outside the specified \a range. If \a keepOneOutlier is true, it preserves one tick just outside the range on both sides, if present. - + The passed \a ticks must be sorted in ascending order. */ void QCPAxisTicker::trimTicks(const QCPRange &range, QVector &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; + 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; + 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(); } - } - - 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; + 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; + 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; + 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 + } + } } - 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; + return input; } /* end of 'src/axis/axisticker.cpp' */ @@ -6481,9 +6556,9 @@ double QCPAxisTicker::cleanMantissa(double input) const //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \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 @@ -6491,26 +6566,26 @@ double QCPAxisTicker::cleanMantissa(double input) const 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 or time zone shall be used for the tick label appearance, see \ref setDateTimeSpec or \ref setTimeZone, respectively. - + 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. @@ -6521,17 +6596,17 @@ double QCPAxisTicker::cleanMantissa(double input) const 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) + mDateTimeFormat(QLatin1String("hh:mm:ss\ndd.MM.yy")), + mDateTimeSpec(Qt::LocalTime), + mDateStrategy(dsNone) { - setTickCount(4); + 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(). - + Typical expressions are @@ -6558,16 +6633,16 @@ QCPAxisTickerDateTime::QCPAxisTickerDateTime() :
\c dThe day as a number without a leading zero (1 to 31)
\c ap or \c aUse am/pm display. a/ap will be replaced by a lower-case version of either QLocale::amText() or QLocale::pmText().
\c tThe timezone (for example "CEST")
- + Newlines can be inserted with \c "\n", literal strings (even when containing above expressions) by encapsulating them using single-quotes. A literal single quote can be generated by using two consecutive single quotes in the format. - + \see setDateTimeSpec, setTimeZone */ void QCPAxisTickerDateTime::setDateTimeFormat(const QString &format) { - mDateTimeFormat = format; + mDateTimeFormat = format; } /*! @@ -6576,29 +6651,29 @@ void QCPAxisTickerDateTime::setDateTimeFormat(const QString &format) The default value of QDateTime objects (and also QCPAxisTickerDateTime) is Qt::LocalTime. However, if the displayed tick labels shall be given in UTC, set \a spec to Qt::UTC. - + Tick labels corresponding to other time zones can be achieved with \ref setTimeZone (which sets \a spec to \c Qt::TimeZone internally). Note that if \a spec is afterwards set to not be \c Qt::TimeZone again, the \ref setTimeZone setting will be ignored accordingly. - + \see setDateTimeFormat, setTimeZone */ void QCPAxisTickerDateTime::setDateTimeSpec(Qt::TimeSpec spec) { - mDateTimeSpec = spec; + mDateTimeSpec = spec; } # if QT_VERSION >= QT_VERSION_CHECK(5, 2, 0) /*! Sets the time zone that is used for creating the tick labels from corresponding dates/times. The time spec (\ref setDateTimeSpec) is set to \c Qt::TimeZone. - + \see setDateTimeFormat, setTimeZone */ void QCPAxisTickerDateTime::setTimeZone(const QTimeZone &zone) { - mTimeZone = zone; - mDateTimeSpec = Qt::TimeZone; + mTimeZone = zone; + mDateTimeSpec = Qt::TimeZone; } #endif @@ -6606,225 +6681,257 @@ void QCPAxisTickerDateTime::setTimeZone(const QTimeZone &zone) 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); + 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)); + 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; // leaving it at dsNone means tick coordinates will not be tuned in any special way in createTickVector - 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; + double result = range.size() / double(mTickCount + 1e-10); // mTickCount ticks on average, the small addition is to prevent jitter on exact integers + + mDateStrategy = dsNone; // leaving it at dsNone means tick coordinates will not be tuned in any special way in createTickVector + 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; + 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), time spec (\ref setDateTimeSpec), and possibly time zone (\ref setTimeZone). - + \seebaseclassmethod */ QString QCPAxisTickerDateTime::getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision) { - Q_UNUSED(precision) - Q_UNUSED(formatChar) + Q_UNUSED(precision) + Q_UNUSED(formatChar) # if QT_VERSION >= QT_VERSION_CHECK(5, 2, 0) - if (mDateTimeSpec == Qt::TimeZone) - return locale.toString(keyToDateTime(tick).toTimeZone(mTimeZone), mDateTimeFormat); - else - return locale.toString(keyToDateTime(tick).toTimeSpec(mDateTimeSpec), mDateTimeFormat); + if (mDateTimeSpec == Qt::TimeZone) { + return locale.toString(keyToDateTime(tick).toTimeZone(mTimeZone), mDateTimeFormat); + } else { + return locale.toString(keyToDateTime(tick).toTimeSpec(mDateTimeSpec), mDateTimeFormat); + } # else - return locale.toString(keyToDateTime(tick).toTimeSpec(mDateTimeSpec), mDateTimeFormat); + return locale.toString(keyToDateTime(tick).toTimeSpec(mDateTimeSpec), mDateTimeFormat); # endif } /*! \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); - } + 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 < result.size(); ++i) { + tickDateTime = keyToDateTime(result.at(i)); + tickDateTime.setTime(uniformDateTime.time()); + result[i] = dateTimeToKey(tickDateTime); + } + } else if (mDateStrategy == dsUniformDayInMonth) { + QDateTime uniformDateTime = keyToDateTime(mTickOrigin); // this day (in month) and time will be set for all other ticks, if possible + QDateTime tickDateTime; + for (int i = 0; i < result.size(); ++i) { + tickDateTime = keyToDateTime(result.at(i)); + tickDateTime.setTime(uniformDateTime.time()); + int thisUniformDay = uniformDateTime.date().day() <= tickDateTime.date().daysInMonth() ? uniformDateTime.date().day() : tickDateTime.date().daysInMonth(); // don't exceed month (e.g. try to set day 31 in February) + if (thisUniformDay - tickDateTime.date().day() < -15) { // with leap years involved, date month may jump backwards or forwards, and needs to be corrected before setting day + tickDateTime = tickDateTime.addMonths(1); + } else if (thisUniformDay - tickDateTime.date().day() > 15) { // with leap years involved, date month may jump backwards or forwards, and needs to be corrected before setting day + tickDateTime = tickDateTime.addMonths(-1); + } + tickDateTime.setDate(QDate(tickDateTime.date().year(), tickDateTime.date().month(), thisUniformDay)); + result[i] = dateTimeToKey(tickDateTime); + } + } } - } - return result; + 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); + return QDateTime::fromTime_t(key).addMSecs((key - (qint64)key) * 1000); # else - return QDateTime::fromMSecsSinceEpoch(qint64(key*1000.0)); + return QDateTime::fromMSecsSinceEpoch(qint64(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; + return dateTime.toTime_t() + dateTime.time().msec() / 1000.0; # else - return dateTime.toMSecsSinceEpoch()/1000.0; + 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. - + The returned value will be the start of the passed day of \a date, interpreted in the given \a timeSpec. - + \see keyToDateTime */ double QCPAxisTickerDateTime::dateTimeToKey(const QDate &date, Qt::TimeSpec timeSpec) { # if QT_VERSION < QT_VERSION_CHECK(4, 7, 0) - return QDateTime(date, QTime(0, 0), timeSpec).toTime_t(); + return QDateTime(date, QTime(0, 0), timeSpec).toTime_t(); # elif QT_VERSION < QT_VERSION_CHECK(5, 14, 0) - return QDateTime(date, QTime(0, 0), timeSpec).toMSecsSinceEpoch()/1000.0; + return QDateTime(date, QTime(0, 0), timeSpec).toMSecsSinceEpoch() / 1000.0; # else - return date.startOfDay(timeSpec).toMSecsSinceEpoch()/1000.0; + return date.startOfDay(timeSpec).toMSecsSinceEpoch() / 1000.0; # endif } /* end of 'src/axis/axistickerdatetime.cpp' */ @@ -6838,16 +6945,16 @@ double QCPAxisTickerDateTime::dateTimeToKey(const QDate &date, Qt::TimeSpec time //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \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 @@ -6855,19 +6962,19 @@ double QCPAxisTickerDateTime::dateTimeToKey(const QDate &date, Qt::TimeSpec time 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. */ @@ -6877,36 +6984,36 @@ double QCPAxisTickerDateTime::dateTimeToKey(const QDate &date, Qt::TimeSpec time managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker. */ QCPAxisTickerTime::QCPAxisTickerTime() : - mTimeFormat(QLatin1String("%h:%m:%s")), - mSmallestUnit(tuSeconds), - mBiggestUnit(tuHours) + 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"); + 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 @@ -6915,38 +7022,35 @@ QCPAxisTickerTime::QCPAxisTickerTime() : */ 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; + 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); + mFieldWidth[unit] = qMax(width, 1); } /*! \internal @@ -6955,126 +7059,153 @@ void QCPAxisTickerTime::setFieldWidth(QCPAxisTickerTime::TimeUnit unit, int widt 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; + 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; + 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; + 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); + 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' */ @@ -7087,20 +7218,20 @@ void QCPAxisTickerTime::replaceUnit(QString &text, QCPAxisTickerTime::TimeUnit u //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \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 */ @@ -7110,14 +7241,14 @@ void QCPAxisTickerTime::replaceUnit(QString &text, QCPAxisTickerTime::TimeUnit u managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker. */ QCPAxisTickerFixed::QCPAxisTickerFixed() : - mTickStep(1.0), - mScaleStrategy(ssNone) + 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 @@ -7126,57 +7257,55 @@ QCPAxisTickerFixed::QCPAxisTickerFixed() : */ void QCPAxisTickerFixed::setTickStep(double step) { - if (step > 0) - mTickStep = step; - else - qDebug() << Q_FUNC_INFO << "tick step must be greater than zero:" << 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; + 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; + 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)); + } } - 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; + return mTickStep; } /* end of 'src/axis/axistickerfixed.cpp' */ @@ -7189,20 +7318,20 @@ double QCPAxisTickerFixed::getTickStep(const QCPRange &range) //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \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 */ @@ -7210,7 +7339,7 @@ double QCPAxisTickerFixed::getTickStep(const QCPRange &range) /* 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. @@ -7225,37 +7354,37 @@ double QCPAxisTickerFixed::getTickStep(const QCPRange &range) managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker. */ QCPAxisTickerText::QCPAxisTickerText() : - mSubTickCount(0) + 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; + 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); + clear(); + addTicks(positions, labels); } /*! @@ -7265,135 +7394,144 @@ void QCPAxisTickerText::setTicks(const QVector &positions, const QVector */ void QCPAxisTickerText::setSubTickCount(int subTicks) { - if (subTicks >= 0) - mSubTickCount = subTicks; - else - qDebug() << Q_FUNC_INFO << "sub tick count can't be negative:" << 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(); + 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, const QString &label) { - mTicks.insert(position, 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) { #if QT_VERSION < QT_VERSION_CHECK(5, 15, 0) - mTicks.unite(ticks); + mTicks.unite(ticks); #else - mTicks.insert(ticks); + mTicks.insert(ticks); #endif } /*! \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()) + 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; - - 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' */ @@ -7406,16 +7544,16 @@ QVector QCPAxisTickerText::createTickVector(double tickStep, const QCPRa //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \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 */ @@ -7425,25 +7563,25 @@ QVector QCPAxisTickerText::createTickVector(double tickStep, const QCPRa 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) + mPiSymbol(QLatin1String(" ") + QChar(0x03C0)), + mPiValue(M_PI), + mPeriodicity(0), + mFractionStyle(fsUnicodeFractions), + mPiTickStep(0) { - setTickCount(4); + 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; + mPiSymbol = symbol; } /*! @@ -7454,20 +7592,20 @@ void QCPAxisTickerPi::setPiSymbol(QString symbol) */ void QCPAxisTickerPi::setPiValue(double pi) { - mPiValue = 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); + mPeriodicity = qAbs(multiplesOfPi); } /*! @@ -7476,211 +7614,215 @@ void QCPAxisTickerPi::setPeriodicity(int multiplesOfPi) */ void QCPAxisTickerPi::setFractionStyle(QCPAxisTickerPi::FractionStyle style) { - mFractionStyle = 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; + 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); + 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; - } + 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; + if (numerator == 0 || denominator == 0) { + return; + } + + int num = numerator; + int denom = denominator; + while (denom != 0) { // euclidean gcd algorithm + int oldDenom = denom; + denom = num % denom; + num = oldDenom; + } + // num is now gcd of numerator and denominator + numerator /= num; + denominator /= num; } /*! \internal - + Takes the fraction given by \a numerator and \a denominator and returns a string representation. The result depends on the configured fraction style (\ref setFractionStyle). - + This method is used to format the numerical/fractional part when generating tick labels. It simplifies the passed fraction to an irreducible form using \ref simplifyFraction and factors out any integer parts of the fraction (e.g. "10/4" becomes "2 1/2"). */ QString QCPAxisTickerPi::fractionToString(int numerator, int denominator) const { - if (denominator == 0) - { - qDebug() << Q_FUNC_INFO << "called with zero denominator"; - return QString(); - } - if (mFractionStyle == fsFloatingPoint) // should never be the case when calling this function - { - qDebug() << Q_FUNC_INFO << "shouldn't be called with fraction style fsDecimal"; - return QString::number(numerator/double(denominator)); // failsafe - } - int sign = numerator*denominator < 0 ? -1 : 1; - numerator = qAbs(numerator); - denominator = qAbs(denominator); - - if (denominator == 1) - { - return QString::number(sign*numerator); - } else - { - int integerPart = numerator/denominator; - int remainder = numerator%denominator; - if (remainder == 0) - { - return QString::number(sign*integerPart); - } else - { - if (mFractionStyle == fsAsciiFractions) - { - return QString(QLatin1String("%1%2%3/%4")) - .arg(sign == -1 ? QLatin1String("-") : QLatin1String("")) - .arg(integerPart > 0 ? QString::number(integerPart)+QLatin1String(" ") : QString(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)); - } + if (denominator == 0) { + qDebug() << Q_FUNC_INFO << "called with zero denominator"; + return QString(); } - } - return QString(); + if (mFractionStyle == fsFloatingPoint) { // should never be the case when calling this function + qDebug() << Q_FUNC_INFO << "shouldn't be called with fraction style fsDecimal"; + return QString::number(numerator / double(denominator)); // failsafe + } + int sign = numerator * denominator < 0 ? -1 : 1; + numerator = qAbs(numerator); + denominator = qAbs(denominator); + + if (denominator == 1) { + return QString::number(sign * numerator); + } else { + int integerPart = numerator / denominator; + int remainder = numerator % denominator; + if (remainder == 0) { + return QString::number(sign * integerPart); + } else { + if (mFractionStyle == fsAsciiFractions) { + return QString(QLatin1String("%1%2%3/%4")) + .arg(sign == -1 ? QLatin1String("-") : QLatin1String("")) + .arg(integerPart > 0 ? QString::number(integerPart) + QLatin1String(" ") : QString(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); + 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; } + if (number == 0) { + return QString(QChar(0x2070)); } - number /= 10; - } - return result; + + 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; + 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' */ @@ -7693,23 +7835,23 @@ QString QCPAxisTickerPi::unicodeSubscript(int number) const //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \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 - + Note that the nature of logarithmic ticks imply that there exists a smallest possible tick step, corresponding to one multiplication by the log base. If the user zooms in further than that, no new ticks would appear, leading to very sparse or even no axis ticks on the axis. To prevent this @@ -7722,9 +7864,9 @@ QString QCPAxisTickerPi::unicodeSubscript(int number) const 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)) + mLogBase(10.0), + mSubTickCount(8), // generates 10 intervals + mLogBaseLnInv(1.0 / qLn(mLogBase)) { } @@ -7734,19 +7876,19 @@ QCPAxisTickerLog::QCPAxisTickerLog() : */ 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; + 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, @@ -7754,27 +7896,28 @@ void QCPAxisTickerLog::setLogBase(double base) */ void QCPAxisTickerLog::setSubTickCount(int subTicks) { - if (subTicks >= 0) - mSubTickCount = subTicks; - else - qDebug() << Q_FUNC_INFO << "sub tick count can't be negative:" << subTicks; + if (subTicks >= 0) { + mSubTickCount = subTicks; + } else { + qDebug() << Q_FUNC_INFO << "sub tick count can't be negative:" << subTicks; + } } /*! \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; + 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). @@ -7782,46 +7925,43 @@ int QCPAxisTickerLog::getSubTickCount(double tickStep) The parameter \a tickStep is ignored for the normal logarithmic ticker generation. Only when zoomed in very far such that not enough logarithmically placed ticks would be visible, this function falls back to the regular QCPAxisTicker::createTickVector, which then uses \a tickStep. - + \seebaseclassmethod */ QVector QCPAxisTickerLog::createTickVector(double tickStep, const QCPRange &range) { - QVector result; - if (range.lower > 0 && range.upper > 0) // positive range - { - const double baseTickCount = qLn(range.upper/range.lower)*mLogBaseLnInv; - if (baseTickCount < 1.6) // if too few log ticks would be visible in axis range, fall back to regular tick vector generation - return QCPAxisTicker::createTickVector(tickStep, range); - const double exactPowerStep = baseTickCount/double(mTickCount+1e-10); - const 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); + QVector result; + if (range.lower > 0 && range.upper > 0) { // positive range + const double baseTickCount = qLn(range.upper / range.lower) * mLogBaseLnInv; + if (baseTickCount < 1.6) { // if too few log ticks would be visible in axis range, fall back to regular tick vector generation + return QCPAxisTicker::createTickVector(tickStep, range); + } + const double exactPowerStep = baseTickCount / double(mTickCount + 1e-10); + const 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 + const double baseTickCount = qLn(range.lower / range.upper) * mLogBaseLnInv; + if (baseTickCount < 1.6) { // if too few log ticks would be visible in axis range, fall back to regular tick vector generation + return QCPAxisTicker::createTickVector(tickStep, range); + } + const double exactPowerStep = baseTickCount / double(mTickCount + 1e-10); + const 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; } - } else if (range.lower < 0 && range.upper < 0) // negative range - { - const double baseTickCount = qLn(range.lower/range.upper)*mLogBaseLnInv; - if (baseTickCount < 1.6) // if too few log ticks would be visible in axis range, fall back to regular tick vector generation - return QCPAxisTicker::createTickVector(tickStep, range); - const double exactPowerStep = baseTickCount/double(mTickCount+1e-10); - const 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; + + return result; } /* end of 'src/axis/axistickerlog.cpp' */ @@ -7836,11 +7976,11 @@ QVector QCPAxisTickerLog::createTickVector(double tickStep, const QCPRan /*! \class QCPGrid \brief Responsible for drawing the grid of a QCPAxis. - + This class is tightly bound to QCPAxis. Every axis owns a grid instance and uses it to draw the grid lines, sub grid lines and zero-line. You can interact with the grid of an axis via \ref QCPAxis::grid. Normally, you don't need to create an instance of QCPGrid yourself. - + The axis and grid drawing was split into two classes to allow them to be placed on different layers (both QCPAxis and QCPGrid inherit from QCPLayerable). Thus it is possible to have the grid in the background and the axes in the foreground, and any plottables/items in between. This @@ -7849,35 +7989,35 @@ QVector QCPAxisTickerLog::createTickVector(double tickStep, const QCPRan /*! Creates a QCPGrid instance and sets default values. - + You shouldn't instantiate grids on their own, since every QCPAxis brings its own QCPGrid. */ QCPGrid::QCPGrid(QCPAxis *parentAxis) : - QCPLayerable(parentAxis->parentPlot(), QString(), parentAxis), - mSubGridVisible{}, - mAntialiasedSubGrid{}, - mAntialiasedZeroLine{}, - mParentAxis(parentAxis) + QCPLayerable(parentAxis->parentPlot(), QString(), parentAxis), + mSubGridVisible{}, + mAntialiasedSubGrid{}, + mAntialiasedZeroLine{}, + mParentAxis(parentAxis) { - // warning: this is called in QCPAxis constructor, so parentAxis members should not be accessed/called - setParent(parentAxis); - setPen(QPen(QColor(200,200,200), 0, Qt::DotLine)); - setSubGridPen(QPen(QColor(220,220,220), 0, Qt::DotLine)); - setZeroLinePen(QPen(QColor(200,200,200), 0, Qt::SolidLine)); - setSubGridVisible(false); - setAntialiased(false); - setAntialiasedSubGrid(false); - setAntialiasedZeroLine(false); + // warning: this is called in QCPAxis constructor, so parentAxis members should not be accessed/called + setParent(parentAxis); + setPen(QPen(QColor(200, 200, 200), 0, Qt::DotLine)); + setSubGridPen(QPen(QColor(220, 220, 220), 0, Qt::DotLine)); + setZeroLinePen(QPen(QColor(200, 200, 200), 0, Qt::SolidLine)); + setSubGridVisible(false); + setAntialiased(false); + setAntialiasedSubGrid(false); + setAntialiasedZeroLine(false); } /*! Sets whether grid lines at sub tick marks are drawn. - + \see setSubGridPen */ void QCPGrid::setSubGridVisible(bool visible) { - mSubGridVisible = visible; + mSubGridVisible = visible; } /*! @@ -7885,7 +8025,7 @@ void QCPGrid::setSubGridVisible(bool visible) */ void QCPGrid::setAntialiasedSubGrid(bool enabled) { - mAntialiasedSubGrid = enabled; + mAntialiasedSubGrid = enabled; } /*! @@ -7893,7 +8033,7 @@ void QCPGrid::setAntialiasedSubGrid(bool enabled) */ void QCPGrid::setAntialiasedZeroLine(bool enabled) { - mAntialiasedZeroLine = enabled; + mAntialiasedZeroLine = enabled; } /*! @@ -7901,7 +8041,7 @@ void QCPGrid::setAntialiasedZeroLine(bool enabled) */ void QCPGrid::setPen(const QPen &pen) { - mPen = pen; + mPen = pen; } /*! @@ -7909,18 +8049,18 @@ void QCPGrid::setPen(const QPen &pen) */ void QCPGrid::setSubGridPen(const QPen &pen) { - mSubGridPen = pen; + mSubGridPen = pen; } /*! Sets the pen with which zero lines are drawn. - + Zero lines are lines at value coordinate 0 which may be drawn with a different pen than other grid lines. To disable zero lines and just draw normal grid lines at zero, set \a pen to Qt::NoPen. */ void QCPGrid::setZeroLinePen(const QPen &pen) { - mZeroLinePen = pen; + mZeroLinePen = pen; } /*! \internal @@ -7929,133 +8069,133 @@ void QCPGrid::setZeroLinePen(const QPen &pen) before drawing the major grid lines. This is the antialiasing state the painter passed to the \ref draw method is in by default. - + 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 */ void QCPGrid::applyDefaultAntialiasingHint(QCPPainter *painter) const { - applyAntialiasingHint(painter, mAntialiased, QCP::aeGrid); + applyAntialiasingHint(painter, mAntialiased, QCP::aeGrid); } /*! \internal - + Draws grid lines and sub grid lines at the positions of (sub) ticks of the parent axis, spanning over the complete axis rect. Also draws the zero line, if appropriate (\ref setZeroLinePen). */ void QCPGrid::draw(QCPPainter *painter) { - if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; } - - if (mParentAxis->subTicks() && mSubGridVisible) - drawSubGridLines(painter); - drawGridLines(painter); + if (!mParentAxis) { + qDebug() << Q_FUNC_INFO << "invalid parent axis"; + return; + } + + if (mParentAxis->subTicks() && mSubGridVisible) { + drawSubGridLines(painter); + } + drawGridLines(painter); } /*! \internal - + Draws the main grid lines and possibly a zero line with the specified painter. - + This is a helper function called by \ref draw. */ void QCPGrid::drawGridLines(QCPPainter *painter) const { - if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; } - - const int tickCount = mParentAxis->mTickVector.size(); - double t; // helper variable, result of coordinate-to-pixel transforms - if (mParentAxis->orientation() == Qt::Horizontal) - { - // draw zeroline: - int zeroLineIndex = -1; - if (mZeroLinePen.style() != Qt::NoPen && mParentAxis->mRange.lower < 0 && mParentAxis->mRange.upper > 0) - { - applyAntialiasingHint(painter, mAntialiasedZeroLine, QCP::aeZeroLine); - painter->setPen(mZeroLinePen); - double epsilon = mParentAxis->range().size()*1E-6; // for comparing double to zero - for (int i=0; imTickVector.at(i)) < epsilon) - { - zeroLineIndex = i; - t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // x - painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top())); - break; + if (!mParentAxis) { + qDebug() << Q_FUNC_INFO << "invalid parent axis"; + return; + } + + const int tickCount = mParentAxis->mTickVector.size(); + double t; // helper variable, result of coordinate-to-pixel transforms + if (mParentAxis->orientation() == Qt::Horizontal) { + // draw zeroline: + int zeroLineIndex = -1; + if (mZeroLinePen.style() != Qt::NoPen && mParentAxis->mRange.lower < 0 && mParentAxis->mRange.upper > 0) { + applyAntialiasingHint(painter, mAntialiasedZeroLine, QCP::aeZeroLine); + painter->setPen(mZeroLinePen); + double epsilon = mParentAxis->range().size() * 1E-6; // for comparing double to zero + for (int i = 0; i < tickCount; ++i) { + if (qAbs(mParentAxis->mTickVector.at(i)) < epsilon) { + zeroLineIndex = i; + t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // x + painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top())); + break; + } + } } - } - } - // draw grid lines: - applyDefaultAntialiasingHint(painter); - painter->setPen(mPen); - for (int i=0; icoordToPixel(mParentAxis->mTickVector.at(i)); // x - painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top())); - } - } else - { - // draw zeroline: - int zeroLineIndex = -1; - if (mZeroLinePen.style() != Qt::NoPen && mParentAxis->mRange.lower < 0 && mParentAxis->mRange.upper > 0) - { - applyAntialiasingHint(painter, mAntialiasedZeroLine, QCP::aeZeroLine); - painter->setPen(mZeroLinePen); - double epsilon = mParentAxis->mRange.size()*1E-6; // for comparing double to zero - for (int i=0; imTickVector.at(i)) < epsilon) - { - zeroLineIndex = i; - t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // y - painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t)); - break; + // draw grid lines: + applyDefaultAntialiasingHint(painter); + painter->setPen(mPen); + for (int i = 0; i < tickCount; ++i) { + if (i == zeroLineIndex) { + continue; // don't draw a gridline on top of the zeroline + } + t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // x + painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top())); + } + } else { + // draw zeroline: + int zeroLineIndex = -1; + if (mZeroLinePen.style() != Qt::NoPen && mParentAxis->mRange.lower < 0 && mParentAxis->mRange.upper > 0) { + applyAntialiasingHint(painter, mAntialiasedZeroLine, QCP::aeZeroLine); + painter->setPen(mZeroLinePen); + double epsilon = mParentAxis->mRange.size() * 1E-6; // for comparing double to zero + for (int i = 0; i < tickCount; ++i) { + if (qAbs(mParentAxis->mTickVector.at(i)) < epsilon) { + zeroLineIndex = i; + t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // y + painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t)); + break; + } + } + } + // draw grid lines: + applyDefaultAntialiasingHint(painter); + painter->setPen(mPen); + for (int i = 0; i < tickCount; ++i) { + if (i == zeroLineIndex) { + continue; // don't draw a gridline on top of the zeroline + } + t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // y + painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t)); } - } } - // draw grid lines: - applyDefaultAntialiasingHint(painter); - painter->setPen(mPen); - for (int i=0; icoordToPixel(mParentAxis->mTickVector.at(i)); // y - painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t)); - } - } } /*! \internal - + Draws the sub grid lines with the specified painter. - + This is a helper function called by \ref draw. */ void QCPGrid::drawSubGridLines(QCPPainter *painter) const { - if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; } - - applyAntialiasingHint(painter, mAntialiasedSubGrid, QCP::aeSubGrid); - double t; // helper variable, result of coordinate-to-pixel transforms - painter->setPen(mSubGridPen); - if (mParentAxis->orientation() == Qt::Horizontal) - { - foreach (double tickCoord, mParentAxis->mSubTickVector) - { - t = mParentAxis->coordToPixel(tickCoord); // x - painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top())); + if (!mParentAxis) { + qDebug() << Q_FUNC_INFO << "invalid parent axis"; + return; } - } else - { - foreach (double tickCoord, mParentAxis->mSubTickVector) - { - t = mParentAxis->coordToPixel(tickCoord); // y - painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t)); + + applyAntialiasingHint(painter, mAntialiasedSubGrid, QCP::aeSubGrid); + double t; // helper variable, result of coordinate-to-pixel transforms + painter->setPen(mSubGridPen); + if (mParentAxis->orientation() == Qt::Horizontal) { + foreach (double tickCoord, mParentAxis->mSubTickVector) { + t = mParentAxis->coordToPixel(tickCoord); // x + painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top())); + } + } else { + foreach (double tickCoord, mParentAxis->mSubTickVector) { + t = mParentAxis->coordToPixel(tickCoord); // y + painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t)); + } } - } } @@ -8069,16 +8209,16 @@ void QCPGrid::drawSubGridLines(QCPPainter *painter) const Usually doesn't need to be instantiated externally. Access %QCustomPlot's default four axes via QCustomPlot::xAxis (bottom), QCustomPlot::yAxis (left), QCustomPlot::xAxis2 (top) and QCustomPlot::yAxis2 (right). - + Axes are always part of an axis rect, see QCPAxisRect. \image html AxisNamesOverview.png
Naming convention of axis parts
\n - + \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 @@ -8096,7 +8236,7 @@ void QCPGrid::drawSubGridLines(QCPPainter *painter) const */ /*! \fn QCPGrid *QCPAxis::grid() const - + Returns the \ref QCPGrid instance belonging to this axis. Access it to set details about the way the grid is displayed. */ @@ -8151,7 +8291,7 @@ void QCPGrid::drawSubGridLines(QCPPainter *painter) const This signal is emitted when the range of this axis has changed. You can connect it to the \ref setRange slot of another axis to communicate the new range to the other axis, in order for it to be synchronized. - + 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 (see \ref QCPRange::bounded). For example, the following @@ -8163,24 +8303,24 @@ void QCPGrid::drawSubGridLines(QCPPainter *painter) const /*! \fn void QCPAxis::rangeChanged(const QCPRange &newRange, const QCPRange &oldRange) \overload - + Additionally to the new range, this signal also provides the previous range held by the axis as \a oldRange. */ /*! \fn void QCPAxis::scaleTypeChanged(QCPAxis::ScaleType scaleType); - + This signal is emitted when the scale type changes, by calls to \ref setScaleType */ /*! \fn void QCPAxis::selectionChanged(QCPAxis::SelectableParts selection) - + This signal is emitted when the selection state of this axis has changed, either by user interaction or by a direct call to \ref setSelectedParts. */ /*! \fn void QCPAxis::selectableChanged(const QCPAxis::SelectableParts &parts); - + This signal is emitted when the selectability changes, by calls to \ref setSelectableParts */ @@ -8188,295 +8328,291 @@ void QCPGrid::drawSubGridLines(QCPPainter *painter) const /*! Constructs an Axis instance of Type \a type for the axis rect \a parent. - + Usually it isn't necessary to instantiate axes directly, because you can let QCustomPlot create them for you with \ref QCPAxisRect::addAxis. If you want to use own QCPAxis-subclasses however, create them manually and then inject them also via \ref QCPAxisRect::addAxis. */ QCPAxis::QCPAxis(QCPAxisRect *parent, AxisType type) : - QCPLayerable(parent->parentPlot(), QString(), parent), - // axis base: - mAxisType(type), - mAxisRect(parent), - mPadding(5), - mOrientation(orientation(type)), - mSelectableParts(spAxis | spTickLabels | spAxisLabel), - mSelectedParts(spNone), - mBasePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), - mSelectedBasePen(QPen(Qt::blue, 2)), - // axis label: - mLabel(), - mLabelFont(mParentPlot->font()), - mSelectedLabelFont(QFont(mLabelFont.family(), mLabelFont.pointSize(), QFont::Bold)), - mLabelColor(Qt::black), - mSelectedLabelColor(Qt::blue), - // tick labels: - mTickLabels(true), - mTickLabelFont(mParentPlot->font()), - mSelectedTickLabelFont(QFont(mTickLabelFont.family(), mTickLabelFont.pointSize(), QFont::Bold)), - mTickLabelColor(Qt::black), - mSelectedTickLabelColor(Qt::blue), - mNumberPrecision(6), - mNumberFormatChar('g'), - mNumberBeautifulPowers(true), - // ticks and subticks: - mTicks(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)), - mSelectedSubTickPen(QPen(Qt::blue, 2)), - // scale and range: - mRange(0, 5), - mRangeReversed(false), - mScaleType(stLinear), - // internal members: - mGrid(new QCPGrid(this)), - mAxisPainter(new QCPAxisPainterPrivate(parent->parentPlot())), - mTicker(new QCPAxisTicker), - mCachedMarginValid(false), - mCachedMargin(0), - mDragging(false) + QCPLayerable(parent->parentPlot(), QString(), parent), + // axis base: + mAxisType(type), + mAxisRect(parent), + mPadding(5), + mOrientation(orientation(type)), + mSelectableParts(spAxis | spTickLabels | spAxisLabel), + mSelectedParts(spNone), + mBasePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), + mSelectedBasePen(QPen(Qt::blue, 2)), + // axis label: + mLabel(), + mLabelFont(mParentPlot->font()), + mSelectedLabelFont(QFont(mLabelFont.family(), mLabelFont.pointSize(), QFont::Bold)), + mLabelColor(Qt::black), + mSelectedLabelColor(Qt::blue), + // tick labels: + mTickLabels(true), + mTickLabelFont(mParentPlot->font()), + mSelectedTickLabelFont(QFont(mTickLabelFont.family(), mTickLabelFont.pointSize(), QFont::Bold)), + mTickLabelColor(Qt::black), + mSelectedTickLabelColor(Qt::blue), + mNumberPrecision(6), + mNumberFormatChar('g'), + mNumberBeautifulPowers(true), + // ticks and subticks: + mTicks(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)), + mSelectedSubTickPen(QPen(Qt::blue, 2)), + // scale and range: + mRange(0, 5), + mRangeReversed(false), + mScaleType(stLinear), + // internal members: + mGrid(new QCPGrid(this)), + mAxisPainter(new QCPAxisPainterPrivate(parent->parentPlot())), + mTicker(new QCPAxisTicker), + mCachedMarginValid(false), + mCachedMargin(0), + mDragging(false) { - 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 - - if (type == atTop) - { - setTickLabelPadding(3); - setLabelPadding(6); - } else if (type == atRight) - { - setTickLabelPadding(7); - setLabelPadding(12); - } else if (type == atBottom) - { - setTickLabelPadding(3); - setLabelPadding(3); - } else if (type == atLeft) - { - setTickLabelPadding(5); - setLabelPadding(10); - } + 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 + + if (type == atTop) { + setTickLabelPadding(3); + setLabelPadding(6); + } else if (type == atRight) { + setTickLabelPadding(7); + setLabelPadding(12); + } else if (type == atBottom) { + setTickLabelPadding(3); + setLabelPadding(3); + } else if (type == atLeft) { + setTickLabelPadding(5); + setLabelPadding(10); + } } QCPAxis::~QCPAxis() { - delete mAxisPainter; - delete mGrid; // delete grid here instead of via parent ~QObject for better defined deletion order + delete mAxisPainter; + delete mGrid; // delete grid here instead of via parent ~QObject for better defined deletion order } /* No documentation as it is a property getter */ int QCPAxis::tickLabelPadding() const { - return mAxisPainter->tickLabelPadding; + return mAxisPainter->tickLabelPadding; } /* No documentation as it is a property getter */ double QCPAxis::tickLabelRotation() const { - return mAxisPainter->tickLabelRotation; + return mAxisPainter->tickLabelRotation; } /* No documentation as it is a property getter */ QCPAxis::LabelSide QCPAxis::tickLabelSide() const { - return mAxisPainter->tickLabelSide; + return mAxisPainter->tickLabelSide; } /* No documentation as it is a property getter */ QString QCPAxis::numberFormat() const { - QString result; - result.append(mNumberFormatChar); - if (mNumberBeautifulPowers) - { - result.append(QLatin1Char('b')); - if (mAxisPainter->numberMultiplyCross) - result.append(QLatin1Char('c')); - } - return result; + QString result; + result.append(mNumberFormatChar); + if (mNumberBeautifulPowers) { + result.append(QLatin1Char('b')); + if (mAxisPainter->numberMultiplyCross) { + result.append(QLatin1Char('c')); + } + } + return result; } /* No documentation as it is a property getter */ int QCPAxis::tickLengthIn() const { - return mAxisPainter->tickLengthIn; + return mAxisPainter->tickLengthIn; } /* No documentation as it is a property getter */ int QCPAxis::tickLengthOut() const { - return mAxisPainter->tickLengthOut; + return mAxisPainter->tickLengthOut; } /* No documentation as it is a property getter */ int QCPAxis::subTickLengthIn() const { - return mAxisPainter->subTickLengthIn; + return mAxisPainter->subTickLengthIn; } /* No documentation as it is a property getter */ int QCPAxis::subTickLengthOut() const { - return mAxisPainter->subTickLengthOut; + return mAxisPainter->subTickLengthOut; } /* No documentation as it is a property getter */ int QCPAxis::labelPadding() const { - return mAxisPainter->labelPadding; + return mAxisPainter->labelPadding; } /* No documentation as it is a property getter */ int QCPAxis::offset() const { - return mAxisPainter->offset; + return mAxisPainter->offset; } /* No documentation as it is a property getter */ QCPLineEnding QCPAxis::lowerEnding() const { - return mAxisPainter->lowerEnding; + return mAxisPainter->lowerEnding; } /* No documentation as it is a property getter */ QCPLineEnding QCPAxis::upperEnding() const { - return mAxisPainter->upperEnding; + return mAxisPainter->upperEnding; } /*! Sets whether the axis uses a linear scale or a logarithmic scale. - + Note that this method controls the coordinate transformation. For logarithmic scales, you will likely also want to use a logarithmic tick spacing and labeling, which can be achieved by setting the axis ticker to an instance of \ref QCPAxisTickerLog : - + \snippet documentation/doc-code-snippets/mainwindow.cpp qcpaxisticker-log-creation - + See the documentation of \ref QCPAxisTickerLog about the details of logarithmic axis tick creation. - + \ref setNumberPrecision */ void QCPAxis::setScaleType(QCPAxis::ScaleType type) { - if (mScaleType != type) - { - mScaleType = type; - if (mScaleType == stLogarithmic) - setRange(mRange.sanitizedForLogScale()); - mCachedMarginValid = false; - emit scaleTypeChanged(mScaleType); - } + if (mScaleType != type) { + mScaleType = type; + if (mScaleType == stLogarithmic) { + setRange(mRange.sanitizedForLogScale()); + } + mCachedMarginValid = false; + emit scaleTypeChanged(mScaleType); + } } /*! Sets the range of the axis. - + This slot may be connected with the \ref rangeChanged signal of another axis so this axis is always synchronized with the other axis range, when it changes. - + To invert the direction of an axis, use \ref setRangeReversed. */ void QCPAxis::setRange(const QCPRange &range) { - if (range.lower == mRange.lower && range.upper == mRange.upper) - return; - - if (!QCPRange::validRange(range)) return; - QCPRange oldRange = mRange; - if (mScaleType == stLogarithmic) - { - mRange = range.sanitizedForLogScale(); - } else - { - mRange = range.sanitizedForLinScale(); - } - emit rangeChanged(mRange); - emit rangeChanged(mRange, oldRange); + if (range.lower == mRange.lower && range.upper == mRange.upper) { + return; + } + + if (!QCPRange::validRange(range)) { + return; + } + QCPRange oldRange = mRange; + if (mScaleType == stLogarithmic) { + mRange = range.sanitizedForLogScale(); + } else { + mRange = range.sanitizedForLinScale(); + } + emit rangeChanged(mRange); + emit rangeChanged(mRange, oldRange); } /*! Sets whether the user can (de-)select the parts in \a selectable by clicking on the QCustomPlot surface. (When \ref QCustomPlot::setInteractions contains iSelectAxes.) - + However, even when \a selectable is set to a value not allowing the selection of a specific part, it is still possible to set the selection of this part manually, by calling \ref setSelectedParts directly. - + \see SelectablePart, setSelectedParts */ void QCPAxis::setSelectableParts(const SelectableParts &selectable) { - if (mSelectableParts != selectable) - { - mSelectableParts = selectable; - emit selectableChanged(mSelectableParts); - } + if (mSelectableParts != selectable) { + mSelectableParts = selectable; + emit selectableChanged(mSelectableParts); + } } /*! Sets the selected state of the respective axis parts described by \ref SelectablePart. When a part is selected, it uses a different pen/font. - + The entire selection mechanism for axes is handled automatically when \ref QCustomPlot::setInteractions contains iSelectAxes. You only need to call this function when you wish to change the selection state manually. - + This function can change the selection state of a part, independent of the \ref setSelectableParts setting. - + emits the \ref selectionChanged signal when \a selected is different from the previous selection state. - + \see SelectablePart, setSelectableParts, selectTest, setSelectedBasePen, setSelectedTickPen, setSelectedSubTickPen, setSelectedTickLabelFont, setSelectedLabelFont, setSelectedTickLabelColor, setSelectedLabelColor */ void QCPAxis::setSelectedParts(const SelectableParts &selected) { - if (mSelectedParts != selected) - { - mSelectedParts = selected; - emit selectionChanged(mSelectedParts); - } + if (mSelectedParts != selected) { + mSelectedParts = selected; + emit selectionChanged(mSelectedParts); + } } /*! \overload - + Sets the lower and upper bound of the axis range. - + To invert the direction of an axis, use \ref setRangeReversed. - + There is also a slot to set a range, see \ref setRange(const QCPRange &range). */ void QCPAxis::setRange(double lower, double upper) { - if (lower == mRange.lower && upper == mRange.upper) - return; - - if (!QCPRange::validRange(lower, upper)) return; - QCPRange oldRange = mRange; - mRange.lower = lower; - mRange.upper = upper; - if (mScaleType == stLogarithmic) - { - mRange = mRange.sanitizedForLogScale(); - } else - { - mRange = mRange.sanitizedForLinScale(); - } - emit rangeChanged(mRange); - emit rangeChanged(mRange, oldRange); + if (lower == mRange.lower && upper == mRange.upper) { + return; + } + + if (!QCPRange::validRange(lower, upper)) { + return; + } + QCPRange oldRange = mRange; + mRange.lower = lower; + mRange.upper = upper; + if (mScaleType == stLogarithmic) { + mRange = mRange.sanitizedForLogScale(); + } else { + mRange = mRange.sanitizedForLinScale(); + } + emit rangeChanged(mRange); + emit rangeChanged(mRange, oldRange); } /*! \overload - + Sets the range of the axis. - + The \a position coordinate indicates together with the \a alignment parameter, where the new range will be positioned. \a size defines the size of the new axis range. \a alignment may be Qt::AlignLeft, Qt::AlignRight or Qt::AlignCenter. This will cause the left border, right border, @@ -8485,12 +8621,13 @@ void QCPAxis::setRange(double lower, double upper) */ void QCPAxis::setRange(double position, double size, Qt::AlignmentFlag alignment) { - if (alignment == Qt::AlignLeft) - setRange(position, position+size); - else if (alignment == Qt::AlignRight) - setRange(position-size, position); - else // alignment == Qt::AlignCenter - setRange(position-size/2.0, position+size/2.0); + if (alignment == Qt::AlignLeft) { + setRange(position, position + size); + } else if (alignment == Qt::AlignRight) { + setRange(position - size, position); + } else { // alignment == Qt::AlignCenter + setRange(position - size / 2.0, position + size / 2.0); + } } /*! @@ -8499,20 +8636,19 @@ void QCPAxis::setRange(double position, double size, Qt::AlignmentFlag alignment */ void QCPAxis::setRangeLower(double lower) { - if (mRange.lower == lower) - return; - - QCPRange oldRange = mRange; - mRange.lower = lower; - if (mScaleType == stLogarithmic) - { - mRange = mRange.sanitizedForLogScale(); - } else - { - mRange = mRange.sanitizedForLinScale(); - } - emit rangeChanged(mRange); - emit rangeChanged(mRange, oldRange); + if (mRange.lower == lower) { + return; + } + + QCPRange oldRange = mRange; + mRange.lower = lower; + if (mScaleType == stLogarithmic) { + mRange = mRange.sanitizedForLogScale(); + } else { + mRange = mRange.sanitizedForLinScale(); + } + emit rangeChanged(mRange); + emit rangeChanged(mRange, oldRange); } /*! @@ -8521,20 +8657,19 @@ void QCPAxis::setRangeLower(double lower) */ void QCPAxis::setRangeUpper(double upper) { - if (mRange.upper == upper) - return; - - QCPRange oldRange = mRange; - mRange.upper = upper; - if (mScaleType == stLogarithmic) - { - mRange = mRange.sanitizedForLogScale(); - } else - { - mRange = mRange.sanitizedForLinScale(); - } - emit rangeChanged(mRange); - emit rangeChanged(mRange, oldRange); + if (mRange.upper == upper) { + return; + } + + QCPRange oldRange = mRange; + mRange.upper = upper; + if (mScaleType == stLogarithmic) { + mRange = mRange.sanitizedForLogScale(); + } else { + mRange = mRange.sanitizedForLinScale(); + } + emit rangeChanged(mRange); + emit rangeChanged(mRange, oldRange); } /*! @@ -8548,29 +8683,30 @@ void QCPAxis::setRangeUpper(double upper) */ void QCPAxis::setRangeReversed(bool reversed) { - mRangeReversed = reversed; + mRangeReversed = reversed; } /*! 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. - + 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. - + 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 ticker */ void QCPAxis::setTicker(QSharedPointer ticker) { - if (ticker) - mTicker = ticker; - else - qDebug() << Q_FUNC_INFO << "can not set nullptr as axis ticker"; - // no need to invalidate margin cache here because produced tick labels are checked for changes in setupTickVector + if (ticker) { + mTicker = ticker; + } else { + qDebug() << Q_FUNC_INFO << "can not set nullptr as axis ticker"; + } + // no need to invalidate margin cache here because produced tick labels are checked for changes in setupTickVector } /*! @@ -8578,16 +8714,15 @@ void QCPAxis::setTicker(QSharedPointer ticker) 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) { - if (mTicks != show) - { - mTicks = show; - mCachedMarginValid = false; - } + if (mTicks != show) { + mTicks = show; + mCachedMarginValid = false; + } } /*! @@ -8595,13 +8730,13 @@ void QCPAxis::setTicks(bool show) */ void QCPAxis::setTickLabels(bool show) { - if (mTickLabels != show) - { - mTickLabels = show; - mCachedMarginValid = false; - if (!mTickLabels) - mTickVectorLabels.clear(); - } + if (mTickLabels != show) { + mTickLabels = show; + mCachedMarginValid = false; + if (!mTickLabels) { + mTickVectorLabels.clear(); + } + } } /*! @@ -8610,73 +8745,70 @@ void QCPAxis::setTickLabels(bool show) */ void QCPAxis::setTickLabelPadding(int padding) { - if (mAxisPainter->tickLabelPadding != padding) - { - mAxisPainter->tickLabelPadding = padding; - mCachedMarginValid = false; - } + if (mAxisPainter->tickLabelPadding != padding) { + mAxisPainter->tickLabelPadding = padding; + mCachedMarginValid = false; + } } /*! Sets the font of the tick labels. - + \see setTickLabels, setTickLabelColor */ void QCPAxis::setTickLabelFont(const QFont &font) { - if (font != mTickLabelFont) - { - mTickLabelFont = font; - mCachedMarginValid = false; - } + if (font != mTickLabelFont) { + mTickLabelFont = font; + mCachedMarginValid = false; + } } /*! Sets the color of the tick labels. - + \see setTickLabels, setTickLabelFont */ void QCPAxis::setTickLabelColor(const QColor &color) { - mTickLabelColor = color; + mTickLabelColor = color; } /*! Sets the rotation of the tick labels. If \a degrees is zero, the labels are drawn normally. Else, the tick labels are drawn rotated by \a degrees clockwise. The specified angle is bound to values from -90 to 90 degrees. - + If \a degrees is exactly -90, 0 or 90, the tick labels are centered on the tick coordinate. For other angles, the label is drawn with an offset such that it seems to point toward or away from the tick mark. */ void QCPAxis::setTickLabelRotation(double degrees) { - if (!qFuzzyIsNull(degrees-mAxisPainter->tickLabelRotation)) - { - mAxisPainter->tickLabelRotation = qBound(-90.0, degrees, 90.0); - mCachedMarginValid = false; - } + if (!qFuzzyIsNull(degrees - mAxisPainter->tickLabelRotation)) { + mAxisPainter->tickLabelRotation = qBound(-90.0, degrees, 90.0); + mCachedMarginValid = false; + } } /*! Sets whether the tick labels (numbers) shall appear inside or outside the axis rect. - + The usual and default setting is \ref lsOutside. Very compact plots sometimes require tick labels to be inside the axis rect, to save space. If \a side is set to \ref lsInside, the tick labels appear on the inside are additionally clipped to the axis rect. */ void QCPAxis::setTickLabelSide(LabelSide side) { - mAxisPainter->tickLabelSide = side; - mCachedMarginValid = false; + mAxisPainter->tickLabelSide = side; + mCachedMarginValid = false; } /*! 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. - + \a formatCode is a string of one, two or three characters. The first character is identical to @@ -8694,7 +8826,7 @@ void QCPAxis::setTickLabelSide(LabelSide side) If instead a cross should be shown (as is usual in the USA), the third char of \a formatCode can be set to 'c'. The inserted multiplication signs are the UTF-8 characters 215 (0xD7) for the cross and 183 (0xB7) for the dot. - + 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 @@ -8709,57 +8841,47 @@ void QCPAxis::setTickLabelSide(LabelSide side) */ void QCPAxis::setNumberFormat(const QString &formatCode) { - if (formatCode.isEmpty()) - { - qDebug() << Q_FUNC_INFO << "Passed formatCode is empty"; - return; - } - mCachedMarginValid = false; - - // interpret first char as number format char: - QString allowedFormatChars(QLatin1String("eEfgG")); - if (allowedFormatChars.contains(formatCode.at(0))) - { - mNumberFormatChar = QLatin1Char(formatCode.at(0).toLatin1()); - } else - { - qDebug() << Q_FUNC_INFO << "Invalid number format code (first char not in 'eEfgG'):" << formatCode; - return; - } - if (formatCode.length() < 2) - { - mNumberBeautifulPowers = false; - mAxisPainter->numberMultiplyCross = false; - return; - } - - // interpret second char as indicator for beautiful decimal powers: - if (formatCode.at(1) == QLatin1Char('b') && (mNumberFormatChar == QLatin1Char('e') || mNumberFormatChar == QLatin1Char('g'))) - { - mNumberBeautifulPowers = true; - } else - { - qDebug() << Q_FUNC_INFO << "Invalid number format code (second char not 'b' or first char neither 'e' nor 'g'):" << formatCode; - return; - } - if (formatCode.length() < 3) - { - mAxisPainter->numberMultiplyCross = false; - return; - } - - // interpret third char as indicator for dot or cross multiplication symbol: - if (formatCode.at(2) == QLatin1Char('c')) - { - mAxisPainter->numberMultiplyCross = true; - } else if (formatCode.at(2) == QLatin1Char('d')) - { - mAxisPainter->numberMultiplyCross = false; - } else - { - qDebug() << Q_FUNC_INFO << "Invalid number format code (third char neither 'c' nor 'd'):" << formatCode; - return; - } + if (formatCode.isEmpty()) { + qDebug() << Q_FUNC_INFO << "Passed formatCode is empty"; + return; + } + mCachedMarginValid = false; + + // interpret first char as number format char: + QString allowedFormatChars(QLatin1String("eEfgG")); + if (allowedFormatChars.contains(formatCode.at(0))) { + mNumberFormatChar = QLatin1Char(formatCode.at(0).toLatin1()); + } else { + qDebug() << Q_FUNC_INFO << "Invalid number format code (first char not in 'eEfgG'):" << formatCode; + return; + } + if (formatCode.length() < 2) { + mNumberBeautifulPowers = false; + mAxisPainter->numberMultiplyCross = false; + return; + } + + // interpret second char as indicator for beautiful decimal powers: + if (formatCode.at(1) == QLatin1Char('b') && (mNumberFormatChar == QLatin1Char('e') || mNumberFormatChar == QLatin1Char('g'))) { + mNumberBeautifulPowers = true; + } else { + qDebug() << Q_FUNC_INFO << "Invalid number format code (second char not 'b' or first char neither 'e' nor 'g'):" << formatCode; + return; + } + if (formatCode.length() < 3) { + mAxisPainter->numberMultiplyCross = false; + return; + } + + // interpret third char as indicator for dot or cross multiplication symbol: + if (formatCode.at(2) == QLatin1Char('c')) { + mAxisPainter->numberMultiplyCross = true; + } else if (formatCode.at(2) == QLatin1Char('d')) { + mAxisPainter->numberMultiplyCross = false; + } else { + qDebug() << Q_FUNC_INFO << "Invalid number format code (third char neither 'c' nor 'd'):" << formatCode; + return; + } } /*! @@ -8769,11 +8891,10 @@ void QCPAxis::setNumberFormat(const QString &formatCode) */ void QCPAxis::setNumberPrecision(int precision) { - if (mNumberPrecision != precision) - { - mNumberPrecision = precision; - mCachedMarginValid = false; - } + if (mNumberPrecision != precision) { + mNumberPrecision = precision; + mCachedMarginValid = false; + } } /*! @@ -8781,59 +8902,56 @@ void QCPAxis::setNumberPrecision(int precision) plot and \a outside is the length they will reach outside the plot. If \a outside is greater than zero, the tick labels and axis label will increase their distance to the axis accordingly, so they won't collide with the ticks. - + \see setSubTickLength, setTickLengthIn, setTickLengthOut */ void QCPAxis::setTickLength(int inside, int outside) { - setTickLengthIn(inside); - setTickLengthOut(outside); + setTickLengthIn(inside); + setTickLengthOut(outside); } /*! Sets the length of the inward ticks in pixels. \a inside is the length the ticks will reach inside the plot. - + \see setTickLengthOut, setTickLength, setSubTickLength */ void QCPAxis::setTickLengthIn(int inside) { - if (mAxisPainter->tickLengthIn != inside) - { - mAxisPainter->tickLengthIn = inside; - } + if (mAxisPainter->tickLengthIn != inside) { + mAxisPainter->tickLengthIn = inside; + } } /*! Sets the length of the outward ticks in pixels. \a outside is the length the ticks will reach outside the plot. If \a outside is greater than zero, the tick labels and axis label will increase their distance to the axis accordingly, so they won't collide with the ticks. - + \see setTickLengthIn, setTickLength, setSubTickLength */ void QCPAxis::setTickLengthOut(int outside) { - if (mAxisPainter->tickLengthOut != outside) - { - mAxisPainter->tickLengthOut = outside; - mCachedMarginValid = false; // only outside tick length can change margin - } + if (mAxisPainter->tickLengthOut != outside) { + mAxisPainter->tickLengthOut = outside; + mCachedMarginValid = false; // only outside tick length can change margin + } } /*! Sets whether sub tick marks are displayed. - + Sub ticks are only potentially visible if (major) ticks are also visible (see \ref setTicks) - + \see setTicks */ void QCPAxis::setSubTicks(bool show) { - if (mSubTicks != show) - { - mSubTicks = show; - mCachedMarginValid = false; - } + if (mSubTicks != show) { + mSubTicks = show; + mCachedMarginValid = false; + } } /*! @@ -8841,97 +8959,94 @@ void QCPAxis::setSubTicks(bool show) the plot and \a outside is the length they will reach outside the plot. If \a outside is greater than zero, the tick labels and axis label will increase their distance to the axis accordingly, so they won't collide with the ticks. - + \see setTickLength, setSubTickLengthIn, setSubTickLengthOut */ void QCPAxis::setSubTickLength(int inside, int outside) { - setSubTickLengthIn(inside); - setSubTickLengthOut(outside); + setSubTickLengthIn(inside); + setSubTickLengthOut(outside); } /*! Sets the length of the inward subticks in pixels. \a inside is the length the subticks will reach inside the plot. - + \see setSubTickLengthOut, setSubTickLength, setTickLength */ void QCPAxis::setSubTickLengthIn(int inside) { - if (mAxisPainter->subTickLengthIn != inside) - { - mAxisPainter->subTickLengthIn = inside; - } + if (mAxisPainter->subTickLengthIn != inside) { + mAxisPainter->subTickLengthIn = inside; + } } /*! Sets the length of the outward subticks in pixels. \a outside is the length the subticks will reach outside the plot. If \a outside is greater than zero, the tick labels will increase their distance to the axis accordingly, so they won't collide with the ticks. - + \see setSubTickLengthIn, setSubTickLength, setTickLength */ void QCPAxis::setSubTickLengthOut(int outside) { - if (mAxisPainter->subTickLengthOut != outside) - { - mAxisPainter->subTickLengthOut = outside; - mCachedMarginValid = false; // only outside tick length can change margin - } + if (mAxisPainter->subTickLengthOut != outside) { + mAxisPainter->subTickLengthOut = outside; + mCachedMarginValid = false; // only outside tick length can change margin + } } /*! Sets the pen, the axis base line is drawn with. - + \see setTickPen, setSubTickPen */ void QCPAxis::setBasePen(const QPen &pen) { - mBasePen = pen; + mBasePen = pen; } /*! Sets the pen, tick marks will be drawn with. - + \see setTickLength, setBasePen */ void QCPAxis::setTickPen(const QPen &pen) { - mTickPen = pen; + mTickPen = pen; } /*! Sets the pen, subtick marks will be drawn with. - + \see setSubTickCount, setSubTickLength, setBasePen */ void QCPAxis::setSubTickPen(const QPen &pen) { - mSubTickPen = pen; + mSubTickPen = pen; } /*! Sets the font of the axis label. - + \see setLabelColor */ void QCPAxis::setLabelFont(const QFont &font) { - if (mLabelFont != font) - { - mLabelFont = font; - mCachedMarginValid = false; - } + if (mLabelFont != font) { + mLabelFont = font; + mCachedMarginValid = false; + } } /*! Sets the color of the axis label. - + \see setLabelFont */ void QCPAxis::setLabelColor(const QColor &color) { - mLabelColor = color; + mLabelColor = color; } /*! @@ -8940,25 +9055,23 @@ void QCPAxis::setLabelColor(const QColor &color) */ void QCPAxis::setLabel(const QString &str) { - if (mLabel != str) - { - mLabel = str; - mCachedMarginValid = false; - } + if (mLabel != str) { + mLabel = str; + mCachedMarginValid = false; + } } /*! Sets the distance between the tick labels and the axis label. - + \see setTickLabelPadding, setPadding */ void QCPAxis::setLabelPadding(int padding) { - if (mAxisPainter->labelPadding != padding) - { - mAxisPainter->labelPadding = padding; - mCachedMarginValid = false; - } + if (mAxisPainter->labelPadding != padding) { + mAxisPainter->labelPadding = padding; + mCachedMarginValid = false; + } } /*! @@ -8966,23 +9079,22 @@ void QCPAxis::setLabelPadding(int padding) When \ref QCPAxisRect::setAutoMargins is enabled, the padding is the additional outer most space, that is left blank. - + The axis padding has no meaning if \ref QCPAxisRect::setAutoMargins is disabled. - + \see setLabelPadding, setTickLabelPadding */ void QCPAxis::setPadding(int padding) { - if (mPadding != padding) - { - mPadding = padding; - mCachedMarginValid = false; - } + if (mPadding != padding) { + mPadding = padding; + mCachedMarginValid = false; + } } /*! Sets the offset the axis has to its axis rect side. - + If an axis rect side has multiple axes and automatic margin calculation is enabled for that side, only the offset of the inner most axis has meaning (even if it is set to be invisible). The offset of the other, outer axes is controlled automatically, to place them at appropriate @@ -8990,138 +9102,134 @@ void QCPAxis::setPadding(int padding) */ void QCPAxis::setOffset(int offset) { - mAxisPainter->offset = offset; + mAxisPainter->offset = offset; } /*! Sets the font that is used for tick labels when they are selected. - + \see setTickLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPAxis::setSelectedTickLabelFont(const QFont &font) { - if (font != mSelectedTickLabelFont) - { - mSelectedTickLabelFont = font; - // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts - } + if (font != mSelectedTickLabelFont) { + mSelectedTickLabelFont = font; + // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts + } } /*! Sets the font that is used for the axis label when it is selected. - + \see setLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPAxis::setSelectedLabelFont(const QFont &font) { - mSelectedLabelFont = font; - // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts + mSelectedLabelFont = font; + // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts } /*! Sets the color that is used for tick labels when they are selected. - + \see setTickLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPAxis::setSelectedTickLabelColor(const QColor &color) { - if (color != mSelectedTickLabelColor) - { - mSelectedTickLabelColor = color; - } + if (color != mSelectedTickLabelColor) { + mSelectedTickLabelColor = color; + } } /*! Sets the color that is used for the axis label when it is selected. - + \see setLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPAxis::setSelectedLabelColor(const QColor &color) { - mSelectedLabelColor = color; + mSelectedLabelColor = color; } /*! Sets the pen that is used to draw the axis base line when selected. - + \see setBasePen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPAxis::setSelectedBasePen(const QPen &pen) { - mSelectedBasePen = pen; + mSelectedBasePen = pen; } /*! Sets the pen that is used to draw the (major) ticks when selected. - + \see setTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPAxis::setSelectedTickPen(const QPen &pen) { - mSelectedTickPen = pen; + mSelectedTickPen = pen; } /*! Sets the pen that is used to draw the subticks when selected. - + \see setSubTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPAxis::setSelectedSubTickPen(const QPen &pen) { - mSelectedSubTickPen = pen; + mSelectedSubTickPen = pen; } /*! Sets the style for the lower axis ending. See the documentation of QCPLineEnding for available styles. - + For horizontal axes, this method refers to the left ending, for vertical axes the bottom ending. Note that this meaning does not change when the axis range is reversed with \ref setRangeReversed. - + \see setUpperEnding */ void QCPAxis::setLowerEnding(const QCPLineEnding &ending) { - mAxisPainter->lowerEnding = ending; + mAxisPainter->lowerEnding = ending; } /*! Sets the style for the upper axis ending. See the documentation of QCPLineEnding for available styles. - + For horizontal axes, this method refers to the right ending, for vertical axes the top ending. Note that this meaning does not change when the axis range is reversed with \ref setRangeReversed. - + \see setLowerEnding */ void QCPAxis::setUpperEnding(const QCPLineEnding &ending) { - mAxisPainter->upperEnding = ending; + mAxisPainter->upperEnding = ending; } /*! If the scale type (\ref setScaleType) is \ref stLinear, \a diff is added to the lower and upper bounds of the range. The range is simply moved by \a diff. - + If the scale type is \ref stLogarithmic, the range bounds are multiplied by \a diff. This corresponds to an apparent "linear" move in logarithmic scaling by a distance of log(diff). */ void QCPAxis::moveRange(double diff) { - QCPRange oldRange = mRange; - if (mScaleType == stLinear) - { - mRange.lower += diff; - mRange.upper += diff; - } else // mScaleType == stLogarithmic - { - mRange.lower *= diff; - mRange.upper *= diff; - } - emit rangeChanged(mRange); - emit rangeChanged(mRange, oldRange); + QCPRange oldRange = mRange; + if (mScaleType == stLinear) { + mRange.lower += diff; + mRange.upper += diff; + } else { // mScaleType == stLogarithmic + mRange.lower *= diff; + mRange.upper *= diff; + } + emit rangeChanged(mRange); + emit rangeChanged(mRange, oldRange); } /*! @@ -9135,7 +9243,7 @@ void QCPAxis::moveRange(double diff) */ void QCPAxis::scaleRange(double factor) { - scaleRange(factor, range().center()); + scaleRange(factor, range().center()); } /*! \overload @@ -9149,28 +9257,28 @@ void QCPAxis::scaleRange(double factor) */ void QCPAxis::scaleRange(double factor, double center) { - QCPRange oldRange = mRange; - if (mScaleType == stLinear) - { - QCPRange newRange; - newRange.lower = (mRange.lower-center)*factor + center; - newRange.upper = (mRange.upper-center)*factor + center; - if (QCPRange::validRange(newRange)) - mRange = newRange.sanitizedForLinScale(); - } else // mScaleType == stLogarithmic - { - if ((mRange.upper < 0 && center < 0) || (mRange.upper > 0 && center > 0)) // make sure center has same sign as range - { - QCPRange newRange; - newRange.lower = qPow(mRange.lower/center, factor)*center; - newRange.upper = qPow(mRange.upper/center, factor)*center; - if (QCPRange::validRange(newRange)) - mRange = newRange.sanitizedForLogScale(); - } else - qDebug() << Q_FUNC_INFO << "Center of scaling operation doesn't lie in same logarithmic sign domain as range:" << center; - } - emit rangeChanged(mRange); - emit rangeChanged(mRange, oldRange); + QCPRange oldRange = mRange; + if (mScaleType == stLinear) { + QCPRange newRange; + newRange.lower = (mRange.lower - center) * factor + center; + newRange.upper = (mRange.upper - center) * factor + center; + if (QCPRange::validRange(newRange)) { + mRange = newRange.sanitizedForLinScale(); + } + } else { // mScaleType == stLogarithmic + if ((mRange.upper < 0 && center < 0) || (mRange.upper > 0 && center > 0)) { // make sure center has same sign as range + QCPRange newRange; + newRange.lower = qPow(mRange.lower / center, factor) * center; + newRange.upper = qPow(mRange.upper / center, factor) * center; + if (QCPRange::validRange(newRange)) { + mRange = newRange.sanitizedForLogScale(); + } + } else { + qDebug() << Q_FUNC_INFO << "Center of scaling operation doesn't lie in same logarithmic sign domain as range:" << center; + } + } + emit rangeChanged(mRange); + emit rangeChanged(mRange, oldRange); } /*! @@ -9188,71 +9296,71 @@ void QCPAxis::scaleRange(double factor, double center) */ void QCPAxis::setScaleRatio(const QCPAxis *otherAxis, double ratio) { - int otherPixelSize, ownPixelSize; - - if (otherAxis->orientation() == Qt::Horizontal) - otherPixelSize = otherAxis->axisRect()->width(); - else - otherPixelSize = otherAxis->axisRect()->height(); - - if (orientation() == Qt::Horizontal) - ownPixelSize = axisRect()->width(); - else - ownPixelSize = axisRect()->height(); - - double newRangeSize = ratio*otherAxis->range().size()*ownPixelSize/double(otherPixelSize); - setRange(range().center(), newRangeSize, Qt::AlignCenter); + int otherPixelSize, ownPixelSize; + + if (otherAxis->orientation() == Qt::Horizontal) { + otherPixelSize = otherAxis->axisRect()->width(); + } else { + otherPixelSize = otherAxis->axisRect()->height(); + } + + if (orientation() == Qt::Horizontal) { + ownPixelSize = axisRect()->width(); + } else { + ownPixelSize = axisRect()->height(); + } + + double newRangeSize = ratio * otherAxis->range().size() * ownPixelSize / double(otherPixelSize); + setRange(range().center(), newRangeSize, Qt::AlignCenter); } /*! Changes the axis range such that all plottables associated with this axis are fully visible in that dimension. - + \see QCPAbstractPlottable::rescaleAxes, QCustomPlot::rescaleAxes */ void QCPAxis::rescale(bool onlyVisiblePlottables) { - QCPRange newRange; - bool haveRange = false; - foreach (QCPAbstractPlottable *plottable, plottables()) - { - if (!plottable->realVisibility() && onlyVisiblePlottables) - continue; - QCPRange plottableRange; - bool currentFoundRange; - QCP::SignDomain signDomain = QCP::sdBoth; - if (mScaleType == stLogarithmic) - signDomain = (mRange.upper < 0 ? QCP::sdNegative : QCP::sdPositive); - if (plottable->keyAxis() == this) - plottableRange = plottable->getKeyRange(currentFoundRange, signDomain); - else - plottableRange = plottable->getValueRange(currentFoundRange, signDomain); - if (currentFoundRange) - { - if (!haveRange) - newRange = plottableRange; - else - newRange.expand(plottableRange); - haveRange = true; + QCPRange newRange; + bool haveRange = false; + foreach (QCPAbstractPlottable *plottable, plottables()) { + if (!plottable->realVisibility() && onlyVisiblePlottables) { + continue; + } + QCPRange plottableRange; + bool currentFoundRange; + QCP::SignDomain signDomain = QCP::sdBoth; + if (mScaleType == stLogarithmic) { + signDomain = (mRange.upper < 0 ? QCP::sdNegative : QCP::sdPositive); + } + if (plottable->keyAxis() == this) { + plottableRange = plottable->getKeyRange(currentFoundRange, signDomain); + } else { + plottableRange = plottable->getValueRange(currentFoundRange, signDomain); + } + if (currentFoundRange) { + if (!haveRange) { + newRange = plottableRange; + } else { + newRange.expand(plottableRange); + } + haveRange = true; + } } - } - if (haveRange) - { - if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable - { - double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason - if (mScaleType == stLinear) - { - newRange.lower = center-mRange.size()/2.0; - newRange.upper = center+mRange.size()/2.0; - } else // mScaleType == stLogarithmic - { - newRange.lower = center/qSqrt(mRange.upper/mRange.lower); - newRange.upper = center*qSqrt(mRange.upper/mRange.lower); - } + if (haveRange) { + if (!QCPRange::validRange(newRange)) { // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable + double center = (newRange.lower + newRange.upper) * 0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason + if (mScaleType == stLinear) { + newRange.lower = center - mRange.size() / 2.0; + newRange.upper = center + mRange.size() / 2.0; + } else { // mScaleType == stLogarithmic + newRange.lower = center / qSqrt(mRange.upper / mRange.lower); + newRange.upper = center * qSqrt(mRange.upper / mRange.lower); + } + } + setRange(newRange); } - setRange(newRange); - } } /*! @@ -9260,37 +9368,35 @@ void QCPAxis::rescale(bool onlyVisiblePlottables) */ double QCPAxis::pixelToCoord(double value) const { - if (orientation() == Qt::Horizontal) - { - if (mScaleType == stLinear) - { - if (!mRangeReversed) - return (value-mAxisRect->left())/double(mAxisRect->width())*mRange.size()+mRange.lower; - else - return -(value-mAxisRect->left())/double(mAxisRect->width())*mRange.size()+mRange.upper; - } else // mScaleType == stLogarithmic - { - if (!mRangeReversed) - return qPow(mRange.upper/mRange.lower, (value-mAxisRect->left())/double(mAxisRect->width()))*mRange.lower; - else - return qPow(mRange.upper/mRange.lower, (mAxisRect->left()-value)/double(mAxisRect->width()))*mRange.upper; + if (orientation() == Qt::Horizontal) { + if (mScaleType == stLinear) { + if (!mRangeReversed) { + return (value - mAxisRect->left()) / double(mAxisRect->width()) * mRange.size() + mRange.lower; + } else { + return -(value - mAxisRect->left()) / double(mAxisRect->width()) * mRange.size() + mRange.upper; + } + } else { // mScaleType == stLogarithmic + if (!mRangeReversed) { + return qPow(mRange.upper / mRange.lower, (value - mAxisRect->left()) / double(mAxisRect->width())) * mRange.lower; + } else { + return qPow(mRange.upper / mRange.lower, (mAxisRect->left() - value) / double(mAxisRect->width())) * mRange.upper; + } + } + } else { // orientation() == Qt::Vertical + if (mScaleType == stLinear) { + if (!mRangeReversed) { + return (mAxisRect->bottom() - value) / double(mAxisRect->height()) * mRange.size() + mRange.lower; + } else { + return -(mAxisRect->bottom() - value) / double(mAxisRect->height()) * mRange.size() + mRange.upper; + } + } else { // mScaleType == stLogarithmic + if (!mRangeReversed) { + return qPow(mRange.upper / mRange.lower, (mAxisRect->bottom() - value) / double(mAxisRect->height())) * mRange.lower; + } else { + return qPow(mRange.upper / mRange.lower, (value - mAxisRect->bottom()) / double(mAxisRect->height())) * mRange.upper; + } + } } - } else // orientation() == Qt::Vertical - { - if (mScaleType == stLinear) - { - if (!mRangeReversed) - return (mAxisRect->bottom()-value)/double(mAxisRect->height())*mRange.size()+mRange.lower; - else - return -(mAxisRect->bottom()-value)/double(mAxisRect->height())*mRange.size()+mRange.upper; - } else // mScaleType == stLogarithmic - { - if (!mRangeReversed) - return qPow(mRange.upper/mRange.lower, (mAxisRect->bottom()-value)/double(mAxisRect->height()))*mRange.lower; - else - return qPow(mRange.upper/mRange.lower, (value-mAxisRect->bottom())/double(mAxisRect->height()))*mRange.upper; - } - } } /*! @@ -9298,151 +9404,156 @@ double QCPAxis::pixelToCoord(double value) const */ double QCPAxis::coordToPixel(double value) const { - if (orientation() == Qt::Horizontal) - { - if (mScaleType == stLinear) - { - if (!mRangeReversed) - return (value-mRange.lower)/mRange.size()*mAxisRect->width()+mAxisRect->left(); - else - return (mRange.upper-value)/mRange.size()*mAxisRect->width()+mAxisRect->left(); - } else // mScaleType == stLogarithmic - { - if (value >= 0.0 && mRange.upper < 0.0) // invalid value for logarithmic scale, just draw it outside visible range - return !mRangeReversed ? mAxisRect->right()+200 : mAxisRect->left()-200; - else if (value <= 0.0 && mRange.upper >= 0.0) // invalid value for logarithmic scale, just draw it outside visible range - return !mRangeReversed ? mAxisRect->left()-200 : mAxisRect->right()+200; - else - { - if (!mRangeReversed) - return qLn(value/mRange.lower)/qLn(mRange.upper/mRange.lower)*mAxisRect->width()+mAxisRect->left(); - else - return qLn(mRange.upper/value)/qLn(mRange.upper/mRange.lower)*mAxisRect->width()+mAxisRect->left(); - } + if (orientation() == Qt::Horizontal) { + if (mScaleType == stLinear) { + if (!mRangeReversed) { + return (value - mRange.lower) / mRange.size() * mAxisRect->width() + mAxisRect->left(); + } else { + return (mRange.upper - value) / mRange.size() * mAxisRect->width() + mAxisRect->left(); + } + } else { // mScaleType == stLogarithmic + if (value >= 0.0 && mRange.upper < 0.0) { // invalid value for logarithmic scale, just draw it outside visible range + return !mRangeReversed ? mAxisRect->right() + 200 : mAxisRect->left() - 200; + } else if (value <= 0.0 && mRange.upper >= 0.0) { // invalid value for logarithmic scale, just draw it outside visible range + return !mRangeReversed ? mAxisRect->left() - 200 : mAxisRect->right() + 200; + } else { + if (!mRangeReversed) { + return qLn(value / mRange.lower) / qLn(mRange.upper / mRange.lower) * mAxisRect->width() + mAxisRect->left(); + } else { + return qLn(mRange.upper / value) / qLn(mRange.upper / mRange.lower) * mAxisRect->width() + mAxisRect->left(); + } + } + } + } else { // orientation() == Qt::Vertical + if (mScaleType == stLinear) { + if (!mRangeReversed) { + return mAxisRect->bottom() - (value - mRange.lower) / mRange.size() * mAxisRect->height(); + } else { + return mAxisRect->bottom() - (mRange.upper - value) / mRange.size() * mAxisRect->height(); + } + } else { // mScaleType == stLogarithmic + if (value >= 0.0 && mRange.upper < 0.0) { // invalid value for logarithmic scale, just draw it outside visible range + return !mRangeReversed ? mAxisRect->top() - 200 : mAxisRect->bottom() + 200; + } else if (value <= 0.0 && mRange.upper >= 0.0) { // invalid value for logarithmic scale, just draw it outside visible range + return !mRangeReversed ? mAxisRect->bottom() + 200 : mAxisRect->top() - 200; + } else { + if (!mRangeReversed) { + return mAxisRect->bottom() - qLn(value / mRange.lower) / qLn(mRange.upper / mRange.lower) * mAxisRect->height(); + } else { + return mAxisRect->bottom() - qLn(mRange.upper / value) / qLn(mRange.upper / mRange.lower) * mAxisRect->height(); + } + } + } } - } else // orientation() == Qt::Vertical - { - if (mScaleType == stLinear) - { - if (!mRangeReversed) - return mAxisRect->bottom()-(value-mRange.lower)/mRange.size()*mAxisRect->height(); - else - return mAxisRect->bottom()-(mRange.upper-value)/mRange.size()*mAxisRect->height(); - } else // mScaleType == stLogarithmic - { - if (value >= 0.0 && mRange.upper < 0.0) // invalid value for logarithmic scale, just draw it outside visible range - return !mRangeReversed ? mAxisRect->top()-200 : mAxisRect->bottom()+200; - else if (value <= 0.0 && mRange.upper >= 0.0) // invalid value for logarithmic scale, just draw it outside visible range - return !mRangeReversed ? mAxisRect->bottom()+200 : mAxisRect->top()-200; - else - { - if (!mRangeReversed) - return mAxisRect->bottom()-qLn(value/mRange.lower)/qLn(mRange.upper/mRange.lower)*mAxisRect->height(); - else - return mAxisRect->bottom()-qLn(mRange.upper/value)/qLn(mRange.upper/mRange.lower)*mAxisRect->height(); - } - } - } } /*! Returns the part of the axis that is hit by \a pos (in pixels). The return value of this function is independent of the user-selectable parts defined with \ref setSelectableParts. Further, this function does not change the current selection state of the axis. - + If the axis is not visible (\ref setVisible), this function always returns \ref spNone. - + \see setSelectedParts, setSelectableParts, QCustomPlot::setInteractions */ QCPAxis::SelectablePart QCPAxis::getPartAt(const QPointF &pos) const { - if (!mVisible) - return spNone; - - if (mAxisPainter->axisSelectionBox().contains(pos.toPoint())) - return spAxis; - else if (mAxisPainter->tickLabelsSelectionBox().contains(pos.toPoint())) - return spTickLabels; - else if (mAxisPainter->labelSelectionBox().contains(pos.toPoint())) - return spAxisLabel; - else - return spNone; + if (!mVisible) { + return spNone; + } + + if (mAxisPainter->axisSelectionBox().contains(pos.toPoint())) { + return spAxis; + } else if (mAxisPainter->tickLabelsSelectionBox().contains(pos.toPoint())) { + return spTickLabels; + } else if (mAxisPainter->labelSelectionBox().contains(pos.toPoint())) { + return spAxisLabel; + } else { + return spNone; + } } /* inherits documentation from base class */ double QCPAxis::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { - if (!mParentPlot) return -1; - SelectablePart part = getPartAt(pos); - if ((onlySelectable && !mSelectableParts.testFlag(part)) || part == spNone) - return -1; - - if (details) - details->setValue(part); - return mParentPlot->selectionTolerance()*0.99; + if (!mParentPlot) { + return -1; + } + SelectablePart part = getPartAt(pos); + if ((onlySelectable && !mSelectableParts.testFlag(part)) || part == spNone) { + return -1; + } + + if (details) { + details->setValue(part); + } + return mParentPlot->selectionTolerance() * 0.99; } /*! Returns a list of all the plottables that have this axis as key or value axis. - + If you are only interested in plottables of type QCPGraph, see \ref graphs. - + \see graphs, items */ -QList QCPAxis::plottables() const +QList QCPAxis::plottables() const { - QList result; - if (!mParentPlot) return result; - - foreach (QCPAbstractPlottable *plottable, mParentPlot->mPlottables) - { - if (plottable->keyAxis() == this || plottable->valueAxis() == this) - result.append(plottable); - } - return result; + QList result; + if (!mParentPlot) { + return result; + } + + foreach (QCPAbstractPlottable *plottable, mParentPlot->mPlottables) { + if (plottable->keyAxis() == this || plottable->valueAxis() == this) { + result.append(plottable); + } + } + return result; } /*! Returns a list of all the graphs that have this axis as key or value axis. - + \see plottables, items */ -QList QCPAxis::graphs() const +QList QCPAxis::graphs() const { - QList result; - if (!mParentPlot) return result; - - foreach (QCPGraph *graph, mParentPlot->mGraphs) - { - if (graph->keyAxis() == this || graph->valueAxis() == this) - result.append(graph); - } - return result; + QList result; + if (!mParentPlot) { + return result; + } + + foreach (QCPGraph *graph, mParentPlot->mGraphs) { + if (graph->keyAxis() == this || graph->valueAxis() == this) { + result.append(graph); + } + } + return result; } /*! Returns a list of all the items that are associated with this axis. An item is considered associated with an axis if at least one of its positions uses the axis as key or value axis. - + \see plottables, graphs */ -QList QCPAxis::items() const +QList QCPAxis::items() const { - QList result; - if (!mParentPlot) return result; - - foreach (QCPAbstractItem *item, mParentPlot->mItems) - { - foreach (QCPItemPosition *position, item->positions()) - { - if (position->keyAxis() == this || position->valueAxis() == this) - { - result.append(item); - break; - } + QList result; + if (!mParentPlot) { + return result; } - } - return result; + + foreach (QCPAbstractItem *item, mParentPlot->mItems) { + foreach (QCPItemPosition *position, item->positions()) { + if (position->keyAxis() == this || position->valueAxis() == this) { + result.append(item); + break; + } + } + } + return result; } /*! @@ -9451,16 +9562,20 @@ QList QCPAxis::items() const */ QCPAxis::AxisType QCPAxis::marginSideToAxisType(QCP::MarginSide side) { - switch (side) - { - case QCP::msLeft: return atLeft; - case QCP::msRight: return atRight; - case QCP::msTop: return atTop; - case QCP::msBottom: return atBottom; - default: break; - } - qDebug() << Q_FUNC_INFO << "Invalid margin side passed:" << static_cast(side); - return atLeft; + switch (side) { + case QCP::msLeft: + return atLeft; + case QCP::msRight: + return atRight; + case QCP::msTop: + return atTop; + case QCP::msBottom: + return atBottom; + default: + break; + } + qDebug() << Q_FUNC_INFO << "Invalid margin side passed:" << static_cast(side); + return atLeft; } /*! @@ -9468,42 +9583,46 @@ QCPAxis::AxisType QCPAxis::marginSideToAxisType(QCP::MarginSide side) */ QCPAxis::AxisType QCPAxis::opposite(QCPAxis::AxisType type) { - switch (type) - { - case atLeft: return atRight; - case atRight: return atLeft; - case atBottom: return atTop; - case atTop: return atBottom; - } - qDebug() << Q_FUNC_INFO << "invalid axis type"; - return atLeft; + switch (type) { + case atLeft: + return atRight; + case atRight: + return atLeft; + case atBottom: + return atTop; + case atTop: + return atBottom; + } + qDebug() << Q_FUNC_INFO << "invalid axis type"; + return atLeft; } /* inherits documentation from base class */ void QCPAxis::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) { - Q_UNUSED(event) - SelectablePart part = details.value(); - if (mSelectableParts.testFlag(part)) - { - SelectableParts selBefore = mSelectedParts; - setSelectedParts(additive ? mSelectedParts^part : part); - if (selectionStateChanged) - *selectionStateChanged = mSelectedParts != selBefore; - } + Q_UNUSED(event) + SelectablePart part = details.value(); + if (mSelectableParts.testFlag(part)) { + SelectableParts selBefore = mSelectedParts; + setSelectedParts(additive ? mSelectedParts ^part : part); + if (selectionStateChanged) { + *selectionStateChanged = mSelectedParts != selBefore; + } + } } /* inherits documentation from base class */ void QCPAxis::deselectEvent(bool *selectionStateChanged) { - SelectableParts selBefore = mSelectedParts; - setSelectedParts(mSelectedParts & ~mSelectableParts); - if (selectionStateChanged) - *selectionStateChanged = mSelectedParts != selBefore; + SelectableParts selBefore = mSelectedParts; + setSelectedParts(mSelectedParts & ~mSelectableParts); + if (selectionStateChanged) { + *selectionStateChanged = mSelectedParts != selBefore; + } } /*! \internal - + This mouse event reimplementation provides the functionality to let the user drag individual axes exclusively, by startig the drag on top of the axis. @@ -9511,98 +9630,93 @@ void QCPAxis::deselectEvent(bool *selectionStateChanged) must be configured accordingly, i.e. it must allow range dragging in the orientation of this axis (\ref QCPAxisRect::setRangeDrag) and this axis must be a draggable axis (\ref QCPAxisRect::setRangeDragAxes) - + \seebaseclassmethod - + \note The dragging of possibly multiple axes at once by starting the drag anywhere in the axis rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::mousePressEvent. */ void QCPAxis::mousePressEvent(QMouseEvent *event, const QVariant &details) { - Q_UNUSED(details) - if (!mParentPlot->interactions().testFlag(QCP::iRangeDrag) || - !mAxisRect->rangeDrag().testFlag(orientation()) || - !mAxisRect->rangeDragAxes(orientation()).contains(this)) - { - event->ignore(); - return; - } - - if (event->buttons() & Qt::LeftButton) - { - mDragging = true; - // initialize antialiasing backup in case we start dragging: - if (mParentPlot->noAntialiasingOnDrag()) - { - mAADragBackup = mParentPlot->antialiasedElements(); - mNotAADragBackup = mParentPlot->notAntialiasedElements(); + Q_UNUSED(details) + if (!mParentPlot->interactions().testFlag(QCP::iRangeDrag) || + !mAxisRect->rangeDrag().testFlag(orientation()) || + !mAxisRect->rangeDragAxes(orientation()).contains(this)) { + event->ignore(); + return; + } + + if (event->buttons() & Qt::LeftButton) { + mDragging = true; + // initialize antialiasing backup in case we start dragging: + if (mParentPlot->noAntialiasingOnDrag()) { + mAADragBackup = mParentPlot->antialiasedElements(); + mNotAADragBackup = mParentPlot->notAntialiasedElements(); + } + // Mouse range dragging interaction: + if (mParentPlot->interactions().testFlag(QCP::iRangeDrag)) { + mDragStartRange = mRange; + } } - // Mouse range dragging interaction: - if (mParentPlot->interactions().testFlag(QCP::iRangeDrag)) - mDragStartRange = mRange; - } } /*! \internal - + This mouse event reimplementation provides the functionality to let the user drag individual axes exclusively, by startig the drag on top of the axis. - + \seebaseclassmethod - + \note The dragging of possibly multiple axes at once by starting the drag anywhere in the axis rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::mousePressEvent. - + \see QCPAxis::mousePressEvent */ void QCPAxis::mouseMoveEvent(QMouseEvent *event, const QPointF &startPos) { - if (mDragging) - { - const double startPixel = orientation() == Qt::Horizontal ? startPos.x() : startPos.y(); - const double currentPixel = orientation() == Qt::Horizontal ? event->pos().x() : event->pos().y(); - if (mScaleType == QCPAxis::stLinear) - { - const double diff = pixelToCoord(startPixel) - pixelToCoord(currentPixel); - setRange(mDragStartRange.lower+diff, mDragStartRange.upper+diff); - } else if (mScaleType == QCPAxis::stLogarithmic) - { - const double diff = pixelToCoord(startPixel) / pixelToCoord(currentPixel); - setRange(mDragStartRange.lower*diff, mDragStartRange.upper*diff); + if (mDragging) { + const double startPixel = orientation() == Qt::Horizontal ? startPos.x() : startPos.y(); + const double currentPixel = orientation() == Qt::Horizontal ? event->pos().x() : event->pos().y(); + if (mScaleType == QCPAxis::stLinear) { + const double diff = pixelToCoord(startPixel) - pixelToCoord(currentPixel); + setRange(mDragStartRange.lower + diff, mDragStartRange.upper + diff); + } else if (mScaleType == QCPAxis::stLogarithmic) { + const double diff = pixelToCoord(startPixel) / pixelToCoord(currentPixel); + setRange(mDragStartRange.lower * diff, mDragStartRange.upper * diff); + } + + if (mParentPlot->noAntialiasingOnDrag()) { + mParentPlot->setNotAntialiasedElements(QCP::aeAll); + } + mParentPlot->replot(QCustomPlot::rpQueuedReplot); } - - if (mParentPlot->noAntialiasingOnDrag()) - mParentPlot->setNotAntialiasedElements(QCP::aeAll); - mParentPlot->replot(QCustomPlot::rpQueuedReplot); - } } /*! \internal - + This mouse event reimplementation provides the functionality to let the user drag individual axes exclusively, by startig the drag on top of the axis. - + \seebaseclassmethod - + \note The dragging of possibly multiple axes at once by starting the drag anywhere in the axis rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::mousePressEvent. - + \see QCPAxis::mousePressEvent */ void QCPAxis::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos) { - Q_UNUSED(event) - Q_UNUSED(startPos) - mDragging = false; - if (mParentPlot->noAntialiasingOnDrag()) - { - mParentPlot->setAntialiasedElements(mAADragBackup); - mParentPlot->setNotAntialiasedElements(mNotAADragBackup); - } + Q_UNUSED(event) + Q_UNUSED(startPos) + mDragging = false; + if (mParentPlot->noAntialiasingOnDrag()) { + mParentPlot->setAntialiasedElements(mAADragBackup); + mParentPlot->setNotAntialiasedElements(mNotAADragBackup); + } } /*! \internal - + This mouse event reimplementation provides the functionality to let the user zoom individual axes exclusively, by performing the wheel event on top of the axis. @@ -9610,39 +9724,38 @@ void QCPAxis::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos) must be configured accordingly, i.e. it must allow range zooming in the orientation of this axis (\ref QCPAxisRect::setRangeZoom) and this axis must be a zoomable axis (\ref QCPAxisRect::setRangeZoomAxes) - + \seebaseclassmethod - + \note The zooming of possibly multiple axes at once by performing the wheel event anywhere in the axis rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::wheelEvent. */ void QCPAxis::wheelEvent(QWheelEvent *event) { - // Mouse range zooming interaction: - if (!mParentPlot->interactions().testFlag(QCP::iRangeZoom) || - !mAxisRect->rangeZoom().testFlag(orientation()) || - !mAxisRect->rangeZoomAxes(orientation()).contains(this)) - { - event->ignore(); - return; - } - + // Mouse range zooming interaction: + if (!mParentPlot->interactions().testFlag(QCP::iRangeZoom) || + !mAxisRect->rangeZoom().testFlag(orientation()) || + !mAxisRect->rangeZoomAxes(orientation()).contains(this)) { + event->ignore(); + return; + } + #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) - const double delta = event->delta(); + const double delta = event->delta(); #else - const double delta = event->angleDelta().y(); + const double delta = event->angleDelta().y(); #endif - + #if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) - const QPointF pos = event->pos(); + const QPointF pos = event->pos(); #else - const QPointF pos = event->position(); + const QPointF pos = event->position(); #endif - - const double wheelSteps = delta/120.0; // a single step delta is +/-120 usually - const double factor = qPow(mAxisRect->rangeZoomFactor(orientation()), wheelSteps); - scaleRange(factor, pixelToCoord(orientation() == Qt::Horizontal ? pos.x() : pos.y())); - mParentPlot->replot(); + + const double wheelSteps = delta / 120.0; // a single step delta is +/-120 usually + const double factor = qPow(mAxisRect->rangeZoomFactor(orientation()), wheelSteps); + scaleRange(factor, pixelToCoord(orientation() == Qt::Horizontal ? pos.x() : pos.y())); + mParentPlot->replot(); } /*! \internal @@ -9651,223 +9764,227 @@ void QCPAxis::wheelEvent(QWheelEvent *event) before drawing axis lines. This is the antialiasing state the painter passed to the \ref draw method is in by default. - + 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. - + \seebaseclassmethod - + \see setAntialiased */ void QCPAxis::applyDefaultAntialiasingHint(QCPPainter *painter) const { - applyAntialiasingHint(painter, mAntialiased, QCP::aeAxes); + applyAntialiasingHint(painter, mAntialiased, QCP::aeAxes); } /*! \internal - + Draws the axis with the specified \a painter, using the internal QCPAxisPainterPrivate instance. \seebaseclassmethod */ void QCPAxis::draw(QCPPainter *painter) { - 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(mTickVector.size()); - tickLabels.reserve(mTickVector.size()); - subTickPositions.reserve(mSubTickVector.size()); - - if (mTicks) - { - for (int i=0; i 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(mTickVector.size()); + tickLabels.reserve(mTickVector.size()); + subTickPositions.reserve(mSubTickVector.size()); + + if (mTicks) { + for (int i = 0; i < mTickVector.size(); ++i) { + tickPositions.append(coordToPixel(mTickVector.at(i))); + if (mTickLabels) { + tickLabels.append(mTickVectorLabels.at(i)); + } + } + + if (mSubTicks) { + const int subTickCount = mSubTickVector.size(); + for (int i = 0; i < subTickCount; ++i) { + subTickPositions.append(coordToPixel(mSubTickVector.at(i))); + } + } } - if (mSubTicks) - { - const int subTickCount = mSubTickVector.size(); - for (int i=0; itype = mAxisType; - mAxisPainter->basePen = getBasePen(); - mAxisPainter->labelFont = getLabelFont(); - mAxisPainter->labelColor = getLabelColor(); - mAxisPainter->label = mLabel; - mAxisPainter->substituteExponent = mNumberBeautifulPowers; - mAxisPainter->tickPen = getTickPen(); - mAxisPainter->subTickPen = getSubTickPen(); - mAxisPainter->tickLabelFont = getTickLabelFont(); - mAxisPainter->tickLabelColor = getTickLabelColor(); - mAxisPainter->axisRect = mAxisRect->rect(); - mAxisPainter->viewportRect = mParentPlot->viewport(); - mAxisPainter->abbreviateDecimalPowers = mScaleType == stLogarithmic; - mAxisPainter->reversedEndings = mRangeReversed; - mAxisPainter->tickPositions = tickPositions; - mAxisPainter->tickLabels = tickLabels; - mAxisPainter->subTickPositions = subTickPositions; - mAxisPainter->draw(painter); + // transfer all properties of this axis to QCPAxisPainterPrivate which it needs to draw the axis. + // Note that some axis painter properties are already set by direct feed-through with QCPAxis setters + mAxisPainter->type = mAxisType; + mAxisPainter->basePen = getBasePen(); + mAxisPainter->labelFont = getLabelFont(); + mAxisPainter->labelColor = getLabelColor(); + mAxisPainter->label = mLabel; + mAxisPainter->substituteExponent = mNumberBeautifulPowers; + mAxisPainter->tickPen = getTickPen(); + mAxisPainter->subTickPen = getSubTickPen(); + mAxisPainter->tickLabelFont = getTickLabelFont(); + mAxisPainter->tickLabelColor = getTickLabelColor(); + mAxisPainter->axisRect = mAxisRect->rect(); + mAxisPainter->viewportRect = mParentPlot->viewport(); + mAxisPainter->abbreviateDecimalPowers = mScaleType == stLogarithmic; + mAxisPainter->reversedEndings = mRangeReversed; + mAxisPainter->tickPositions = tickPositions; + mAxisPainter->tickLabels = tickLabels; + mAxisPainter->subTickPositions = subTickPositions; + mAxisPainter->draw(painter); } /*! \internal - + Prepares the internal tick vector, sub tick vector and tick label vector. This is done by calling QCPAxisTicker::generate on the currently installed ticker. - + 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::setupTickVectors() { - if (!mParentPlot) return; - if ((!mTicks && !mTickLabels && !mGrid->visible()) || mRange.size() <= 0) return; - - QVector oldLabels = mTickVectorLabels; - mTicker->generate(mRange, mParentPlot->locale(), mNumberFormatChar, mNumberPrecision, mTickVector, mSubTicks ? &mSubTickVector : nullptr, mTickLabels ? &mTickVectorLabels : nullptr); - mCachedMarginValid &= mTickVectorLabels == oldLabels; // if labels have changed, margin might have changed, too + if (!mParentPlot) { + return; + } + if ((!mTicks && !mTickLabels && !mGrid->visible()) || mRange.size() <= 0) { + return; + } + + QVector oldLabels = mTickVectorLabels; + mTicker->generate(mRange, mParentPlot->locale(), mNumberFormatChar, mNumberPrecision, mTickVector, mSubTicks ? &mSubTickVector : nullptr, mTickLabels ? &mTickVectorLabels : nullptr); + mCachedMarginValid &= mTickVectorLabels == oldLabels; // if labels have changed, margin might have changed, too } /*! \internal - + Returns the pen that is used to draw the axis base line. Depending on the selection state, this is either mSelectedBasePen or mBasePen. */ QPen QCPAxis::getBasePen() const { - return mSelectedParts.testFlag(spAxis) ? mSelectedBasePen : mBasePen; + return mSelectedParts.testFlag(spAxis) ? mSelectedBasePen : mBasePen; } /*! \internal - + Returns the pen that is used to draw the (major) ticks. Depending on the selection state, this is either mSelectedTickPen or mTickPen. */ QPen QCPAxis::getTickPen() const { - return mSelectedParts.testFlag(spAxis) ? mSelectedTickPen : mTickPen; + return mSelectedParts.testFlag(spAxis) ? mSelectedTickPen : mTickPen; } /*! \internal - + Returns the pen that is used to draw the subticks. Depending on the selection state, this is either mSelectedSubTickPen or mSubTickPen. */ QPen QCPAxis::getSubTickPen() const { - return mSelectedParts.testFlag(spAxis) ? mSelectedSubTickPen : mSubTickPen; + return mSelectedParts.testFlag(spAxis) ? mSelectedSubTickPen : mSubTickPen; } /*! \internal - + Returns the font that is used to draw the tick labels. Depending on the selection state, this is either mSelectedTickLabelFont or mTickLabelFont. */ QFont QCPAxis::getTickLabelFont() const { - return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelFont : mTickLabelFont; + return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelFont : mTickLabelFont; } /*! \internal - + Returns the font that is used to draw the axis label. Depending on the selection state, this is either mSelectedLabelFont or mLabelFont. */ QFont QCPAxis::getLabelFont() const { - return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelFont : mLabelFont; + return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelFont : mLabelFont; } /*! \internal - + Returns the color that is used to draw the tick labels. Depending on the selection state, this is either mSelectedTickLabelColor or mTickLabelColor. */ QColor QCPAxis::getTickLabelColor() const { - return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelColor : mTickLabelColor; + return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelColor : mTickLabelColor; } /*! \internal - + Returns the color that is used to draw the axis label. Depending on the selection state, this is either mSelectedLabelColor or mLabelColor. */ QColor QCPAxis::getLabelColor() const { - return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelColor : mLabelColor; + return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelColor : mLabelColor; } /*! \internal - + Returns the appropriate outward margin for this axis. It is needed if \ref QCPAxisRect::setAutoMargins is set to true on the parent axis rect. An axis with axis type \ref atLeft will return an appropriate left margin, \ref atBottom will return an appropriate bottom margin and so forth. For the calculation, this function goes through similar steps as \ref draw, so changing one function likely requires the modification of the other one as well. - + The margin consists of the outward tick length, tick label padding, tick label size, label padding, label size, and padding. - + The margin is cached internally, so repeated calls while leaving the axis range, fonts, etc. unchanged are very fast. */ int QCPAxis::calculateMargin() { - if (!mVisible) // if not visible, directly return 0, don't cache 0 because we can't react to setVisible in QCPAxis - return 0; - - if (mCachedMarginValid) - return mCachedMargin; - - // run through similar steps as QCPAxis::draw, and calculate margin needed to fit axis and its labels - int margin = 0; - - QVector tickPositions; // the final coordToPixel transformed vector passed to QCPAxisPainter - QVector tickLabels; // the final vector passed to QCPAxisPainter - tickPositions.reserve(mTickVector.size()); - tickLabels.reserve(mTickVector.size()); - - if (mTicks) - { - for (int i=0; itype = mAxisType; - mAxisPainter->labelFont = getLabelFont(); - mAxisPainter->label = mLabel; - mAxisPainter->tickLabelFont = mTickLabelFont; - mAxisPainter->axisRect = mAxisRect->rect(); - mAxisPainter->viewportRect = mParentPlot->viewport(); - mAxisPainter->tickPositions = tickPositions; - mAxisPainter->tickLabels = tickLabels; - margin += mAxisPainter->size(); - margin += mPadding; - mCachedMargin = margin; - mCachedMarginValid = true; - return margin; + if (mCachedMarginValid) { + return mCachedMargin; + } + + // run through similar steps as QCPAxis::draw, and calculate margin needed to fit axis and its labels + int margin = 0; + + QVector tickPositions; // the final coordToPixel transformed vector passed to QCPAxisPainter + QVector tickLabels; // the final vector passed to QCPAxisPainter + tickPositions.reserve(mTickVector.size()); + tickLabels.reserve(mTickVector.size()); + + if (mTicks) { + for (int i = 0; i < mTickVector.size(); ++i) { + tickPositions.append(coordToPixel(mTickVector.at(i))); + if (mTickLabels) { + tickLabels.append(mTickVectorLabels.at(i)); + } + } + } + // transfer all properties of this axis to QCPAxisPainterPrivate which it needs to calculate the size. + // Note that some axis painter properties are already set by direct feed-through with QCPAxis setters + mAxisPainter->type = mAxisType; + mAxisPainter->labelFont = getLabelFont(); + mAxisPainter->label = mLabel; + mAxisPainter->tickLabelFont = mTickLabelFont; + mAxisPainter->axisRect = mAxisRect->rect(); + mAxisPainter->viewportRect = mParentPlot->viewport(); + mAxisPainter->tickPositions = tickPositions; + mAxisPainter->tickLabels = tickLabels; + margin += mAxisPainter->size(); + margin += mPadding; + + mCachedMargin = margin; + mCachedMarginValid = true; + return margin; } /* inherits documentation from base class */ QCP::Interaction QCPAxis::selectionCategory() const { - return QCP::iSelectAxes; + return QCP::iSelectAxes; } @@ -9879,9 +9996,9 @@ QCP::Interaction QCPAxis::selectionCategory() const \internal \brief (Private) - + This is a private class and not part of the public QCustomPlot interface. - + It is used by QCPAxis to do the low-level drawing of axis backbone, tick marks, tick labels and axis label. It also buffers the labels to reduce replot times. The parameters are configured by directly accessing the public member variables. @@ -9892,27 +10009,27 @@ QCP::Interaction QCPAxis::selectionCategory() const redraw, to utilize the caching mechanisms. */ QCPAxisPainterPrivate::QCPAxisPainterPrivate(QCustomPlot *parentPlot) : - type(QCPAxis::atLeft), - basePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), - lowerEnding(QCPLineEnding::esNone), - upperEnding(QCPLineEnding::esNone), - labelPadding(0), - tickLabelPadding(0), - tickLabelRotation(0), - tickLabelSide(QCPAxis::lsOutside), - substituteExponent(true), - numberMultiplyCross(false), - tickLengthIn(5), - tickLengthOut(0), - subTickLengthIn(2), - subTickLengthOut(0), - tickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), - subTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), - offset(0), - abbreviateDecimalPowers(false), - reversedEndings(false), - mParentPlot(parentPlot), - mLabelCache(16) // cache at most 16 (tick) labels + type(QCPAxis::atLeft), + basePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), + lowerEnding(QCPLineEnding::esNone), + upperEnding(QCPLineEnding::esNone), + labelPadding(0), + tickLabelPadding(0), + tickLabelRotation(0), + tickLabelSide(QCPAxis::lsOutside), + substituteExponent(true), + numberMultiplyCross(false), + tickLengthIn(5), + tickLengthOut(0), + subTickLengthIn(2), + subTickLengthOut(0), + tickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), + subTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), + offset(0), + abbreviateDecimalPowers(false), + reversedEndings(false), + mParentPlot(parentPlot), + mLabelCache(16) // cache at most 16 (tick) labels { } @@ -9921,258 +10038,262 @@ QCPAxisPainterPrivate::~QCPAxisPainterPrivate() } /*! \internal - + Draws the axis with the specified \a painter. - + The selection boxes (mAxisSelectionBox, mTickLabelsSelectionBox, mLabelSelectionBox) are set here, too. */ void QCPAxisPainterPrivate::draw(QCPPainter *painter) { - QByteArray newHash = generateLabelParameterHash(); - if (newHash != mLabelParameterHash) - { - mLabelCache.clear(); - mLabelParameterHash = newHash; - } - - QPoint origin; - switch (type) - { - case QCPAxis::atLeft: origin = axisRect.bottomLeft() +QPoint(-offset, 0); break; - case QCPAxis::atRight: origin = axisRect.bottomRight()+QPoint(+offset, 0); break; - case QCPAxis::atTop: origin = axisRect.topLeft() +QPoint(0, -offset); break; - case QCPAxis::atBottom: origin = axisRect.bottomLeft() +QPoint(0, +offset); break; - } + QByteArray newHash = generateLabelParameterHash(); + if (newHash != mLabelParameterHash) { + mLabelCache.clear(); + mLabelParameterHash = newHash; + } - double xCor = 0, yCor = 0; // paint system correction, for pixel exact matches (affects baselines and ticks of top/right axes) - switch (type) - { - case QCPAxis::atTop: yCor = -1; break; - case QCPAxis::atRight: xCor = 1; break; - default: break; - } - int margin = 0; - // draw baseline: - QLineF baseLine; - painter->setPen(basePen); - if (QCPAxis::orientation(type) == Qt::Horizontal) - baseLine.setPoints(origin+QPointF(xCor, yCor), origin+QPointF(axisRect.width()+xCor, yCor)); - else - baseLine.setPoints(origin+QPointF(xCor, yCor), origin+QPointF(xCor, -axisRect.height()+yCor)); - if (reversedEndings) - baseLine = QLineF(baseLine.p2(), baseLine.p1()); // won't make a difference for line itself, but for line endings later - painter->drawLine(baseLine); - - // draw ticks: - if (!tickPositions.isEmpty()) - { - painter->setPen(tickPen); - int tickDir = (type == QCPAxis::atBottom || type == QCPAxis::atRight) ? -1 : 1; // direction of ticks ("inward" is right for left axis and left for right axis) - if (QCPAxis::orientation(type) == Qt::Horizontal) - { - foreach (double tickPos, tickPositions) - painter->drawLine(QLineF(tickPos+xCor, origin.y()-tickLengthOut*tickDir+yCor, tickPos+xCor, origin.y()+tickLengthIn*tickDir+yCor)); - } else - { - foreach (double tickPos, tickPositions) - painter->drawLine(QLineF(origin.x()-tickLengthOut*tickDir+xCor, tickPos+yCor, origin.x()+tickLengthIn*tickDir+xCor, tickPos+yCor)); + QPoint origin; + switch (type) { + case QCPAxis::atLeft: + origin = axisRect.bottomLeft() + QPoint(-offset, 0); + break; + case QCPAxis::atRight: + origin = axisRect.bottomRight() + QPoint(+offset, 0); + break; + case QCPAxis::atTop: + origin = axisRect.topLeft() + QPoint(0, -offset); + break; + case QCPAxis::atBottom: + origin = axisRect.bottomLeft() + QPoint(0, +offset); + break; } - } - - // draw subticks: - if (!subTickPositions.isEmpty()) - { - painter->setPen(subTickPen); - // direction of ticks ("inward" is right for left axis and left for right axis) - int tickDir = (type == QCPAxis::atBottom || type == QCPAxis::atRight) ? -1 : 1; - if (QCPAxis::orientation(type) == Qt::Horizontal) - { - foreach (double subTickPos, subTickPositions) - painter->drawLine(QLineF(subTickPos+xCor, origin.y()-subTickLengthOut*tickDir+yCor, subTickPos+xCor, origin.y()+subTickLengthIn*tickDir+yCor)); - } else - { - foreach (double subTickPos, subTickPositions) - painter->drawLine(QLineF(origin.x()-subTickLengthOut*tickDir+xCor, subTickPos+yCor, origin.x()+subTickLengthIn*tickDir+xCor, subTickPos+yCor)); + + double xCor = 0, yCor = 0; // paint system correction, for pixel exact matches (affects baselines and ticks of top/right axes) + switch (type) { + case QCPAxis::atTop: + yCor = -1; + break; + case QCPAxis::atRight: + xCor = 1; + break; + default: + break; } - } - margin += qMax(0, qMax(tickLengthOut, subTickLengthOut)); - - // draw axis base endings: - bool antialiasingBackup = painter->antialiasing(); - painter->setAntialiasing(true); // always want endings to be antialiased, even if base and ticks themselves aren't - painter->setBrush(QBrush(basePen.color())); - QCPVector2D baseLineVector(baseLine.dx(), baseLine.dy()); - if (lowerEnding.style() != QCPLineEnding::esNone) - lowerEnding.draw(painter, QCPVector2D(baseLine.p1())-baseLineVector.normalized()*lowerEnding.realLength()*(lowerEnding.inverted()?-1:1), -baseLineVector); - if (upperEnding.style() != QCPLineEnding::esNone) - upperEnding.draw(painter, QCPVector2D(baseLine.p2())+baseLineVector.normalized()*upperEnding.realLength()*(upperEnding.inverted()?-1:1), baseLineVector); - painter->setAntialiasing(antialiasingBackup); - - // tick labels: - QRect oldClipRect; - if (tickLabelSide == QCPAxis::lsInside) // if using inside labels, clip them to the axis rect - { - oldClipRect = painter->clipRegion().boundingRect(); - painter->setClipRect(axisRect); - } - QSize tickLabelsSize(0, 0); // size of largest tick label, for offset calculation of axis label - if (!tickLabels.isEmpty()) - { - if (tickLabelSide == QCPAxis::lsOutside) - margin += tickLabelPadding; - painter->setFont(tickLabelFont); - painter->setPen(QPen(tickLabelColor)); - const int maxLabelIndex = qMin(tickPositions.size(), tickLabels.size()); - int distanceToAxis = margin; - if (tickLabelSide == QCPAxis::lsInside) - distanceToAxis = -(qMax(tickLengthIn, subTickLengthIn)+tickLabelPadding); - for (int i=0; isetClipRect(oldClipRect); - - // axis label: - QRect labelBounds; - if (!label.isEmpty()) - { - margin += labelPadding; - painter->setFont(labelFont); - painter->setPen(QPen(labelColor)); - labelBounds = painter->fontMetrics().boundingRect(0, 0, 0, 0, Qt::TextDontClip, label); - if (type == QCPAxis::atLeft) - { - QTransform oldTransform = painter->transform(); - painter->translate((origin.x()-margin-labelBounds.height()), origin.y()); - painter->rotate(-90); - painter->drawText(0, 0, axisRect.height(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label); - painter->setTransform(oldTransform); + int margin = 0; + // draw baseline: + QLineF baseLine; + painter->setPen(basePen); + if (QCPAxis::orientation(type) == Qt::Horizontal) { + baseLine.setPoints(origin + QPointF(xCor, yCor), origin + QPointF(axisRect.width() + xCor, yCor)); + } else { + baseLine.setPoints(origin + QPointF(xCor, yCor), origin + QPointF(xCor, -axisRect.height() + yCor)); } - else if (type == QCPAxis::atRight) - { - QTransform oldTransform = painter->transform(); - painter->translate((origin.x()+margin+labelBounds.height()), origin.y()-axisRect.height()); - painter->rotate(90); - painter->drawText(0, 0, axisRect.height(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label); - painter->setTransform(oldTransform); + if (reversedEndings) { + baseLine = QLineF(baseLine.p2(), baseLine.p1()); // won't make a difference for line itself, but for line endings later } - else if (type == QCPAxis::atTop) - painter->drawText(origin.x(), origin.y()-margin-labelBounds.height(), axisRect.width(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label); - else if (type == QCPAxis::atBottom) - painter->drawText(origin.x(), origin.y()+margin, axisRect.width(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label); - } - - // set selection boxes: - int selectionTolerance = 0; - if (mParentPlot) - selectionTolerance = mParentPlot->selectionTolerance(); - else - qDebug() << Q_FUNC_INFO << "mParentPlot is null"; - int selAxisOutSize = qMax(qMax(tickLengthOut, subTickLengthOut), selectionTolerance); - int selAxisInSize = selectionTolerance; - int selTickLabelSize; - int selTickLabelOffset; - if (tickLabelSide == QCPAxis::lsOutside) - { - selTickLabelSize = (QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width()); - selTickLabelOffset = qMax(tickLengthOut, subTickLengthOut)+tickLabelPadding; - } else - { - selTickLabelSize = -(QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width()); - selTickLabelOffset = -(qMax(tickLengthIn, subTickLengthIn)+tickLabelPadding); - } - int selLabelSize = labelBounds.height(); - int selLabelOffset = qMax(tickLengthOut, subTickLengthOut)+(!tickLabels.isEmpty() && tickLabelSide == QCPAxis::lsOutside ? tickLabelPadding+selTickLabelSize : 0)+labelPadding; - if (type == QCPAxis::atLeft) - { - mAxisSelectionBox.setCoords(origin.x()-selAxisOutSize, axisRect.top(), origin.x()+selAxisInSize, axisRect.bottom()); - mTickLabelsSelectionBox.setCoords(origin.x()-selTickLabelOffset-selTickLabelSize, axisRect.top(), origin.x()-selTickLabelOffset, axisRect.bottom()); - mLabelSelectionBox.setCoords(origin.x()-selLabelOffset-selLabelSize, axisRect.top(), origin.x()-selLabelOffset, axisRect.bottom()); - } else if (type == QCPAxis::atRight) - { - mAxisSelectionBox.setCoords(origin.x()-selAxisInSize, axisRect.top(), origin.x()+selAxisOutSize, axisRect.bottom()); - mTickLabelsSelectionBox.setCoords(origin.x()+selTickLabelOffset+selTickLabelSize, axisRect.top(), origin.x()+selTickLabelOffset, axisRect.bottom()); - mLabelSelectionBox.setCoords(origin.x()+selLabelOffset+selLabelSize, axisRect.top(), origin.x()+selLabelOffset, axisRect.bottom()); - } else if (type == QCPAxis::atTop) - { - mAxisSelectionBox.setCoords(axisRect.left(), origin.y()-selAxisOutSize, axisRect.right(), origin.y()+selAxisInSize); - mTickLabelsSelectionBox.setCoords(axisRect.left(), origin.y()-selTickLabelOffset-selTickLabelSize, axisRect.right(), origin.y()-selTickLabelOffset); - mLabelSelectionBox.setCoords(axisRect.left(), origin.y()-selLabelOffset-selLabelSize, axisRect.right(), origin.y()-selLabelOffset); - } else if (type == QCPAxis::atBottom) - { - mAxisSelectionBox.setCoords(axisRect.left(), origin.y()-selAxisInSize, axisRect.right(), origin.y()+selAxisOutSize); - mTickLabelsSelectionBox.setCoords(axisRect.left(), origin.y()+selTickLabelOffset+selTickLabelSize, axisRect.right(), origin.y()+selTickLabelOffset); - mLabelSelectionBox.setCoords(axisRect.left(), origin.y()+selLabelOffset+selLabelSize, axisRect.right(), origin.y()+selLabelOffset); - } - mAxisSelectionBox = mAxisSelectionBox.normalized(); - mTickLabelsSelectionBox = mTickLabelsSelectionBox.normalized(); - mLabelSelectionBox = mLabelSelectionBox.normalized(); - // draw hitboxes for debug purposes: - //painter->setBrush(Qt::NoBrush); - //painter->drawRects(QVector() << mAxisSelectionBox << mTickLabelsSelectionBox << mLabelSelectionBox); + painter->drawLine(baseLine); + + // draw ticks: + if (!tickPositions.isEmpty()) { + painter->setPen(tickPen); + int tickDir = (type == QCPAxis::atBottom || type == QCPAxis::atRight) ? -1 : 1; // direction of ticks ("inward" is right for left axis and left for right axis) + if (QCPAxis::orientation(type) == Qt::Horizontal) { + foreach (double tickPos, tickPositions) { + painter->drawLine(QLineF(tickPos + xCor, origin.y() - tickLengthOut * tickDir + yCor, tickPos + xCor, origin.y() + tickLengthIn * tickDir + yCor)); + } + } else { + foreach (double tickPos, tickPositions) { + painter->drawLine(QLineF(origin.x() - tickLengthOut * tickDir + xCor, tickPos + yCor, origin.x() + tickLengthIn * tickDir + xCor, tickPos + yCor)); + } + } + } + + // draw subticks: + if (!subTickPositions.isEmpty()) { + painter->setPen(subTickPen); + // direction of ticks ("inward" is right for left axis and left for right axis) + int tickDir = (type == QCPAxis::atBottom || type == QCPAxis::atRight) ? -1 : 1; + if (QCPAxis::orientation(type) == Qt::Horizontal) { + foreach (double subTickPos, subTickPositions) { + painter->drawLine(QLineF(subTickPos + xCor, origin.y() - subTickLengthOut * tickDir + yCor, subTickPos + xCor, origin.y() + subTickLengthIn * tickDir + yCor)); + } + } else { + foreach (double subTickPos, subTickPositions) { + painter->drawLine(QLineF(origin.x() - subTickLengthOut * tickDir + xCor, subTickPos + yCor, origin.x() + subTickLengthIn * tickDir + xCor, subTickPos + yCor)); + } + } + } + margin += qMax(0, qMax(tickLengthOut, subTickLengthOut)); + + // draw axis base endings: + bool antialiasingBackup = painter->antialiasing(); + painter->setAntialiasing(true); // always want endings to be antialiased, even if base and ticks themselves aren't + painter->setBrush(QBrush(basePen.color())); + QCPVector2D baseLineVector(baseLine.dx(), baseLine.dy()); + if (lowerEnding.style() != QCPLineEnding::esNone) { + lowerEnding.draw(painter, QCPVector2D(baseLine.p1()) - baseLineVector.normalized()*lowerEnding.realLength() * (lowerEnding.inverted() ? -1 : 1), -baseLineVector); + } + if (upperEnding.style() != QCPLineEnding::esNone) { + upperEnding.draw(painter, QCPVector2D(baseLine.p2()) + baseLineVector.normalized()*upperEnding.realLength() * (upperEnding.inverted() ? -1 : 1), baseLineVector); + } + painter->setAntialiasing(antialiasingBackup); + + // tick labels: + QRect oldClipRect; + if (tickLabelSide == QCPAxis::lsInside) { // if using inside labels, clip them to the axis rect + oldClipRect = painter->clipRegion().boundingRect(); + painter->setClipRect(axisRect); + } + QSize tickLabelsSize(0, 0); // size of largest tick label, for offset calculation of axis label + if (!tickLabels.isEmpty()) { + if (tickLabelSide == QCPAxis::lsOutside) { + margin += tickLabelPadding; + } + painter->setFont(tickLabelFont); + painter->setPen(QPen(tickLabelColor)); + const int maxLabelIndex = qMin(tickPositions.size(), tickLabels.size()); + int distanceToAxis = margin; + if (tickLabelSide == QCPAxis::lsInside) { + distanceToAxis = -(qMax(tickLengthIn, subTickLengthIn) + tickLabelPadding); + } + for (int i = 0; i < maxLabelIndex; ++i) { + placeTickLabel(painter, tickPositions.at(i), distanceToAxis, tickLabels.at(i), &tickLabelsSize); + } + if (tickLabelSide == QCPAxis::lsOutside) { + margin += (QCPAxis::orientation(type) == Qt::Horizontal) ? tickLabelsSize.height() : tickLabelsSize.width(); + } + } + if (tickLabelSide == QCPAxis::lsInside) { + painter->setClipRect(oldClipRect); + } + + // axis label: + QRect labelBounds; + if (!label.isEmpty()) { + margin += labelPadding; + painter->setFont(labelFont); + painter->setPen(QPen(labelColor)); + labelBounds = painter->fontMetrics().boundingRect(0, 0, 0, 0, Qt::TextDontClip, label); + if (type == QCPAxis::atLeft) { + QTransform oldTransform = painter->transform(); + painter->translate((origin.x() - margin - labelBounds.height()), origin.y()); + painter->rotate(-90); + painter->drawText(0, 0, axisRect.height(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label); + painter->setTransform(oldTransform); + } else if (type == QCPAxis::atRight) { + QTransform oldTransform = painter->transform(); + painter->translate((origin.x() + margin + labelBounds.height()), origin.y() - axisRect.height()); + painter->rotate(90); + painter->drawText(0, 0, axisRect.height(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label); + painter->setTransform(oldTransform); + } else if (type == QCPAxis::atTop) { + painter->drawText(origin.x(), origin.y() - margin - labelBounds.height(), axisRect.width(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label); + } else if (type == QCPAxis::atBottom) { + painter->drawText(origin.x(), origin.y() + margin, axisRect.width(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label); + } + } + + // set selection boxes: + int selectionTolerance = 0; + if (mParentPlot) { + selectionTolerance = mParentPlot->selectionTolerance(); + } else { + qDebug() << Q_FUNC_INFO << "mParentPlot is null"; + } + int selAxisOutSize = qMax(qMax(tickLengthOut, subTickLengthOut), selectionTolerance); + int selAxisInSize = selectionTolerance; + int selTickLabelSize; + int selTickLabelOffset; + if (tickLabelSide == QCPAxis::lsOutside) { + selTickLabelSize = (QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width()); + selTickLabelOffset = qMax(tickLengthOut, subTickLengthOut) + tickLabelPadding; + } else { + selTickLabelSize = -(QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width()); + selTickLabelOffset = -(qMax(tickLengthIn, subTickLengthIn) + tickLabelPadding); + } + int selLabelSize = labelBounds.height(); + int selLabelOffset = qMax(tickLengthOut, subTickLengthOut) + (!tickLabels.isEmpty() && tickLabelSide == QCPAxis::lsOutside ? tickLabelPadding + selTickLabelSize : 0) + labelPadding; + if (type == QCPAxis::atLeft) { + mAxisSelectionBox.setCoords(origin.x() - selAxisOutSize, axisRect.top(), origin.x() + selAxisInSize, axisRect.bottom()); + mTickLabelsSelectionBox.setCoords(origin.x() - selTickLabelOffset - selTickLabelSize, axisRect.top(), origin.x() - selTickLabelOffset, axisRect.bottom()); + mLabelSelectionBox.setCoords(origin.x() - selLabelOffset - selLabelSize, axisRect.top(), origin.x() - selLabelOffset, axisRect.bottom()); + } else if (type == QCPAxis::atRight) { + mAxisSelectionBox.setCoords(origin.x() - selAxisInSize, axisRect.top(), origin.x() + selAxisOutSize, axisRect.bottom()); + mTickLabelsSelectionBox.setCoords(origin.x() + selTickLabelOffset + selTickLabelSize, axisRect.top(), origin.x() + selTickLabelOffset, axisRect.bottom()); + mLabelSelectionBox.setCoords(origin.x() + selLabelOffset + selLabelSize, axisRect.top(), origin.x() + selLabelOffset, axisRect.bottom()); + } else if (type == QCPAxis::atTop) { + mAxisSelectionBox.setCoords(axisRect.left(), origin.y() - selAxisOutSize, axisRect.right(), origin.y() + selAxisInSize); + mTickLabelsSelectionBox.setCoords(axisRect.left(), origin.y() - selTickLabelOffset - selTickLabelSize, axisRect.right(), origin.y() - selTickLabelOffset); + mLabelSelectionBox.setCoords(axisRect.left(), origin.y() - selLabelOffset - selLabelSize, axisRect.right(), origin.y() - selLabelOffset); + } else if (type == QCPAxis::atBottom) { + mAxisSelectionBox.setCoords(axisRect.left(), origin.y() - selAxisInSize, axisRect.right(), origin.y() + selAxisOutSize); + mTickLabelsSelectionBox.setCoords(axisRect.left(), origin.y() + selTickLabelOffset + selTickLabelSize, axisRect.right(), origin.y() + selTickLabelOffset); + mLabelSelectionBox.setCoords(axisRect.left(), origin.y() + selLabelOffset + selLabelSize, axisRect.right(), origin.y() + selLabelOffset); + } + mAxisSelectionBox = mAxisSelectionBox.normalized(); + mTickLabelsSelectionBox = mTickLabelsSelectionBox.normalized(); + mLabelSelectionBox = mLabelSelectionBox.normalized(); + // draw hitboxes for debug purposes: + //painter->setBrush(Qt::NoBrush); + //painter->drawRects(QVector() << mAxisSelectionBox << mTickLabelsSelectionBox << mLabelSelectionBox); } /*! \internal - + Returns the size ("margin" in QCPAxisRect context, so measured perpendicular to the axis backbone direction) needed to fit the axis. */ int QCPAxisPainterPrivate::size() { - int result = 0; + int result = 0; - QByteArray newHash = generateLabelParameterHash(); - if (newHash != mLabelParameterHash) - { - mLabelCache.clear(); - mLabelParameterHash = newHash; - } - - // get length of tick marks pointing outwards: - if (!tickPositions.isEmpty()) - result += qMax(0, qMax(tickLengthOut, subTickLengthOut)); - - // calculate size of tick labels: - if (tickLabelSide == QCPAxis::lsOutside) - { - QSize tickLabelsSize(0, 0); - if (!tickLabels.isEmpty()) - { - foreach (const QString &tickLabel, tickLabels) - getMaxTickLabelSize(tickLabelFont, tickLabel, &tickLabelsSize); - result += QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width(); - result += tickLabelPadding; + QByteArray newHash = generateLabelParameterHash(); + if (newHash != mLabelParameterHash) { + mLabelCache.clear(); + mLabelParameterHash = newHash; } - } - - // calculate size of axis label (only height needed, because left/right labels are rotated by 90 degrees): - if (!label.isEmpty()) - { - QFontMetrics fontMetrics(labelFont); - QRect bounds; - bounds = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip | Qt::AlignHCenter | Qt::AlignVCenter, label); - result += bounds.height() + labelPadding; - } - return result; + // get length of tick marks pointing outwards: + if (!tickPositions.isEmpty()) { + result += qMax(0, qMax(tickLengthOut, subTickLengthOut)); + } + + // calculate size of tick labels: + if (tickLabelSide == QCPAxis::lsOutside) { + QSize tickLabelsSize(0, 0); + if (!tickLabels.isEmpty()) { + foreach (const QString &tickLabel, tickLabels) { + getMaxTickLabelSize(tickLabelFont, tickLabel, &tickLabelsSize); + } + result += QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width(); + result += tickLabelPadding; + } + } + + // calculate size of axis label (only height needed, because left/right labels are rotated by 90 degrees): + if (!label.isEmpty()) { + QFontMetrics fontMetrics(labelFont); + QRect bounds; + bounds = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip | Qt::AlignHCenter | Qt::AlignVCenter, label); + result += bounds.height() + labelPadding; + } + + return result; } /*! \internal - + Clears the internal label cache. Upon the next \ref draw, all labels will be created new. This method is called automatically in \ref draw, if any parameters have changed that invalidate the cached labels, such as font, color, etc. */ void QCPAxisPainterPrivate::clearCache() { - mLabelCache.clear(); + mLabelCache.clear(); } /*! \internal - + Returns a hash that allows uniquely identifying whether the label parameters have changed such that the cached labels must be refreshed (\ref clearCache). It is used in \ref draw. If the return value of this method hasn't changed since the last redraw, the respective label parameters @@ -10180,120 +10301,126 @@ 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))); - result.append(QByteArray::number(int(numberMultiplyCross))); - result.append(tickLabelColor.name().toLatin1()+QByteArray::number(tickLabelColor.alpha(), 16)); - result.append(tickLabelFont.toString().toLatin1()); - return result; + 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))); + result.append(QByteArray::number(int(numberMultiplyCross))); + result.append(tickLabelColor.name().toLatin1() + QByteArray::number(tickLabelColor.alpha(), 16)); + result.append(tickLabelFont.toString().toLatin1()); + return result; } /*! \internal - + Draws a single tick label with the provided \a painter, utilizing the internal label cache to significantly speed up drawing of labels that were drawn in previous calls. The tick label is always bound to an axis, the distance to the axis is controllable via \a distanceToAxis in pixels. The pixel position in the axis direction is passed in the \a position parameter. Hence for the bottom axis, \a position would indicate the horizontal pixel position (not coordinate), at which the label should be drawn. - + In order to later draw the axis label in a place that doesn't overlap with the tick labels, the largest tick label size is needed. This is acquired by passing a \a tickLabelsSize to the \ref drawTickLabel calls during the process of drawing all tick labels of one axis. In every call, \a tickLabelsSize is expanded, if the drawn label exceeds the value \a tickLabelsSize currently holds. - + The label is drawn with the font and pen that are currently set on the \a painter. To draw superscripted powers, the font is temporarily made smaller by a fixed factor (see \ref getTickLabelData). */ void QCPAxisPainterPrivate::placeTickLabel(QCPPainter *painter, double position, int distanceToAxis, const QString &text, QSize *tickLabelsSize) { - // warning: if you change anything here, also adapt getMaxTickLabelSize() accordingly! - if (text.isEmpty()) return; - QSize finalSize; - QPointF labelAnchor; - switch (type) - { - case QCPAxis::atLeft: labelAnchor = QPointF(axisRect.left()-distanceToAxis-offset, position); break; - case QCPAxis::atRight: labelAnchor = QPointF(axisRect.right()+distanceToAxis+offset, position); break; - case QCPAxis::atTop: labelAnchor = QPointF(position, axisRect.top()-distanceToAxis-offset); break; - case QCPAxis::atBottom: labelAnchor = QPointF(position, axisRect.bottom()+distanceToAxis+offset); break; - } - if (mParentPlot->plottingHints().testFlag(QCP::phCacheLabels) && !painter->modes().testFlag(QCPPainter::pmNoCaching)) // label caching enabled - { - CachedLabel *cachedLabel = mLabelCache.take(text); // attempt to get label from cache - if (!cachedLabel) // no cached label existed, create it - { - 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()); + // warning: if you change anything here, also adapt getMaxTickLabelSize() accordingly! + if (text.isEmpty()) { + return; + } + QSize finalSize; + QPointF labelAnchor; + switch (type) { + case QCPAxis::atLeft: + labelAnchor = QPointF(axisRect.left() - distanceToAxis - offset, position); + break; + case QCPAxis::atRight: + labelAnchor = QPointF(axisRect.right() + distanceToAxis + offset, position); + break; + case QCPAxis::atTop: + labelAnchor = QPointF(position, axisRect.top() - distanceToAxis - offset); + break; + case QCPAxis::atBottom: + labelAnchor = QPointF(position, axisRect.bottom() + distanceToAxis + offset); + break; + } + if (mParentPlot->plottingHints().testFlag(QCP::phCacheLabels) && !painter->modes().testFlag(QCPPainter::pmNoCaching)) { // label caching enabled + CachedLabel *cachedLabel = mLabelCache.take(text); // attempt to get label from cache + if (!cachedLabel) { // no cached label existed, create it + 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 # ifdef QCP_DEVICEPIXELRATIO_FLOAT - cachedLabel->pixmap.setDevicePixelRatio(mParentPlot->devicePixelRatioF()); + cachedLabel->pixmap.setDevicePixelRatio(mParentPlot->devicePixelRatioF()); # else - cachedLabel->pixmap.setDevicePixelRatio(mParentPlot->devicePixelRatio()); + cachedLabel->pixmap.setDevicePixelRatio(mParentPlot->devicePixelRatio()); # endif #endif - } else - cachedLabel->pixmap = QPixmap(labelData.rotatedTotalBounds.size()); - cachedLabel->pixmap.fill(Qt::transparent); - QCPPainter cachePainter(&cachedLabel->pixmap); - cachePainter.setPen(painter->pen()); - drawTickLabel(&cachePainter, -labelData.rotatedTotalBounds.topLeft().x(), -labelData.rotatedTotalBounds.topLeft().y(), labelData); + } else { + cachedLabel->pixmap = QPixmap(labelData.rotatedTotalBounds.size()); + } + cachedLabel->pixmap.fill(Qt::transparent); + QCPPainter cachePainter(&cachedLabel->pixmap); + cachePainter.setPen(painter->pen()); + drawTickLabel(&cachePainter, -labelData.rotatedTotalBounds.topLeft().x(), -labelData.rotatedTotalBounds.topLeft().y(), labelData); + } + // if label would be partly clipped by widget border on sides, don't draw it (only for outside tick labels): + bool labelClippedByBorder = false; + if (tickLabelSide == QCPAxis::lsOutside) { + if (QCPAxis::orientation(type) == Qt::Horizontal) { + 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() / mParentPlot->bufferDevicePixelRatio() > viewportRect.bottom() || labelAnchor.y() + cachedLabel->offset.y() < viewportRect.top(); + } + } + if (!labelClippedByBorder) { + painter->drawPixmap(labelAnchor + cachedLabel->offset, cachedLabel->pixmap); + 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: + TickLabelData labelData = getTickLabelData(painter->font(), text); + QPointF finalPosition = labelAnchor + getTickLabelDrawOffset(labelData); + // if label would be partly clipped by widget border on sides, don't draw it (only for outside tick labels): + bool labelClippedByBorder = false; + if (tickLabelSide == QCPAxis::lsOutside) { + if (QCPAxis::orientation(type) == Qt::Horizontal) { + labelClippedByBorder = finalPosition.x() + (labelData.rotatedTotalBounds.width() + labelData.rotatedTotalBounds.left()) > viewportRect.right() || finalPosition.x() + labelData.rotatedTotalBounds.left() < viewportRect.left(); + } else { + labelClippedByBorder = finalPosition.y() + (labelData.rotatedTotalBounds.height() + labelData.rotatedTotalBounds.top()) > viewportRect.bottom() || finalPosition.y() + labelData.rotatedTotalBounds.top() < viewportRect.top(); + } + } + if (!labelClippedByBorder) { + drawTickLabel(painter, finalPosition.x(), finalPosition.y(), labelData); + finalSize = labelData.rotatedTotalBounds.size(); + } } - // if label would be partly clipped by widget border on sides, don't draw it (only for outside tick labels): - bool labelClippedByBorder = false; - if (tickLabelSide == QCPAxis::lsOutside) - { - if (QCPAxis::orientation(type) == Qt::Horizontal) - 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()/mParentPlot->bufferDevicePixelRatio() > viewportRect.bottom() || labelAnchor.y()+cachedLabel->offset.y() < viewportRect.top(); + + // expand passed tickLabelsSize if current tick label is larger: + if (finalSize.width() > tickLabelsSize->width()) { + tickLabelsSize->setWidth(finalSize.width()); } - if (!labelClippedByBorder) - { - painter->drawPixmap(labelAnchor+cachedLabel->offset, cachedLabel->pixmap); - finalSize = cachedLabel->pixmap.size()/mParentPlot->bufferDevicePixelRatio(); + if (finalSize.height() > tickLabelsSize->height()) { + tickLabelsSize->setHeight(finalSize.height()); } - 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: - { - TickLabelData labelData = getTickLabelData(painter->font(), text); - QPointF finalPosition = labelAnchor + getTickLabelDrawOffset(labelData); - // if label would be partly clipped by widget border on sides, don't draw it (only for outside tick labels): - bool labelClippedByBorder = false; - if (tickLabelSide == QCPAxis::lsOutside) - { - if (QCPAxis::orientation(type) == Qt::Horizontal) - labelClippedByBorder = finalPosition.x()+(labelData.rotatedTotalBounds.width()+labelData.rotatedTotalBounds.left()) > viewportRect.right() || finalPosition.x()+labelData.rotatedTotalBounds.left() < viewportRect.left(); - else - labelClippedByBorder = finalPosition.y()+(labelData.rotatedTotalBounds.height()+labelData.rotatedTotalBounds.top()) > viewportRect.bottom() || finalPosition.y()+labelData.rotatedTotalBounds.top() < viewportRect.top(); - } - if (!labelClippedByBorder) - { - drawTickLabel(painter, finalPosition.x(), finalPosition.y(), labelData); - finalSize = labelData.rotatedTotalBounds.size(); - } - } - - // expand passed tickLabelsSize if current tick label is larger: - if (finalSize.width() > tickLabelsSize->width()) - tickLabelsSize->setWidth(finalSize.width()); - if (finalSize.height() > tickLabelsSize->height()) - tickLabelsSize->setHeight(finalSize.height()); } /*! \internal - + This is a \ref placeTickLabel helper function. - + Draws the tick label specified in \a labelData with \a painter at the pixel positions \a x and \a y. This function is used by \ref placeTickLabel to create new tick labels for the cache, or to directly draw the labels on the QCustomPlot surface when label caching is disabled, i.e. when @@ -10301,128 +10428,131 @@ void QCPAxisPainterPrivate::placeTickLabel(QCPPainter *painter, double position, */ void QCPAxisPainterPrivate::drawTickLabel(QCPPainter *painter, double x, double y, const TickLabelData &labelData) const { - // backup painter settings that we're about to change: - QTransform oldTransform = painter->transform(); - QFont oldFont = painter->font(); - - // transform painter to position/rotation: - painter->translate(x, y); - if (!qFuzzyIsNull(tickLabelRotation)) - painter->rotate(tickLabelRotation); - - // draw text: - if (!labelData.expPart.isEmpty()) // indicator that beautiful powers must be used - { - 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 - { - painter->setFont(labelData.baseFont); - painter->drawText(0, 0, labelData.totalBounds.width(), labelData.totalBounds.height(), Qt::TextDontClip | Qt::AlignHCenter, labelData.basePart); - } - - // reset painter settings to what it was before: - painter->setTransform(oldTransform); - painter->setFont(oldFont); + // backup painter settings that we're about to change: + QTransform oldTransform = painter->transform(); + QFont oldFont = painter->font(); + + // transform painter to position/rotation: + painter->translate(x, y); + if (!qFuzzyIsNull(tickLabelRotation)) { + painter->rotate(tickLabelRotation); + } + + // draw text: + if (!labelData.expPart.isEmpty()) { // indicator that beautiful powers must be used + 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 { + painter->setFont(labelData.baseFont); + painter->drawText(0, 0, labelData.totalBounds.width(), labelData.totalBounds.height(), Qt::TextDontClip | Qt::AlignHCenter, labelData.basePart); + } + + // reset painter settings to what it was before: + painter->setTransform(oldTransform); + painter->setFont(oldFont); } /*! \internal - + This is a \ref placeTickLabel helper function. - + Transforms the passed \a text and \a font to a tickLabelData structure that can then be further processed by \ref getTickLabelDrawOffset and \ref drawTickLabel. It splits the text into base and exponent if necessary (member substituteExponent) and calculates appropriate bounding boxes. */ QCPAxisPainterPrivate::TickLabelData QCPAxisPainterPrivate::getTickLabelData(const QFont &font, const QString &text) const { - TickLabelData result; - - // determine whether beautiful decimal powers should be used - bool useBeautifulPowers = false; - 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 > 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; + TickLabelData result; + + // determine whether beautiful decimal powers should be used + bool useBeautifulPowers = false; + 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 > 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: - result.baseFont = font; - if (result.baseFont.pointSizeF() > 0) // might return -1 if specified with setPixelSize, in that case we can't do correction in next line - result.baseFont.setPointSizeF(result.baseFont.pointSizeF()+0.05); // QFontMetrics.boundingRect has a bug for exact point sizes that make the results oscillate due to internal rounding - if (useBeautifulPowers) - { - // 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, 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); - if (!result.expPart.isEmpty() && result.expPart.at(0) == QLatin1Char('+')) - result.expPart.remove(0, 1); - // prepare smaller font for exponent: - result.expFont = font; - if (result.expFont.pointSize() > 0) - result.expFont.setPointSize(int(result.expFont.pointSize()*0.75)); - else - result.expFont.setPixelSize(int(result.expFont.pixelSize()*0.75)); - // 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); - 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; - result.totalBounds = QFontMetrics(result.baseFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip | Qt::AlignHCenter, result.basePart); - } - result.totalBounds.moveTopLeft(QPoint(0, 0)); // want bounding box aligned top left at origin, independent of how it was created, to make further processing simpler - - // calculate possibly different bounding rect after rotation: - result.rotatedTotalBounds = result.totalBounds; - if (!qFuzzyIsNull(tickLabelRotation)) - { - QTransform transform; - transform.rotate(tickLabelRotation); - result.rotatedTotalBounds = transform.mapRect(result.rotatedTotalBounds); - } - - return result; + + // calculate text bounding rects and do string preparation for beautiful decimal powers: + result.baseFont = font; + if (result.baseFont.pointSizeF() > 0) { // might return -1 if specified with setPixelSize, in that case we can't do correction in next line + result.baseFont.setPointSizeF(result.baseFont.pointSizeF() + 0.05); // QFontMetrics.boundingRect has a bug for exact point sizes that make the results oscillate due to internal rounding + } + if (useBeautifulPowers) { + // 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, 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); + } + if (!result.expPart.isEmpty() && result.expPart.at(0) == QLatin1Char('+')) { + result.expPart.remove(0, 1); + } + // prepare smaller font for exponent: + result.expFont = font; + if (result.expFont.pointSize() > 0) { + result.expFont.setPointSize(int(result.expFont.pointSize() * 0.75)); + } else { + result.expFont.setPixelSize(int(result.expFont.pixelSize() * 0.75)); + } + // 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); + 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; + result.totalBounds = QFontMetrics(result.baseFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip | Qt::AlignHCenter, result.basePart); + } + result.totalBounds.moveTopLeft(QPoint(0, 0)); // want bounding box aligned top left at origin, independent of how it was created, to make further processing simpler + + // calculate possibly different bounding rect after rotation: + result.rotatedTotalBounds = result.totalBounds; + if (!qFuzzyIsNull(tickLabelRotation)) { + QTransform transform; + transform.rotate(tickLabelRotation); + result.rotatedTotalBounds = transform.mapRect(result.rotatedTotalBounds); + } + + return result; } /*! \internal - + This is a \ref placeTickLabel helper function. - + Calculates the offset at which the top left corner of the specified tick label shall be drawn. The offset is relative to a point right next to the tick the label belongs to. - + This function is thus responsible for e.g. centering tick labels under ticks and positioning them appropriately when they are rotated. */ QPointF QCPAxisPainterPrivate::getTickLabelDrawOffset(const TickLabelData &labelData) const { - /* + /* calculate label offset from base point at tick (non-trivial, for best visual appearance): short explanation for bottom axis: The anchor, i.e. the point in the label that is placed horizontally under the corresponding tick is always on the label side that is closer to the @@ -10431,91 +10561,71 @@ QPointF QCPAxisPainterPrivate::getTickLabelDrawOffset(const TickLabelData &label will be centered under the tick (i.e. displaced horizontally by half its height). At the same time, a 45 degree rotated text will "point toward" its tick, as is typical for rotated tick labels. - */ - bool doRotation = !qFuzzyIsNull(tickLabelRotation); - bool flip = qFuzzyCompare(qAbs(tickLabelRotation), 90.0); // perfect +/-90 degree flip. Indicates vertical label centering on vertical axes. - double radians = tickLabelRotation/180.0*M_PI; - double x = 0; - double y = 0; - if ((type == QCPAxis::atLeft && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atRight && tickLabelSide == QCPAxis::lsInside)) // Anchor at right side of tick label - { - if (doRotation) - { - if (tickLabelRotation > 0) - { - x = -qCos(radians)*labelData.totalBounds.width(); - y = flip ? -labelData.totalBounds.width()/2.0 : -qSin(radians)*labelData.totalBounds.width()-qCos(radians)*labelData.totalBounds.height()/2.0; - } else - { - x = -qCos(-radians)*labelData.totalBounds.width()-qSin(-radians)*labelData.totalBounds.height(); - y = flip ? +labelData.totalBounds.width()/2.0 : +qSin(-radians)*labelData.totalBounds.width()-qCos(-radians)*labelData.totalBounds.height()/2.0; - } - } else - { - x = -labelData.totalBounds.width(); - y = -labelData.totalBounds.height()/2.0; + */ + bool doRotation = !qFuzzyIsNull(tickLabelRotation); + bool flip = qFuzzyCompare(qAbs(tickLabelRotation), 90.0); // perfect +/-90 degree flip. Indicates vertical label centering on vertical axes. + double radians = tickLabelRotation / 180.0 * M_PI; + double x = 0; + double y = 0; + if ((type == QCPAxis::atLeft && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atRight && tickLabelSide == QCPAxis::lsInside)) { // Anchor at right side of tick label + if (doRotation) { + if (tickLabelRotation > 0) { + x = -qCos(radians) * labelData.totalBounds.width(); + y = flip ? -labelData.totalBounds.width() / 2.0 : -qSin(radians) * labelData.totalBounds.width() - qCos(radians) * labelData.totalBounds.height() / 2.0; + } else { + x = -qCos(-radians) * labelData.totalBounds.width() - qSin(-radians) * labelData.totalBounds.height(); + y = flip ? +labelData.totalBounds.width() / 2.0 : +qSin(-radians) * labelData.totalBounds.width() - qCos(-radians) * labelData.totalBounds.height() / 2.0; + } + } else { + x = -labelData.totalBounds.width(); + y = -labelData.totalBounds.height() / 2.0; + } + } else if ((type == QCPAxis::atRight && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atLeft && tickLabelSide == QCPAxis::lsInside)) { // Anchor at left side of tick label + if (doRotation) { + if (tickLabelRotation > 0) { + x = +qSin(radians) * labelData.totalBounds.height(); + y = flip ? -labelData.totalBounds.width() / 2.0 : -qCos(radians) * labelData.totalBounds.height() / 2.0; + } else { + x = 0; + y = flip ? +labelData.totalBounds.width() / 2.0 : -qCos(-radians) * labelData.totalBounds.height() / 2.0; + } + } else { + x = 0; + y = -labelData.totalBounds.height() / 2.0; + } + } else if ((type == QCPAxis::atTop && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atBottom && tickLabelSide == QCPAxis::lsInside)) { // Anchor at bottom side of tick label + if (doRotation) { + if (tickLabelRotation > 0) { + x = -qCos(radians) * labelData.totalBounds.width() + qSin(radians) * labelData.totalBounds.height() / 2.0; + y = -qSin(radians) * labelData.totalBounds.width() - qCos(radians) * labelData.totalBounds.height(); + } else { + x = -qSin(-radians) * labelData.totalBounds.height() / 2.0; + y = -qCos(-radians) * labelData.totalBounds.height(); + } + } else { + x = -labelData.totalBounds.width() / 2.0; + y = -labelData.totalBounds.height(); + } + } else if ((type == QCPAxis::atBottom && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atTop && tickLabelSide == QCPAxis::lsInside)) { // Anchor at top side of tick label + if (doRotation) { + if (tickLabelRotation > 0) { + x = +qSin(radians) * labelData.totalBounds.height() / 2.0; + y = 0; + } else { + x = -qCos(-radians) * labelData.totalBounds.width() - qSin(-radians) * labelData.totalBounds.height() / 2.0; + y = +qSin(-radians) * labelData.totalBounds.width(); + } + } else { + x = -labelData.totalBounds.width() / 2.0; + y = 0; + } } - } else if ((type == QCPAxis::atRight && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atLeft && tickLabelSide == QCPAxis::lsInside)) // Anchor at left side of tick label - { - if (doRotation) - { - if (tickLabelRotation > 0) - { - x = +qSin(radians)*labelData.totalBounds.height(); - y = flip ? -labelData.totalBounds.width()/2.0 : -qCos(radians)*labelData.totalBounds.height()/2.0; - } else - { - x = 0; - y = flip ? +labelData.totalBounds.width()/2.0 : -qCos(-radians)*labelData.totalBounds.height()/2.0; - } - } else - { - x = 0; - y = -labelData.totalBounds.height()/2.0; - } - } else if ((type == QCPAxis::atTop && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atBottom && tickLabelSide == QCPAxis::lsInside)) // Anchor at bottom side of tick label - { - if (doRotation) - { - if (tickLabelRotation > 0) - { - x = -qCos(radians)*labelData.totalBounds.width()+qSin(radians)*labelData.totalBounds.height()/2.0; - y = -qSin(radians)*labelData.totalBounds.width()-qCos(radians)*labelData.totalBounds.height(); - } else - { - x = -qSin(-radians)*labelData.totalBounds.height()/2.0; - y = -qCos(-radians)*labelData.totalBounds.height(); - } - } else - { - x = -labelData.totalBounds.width()/2.0; - y = -labelData.totalBounds.height(); - } - } else if ((type == QCPAxis::atBottom && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atTop && tickLabelSide == QCPAxis::lsInside)) // Anchor at top side of tick label - { - if (doRotation) - { - if (tickLabelRotation > 0) - { - x = +qSin(radians)*labelData.totalBounds.height()/2.0; - y = 0; - } else - { - x = -qCos(-radians)*labelData.totalBounds.width()-qSin(-radians)*labelData.totalBounds.height()/2.0; - y = +qSin(-radians)*labelData.totalBounds.width(); - } - } else - { - x = -labelData.totalBounds.width()/2.0; - y = 0; - } - } - - return {x, y}; + + return {x, y}; } /*! \internal - + Simulates the steps done by \ref placeTickLabel by calculating bounding boxes of the text label to be drawn, depending on number format etc. Since only the largest tick label is wanted for the margin calculation, the passed \a tickLabelsSize is only expanded, if it's currently set to a @@ -10523,23 +10633,23 @@ QPointF QCPAxisPainterPrivate::getTickLabelDrawOffset(const TickLabelData &label */ void QCPAxisPainterPrivate::getMaxTickLabelSize(const QFont &font, const QString &text, QSize *tickLabelsSize) const { - // note: this function must return the same tick label sizes as the placeTickLabel function. - QSize finalSize; - 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()/mParentPlot->bufferDevicePixelRatio(); - } else // label caching disabled or no label with this text cached: - { - TickLabelData labelData = getTickLabelData(font, text); - finalSize = labelData.rotatedTotalBounds.size(); - } - - // expand passed tickLabelsSize if current tick label is larger: - if (finalSize.width() > tickLabelsSize->width()) - tickLabelsSize->setWidth(finalSize.width()); - if (finalSize.height() > tickLabelsSize->height()) - tickLabelsSize->setHeight(finalSize.height()); + // note: this function must return the same tick label sizes as the placeTickLabel function. + QSize finalSize; + 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() / mParentPlot->bufferDevicePixelRatio(); + } else { // label caching disabled or no label with this text cached: + TickLabelData labelData = getTickLabelData(font, text); + finalSize = labelData.rotatedTotalBounds.size(); + } + + // expand passed tickLabelsSize if current tick label is larger: + if (finalSize.width() > tickLabelsSize->width()) { + tickLabelsSize->setWidth(finalSize.width()); + } + if (finalSize.height() > tickLabelsSize->height()) { + tickLabelsSize->setHeight(finalSize.height()); + } } /* end of 'src/axis/axis.cpp' */ @@ -10553,33 +10663,33 @@ void QCPAxisPainterPrivate::getMaxTickLabelSize(const QFont &font, const QString /*! \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 @@ -10587,15 +10697,15 @@ void QCPAxisPainterPrivate::getMaxTickLabelSize(const QFont &font, const QString 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. @@ -10604,23 +10714,23 @@ void QCPAxisPainterPrivate::getMaxTickLabelSize(const QFont &font, const QString /* 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 */ @@ -10628,32 +10738,32 @@ void QCPAxisPainterPrivate::getMaxTickLabelSize(const QFont &font, const QString /*! 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) + 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) + mSize(size), + mShape(shape), + mPen(Qt::NoPen), + mBrush(Qt::NoBrush), + mPenDefined(false) { } @@ -10662,11 +10772,11 @@ QCPScatterStyle::QCPScatterStyle(ScatterShape shape, double size) : 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) + mSize(size), + mShape(shape), + mPen(QPen(color)), + mBrush(Qt::NoBrush), + mPenDefined(true) { } @@ -10675,18 +10785,18 @@ QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QColor &color, double 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) + 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 @@ -10699,11 +10809,11 @@ QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QColor &color, const 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) + mSize(size), + mShape(shape), + mPen(pen), + mBrush(brush), + mPenDefined(pen.style() != Qt::NoPen) { } @@ -10712,31 +10822,31 @@ QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QPen &pen, const QBru is set to \ref ssPixmap. */ QCPScatterStyle::QCPScatterStyle(const QPixmap &pixmap) : - mSize(5), - mShape(ssPixmap), - mPen(Qt::NoPen), - mBrush(Qt::NoBrush), - mPixmap(pixmap), - mPenDefined(false) + 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 in its original size by default. To for example double the size of the path, 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) + mSize(size), + mShape(ssCustom), + mPen(pen), + mBrush(brush), + mCustomPath(customPath), + mPenDefined(pen.style() != Qt::NoPen) { } @@ -10745,97 +10855,99 @@ QCPScatterStyle::QCPScatterStyle(const QPainterPath &customPath, const QPen &pen */ 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()); - } + 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; + 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; + 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; + 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; + 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; + 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; + setShape(ssCustom); + mCustomPath = customPath; } /*! @@ -10846,35 +10958,35 @@ void QCPScatterStyle::setCustomPath(const QPainterPath &customPath) */ void QCPScatterStyle::undefinePen() { - mPenDefined = false; + 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); + 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()); + drawShape(painter, pos.x(), pos.y()); } /*! \overload @@ -10882,137 +10994,124 @@ void QCPScatterStyle::drawShape(QCPPainter *painter, const QPointF &pos) const */ 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: - { - QPointF lineArray[4] = {QPointF(x-w, y), - QPointF( x, y-w), - QPointF(x+w, y), - QPointF( x, y+w)}; - painter->drawPolygon(lineArray, 4); - 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: - { - QPointF lineArray[3] = {QPointF(x-w, y+0.755*w), - QPointF(x+w, y+0.755*w), - QPointF( x, y-0.977*w)}; - painter->drawPolygon(lineArray, 3); - break; - } - case ssTriangleInverted: - { - QPointF lineArray[3] = {QPointF(x-w, y-0.755*w), - QPointF(x+w, y-0.755*w), - QPointF( x, y+0.977*w)}; - painter->drawPolygon(lineArray, 3); - break; - } - case ssCrossSquare: - { - painter->drawRect(QRectF(x-w, y-w, mSize, mSize)); - 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)); - break; - } - case ssPlusSquare: - { - painter->drawRect(QRectF(x-w, y-w, mSize, mSize)); - painter->drawLine(QLineF(x-w, y, x+w*0.95, y)); - painter->drawLine(QLineF( x, y+w, x, y-w)); - break; - } - case ssCrossCircle: - { - painter->drawEllipse(QPointF(x, y), w, w); - 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)); - break; - } - case ssPlusCircle: - { - painter->drawEllipse(QPointF(x, y), w, w); - painter->drawLine(QLineF(x-w, y, x+w, y)); - painter->drawLine(QLineF( x, y+w, x, y-w)); - break; - } - case ssPeace: - { - painter->drawEllipse(QPointF(x, y), w, w); - 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)); - break; - } - case ssPixmap: - { - const double widthHalf = mPixmap.width()*0.5; - const double heightHalf = mPixmap.height()*0.5; + 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: { + QPointF lineArray[4] = {QPointF(x - w, y), + QPointF(x, y - w), + QPointF(x + w, y), + QPointF(x, y + w) + }; + painter->drawPolygon(lineArray, 4); + 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: { + QPointF lineArray[3] = {QPointF(x - w, y + 0.755 * w), + QPointF(x + w, y + 0.755 * w), + QPointF(x, y - 0.977 * w) + }; + painter->drawPolygon(lineArray, 3); + break; + } + case ssTriangleInverted: { + QPointF lineArray[3] = {QPointF(x - w, y - 0.755 * w), + QPointF(x + w, y - 0.755 * w), + QPointF(x, y + 0.977 * w) + }; + painter->drawPolygon(lineArray, 3); + break; + } + case ssCrossSquare: { + painter->drawRect(QRectF(x - w, y - w, mSize, mSize)); + 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)); + break; + } + case ssPlusSquare: { + painter->drawRect(QRectF(x - w, y - w, mSize, mSize)); + painter->drawLine(QLineF(x - w, y, x + w * 0.95, y)); + painter->drawLine(QLineF(x, y + w, x, y - w)); + break; + } + case ssCrossCircle: { + painter->drawEllipse(QPointF(x, y), w, w); + 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)); + break; + } + case ssPlusCircle: { + painter->drawEllipse(QPointF(x, y), w, w); + painter->drawLine(QLineF(x - w, y, x + w, y)); + painter->drawLine(QLineF(x, y + w, x, y - w)); + break; + } + case ssPeace: { + painter->drawEllipse(QPointF(x, y), w, w); + 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)); + 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); + const QRectF clipRect = painter->clipRegion().boundingRect().adjusted(-widthHalf, -heightHalf, widthHalf, heightHalf); #else - const QRectF clipRect = painter->clipBoundingRect().adjusted(-widthHalf, -heightHalf, widthHalf, heightHalf); + const QRectF clipRect = painter->clipBoundingRect().adjusted(-widthHalf, -heightHalf, widthHalf, heightHalf); #endif - if (clipRect.contains(x, y)) - painter->drawPixmap(qRound(x-widthHalf), qRound(y-heightHalf), mPixmap); - break; + if (clipRect.contains(x, y)) { + painter->drawPixmap(qRound(x - widthHalf), qRound(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; + } } - 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' */ @@ -11026,24 +11125,24 @@ void QCPScatterStyle::drawShape(QCPPainter *painter, double x, double y) const /*! \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 @@ -11054,10 +11153,10 @@ void QCPScatterStyle::drawShape(QCPPainter *painter, double x, double y) const Creates a new QCPSelectionDecorator instance with default values */ QCPSelectionDecorator::QCPSelectionDecorator() : - mPen(QColor(80, 80, 255), 2.5), - mBrush(Qt::NoBrush), - mUsedScatterProperties(QCPScatterStyle::spNone), - mPlottable(nullptr) + mPen(QColor(80, 80, 255), 2.5), + mBrush(Qt::NoBrush), + mUsedScatterProperties(QCPScatterStyle::spNone), + mPlottable(nullptr) { } @@ -11070,7 +11169,7 @@ QCPSelectionDecorator::~QCPSelectionDecorator() */ void QCPSelectionDecorator::setPen(const QPen &pen) { - mPen = pen; + mPen = pen; } /*! @@ -11078,52 +11177,52 @@ void QCPSelectionDecorator::setPen(const QPen &pen) */ void QCPSelectionDecorator::setBrush(const QBrush &brush) { - mBrush = 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); + 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. - + \see QCPScatterStyle::ScatterProperty */ void QCPSelectionDecorator::setUsedScatterProperties(const QCPScatterStyle::ScatterProperties &properties) { - mUsedScatterProperties = 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); + 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); + painter->setBrush(mBrush); } /*! @@ -11131,21 +11230,22 @@ void QCPSelectionDecorator::applyBrush(QCPPainter *painter) const 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; + 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; } /*! @@ -11154,45 +11254,43 @@ QCPScatterStyle QCPSelectionDecorator::getFinalScatterStyle(const QCPScatterStyl */ void QCPSelectionDecorator::copyFrom(const QCPSelectionDecorator *other) { - setPen(other->pen()); - setBrush(other->brush()); - setScatterStyle(other->scatterStyle(), other->usedScatterProperties()); + 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) + 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; - } + if (!mPlottable) { + mPlottable = plottable; + return true; + } else { + qDebug() << Q_FUNC_INFO << "This selection decorator is already registered with plottable:" << reinterpret_cast(mPlottable); + return false; + } } @@ -11209,7 +11307,7 @@ bool QCPSelectionDecorator::registerWithPlottable(QCPAbstractPlottable *plottabl 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 and/or scatter points \ref QCPGraph (typically created with \ref QCustomPlot::addGraph) @@ -11218,14 +11316,14 @@ bool QCPSelectionDecorator::registerWithPlottable(QCPAbstractPlottable *plottabl \li A statistical box plot: \ref QCPStatisticalBox \li A color encoded two-dimensional map: \ref QCPColorMap \li An OHLC/Candlestick chart: \ref QCPFinancial - + \section plottables-subclassing Creating own plottables - + 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 @@ -11233,9 +11331,9 @@ bool QCPSelectionDecorator::registerWithPlottable(QCPAbstractPlottable *plottabl \li \ref drawLegendIcon \li \ref getKeyRange \li \ref getValueRange - + See the documentation of those functions for what they need to do. - + For drawing your plot, you can use the \ref coordsToPixels functions to translate a point in plot coordinates to pixel coordinates. This function is quite convenient, because it takes the orientation of the key and value axes into account for you (x and y are swapped when the key axis @@ -11243,7 +11341,7 @@ bool QCPSelectionDecorator::registerWithPlottable(QCPAbstractPlottable *plottabl to translate many points in a loop like QCPGraph), you can directly use \ref QCPAxis::coordToPixel. However, you must then take care about the orientation of the axis yourself. - + Here are some important members you inherit from QCPAbstractPlottable: @@ -11284,35 +11382,35 @@ bool QCPSelectionDecorator::registerWithPlottable(QCPAbstractPlottable *plottabl /* start of documentation of inline functions */ /*! \fn QCPSelectionDecorator *QCPAbstractPlottable::selectionDecorator() const - + Provides access to the selection decorator of this plottable. The selection decorator controls how selected data ranges are drawn (e.g. their pen color and fill), see \ref QCPSelectionDecorator for details. - + If you wish to use an own \ref QCPSelectionDecorator subclass, pass an instance of it to \ref setSelectionDecorator. */ /*! \fn bool QCPAbstractPlottable::selected() const - + Returns true if there are any data points of the plottable currently selected. Use \ref selection to retrieve the current \ref QCPDataSelection. */ /*! \fn QCPDataSelection QCPAbstractPlottable::selection() const - + Returns a \ref QCPDataSelection encompassing all the data points that are currently selected on this plottable. - + \see selected, setSelection, setSelectable */ /*! \fn 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. */ @@ -11322,16 +11420,16 @@ bool QCPSelectionDecorator::registerWithPlottable(QCPAbstractPlottable *plottabl /*! \fn void QCPAbstractPlottable::drawLegendIcon(QCPPainter *painter, const QRect &rect) const = 0 \internal - + called by QCPLegend::draw (via QCPPlottableLegendItem::draw) to create a graphical representation of this plottable inside \a rect, next to the plottable name. - + The passed \a painter has its cliprect set to \a rect, so painting outside of \a rect won't appear outside the legend icon border. */ /*! \fn QCPRange QCPAbstractPlottable::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const = 0 - + 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 @@ -11344,12 +11442,12 @@ bool QCPSelectionDecorator::registerWithPlottable(QCPAbstractPlottable *plottabl 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, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const = 0 - + Returns the coordinate range that the data points in the specified key range (\a inKeyRange) span in the value axis dimension. For logarithmic plots, one can set \a inSignDomain to either \ref QCP::sdNegative or \ref QCP::sdPositive in order to restrict the returned range to that sign @@ -11358,7 +11456,7 @@ bool QCPSelectionDecorator::registerWithPlottable(QCPAbstractPlottable *plottabl 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. @@ -11366,7 +11464,7 @@ bool QCPSelectionDecorator::registerWithPlottable(QCPAbstractPlottable *plottabl 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 */ @@ -11374,27 +11472,27 @@ bool QCPSelectionDecorator::registerWithPlottable(QCPAbstractPlottable *plottabl /* start of documentation of signals */ /*! \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 setSelection. The parameter \a selected indicates whether there are any points selected or not. - + \see selectionChanged(const QCPDataSelection &selection) */ /*! \fn void QCPAbstractPlottable::selectionChanged(const QCPDataSelection &selection) - + This signal is emitted when the selection state of this plottable has changed, either by user interaction or by a direct call to \ref setSelection. The parameter \a selection holds the currently selected data ranges. - + \see selectionChanged(bool selected) */ /*! \fn void QCPAbstractPlottable::selectableChanged(QCP::SelectionType selectable); - + This signal is emitted when the selectability of this plottable has changed. - + \see setSelectable */ @@ -11405,40 +11503,41 @@ bool QCPSelectionDecorator::registerWithPlottable(QCPAbstractPlottable *plottabl its value axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and have perpendicular orientations. If either of these restrictions is violated, a corresponding message is printed to the debug output (qDebug), the construction is not aborted, though. - + Since QCPAbstractPlottable is an abstract class that defines the basic interface to plottables, it can't be directly instantiated. - + You probably want one of the subclasses like \ref QCPGraph or \ref QCPCurve instead. */ QCPAbstractPlottable::QCPAbstractPlottable(QCPAxis *keyAxis, QCPAxis *valueAxis) : - QCPLayerable(keyAxis->parentPlot(), QString(), keyAxis->axisRect()), - mName(), - mAntialiasedFill(true), - mAntialiasedScatters(true), - mPen(Qt::black), - mBrush(Qt::NoBrush), - mKeyAxis(keyAxis), - mValueAxis(valueAxis), - mSelectable(QCP::stWhole), - mSelectionDecorator(nullptr) + QCPLayerable(keyAxis->parentPlot(), QString(), keyAxis->axisRect()), + mName(), + mAntialiasedFill(true), + mAntialiasedScatters(true), + mPen(Qt::black), + mBrush(Qt::NoBrush), + mKeyAxis(keyAxis), + mValueAxis(valueAxis), + mSelectable(QCP::stWhole), + mSelectionDecorator(nullptr) { - 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); + 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 = nullptr; - } + if (mSelectionDecorator) { + delete mSelectionDecorator; + mSelectionDecorator = nullptr; + } } /*! @@ -11447,48 +11546,48 @@ QCPAbstractPlottable::~QCPAbstractPlottable() */ void QCPAbstractPlottable::setName(const QString &name) { - mName = name; + mName = name; } /*! Sets whether fills 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::setAntialiasedFill(bool enabled) { - mAntialiasedFill = enabled; + mAntialiasedFill = enabled; } /*! Sets whether the scatter symbols 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::setAntialiasedScatters(bool enabled) { - mAntialiasedScatters = enabled; + mAntialiasedScatters = enabled; } /*! The pen is used to draw basic lines that make up the plottable representation in the plot. - + For example, the \ref QCPGraph subclass draws its graph lines with this pen. \see setBrush */ void QCPAbstractPlottable::setPen(const QPen &pen) { - mPen = pen; + mPen = 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. - + For example, the \ref QCPGraph subclass draws the fill under the graph with this brush, when it's not set to Qt::NoBrush. @@ -11496,7 +11595,7 @@ void QCPAbstractPlottable::setPen(const QPen &pen) */ void QCPAbstractPlottable::setBrush(const QBrush &brush) { - mBrush = brush; + mBrush = brush; } /*! @@ -11504,7 +11603,7 @@ void QCPAbstractPlottable::setBrush(const QBrush &brush) to the plottable's value axis. This function performs no checks to make sure this is the case. The typical mathematical choice is to use the x-axis (QCustomPlot::xAxis) as key axis and the y-axis (QCustomPlot::yAxis) as value axis. - + Normally, the key and value axes are set in the constructor of the plottable (or \ref QCustomPlot::addGraph when working with QCPGraphs through the dedicated graph interface). @@ -11512,7 +11611,7 @@ void QCPAbstractPlottable::setBrush(const QBrush &brush) */ void QCPAbstractPlottable::setKeyAxis(QCPAxis *axis) { - mKeyAxis = axis; + mKeyAxis = axis; } /*! @@ -11523,12 +11622,12 @@ void QCPAbstractPlottable::setKeyAxis(QCPAxis *axis) Normally, the key and value axes are set in the constructor of the plottable (or \ref QCustomPlot::addGraph when working with QCPGraphs through the dedicated graph interface). - + \see setKeyAxis */ void QCPAbstractPlottable::setValueAxis(QCPAxis *axis) { - mValueAxis = axis; + mValueAxis = axis; } @@ -11536,54 +11635,50 @@ void QCPAbstractPlottable::setValueAxis(QCPAxis *axis) 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 programmatically. - + Using \ref setSelectable you can further specify for each plottable whether and to which granularity it is selectable. If \a selection is not compatible with the current \ref QCP::SelectionType set via \ref setSelectable, the resulting selection will be adjusted accordingly (see \ref QCPDataSelection::enforceType). - + emits the \ref selectionChanged signal when \a selected is different from the previous selection state. - + \see setSelectable, selectTest */ void QCPAbstractPlottable::setSelection(QCPDataSelection selection) { - selection.enforceType(mSelectable); - if (mSelection != selection) - { - mSelection = selection; - emit selectionChanged(selected()); - emit selectionChanged(mSelection); - } + selection.enforceType(mSelectable); + if (mSelection != selection) { + mSelection = selection; + emit selectionChanged(selected()); + emit selectionChanged(mSelection); + } } /*! Use this method to set an own QCPSelectionDecorator (subclass) instance. This allows you to customize the visual representation of selected data ranges further than by using the default QCPSelectionDecorator. - + The plottable takes ownership of the \a decorator. - + The currently set decorator can be accessed via \ref selectionDecorator. */ void QCPAbstractPlottable::setSelectionDecorator(QCPSelectionDecorator *decorator) { - if (decorator) - { - if (decorator->registerWithPlottable(this)) - { - delete mSelectionDecorator; // delete old decorator if necessary - mSelectionDecorator = decorator; + if (decorator) { + if (decorator->registerWithPlottable(this)) { + delete mSelectionDecorator; // delete old decorator if necessary + mSelectionDecorator = decorator; + } + } else if (mSelectionDecorator) { // just clear decorator + delete mSelectionDecorator; + mSelectionDecorator = nullptr; } - } else if (mSelectionDecorator) // just clear decorator - { - delete mSelectionDecorator; - mSelectionDecorator = nullptr; - } } /*! @@ -11593,23 +11688,21 @@ void QCPAbstractPlottable::setSelectionDecorator(QCPSelectionDecorator *decorato 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); + if (mSelectable != selectable) { + mSelectable = selectable; + QCPDataSelection oldSelection = mSelection; + mSelection.enforceType(mSelectable); + emit selectableChanged(mSelectable); + if (mSelection != oldSelection) { + emit selectionChanged(selected()); + emit selectionChanged(mSelection); + } } - } } @@ -11624,19 +11717,20 @@ void QCPAbstractPlottable::setSelectable(QCP::SelectionType selectable) */ 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); - } + 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 @@ -11645,14 +11739,18 @@ void QCPAbstractPlottable::coordsToPixels(double key, double value, double &x, d */ 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)); + 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)); + } } /*! @@ -11666,19 +11764,20 @@ const QPointF QCPAbstractPlottable::coordsToPixels(double key, double value) con */ 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); - } + 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 @@ -11687,7 +11786,7 @@ void QCPAbstractPlottable::pixelsToCoords(double x, double y, double &key, doubl */ void QCPAbstractPlottable::pixelsToCoords(const QPointF &pixelPos, double &key, double &value) const { - pixelsToCoords(pixelPos.x(), pixelPos.y(), key, value); + pixelsToCoords(pixelPos.x(), pixelPos.y(), key, value); } /*! @@ -11696,54 +11795,55 @@ void QCPAbstractPlottable::pixelsToCoords(const QPointF &pixelPos, double &key, sure not to rescale to an illegal range i.e. a range containing different signs and/or zero. Instead it will stay in the current sign domain and ignore all parts of the plottable that lie outside of that domain. - + \a onlyEnlarge makes sure the ranges are only expanded, never reduced. So it's possible to show multiple plottables in their entirety by multiple calls to rescaleAxes where the first call has \a onlyEnlarge set to false (the default), and all subsequent set to true. - + \see rescaleKeyAxis, rescaleValueAxis, QCustomPlot::rescaleAxes, QCPAxis::rescale */ void QCPAbstractPlottable::rescaleAxes(bool onlyEnlarge) const { - rescaleKeyAxis(onlyEnlarge); - rescaleValueAxis(onlyEnlarge); + rescaleKeyAxis(onlyEnlarge); + rescaleValueAxis(onlyEnlarge); } /*! Rescales the key axis of the plottable so the whole plottable is visible. - + See \ref rescaleAxes for detailed behaviour. */ void QCPAbstractPlottable::rescaleKeyAxis(bool onlyEnlarge) const { - QCPAxis *keyAxis = mKeyAxis.data(); - if (!keyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; } - - QCP::SignDomain signDomain = QCP::sdBoth; - if (keyAxis->scaleType() == QCPAxis::stLogarithmic) - signDomain = (keyAxis->range().upper < 0 ? QCP::sdNegative : QCP::sdPositive); - - bool foundRange; - QCPRange newRange = getKeyRange(foundRange, signDomain); - if (foundRange) - { - if (onlyEnlarge) - newRange.expand(keyAxis->range()); - if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable - { - double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason - if (keyAxis->scaleType() == QCPAxis::stLinear) - { - newRange.lower = center-keyAxis->range().size()/2.0; - newRange.upper = center+keyAxis->range().size()/2.0; - } else // scaleType() == stLogarithmic - { - newRange.lower = center/qSqrt(keyAxis->range().upper/keyAxis->range().lower); - newRange.upper = center*qSqrt(keyAxis->range().upper/keyAxis->range().lower); - } + QCPAxis *keyAxis = mKeyAxis.data(); + if (!keyAxis) { + qDebug() << Q_FUNC_INFO << "invalid key axis"; + return; + } + + QCP::SignDomain signDomain = QCP::sdBoth; + if (keyAxis->scaleType() == QCPAxis::stLogarithmic) { + signDomain = (keyAxis->range().upper < 0 ? QCP::sdNegative : QCP::sdPositive); + } + + bool foundRange; + QCPRange newRange = getKeyRange(foundRange, signDomain); + if (foundRange) { + if (onlyEnlarge) { + newRange.expand(keyAxis->range()); + } + if (!QCPRange::validRange(newRange)) { // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable + double center = (newRange.lower + newRange.upper) * 0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason + if (keyAxis->scaleType() == QCPAxis::stLinear) { + newRange.lower = center - keyAxis->range().size() / 2.0; + newRange.upper = center + keyAxis->range().size() / 2.0; + } else { // scaleType() == stLogarithmic + newRange.lower = center / qSqrt(keyAxis->range().upper / keyAxis->range().lower); + newRange.upper = center * qSqrt(keyAxis->range().upper / keyAxis->range().lower); + } + } + keyAxis->setRange(newRange); } - keyAxis->setRange(newRange); - } } /*! @@ -11758,35 +11858,36 @@ void QCPAbstractPlottable::rescaleKeyAxis(bool onlyEnlarge) const */ void QCPAbstractPlottable::rescaleValueAxis(bool onlyEnlarge, bool inKeyRange) const { - QCPAxis *keyAxis = mKeyAxis.data(); - QCPAxis *valueAxis = mValueAxis.data(); - if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } - - QCP::SignDomain signDomain = QCP::sdBoth; - if (valueAxis->scaleType() == QCPAxis::stLogarithmic) - signDomain = (valueAxis->range().upper < 0 ? QCP::sdNegative : QCP::sdPositive); - - bool foundRange; - QCPRange newRange = getValueRange(foundRange, signDomain, inKeyRange ? keyAxis->range() : QCPRange()); - if (foundRange) - { - if (onlyEnlarge) - newRange.expand(valueAxis->range()); - if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable - { - double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason - if (valueAxis->scaleType() == QCPAxis::stLinear) - { - newRange.lower = center-valueAxis->range().size()/2.0; - newRange.upper = center+valueAxis->range().size()/2.0; - } else // scaleType() == stLogarithmic - { - newRange.lower = center/qSqrt(valueAxis->range().upper/valueAxis->range().lower); - newRange.upper = center*qSqrt(valueAxis->range().upper/valueAxis->range().lower); - } + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + return; + } + + QCP::SignDomain signDomain = QCP::sdBoth; + if (valueAxis->scaleType() == QCPAxis::stLogarithmic) { + signDomain = (valueAxis->range().upper < 0 ? QCP::sdNegative : QCP::sdPositive); + } + + bool foundRange; + QCPRange newRange = getValueRange(foundRange, signDomain, inKeyRange ? keyAxis->range() : QCPRange()); + if (foundRange) { + if (onlyEnlarge) { + newRange.expand(valueAxis->range()); + } + if (!QCPRange::validRange(newRange)) { // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable + double center = (newRange.lower + newRange.upper) * 0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason + if (valueAxis->scaleType() == QCPAxis::stLinear) { + newRange.lower = center - valueAxis->range().size() / 2.0; + newRange.upper = center + valueAxis->range().size() / 2.0; + } else { // scaleType() == stLogarithmic + newRange.lower = center / qSqrt(valueAxis->range().upper / valueAxis->range().lower); + newRange.upper = center * qSqrt(valueAxis->range().upper / valueAxis->range().lower); + } + } + valueAxis->setRange(newRange); } - valueAxis->setRange(newRange); - } } /*! \overload @@ -11805,23 +11906,21 @@ void QCPAbstractPlottable::rescaleValueAxis(bool onlyEnlarge, bool inKeyRange) c */ bool QCPAbstractPlottable::addToLegend(QCPLegend *legend) { - if (!legend) - { - qDebug() << Q_FUNC_INFO << "passed legend is null"; - return false; - } - if (legend->parentPlot() != mParentPlot) - { - qDebug() << Q_FUNC_INFO << "passed legend isn't in the same QCustomPlot as this plottable"; - return false; - } - - if (!legend->hasItemWithPlottable(this)) - { - legend->addItem(new QCPPlottableLegendItem(legend, this)); - return true; - } else - return false; + if (!legend) { + qDebug() << Q_FUNC_INFO << "passed legend is null"; + return false; + } + if (legend->parentPlot() != mParentPlot) { + qDebug() << Q_FUNC_INFO << "passed legend isn't in the same QCustomPlot as this plottable"; + return false; + } + + if (!legend->hasItemWithPlottable(this)) { + legend->addItem(new QCPPlottableLegendItem(legend, this)); + return true; + } else { + return false; + } } /*! \overload @@ -11832,10 +11931,11 @@ bool QCPAbstractPlottable::addToLegend(QCPLegend *legend) */ bool QCPAbstractPlottable::addToLegend() { - if (!mParentPlot || !mParentPlot->legend) - return false; - else - return addToLegend(mParentPlot->legend); + if (!mParentPlot || !mParentPlot->legend) { + return false; + } else { + return addToLegend(mParentPlot->legend); + } } /*! \overload @@ -11850,16 +11950,16 @@ bool QCPAbstractPlottable::addToLegend() */ 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; + 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 @@ -11870,25 +11970,26 @@ bool QCPAbstractPlottable::removeFromLegend(QCPLegend *legend) const */ bool QCPAbstractPlottable::removeFromLegend() const { - if (!mParentPlot || !mParentPlot->legend) - return false; - else - return removeFromLegend(mParentPlot->legend); + if (!mParentPlot || !mParentPlot->legend) { + return false; + } else { + return removeFromLegend(mParentPlot->legend); + } } /* inherits documentation from base class */ QRect QCPAbstractPlottable::clipRect() const { - if (mKeyAxis && mValueAxis) - return mKeyAxis.data()->axisRect()->rect() & mValueAxis.data()->axisRect()->rect(); - else - return {}; + if (mKeyAxis && mValueAxis) { + return mKeyAxis.data()->axisRect()->rect() & mValueAxis.data()->axisRect()->rect(); + } else + return {}; } /* inherits documentation from base class */ QCP::Interaction QCPAbstractPlottable::selectionCategory() const { - return QCP::iSelectPlottables; + return QCP::iSelectPlottables; } /*! \internal @@ -11897,93 +11998,93 @@ QCP::Interaction QCPAbstractPlottable::selectionCategory() const before drawing plottable lines. This is the antialiasing state the painter passed to the \ref draw method is in by default. - + 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. - + \seebaseclassmethod - + \see setAntialiased, applyFillAntialiasingHint, applyScattersAntialiasingHint */ void QCPAbstractPlottable::applyDefaultAntialiasingHint(QCPPainter *painter) const { - applyAntialiasingHint(painter, mAntialiased, QCP::aePlottables); + applyAntialiasingHint(painter, mAntialiased, QCP::aePlottables); } /*! \internal A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter before drawing plottable fills. - + 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, applyDefaultAntialiasingHint, applyScattersAntialiasingHint */ void QCPAbstractPlottable::applyFillAntialiasingHint(QCPPainter *painter) const { - applyAntialiasingHint(painter, mAntialiasedFill, QCP::aeFills); + applyAntialiasingHint(painter, mAntialiasedFill, QCP::aeFills); } /*! \internal A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter before drawing plottable scatter points. - + 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, applyDefaultAntialiasingHint */ void QCPAbstractPlottable::applyScattersAntialiasingHint(QCPPainter *painter) const { - applyAntialiasingHint(painter, mAntialiasedScatters, QCP::aeScatters); + applyAntialiasingHint(painter, mAntialiasedScatters, QCP::aeScatters); } /* inherits documentation from base class */ void QCPAbstractPlottable::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) { - Q_UNUSED(event) - - if (mSelectable != QCP::stNone) - { - 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 = mSelection != selectionBefore; - } + Q_UNUSED(event) + + if (mSelectable != QCP::stNone) { + 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 = mSelection != selectionBefore; + } + } } /* inherits documentation from base class */ void QCPAbstractPlottable::deselectEvent(bool *selectionStateChanged) { - if (mSelectable != QCP::stNone) - { - QCPDataSelection selectionBefore = mSelection; - setSelection(QCPDataSelection()); - if (selectionStateChanged) - *selectionStateChanged = mSelection != selectionBefore; - } + if (mSelectable != QCP::stNone) { + QCPDataSelection selectionBefore = mSelection; + setSelection(QCPDataSelection()); + if (selectionStateChanged) { + *selectionStateChanged = mSelection != selectionBefore; + } + } } /* end of 'src/plottable.cpp' */ @@ -11997,7 +12098,7 @@ void QCPAbstractPlottable::deselectEvent(bool *selectionStateChanged) /*! \class QCPItemAnchor \brief An anchor of an item to which positions can be attached to. - + An item (QCPAbstractItem) may have one or more anchors. Unlike QCPItemPosition, an anchor doesn't control anything on its item, but provides a way to tie other items via their positions to the anchor. @@ -12008,10 +12109,10 @@ void QCPAbstractPlottable::deselectEvent(bool *selectionStateChanged) calling QCPItemPosition::setParentAnchor on \a start, passing the wanted anchor of the QCPItemRect. This way the start of the line will now always follow the respective anchor location on the rect item. - + Note that QCPItemPosition derives from QCPItemAnchor, so every position can also serve as an anchor to other positions. - + To learn how to provide anchors in your own item subclasses, see the subclassing section of the QCPAbstractItem documentation. */ @@ -12019,10 +12120,10 @@ void QCPAbstractPlottable::deselectEvent(bool *selectionStateChanged) /* start documentation of inline functions */ /*! \fn virtual QCPItemPosition *QCPItemAnchor::toQCPItemPosition() - + Returns \c nullptr if this instance is merely a QCPItemAnchor, and a valid pointer of type QCPItemPosition* if it actually is a QCPItemPosition (which is a subclass of QCPItemAnchor). - + This safe downcast functionality could also be achieved with a dynamic_cast. However, QCustomPlot avoids dynamic_cast to work with projects that don't have RTTI support enabled (e.g. -fno-rtti flag with gcc compiler). @@ -12036,51 +12137,47 @@ void QCPAbstractPlottable::deselectEvent(bool *selectionStateChanged) explained in the subclassing section of the QCPAbstractItem documentation. */ QCPItemAnchor::QCPItemAnchor(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString &name, int anchorId) : - mName(name), - mParentPlot(parentPlot), - mParentItem(parentItem), - mAnchorId(anchorId) + mName(name), + mParentPlot(parentPlot), + mParentItem(parentItem), + mAnchorId(anchorId) { } QCPItemAnchor::~QCPItemAnchor() { - // unregister as parent at children: - foreach (QCPItemPosition *child, mChildrenX.values()) - { - if (child->parentAnchorX() == this) - child->setParentAnchorX(nullptr); // this acts back on this anchor and child removes itself from mChildrenX - } - foreach (QCPItemPosition *child, mChildrenY.values()) - { - if (child->parentAnchorY() == this) - child->setParentAnchorY(nullptr); // this acts back on this anchor and child removes itself from mChildrenY - } + // unregister as parent at children: + foreach (QCPItemPosition *child, mChildrenX.values()) { + if (child->parentAnchorX() == this) { + child->setParentAnchorX(nullptr); // this acts back on this anchor and child removes itself from mChildrenX + } + } + foreach (QCPItemPosition *child, mChildrenY.values()) { + if (child->parentAnchorY() == this) { + child->setParentAnchorY(nullptr); // this acts back on this anchor and child removes itself from mChildrenY + } + } } /*! Returns the final absolute pixel position of the QCPItemAnchor on the QCustomPlot surface. - + The pixel information is internally retrieved via QCPAbstractItem::anchorPixelPosition of the parent item, QCPItemAnchor is just an intermediary. */ QPointF QCPItemAnchor::pixelPosition() const { - if (mParentItem) - { - if (mAnchorId > -1) - { - return mParentItem->anchorPixelPosition(mAnchorId); - } else - { - qDebug() << Q_FUNC_INFO << "no valid anchor id set:" << mAnchorId; - return {}; + if (mParentItem) { + if (mAnchorId > -1) { + return mParentItem->anchorPixelPosition(mAnchorId); + } else { + qDebug() << Q_FUNC_INFO << "no valid anchor id set:" << mAnchorId; + return {}; + } + } else { + qDebug() << Q_FUNC_INFO << "no parent item set"; + return {}; } - } else - { - qDebug() << Q_FUNC_INFO << "no parent item set"; - return {}; - } } /*! \internal @@ -12088,27 +12185,29 @@ QPointF QCPItemAnchor::pixelPosition() const Adds \a pos to the childX list of this anchor, which keeps track of which children use this anchor as parent anchor for the respective coordinate. This is necessary to notify the children prior to destruction of the anchor. - + Note that this function does not change the parent setting in \a pos. */ void QCPItemAnchor::addChildX(QCPItemPosition *pos) { - if (!mChildrenX.contains(pos)) - mChildrenX.insert(pos); - else - qDebug() << Q_FUNC_INFO << "provided pos is child already" << reinterpret_cast(pos); + if (!mChildrenX.contains(pos)) { + mChildrenX.insert(pos); + } else { + qDebug() << Q_FUNC_INFO << "provided pos is child already" << reinterpret_cast(pos); + } } /*! \internal Removes \a pos from the childX list of this anchor. - + Note that this function does not change the parent setting in \a pos. */ void QCPItemAnchor::removeChildX(QCPItemPosition *pos) { - if (!mChildrenX.remove(pos)) - qDebug() << Q_FUNC_INFO << "provided pos isn't child" << reinterpret_cast(pos); + if (!mChildrenX.remove(pos)) { + qDebug() << Q_FUNC_INFO << "provided pos isn't child" << reinterpret_cast(pos); + } } /*! \internal @@ -12116,27 +12215,29 @@ void QCPItemAnchor::removeChildX(QCPItemPosition *pos) Adds \a pos to the childY list of this anchor, which keeps track of which children use this anchor as parent anchor for the respective coordinate. This is necessary to notify the children prior to destruction of the anchor. - + Note that this function does not change the parent setting in \a pos. */ void QCPItemAnchor::addChildY(QCPItemPosition *pos) { - if (!mChildrenY.contains(pos)) - mChildrenY.insert(pos); - else - qDebug() << Q_FUNC_INFO << "provided pos is child already" << reinterpret_cast(pos); + if (!mChildrenY.contains(pos)) { + mChildrenY.insert(pos); + } else { + qDebug() << Q_FUNC_INFO << "provided pos is child already" << reinterpret_cast(pos); + } } /*! \internal Removes \a pos from the childY list of this anchor. - + Note that this function does not change the parent setting in \a pos. */ void QCPItemAnchor::removeChildY(QCPItemPosition *pos) { - if (!mChildrenY.remove(pos)) - qDebug() << Q_FUNC_INFO << "provided pos isn't child" << reinterpret_cast(pos); + if (!mChildrenY.remove(pos)) { + qDebug() << Q_FUNC_INFO << "provided pos isn't child" << reinterpret_cast(pos); + } } @@ -12146,7 +12247,7 @@ void QCPItemAnchor::removeChildY(QCPItemPosition *pos) /*! \class QCPItemPosition \brief Manages the position of an item. - + Every item has at least one public QCPItemPosition member pointer which provides ways to position the item on the QCustomPlot surface. Some items have multiple positions, for example QCPItemRect has two: \a topLeft and \a bottomRight. @@ -12182,23 +12283,23 @@ void QCPItemAnchor::removeChildY(QCPItemPosition *pos) /* start documentation of inline functions */ /*! \fn QCPItemPosition::PositionType *QCPItemPosition::type() const - + Returns the current position type. - + If different types were set for X and Y (\ref setTypeX, \ref setTypeY), this method returns the type of the X coordinate. In that case rather use \a typeX() and \a typeY(). - + \see setType */ /*! \fn QCPItemAnchor *QCPItemPosition::parentAnchor() const - + Returns the current parent anchor. - + If different parent anchors were set for X and Y (\ref setParentAnchorX, \ref setParentAnchorY), this method returns the parent anchor of the Y coordinate. In that case rather use \a parentAnchorX() and \a parentAnchorY(). - + \see setParentAnchor */ @@ -12210,133 +12311,141 @@ void QCPItemAnchor::removeChildY(QCPItemPosition *pos) explained in the subclassing section of the QCPAbstractItem documentation. */ QCPItemPosition::QCPItemPosition(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString &name) : - QCPItemAnchor(parentPlot, parentItem, name), - mPositionTypeX(ptAbsolute), - mPositionTypeY(ptAbsolute), - mKey(0), - mValue(0), - mParentAnchorX(nullptr), - mParentAnchorY(nullptr) + QCPItemAnchor(parentPlot, parentItem, name), + mPositionTypeX(ptAbsolute), + mPositionTypeY(ptAbsolute), + mKey(0), + mValue(0), + mParentAnchorX(nullptr), + mParentAnchorY(nullptr) { } 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::pixelPosition function instead of QCPItemAnchor::pixelPosition - foreach (QCPItemPosition *child, mChildrenX.values()) - { - if (child->parentAnchorX() == this) - child->setParentAnchorX(nullptr); // this acts back on this anchor and child removes itself from mChildrenX - } - foreach (QCPItemPosition *child, mChildrenY.values()) - { - if (child->parentAnchorY() == this) - child->setParentAnchorY(nullptr); // this acts back on this anchor and child removes itself from mChildrenY - } - // unregister as child in parent: - if (mParentAnchorX) - mParentAnchorX->removeChildX(this); - if (mParentAnchorY) - mParentAnchorY->removeChildY(this); + // 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::pixelPosition function instead of QCPItemAnchor::pixelPosition + foreach (QCPItemPosition *child, mChildrenX.values()) { + if (child->parentAnchorX() == this) { + child->setParentAnchorX(nullptr); // this acts back on this anchor and child removes itself from mChildrenX + } + } + foreach (QCPItemPosition *child, mChildrenY.values()) { + if (child->parentAnchorY() == this) { + child->setParentAnchorY(nullptr); // this acts back on this anchor and child removes itself from mChildrenY + } + } + // unregister as child in parent: + if (mParentAnchorX) { + mParentAnchorX->removeChildX(this); + } + if (mParentAnchorY) { + mParentAnchorY->removeChildY(this); + } } /* can't make this a header inline function, because QPointer breaks with forward declared types, see QTBUG-29588 */ QCPAxisRect *QCPItemPosition::axisRect() const { - return mAxisRect.data(); + return mAxisRect.data(); } /*! Sets the type of the position. The type defines how the coordinates passed to \ref setCoords should be handled and how the QCPItemPosition should behave in the plot. - + The possible values for \a type can be separated in two main categories: \li The position is regarded as a point in plot coordinates. This corresponds to \ref ptPlotCoords and requires two axes that define the plot coordinate system. They can be specified with \ref setAxes. By default, the QCustomPlot's x- and yAxis are used. - + \li The position is fixed on the QCustomPlot surface, i.e. independent of axis ranges. This corresponds to all other types, i.e. \ref ptAbsolute, \ref ptViewportRatio and \ref ptAxisRectRatio. They differ only in the way the absolute position is described, see the documentation of \ref PositionType for details. For \ref ptAxisRectRatio, note that you can specify the axis rect with \ref setAxisRect. By default this is set to the main axis rect. - + Note that the position type \ref ptPlotCoords is only available (and sensible) when the position has no parent anchor (\ref setParentAnchor). - + If the type is changed, the apparent pixel position on the plot is preserved. This means the coordinates as retrieved with coords() and set with \ref setCoords may change in the process. - + This method sets the type for both X and Y directions. It is also possible to set different types for X and Y, see \ref setTypeX, \ref setTypeY. */ void QCPItemPosition::setType(QCPItemPosition::PositionType type) { - setTypeX(type); - setTypeY(type); + setTypeX(type); + setTypeY(type); } /*! This method sets the position type of the X coordinate to \a type. - + For a detailed description of what a position type is, see the documentation of \ref setType. - + \see setType, setTypeY */ 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 pixelPosition() because it would output a qDebug warning. - bool retainPixelPosition = true; - if ((mPositionTypeX == ptPlotCoords || type == ptPlotCoords) && (!mKeyAxis || !mValueAxis)) - retainPixelPosition = false; - if ((mPositionTypeX == ptAxisRectRatio || type == ptAxisRectRatio) && (!mAxisRect)) - retainPixelPosition = false; - - QPointF pixel; - if (retainPixelPosition) - pixel = pixelPosition(); - - mPositionTypeX = type; - - if (retainPixelPosition) - setPixelPosition(pixel); - } + 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 pixelPosition() because it would output a qDebug warning. + bool retainPixelPosition = true; + if ((mPositionTypeX == ptPlotCoords || type == ptPlotCoords) && (!mKeyAxis || !mValueAxis)) { + retainPixelPosition = false; + } + if ((mPositionTypeX == ptAxisRectRatio || type == ptAxisRectRatio) && (!mAxisRect)) { + retainPixelPosition = false; + } + + QPointF pixel; + if (retainPixelPosition) { + pixel = pixelPosition(); + } + + mPositionTypeX = type; + + if (retainPixelPosition) { + setPixelPosition(pixel); + } + } } /*! This method sets the position type of the Y coordinate to \a type. - + For a detailed description of what a position type is, see the documentation of \ref setType. - + \see setType, setTypeX */ 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 pixelPosition() because it would output a qDebug warning. - bool retainPixelPosition = true; - if ((mPositionTypeY == ptPlotCoords || type == ptPlotCoords) && (!mKeyAxis || !mValueAxis)) - retainPixelPosition = false; - if ((mPositionTypeY == ptAxisRectRatio || type == ptAxisRectRatio) && (!mAxisRect)) - retainPixelPosition = false; - - QPointF pixel; - if (retainPixelPosition) - pixel = pixelPosition(); - - mPositionTypeY = type; - - if (retainPixelPosition) - setPixelPosition(pixel); - } + 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 pixelPosition() because it would output a qDebug warning. + bool retainPixelPosition = true; + if ((mPositionTypeY == ptPlotCoords || type == ptPlotCoords) && (!mKeyAxis || !mValueAxis)) { + retainPixelPosition = false; + } + if ((mPositionTypeY == ptAxisRectRatio || type == ptAxisRectRatio) && (!mAxisRect)) { + retainPixelPosition = false; + } + + QPointF pixel; + if (retainPixelPosition) { + pixel = pixelPosition(); + } + + mPositionTypeY = type; + + if (retainPixelPosition) { + setPixelPosition(pixel); + } + } } /*! @@ -12344,167 +12453,165 @@ void QCPItemPosition::setTypeY(QCPItemPosition::PositionType type) follow any position changes of the anchor. The local coordinate system of positions with a parent anchor always is absolute pixels, with (0, 0) being exactly on top of the parent anchor. (Hence the type shouldn't be set to \ref ptPlotCoords for positions with parent anchors.) - + if \a keepPixelPosition is true, the current pixel position of the QCPItemPosition is preserved during reparenting. If it's set to false, the coordinates are set to (0, 0), i.e. the position will be exactly on top of the parent anchor. - + To remove this QCPItemPosition from any parent anchor, set \a parentAnchor to \c nullptr. - + If the QCPItemPosition previously had no parent and the type is \ref ptPlotCoords, the type is set to \ref ptAbsolute, to keep the position in a valid state. - + This method sets the parent anchor for both X and Y directions. It is also possible to set different parents for X and Y, see \ref setParentAnchorX, \ref setParentAnchorY. */ bool QCPItemPosition::setParentAnchor(QCPItemAnchor *parentAnchor, bool keepPixelPosition) { - bool successX = setParentAnchorX(parentAnchor, keepPixelPosition); - bool successY = setParentAnchorY(parentAnchor, keepPixelPosition); - return successX && successY; + bool successX = setParentAnchorX(parentAnchor, keepPixelPosition); + bool successY = setParentAnchorY(parentAnchor, keepPixelPosition); + return successX && successY; } /*! This method sets the parent anchor of the X coordinate to \a parentAnchor. - + For a detailed description of what a parent anchor is, see the documentation of \ref setParentAnchor. - + \see setParentAnchor, setParentAnchorY */ bool QCPItemPosition::setParentAnchorX(QCPItemAnchor *parentAnchor, bool keepPixelPosition) { - // make sure self is not assigned as parent: - if (parentAnchor == this) - { - qDebug() << Q_FUNC_INFO << "can't set self as parent anchor" << reinterpret_cast(parentAnchor); - return false; - } - // make sure no recursive parent-child-relationships are created: - QCPItemAnchor *currentParent = parentAnchor; - while (currentParent) - { - if (QCPItemPosition *currentParentPos = currentParent->toQCPItemPosition()) - { - // is a QCPItemPosition, might have further parent, so keep iterating - if (currentParentPos == this) - { - qDebug() << Q_FUNC_INFO << "can't create recursive parent-child-relationship" << reinterpret_cast(parentAnchor); + // make sure self is not assigned as parent: + if (parentAnchor == this) { + qDebug() << Q_FUNC_INFO << "can't set self as parent anchor" << reinterpret_cast(parentAnchor); return false; - } - currentParent = currentParentPos->parentAnchorX(); - } else - { - // is a QCPItemAnchor, can't have further parent. Now make sure the parent items aren't the - // same, to prevent a position being child of an anchor which itself depends on the position, - // because they're both on the same item: - if (currentParent->mParentItem == mParentItem) - { - qDebug() << Q_FUNC_INFO << "can't set parent to be an anchor which itself depends on this position" << reinterpret_cast(parentAnchor); - return false; - } - break; } - } - - // if previously no parent set and PosType is still ptPlotCoords, set to ptAbsolute: - if (!mParentAnchorX && mPositionTypeX == ptPlotCoords) - setTypeX(ptAbsolute); - - // save pixel position: - QPointF pixelP; - if (keepPixelPosition) - pixelP = pixelPosition(); - // unregister at current parent anchor: - if (mParentAnchorX) - mParentAnchorX->removeChildX(this); - // register at new parent anchor: - if (parentAnchor) - parentAnchor->addChildX(this); - mParentAnchorX = parentAnchor; - // restore pixel position under new parent: - if (keepPixelPosition) - setPixelPosition(pixelP); - else - setCoords(0, coords().y()); - return true; + // make sure no recursive parent-child-relationships are created: + QCPItemAnchor *currentParent = parentAnchor; + while (currentParent) { + if (QCPItemPosition *currentParentPos = currentParent->toQCPItemPosition()) { + // is a QCPItemPosition, might have further parent, so keep iterating + if (currentParentPos == this) { + qDebug() << Q_FUNC_INFO << "can't create recursive parent-child-relationship" << reinterpret_cast(parentAnchor); + return false; + } + currentParent = currentParentPos->parentAnchorX(); + } else { + // is a QCPItemAnchor, can't have further parent. Now make sure the parent items aren't the + // same, to prevent a position being child of an anchor which itself depends on the position, + // because they're both on the same item: + if (currentParent->mParentItem == mParentItem) { + qDebug() << Q_FUNC_INFO << "can't set parent to be an anchor which itself depends on this position" << reinterpret_cast(parentAnchor); + return false; + } + break; + } + } + + // if previously no parent set and PosType is still ptPlotCoords, set to ptAbsolute: + if (!mParentAnchorX && mPositionTypeX == ptPlotCoords) { + setTypeX(ptAbsolute); + } + + // save pixel position: + QPointF pixelP; + if (keepPixelPosition) { + pixelP = pixelPosition(); + } + // unregister at current parent anchor: + if (mParentAnchorX) { + mParentAnchorX->removeChildX(this); + } + // register at new parent anchor: + if (parentAnchor) { + parentAnchor->addChildX(this); + } + mParentAnchorX = parentAnchor; + // restore pixel position under new parent: + if (keepPixelPosition) { + setPixelPosition(pixelP); + } else { + setCoords(0, coords().y()); + } + return true; } /*! This method sets the parent anchor of the Y coordinate to \a parentAnchor. - + For a detailed description of what a parent anchor is, see the documentation of \ref setParentAnchor. - + \see setParentAnchor, setParentAnchorX */ bool QCPItemPosition::setParentAnchorY(QCPItemAnchor *parentAnchor, bool keepPixelPosition) { - // make sure self is not assigned as parent: - if (parentAnchor == this) - { - qDebug() << Q_FUNC_INFO << "can't set self as parent anchor" << reinterpret_cast(parentAnchor); - return false; - } - // make sure no recursive parent-child-relationships are created: - QCPItemAnchor *currentParent = parentAnchor; - while (currentParent) - { - if (QCPItemPosition *currentParentPos = currentParent->toQCPItemPosition()) - { - // is a QCPItemPosition, might have further parent, so keep iterating - if (currentParentPos == this) - { - qDebug() << Q_FUNC_INFO << "can't create recursive parent-child-relationship" << reinterpret_cast(parentAnchor); + // make sure self is not assigned as parent: + if (parentAnchor == this) { + qDebug() << Q_FUNC_INFO << "can't set self as parent anchor" << reinterpret_cast(parentAnchor); return false; - } - currentParent = currentParentPos->parentAnchorY(); - } else - { - // is a QCPItemAnchor, can't have further parent. Now make sure the parent items aren't the - // same, to prevent a position being child of an anchor which itself depends on the position, - // because they're both on the same item: - if (currentParent->mParentItem == mParentItem) - { - qDebug() << Q_FUNC_INFO << "can't set parent to be an anchor which itself depends on this position" << reinterpret_cast(parentAnchor); - return false; - } - break; } - } - - // if previously no parent set and PosType is still ptPlotCoords, set to ptAbsolute: - if (!mParentAnchorY && mPositionTypeY == ptPlotCoords) - setTypeY(ptAbsolute); - - // save pixel position: - QPointF pixelP; - if (keepPixelPosition) - pixelP = pixelPosition(); - // unregister at current parent anchor: - if (mParentAnchorY) - mParentAnchorY->removeChildY(this); - // register at new parent anchor: - if (parentAnchor) - parentAnchor->addChildY(this); - mParentAnchorY = parentAnchor; - // restore pixel position under new parent: - if (keepPixelPosition) - setPixelPosition(pixelP); - else - setCoords(coords().x(), 0); - return true; + // make sure no recursive parent-child-relationships are created: + QCPItemAnchor *currentParent = parentAnchor; + while (currentParent) { + if (QCPItemPosition *currentParentPos = currentParent->toQCPItemPosition()) { + // is a QCPItemPosition, might have further parent, so keep iterating + if (currentParentPos == this) { + qDebug() << Q_FUNC_INFO << "can't create recursive parent-child-relationship" << reinterpret_cast(parentAnchor); + return false; + } + currentParent = currentParentPos->parentAnchorY(); + } else { + // is a QCPItemAnchor, can't have further parent. Now make sure the parent items aren't the + // same, to prevent a position being child of an anchor which itself depends on the position, + // because they're both on the same item: + if (currentParent->mParentItem == mParentItem) { + qDebug() << Q_FUNC_INFO << "can't set parent to be an anchor which itself depends on this position" << reinterpret_cast(parentAnchor); + return false; + } + break; + } + } + + // if previously no parent set and PosType is still ptPlotCoords, set to ptAbsolute: + if (!mParentAnchorY && mPositionTypeY == ptPlotCoords) { + setTypeY(ptAbsolute); + } + + // save pixel position: + QPointF pixelP; + if (keepPixelPosition) { + pixelP = pixelPosition(); + } + // unregister at current parent anchor: + if (mParentAnchorY) { + mParentAnchorY->removeChildY(this); + } + // register at new parent anchor: + if (parentAnchor) { + parentAnchor->addChildY(this); + } + mParentAnchorY = parentAnchor; + // restore pixel position under new parent: + if (keepPixelPosition) { + setPixelPosition(pixelP); + } else { + setCoords(coords().x(), 0); + } + return true; } /*! Sets the coordinates of this QCPItemPosition. What the coordinates mean, is defined by the type (\ref setType, \ref setTypeX, \ref setTypeY). - + For example, if the type is \ref ptAbsolute, \a key and \a value mean the x and y pixel position on the QCustomPlot surface. In that case the origin (0, 0) is in the top left corner of the QCustomPlot viewport. If the type is \ref ptPlotCoords, \a key and \a value mean a point in the plot coordinate system defined by the axes set by \ref setAxes. By default those are the QCustomPlot's xAxis and yAxis. See the documentation of \ref setType for other available coordinate types and their meaning. - + If different types were configured for X and Y (\ref setTypeX, \ref setTypeY), \a key and \a 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. @@ -12513,8 +12620,8 @@ bool QCPItemPosition::setParentAnchorY(QCPItemAnchor *parentAnchor, bool keepPix */ void QCPItemPosition::setCoords(double key, double value) { - mKey = key; - mValue = value; + mKey = key; + mValue = value; } /*! \overload @@ -12524,7 +12631,7 @@ void QCPItemPosition::setCoords(double key, double value) */ void QCPItemPosition::setCoords(const QPointF &pos) { - setCoords(pos.x(), pos.y()); + setCoords(pos.x(), pos.y()); } /*! @@ -12535,97 +12642,95 @@ void QCPItemPosition::setCoords(const QPointF &pos) */ QPointF QCPItemPosition::pixelPosition() const { - QPointF result; - - // determine X: - switch (mPositionTypeX) - { - case ptAbsolute: - { - result.rx() = mKey; - if (mParentAnchorX) - result.rx() += mParentAnchorX->pixelPosition().x(); - break; + QPointF result; + + // determine X: + switch (mPositionTypeX) { + case ptAbsolute: { + result.rx() = mKey; + if (mParentAnchorX) { + result.rx() += mParentAnchorX->pixelPosition().x(); + } + break; + } + case ptViewportRatio: { + result.rx() = mKey * mParentPlot->viewport().width(); + if (mParentAnchorX) { + result.rx() += mParentAnchorX->pixelPosition().x(); + } else { + result.rx() += mParentPlot->viewport().left(); + } + break; + } + case ptAxisRectRatio: { + if (mAxisRect) { + result.rx() = mKey * mAxisRect.data()->width(); + if (mParentAnchorX) { + result.rx() += mParentAnchorX->pixelPosition().x(); + } else { + result.rx() += mAxisRect.data()->left(); + } + } else { + qDebug() << Q_FUNC_INFO << "Item position type x is ptAxisRectRatio, but no axis rect was defined"; + } + break; + } + case ptPlotCoords: { + if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Horizontal) { + result.rx() = mKeyAxis.data()->coordToPixel(mKey); + } else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Horizontal) { + result.rx() = mValueAxis.data()->coordToPixel(mValue); + } else { + qDebug() << Q_FUNC_INFO << "Item position type x is ptPlotCoords, but no axes were defined"; + } + break; + } } - case ptViewportRatio: - { - result.rx() = mKey*mParentPlot->viewport().width(); - if (mParentAnchorX) - result.rx() += mParentAnchorX->pixelPosition().x(); - else - result.rx() += mParentPlot->viewport().left(); - break; + + // determine Y: + switch (mPositionTypeY) { + case ptAbsolute: { + result.ry() = mValue; + if (mParentAnchorY) { + result.ry() += mParentAnchorY->pixelPosition().y(); + } + break; + } + case ptViewportRatio: { + result.ry() = mValue * mParentPlot->viewport().height(); + if (mParentAnchorY) { + result.ry() += mParentAnchorY->pixelPosition().y(); + } else { + result.ry() += mParentPlot->viewport().top(); + } + break; + } + case ptAxisRectRatio: { + if (mAxisRect) { + result.ry() = mValue * mAxisRect.data()->height(); + if (mParentAnchorY) { + result.ry() += mParentAnchorY->pixelPosition().y(); + } else { + result.ry() += mAxisRect.data()->top(); + } + } else { + qDebug() << Q_FUNC_INFO << "Item position type y is ptAxisRectRatio, but no axis rect was defined"; + } + break; + } + case ptPlotCoords: { + if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Vertical) { + result.ry() = mKeyAxis.data()->coordToPixel(mKey); + } else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Vertical) { + result.ry() = mValueAxis.data()->coordToPixel(mValue); + } else { + qDebug() << Q_FUNC_INFO << "Item position type y is ptPlotCoords, but no axes were defined"; + } + break; + } } - case ptAxisRectRatio: - { - if (mAxisRect) - { - result.rx() = mKey*mAxisRect.data()->width(); - if (mParentAnchorX) - result.rx() += mParentAnchorX->pixelPosition().x(); - else - result.rx() += mAxisRect.data()->left(); - } else - qDebug() << Q_FUNC_INFO << "Item position type x is ptAxisRectRatio, but no axis rect was defined"; - break; - } - case ptPlotCoords: - { - if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Horizontal) - result.rx() = mKeyAxis.data()->coordToPixel(mKey); - else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Horizontal) - result.rx() = mValueAxis.data()->coordToPixel(mValue); - else - qDebug() << Q_FUNC_INFO << "Item position type x is ptPlotCoords, but no axes were defined"; - break; - } - } - - // determine Y: - switch (mPositionTypeY) - { - case ptAbsolute: - { - result.ry() = mValue; - if (mParentAnchorY) - result.ry() += mParentAnchorY->pixelPosition().y(); - break; - } - case ptViewportRatio: - { - result.ry() = mValue*mParentPlot->viewport().height(); - if (mParentAnchorY) - result.ry() += mParentAnchorY->pixelPosition().y(); - else - result.ry() += mParentPlot->viewport().top(); - break; - } - case ptAxisRectRatio: - { - if (mAxisRect) - { - result.ry() = mValue*mAxisRect.data()->height(); - if (mParentAnchorY) - result.ry() += mParentAnchorY->pixelPosition().y(); - else - result.ry() += mAxisRect.data()->top(); - } else - qDebug() << Q_FUNC_INFO << "Item position type y is ptAxisRectRatio, but no axis rect was defined"; - break; - } - case ptPlotCoords: - { - if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Vertical) - result.ry() = mKeyAxis.data()->coordToPixel(mKey); - else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Vertical) - result.ry() = mValueAxis.data()->coordToPixel(mValue); - else - qDebug() << Q_FUNC_INFO << "Item position type y is ptPlotCoords, but no axes were defined"; - break; - } - } - - return result; + + return result; } /*! @@ -12635,8 +12740,8 @@ QPointF QCPItemPosition::pixelPosition() const */ void QCPItemPosition::setAxes(QCPAxis *keyAxis, QCPAxis *valueAxis) { - mKeyAxis = keyAxis; - mValueAxis = valueAxis; + mKeyAxis = keyAxis; + mValueAxis = valueAxis; } /*! @@ -12646,7 +12751,7 @@ void QCPItemPosition::setAxes(QCPAxis *keyAxis, QCPAxis *valueAxis) */ void QCPItemPosition::setAxisRect(QCPAxisRect *axisRect) { - mAxisRect = axisRect; + mAxisRect = axisRect; } /*! @@ -12661,94 +12766,92 @@ void QCPItemPosition::setAxisRect(QCPAxisRect *axisRect) */ void QCPItemPosition::setPixelPosition(const QPointF &pixelPosition) { - double x = pixelPosition.x(); - double y = pixelPosition.y(); - - switch (mPositionTypeX) - { - case ptAbsolute: - { - if (mParentAnchorX) - x -= mParentAnchorX->pixelPosition().x(); - break; + double x = pixelPosition.x(); + double y = pixelPosition.y(); + + switch (mPositionTypeX) { + case ptAbsolute: { + if (mParentAnchorX) { + x -= mParentAnchorX->pixelPosition().x(); + } + break; + } + case ptViewportRatio: { + if (mParentAnchorX) { + x -= mParentAnchorX->pixelPosition().x(); + } else { + x -= mParentPlot->viewport().left(); + } + x /= double(mParentPlot->viewport().width()); + break; + } + case ptAxisRectRatio: { + if (mAxisRect) { + if (mParentAnchorX) { + x -= mParentAnchorX->pixelPosition().x(); + } else { + x -= mAxisRect.data()->left(); + } + x /= double(mAxisRect.data()->width()); + } else { + qDebug() << Q_FUNC_INFO << "Item position type x is ptAxisRectRatio, but no axis rect was defined"; + } + break; + } + case ptPlotCoords: { + if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Horizontal) { + x = mKeyAxis.data()->pixelToCoord(x); + } else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Horizontal) { + y = mValueAxis.data()->pixelToCoord(x); + } else { + qDebug() << Q_FUNC_INFO << "Item position type x is ptPlotCoords, but no axes were defined"; + } + break; + } } - case ptViewportRatio: - { - if (mParentAnchorX) - x -= mParentAnchorX->pixelPosition().x(); - else - x -= mParentPlot->viewport().left(); - x /= double(mParentPlot->viewport().width()); - break; + + switch (mPositionTypeY) { + case ptAbsolute: { + if (mParentAnchorY) { + y -= mParentAnchorY->pixelPosition().y(); + } + break; + } + case ptViewportRatio: { + if (mParentAnchorY) { + y -= mParentAnchorY->pixelPosition().y(); + } else { + y -= mParentPlot->viewport().top(); + } + y /= double(mParentPlot->viewport().height()); + break; + } + case ptAxisRectRatio: { + if (mAxisRect) { + if (mParentAnchorY) { + y -= mParentAnchorY->pixelPosition().y(); + } else { + y -= mAxisRect.data()->top(); + } + y /= double(mAxisRect.data()->height()); + } else { + qDebug() << Q_FUNC_INFO << "Item position type y is ptAxisRectRatio, but no axis rect was defined"; + } + break; + } + case ptPlotCoords: { + if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Vertical) { + x = mKeyAxis.data()->pixelToCoord(y); + } else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Vertical) { + y = mValueAxis.data()->pixelToCoord(y); + } else { + qDebug() << Q_FUNC_INFO << "Item position type y is ptPlotCoords, but no axes were defined"; + } + break; + } } - case ptAxisRectRatio: - { - if (mAxisRect) - { - if (mParentAnchorX) - x -= mParentAnchorX->pixelPosition().x(); - else - x -= mAxisRect.data()->left(); - x /= double(mAxisRect.data()->width()); - } else - qDebug() << Q_FUNC_INFO << "Item position type x is ptAxisRectRatio, but no axis rect was defined"; - break; - } - case ptPlotCoords: - { - if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Horizontal) - x = mKeyAxis.data()->pixelToCoord(x); - else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Horizontal) - y = mValueAxis.data()->pixelToCoord(x); - else - qDebug() << Q_FUNC_INFO << "Item position type x is ptPlotCoords, but no axes were defined"; - break; - } - } - - switch (mPositionTypeY) - { - case ptAbsolute: - { - if (mParentAnchorY) - y -= mParentAnchorY->pixelPosition().y(); - break; - } - case ptViewportRatio: - { - if (mParentAnchorY) - y -= mParentAnchorY->pixelPosition().y(); - else - y -= mParentPlot->viewport().top(); - y /= double(mParentPlot->viewport().height()); - break; - } - case ptAxisRectRatio: - { - if (mAxisRect) - { - if (mParentAnchorY) - y -= mParentAnchorY->pixelPosition().y(); - else - y -= mAxisRect.data()->top(); - y /= double(mAxisRect.data()->height()); - } else - qDebug() << Q_FUNC_INFO << "Item position type y is ptAxisRectRatio, but no axis rect was defined"; - break; - } - case ptPlotCoords: - { - if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Vertical) - x = mKeyAxis.data()->pixelToCoord(y); - else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Vertical) - y = mValueAxis.data()->pixelToCoord(y); - else - qDebug() << Q_FUNC_INFO << "Item position type y is ptPlotCoords, but no axes were defined"; - break; - } - } - - setCoords(x, y); + + setCoords(x, y); } @@ -12758,18 +12861,18 @@ void QCPItemPosition::setPixelPosition(const QPointF &pixelPosition) /*! \class QCPAbstractItem \brief The abstract base class for all items in a plot. - + In QCustomPlot, items are supplemental graphical elements that are neither plottables (QCPAbstractPlottable) nor axes (QCPAxis). While plottables are always tied to two axes and thus plot coordinates, items can also be placed in absolute coordinates independent of any axes. Each specific item has at least one QCPItemPosition member which controls the positioning. Some items are defined by more than one coordinate and thus have two or more QCPItemPosition members (For example, QCPItemRect has \a topLeft and \a bottomRight). - + This abstract base class defines a very basic interface like visibility and clipping. Since this class is abstract, it can't be instantiated. Use one of the subclasses or create a subclass yourself to create new items. - + The built-in items are:
@@ -12782,7 +12885,7 @@ void QCPItemPosition::setPixelPosition(const QPointF &pixelPosition)
QCPItemLineA line defined by a start and an end point. May have different ending styles on each side (e.g. arrows).
QCPItemBracketA bracket which may be used to reference/highlight certain parts in the plot.
QCPItemTracerAn item that can be attached to a QCPGraph and sticks to its data points, given a key coordinate.
- + \section items-clipping Clipping Items are by default clipped to the main axis rect (they are only visible inside the axis rect). @@ -12794,9 +12897,9 @@ void QCPItemPosition::setPixelPosition(const QPointF &pixelPosition) in principle is independent of the coordinate axes the item might be tied to via its position members (\ref QCPItemPosition::setAxes). However, it is common that the axis rect for clipping also contains the axes used for the item positions. - + \section items-using Using items - + First you instantiate the item you want to use and add it to the plot: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-1 by default, the positions of the item are bound to the x- and y-Axis of the plot. So we can just @@ -12809,35 +12912,35 @@ void QCPItemPosition::setPixelPosition(const QPointF &pixelPosition) \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-4 and make the line visible on the entire QCustomPlot, by disabling clipping to the axis rect: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-5 - + For more advanced plots, it is even possible to set different types and parent anchors per X/Y coordinate of an item position, using for example \ref QCPItemPosition::setTypeX or \ref QCPItemPosition::setParentAnchorX. For details, see the documentation of \ref QCPItemPosition. - + \section items-subclassing Creating own items - + To create an own item, you implement a subclass of QCPAbstractItem. These are the pure virtual functions, you must implement: \li \ref selectTest \li \ref draw - + See the documentation of those functions for what they need to do. - + \subsection items-positioning Allowing the item to be positioned - + As mentioned, item positions are represented by QCPItemPosition members. Let's assume the new item shall have only one point as its position (as opposed to two like a rect or multiple like a polygon). You then add a public member of type QCPItemPosition like so: - + \code QCPItemPosition * const myPosition;\endcode - + the const makes sure the pointer itself can't be modified from the user of your new item (the QCPItemPosition instance it points to, can be modified, of course). The initialization of this pointer is made easy with the \ref createPosition function. Just assign the return value of this function to each QCPItemPosition in the constructor of your item. \ref createPosition takes a string which is the name of the position, typically this is identical to the variable name. For example, the constructor of QCPItemExample could look like this: - + \code QCPItemExample::QCPItemExample(QCustomPlot *parentPlot) : QCPAbstractItem(parentPlot), @@ -12846,9 +12949,9 @@ void QCPItemPosition::setPixelPosition(const QPointF &pixelPosition) // other constructor code } \endcode - + \subsection items-drawing The draw function - + 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::pixelPosition. @@ -12856,19 +12959,19 @@ void QCPItemPosition::setPixelPosition(const QPointF &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 if this is the case. - + \subsection items-selection The selectTest function - + 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 - + Providing anchors (QCPItemAnchor) starts off like adding a position. First you create a public member, e.g. - + \code QCPItemAnchor * const bottom;\endcode and create it in the constructor with the \ref createAnchor function, assigning it a name and an @@ -12876,7 +12979,7 @@ void QCPItemPosition::setPixelPosition(const QPointF &pixelPosition) 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 anchorPixelPosition(int anchorId) function. - + In essence the QCPItemAnchor is merely an intermediary that itself asks your item for the pixel position when anything attached to the anchor needs to know the coordinates. */ @@ -12884,17 +12987,17 @@ void QCPItemPosition::setPixelPosition(const QPointF &pixelPosition) /* start of documentation of inline functions */ /*! \fn QList QCPAbstractItem::positions() const - + Returns all positions of the item in a list. - + \see anchors, position */ /*! \fn QList QCPAbstractItem::anchors() const - + Returns all anchors of the item in a list. Note that since a position (QCPItemPosition) is always also an anchor, the list will also contain the positions of this item. - + \see positions, anchor */ @@ -12903,9 +13006,9 @@ void QCPItemPosition::setPixelPosition(const QPointF &pixelPosition) /*! \fn void QCPAbstractItem::draw(QCPPainter *painter) = 0 \internal - + Draws this item with the provided \a painter. - + The cliprect of the provided painter is set to the rect returned by \ref clipRect before this function is called. The clipRect depends on the clipping settings defined by \ref setClipToAxisRect and \ref setClipAxisRect. @@ -12925,75 +13028,75 @@ void QCPItemPosition::setPixelPosition(const QPointF &pixelPosition) Base class constructor which initializes base class members. */ QCPAbstractItem::QCPAbstractItem(QCustomPlot *parentPlot) : - QCPLayerable(parentPlot), - mClipToAxisRect(false), - mSelectable(true), - mSelected(false) + QCPLayerable(parentPlot), + mClipToAxisRect(false), + mSelectable(true), + mSelected(false) { - parentPlot->registerItem(this); - - QList rects = parentPlot->axisRects(); - if (!rects.isEmpty()) - { - setClipToAxisRect(true); - setClipAxisRect(rects.first()); - } + parentPlot->registerItem(this); + + QList rects = parentPlot->axisRects(); + if (!rects.isEmpty()) { + setClipToAxisRect(true); + setClipAxisRect(rects.first()); + } } QCPAbstractItem::~QCPAbstractItem() { - // don't delete mPositions because every position is also an anchor and thus in mAnchors - qDeleteAll(mAnchors); + // don't delete mPositions because every position is also an anchor and thus in mAnchors + qDeleteAll(mAnchors); } /* can't make this a header inline function, because QPointer breaks with forward declared types, see QTBUG-29588 */ QCPAxisRect *QCPAbstractItem::clipAxisRect() const { - return mClipAxisRect.data(); + return mClipAxisRect.data(); } /*! Sets whether the item shall be clipped to an axis rect or whether it shall be visible on the entire QCustomPlot. The axis rect can be set with \ref setClipAxisRect. - + \see setClipAxisRect */ void QCPAbstractItem::setClipToAxisRect(bool clip) { - mClipToAxisRect = clip; - if (mClipToAxisRect) - setParentLayerable(mClipAxisRect.data()); + mClipToAxisRect = clip; + if (mClipToAxisRect) { + setParentLayerable(mClipAxisRect.data()); + } } /*! Sets the clip axis rect. It defines the rect that will be used to clip the item when \ref setClipToAxisRect is set to true. - + \see setClipToAxisRect */ void QCPAbstractItem::setClipAxisRect(QCPAxisRect *rect) { - mClipAxisRect = rect; - if (mClipToAxisRect) - setParentLayerable(mClipAxisRect.data()); + mClipAxisRect = rect; + if (mClipToAxisRect) { + setParentLayerable(mClipAxisRect.data()); + } } /*! Sets whether the user can (de-)select this item by clicking on the QCustomPlot surface. (When \ref QCustomPlot::setInteractions contains QCustomPlot::iSelectItems.) - + However, even when \a selectable was set to false, it is possible to set the selection manually, by calling \ref setSelected. - + \see QCustomPlot::setInteractions, setSelected */ void QCPAbstractItem::setSelectable(bool selectable) { - if (mSelectable != selectable) - { - mSelectable = selectable; - emit selectableChanged(mSelectable); - } + if (mSelectable != selectable) { + mSelectable = selectable; + emit selectableChanged(mSelectable); + } } /*! @@ -13003,97 +13106,97 @@ void QCPAbstractItem::setSelectable(bool selectable) The entire selection mechanism for items is handled automatically when \ref QCustomPlot::setInteractions contains QCustomPlot::iSelectItems. You only need to call this function when you wish to change the selection state manually. - + This function can change the selection state even when \ref setSelectable was set to false. - + emits the \ref selectionChanged signal when \a selected is different from the previous selection state. - + \see setSelectable, selectTest */ void QCPAbstractItem::setSelected(bool selected) { - if (mSelected != selected) - { - mSelected = selected; - emit selectionChanged(mSelected); - } + if (mSelected != selected) { + mSelected = selected; + emit selectionChanged(mSelected); + } } /*! Returns the QCPItemPosition with the specified \a name. If this item doesn't have a position by that name, returns \c nullptr. - + This function provides an alternative way to access item positions. Normally, you access positions direcly by their member pointers (which typically have the same variable name as \a name). - + \see positions, anchor */ QCPItemPosition *QCPAbstractItem::position(const QString &name) const { - foreach (QCPItemPosition *position, mPositions) - { - if (position->name() == name) - return position; - } - qDebug() << Q_FUNC_INFO << "position with name not found:" << name; - return nullptr; + foreach (QCPItemPosition *position, mPositions) { + if (position->name() == name) { + return position; + } + } + qDebug() << Q_FUNC_INFO << "position with name not found:" << name; + return nullptr; } /*! Returns the QCPItemAnchor with the specified \a name. If this item doesn't have an anchor by that name, returns \c nullptr. - + This function provides an alternative way to access item anchors. Normally, you access anchors direcly by their member pointers (which typically have the same variable name as \a name). - + \see anchors, position */ QCPItemAnchor *QCPAbstractItem::anchor(const QString &name) const { - foreach (QCPItemAnchor *anchor, mAnchors) - { - if (anchor->name() == name) - return anchor; - } - qDebug() << Q_FUNC_INFO << "anchor with name not found:" << name; - return nullptr; + foreach (QCPItemAnchor *anchor, mAnchors) { + if (anchor->name() == name) { + return anchor; + } + } + qDebug() << Q_FUNC_INFO << "anchor with name not found:" << name; + return nullptr; } /*! Returns whether this item has an anchor with the specified \a name. - + Note that you can check for positions with this function, too. This is because every position is also an anchor (QCPItemPosition inherits from QCPItemAnchor). - + \see anchor, position */ bool QCPAbstractItem::hasAnchor(const QString &name) const { - foreach (QCPItemAnchor *anchor, mAnchors) - { - if (anchor->name() == name) - return true; - } - return false; + foreach (QCPItemAnchor *anchor, mAnchors) { + if (anchor->name() == name) { + return true; + } + } + return false; } /*! \internal - + 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, QCustomPlot's viewport rect is returned. - + \see draw */ QRect QCPAbstractItem::clipRect() const { - if (mClipToAxisRect && mClipAxisRect) - return mClipAxisRect.data()->rect(); - else - return mParentPlot->viewport(); + if (mClipToAxisRect && mClipAxisRect) { + return mClipAxisRect.data()->rect(); + } else { + return mParentPlot->viewport(); + } } /*! \internal @@ -13102,16 +13205,16 @@ QRect QCPAbstractItem::clipRect() const before drawing item lines. This is the antialiasing state the painter passed to the \ref draw method is in by default. - + 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 */ void QCPAbstractItem::applyDefaultAntialiasingHint(QCPPainter *painter) const { - applyAntialiasingHint(painter, mAntialiased, QCP::aeItems); + applyAntialiasingHint(painter, mAntialiased, QCP::aeItems); } /*! \internal @@ -13119,54 +13222,54 @@ void QCPAbstractItem::applyDefaultAntialiasingHint(QCPPainter *painter) const A convenience function which returns the selectTest value for a specified \a rect and a specified click position \a pos. \a filledRect defines whether a click inside the rect should also be considered a hit or whether only the rect border is sensitive to hits. - + This function may be used to help with the implementation of the \ref selectTest function for 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 (non -1) of all four returned values. */ double QCPAbstractItem::rectDistance(const QRectF &rect, const QPointF &pos, bool filledRect) const { - double result = -1; + double result = -1; - // distance to border: - const QList lines = QList() << QLineF(rect.topLeft(), rect.topRight()) << QLineF(rect.bottomLeft(), rect.bottomRight()) - << QLineF(rect.topLeft(), rect.bottomLeft()) << QLineF(rect.topRight(), rect.bottomRight()); - const QCPVector2D posVec(pos); - double minDistSqr = (std::numeric_limits::max)(); - foreach (const QLineF &line, lines) - { - double distSqr = posVec.distanceSquaredToLine(line.p1(), line.p2()); - if (distSqr < minDistSqr) - minDistSqr = distSqr; - } - result = qSqrt(minDistSqr); - - // filled rect, allow click inside to count as hit: - if (filledRect && result > mParentPlot->selectionTolerance()*0.99) - { - if (rect.contains(pos)) - result = mParentPlot->selectionTolerance()*0.99; - } - return result; + // distance to border: + const QList lines = QList() << QLineF(rect.topLeft(), rect.topRight()) << QLineF(rect.bottomLeft(), rect.bottomRight()) + << QLineF(rect.topLeft(), rect.bottomLeft()) << QLineF(rect.topRight(), rect.bottomRight()); + const QCPVector2D posVec(pos); + double minDistSqr = (std::numeric_limits::max)(); + foreach (const QLineF &line, lines) { + double distSqr = posVec.distanceSquaredToLine(line.p1(), line.p2()); + if (distSqr < minDistSqr) { + minDistSqr = distSqr; + } + } + result = qSqrt(minDistSqr); + + // filled rect, allow click inside to count as hit: + if (filledRect && result > mParentPlot->selectionTolerance() * 0.99) { + if (rect.contains(pos)) { + result = mParentPlot->selectionTolerance() * 0.99; + } + } + return result; } /*! \internal Returns the pixel position of the anchor with Id \a anchorId. This function must be reimplemented in item subclasses if they want to provide anchors (QCPItemAnchor). - + For example, if the item has two anchors with id 0 and 1, this function takes one of these anchor ids and returns the respective pixel points of the specified anchor. - + \see createAnchor */ QPointF QCPAbstractItem::anchorPixelPosition(int anchorId) const { - qDebug() << Q_FUNC_INFO << "called on item which shouldn't have any anchors (this method not reimplemented). anchorId" << anchorId; - return {}; + qDebug() << Q_FUNC_INFO << "called on item which shouldn't have any anchors (this method not reimplemented). anchorId" << anchorId; + return {}; } /*! \internal @@ -13174,28 +13277,30 @@ QPointF QCPAbstractItem::anchorPixelPosition(int anchorId) const Creates a QCPItemPosition, registers it with this item and returns a pointer to it. The specified \a name must be a unique string that is usually identical to the variable name of the position member (This is needed to provide the name-based \ref position access to positions). - + Don't delete positions created by this function manually, as the item will take care of it. - + Use this function in the constructor (initialization list) of the specific item subclass to create each position member. Don't create QCPItemPositions with \b new yourself, because they won't be registered with the item properly. - + \see createAnchor */ QCPItemPosition *QCPAbstractItem::createPosition(const QString &name) { - if (hasAnchor(name)) - qDebug() << Q_FUNC_INFO << "anchor/position with name exists already:" << name; - QCPItemPosition *newPosition = new QCPItemPosition(mParentPlot, this, name); - mPositions.append(newPosition); - mAnchors.append(newPosition); // every position is also an anchor - newPosition->setAxes(mParentPlot->xAxis, mParentPlot->yAxis); - newPosition->setType(QCPItemPosition::ptPlotCoords); - if (mParentPlot->axisRect()) - newPosition->setAxisRect(mParentPlot->axisRect()); - newPosition->setCoords(0, 0); - return newPosition; + if (hasAnchor(name)) { + qDebug() << Q_FUNC_INFO << "anchor/position with name exists already:" << name; + } + QCPItemPosition *newPosition = new QCPItemPosition(mParentPlot, this, name); + mPositions.append(newPosition); + mAnchors.append(newPosition); // every position is also an anchor + newPosition->setAxes(mParentPlot->xAxis, mParentPlot->yAxis); + newPosition->setType(QCPItemPosition::ptPlotCoords); + if (mParentPlot->axisRect()) { + newPosition->setAxisRect(mParentPlot->axisRect()); + } + newPosition->setCoords(0, 0); + return newPosition; } /*! \internal @@ -13203,59 +13308,60 @@ QCPItemPosition *QCPAbstractItem::createPosition(const QString &name) Creates a QCPItemAnchor, registers it with this item and returns a pointer to it. The specified \a name must be a unique string that is usually identical to the variable name of the anchor member (This is needed to provide the name based \ref anchor access to anchors). - + The \a anchorId must be a number identifying the created anchor. It is recommended to create an enum (e.g. "AnchorIndex") for this on each item that uses anchors. This id is used by the anchor to identify itself when it calls QCPAbstractItem::anchorPixelPosition. That function then returns the correct pixel coordinates for the passed anchor id. - + Don't delete anchors created by this function manually, as the item will take care of it. - + Use this function in the constructor (initialization list) of the specific item subclass to create each anchor member. Don't create QCPItemAnchors with \b new yourself, because then they won't be registered with the item properly. - + \see createPosition */ QCPItemAnchor *QCPAbstractItem::createAnchor(const QString &name, int anchorId) { - if (hasAnchor(name)) - qDebug() << Q_FUNC_INFO << "anchor/position with name exists already:" << name; - QCPItemAnchor *newAnchor = new QCPItemAnchor(mParentPlot, this, name, anchorId); - mAnchors.append(newAnchor); - return newAnchor; + if (hasAnchor(name)) { + qDebug() << Q_FUNC_INFO << "anchor/position with name exists already:" << name; + } + QCPItemAnchor *newAnchor = new QCPItemAnchor(mParentPlot, this, name, anchorId); + mAnchors.append(newAnchor); + return newAnchor; } /* inherits documentation from base class */ void QCPAbstractItem::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) { - Q_UNUSED(event) - Q_UNUSED(details) - if (mSelectable) - { - bool selBefore = mSelected; - setSelected(additive ? !mSelected : true); - if (selectionStateChanged) - *selectionStateChanged = mSelected != selBefore; - } + Q_UNUSED(event) + Q_UNUSED(details) + if (mSelectable) { + bool selBefore = mSelected; + setSelected(additive ? !mSelected : true); + if (selectionStateChanged) { + *selectionStateChanged = mSelected != selBefore; + } + } } /* inherits documentation from base class */ void QCPAbstractItem::deselectEvent(bool *selectionStateChanged) { - if (mSelectable) - { - bool selBefore = mSelected; - setSelected(false); - if (selectionStateChanged) - *selectionStateChanged = mSelected != selBefore; - } + if (mSelectable) { + bool selBefore = mSelected; + setSelected(false); + if (selectionStateChanged) { + *selectionStateChanged = mSelected != selBefore; + } + } } /* inherits documentation from base class */ QCP::Interaction QCPAbstractItem::selectionCategory() const { - return QCP::iSelectItems; + return QCP::iSelectItems; } /* end of 'src/item.cpp' */ @@ -13268,10 +13374,10 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCustomPlot - + \brief The central class of the library. This is the QWidget which displays the plot and interacts with the user. - + For tutorials on how to use QCustomPlot, see the website\n http://www.qcustomplot.com/ */ @@ -13279,15 +13385,15 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const /* start of documentation of inline functions */ /*! \fn QCPSelectionRect *QCustomPlot::selectionRect() const - + Allows access to the currently used QCPSelectionRect instance (or subclass thereof), that is used to handle and draw selection rect interactions (see \ref setSelectionRectMode). - + \see setSelectionRect */ /*! \fn QCPLayoutGrid *QCustomPlot::plotLayout() const - + Returns the top level layout of this QCustomPlot instance. It is a \ref QCPLayoutGrid, initially containing just one cell with the main QCPAxisRect inside. */ @@ -13303,7 +13409,7 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const /*! \fn void QCustomPlot::mousePress(QMouseEvent *event) This signal is emitted when the QCustomPlot receives a mouse press event. - + It is emitted before QCustomPlot handles any other mechanism like range dragging. So a slot connected to this signal can still influence the behaviour e.g. with \ref QCPAxisRect::setRangeDrag or \ref QCPAxisRect::setRangeDragAxes. @@ -13312,11 +13418,11 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const /*! \fn void QCustomPlot::mouseMove(QMouseEvent *event) This signal is emitted when the QCustomPlot receives a mouse move event. - + It is emitted before QCustomPlot handles any other mechanism like range dragging. So a slot connected to this signal can still influence the behaviour e.g. with \ref QCPAxisRect::setRangeDrag or \ref QCPAxisRect::setRangeDragAxes. - + \warning It is discouraged to change the drag-axes with \ref QCPAxisRect::setRangeDragAxes here, because the dragging starting point was saved the moment the mouse was pressed. Thus it only has a meaning for the range drag axes that were set at that moment. If you want to change the drag @@ -13326,7 +13432,7 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const /*! \fn void QCustomPlot::mouseRelease(QMouseEvent *event) This signal is emitted when the QCustomPlot receives a mouse release event. - + It is emitted before QCustomPlot handles any other mechanisms like object selection. So a slot connected to this signal can still influence the behaviour e.g. with \ref setInteractions or \ref QCPAbstractPlottable::setSelectable. @@ -13335,7 +13441,7 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const /*! \fn void QCustomPlot::mouseWheel(QMouseEvent *event) This signal is emitted when the QCustomPlot receives a mouse wheel event. - + It is emitted before QCustomPlot handles any other mechanisms like range zooming. So a slot connected to this signal can still influence the behaviour e.g. with \ref QCPAxisRect::setRangeZoom, \ref QCPAxisRect::setRangeZoomAxes or \ref QCPAxisRect::setRangeZoomFactor. @@ -13364,93 +13470,93 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const */ /*! \fn void QCustomPlot::itemClick(QCPAbstractItem *item, QMouseEvent *event) - + This signal is emitted when an item is clicked. \a event is the mouse event that caused the click and \a item is the item that received the click. - + \see itemDoubleClick */ /*! \fn void QCustomPlot::itemDoubleClick(QCPAbstractItem *item, QMouseEvent *event) - + This signal is emitted when an item is double clicked. - + \a event is the mouse event that caused the click and \a item is the item that received the click. - + \see itemClick */ /*! \fn void QCustomPlot::axisClick(QCPAxis *axis, QCPAxis::SelectablePart part, QMouseEvent *event) - + This signal is emitted when an axis is clicked. - + \a event is the mouse event that caused the click, \a axis is the axis that received the click and \a part indicates the part of the axis that was clicked. - + \see axisDoubleClick */ /*! \fn void QCustomPlot::axisDoubleClick(QCPAxis *axis, QCPAxis::SelectablePart part, QMouseEvent *event) This signal is emitted when an axis is double clicked. - + \a event is the mouse event that caused the click, \a axis is the axis that received the click and \a part indicates the part of the axis that was clicked. - + \see axisClick */ /*! \fn void QCustomPlot::legendClick(QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event) This signal is emitted when a legend (item) is clicked. - + \a event is the mouse event that caused the click, \a legend is the legend that received the click and \a item is the legend item that received the click. If only the legend and no item is clicked, \a item is \c nullptr. This happens for a click inside the legend padding or the space between two items. - + \see legendDoubleClick */ /*! \fn void QCustomPlot::legendDoubleClick(QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event) This signal is emitted when a legend (item) is double clicked. - + \a event is the mouse event that caused the click, \a legend is the legend that received the click and \a item is the legend item that received the click. If only the legend and no item is clicked, \a item is \c nullptr. This happens for a click inside the legend padding or the space between two items. - + \see legendClick */ /*! \fn void QCustomPlot::selectionChangedByUser() - + This signal is emitted after the user has changed the selection in the QCustomPlot, e.g. by clicking. It is not emitted when the selection state of an object has changed programmatically by a direct call to setSelected()/setSelection() on an object or by calling \ref deselectAll. - + 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. - + \see selectedPlottables, selectedGraphs, selectedItems, selectedAxes, selectedLegends */ /*! \fn void QCustomPlot::beforeReplot() - + This signal is emitted immediately before a replot takes place (caused by a call to the slot \ref replot). - + It is safe to mutually connect the replot slot with this signal on two QCustomPlots to make them replot synchronously, it won't cause an infinite recursion. - + \see replot, afterReplot, afterLayout */ @@ -13476,13 +13582,13 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const */ /*! \fn void QCustomPlot::afterReplot() - + This signal is emitted immediately after a replot has taken place (caused by a call to the slot \ref replot). - + It is safe to mutually connect the replot slot with this signal on two QCustomPlots to make them replot synchronously, it won't cause an infinite recursion. - + \see replot, beforeReplot, afterLayout */ @@ -13492,7 +13598,7 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const /*! \var QCPAxis *QCustomPlot::xAxis A pointer to the primary x Axis (bottom) of the main axis rect of the plot. - + QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref yAxis2) and the \ref legend. They make it very easy working with plots that only have a single axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the @@ -13500,7 +13606,7 @@ 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 \c nullptr. - + If an axis convenience pointer is currently \c nullptr 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 @@ -13510,7 +13616,7 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const /*! \var QCPAxis *QCustomPlot::yAxis A pointer to the primary y Axis (left) of the main axis rect of the plot. - + QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref yAxis2) and the \ref legend. They make it very easy working with plots that only have a single axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the @@ -13518,7 +13624,7 @@ 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 \c nullptr. - + If an axis convenience pointer is currently \c nullptr 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 @@ -13530,7 +13636,7 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const A pointer to the secondary x Axis (top) of the main axis rect of the plot. Secondary axes are invisible by default. Use QCPAxis::setVisible to change this (or use \ref QCPAxisRect::setupFullAxesBox). - + QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref yAxis2) and the \ref legend. They make it very easy working with plots that only have a single axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the @@ -13538,7 +13644,7 @@ 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 \c nullptr. - + If an axis convenience pointer is currently \c nullptr 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 @@ -13550,7 +13656,7 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const A pointer to the secondary y Axis (right) of the main axis rect of the plot. Secondary axes are invisible by default. Use QCPAxis::setVisible to change this (or use \ref QCPAxisRect::setupFullAxesBox). - + QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref yAxis2) and the \ref legend. They make it very easy working with plots that only have a single axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the @@ -13558,7 +13664,7 @@ 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 \c nullptr. - + If an axis convenience pointer is currently \c nullptr 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 @@ -13569,7 +13675,7 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const A pointer to the default legend of the main axis rect. The legend is invisible by default. Use QCPLegend::setVisible to change this. - + QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref yAxis2) and the \ref legend. They make it very easy working with plots that only have a single axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the @@ -13578,7 +13684,7 @@ 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 \c nullptr. - + If an axis convenience pointer is currently \c nullptr 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 @@ -13591,232 +13697,237 @@ QCP::Interaction QCPAbstractItem::selectionCategory() const Constructs a QCustomPlot and sets reasonable default values. */ QCustomPlot::QCustomPlot(QWidget *parent) : - QWidget(parent), - xAxis(nullptr), - yAxis(nullptr), - xAxis2(nullptr), - yAxis2(nullptr), - legend(nullptr), - mBufferDevicePixelRatio(1.0), // will be adapted to primary screen below - mPlotLayout(nullptr), - mAutoAddPlottableToLegend(true), - mAntialiasedElements(QCP::aeNone), - mNotAntialiasedElements(QCP::aeNone), - mInteractions(QCP::iNone), - mSelectionTolerance(8), - mNoAntialiasingOnDrag(false), - mBackgroundBrush(Qt::white, Qt::SolidPattern), - mBackgroundScaled(true), - mBackgroundScaledMode(Qt::KeepAspectRatioByExpanding), - mCurrentLayer(nullptr), - mPlottingHints(QCP::phCacheLabels|QCP::phImmediateRefresh), - mMultiSelectModifier(Qt::ControlModifier), - mSelectionRectMode(QCP::srmNone), - mSelectionRect(nullptr), - mOpenGl(false), - mMouseHasMoved(false), - mMouseEventLayerable(nullptr), - mMouseSignalLayerable(nullptr), - mReplotting(false), - mReplotQueued(false), - mReplotTime(0), - mReplotTimeAverage(0), - mOpenGlMultisamples(16), - mOpenGlAntialiasedElementsBackup(QCP::aeNone), - mOpenGlCacheLabelsBackup(true) + QWidget(parent), + xAxis(nullptr), + yAxis(nullptr), + xAxis2(nullptr), + yAxis2(nullptr), + legend(nullptr), + mBufferDevicePixelRatio(1.0), // will be adapted to primary screen below + mPlotLayout(nullptr), + mAutoAddPlottableToLegend(true), + mAntialiasedElements(QCP::aeNone), + mNotAntialiasedElements(QCP::aeNone), + mInteractions(QCP::iNone), + mSelectionTolerance(8), + mNoAntialiasingOnDrag(false), + mBackgroundBrush(Qt::white, Qt::SolidPattern), + mBackgroundScaled(true), + mBackgroundScaledMode(Qt::KeepAspectRatioByExpanding), + mCurrentLayer(nullptr), + mPlottingHints(QCP::phCacheLabels | QCP::phImmediateRefresh), + mMultiSelectModifier(Qt::ControlModifier), + mSelectionRectMode(QCP::srmNone), + mSelectionRect(nullptr), + mOpenGl(false), + mMouseHasMoved(false), + mMouseEventLayerable(nullptr), + mMouseSignalLayerable(nullptr), + mReplotting(false), + mReplotQueued(false), + mReplotTime(0), + mReplotTimeAverage(0), + 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); + 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 # ifdef QCP_DEVICEPIXELRATIO_FLOAT - setBufferDevicePixelRatio(QWidget::devicePixelRatioF()); + setBufferDevicePixelRatio(QWidget::devicePixelRatioF()); # else - setBufferDevicePixelRatio(QWidget::devicePixelRatio()); + setBufferDevicePixelRatio(QWidget::devicePixelRatio()); # endif #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; - mPlotLayout->initializeParentPlot(this); - mPlotLayout->setParent(this); // important because if parent is QWidget, QCPLayout::sizeConstraintsChanged will call QWidget::updateGeometry - mPlotLayout->setLayer(QLatin1String("main")); - QCPAxisRect *defaultAxisRect = new QCPAxisRect(this, true); - mPlotLayout->addElement(0, 0, defaultAxisRect); - xAxis = defaultAxisRect->axis(QCPAxis::atBottom); - yAxis = defaultAxisRect->axis(QCPAxis::atLeft); - xAxis2 = defaultAxisRect->axis(QCPAxis::atTop); - yAxis2 = defaultAxisRect->axis(QCPAxis::atRight); - legend = new QCPLegend; - legend->setVisible(false); - defaultAxisRect->insetLayout()->addElement(legend, Qt::AlignRight|Qt::AlignTop); - defaultAxisRect->insetLayout()->setMargins(QMargins(12, 12, 12, 12)); - - defaultAxisRect->setLayer(QLatin1String("background")); - xAxis->setLayer(QLatin1String("axes")); - yAxis->setLayer(QLatin1String("axes")); - xAxis2->setLayer(QLatin1String("axes")); - yAxis2->setLayer(QLatin1String("axes")); - xAxis->grid()->setLayer(QLatin1String("grid")); - yAxis->grid()->setLayer(QLatin1String("grid")); - xAxis2->grid()->setLayer(QLatin1String("grid")); - 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(rpQueuedReplot); + + 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; + mPlotLayout->initializeParentPlot(this); + mPlotLayout->setParent(this); // important because if parent is QWidget, QCPLayout::sizeConstraintsChanged will call QWidget::updateGeometry + mPlotLayout->setLayer(QLatin1String("main")); + QCPAxisRect *defaultAxisRect = new QCPAxisRect(this, true); + mPlotLayout->addElement(0, 0, defaultAxisRect); + xAxis = defaultAxisRect->axis(QCPAxis::atBottom); + yAxis = defaultAxisRect->axis(QCPAxis::atLeft); + xAxis2 = defaultAxisRect->axis(QCPAxis::atTop); + yAxis2 = defaultAxisRect->axis(QCPAxis::atRight); + legend = new QCPLegend; + legend->setVisible(false); + defaultAxisRect->insetLayout()->addElement(legend, Qt::AlignRight | Qt::AlignTop); + defaultAxisRect->insetLayout()->setMargins(QMargins(12, 12, 12, 12)); + + defaultAxisRect->setLayer(QLatin1String("background")); + xAxis->setLayer(QLatin1String("axes")); + yAxis->setLayer(QLatin1String("axes")); + xAxis2->setLayer(QLatin1String("axes")); + yAxis2->setLayer(QLatin1String("axes")); + xAxis->grid()->setLayer(QLatin1String("grid")); + yAxis->grid()->setLayer(QLatin1String("grid")); + xAxis2->grid()->setLayer(QLatin1String("grid")); + 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(rpQueuedReplot); } QCustomPlot::~QCustomPlot() { - clearPlottables(); - clearItems(); + clearPlottables(); + clearItems(); - if (mPlotLayout) - { - delete mPlotLayout; - mPlotLayout = nullptr; - } - - mCurrentLayer = nullptr; - qDeleteAll(mLayers); // don't use removeLayer, because it would prevent the last layer to be removed - mLayers.clear(); + if (mPlotLayout) { + delete mPlotLayout; + mPlotLayout = nullptr; + } + + mCurrentLayer = nullptr; + qDeleteAll(mLayers); // don't use removeLayer, because it would prevent the last layer to be removed + mLayers.clear(); } /*! Sets which elements are forcibly drawn antialiased as an \a or combination of QCP::AntialiasedElement. - + This overrides the antialiasing settings for whole element groups, normally controlled with the \a setAntialiasing function on the individual elements. If an element is neither specified in \ref setAntialiasedElements nor in \ref setNotAntialiasedElements, the antialiasing setting on each individual element instance is used. - + For example, if \a antialiasedElements contains \ref QCP::aePlottables, all plottables will be drawn antialiased, no matter what the specific QCPAbstractPlottable::setAntialiased value was set to. - + if an element in \a antialiasedElements is already set in \ref setNotAntialiasedElements, it is removed from there. - + \see setNotAntialiasedElements */ void QCustomPlot::setAntialiasedElements(const QCP::AntialiasedElements &antialiasedElements) { - mAntialiasedElements = antialiasedElements; - - // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously: - if ((mNotAntialiasedElements & mAntialiasedElements) != 0) - mNotAntialiasedElements |= ~mAntialiasedElements; + mAntialiasedElements = antialiasedElements; + + // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously: + if ((mNotAntialiasedElements & mAntialiasedElements) != 0) { + mNotAntialiasedElements |= ~mAntialiasedElements; + } } /*! Sets whether the specified \a antialiasedElement is forcibly drawn antialiased. - + See \ref setAntialiasedElements for details. - + \see setNotAntialiasedElement */ void QCustomPlot::setAntialiasedElement(QCP::AntialiasedElement antialiasedElement, bool enabled) { - if (!enabled && mAntialiasedElements.testFlag(antialiasedElement)) - mAntialiasedElements &= ~antialiasedElement; - else if (enabled && !mAntialiasedElements.testFlag(antialiasedElement)) - mAntialiasedElements |= antialiasedElement; - - // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously: - if ((mNotAntialiasedElements & mAntialiasedElements) != 0) - mNotAntialiasedElements |= ~mAntialiasedElements; + if (!enabled && mAntialiasedElements.testFlag(antialiasedElement)) { + mAntialiasedElements &= ~antialiasedElement; + } else if (enabled && !mAntialiasedElements.testFlag(antialiasedElement)) { + mAntialiasedElements |= antialiasedElement; + } + + // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously: + if ((mNotAntialiasedElements & mAntialiasedElements) != 0) { + mNotAntialiasedElements |= ~mAntialiasedElements; + } } /*! Sets which elements are forcibly drawn not antialiased as an \a or combination of QCP::AntialiasedElement. - + This overrides the antialiasing settings for whole element groups, normally controlled with the \a setAntialiasing function on the individual elements. If an element is neither specified in \ref setAntialiasedElements nor in \ref setNotAntialiasedElements, the antialiasing setting on each individual element instance is used. - + For example, if \a notAntialiasedElements contains \ref QCP::aePlottables, no plottables will be drawn antialiased, no matter what the specific QCPAbstractPlottable::setAntialiased value was set to. - + if an element in \a notAntialiasedElements is already set in \ref setAntialiasedElements, it is removed from there. - + \see setAntialiasedElements */ void QCustomPlot::setNotAntialiasedElements(const QCP::AntialiasedElements ¬AntialiasedElements) { - mNotAntialiasedElements = notAntialiasedElements; - - // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously: - if ((mNotAntialiasedElements & mAntialiasedElements) != 0) - mAntialiasedElements |= ~mNotAntialiasedElements; + mNotAntialiasedElements = notAntialiasedElements; + + // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously: + if ((mNotAntialiasedElements & mAntialiasedElements) != 0) { + mAntialiasedElements |= ~mNotAntialiasedElements; + } } /*! Sets whether the specified \a notAntialiasedElement is forcibly drawn not antialiased. - + See \ref setNotAntialiasedElements for details. - + \see setAntialiasedElement */ void QCustomPlot::setNotAntialiasedElement(QCP::AntialiasedElement notAntialiasedElement, bool enabled) { - if (!enabled && mNotAntialiasedElements.testFlag(notAntialiasedElement)) - mNotAntialiasedElements &= ~notAntialiasedElement; - else if (enabled && !mNotAntialiasedElements.testFlag(notAntialiasedElement)) - mNotAntialiasedElements |= notAntialiasedElement; - - // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously: - if ((mNotAntialiasedElements & mAntialiasedElements) != 0) - mAntialiasedElements |= ~mNotAntialiasedElements; + if (!enabled && mNotAntialiasedElements.testFlag(notAntialiasedElement)) { + mNotAntialiasedElements &= ~notAntialiasedElement; + } else if (enabled && !mNotAntialiasedElements.testFlag(notAntialiasedElement)) { + mNotAntialiasedElements |= notAntialiasedElement; + } + + // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously: + if ((mNotAntialiasedElements & mAntialiasedElements) != 0) { + mAntialiasedElements |= ~mNotAntialiasedElements; + } } /*! 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 addGraph, QCPLegend::addItem */ void QCustomPlot::setAutoAddPlottableToLegend(bool on) { - mAutoAddPlottableToLegend = on; + mAutoAddPlottableToLegend = on; } /*! Sets the possible interactions of this QCustomPlot as an or-combination of \ref QCP::Interaction enums. There are the following types of interactions: - + Axis range manipulation is controlled via \ref QCP::iRangeDrag and \ref QCP::iRangeZoom. When the respective interaction is enabled, the user may drag axes ranges and zoom with the mouse wheel. For details how to control which axes the user may drag/zoom and in what orientations, see \ref QCPAxisRect::setRangeDrag, \ref QCPAxisRect::setRangeZoom, \ref QCPAxisRect::setRangeDragAxes, \ref QCPAxisRect::setRangeZoomAxes. - + 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 @@ -13825,78 +13936,79 @@ void QCustomPlot::setAutoAddPlottableToLegend(bool on) 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 out whether a specific item is selected, call QCPAbstractItem::selected(). To retrieve a list of all currently selected items, call \ref selectedItems. - + Axis selection is controlled with \ref QCP::iSelectAxes. If \ref QCP::iSelectAxes is set, the user may select parts of the axes by clicking on them. What parts exactly (e.g. Axis base line, tick labels, axis label) are selectable can be controlled via \ref QCPAxis::setSelectableParts for each axis. To retrieve a list of all axes that currently contain selected parts, call \ref selectedAxes. Which parts of an axis are selected, can be retrieved with QCPAxis::selectedParts(). - + Legend selection is controlled with \ref QCP::iSelectLegend. If this is set, the user may select the legend itself or individual items by clicking on them. What parts exactly are selectable can be controlled via \ref QCPLegend::setSelectableParts. To find out whether the legend or any of its child items are selected, check the value of QCPLegend::selectedParts. To find out which child items are selected, call \ref QCPLegend::selectedItems. - + All other selectable elements The selection of all other selectable objects (e.g. 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. - + If the selection state has changed by user interaction, the \ref selectionChangedByUser signal is emitted. Each selectable object additionally emits an individual selectionChanged signal whenever their selection state has changed, i.e. not only by user interaction. - + To allow multiple objects to be selected by holding the selection modifier (\ref setMultiSelectModifier), set the flag \ref QCP::iMultiSelect. - + \note In addition to the selection mechanism presented here, QCustomPlot always emits corresponding signals, when an object is clicked or double clicked. see \ref plottableClick and \ref plottableDoubleClick for example. - + \see setInteraction, setSelectionTolerance */ void QCustomPlot::setInteractions(const QCP::Interactions &interactions) { - mInteractions = interactions; + mInteractions = interactions; } /*! Sets the single \a interaction of this QCustomPlot to \a enabled. - + For details about the interaction system, see \ref setInteractions. - + \see setInteractions */ void QCustomPlot::setInteraction(const QCP::Interaction &interaction, bool enabled) { - if (!enabled && mInteractions.testFlag(interaction)) - mInteractions &= ~interaction; - else if (enabled && !mInteractions.testFlag(interaction)) - mInteractions |= interaction; + if (!enabled && mInteractions.testFlag(interaction)) { + mInteractions &= ~interaction; + } else if (enabled && !mInteractions.testFlag(interaction)) { + mInteractions |= interaction; + } } /*! Sets the tolerance that is used to decide whether a click selects an object (e.g. a plottable) or not. - + If the user clicks in the vicinity of the line of e.g. a QCPGraph, it's only regarded as a potential selection when the minimum distance between the click position and the graph line is smaller than \a pixels. Objects that are defined by an area (e.g. QCPBars) only react to clicks directly inside the area and ignore this selection tolerance. In other words, it only has meaning for parts of objects that are too thin to exactly hit with a click and thus need such a tolerance. - + \see setInteractions, QCPLayerable::selectTest */ void QCustomPlot::setSelectionTolerance(int pixels) { - mSelectionTolerance = pixels; + mSelectionTolerance = pixels; } /*! @@ -13905,54 +14017,56 @@ void QCustomPlot::setSelectionTolerance(int pixels) performance during dragging. Thus it creates a more responsive user experience. As soon as the user stops dragging, the last replot is done with normal antialiasing, to restore high image quality. - + \see setAntialiasedElements, setNotAntialiasedElements */ void QCustomPlot::setNoAntialiasingOnDrag(bool enabled) { - mNoAntialiasingOnDrag = enabled; + mNoAntialiasingOnDrag = enabled; } /*! Sets the plotting hints for this QCustomPlot instance as an \a or combination of QCP::PlottingHint. - + \see setPlottingHint */ void QCustomPlot::setPlottingHints(const QCP::PlottingHints &hints) { - mPlottingHints = hints; + mPlottingHints = hints; } /*! Sets the specified plotting \a hint to \a enabled. - + \see setPlottingHints */ void QCustomPlot::setPlottingHint(QCP::PlottingHint hint, bool enabled) { - QCP::PlottingHints newHints = mPlottingHints; - if (!enabled) - newHints &= ~hint; - else - newHints |= hint; - - if (newHints != mPlottingHints) - setPlottingHints(newHints); + QCP::PlottingHints newHints = mPlottingHints; + if (!enabled) { + newHints &= ~hint; + } else { + newHints |= hint; + } + + if (newHints != mPlottingHints) { + setPlottingHints(newHints); + } } /*! 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 (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. - + \see setInteractions */ void QCustomPlot::setMultiSelectModifier(Qt::KeyboardModifier modifier) { - mMultiSelectModifier = modifier; + mMultiSelectModifier = modifier; } /*! @@ -13962,73 +14076,75 @@ void QCustomPlot::setMultiSelectModifier(Qt::KeyboardModifier modifier) 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; + 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) { - 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*))); - } + 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 *))); + } + } } /*! \warning This is still an experimental feature and its performance depends on the system that it runs on. Having multiple QCustomPlot widgets in one application with enabled OpenGL rendering might cause context conflicts on some systems. - + This method allows to enable OpenGL plot rendering, for increased plotting performance of graphically demanding plots (thick lines, translucent fills, etc.). @@ -14062,39 +14178,37 @@ void QCustomPlot::setSelectionRect(QCPSelectionRect *selectionRect) */ void QCustomPlot::setOpenGl(bool enabled, int multisampling) { - mOpenGlMultisamples = qMax(0, 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; + 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(); } - } 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(); + // 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)"; + 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 } @@ -14116,9 +14230,10 @@ void QCustomPlot::setOpenGl(bool enabled, int multisampling) */ void QCustomPlot::setViewport(const QRect &rect) { - mViewport = rect; - if (mPlotLayout) - mPlotLayout->setOuterRect(mViewport); + mViewport = rect; + if (mPlotLayout) { + mPlotLayout->setOuterRect(mViewport); + } } /*! @@ -14134,18 +14249,18 @@ void QCustomPlot::setViewport(const QRect &rect) */ void QCustomPlot::setBufferDevicePixelRatio(double ratio) { - if (!qFuzzyCompare(ratio, mBufferDevicePixelRatio)) - { + if (!qFuzzyCompare(ratio, mBufferDevicePixelRatio)) { #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED - mBufferDevicePixelRatio = ratio; - foreach (QSharedPointer buffer, mPaintBuffers) - buffer->setDevicePixelRatio(mBufferDevicePixelRatio); - // Note: axis label cache has devicePixelRatio as part of cache hash, so no need to manually clear cache here + mBufferDevicePixelRatio = ratio; + foreach (QSharedPointer buffer, mPaintBuffers) { + buffer->setDevicePixelRatio(mBufferDevicePixelRatio); + } + // Note: axis label cache has devicePixelRatio as part of cache hash, so no need to manually clear cache here #else - qDebug() << Q_FUNC_INFO << "Device pixel ratios not supported for Qt versions before 5.4"; - mBufferDevicePixelRatio = 1.0; + qDebug() << Q_FUNC_INFO << "Device pixel ratios not supported for Qt versions before 5.4"; + mBufferDevicePixelRatio = 1.0; #endif - } + } } /*! @@ -14156,7 +14271,7 @@ void QCustomPlot::setBufferDevicePixelRatio(double ratio) enabled with \ref setBackgroundScaled and the scaling mode (whether and how the aspect ratio is preserved) can be set with \ref setBackgroundScaledMode. To set all these options in one call, consider using the overloaded version of this function. - + If a background brush was set with \ref setBackground(const QBrush &brush), the viewport will first be filled with that brush, before drawing the background pixmap. This can be useful for background pixmaps with translucent areas. @@ -14165,8 +14280,8 @@ void QCustomPlot::setBufferDevicePixelRatio(double ratio) */ void QCustomPlot::setBackground(const QPixmap &pm) { - mBackgroundPixmap = pm; - mScaledBackgroundPixmap = QPixmap(); + mBackgroundPixmap = pm; + mScaledBackgroundPixmap = QPixmap(); } /*! @@ -14176,7 +14291,7 @@ void QCustomPlot::setBackground(const QPixmap &pm) was set with \ref setBackground(const QPixmap &pm), this brush will be used to fill the viewport before the background pixmap is drawn. This can be useful for background pixmaps with translucent areas. - + Set \a brush to Qt::NoBrush or Qt::Transparent to leave background transparent. This can be useful for exporting to image formats which support transparency, e.g. \ref savePng. @@ -14184,11 +14299,11 @@ void QCustomPlot::setBackground(const QPixmap &pm) */ void QCustomPlot::setBackground(const QBrush &brush) { - mBackgroundBrush = brush; + mBackgroundBrush = brush; } /*! \overload - + Allows setting the background pixmap of the viewport, whether it shall be scaled and how it shall be scaled in one call. @@ -14196,172 +14311,170 @@ void QCustomPlot::setBackground(const QBrush &brush) */ void QCustomPlot::setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode) { - mBackgroundPixmap = pm; - mScaledBackgroundPixmap = QPixmap(); - mBackgroundScaled = scaled; - mBackgroundScaledMode = mode; + mBackgroundPixmap = pm; + mScaledBackgroundPixmap = QPixmap(); + mBackgroundScaled = scaled; + mBackgroundScaledMode = mode; } /*! Sets whether the viewport background pixmap shall be scaled to fit the viewport. If \a scaled is set to true, control whether and how the aspect ratio of the original pixmap is preserved with \ref setBackgroundScaledMode. - + Note that the scaled version of the original pixmap is buffered, so there is no performance penalty on replots. (Except when the viewport dimensions are changed continuously.) - + \see setBackground, setBackgroundScaledMode */ void QCustomPlot::setBackgroundScaled(bool scaled) { - mBackgroundScaled = scaled; + mBackgroundScaled = scaled; } /*! If scaling of the viewport background pixmap is enabled (\ref setBackgroundScaled), use this function to define whether and how the aspect ratio of the original pixmap is preserved. - + \see setBackground, setBackgroundScaled */ void QCustomPlot::setBackgroundScaledMode(Qt::AspectRatioMode mode) { - mBackgroundScaledMode = mode; + mBackgroundScaledMode = mode; } /*! Returns the plottable with \a index. If the index is invalid, returns \c nullptr. - + There is an overloaded version of this function with no parameter which returns the last added plottable, see QCustomPlot::plottable() - + \see plottableCount */ QCPAbstractPlottable *QCustomPlot::plottable(int index) { - if (index >= 0 && index < mPlottables.size()) - { - return mPlottables.at(index); - } else - { - qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; - return nullptr; - } + if (index >= 0 && index < mPlottables.size()) { + return mPlottables.at(index); + } else { + qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; + return nullptr; + } } /*! \overload - + Returns the last plottable that was added to the plot. If there are no plottables in the plot, returns \c nullptr. - + \see plottableCount */ QCPAbstractPlottable *QCustomPlot::plottable() { - if (!mPlottables.isEmpty()) - { - return mPlottables.last(); - } else - return nullptr; + if (!mPlottables.isEmpty()) { + return mPlottables.last(); + } else { + return nullptr; + } } /*! 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 clearPlottables */ bool QCustomPlot::removePlottable(QCPAbstractPlottable *plottable) { - if (!mPlottables.contains(plottable)) - { - qDebug() << Q_FUNC_INFO << "plottable not in list:" << reinterpret_cast(plottable); - return false; - } - - // remove plottable from legend: - plottable->removeFromLegend(); - // special handling for QCPGraphs to maintain the simple graph interface: - if (QCPGraph *graph = qobject_cast(plottable)) - mGraphs.removeOne(graph); - // remove plottable: - delete plottable; - mPlottables.removeOne(plottable); - return true; + if (!mPlottables.contains(plottable)) { + qDebug() << Q_FUNC_INFO << "plottable not in list:" << reinterpret_cast(plottable); + return false; + } + + // remove plottable from legend: + plottable->removeFromLegend(); + // special handling for QCPGraphs to maintain the simple graph interface: + if (QCPGraph *graph = qobject_cast(plottable)) { + mGraphs.removeOne(graph); + } + // remove plottable: + delete plottable; + mPlottables.removeOne(plottable); + return true; } /*! \overload - + Removes and deletes the plottable by its \a index. */ bool QCustomPlot::removePlottable(int index) { - if (index >= 0 && index < mPlottables.size()) - return removePlottable(mPlottables[index]); - else - { - qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; - return false; - } + if (index >= 0 && index < mPlottables.size()) { + return removePlottable(mPlottables[index]); + } else { + qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; + return false; + } } /*! 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. - + \see removePlottable */ int QCustomPlot::clearPlottables() { - int c = mPlottables.size(); - for (int i=c-1; i >= 0; --i) - removePlottable(mPlottables[i]); - return c; + int c = mPlottables.size(); + for (int i = c - 1; i >= 0; --i) { + removePlottable(mPlottables[i]); + } + return c; } /*! Returns the number of currently existing plottables in the plot - + \see plottable */ int QCustomPlot::plottableCount() const { - return mPlottables.size(); + return mPlottables.size(); } /*! Returns a list of the selected plottables. If no plottables are currently selected, the list is empty. - + There is a convenience function if you're only interested in selected graphs, see \ref selectedGraphs. - + \see setInteractions, QCPAbstractPlottable::setSelectable, QCPAbstractPlottable::setSelection */ -QList QCustomPlot::selectedPlottables() const +QList QCustomPlot::selectedPlottables() const { - QList result; - foreach (QCPAbstractPlottable *plottable, mPlottables) - { - if (plottable->selected()) - result.append(plottable); - } - return result; + QList result; + foreach (QCPAbstractPlottable *plottable, mPlottables) { + if (plottable->selected()) { + result.append(plottable); + } + } + return result; } /*! Returns any plottable at the pixel position \a pos. Since it can capture all plottables, the return type is the abstract base class of all plottables, QCPAbstractPlottable. - + For details, and if you wish to specify a certain plottable type (e.g. QCPGraph), see the template method plottableAt() - + \see plottableAt(), itemAt, layoutElementAt */ QCPAbstractPlottable *QCustomPlot::plottableAt(const QPointF &pos, bool onlySelectable, int *dataIndex) const { - return plottableAt(pos, onlySelectable, dataIndex); + return plottableAt(pos, onlySelectable, dataIndex); } /*! @@ -14369,75 +14482,75 @@ QCPAbstractPlottable *QCustomPlot::plottableAt(const QPointF &pos, bool onlySele */ bool QCustomPlot::hasPlottable(QCPAbstractPlottable *plottable) const { - return mPlottables.contains(plottable); + return mPlottables.contains(plottable); } /*! Returns the graph with \a index. If the index is invalid, returns \c nullptr. - + There is an overloaded version of this function with no parameter which returns the last created graph, see QCustomPlot::graph() - + \see graphCount, addGraph */ QCPGraph *QCustomPlot::graph(int index) const { - if (index >= 0 && index < mGraphs.size()) - { - return mGraphs.at(index); - } else - { - qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; - return nullptr; - } + if (index >= 0 && index < mGraphs.size()) { + return mGraphs.at(index); + } else { + qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; + return nullptr; + } } /*! \overload - + Returns the last graph, that was created with \ref addGraph. If there are no graphs in the plot, returns \c nullptr. - + \see graphCount, addGraph */ QCPGraph *QCustomPlot::graph() const { - if (!mGraphs.isEmpty()) - { - return mGraphs.last(); - } else - return nullptr; + if (!mGraphs.isEmpty()) { + return mGraphs.last(); + } else { + return nullptr; + } } /*! Creates a new graph inside the plot. If \a keyAxis and \a valueAxis are left unspecified (0), the bottom (xAxis) is used as key and the left (yAxis) is used as value axis. If specified, \a keyAxis and \a valueAxis must reside in this QCustomPlot. - + \a keyAxis will be used as key axis (typically "x") and \a valueAxis as value axis (typically "y") for the graph. - + Returns a pointer to the newly created graph, or \c nullptr if adding the graph failed. - + \see graph, graphCount, removeGraph, clearGraphs */ QCPGraph *QCustomPlot::addGraph(QCPAxis *keyAxis, QCPAxis *valueAxis) { - if (!keyAxis) keyAxis = xAxis; - if (!valueAxis) valueAxis = yAxis; - if (!keyAxis || !valueAxis) - { - qDebug() << Q_FUNC_INFO << "can't use default QCustomPlot xAxis or yAxis, because at least one is invalid (has been deleted)"; - return nullptr; - } - if (keyAxis->parentPlot() != this || valueAxis->parentPlot() != this) - { - qDebug() << Q_FUNC_INFO << "passed keyAxis or valueAxis doesn't have this QCustomPlot as parent"; - return nullptr; - } - - QCPGraph *newGraph = new QCPGraph(keyAxis, valueAxis); - newGraph->setName(QLatin1String("Graph ")+QString::number(mGraphs.size())); - return newGraph; + if (!keyAxis) { + keyAxis = xAxis; + } + if (!valueAxis) { + valueAxis = yAxis; + } + if (!keyAxis || !valueAxis) { + qDebug() << Q_FUNC_INFO << "can't use default QCustomPlot xAxis or yAxis, because at least one is invalid (has been deleted)"; + return nullptr; + } + if (keyAxis->parentPlot() != this || valueAxis->parentPlot() != this) { + qDebug() << Q_FUNC_INFO << "passed keyAxis or valueAxis doesn't have this QCustomPlot as parent"; + return nullptr; + } + + QCPGraph *newGraph = new QCPGraph(keyAxis, valueAxis); + newGraph->setName(QLatin1String("Graph ") + QString::number(mGraphs.size())); + return newGraph; } /*! @@ -14445,26 +14558,27 @@ QCPGraph *QCustomPlot::addGraph(QCPAxis *keyAxis, QCPAxis *valueAxis) 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 \c nullptr (no channel fill). - + Returns true on success. - + \see clearGraphs */ bool QCustomPlot::removeGraph(QCPGraph *graph) { - return removePlottable(graph); + return removePlottable(graph); } /*! \overload - + Removes and deletes the graph by its \a index. */ bool QCustomPlot::removeGraph(int index) { - if (index >= 0 && index < mGraphs.size()) - return removeGraph(mGraphs[index]); - else - return false; + if (index >= 0 && index < mGraphs.size()) { + return removeGraph(mGraphs[index]); + } else { + return false; + } } /*! @@ -14472,217 +14586,212 @@ bool QCustomPlot::removeGraph(int index) from the default legend (QCustomPlot::legend). Returns the number of graphs removed. - + \see removeGraph */ int QCustomPlot::clearGraphs() { - int c = mGraphs.size(); - for (int i=c-1; i >= 0; --i) - removeGraph(mGraphs[i]); - return c; + int c = mGraphs.size(); + for (int i = c - 1; i >= 0; --i) { + removeGraph(mGraphs[i]); + } + return c; } /*! Returns the number of currently existing graphs in the plot - + \see graph, addGraph */ int QCustomPlot::graphCount() const { - return mGraphs.size(); + return mGraphs.size(); } /*! Returns a list of the selected graphs. If no graphs are currently selected, the list is empty. - + 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::setSelection */ -QList QCustomPlot::selectedGraphs() const +QList QCustomPlot::selectedGraphs() const { - QList result; - foreach (QCPGraph *graph, mGraphs) - { - if (graph->selected()) - result.append(graph); - } - return result; + QList result; + foreach (QCPGraph *graph, mGraphs) { + if (graph->selected()) { + result.append(graph); + } + } + return result; } /*! Returns the item with \a index. If the index is invalid, returns \c nullptr. - + There is an overloaded version of this function with no parameter which returns the last added item, see QCustomPlot::item() - + \see itemCount */ QCPAbstractItem *QCustomPlot::item(int index) const { - if (index >= 0 && index < mItems.size()) - { - return mItems.at(index); - } else - { - qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; - return nullptr; - } + if (index >= 0 && index < mItems.size()) { + return mItems.at(index); + } else { + qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; + return nullptr; + } } /*! \overload - + Returns the last item that was added to this plot. If there are no items in the plot, returns \c nullptr. - + \see itemCount */ QCPAbstractItem *QCustomPlot::item() const { - if (!mItems.isEmpty()) - { - return mItems.last(); - } else - return nullptr; + if (!mItems.isEmpty()) { + return mItems.last(); + } else { + return nullptr; + } } /*! Removes the specified item from the plot and deletes it. - + Returns true on success. - + \see clearItems */ bool QCustomPlot::removeItem(QCPAbstractItem *item) { - if (mItems.contains(item)) - { - delete item; - mItems.removeOne(item); - return true; - } else - { - qDebug() << Q_FUNC_INFO << "item not in list:" << reinterpret_cast(item); - return false; - } + if (mItems.contains(item)) { + delete item; + mItems.removeOne(item); + return true; + } else { + qDebug() << Q_FUNC_INFO << "item not in list:" << reinterpret_cast(item); + return false; + } } /*! \overload - + Removes and deletes the item by its \a index. */ bool QCustomPlot::removeItem(int index) { - if (index >= 0 && index < mItems.size()) - return removeItem(mItems[index]); - else - { - qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; - return false; - } + if (index >= 0 && index < mItems.size()) { + return removeItem(mItems[index]); + } else { + qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; + return false; + } } /*! Removes all items from the plot and deletes them. - + Returns the number of items removed. - + \see removeItem */ int QCustomPlot::clearItems() { - int c = mItems.size(); - for (int i=c-1; i >= 0; --i) - removeItem(mItems[i]); - return c; + int c = mItems.size(); + for (int i = c - 1; i >= 0; --i) { + removeItem(mItems[i]); + } + return c; } /*! Returns the number of currently existing items in the plot - + \see item */ int QCustomPlot::itemCount() const { - return mItems.size(); + return mItems.size(); } /*! Returns a list of the selected items. If no items are currently selected, the list is empty. - + \see setInteractions, QCPAbstractItem::setSelectable, QCPAbstractItem::setSelected */ -QList QCustomPlot::selectedItems() const +QList QCustomPlot::selectedItems() const { - QList result; - foreach (QCPAbstractItem *item, mItems) - { - if (item->selected()) - result.append(item); - } - return result; + QList result; + foreach (QCPAbstractItem *item, mItems) { + if (item->selected()) { + result.append(item); + } + } + return result; } /*! Returns the item at the pixel position \a pos. Since it can capture all items, the return type is the abstract base class of all items, QCPAbstractItem. - + For details, and if you wish to specify a certain item type (e.g. QCPItemLine), see the template method itemAt() - + \see itemAt(), plottableAt, layoutElementAt */ QCPAbstractItem *QCustomPlot::itemAt(const QPointF &pos, bool onlySelectable) const { - return itemAt(pos, onlySelectable); + return itemAt(pos, onlySelectable); } /*! Returns whether this QCustomPlot contains the \a item. - + \see item */ bool QCustomPlot::hasItem(QCPAbstractItem *item) const { - return mItems.contains(item); + return mItems.contains(item); } /*! Returns the layer with the specified \a name. If there is no layer with the specified name, \c nullptr is returned. - + Layer names are case-sensitive. - + \see addLayer, moveLayer, removeLayer */ QCPLayer *QCustomPlot::layer(const QString &name) const { - foreach (QCPLayer *layer, mLayers) - { - if (layer->name() == name) - return layer; - } - return nullptr; + foreach (QCPLayer *layer, mLayers) { + if (layer->name() == name) { + return layer; + } + } + return nullptr; } /*! \overload - + Returns the layer by \a index. If the index is invalid, \c nullptr is returned. - + \see addLayer, moveLayer, removeLayer */ QCPLayer *QCustomPlot::layer(int index) const { - if (index >= 0 && index < mLayers.size()) - { - return mLayers.at(index); - } else - { - qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; - return nullptr; - } + if (index >= 0 && index < mLayers.size()) { + return mLayers.at(index); + } else { + qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; + return nullptr; + } } /*! @@ -14690,292 +14799,285 @@ QCPLayer *QCustomPlot::layer(int index) const */ QCPLayer *QCustomPlot::currentLayer() const { - return mCurrentLayer; + return mCurrentLayer; } /*! Sets the layer with the specified \a name to be the current layer. All layerables (\ref QCPLayerable), e.g. plottables and items, are created on the current layer. - + Returns true on success, i.e. if there is a layer with the specified \a name in the QCustomPlot. - + Layer names are case-sensitive. - + \see addLayer, moveLayer, removeLayer, QCPLayerable::setLayer */ bool QCustomPlot::setCurrentLayer(const QString &name) { - if (QCPLayer *newCurrentLayer = layer(name)) - { - return setCurrentLayer(newCurrentLayer); - } else - { - qDebug() << Q_FUNC_INFO << "layer with name doesn't exist:" << name; - return false; - } + if (QCPLayer *newCurrentLayer = layer(name)) { + return setCurrentLayer(newCurrentLayer); + } else { + qDebug() << Q_FUNC_INFO << "layer with name doesn't exist:" << name; + return false; + } } /*! \overload - + Sets the provided \a layer to be the current layer. - + Returns true on success, i.e. when \a layer is a valid layer in the QCustomPlot. - + \see addLayer, moveLayer, removeLayer */ bool QCustomPlot::setCurrentLayer(QCPLayer *layer) { - if (!mLayers.contains(layer)) - { - qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast(layer); - return false; - } - - mCurrentLayer = layer; - return true; + if (!mLayers.contains(layer)) { + qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast(layer); + return false; + } + + mCurrentLayer = layer; + return true; } /*! Returns the number of currently existing layers in the plot - + \see layer, addLayer */ int QCustomPlot::layerCount() const { - return mLayers.size(); + return mLayers.size(); } /*! Adds a new layer to this QCustomPlot instance. The new layer will have the name \a name, which must be unique. Depending on \a insertMode, it is positioned either below or above \a otherLayer. - + Returns true on success, i.e. if there is no other layer named \a name and \a otherLayer is a valid layer inside this QCustomPlot. - + If \a otherLayer is 0, the highest layer in the QCustomPlot will be used. - + For an explanation of what layers are in QCustomPlot, see the documentation of \ref QCPLayer. - + \see layer, moveLayer, removeLayer */ bool QCustomPlot::addLayer(const QString &name, QCPLayer *otherLayer, QCustomPlot::LayerInsertMode insertMode) { - if (!otherLayer) - otherLayer = mLayers.last(); - if (!mLayers.contains(otherLayer)) - { - qDebug() << Q_FUNC_INFO << "otherLayer not a layer of this QCustomPlot:" << reinterpret_cast(otherLayer); - return false; - } - if (layer(name)) - { - qDebug() << Q_FUNC_INFO << "A layer exists already with the name" << name; - return false; - } - - 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; + if (!otherLayer) { + otherLayer = mLayers.last(); + } + if (!mLayers.contains(otherLayer)) { + qDebug() << Q_FUNC_INFO << "otherLayer not a layer of this QCustomPlot:" << reinterpret_cast(otherLayer); + return false; + } + if (layer(name)) { + qDebug() << Q_FUNC_INFO << "A layer exists already with the name" << name; + return false; + } + + 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; } /*! Removes the specified \a layer and returns true on success. - + All layerables (e.g. plottables and items) on the removed layer will be moved to the layer below \a layer. If \a layer is the bottom layer, the layerables are moved to the layer above. In both cases, the total rendering order of all layerables in the QCustomPlot is preserved. - + If \a layer is the current layer (\ref setCurrentLayer), the layer below (or above, if bottom layer) becomes the new current layer. - + It is not possible to remove the last layer of the plot. - + \see layer, addLayer, moveLayer */ bool QCustomPlot::removeLayer(QCPLayer *layer) { - if (!mLayers.contains(layer)) - { - qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast(layer); - return false; - } - if (mLayers.size() < 2) - { - qDebug() << Q_FUNC_INFO << "can't remove last layer"; - return false; - } - - // append all children of this layer to layer below (if this is lowest layer, prepend to layer above) - int removedIndex = layer->index(); - bool isFirstLayer = removedIndex==0; - QCPLayer *targetLayer = isFirstLayer ? mLayers.at(removedIndex+1) : mLayers.at(removedIndex-1); - QList children = layer->children(); - if (isFirstLayer) // prepend in reverse order (such that relative order stays the same) - std::reverse(children.begin(), children.end()); - foreach (QCPLayerable *child, children) - child->moveToLayer(targetLayer, isFirstLayer); // prepend if isFirstLayer, otherwise append - - // 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 (QSharedPointer pb = layer->mPaintBuffer.toStrongRef()) - pb->setInvalidated(); - - // remove layer: - delete layer; - mLayers.removeOne(layer); - updateLayerIndices(); - return true; + if (!mLayers.contains(layer)) { + qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast(layer); + return false; + } + if (mLayers.size() < 2) { + qDebug() << Q_FUNC_INFO << "can't remove last layer"; + return false; + } + + // append all children of this layer to layer below (if this is lowest layer, prepend to layer above) + int removedIndex = layer->index(); + bool isFirstLayer = removedIndex == 0; + QCPLayer *targetLayer = isFirstLayer ? mLayers.at(removedIndex + 1) : mLayers.at(removedIndex - 1); + QList children = layer->children(); + if (isFirstLayer) { // prepend in reverse order (such that relative order stays the same) + std::reverse(children.begin(), children.end()); + } + foreach (QCPLayerable *child, children) { + child->moveToLayer(targetLayer, isFirstLayer); // prepend if isFirstLayer, otherwise append + } + + // 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 (QSharedPointer pb = layer->mPaintBuffer.toStrongRef()) { + pb->setInvalidated(); + } + + // remove layer: + delete layer; + mLayers.removeOne(layer); + updateLayerIndices(); + return true; } /*! Moves the specified \a layer either above or below \a otherLayer. Whether it's placed above or below is controlled with \a insertMode. - + Returns true on success, i.e. when both \a layer and \a otherLayer are valid layers in the QCustomPlot. - + \see layer, addLayer, moveLayer */ bool QCustomPlot::moveLayer(QCPLayer *layer, QCPLayer *otherLayer, QCustomPlot::LayerInsertMode insertMode) { - if (!mLayers.contains(layer)) - { - qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast(layer); - return false; - } - if (!mLayers.contains(otherLayer)) - { - qDebug() << Q_FUNC_INFO << "otherLayer not a layer of this QCustomPlot:" << reinterpret_cast(otherLayer); - return false; - } - - 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 (QSharedPointer pb = layer->mPaintBuffer.toStrongRef()) - pb->setInvalidated(); - if (QSharedPointer pb = otherLayer->mPaintBuffer.toStrongRef()) - pb->setInvalidated(); - - updateLayerIndices(); - return true; + if (!mLayers.contains(layer)) { + qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast(layer); + return false; + } + if (!mLayers.contains(otherLayer)) { + qDebug() << Q_FUNC_INFO << "otherLayer not a layer of this QCustomPlot:" << reinterpret_cast(otherLayer); + return false; + } + + 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 (QSharedPointer pb = layer->mPaintBuffer.toStrongRef()) { + pb->setInvalidated(); + } + if (QSharedPointer pb = otherLayer->mPaintBuffer.toStrongRef()) { + pb->setInvalidated(); + } + + updateLayerIndices(); + return true; } /*! Returns the number of axis rects in the plot. - + All axis rects can be accessed via QCustomPlot::axisRect(). - + Initially, only one axis rect exists in the plot. - + \see axisRect, axisRects */ int QCustomPlot::axisRectCount() const { - return axisRects().size(); + return axisRects().size(); } /*! Returns the axis rect with \a index. - + Initially, only one axis rect (with index 0) exists in the plot. If multiple axis rects were added, all of them may be accessed with this function in a linear fashion (even when they are nested in a layout hierarchy or inside other axis rects via QCPAxisRect::insetLayout). - + The order of the axis rects is given by the fill order of the \ref QCPLayout that is holding them. For example, if the axis rects are in the top level grid layout (accessible via \ref QCustomPlot::plotLayout), they are ordered from left to right, top to bottom, if the layout's default \ref QCPLayoutGrid::setFillOrder "setFillOrder" of \ref QCPLayoutGrid::foColumnsFirst "foColumnsFirst" wasn't changed. - + If you want to access axis rects by their row and column index, use the layout interface. For example, use \ref QCPLayoutGrid::element of the top level grid layout, and \c qobject_cast the returned layout element to \ref QCPAxisRect. (See also \ref thelayoutsystem.) - + \see axisRectCount, axisRects, QCPLayoutGrid::setFillOrder */ QCPAxisRect *QCustomPlot::axisRect(int index) const { - const QList rectList = axisRects(); - if (index >= 0 && index < rectList.size()) - { - return rectList.at(index); - } else - { - qDebug() << Q_FUNC_INFO << "invalid axis rect index" << index; - return nullptr; - } + const QList rectList = axisRects(); + if (index >= 0 && index < rectList.size()) { + return rectList.at(index); + } else { + qDebug() << Q_FUNC_INFO << "invalid axis rect index" << index; + return nullptr; + } } /*! Returns all axis rects in the plot. - + The order of the axis rects is given by the fill order of the \ref QCPLayout that is holding them. For example, if the axis rects are in the top level grid layout (accessible via \ref QCustomPlot::plotLayout), they are ordered from left to right, top to bottom, if the layout's default \ref QCPLayoutGrid::setFillOrder "setFillOrder" of \ref QCPLayoutGrid::foColumnsFirst "foColumnsFirst" wasn't changed. - + \see axisRectCount, axisRect, QCPLayoutGrid::setFillOrder */ -QList QCustomPlot::axisRects() const +QList QCustomPlot::axisRects() const { - QList result; - QStack elementStack; - if (mPlotLayout) - elementStack.push(mPlotLayout); - - while (!elementStack.isEmpty()) - { - foreach (QCPLayoutElement *element, elementStack.pop()->elements(false)) - { - if (element) - { - elementStack.push(element); - if (QCPAxisRect *ar = qobject_cast(element)) - result.append(ar); - } + QList result; + QStack elementStack; + if (mPlotLayout) { + elementStack.push(mPlotLayout); } - } - - return result; + + while (!elementStack.isEmpty()) { + foreach (QCPLayoutElement *element, elementStack.pop()->elements(false)) { + if (element) { + elementStack.push(element); + if (QCPAxisRect *ar = qobject_cast(element)) { + result.append(ar); + } + } + } + } + + return result; } /*! Returns the layout element at pixel position \a pos. If there is no element at that position, returns \c nullptr. - + Only visible elements are used. If \ref QCPLayoutElement::setVisible on the element itself or on any of its parent elements is set to false, it will not be considered. - + \see itemAt, plottableAt */ QCPLayoutElement *QCustomPlot::layoutElementAt(const QPointF &pos) const { - 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; - break; - } + 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; + break; + } + } } - } - return currentElement; + return currentElement; } /*! @@ -14990,99 +15092,96 @@ QCPLayoutElement *QCustomPlot::layoutElementAt(const QPointF &pos) const */ QCPAxisRect *QCustomPlot::axisRectAt(const QPointF &pos) const { - QCPAxisRect *result = nullptr; - 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; - } + QCPAxisRect *result = nullptr; + 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; + return result; } /*! Returns the axes that currently have selected parts, i.e. whose selection state is not \ref QCPAxis::spNone. - + \see selectedPlottables, selectedLegends, setInteractions, QCPAxis::setSelectedParts, QCPAxis::setSelectableParts */ -QList QCustomPlot::selectedAxes() const +QList QCustomPlot::selectedAxes() const { - QList result, allAxes; - foreach (QCPAxisRect *rect, axisRects()) - allAxes << rect->axes(); - - foreach (QCPAxis *axis, allAxes) - { - if (axis->selectedParts() != QCPAxis::spNone) - result.append(axis); - } - - return result; + QList result, allAxes; + foreach (QCPAxisRect *rect, axisRects()) { + allAxes << rect->axes(); + } + + foreach (QCPAxis *axis, allAxes) { + if (axis->selectedParts() != QCPAxis::spNone) { + result.append(axis); + } + } + + return result; } /*! Returns the legends that currently have selected parts, i.e. whose selection state is not \ref QCPLegend::spNone. - + \see selectedPlottables, selectedAxes, setInteractions, QCPLegend::setSelectedParts, QCPLegend::setSelectableParts, QCPLegend::selectedItems */ -QList QCustomPlot::selectedLegends() const +QList QCustomPlot::selectedLegends() const { - QList result; - - QStack elementStack; - if (mPlotLayout) - elementStack.push(mPlotLayout); - - while (!elementStack.isEmpty()) - { - foreach (QCPLayoutElement *subElement, elementStack.pop()->elements(false)) - { - if (subElement) - { - elementStack.push(subElement); - if (QCPLegend *leg = qobject_cast(subElement)) - { - if (leg->selectedParts() != QCPLegend::spNone) - result.append(leg); - } - } + QList result; + + QStack elementStack; + if (mPlotLayout) { + elementStack.push(mPlotLayout); } - } - - return result; + + while (!elementStack.isEmpty()) { + foreach (QCPLayoutElement *subElement, elementStack.pop()->elements(false)) { + if (subElement) { + elementStack.push(subElement); + if (QCPLegend *leg = qobject_cast(subElement)) { + if (leg->selectedParts() != QCPLegend::spNone) { + result.append(leg); + } + } + } + } + } + + return result; } /*! Deselects all layerables (plottables, items, axes, legends,...) of the QCustomPlot. - + Since calling this function is not a user interaction, this does not emit the \ref selectionChangedByUser signal. The individual selectionChanged signals are emitted though, if the objects were previously selected. - + \see setInteractions, selectedPlottables, selectedItems, selectedAxes, selectedLegends */ void QCustomPlot::deselectAll() { - foreach (QCPLayer *layer, mLayers) - { - foreach (QCPLayerable *layerable, layer->children()) - layerable->deselectEvent(nullptr); - } + foreach (QCPLayer *layer, mLayers) { + foreach (QCPLayerable *layerable, layer->children()) { + layerable->deselectEvent(nullptr); + } + } } /*! @@ -15109,89 +15208,94 @@ void QCustomPlot::deselectAll() 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. - + \see replotTime */ void QCustomPlot::replot(QCustomPlot::RefreshPriority refreshPriority) { - if (refreshPriority == QCustomPlot::rpQueuedReplot) - { - if (!mReplotQueued) - { - mReplotQueued = true; - QTimer::singleShot(0, this, SLOT(replot())); + if (refreshPriority == QCustomPlot::rpQueuedReplot) { + if (!mReplotQueued) { + mReplotQueued = true; + QTimer::singleShot(0, this, SLOT(replot())); + } + return; } - return; - } - - if (mReplotting) // incase signals loop back to replot slot - return; - mReplotting = true; - mReplotQueued = false; - emit beforeReplot(); - + + if (mReplotting) { // incase signals loop back to replot slot + return; + } + mReplotting = true; + mReplotQueued = false; + emit beforeReplot(); + # if QT_VERSION < QT_VERSION_CHECK(4, 8, 0) - QTime replotTimer; - replotTimer.start(); + QTime replotTimer; + replotTimer.start(); # else - QElapsedTimer replotTimer; - replotTimer.start(); + QElapsedTimer replotTimer; + replotTimer.start(); # endif - - updateLayout(); - // draw all layered objects (grid, axes, plottables, items, legend,...) into their buffers: - setupPaintBuffers(); - foreach (QCPLayer *layer, mLayers) - layer->drawToPaintBuffer(); - foreach (QSharedPointer buffer, mPaintBuffers) - buffer->setInvalidated(false); - - if ((refreshPriority == rpRefreshHint && mPlottingHints.testFlag(QCP::phImmediateRefresh)) || refreshPriority==rpImmediateRefresh) - repaint(); - else - update(); - + + updateLayout(); + // draw all layered objects (grid, axes, plottables, items, legend,...) into their buffers: + setupPaintBuffers(); + foreach (QCPLayer *layer, mLayers) { + layer->drawToPaintBuffer(); + } + foreach (QSharedPointer buffer, mPaintBuffers) { + buffer->setInvalidated(false); + } + + if ((refreshPriority == rpRefreshHint && mPlottingHints.testFlag(QCP::phImmediateRefresh)) || refreshPriority == rpImmediateRefresh) { + repaint(); + } else { + update(); + } + # if QT_VERSION < QT_VERSION_CHECK(4, 8, 0) - mReplotTime = replotTimer.elapsed(); + mReplotTime = replotTimer.elapsed(); # else - mReplotTime = replotTimer.nsecsElapsed()*1e-6; + mReplotTime = replotTimer.nsecsElapsed() * 1e-6; # endif - if (!qFuzzyIsNull(mReplotTimeAverage)) - mReplotTimeAverage = mReplotTimeAverage*0.9 + mReplotTime*0.1; // exponential moving average with a time constant of 10 last replots - else - mReplotTimeAverage = mReplotTime; // no previous replots to average with, so initialize with replot time - - emit afterReplot(); - mReplotting = false; + if (!qFuzzyIsNull(mReplotTimeAverage)) { + mReplotTimeAverage = mReplotTimeAverage * 0.9 + mReplotTime * 0.1; // exponential moving average with a time constant of 10 last replots + } else { + mReplotTimeAverage = mReplotTime; // no previous replots to average with, so initialize with replot time + } + + emit afterReplot(); + mReplotting = false; } /*! Returns the time in milliseconds that the last replot took. If \a average is set to true, an exponential moving average over the last couple of replots is returned. - + \see replot */ double QCustomPlot::replotTime(bool average) const { - return average ? mReplotTimeAverage : mReplotTime; + return average ? mReplotTimeAverage : mReplotTime; } /*! Rescales the axes such that all plottables (like graphs) in the plot are fully visible. - + if \a onlyVisiblePlottables is set to true, only the plottables that have their visibility set to true (QCPLayerable::setVisible), will be used to rescale the axes. - + \see QCPAbstractPlottable::rescaleAxes, QCPAxis::rescale */ void QCustomPlot::rescaleAxes(bool onlyVisiblePlottables) { - QList allAxes; - foreach (QCPAxisRect *rect, axisRects()) - allAxes << rect->axes(); - - foreach (QCPAxis *axis, allAxes) - axis->rescale(onlyVisiblePlottables); + QList allAxes; + foreach (QCPAxisRect *rect, axisRects()) { + allAxes << rect->axes(); + } + + foreach (QCPAxis *axis, allAxes) { + axis->rescale(onlyVisiblePlottables); + } } /*! @@ -15233,65 +15337,63 @@ void QCustomPlot::rescaleAxes(bool onlyVisiblePlottables) */ bool QCustomPlot::savePdf(const QString &fileName, int width, int height, QCP::ExportPen exportPen, const QString &pdfCreator, const QString &pdfTitle) { - bool success = false; + bool success = false; #ifdef QT_NO_PRINTER - Q_UNUSED(fileName) - Q_UNUSED(exportPen) - Q_UNUSED(width) - Q_UNUSED(height) - Q_UNUSED(pdfCreator) - Q_UNUSED(pdfTitle) - qDebug() << Q_FUNC_INFO << "Qt was built without printer support (QT_NO_PRINTER). PDF not created."; + Q_UNUSED(fileName) + Q_UNUSED(exportPen) + Q_UNUSED(width) + Q_UNUSED(height) + Q_UNUSED(pdfCreator) + Q_UNUSED(pdfTitle) + qDebug() << Q_FUNC_INFO << "Qt was built without printer support (QT_NO_PRINTER). PDF not created."; #else - int newWidth, newHeight; - if (width == 0 || height == 0) - { - newWidth = this->width(); - newHeight = this->height(); - } else - { - newWidth = width; - newHeight = height; - } - - QPrinter printer(QPrinter::ScreenResolution); - printer.setOutputFileName(fileName); - printer.setOutputFormat(QPrinter::PdfFormat); - printer.setColorMode(QPrinter::Color); - printer.printEngine()->setProperty(QPrintEngine::PPK_Creator, pdfCreator); - printer.printEngine()->setProperty(QPrintEngine::PPK_DocumentName, pdfTitle); - QRect oldViewport = viewport(); - setViewport(QRect(0, 0, newWidth, newHeight)); + int newWidth, newHeight; + if (width == 0 || height == 0) { + newWidth = this->width(); + newHeight = this->height(); + } else { + newWidth = width; + newHeight = height; + } + + QPrinter printer(QPrinter::ScreenResolution); + printer.setOutputFileName(fileName); + printer.setOutputFormat(QPrinter::PdfFormat); + printer.setColorMode(QPrinter::Color); + printer.printEngine()->setProperty(QPrintEngine::PPK_Creator, pdfCreator); + printer.printEngine()->setProperty(QPrintEngine::PPK_DocumentName, pdfTitle); + QRect oldViewport = viewport(); + setViewport(QRect(0, 0, newWidth, newHeight)); #if QT_VERSION < QT_VERSION_CHECK(5, 3, 0) - printer.setFullPage(true); - printer.setPaperSize(viewport().size(), QPrinter::DevicePixel); + printer.setFullPage(true); + printer.setPaperSize(viewport().size(), QPrinter::DevicePixel); #else - QPageLayout pageLayout; - pageLayout.setMode(QPageLayout::FullPageMode); - pageLayout.setOrientation(QPageLayout::Portrait); - pageLayout.setMargins(QMarginsF(0, 0, 0, 0)); - pageLayout.setPageSize(QPageSize(viewport().size(), QPageSize::Point, QString(), QPageSize::ExactMatch)); - printer.setPageLayout(pageLayout); + QPageLayout pageLayout; + pageLayout.setMode(QPageLayout::FullPageMode); + pageLayout.setOrientation(QPageLayout::Portrait); + pageLayout.setMargins(QMarginsF(0, 0, 0, 0)); + pageLayout.setPageSize(QPageSize(viewport().size(), QPageSize::Point, QString(), QPageSize::ExactMatch)); + printer.setPageLayout(pageLayout); #endif - QCPPainter printpainter; - if (printpainter.begin(&printer)) - { - printpainter.setMode(QCPPainter::pmVectorized); - printpainter.setMode(QCPPainter::pmNoCaching); - printpainter.setMode(QCPPainter::pmNonCosmetic, exportPen==QCP::epNoCosmetic); - printpainter.setWindow(mViewport); - if (mBackgroundBrush.style() != Qt::NoBrush && - mBackgroundBrush.color() != Qt::white && - mBackgroundBrush.color() != Qt::transparent && - mBackgroundBrush.color().alpha() > 0) // draw pdf background color if not white/transparent - printpainter.fillRect(viewport(), mBackgroundBrush); - draw(&printpainter); - printpainter.end(); - success = true; - } - setViewport(oldViewport); + QCPPainter printpainter; + if (printpainter.begin(&printer)) { + printpainter.setMode(QCPPainter::pmVectorized); + printpainter.setMode(QCPPainter::pmNoCaching); + printpainter.setMode(QCPPainter::pmNonCosmetic, exportPen == QCP::epNoCosmetic); + printpainter.setWindow(mViewport); + if (mBackgroundBrush.style() != Qt::NoBrush && + mBackgroundBrush.color() != Qt::white && + mBackgroundBrush.color() != Qt::transparent && + mBackgroundBrush.color().alpha() > 0) { // draw pdf background color if not white/transparent + printpainter.fillRect(viewport(), mBackgroundBrush); + } + draw(&printpainter); + printpainter.end(); + success = true; + } + setViewport(oldViewport); #endif // QT_NO_PRINTER - return success; + return success; } /*! @@ -15341,7 +15443,7 @@ bool QCustomPlot::savePdf(const QString &fileName, int width, int height, QCP::E */ 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); + return saveRastered(fileName, width, height, scale, "PNG", quality, resolution, resolutionUnit); } /*! @@ -15388,7 +15490,7 @@ bool QCustomPlot::savePng(const QString &fileName, int width, int height, double */ 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, resolution, resolutionUnit); + return saveRastered(fileName, width, height, scale, "JPG", quality, resolution, resolutionUnit); } /*! @@ -15432,11 +15534,11 @@ bool QCustomPlot::saveJpg(const QString &fileName, int width, int height, double */ bool QCustomPlot::saveBmp(const QString &fileName, int width, int height, double scale, int resolution, QCP::ResolutionUnit resolutionUnit) { - return saveRastered(fileName, width, height, scale, "BMP", -1, resolution, resolutionUnit); + return saveRastered(fileName, width, height, scale, "BMP", -1, resolution, resolutionUnit); } /*! \internal - + Returns a minimum size hint that corresponds to the minimum size of the top level layout (\ref plotLayout). To prevent QCustomPlot from being collapsed to size/width zero, set a minimum size (setMinimumSize) either on the whole QCustomPlot or on any layout elements inside the plot. @@ -15445,178 +15547,175 @@ bool QCustomPlot::saveBmp(const QString &fileName, int width, int height, double */ QSize QCustomPlot::minimumSizeHint() const { - return mPlotLayout->minimumOuterSizeHint(); + return mPlotLayout->minimumOuterSizeHint(); } /*! \internal - + Returns a size hint that is the same as \ref minimumSizeHint. - + */ QSize QCustomPlot::sizeHint() const { - return mPlotLayout->minimumOuterSizeHint(); + return mPlotLayout->minimumOuterSizeHint(); } /*! \internal - + Event handler for when the QCustomPlot widget needs repainting. This does not cause a \ref replot, but draws the internal buffer on the widget surface. */ void QCustomPlot::paintEvent(QPaintEvent *event) { - Q_UNUSED(event) - QCPPainter painter(this); - if (painter.isActive()) - { + Q_UNUSED(event) + QCPPainter painter(this); + if (painter.isActive()) { #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) - painter.setRenderHint(QPainter::HighQualityAntialiasing); // to make Antialiasing look good if using the OpenGL graphicssystem + painter.setRenderHint(QPainter::HighQualityAntialiasing); // to make Antialiasing look good if using the OpenGL graphicssystem #endif - if (mBackgroundBrush.style() != Qt::NoBrush) - painter.fillRect(mViewport, mBackgroundBrush); - drawBackground(&painter); - foreach (QSharedPointer buffer, mPaintBuffers) - buffer->draw(&painter); - } + if (mBackgroundBrush.style() != Qt::NoBrush) { + painter.fillRect(mViewport, mBackgroundBrush); + } + drawBackground(&painter); + foreach (QSharedPointer buffer, mPaintBuffers) { + buffer->draw(&painter); + } + } } /*! \internal - + 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: - setViewport(rect()); - replot(rpQueuedRefresh); // queued refresh is important here, to prevent painting issues in some contexts (e.g. MDI subwindow) + Q_UNUSED(event) + // resize and repaint the buffer: + setViewport(rect()); + 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 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(); - - // 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; iaccept(); // default impl of QCPLayerable's mouse events ignore the event, in that case propagate to next candidate in list - candidates.at(i)->mouseDoubleClickEvent(event, details.at(i)); - if (event->isAccepted()) - { - mMouseEventLayerable = candidates.at(i); - mMouseEventLayerableDetails = details.at(i); - break; + emit mouseDoubleClick(event); + mMouseHasMoved = false; + mMousePressPos = event->pos(); + + // 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; i < candidates.size(); ++i) { + event->accept(); // default impl of QCPLayerable's mouse events ignore the event, in that case propagate to next candidate in list + candidates.at(i)->mouseDoubleClickEvent(event, details.at(i)); + if (event->isAccepted()) { + mMouseEventLayerable = candidates.at(i); + mMouseEventLayerableDetails = details.at(i); + break; + } } - } - - // emit specialized object double click signals: - if (!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, nullptr, 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. + + // 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, nullptr, 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. 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); - // save some state to tell in releaseEvent whether it was a click: - mMouseHasMoved = false; - mMousePressPos = event->pos(); - - 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, prepare for click signal emission and forward event to layerable under the cursor: - QList details; - QList candidates = layerableListAt(mMousePressPos, false, &details); - if (!candidates.isEmpty()) - { - mMouseSignalLayerable = candidates.first(); // candidate for signal emission is always topmost hit layerable (signal emitted in release event) - mMouseSignalLayerableDetails = details.first(); + emit mousePress(event); + // save some state to tell in releaseEvent whether it was a click: + mMouseHasMoved = false; + mMousePressPos = event->pos(); + + 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, prepare for click signal emission and forward event to layerable under the cursor: + QList details; + QList candidates = layerableListAt(mMousePressPos, false, &details); + if (!candidates.isEmpty()) { + mMouseSignalLayerable = candidates.first(); // candidate for signal emission is always topmost hit layerable (signal emitted in release event) + mMouseSignalLayerableDetails = details.first(); + } + // forward event to topmost candidate which accepts the event: + for (int i = 0; i < candidates.size(); ++i) { + event->accept(); // default impl of QCPLayerable's mouse events call ignore() on 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; + } + } } - // forward event to topmost candidate which accepts the event: - for (int i=0; iaccept(); // default impl of QCPLayerable's mouse events call ignore() on 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; - } - } - } - - event->accept(); // in case QCPLayerable reimplementation manipulates event accepted state. In QWidget event system, QCustomPlot wants to accept the 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 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); - - 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. + emit mouseMove(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 @@ -15635,51 +15734,51 @@ void QCustomPlot::mouseMoveEvent(QMouseEvent *event) */ void QCustomPlot::mouseReleaseEvent(QMouseEvent *event) { - emit mouseRelease(event); - - 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) - processPointSelection(event); - - // emit specialized click signals of QCustomPlot instance: - if (QCPAbstractPlottable *ap = qobject_cast(mMouseSignalLayerable)) - { - int dataIndex = 0; - if (!mMouseSignalLayerableDetails.value().isEmpty()) - dataIndex = mMouseSignalLayerableDetails.value().dataRange().begin(); - emit plottableClick(ap, dataIndex, event); - } else if (QCPAxis *ax = qobject_cast(mMouseSignalLayerable)) - emit axisClick(ax, mMouseSignalLayerableDetails.value(), event); - else if (QCPAbstractItem *ai = qobject_cast(mMouseSignalLayerable)) - emit itemClick(ai, event); - else if (QCPLegend *lg = qobject_cast(mMouseSignalLayerable)) - emit legendClick(lg, nullptr, event); - else if (QCPAbstractLegendItem *li = qobject_cast(mMouseSignalLayerable)) - emit legendClick(li->parentLegend(), li, event); - mMouseSignalLayerable = nullptr; - } - - if (mSelectionRect && mSelectionRect->isActive()) // Note: if a click was detected above, the selection rect is canceled there - { - // finish selection rect, the appropriate action will be taken via signal-slot connection: - mSelectionRect->endSelection(event); - } else - { - // call event of affected layerable: - if (mMouseEventLayerable) - { - mMouseEventLayerable->mouseReleaseEvent(event, mMousePressPos); - mMouseEventLayerable = nullptr; + emit mouseRelease(event); + + 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) { + processPointSelection(event); + } + + // emit specialized click signals of QCustomPlot instance: + if (QCPAbstractPlottable *ap = qobject_cast(mMouseSignalLayerable)) { + int dataIndex = 0; + if (!mMouseSignalLayerableDetails.value().isEmpty()) { + dataIndex = mMouseSignalLayerableDetails.value().dataRange().begin(); + } + emit plottableClick(ap, dataIndex, event); + } else if (QCPAxis *ax = qobject_cast(mMouseSignalLayerable)) { + emit axisClick(ax, mMouseSignalLayerableDetails.value(), event); + } else if (QCPAbstractItem *ai = qobject_cast(mMouseSignalLayerable)) { + emit itemClick(ai, event); + } else if (QCPLegend *lg = qobject_cast(mMouseSignalLayerable)) { + emit legendClick(lg, nullptr, event); + } else if (QCPAbstractLegendItem *li = qobject_cast(mMouseSignalLayerable)) { + emit legendClick(li->parentLegend(), li, event); + } + mMouseSignalLayerable = nullptr; } - } - - if (noAntialiasingOnDrag()) - replot(rpQueuedReplot); - - event->accept(); // in case QCPLayerable reimplementation manipulates event accepted state. In QWidget event system, QCustomPlot wants to accept the event. + + if (mSelectionRect && mSelectionRect->isActive()) { // Note: if a click was detected above, the selection rect is canceled there + // finish selection rect, the appropriate action will be taken via signal-slot connection: + mSelectionRect->endSelection(event); + } else { + // call event of affected layerable: + if (mMouseEventLayerable) { + mMouseEventLayerable->mouseReleaseEvent(event, mMousePressPos); + mMouseEventLayerable = nullptr; + } + } + + if (noAntialiasingOnDrag()) { + replot(rpQueuedReplot); + } + + event->accept(); // in case QCPLayerable reimplementation manipulates event accepted state. In QWidget event system, QCustomPlot wants to accept the event. } /*! \internal @@ -15689,27 +15788,27 @@ void QCustomPlot::mouseReleaseEvent(QMouseEvent *event) */ void QCustomPlot::wheelEvent(QWheelEvent *event) { - emit mouseWheel(event); - + emit mouseWheel(event); + #if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) - const QPointF pos = event->pos(); + const QPointF pos = event->pos(); #else - const QPointF pos = event->position(); + const QPointF pos = event->position(); #endif - - // forward event to layerable under cursor: - foreach (QCPLayerable *candidate, layerableListAt(pos, false)) - { - event->accept(); // default impl of QCPLayerable's mouse events ignore the event, in that case propagate to next candidate in list - candidate->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. + + // forward event to layerable under cursor: + foreach (QCPLayerable *candidate, layerableListAt(pos, false)) { + event->accept(); // default impl of QCPLayerable's mouse events ignore the event, in that case propagate to next candidate in list + candidate->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 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. @@ -15720,25 +15819,26 @@ void QCustomPlot::wheelEvent(QWheelEvent *event) */ void QCustomPlot::draw(QCPPainter *painter) { - updateLayout(); - - // draw viewport background pixmap: - drawBackground(painter); + updateLayout(); - // draw all layered objects (grid, axes, plottables, items, legend,...): - foreach (QCPLayer *layer, mLayers) - layer->draw(painter); - - /* Debug code to draw all layout element rects - foreach (QCPLayoutElement *el, findChildren()) - { + // draw viewport background pixmap: + drawBackground(painter); + + // draw all layered objects (grid, axes, plottables, items, legend,...): + foreach (QCPLayer *layer, mLayers) { + layer->draw(painter); + } + + /* Debug code to draw all layout element rects + foreach (QCPLayoutElement *el, findChildren()) + { painter->setBrush(Qt::NoBrush); painter->setPen(QPen(QColor(0, 0, 0, 100), 0, Qt::DashLine)); painter->drawRect(el->rect()); painter->setPen(QPen(QColor(255, 0, 0, 100), 0, Qt::DashLine)); painter->drawRect(el->outerRect()); - } - */ + } + */ } /*! \internal @@ -15751,18 +15851,18 @@ void QCustomPlot::draw(QCPPainter *painter) */ void QCustomPlot::updateLayout() { - // run through layout phases: - mPlotLayout->update(QCPLayoutElement::upPreparation); - mPlotLayout->update(QCPLayoutElement::upMargins); - mPlotLayout->update(QCPLayoutElement::upLayout); + // run through layout phases: + mPlotLayout->update(QCPLayoutElement::upPreparation); + mPlotLayout->update(QCPLayoutElement::upMargins); + mPlotLayout->update(QCPLayoutElement::upLayout); - emit afterLayout(); + emit afterLayout(); } /*! \internal - + Draws the viewport background pixmap of the plot. - + If a pixmap was provided via \ref setBackground, this function buffers the scaled version depending on \ref setBackgroundScaled and \ref setBackgroundScaledMode and then draws it inside the viewport with the provided \a painter. The scaled version is buffered in @@ -15770,32 +15870,30 @@ void QCustomPlot::updateLayout() the axis rect has changed in a way that requires a rescale of the background pixmap (this is 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. - + \see setBackground, setBackgroundScaled, setBackgroundScaledMode */ void QCustomPlot::drawBackground(QCPPainter *painter) { - // Note: background color is handled in individual replot/save functions + // Note: background color is handled in individual replot/save functions - // draw background pixmap (on top of fill, if brush specified): - if (!mBackgroundPixmap.isNull()) - { - if (mBackgroundScaled) - { - // check whether mScaledBackground needs to be updated: - QSize scaledSize(mBackgroundPixmap.size()); - scaledSize.scale(mViewport.size(), mBackgroundScaledMode); - if (mScaledBackgroundPixmap.size() != scaledSize) - mScaledBackgroundPixmap = mBackgroundPixmap.scaled(mViewport.size(), mBackgroundScaledMode, Qt::SmoothTransformation); - painter->drawPixmap(mViewport.topLeft(), mScaledBackgroundPixmap, QRect(0, 0, mViewport.width(), mViewport.height()) & mScaledBackgroundPixmap.rect()); - } else - { - painter->drawPixmap(mViewport.topLeft(), mBackgroundPixmap, QRect(0, 0, mViewport.width(), mViewport.height())); + // draw background pixmap (on top of fill, if brush specified): + if (!mBackgroundPixmap.isNull()) { + if (mBackgroundScaled) { + // check whether mScaledBackground needs to be updated: + QSize scaledSize(mBackgroundPixmap.size()); + scaledSize.scale(mViewport.size(), mBackgroundScaledMode); + if (mScaledBackgroundPixmap.size() != scaledSize) { + mScaledBackgroundPixmap = mBackgroundPixmap.scaled(mViewport.size(), mBackgroundScaledMode, Qt::SmoothTransformation); + } + painter->drawPixmap(mViewport.topLeft(), mScaledBackgroundPixmap, QRect(0, 0, mViewport.width(), mViewport.height()) & mScaledBackgroundPixmap.rect()); + } else { + painter->drawPixmap(mViewport.topLeft(), mBackgroundPixmap, QRect(0, 0, mViewport.width(), mViewport.height())); + } } - } } /*! \internal @@ -15819,40 +15917,39 @@ void QCustomPlot::drawBackground(QCPPainter *painter) */ 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()) + int bufferIndex = 0; + if (mPaintBuffers.isEmpty()) { 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: - foreach (QSharedPointer buffer, mPaintBuffers) - { - buffer->setSize(viewport().size()); // won't do anything if already correct size - buffer->clear(Qt::transparent); - buffer->setInvalidated(); - } + + 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: + foreach (QSharedPointer buffer, mPaintBuffers) { + buffer->setSize(viewport().size()); // won't do anything if already correct size + buffer->clear(Qt::transparent); + buffer->setInvalidated(); + } } /*! \internal @@ -15865,18 +15962,18 @@ void QCustomPlot::setupPaintBuffers() */ QCPAbstractPaintBuffer *QCustomPlot::createPaintBuffer() { - if (mOpenGl) - { + if (mOpenGl) { #if defined(QCP_OPENGL_FBO) - return new QCPPaintBufferGlFbo(viewport().size(), mBufferDevicePixelRatio, mGlContext, mGlPaintDevice); + return new QCPPaintBufferGlFbo(viewport().size(), mBufferDevicePixelRatio, mGlContext, mGlPaintDevice); #elif defined(QCP_OPENGL_PBUFFER) - return new QCPPaintBufferGlPbuffer(viewport().size(), mBufferDevicePixelRatio, mOpenGlMultisamples); + 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); + 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); + } else { + return new QCPPaintBufferPixmap(viewport().size(), mBufferDevicePixelRatio); + } } /*! @@ -15892,12 +15989,12 @@ QCPAbstractPaintBuffer *QCustomPlot::createPaintBuffer() */ bool QCustomPlot::hasInvalidatedPaintBuffers() { - foreach (QSharedPointer buffer, mPaintBuffers) - { - if (buffer->invalidated()) - return true; - } - return false; + foreach (QSharedPointer buffer, mPaintBuffers) { + if (buffer->invalidated()) { + return true; + } + } + return false; } /*! \internal @@ -15916,47 +16013,44 @@ bool QCustomPlot::hasInvalidatedPaintBuffers() bool QCustomPlot::setupOpenGl() { #ifdef QCP_OPENGL_FBO - freeOpenGl(); - QSurfaceFormat proposedSurfaceFormat; - proposedSurfaceFormat.setSamples(mOpenGlMultisamples); + freeOpenGl(); + QSurfaceFormat proposedSurfaceFormat; + proposedSurfaceFormat.setSamples(mOpenGlMultisamples); #ifdef QCP_OPENGL_OFFSCREENSURFACE - QOffscreenSurface *surface = new QOffscreenSurface; + QOffscreenSurface *surface = new QOffscreenSurface; #else - QWindow *surface = new QWindow; - surface->setSurfaceType(QSurface::OpenGLSurface); + 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; + 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(); + return QGLFormat::hasOpenGL(); #else - return false; + return false; #endif } @@ -15974,44 +16068,49 @@ bool QCustomPlot::setupOpenGl() void QCustomPlot::freeOpenGl() { #ifdef QCP_OPENGL_FBO - mGlPaintDevice.clear(); - mGlContext.clear(); - mGlSurface.clear(); + mGlPaintDevice.clear(); + mGlContext.clear(); + mGlSurface.clear(); #endif } /*! \internal - + This method is used by \ref QCPAxisRect::removeAxis to report removed axes to the QCustomPlot so it may clear its QCustomPlot::xAxis, yAxis, xAxis2 and yAxis2 members accordingly. */ void QCustomPlot::axisRemoved(QCPAxis *axis) { - if (xAxis == axis) - xAxis = nullptr; - if (xAxis2 == axis) - xAxis2 = nullptr; - if (yAxis == axis) - yAxis = nullptr; - if (yAxis2 == axis) - yAxis2 = nullptr; - - // Note: No need to take care of range drag axes and range zoom axes, because they are stored in smart pointers + if (xAxis == axis) { + xAxis = nullptr; + } + if (xAxis2 == axis) { + xAxis2 = nullptr; + } + if (yAxis == axis) { + yAxis = nullptr; + } + if (yAxis2 == axis) { + yAxis2 = nullptr; + } + + // Note: No need to take care of range drag axes and range zoom axes, because they are stored in smart pointers } /*! \internal - + This method is used by the QCPLegend destructor to report legend removal to the QCustomPlot so it may clear its QCustomPlot::legend member accordingly. */ void QCustomPlot::legendRemoved(QCPLegend *legend) { - if (this->legend == legend) - this->legend = nullptr; + if (this->legend == legend) { + this->legend = nullptr; + } } /*! \internal - + This slot is connected to the selection rect's \ref QCPSelectionRect::accepted signal when \ref setSelectionRectMode is set to \ref QCP::srmSelect. @@ -16019,112 +16118,101 @@ void QCustomPlot::legendRemoved(QCPLegend *legend) 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) { - typedef QPair SelectionCandidate; - typedef QMultiMap SelectionCandidates; // map key is number of selected data points, so we have selections sorted by size - - bool selectionStateChanged = false; - - if (mInteractions.testFlag(QCP::iSelectPlottables)) - { - SelectionCandidates potentialSelections; - 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.insert(dataSel.dataPointCount(), SelectionCandidate(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()) - { - SelectionCandidates::iterator it = potentialSelections.begin(); - while (it != std::prev(potentialSelections.end())) // 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; + typedef QPair SelectionCandidate; + typedef QMultiMap SelectionCandidates; // map key is number of selected data points, so we have selections sorted by size + + bool selectionStateChanged = false; + + if (mInteractions.testFlag(QCP::iSelectPlottables)) { + SelectionCandidates potentialSelections; + 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.insert(dataSel.dataPointCount(), SelectionCandidate(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()) { + SelectionCandidates::iterator it = potentialSelections.begin(); + while (it != std::prev(potentialSelections.end())) { // 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: + SelectionCandidates::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; + } } - } } - } - - // go through selections in reverse (largest selection first) and emit select events: - SelectionCandidates::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(); + + 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(nullptr)); - axisRect->zoom(QRectF(rect), affectedAxes); - } - replot(rpQueuedReplot); // always replot to make selection rect disappear + Q_UNUSED(event) + if (QCPAxisRect *axisRect = axisRectAt(rect.topLeft())) { + QList affectedAxes = QList() << axisRect->rangeZoomAxes(Qt::Horizontal) << axisRect->rangeZoomAxes(Qt::Vertical); + affectedAxes.removeAll(static_cast(nullptr)); + axisRect->zoom(QRectF(rect), affectedAxes); + } + replot(rpQueuedReplot); // always replot to make selection rect disappear } /*! \internal @@ -16146,138 +16234,130 @@ void QCustomPlot::processRectZoom(QRect rect, QMouseEvent *event) */ 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; + 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); - } + 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; + 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; + 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; + 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 after every operation that changes the layer indices, like layer removal, layer creation, layer moving. */ void QCustomPlot::updateLayerIndices() const { - for (int i=0; imIndex = i; + for (int i = 0; i < mLayers.size(); ++i) { + mLayers.at(i)->mIndex = i; + } } /*! \internal @@ -16292,19 +16372,21 @@ void QCustomPlot::updateLayerIndices() const 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 layerableListAt, layoutElementAt, axisRectAt */ QCPLayerable *QCustomPlot::layerableAt(const QPointF &pos, bool onlySelectable, QVariant *selectionDetails) const { - QList details; - QList candidates = layerableListAt(pos, onlySelectable, selectionDetails ? &details : nullptr); - if (selectionDetails && !details.isEmpty()) - *selectionDetails = details.first(); - if (!candidates.isEmpty()) - return candidates.first(); - else - return nullptr; + QList details; + QList candidates = layerableListAt(pos, onlySelectable, selectionDetails ? &details : nullptr); + if (selectionDetails && !details.isEmpty()) { + *selectionDetails = details.first(); + } + if (!candidates.isEmpty()) { + return candidates.first(); + } else { + return nullptr; + } } /*! \internal @@ -16323,30 +16405,29 @@ QCPLayerable *QCustomPlot::layerableAt(const QPointF &pos, bool onlySelectable, 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 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(); - 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, selectionDetails ? &details : nullptr); - if (dist >= 0 && dist < selectionTolerance()) - { - result.append(layerables.at(i)); - if (selectionDetails) - selectionDetails->append(details); - } + QList result; + for (int layerIndex = mLayers.size() - 1; layerIndex >= 0; --layerIndex) { + const QList layerables = mLayers.at(layerIndex)->children(); + 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, selectionDetails ? &details : nullptr); + if (dist >= 0 && dist < selectionTolerance()) { + result.append(layerables.at(i)); + if (selectionDetails) { + selectionDetails->append(details); + } + } + } } - } - return result; + return result; } /*! @@ -16369,112 +16450,114 @@ QList QCustomPlot::layerableListAt(const QPointF &pos, bool onlyS */ bool QCustomPlot::saveRastered(const QString &fileName, int width, int height, double scale, const char *format, int quality, int resolution, QCP::ResolutionUnit resolutionUnit) { - 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 = int(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 - return false; + 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 = int(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 { + return false; + } } /*! Renders the plot to a pixmap and returns it. - + The plot is 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 pixmap with width 200.) - + \see toPainter, saveRastered, saveBmp, savePng, saveJpg, savePdf */ QPixmap QCustomPlot::toPixmap(int width, int height, double scale) { - // this method is somewhat similar to toPainter. Change something here, and a change in toPainter might be necessary, too. - int newWidth, newHeight; - if (width == 0 || height == 0) - { - newWidth = this->width(); - newHeight = this->height(); - } else - { - newWidth = width; - newHeight = height; - } - int scaledWidth = qRound(scale*newWidth); - int scaledHeight = qRound(scale*newHeight); - - QPixmap result(scaledWidth, scaledHeight); - result.fill(mBackgroundBrush.style() == Qt::SolidPattern ? mBackgroundBrush.color() : Qt::transparent); // if using non-solid pattern, make transparent now and draw brush pattern later - QCPPainter painter; - painter.begin(&result); - if (painter.isActive()) - { - QRect oldViewport = viewport(); - setViewport(QRect(0, 0, newWidth, newHeight)); - painter.setMode(QCPPainter::pmNoCaching); - if (!qFuzzyCompare(scale, 1.0)) - { - if (scale > 1.0) // for scale < 1 we always want cosmetic pens where possible, because else lines might disappear for very small scales - painter.setMode(QCPPainter::pmNonCosmetic); - painter.scale(scale, scale); + // this method is somewhat similar to toPainter. Change something here, and a change in toPainter might be necessary, too. + int newWidth, newHeight; + if (width == 0 || height == 0) { + newWidth = this->width(); + newHeight = this->height(); + } else { + newWidth = width; + newHeight = height; } - if (mBackgroundBrush.style() != Qt::SolidPattern && mBackgroundBrush.style() != Qt::NoBrush) // solid fills were done a few lines above with QPixmap::fill - painter.fillRect(mViewport, mBackgroundBrush); - draw(&painter); - setViewport(oldViewport); - painter.end(); - } else // might happen if pixmap has width or height zero - { - qDebug() << Q_FUNC_INFO << "Couldn't activate painter on pixmap"; - return QPixmap(); - } - return result; + int scaledWidth = qRound(scale * newWidth); + int scaledHeight = qRound(scale * newHeight); + + QPixmap result(scaledWidth, scaledHeight); + result.fill(mBackgroundBrush.style() == Qt::SolidPattern ? mBackgroundBrush.color() : Qt::transparent); // if using non-solid pattern, make transparent now and draw brush pattern later + QCPPainter painter; + painter.begin(&result); + if (painter.isActive()) { + QRect oldViewport = viewport(); + setViewport(QRect(0, 0, newWidth, newHeight)); + painter.setMode(QCPPainter::pmNoCaching); + if (!qFuzzyCompare(scale, 1.0)) { + if (scale > 1.0) { // for scale < 1 we always want cosmetic pens where possible, because else lines might disappear for very small scales + painter.setMode(QCPPainter::pmNonCosmetic); + } + painter.scale(scale, scale); + } + if (mBackgroundBrush.style() != Qt::SolidPattern && mBackgroundBrush.style() != Qt::NoBrush) { // solid fills were done a few lines above with QPixmap::fill + painter.fillRect(mViewport, mBackgroundBrush); + } + draw(&painter); + setViewport(oldViewport); + painter.end(); + } else { // might happen if pixmap has width or height zero + qDebug() << Q_FUNC_INFO << "Couldn't activate painter on pixmap"; + return QPixmap(); + } + return result; } /*! Renders the plot using the passed \a painter. - + The plot is sized to \a width and \a height in pixels. If the \a painter's scale is not 1.0, the resulting plot will appear scaled accordingly. - + \note If you are restricted to using a QPainter (instead of QCPPainter), create a temporary QPicture and open a QCPPainter on it. Then call \ref toPainter with this QCPPainter. After ending the paint operation on the picture, draw it with the QPainter. This will reproduce the painter actions the QCPPainter took, with a QPainter. - + \see toPixmap */ void QCustomPlot::toPainter(QCPPainter *painter, int width, int height) { - // this method is somewhat similar to toPixmap. Change something here, and a change in toPixmap might be necessary, too. - int newWidth, newHeight; - if (width == 0 || height == 0) - { - newWidth = this->width(); - newHeight = this->height(); - } else - { - newWidth = width; - newHeight = height; - } + // this method is somewhat similar to toPixmap. Change something here, and a change in toPixmap might be necessary, too. + int newWidth, newHeight; + if (width == 0 || height == 0) { + newWidth = this->width(); + newHeight = this->height(); + } else { + newWidth = width; + newHeight = height; + } - if (painter->isActive()) - { - QRect oldViewport = viewport(); - setViewport(QRect(0, 0, newWidth, newHeight)); - painter->setMode(QCPPainter::pmNoCaching); - if (mBackgroundBrush.style() != Qt::NoBrush) // unlike in toPixmap, we can't do QPixmap::fill for Qt::SolidPattern brush style, so we also draw solid fills with fillRect here - painter->fillRect(mViewport, mBackgroundBrush); - draw(painter); - setViewport(oldViewport); - } else - qDebug() << Q_FUNC_INFO << "Passed painter is not active"; + if (painter->isActive()) { + QRect oldViewport = viewport(); + setViewport(QRect(0, 0, newWidth, newHeight)); + painter->setMode(QCPPainter::pmNoCaching); + if (mBackgroundBrush.style() != Qt::NoBrush) { // unlike in toPixmap, we can't do QPixmap::fill for Qt::SolidPattern brush style, so we also draw solid fills with fillRect here + painter->fillRect(mViewport, mBackgroundBrush); + } + draw(painter); + setViewport(oldViewport); + } else { + qDebug() << Q_FUNC_INFO << "Passed painter is not active"; + } } /* end of 'src/core.cpp' */ @@ -16489,7 +16572,7 @@ void QCustomPlot::toPainter(QCPPainter *painter, int width, int height) /*! \class QCPColorGradient \brief Defines a color gradient for use with e.g. \ref QCPColorMap - + This class describes a color gradient which can be used to encode data with color. For example, QCPColorMap and QCPColorScale have \ref QCPColorMap::setGradient "setGradient" methods which take an instance of this class. Colors are set with \ref setColorStopAt(double position, const QColor &color) @@ -16498,20 +16581,20 @@ 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. - + How NaN values are interpreted can be configured with \ref setNanHandling. - + \image html QCPColorGradient.png - + The constructor \ref QCPColorGradient(GradientPreset preset) 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 color gradient shall be applied periodically (wrapping around) to data values that lie outside the data range specified on the plottable instance can be controlled with \ref setPeriodic. @@ -16524,14 +16607,14 @@ void QCustomPlot::toPainter(QCPPainter *painter, int width, int height) The color level count is initialized to 350. */ QCPColorGradient::QCPColorGradient() : - mLevelCount(350), - mColorInterpolation(ciRGB), - mNanHandling(nhNone), - mNanColor(Qt::black), - mPeriodic(false), - mColorBufferInvalidated(true) + mLevelCount(350), + mColorInterpolation(ciRGB), + mNanHandling(nhNone), + mNanColor(Qt::black), + mPeriodic(false), + mColorBufferInvalidated(true) { - mColorBuffer.fill(qRgb(0, 0, 0), mLevelCount); + mColorBuffer.fill(qRgb(0, 0, 0), mLevelCount); } /*! @@ -16541,26 +16624,26 @@ QCPColorGradient::QCPColorGradient() : The color level count is initialized to 350. */ QCPColorGradient::QCPColorGradient(GradientPreset preset) : - mLevelCount(350), - mColorInterpolation(ciRGB), - mNanHandling(nhNone), - mNanColor(Qt::black), - mPeriodic(false), - mColorBufferInvalidated(true) + mLevelCount(350), + mColorInterpolation(ciRGB), + mNanHandling(nhNone), + mNanColor(Qt::black), + mPeriodic(false), + mColorBufferInvalidated(true) { - mColorBuffer.fill(qRgb(0, 0, 0), mLevelCount); - loadPreset(preset); + mColorBuffer.fill(qRgb(0, 0, 0), mLevelCount); + loadPreset(preset); } /* undocumented operator */ bool QCPColorGradient::operator==(const QCPColorGradient &other) const { - return ((other.mLevelCount == this->mLevelCount) && - (other.mColorInterpolation == this->mColorInterpolation) && - (other.mNanHandling == this ->mNanHandling) && - (other.mNanColor == this->mNanColor) && - (other.mPeriodic == this->mPeriodic) && - (other.mColorStops == this->mColorStops)); + return ((other.mLevelCount == this->mLevelCount) && + (other.mColorInterpolation == this->mColorInterpolation) && + (other.mNanHandling == this ->mNanHandling) && + (other.mNanColor == this->mNanColor) && + (other.mPeriodic == this->mPeriodic) && + (other.mColorStops == this->mColorStops)); } /*! @@ -16571,106 +16654,103 @@ bool QCPColorGradient::operator==(const QCPColorGradient &other) const */ void QCPColorGradient::setLevelCount(int n) { - if (n < 2) - { - qDebug() << Q_FUNC_INFO << "n must be greater or equal 2 but was" << n; - n = 2; - } - if (n != mLevelCount) - { - mLevelCount = n; - mColorBufferInvalidated = true; - } + if (n < 2) { + qDebug() << Q_FUNC_INFO << "n must be greater or equal 2 but was" << n; + n = 2; + } + if (n != mLevelCount) { + mLevelCount = n; + mColorBufferInvalidated = true; + } } /*! Sets at which positions from 0 to 1 which color shall occur. The positions are the keys, the colors are the values of the passed QMap \a colorStops. In between these color stops, the color 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 (or creating a new, empty QCPColorGradient) and then adding them one by one with \ref setColorStopAt. - + \see clearColorStops */ void QCPColorGradient::setColorStops(const QMap &colorStops) { - mColorStops = colorStops; - mColorBufferInvalidated = true; + mColorStops = colorStops; + mColorBufferInvalidated = true; } /*! Sets the \a color the gradient will have at the specified \a position (from 0 to 1). In between these color stops, the color is interpolated according to \ref setColorInterpolation. - + \see setColorStops, clearColorStops */ void QCPColorGradient::setColorStopAt(double position, const QColor &color) { - mColorStops.insert(position, color); - mColorBufferInvalidated = true; + mColorStops.insert(position, color); + mColorBufferInvalidated = true; } /*! Sets whether the colors in between the configured color stops (see \ref setColorStopAt) shall be interpolated linearly in RGB or in HSV color space. - + For example, a sweep in RGB space from red to green will have a muddy brown intermediate color, whereas in HSV space the intermediate color is yellow. */ void QCPColorGradient::setColorInterpolation(QCPColorGradient::ColorInterpolation interpolation) { - if (interpolation != mColorInterpolation) - { - mColorInterpolation = interpolation; - mColorBufferInvalidated = true; - } + if (interpolation != mColorInterpolation) { + mColorInterpolation = interpolation; + mColorBufferInvalidated = true; + } } /*! Sets how NaNs in the data are displayed in the plot. - + \see setNanColor */ void QCPColorGradient::setNanHandling(QCPColorGradient::NanHandling handling) { - mNanHandling = handling; + mNanHandling = handling; } /*! Sets the color that NaN data is represented by, if \ref setNanHandling is set to ref nhNanColor. - + \see setNanHandling */ void QCPColorGradient::setNanColor(const QColor &color) { - mNanColor = color; + mNanColor = color; } /*! Sets whether data points that are outside the configured data range (e.g. \ref QCPColorMap::setDataRange) are colored by periodically repeating the color gradient or whether they all have the same color, corresponding to the respective gradient boundary color. - + \image html QCPColorGradient-periodic.png - + As shown in the image above, gradients that have the same start and end color are especially suitable for a periodic gradient mapping, since they produce smooth color transitions throughout the color map. A preset that has this property is \ref gpHues. - + In practice, using periodic color gradients makes sense when the data corresponds to a periodic dimension, such as an angle or a phase. If this is not the case, the color encoding might become ambiguous, because multiple different data values are shown as the same color. */ void QCPColorGradient::setPeriodic(bool enabled) { - mPeriodic = 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 @@ -16681,7 +16761,7 @@ void QCPColorGradient::setPeriodic(bool enabled) 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 @@ -16689,50 +16769,53 @@ void QCPColorGradient::setPeriodic(bool enabled) */ 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() and the other colorize() overload - if (!data) - { - qDebug() << Q_FUNC_INFO << "null pointer given as data"; - return; - } - if (!scanLine) - { - qDebug() << Q_FUNC_INFO << "null pointer given as scanLine"; - return; - } - if (mColorBufferInvalidated) - updateColorBuffer(); - - const bool skipNanCheck = mNanHandling == nhNone; - const double posToIndexFactor = !logarithmic ? (mLevelCount-1)/range.size() : (mLevelCount-1)/qLn(range.upper/range.lower); - for (int i=0; i::const_iterator it=mColorStops.constBegin(); it!=mColorStops.constEnd(); ++it) - result.setColorStopAt(1.0-it.key(), it.value()); - return result; + QCPColorGradient result(*this); + result.clearColorStops(); + for (QMap::const_iterator it = mColorStops.constBegin(); it != mColorStops.constEnd(); ++it) { + result.setColorStopAt(1.0 - it.key(), it.value()); + } + 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; + 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 convert positions to colors. This is where the interpolation between color stops is calculated. */ void QCPColorGradient::updateColorBuffer() { - if (mColorBuffer.size() != mLevelCount) - mColorBuffer.resize(mLevelCount); - if (mColorStops.size() > 1) - { - double indexToPosFactor = 1.0/double(mLevelCount-1); - const bool useAlpha = stopsUseAlpha(); - for (int i=0; i::const_iterator it = mColorStops.lowerBound(position); - if (it == mColorStops.constEnd()) // position is on or after last stop, use color of last stop - { - if (useAlpha) - { - const QColor col = std::prev(it).value(); - const double alphaPremultiplier = col.alpha()/255.0; // since we use QImage::Format_ARGB32_Premultiplied - mColorBuffer[i] = qRgba(int(col.red()*alphaPremultiplier), - int(col.green()*alphaPremultiplier), - int(col.blue()*alphaPremultiplier), - col.alpha()); - } else - mColorBuffer[i] = std::prev(it).value().rgba(); - } else if (it == mColorStops.constBegin()) // position is on or before first stop, use color of first stop - { - if (useAlpha) - { - const QColor &col = it.value(); - const double alphaPremultiplier = col.alpha()/255.0; // since we use QImage::Format_ARGB32_Premultiplied - mColorBuffer[i] = qRgba(int(col.red()*alphaPremultiplier), - int(col.green()*alphaPremultiplier), - int(col.blue()*alphaPremultiplier), - col.alpha()); - } else - mColorBuffer[i] = it.value().rgba(); - } else // position is in between stops (or on an intermediate stop), interpolate color - { - QMap::const_iterator high = it; - QMap::const_iterator low = std::prev(it); - double t = (position-low.key())/(high.key()-low.key()); // interpolation factor 0..1 - switch (mColorInterpolation) - { - case ciRGB: - { - if (useAlpha) - { - const int alpha = int((1-t)*low.value().alpha() + t*high.value().alpha()); - const double alphaPremultiplier = alpha/255.0; // since we use QImage::Format_ARGB32_Premultiplied - mColorBuffer[i] = qRgba(int( ((1-t)*low.value().red() + t*high.value().red())*alphaPremultiplier ), - int( ((1-t)*low.value().green() + t*high.value().green())*alphaPremultiplier ), - int( ((1-t)*low.value().blue() + t*high.value().blue())*alphaPremultiplier ), - alpha); - } else - { - mColorBuffer[i] = qRgb(int( ((1-t)*low.value().red() + t*high.value().red()) ), - int( ((1-t)*low.value().green() + t*high.value().green()) ), - int( ((1-t)*low.value().blue() + t*high.value().blue())) ); - } - break; - } - case ciHSV: - { - QColor lowHsv = low.value().toHsv(); - QColor highHsv = high.value().toHsv(); - double hue = 0; - double hueDiff = highHsv.hueF()-lowHsv.hueF(); - if (hueDiff > 0.5) - hue = lowHsv.hueF() - t*(1.0-hueDiff); - else if (hueDiff < -0.5) - hue = lowHsv.hueF() + t*(1.0+hueDiff); - else - hue = lowHsv.hueF() + t*hueDiff; - if (hue < 0) hue += 1.0; - else if (hue >= 1.0) hue -= 1.0; - if (useAlpha) - { - const QRgb rgb = QColor::fromHsvF(hue, - (1-t)*lowHsv.saturationF() + t*highHsv.saturationF(), - (1-t)*lowHsv.valueF() + t*highHsv.valueF()).rgb(); - const double alpha = (1-t)*lowHsv.alphaF() + t*highHsv.alphaF(); - mColorBuffer[i] = qRgba(int(qRed(rgb)*alpha), int(qGreen(rgb)*alpha), int(qBlue(rgb)*alpha), int(255*alpha)); - } - else - { - mColorBuffer[i] = QColor::fromHsvF(hue, - (1-t)*lowHsv.saturationF() + t*highHsv.saturationF(), - (1-t)*lowHsv.valueF() + t*highHsv.valueF()).rgb(); - } - break; - } - } - } + if (mColorBuffer.size() != mLevelCount) { + mColorBuffer.resize(mLevelCount); } - } else if (mColorStops.size() == 1) - { - const QRgb rgb = mColorStops.constBegin().value().rgb(); - const double alpha = mColorStops.constBegin().value().alphaF(); - mColorBuffer.fill(qRgba(int(qRed(rgb)*alpha), int(qGreen(rgb)*alpha), int(qBlue(rgb)*alpha), int(255*alpha))); - } else // mColorStops is empty, fill color buffer with black - { - mColorBuffer.fill(qRgb(0, 0, 0)); - } - mColorBufferInvalidated = false; + if (mColorStops.size() > 1) { + double indexToPosFactor = 1.0 / double(mLevelCount - 1); + const bool useAlpha = stopsUseAlpha(); + for (int i = 0; i < mLevelCount; ++i) { + double position = i * indexToPosFactor; + QMap::const_iterator it = mColorStops.lowerBound(position); + if (it == mColorStops.constEnd()) { // position is on or after last stop, use color of last stop + if (useAlpha) { + const QColor col = std::prev(it).value(); + const double alphaPremultiplier = col.alpha() / 255.0; // since we use QImage::Format_ARGB32_Premultiplied + mColorBuffer[i] = qRgba(int(col.red() * alphaPremultiplier), + int(col.green() * alphaPremultiplier), + int(col.blue() * alphaPremultiplier), + col.alpha()); + } else { + mColorBuffer[i] = std::prev(it).value().rgba(); + } + } else if (it == mColorStops.constBegin()) { // position is on or before first stop, use color of first stop + if (useAlpha) { + const QColor &col = it.value(); + const double alphaPremultiplier = col.alpha() / 255.0; // since we use QImage::Format_ARGB32_Premultiplied + mColorBuffer[i] = qRgba(int(col.red() * alphaPremultiplier), + int(col.green() * alphaPremultiplier), + int(col.blue() * alphaPremultiplier), + col.alpha()); + } else { + mColorBuffer[i] = it.value().rgba(); + } + } else { // position is in between stops (or on an intermediate stop), interpolate color + QMap::const_iterator high = it; + QMap::const_iterator low = std::prev(it); + double t = (position - low.key()) / (high.key() - low.key()); // interpolation factor 0..1 + switch (mColorInterpolation) { + case ciRGB: { + if (useAlpha) { + const int alpha = int((1 - t) * low.value().alpha() + t * high.value().alpha()); + const double alphaPremultiplier = alpha / 255.0; // since we use QImage::Format_ARGB32_Premultiplied + mColorBuffer[i] = qRgba(int(((1 - t) * low.value().red() + t * high.value().red()) * alphaPremultiplier), + int(((1 - t) * low.value().green() + t * high.value().green()) * alphaPremultiplier), + int(((1 - t) * low.value().blue() + t * high.value().blue()) * alphaPremultiplier), + alpha); + } else { + mColorBuffer[i] = qRgb(int(((1 - t) * low.value().red() + t * high.value().red())), + int(((1 - t) * low.value().green() + t * high.value().green())), + int(((1 - t) * low.value().blue() + t * high.value().blue()))); + } + break; + } + case ciHSV: { + QColor lowHsv = low.value().toHsv(); + QColor highHsv = high.value().toHsv(); + double hue = 0; + double hueDiff = highHsv.hueF() - lowHsv.hueF(); + if (hueDiff > 0.5) { + hue = lowHsv.hueF() - t * (1.0 - hueDiff); + } else if (hueDiff < -0.5) { + hue = lowHsv.hueF() + t * (1.0 + hueDiff); + } else { + hue = lowHsv.hueF() + t * hueDiff; + } + if (hue < 0) { + hue += 1.0; + } else if (hue >= 1.0) { + hue -= 1.0; + } + if (useAlpha) { + const QRgb rgb = QColor::fromHsvF(hue, + (1 - t) * lowHsv.saturationF() + t * highHsv.saturationF(), + (1 - t) * lowHsv.valueF() + t * highHsv.valueF()).rgb(); + const double alpha = (1 - t) * lowHsv.alphaF() + t * highHsv.alphaF(); + mColorBuffer[i] = qRgba(int(qRed(rgb) * alpha), int(qGreen(rgb) * alpha), int(qBlue(rgb) * alpha), int(255 * alpha)); + } else { + mColorBuffer[i] = QColor::fromHsvF(hue, + (1 - t) * lowHsv.saturationF() + t * highHsv.saturationF(), + (1 - t) * lowHsv.valueF() + t * highHsv.valueF()).rgb(); + } + break; + } + } + } + } + } else if (mColorStops.size() == 1) { + const QRgb rgb = mColorStops.constBegin().value().rgb(); + const double alpha = mColorStops.constBegin().value().alphaF(); + mColorBuffer.fill(qRgba(int(qRed(rgb)*alpha), int(qGreen(rgb)*alpha), int(qBlue(rgb)*alpha), int(255 * alpha))); + } else { // mColorStops is empty, fill color buffer with black + mColorBuffer.fill(qRgb(0, 0, 0)); + } + mColorBufferInvalidated = false; } /* end of 'src/colorgradient.cpp' */ @@ -17123,15 +17199,15 @@ void QCPColorGradient::updateColorBuffer() /*! \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. @@ -17141,15 +17217,15 @@ void QCPColorGradient::updateColorBuffer() 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) + mBracketPen(QPen(Qt::black)), + mBracketBrush(Qt::NoBrush), + mBracketWidth(5), + mBracketHeight(50), + mBracketStyle(bsSquareBracket), + mTangentToData(false), + mTangentAverage(2) { - + } QCPSelectionDecoratorBracket::~QCPSelectionDecoratorBracket() @@ -17162,7 +17238,7 @@ QCPSelectionDecoratorBracket::~QCPSelectionDecoratorBracket() */ void QCPSelectionDecoratorBracket::setBracketPen(const QPen &pen) { - mBracketPen = pen; + mBracketPen = pen; } /*! @@ -17171,7 +17247,7 @@ void QCPSelectionDecoratorBracket::setBracketPen(const QPen &pen) */ void QCPSelectionDecoratorBracket::setBracketBrush(const QBrush &brush) { - mBracketBrush = brush; + mBracketBrush = brush; } /*! @@ -17181,7 +17257,7 @@ void QCPSelectionDecoratorBracket::setBracketBrush(const QBrush &brush) */ void QCPSelectionDecoratorBracket::setBracketWidth(int width) { - mBracketWidth = width; + mBracketWidth = width; } /*! @@ -17191,211 +17267,208 @@ void QCPSelectionDecoratorBracket::setBracketWidth(int width) */ void QCPSelectionDecoratorBracket::setBracketHeight(int height) { - mBracketHeight = height; + mBracketHeight = height; } /*! Sets the shape that the bracket/marker will have. - + \see setBracketWidth, setBracketHeight */ void QCPSelectionDecoratorBracket::setBracketStyle(QCPSelectionDecoratorBracket::BracketStyle style) { - mBracketStyle = 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; + 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; + 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; + 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(QRectF(-mBracketWidth * 0.5, -mBracketHeight * 0.5, mBracketWidth, mBracketHeight), -90 * 16, -180 * 16 * direction); + break; + } + case bsEllipse: { + painter->drawEllipse(QRectF(-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; + } } - case bsHalfEllipse: - { - painter->drawArc(QRectF(-mBracketWidth*0.5, -mBracketHeight*0.5, mBracketWidth, mBracketHeight), -90*16, -180*16*direction); - break; - } - case bsEllipse: - { - painter->drawEllipse(QRectF(-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); + 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; i= 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; i < averageCount; ++i) { + points[i] = getPixelCoordinates(interface1d, currentIndex); + pointsAverage += points[i]; + currentIndex += direction; + } + pointsAverage /= double(averageCount); + + // calculate slope of linear regression through points: + double numSum = 0; + double denomSum = 0; + for (int i = 0; i < averageCount; ++i) { + const double dx = points.at(i).x() - pointsAverage.x(); + const double dy = points.at(i).y() - pointsAverage.y(); + numSum += dx * dy; + denomSum += dx * dx; + } + if (!qFuzzyIsNull(denomSum) && !qFuzzyIsNull(numSum)) { + return qAtan2(numSum, denomSum); + } else { // undetermined angle, probably mTangentAverage == 1, so using only one data point + return 0; + } } /*! \internal - + Returns the pixel coordinates of the data point at \a dataIndex, using \a interface1d to access the data points. */ QPointF QCPSelectionDecoratorBracket::getPixelCoordinates(const QCPPlottableInterface1D *interface1d, int dataIndex) const { - QCPAxis *keyAxis = mPlottable->keyAxis(); - QCPAxis *valueAxis = mPlottable->valueAxis(); - if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return {0, 0}; } - - if (keyAxis->orientation() == Qt::Horizontal) - return {keyAxis->coordToPixel(interface1d->dataMainKey(dataIndex)), valueAxis->coordToPixel(interface1d->dataMainValue(dataIndex))}; - else - return {valueAxis->coordToPixel(interface1d->dataMainValue(dataIndex)), keyAxis->coordToPixel(interface1d->dataMainKey(dataIndex))}; + QCPAxis *keyAxis = mPlottable->keyAxis(); + QCPAxis *valueAxis = mPlottable->valueAxis(); + if (!keyAxis || !valueAxis) { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + return {0, 0}; + } + + if (keyAxis->orientation() == Qt::Horizontal) + return {keyAxis->coordToPixel(interface1d->dataMainKey(dataIndex)), valueAxis->coordToPixel(interface1d->dataMainValue(dataIndex))}; + else + return {valueAxis->coordToPixel(interface1d->dataMainValue(dataIndex)), keyAxis->coordToPixel(interface1d->dataMainKey(dataIndex))}; } /* end of 'src/selectiondecorator-bracket.cpp' */ @@ -17410,36 +17483,36 @@ QPointF QCPSelectionDecoratorBracket::getPixelCoordinates(const QCPPlottableInte /*! \class QCPAxisRect \brief Holds multiple axes and arranges them in a rectangular shape. - + This class represents an axis rect, a rectangular area that is bounded on all sides with an arbitrary number of axes. - + Initially QCustomPlot has one axis rect, accessible via QCustomPlot::axisRect(). However, the layout system allows to have multiple axis rects, e.g. arranged in a grid layout (QCustomPlot::plotLayout). - + By default, QCPAxisRect comes with four axes, at bottom, top, left and right. They can be accessed via \ref axis by providing the respective axis type (\ref QCPAxis::AxisType) and index. If you need all axes in the axis rect, use \ref axes. The top and right axes are set to be invisible initially (QCPAxis::setVisible). To add more axes to a side, use \ref addAxis or \ref addAxes. To remove an axis, use \ref removeAxis. - + The axis rect layerable itself only draws a background pixmap or color, if specified (\ref setBackground). It is placed on the "background" layer initially (see \ref QCPLayer for an explanation of the QCustomPlot layer system). The axes that are held by the axis rect can be placed on other layers, independently of the axis rect. - + Every axis rect has a child layout of type \ref QCPLayoutInset. It is accessible via \ref insetLayout and can be used to have other layout elements (or even other layouts with multiple elements) hovering inside the axis rect. - + If an axis rect is clicked and dragged, it processes this by moving certain axis ranges. The behaviour can be controlled with \ref setRangeDrag and \ref setRangeDragAxes. If the mouse wheel is scrolled while the cursor is on the axis rect, certain axes are scaled. This is controllable via \ref setRangeZoom, \ref setRangeZoomAxes and \ref setRangeZoomFactor. These interactions are only enabled if \ref QCustomPlot::setInteractions contains \ref QCP::iRangeDrag and \ref QCP::iRangeZoom. - + \image html AxisRectSpacingOverview.png
Overview of the spacings and paddings that define the geometry of an axis. The dashed line on the far left indicates the viewport/widget border.
@@ -17448,81 +17521,81 @@ QPointF QCPSelectionDecoratorBracket::getPixelCoordinates(const QCPPlottableInte /* start documentation of inline functions */ /*! \fn QCPLayoutInset *QCPAxisRect::insetLayout() const - + Returns the inset layout of this axis rect. It can be used to place other layout elements (or even layouts with multiple other elements) inside/on top of an axis rect. - + \see QCPLayoutInset */ /*! \fn int QCPAxisRect::left() const - + Returns the pixel position of the left border of this axis rect. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn int QCPAxisRect::right() const - + Returns the pixel position of the right border of this axis rect. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn int QCPAxisRect::top() const - + Returns the pixel position of the top border of this axis rect. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn int QCPAxisRect::bottom() const - + Returns the pixel position of the bottom border of this axis rect. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn int QCPAxisRect::width() const - + Returns the pixel width of this axis rect. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn int QCPAxisRect::height() const - + Returns the pixel height of this axis rect. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn QSize QCPAxisRect::size() const - + Returns the pixel size of this axis rect. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn QPoint QCPAxisRect::topLeft() const - + Returns the top left corner of this axis rect in pixels. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn QPoint QCPAxisRect::topRight() const - + Returns the top right corner of this axis rect in pixels. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn QPoint QCPAxisRect::bottomLeft() const - + Returns the bottom left corner of this axis rect in pixels. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn QPoint QCPAxisRect::bottomRight() const - + Returns the bottom right corner of this axis rect in pixels. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn QPoint QCPAxisRect::center() const - + Returns the center of this axis rect in pixels. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ @@ -17534,122 +17607,123 @@ QPointF QCPSelectionDecoratorBracket::getPixelCoordinates(const QCPPlottableInte sides, the top and right axes are set invisible initially. */ QCPAxisRect::QCPAxisRect(QCustomPlot *parentPlot, bool setupDefaultAxes) : - QCPLayoutElement(parentPlot), - mBackgroundBrush(Qt::NoBrush), - mBackgroundScaled(true), - mBackgroundScaledMode(Qt::KeepAspectRatioByExpanding), - mInsetLayout(new QCPLayoutInset), - mRangeDrag(Qt::Horizontal|Qt::Vertical), - mRangeZoom(Qt::Horizontal|Qt::Vertical), - mRangeZoomFactorHorz(0.85), - mRangeZoomFactorVert(0.85), - mDragging(false) + QCPLayoutElement(parentPlot), + mBackgroundBrush(Qt::NoBrush), + mBackgroundScaled(true), + mBackgroundScaledMode(Qt::KeepAspectRatioByExpanding), + mInsetLayout(new QCPLayoutInset), + mRangeDrag(Qt::Horizontal | Qt::Vertical), + mRangeZoom(Qt::Horizontal | Qt::Vertical), + mRangeZoomFactorHorz(0.85), + mRangeZoomFactorVert(0.85), + mDragging(false) { - mInsetLayout->initializeParentPlot(mParentPlot); - mInsetLayout->setParentLayerable(this); - mInsetLayout->setParent(this); - - setMinimumSize(50, 50); - setMinimumMargins(QMargins(15, 15, 15, 15)); - mAxes.insert(QCPAxis::atLeft, QList()); - mAxes.insert(QCPAxis::atRight, QList()); - mAxes.insert(QCPAxis::atTop, QList()); - mAxes.insert(QCPAxis::atBottom, QList()); - - if (setupDefaultAxes) - { - QCPAxis *xAxis = addAxis(QCPAxis::atBottom); - QCPAxis *yAxis = addAxis(QCPAxis::atLeft); - QCPAxis *xAxis2 = addAxis(QCPAxis::atTop); - QCPAxis *yAxis2 = addAxis(QCPAxis::atRight); - setRangeDragAxes(xAxis, yAxis); - setRangeZoomAxes(xAxis, yAxis); - xAxis2->setVisible(false); - yAxis2->setVisible(false); - xAxis->grid()->setVisible(true); - yAxis->grid()->setVisible(true); - xAxis2->grid()->setVisible(false); - yAxis2->grid()->setVisible(false); - xAxis2->grid()->setZeroLinePen(Qt::NoPen); - yAxis2->grid()->setZeroLinePen(Qt::NoPen); - xAxis2->grid()->setVisible(false); - yAxis2->grid()->setVisible(false); - } + mInsetLayout->initializeParentPlot(mParentPlot); + mInsetLayout->setParentLayerable(this); + mInsetLayout->setParent(this); + + setMinimumSize(50, 50); + setMinimumMargins(QMargins(15, 15, 15, 15)); + mAxes.insert(QCPAxis::atLeft, QList()); + mAxes.insert(QCPAxis::atRight, QList()); + mAxes.insert(QCPAxis::atTop, QList()); + mAxes.insert(QCPAxis::atBottom, QList()); + + if (setupDefaultAxes) { + QCPAxis *xAxis = addAxis(QCPAxis::atBottom); + QCPAxis *yAxis = addAxis(QCPAxis::atLeft); + QCPAxis *xAxis2 = addAxis(QCPAxis::atTop); + QCPAxis *yAxis2 = addAxis(QCPAxis::atRight); + setRangeDragAxes(xAxis, yAxis); + setRangeZoomAxes(xAxis, yAxis); + xAxis2->setVisible(false); + yAxis2->setVisible(false); + xAxis->grid()->setVisible(true); + yAxis->grid()->setVisible(true); + xAxis2->grid()->setVisible(false); + yAxis2->grid()->setVisible(false); + xAxis2->grid()->setZeroLinePen(Qt::NoPen); + yAxis2->grid()->setZeroLinePen(Qt::NoPen); + xAxis2->grid()->setVisible(false); + yAxis2->grid()->setVisible(false); + } } QCPAxisRect::~QCPAxisRect() { - delete mInsetLayout; - mInsetLayout = nullptr; - - foreach (QCPAxis *axis, axes()) - removeAxis(axis); + delete mInsetLayout; + mInsetLayout = nullptr; + + foreach (QCPAxis *axis, axes()) { + removeAxis(axis); + } } /*! Returns the number of axes on the axis rect side specified with \a type. - + \see axis */ int QCPAxisRect::axisCount(QCPAxis::AxisType type) const { - return mAxes.value(type).size(); + return mAxes.value(type).size(); } /*! Returns the axis with the given \a index on the axis rect side specified with \a type. - + \see axisCount, axes */ QCPAxis *QCPAxisRect::axis(QCPAxis::AxisType type, int index) const { - QList ax(mAxes.value(type)); - if (index >= 0 && index < ax.size()) - { - return ax.at(index); - } else - { - qDebug() << Q_FUNC_INFO << "Axis index out of bounds:" << index; - return nullptr; - } + QList ax(mAxes.value(type)); + if (index >= 0 && index < ax.size()) { + return ax.at(index); + } else { + qDebug() << Q_FUNC_INFO << "Axis index out of bounds:" << index; + return nullptr; + } } /*! Returns all axes on the axis rect sides specified with \a types. - + \a types may be a single \ref QCPAxis::AxisType or an or-combination, to get the axes of multiple sides. - + \see axis */ -QList QCPAxisRect::axes(QCPAxis::AxisTypes types) const +QList QCPAxisRect::axes(QCPAxis::AxisTypes types) const { - QList result; - if (types.testFlag(QCPAxis::atLeft)) - result << mAxes.value(QCPAxis::atLeft); - if (types.testFlag(QCPAxis::atRight)) - result << mAxes.value(QCPAxis::atRight); - if (types.testFlag(QCPAxis::atTop)) - result << mAxes.value(QCPAxis::atTop); - if (types.testFlag(QCPAxis::atBottom)) - result << mAxes.value(QCPAxis::atBottom); - return result; + QList result; + if (types.testFlag(QCPAxis::atLeft)) { + result << mAxes.value(QCPAxis::atLeft); + } + if (types.testFlag(QCPAxis::atRight)) { + result << mAxes.value(QCPAxis::atRight); + } + if (types.testFlag(QCPAxis::atTop)) { + result << mAxes.value(QCPAxis::atTop); + } + if (types.testFlag(QCPAxis::atBottom)) { + result << mAxes.value(QCPAxis::atBottom); + } + return result; } /*! \overload - + Returns all axes of this axis rect. */ -QList QCPAxisRect::axes() const +QList QCPAxisRect::axes() const { - QList result; - QHashIterator > it(mAxes); - while (it.hasNext()) - { - it.next(); - result << it.value(); - } - return result; + QList result; + QHashIterator > it(mAxes); + while (it.hasNext()) { + it.next(); + result << it.value(); + } + return result; } /*! @@ -17674,100 +17748,116 @@ QList QCPAxisRect::axes() const */ QCPAxis *QCPAxisRect::addAxis(QCPAxis::AxisType type, QCPAxis *axis) { - QCPAxis *newAxis = axis; - if (!newAxis) - { - newAxis = new QCPAxis(this, type); - } else // user provided existing axis instance, do some sanity checks - { - if (newAxis->axisType() != type) - { - qDebug() << Q_FUNC_INFO << "passed axis has different axis type than specified in type parameter"; - return nullptr; + QCPAxis *newAxis = axis; + if (!newAxis) { + newAxis = new QCPAxis(this, type); + } else { // user provided existing axis instance, do some sanity checks + if (newAxis->axisType() != type) { + qDebug() << Q_FUNC_INFO << "passed axis has different axis type than specified in type parameter"; + return nullptr; + } + if (newAxis->axisRect() != this) { + qDebug() << Q_FUNC_INFO << "passed axis doesn't have this axis rect as parent axis rect"; + return nullptr; + } + if (axes().contains(newAxis)) { + qDebug() << Q_FUNC_INFO << "passed axis is already owned by this axis rect"; + return nullptr; + } } - if (newAxis->axisRect() != this) - { - qDebug() << Q_FUNC_INFO << "passed axis doesn't have this axis rect as parent axis rect"; - return nullptr; + if (!mAxes[type].isEmpty()) { // multiple axes on one side, add half-bar axis ending to additional axes with offset + bool invert = (type == QCPAxis::atRight) || (type == QCPAxis::atBottom); + newAxis->setLowerEnding(QCPLineEnding(QCPLineEnding::esHalfBar, 6, 10, !invert)); + newAxis->setUpperEnding(QCPLineEnding(QCPLineEnding::esHalfBar, 6, 10, invert)); } - if (axes().contains(newAxis)) - { - qDebug() << Q_FUNC_INFO << "passed axis is already owned by this axis rect"; - return nullptr; + 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; + } + } } - } - if (!mAxes[type].isEmpty()) // multiple axes on one side, add half-bar axis ending to additional axes with offset - { - bool invert = (type == QCPAxis::atRight) || (type == QCPAxis::atBottom); - newAxis->setLowerEnding(QCPLineEnding(QCPLineEnding::esHalfBar, 6, 10, !invert)); - 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; + + return newAxis; } /*! Adds a new axis with \ref addAxis to each axis rect side specified in \a types. This may be an or-combination of QCPAxis::AxisType, so axes can be added to multiple sides at once. - + Returns a list of the added axes. - + \see addAxis, setupFullAxesBox */ -QList QCPAxisRect::addAxes(QCPAxis::AxisTypes types) +QList QCPAxisRect::addAxes(QCPAxis::AxisTypes types) { - QList result; - if (types.testFlag(QCPAxis::atLeft)) - result << addAxis(QCPAxis::atLeft); - if (types.testFlag(QCPAxis::atRight)) - result << addAxis(QCPAxis::atRight); - if (types.testFlag(QCPAxis::atTop)) - result << addAxis(QCPAxis::atTop); - if (types.testFlag(QCPAxis::atBottom)) - result << addAxis(QCPAxis::atBottom); - return result; + QList result; + if (types.testFlag(QCPAxis::atLeft)) { + result << addAxis(QCPAxis::atLeft); + } + if (types.testFlag(QCPAxis::atRight)) { + result << addAxis(QCPAxis::atRight); + } + if (types.testFlag(QCPAxis::atTop)) { + result << addAxis(QCPAxis::atTop); + } + if (types.testFlag(QCPAxis::atBottom)) { + result << addAxis(QCPAxis::atBottom); + } + return result; } /*! Removes the specified \a axis from the axis rect and deletes it. - + Returns true on success, i.e. if \a axis was a valid axis in this axis rect. - + \see addAxis */ bool QCPAxisRect::removeAxis(QCPAxis *axis) { - // don't access axis->axisType() to provide safety when axis is an invalid pointer, rather go through all axis containers: - QHashIterator > it(mAxes); - while (it.hasNext()) - { - it.next(); - if (it.value().contains(axis)) - { - if (it.value().first() == axis && it.value().size() > 1) // if removing first axis, transfer axis offset to the new first axis (which at this point is the second axis, if it exists) - it.value()[1]->setOffset(axis->offset()); - mAxes[it.key()].removeOne(axis); - if (qobject_cast(parentPlot())) // make sure this isn't called from QObject dtor when QCustomPlot is already destructed (happens when the axis rect is not in any layout and thus QObject-child of QCustomPlot) - parentPlot()->axisRemoved(axis); - delete axis; - return true; + // don't access axis->axisType() to provide safety when axis is an invalid pointer, rather go through all axis containers: + QHashIterator > it(mAxes); + while (it.hasNext()) { + it.next(); + if (it.value().contains(axis)) { + if (it.value().first() == axis && it.value().size() > 1) { // if removing first axis, transfer axis offset to the new first axis (which at this point is the second axis, if it exists) + it.value()[1]->setOffset(axis->offset()); + } + mAxes[it.key()].removeOne(axis); + if (qobject_cast(parentPlot())) { // make sure this isn't called from QObject dtor when QCustomPlot is already destructed (happens when the axis rect is not in any layout and thus QObject-child of QCustomPlot) + parentPlot()->axisRemoved(axis); + } + delete axis; + return true; + } } - } - qDebug() << Q_FUNC_INFO << "Axis isn't in axis rect:" << reinterpret_cast(axis); - return false; + qDebug() << Q_FUNC_INFO << "Axis isn't in axis rect:" << reinterpret_cast(axis); + return false; } /*! @@ -17775,38 +17865,37 @@ bool QCPAxisRect::removeAxis(QCPAxis *axis) 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()); + 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) +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; + 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)); } - 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)); - } } /*! @@ -17830,192 +17919,190 @@ void QCPAxisRect::zoom(const QRectF &pixelRect, const QList &affectedA */ void QCPAxisRect::setupFullAxesBox(bool connectRanges) { - QCPAxis *xAxis, *yAxis, *xAxis2, *yAxis2; - if (axisCount(QCPAxis::atBottom) == 0) - xAxis = addAxis(QCPAxis::atBottom); - else - xAxis = axis(QCPAxis::atBottom); - - if (axisCount(QCPAxis::atLeft) == 0) - yAxis = addAxis(QCPAxis::atLeft); - else - yAxis = axis(QCPAxis::atLeft); - - if (axisCount(QCPAxis::atTop) == 0) - xAxis2 = addAxis(QCPAxis::atTop); - else - xAxis2 = axis(QCPAxis::atTop); - - if (axisCount(QCPAxis::atRight) == 0) - yAxis2 = addAxis(QCPAxis::atRight); - else - yAxis2 = axis(QCPAxis::atRight); - - xAxis->setVisible(true); - yAxis->setVisible(true); - xAxis2->setVisible(true); - yAxis2->setVisible(true); - xAxis2->setTickLabels(false); - yAxis2->setTickLabels(false); - - xAxis2->setRange(xAxis->range()); - xAxis2->setRangeReversed(xAxis->rangeReversed()); - xAxis2->setScaleType(xAxis->scaleType()); - xAxis2->setTicks(xAxis->ticks()); - xAxis2->setNumberFormat(xAxis->numberFormat()); - xAxis2->setNumberPrecision(xAxis->numberPrecision()); - 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->setTicks(yAxis->ticks()); - yAxis2->setNumberFormat(yAxis->numberFormat()); - yAxis2->setNumberPrecision(yAxis->numberPrecision()); - yAxis2->ticker()->setTickCount(yAxis->ticker()->tickCount()); - yAxis2->ticker()->setTickOrigin(yAxis->ticker()->tickOrigin()); - - if (connectRanges) - { - connect(xAxis, SIGNAL(rangeChanged(QCPRange)), xAxis2, SLOT(setRange(QCPRange))); - connect(yAxis, SIGNAL(rangeChanged(QCPRange)), yAxis2, SLOT(setRange(QCPRange))); - } + QCPAxis *xAxis, *yAxis, *xAxis2, *yAxis2; + if (axisCount(QCPAxis::atBottom) == 0) { + xAxis = addAxis(QCPAxis::atBottom); + } else { + xAxis = axis(QCPAxis::atBottom); + } + + if (axisCount(QCPAxis::atLeft) == 0) { + yAxis = addAxis(QCPAxis::atLeft); + } else { + yAxis = axis(QCPAxis::atLeft); + } + + if (axisCount(QCPAxis::atTop) == 0) { + xAxis2 = addAxis(QCPAxis::atTop); + } else { + xAxis2 = axis(QCPAxis::atTop); + } + + if (axisCount(QCPAxis::atRight) == 0) { + yAxis2 = addAxis(QCPAxis::atRight); + } else { + yAxis2 = axis(QCPAxis::atRight); + } + + xAxis->setVisible(true); + yAxis->setVisible(true); + xAxis2->setVisible(true); + yAxis2->setVisible(true); + xAxis2->setTickLabels(false); + yAxis2->setTickLabels(false); + + xAxis2->setRange(xAxis->range()); + xAxis2->setRangeReversed(xAxis->rangeReversed()); + xAxis2->setScaleType(xAxis->scaleType()); + xAxis2->setTicks(xAxis->ticks()); + xAxis2->setNumberFormat(xAxis->numberFormat()); + xAxis2->setNumberPrecision(xAxis->numberPrecision()); + 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->setTicks(yAxis->ticks()); + yAxis2->setNumberFormat(yAxis->numberFormat()); + yAxis2->setNumberPrecision(yAxis->numberPrecision()); + yAxis2->ticker()->setTickCount(yAxis->ticker()->tickCount()); + yAxis2->ticker()->setTickOrigin(yAxis->ticker()->tickOrigin()); + + if (connectRanges) { + connect(xAxis, SIGNAL(rangeChanged(QCPRange)), xAxis2, SLOT(setRange(QCPRange))); + connect(yAxis, SIGNAL(rangeChanged(QCPRange)), yAxis2, SLOT(setRange(QCPRange))); + } } /*! Returns a list of all the plottables that are associated with this axis rect. - + A plottable is considered associated with an axis rect if its key or value axis (or both) is in this axis rect. - + \see graphs, items */ -QList QCPAxisRect::plottables() const +QList QCPAxisRect::plottables() const { - // Note: don't append all QCPAxis::plottables() into a list, because we might get duplicate entries - QList result; - foreach (QCPAbstractPlottable *plottable, mParentPlot->mPlottables) - { - if (plottable->keyAxis()->axisRect() == this || plottable->valueAxis()->axisRect() == this) - result.append(plottable); - } - return result; + // Note: don't append all QCPAxis::plottables() into a list, because we might get duplicate entries + QList result; + foreach (QCPAbstractPlottable *plottable, mParentPlot->mPlottables) { + if (plottable->keyAxis()->axisRect() == this || plottable->valueAxis()->axisRect() == this) { + result.append(plottable); + } + } + return result; } /*! Returns a list of all the graphs that are associated with this axis rect. - + A graph is considered associated with an axis rect if its key or value axis (or both) is in this axis rect. - + \see plottables, items */ -QList QCPAxisRect::graphs() const +QList QCPAxisRect::graphs() const { - // Note: don't append all QCPAxis::graphs() into a list, because we might get duplicate entries - QList result; - foreach (QCPGraph *graph, mParentPlot->mGraphs) - { - if (graph->keyAxis()->axisRect() == this || graph->valueAxis()->axisRect() == this) - result.append(graph); - } - return result; + // Note: don't append all QCPAxis::graphs() into a list, because we might get duplicate entries + QList result; + foreach (QCPGraph *graph, mParentPlot->mGraphs) { + if (graph->keyAxis()->axisRect() == this || graph->valueAxis()->axisRect() == this) { + result.append(graph); + } + } + return result; } /*! Returns a list of all the items that are associated with this axis rect. - + An item is considered associated with an axis rect if any of its positions has key or value axis set to an axis that is in this axis rect, or if any of its positions has \ref QCPItemPosition::setAxisRect set to the axis rect, or if the clip axis rect (\ref QCPAbstractItem::setClipAxisRect) is set to this axis rect. - + \see plottables, graphs */ QList QCPAxisRect::items() const { - // Note: don't just append all QCPAxis::items() into a list, because we might get duplicate entries - // and miss those items that have this axis rect as clipAxisRect. - QList result; - foreach (QCPAbstractItem *item, mParentPlot->mItems) - { - if (item->clipAxisRect() == this) - { - result.append(item); - continue; + // Note: don't just append all QCPAxis::items() into a list, because we might get duplicate entries + // and miss those items that have this axis rect as clipAxisRect. + QList result; + foreach (QCPAbstractItem *item, mParentPlot->mItems) { + if (item->clipAxisRect() == this) { + result.append(item); + continue; + } + foreach (QCPItemPosition *position, item->positions()) { + if (position->axisRect() == this || + position->keyAxis()->axisRect() == this || + position->valueAxis()->axisRect() == this) { + result.append(item); + break; + } + } } - foreach (QCPItemPosition *position, item->positions()) - { - if (position->axisRect() == this || - position->keyAxis()->axisRect() == this || - position->valueAxis()->axisRect() == this) - { - result.append(item); - break; - } - } - } - return result; + return result; } /*! This method is called automatically upon replot and doesn't need to be called by users of QCPAxisRect. - + 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) { - QCPLayoutElement::update(phase); - - switch (phase) - { - case upPreparation: - { - foreach (QCPAxis *axis, axes()) - axis->setupTickVectors(); - break; + QCPLayoutElement::update(phase); + + switch (phase) { + case upPreparation: { + foreach (QCPAxis *axis, axes()) { + axis->setupTickVectors(); + } + break; + } + case upLayout: { + mInsetLayout->setOuterRect(rect()); + break; + } + default: + break; } - case upLayout: - { - mInsetLayout->setOuterRect(rect()); - break; - } - default: break; - } - - // pass update call on to inset layout (doesn't happen automatically, because QCPAxisRect doesn't derive from QCPLayout): - mInsetLayout->update(phase); + + // pass update call on to inset layout (doesn't happen automatically, because QCPAxisRect doesn't derive from QCPLayout): + mInsetLayout->update(phase); } /* inherits documentation from base class */ -QList QCPAxisRect::elements(bool recursive) const +QList QCPAxisRect::elements(bool recursive) const { - QList result; - if (mInsetLayout) - { - result << mInsetLayout; - if (recursive) - result << mInsetLayout->elements(recursive); - } - return result; + QList result; + if (mInsetLayout) { + result << mInsetLayout; + if (recursive) { + result << mInsetLayout->elements(recursive); + } + } + return result; } /* inherits documentation from base class */ void QCPAxisRect::applyDefaultAntialiasingHint(QCPPainter *painter) const { - painter->setAntialiasing(false); + painter->setAntialiasing(false); } /* inherits documentation from base class */ void QCPAxisRect::draw(QCPPainter *painter) { - drawBackground(painter); + drawBackground(painter); } /*! @@ -18030,17 +18117,17 @@ void QCPAxisRect::draw(QCPPainter *painter) Below the pixmap, the axis rect may be optionally filled with a brush, if specified with \ref setBackground(const QBrush &brush). - + \see setBackgroundScaled, setBackgroundScaledMode, setBackground(const QBrush &brush) */ void QCPAxisRect::setBackground(const QPixmap &pm) { - mBackgroundPixmap = pm; - mScaledBackgroundPixmap = QPixmap(); + mBackgroundPixmap = pm; + mScaledBackgroundPixmap = QPixmap(); } /*! \overload - + Sets \a brush as the background brush. The axis rect background will be filled with this brush. Since axis rects place themselves on the "background" layer by default, the axis rect backgrounds are usually drawn below everything else. @@ -18049,16 +18136,16 @@ void QCPAxisRect::setBackground(const QPixmap &pm) setBackground(const QPixmap &pm). To disable drawing of a background brush, set \a brush to Qt::NoBrush. - + \see setBackground(const QPixmap &pm) */ void QCPAxisRect::setBackground(const QBrush &brush) { - mBackgroundBrush = brush; + mBackgroundBrush = brush; } /*! \overload - + Allows setting the background pixmap of the axis rect, whether it shall be scaled and how it shall be scaled in one call. @@ -18066,25 +18153,25 @@ void QCPAxisRect::setBackground(const QBrush &brush) */ void QCPAxisRect::setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode) { - mBackgroundPixmap = pm; - mScaledBackgroundPixmap = QPixmap(); - mBackgroundScaled = scaled; - mBackgroundScaledMode = mode; + mBackgroundPixmap = pm; + mScaledBackgroundPixmap = QPixmap(); + mBackgroundScaled = scaled; + mBackgroundScaledMode = mode; } /*! Sets whether the axis background pixmap shall be scaled to fit the axis rect or not. If \a scaled is set to true, you may control whether and how the aspect ratio of the original pixmap is preserved with \ref setBackgroundScaledMode. - + Note that the scaled version of the original pixmap is buffered, so there is no performance penalty on replots. (Except when the axis rect dimensions are changed continuously.) - + \see setBackground, setBackgroundScaledMode */ void QCPAxisRect::setBackgroundScaled(bool scaled) { - mBackgroundScaled = scaled; + mBackgroundScaled = scaled; } /*! @@ -18094,7 +18181,7 @@ void QCPAxisRect::setBackgroundScaled(bool scaled) */ void QCPAxisRect::setBackgroundScaledMode(Qt::AspectRatioMode mode) { - mBackgroundScaledMode = mode; + mBackgroundScaledMode = mode; } /*! @@ -18105,10 +18192,11 @@ void QCPAxisRect::setBackgroundScaledMode(Qt::AspectRatioMode mode) */ QCPAxis *QCPAxisRect::rangeDragAxis(Qt::Orientation orientation) { - if (orientation == Qt::Horizontal) - return mRangeDragHorzAxis.isEmpty() ? nullptr : mRangeDragHorzAxis.first().data(); - else - return mRangeDragVertAxis.isEmpty() ? nullptr : mRangeDragVertAxis.first().data(); + if (orientation == Qt::Horizontal) { + return mRangeDragHorzAxis.isEmpty() ? nullptr : mRangeDragHorzAxis.first().data(); + } else { + return mRangeDragVertAxis.isEmpty() ? nullptr : mRangeDragVertAxis.first().data(); + } } /*! @@ -18119,10 +18207,11 @@ QCPAxis *QCPAxisRect::rangeDragAxis(Qt::Orientation orientation) */ QCPAxis *QCPAxisRect::rangeZoomAxis(Qt::Orientation orientation) { - if (orientation == Qt::Horizontal) - return mRangeZoomHorzAxis.isEmpty() ? nullptr : mRangeZoomHorzAxis.first().data(); - else - return mRangeZoomVertAxis.isEmpty() ? nullptr : mRangeZoomVertAxis.first().data(); + if (orientation == Qt::Horizontal) { + return mRangeZoomHorzAxis.isEmpty() ? nullptr : mRangeZoomHorzAxis.first().data(); + } else { + return mRangeZoomVertAxis.isEmpty() ? nullptr : mRangeZoomVertAxis.first().data(); + } } /*! @@ -18130,25 +18219,23 @@ QCPAxis *QCPAxisRect::rangeZoomAxis(Qt::Orientation orientation) \see rangeZoomAxis, setRangeZoomAxes */ -QList QCPAxisRect::rangeDragAxes(Qt::Orientation orientation) +QList QCPAxisRect::rangeDragAxes(Qt::Orientation orientation) { - QList result; - if (orientation == Qt::Horizontal) - { - foreach (QPointer axis, mRangeDragHorzAxis) - { - if (!axis.isNull()) - result.append(axis.data()); + QList result; + if (orientation == Qt::Horizontal) { + foreach (QPointer axis, mRangeDragHorzAxis) { + if (!axis.isNull()) { + result.append(axis.data()); + } + } + } else { + foreach (QPointer axis, mRangeDragVertAxis) { + if (!axis.isNull()) { + result.append(axis.data()); + } + } } - } else - { - foreach (QPointer axis, mRangeDragVertAxis) - { - if (!axis.isNull()) - result.append(axis.data()); - } - } - return result; + return result; } /*! @@ -18156,35 +18243,33 @@ QList QCPAxisRect::rangeDragAxes(Qt::Orientation orientation) \see rangeDragAxis, setRangeDragAxes */ -QList QCPAxisRect::rangeZoomAxes(Qt::Orientation orientation) +QList QCPAxisRect::rangeZoomAxes(Qt::Orientation orientation) { - QList result; - if (orientation == Qt::Horizontal) - { - foreach (QPointer axis, mRangeZoomHorzAxis) - { - if (!axis.isNull()) - result.append(axis.data()); + QList result; + if (orientation == Qt::Horizontal) { + foreach (QPointer axis, mRangeZoomHorzAxis) { + if (!axis.isNull()) { + result.append(axis.data()); + } + } + } else { + foreach (QPointer axis, mRangeZoomVertAxis) { + if (!axis.isNull()) { + result.append(axis.data()); + } + } } - } else - { - foreach (QPointer axis, mRangeZoomVertAxis) - { - if (!axis.isNull()) - result.append(axis.data()); - } - } - return result; + return result; } /*! Returns the range zoom factor of the \a orientation provided. - + \see setRangeZoomFactor */ double QCPAxisRect::rangeZoomFactor(Qt::Orientation orientation) { - return (orientation == Qt::Horizontal ? mRangeZoomFactorHorz : mRangeZoomFactorVert); + return (orientation == Qt::Horizontal ? mRangeZoomFactorHorz : mRangeZoomFactorVert); } /*! @@ -18193,19 +18278,19 @@ double QCPAxisRect::rangeZoomFactor(Qt::Orientation orientation) \ref setRangeDragAxes(QCPAxis *horizontal, QCPAxis *vertical). By default, the horizontal axis is the bottom axis (xAxis) and the vertical axis is the left axis (yAxis). - + To disable range dragging entirely, pass \c nullptr as \a orientations or remove \ref QCP::iRangeDrag from \ref QCustomPlot::setInteractions. To enable range dragging for both directions, pass Qt::Horizontal | Qt::Vertical as \a orientations. - + In addition to setting \a orientations to a non-zero value, make sure \ref QCustomPlot::setInteractions contains \ref QCP::iRangeDrag to enable the range dragging interaction. - + \see setRangeZoom, setRangeDragAxes, QCustomPlot::setNoAntialiasingOnDrag */ void QCPAxisRect::setRangeDrag(Qt::Orientations orientations) { - mRangeDrag = orientations; + mRangeDrag = orientations; } /*! @@ -18217,19 +18302,19 @@ void QCPAxisRect::setRangeDrag(Qt::Orientations orientations) To disable range zooming entirely, pass \c nullptr as \a orientations or remove \ref QCP::iRangeZoom from \ref QCustomPlot::setInteractions. To enable range zooming for both directions, pass Qt::Horizontal | Qt::Vertical as \a orientations. - + In addition to setting \a orientations to a non-zero value, make sure \ref QCustomPlot::setInteractions contains \ref QCP::iRangeZoom to enable the range zooming interaction. - + \see setRangeZoomFactor, setRangeZoomAxes, setRangeDrag */ void QCPAxisRect::setRangeZoom(Qt::Orientations orientations) { - mRangeZoom = orientations; + mRangeZoom = orientations; } /*! \overload - + Sets the axes whose range will be dragged when \ref setRangeDrag enables mouse range dragging on the QCustomPlot widget. Pass \c nullptr if no axis shall be dragged in the respective orientation. @@ -18241,12 +18326,14 @@ void QCPAxisRect::setRangeZoom(Qt::Orientations orientations) */ void QCPAxisRect::setRangeDragAxes(QCPAxis *horizontal, QCPAxis *vertical) { - QList horz, vert; - if (horizontal) - horz.append(horizontal); - if (vertical) - vert.append(vertical); - setRangeDragAxes(horz, vert); + QList horz, vert; + if (horizontal) { + horz.append(horizontal); + } + if (vertical) { + vert.append(vertical); + } + setRangeDragAxes(horz, vert); } /*! \overload @@ -18258,17 +18345,17 @@ void QCPAxisRect::setRangeDragAxes(QCPAxis *horizontal, QCPAxis *vertical) 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) +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); + QList horz, vert; + foreach (QCPAxis *ax, axes) { + if (ax->orientation() == Qt::Horizontal) { + horz.append(ax); + } else { + vert.append(ax); + } + } + setRangeDragAxes(horz, vert); } /*! \overload @@ -18277,26 +18364,26 @@ void QCPAxisRect::setRangeDragAxes(QList axes) define specifically which axis reacts to which drag orientation (irrespective of the axis orientation). */ -void QCPAxisRect::setRangeDragAxes(QList horizontal, QList vertical) +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); - } + 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); + } + } } /*! @@ -18313,12 +18400,14 @@ void QCPAxisRect::setRangeDragAxes(QList horizontal, QList v */ void QCPAxisRect::setRangeZoomAxes(QCPAxis *horizontal, QCPAxis *vertical) { - QList horz, vert; - if (horizontal) - horz.append(horizontal); - if (vertical) - vert.append(vertical); - setRangeZoomAxes(horz, vert); + QList horz, vert; + if (horizontal) { + horz.append(horizontal); + } + if (vertical) { + vert.append(vertical); + } + setRangeZoomAxes(horz, vert); } /*! \overload @@ -18330,17 +18419,17 @@ void QCPAxisRect::setRangeZoomAxes(QCPAxis *horizontal, QCPAxis *vertical) 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) +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); + QList horz, vert; + foreach (QCPAxis *ax, axes) { + if (ax->orientation() == Qt::Horizontal) { + horz.append(ax); + } else { + vert.append(ax); + } + } + setRangeZoomAxes(horz, vert); } /*! \overload @@ -18349,26 +18438,26 @@ void QCPAxisRect::setRangeZoomAxes(QList axes) define specifically which axis reacts to which zoom orientation (irrespective of the axis orientation). */ -void QCPAxisRect::setRangeZoomAxes(QList horizontal, QList vertical) +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); - } + 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); + } + } } /*! @@ -18383,28 +18472,28 @@ void QCPAxisRect::setRangeZoomAxes(QList horizontal, QList v */ void QCPAxisRect::setRangeZoomFactor(double horizontalFactor, double verticalFactor) { - mRangeZoomFactorHorz = horizontalFactor; - mRangeZoomFactorVert = verticalFactor; + mRangeZoomFactorHorz = horizontalFactor; + mRangeZoomFactorVert = verticalFactor; } /*! \overload - + Sets both the horizontal and vertical zoom \a factor. */ void QCPAxisRect::setRangeZoomFactor(double factor) { - mRangeZoomFactorHorz = factor; - mRangeZoomFactorVert = factor; + mRangeZoomFactorHorz = factor; + mRangeZoomFactorVert = factor; } /*! \internal - + Draws the background of this axis rect. It may consist of a background fill (a QBrush) and a pixmap. - + If a brush was given via \ref setBackground(const QBrush &brush), this function first draws an according filling inside the axis rect with the provided \a painter. - + Then, if a pixmap was provided via \ref setBackground, this function buffers the scaled version depending on \ref setBackgroundScaled and \ref setBackgroundScaledMode and then draws it inside the axis rect with the provided \a painter. The scaled version is buffered in @@ -18412,227 +18501,224 @@ void QCPAxisRect::setRangeZoomFactor(double factor) the axis rect has changed in a way that requires a rescale of the background pixmap (this is dependent on the \ref setBackgroundScaledMode), or when a differend axis background pixmap was set. - + \see setBackground, setBackgroundScaled, setBackgroundScaledMode */ void QCPAxisRect::drawBackground(QCPPainter *painter) { - // draw background fill: - if (mBackgroundBrush != Qt::NoBrush) - painter->fillRect(mRect, mBackgroundBrush); - - // draw background pixmap (on top of fill, if brush specified): - if (!mBackgroundPixmap.isNull()) - { - if (mBackgroundScaled) - { - // check whether mScaledBackground needs to be updated: - QSize scaledSize(mBackgroundPixmap.size()); - scaledSize.scale(mRect.size(), mBackgroundScaledMode); - if (mScaledBackgroundPixmap.size() != scaledSize) - mScaledBackgroundPixmap = mBackgroundPixmap.scaled(mRect.size(), mBackgroundScaledMode, Qt::SmoothTransformation); - painter->drawPixmap(mRect.topLeft()+QPoint(0, -1), mScaledBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height()) & mScaledBackgroundPixmap.rect()); - } else - { - painter->drawPixmap(mRect.topLeft()+QPoint(0, -1), mBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height())); + // draw background fill: + if (mBackgroundBrush != Qt::NoBrush) { + painter->fillRect(mRect, mBackgroundBrush); + } + + // draw background pixmap (on top of fill, if brush specified): + if (!mBackgroundPixmap.isNull()) { + if (mBackgroundScaled) { + // check whether mScaledBackground needs to be updated: + QSize scaledSize(mBackgroundPixmap.size()); + scaledSize.scale(mRect.size(), mBackgroundScaledMode); + if (mScaledBackgroundPixmap.size() != scaledSize) { + mScaledBackgroundPixmap = mBackgroundPixmap.scaled(mRect.size(), mBackgroundScaledMode, Qt::SmoothTransformation); + } + painter->drawPixmap(mRect.topLeft() + QPoint(0, -1), mScaledBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height()) & mScaledBackgroundPixmap.rect()); + } else { + painter->drawPixmap(mRect.topLeft() + QPoint(0, -1), mBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height())); + } } - } } /*! \internal - + This function makes sure multiple axes on the side specified with \a type don't collide, but are distributed according to their respective space requirement (QCPAxis::calculateMargin). - + It does this by setting an appropriate offset (\ref QCPAxis::setOffset) on all axes except the one with index zero. - + This function is called by \ref calculateAutoMargin. */ void QCPAxisRect::updateAxesOffset(QCPAxis::AxisType type) { - const QList axesList = mAxes.value(type); - if (axesList.isEmpty()) - return; - - bool isFirstVisible = !axesList.first()->visible(); // if the first axis is visible, the second axis (which is where the loop starts) isn't the first visible axis, so initialize with false - for (int i=1; ioffset() + axesList.at(i-1)->calculateMargin(); - if (axesList.at(i)->visible()) // only add inner tick length to offset if this axis is visible and it's not the first visible one (might happen if true first axis is invisible) - { - if (!isFirstVisible) - offset += axesList.at(i)->tickLengthIn(); - isFirstVisible = false; + const QList axesList = mAxes.value(type); + if (axesList.isEmpty()) { + return; + } + + bool isFirstVisible = !axesList.first()->visible(); // if the first axis is visible, the second axis (which is where the loop starts) isn't the first visible axis, so initialize with false + for (int i = 1; i < axesList.size(); ++i) { + int offset = axesList.at(i - 1)->offset() + axesList.at(i - 1)->calculateMargin(); + if (axesList.at(i)->visible()) { // only add inner tick length to offset if this axis is visible and it's not the first visible one (might happen if true first axis is invisible) + if (!isFirstVisible) { + offset += axesList.at(i)->tickLengthIn(); + } + isFirstVisible = false; + } + axesList.at(i)->setOffset(offset); } - axesList.at(i)->setOffset(offset); - } } /* inherits documentation from base class */ int QCPAxisRect::calculateAutoMargin(QCP::MarginSide side) { - if (!mAutoMargins.testFlag(side)) - qDebug() << Q_FUNC_INFO << "Called with side that isn't specified as auto margin"; - - updateAxesOffset(QCPAxis::marginSideToAxisType(side)); - - // note: only need to look at the last (outer most) axis to determine the total margin, due to updateAxisOffset call - const QList axesList = mAxes.value(QCPAxis::marginSideToAxisType(side)); - if (!axesList.isEmpty()) - return axesList.last()->offset() + axesList.last()->calculateMargin(); - else - return 0; + if (!mAutoMargins.testFlag(side)) { + qDebug() << Q_FUNC_INFO << "Called with side that isn't specified as auto margin"; + } + + updateAxesOffset(QCPAxis::marginSideToAxisType(side)); + + // note: only need to look at the last (outer most) axis to determine the total margin, due to updateAxisOffset call + const QList axesList = mAxes.value(QCPAxis::marginSideToAxisType(side)); + if (!axesList.isEmpty()) { + return axesList.last()->offset() + axesList.last()->calculateMargin(); + } else { + 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); - } + if (mParentPlot && mParentPlot->axisRectCount() > 0 && mParentPlot->axisRect(0) == this) { + if (axisCount(QCPAxis::atBottom) > 0 && !mParentPlot->xAxis) { + mParentPlot->xAxis = axis(QCPAxis::atBottom); + } + if (axisCount(QCPAxis::atLeft) > 0 && !mParentPlot->yAxis) { + mParentPlot->yAxis = axis(QCPAxis::atLeft); + } + if (axisCount(QCPAxis::atTop) > 0 && !mParentPlot->xAxis2) { + mParentPlot->xAxis2 = axis(QCPAxis::atTop); + } + if (axisCount(QCPAxis::atRight) > 0 && !mParentPlot->yAxis2) { + mParentPlot->yAxis2 = axis(QCPAxis::atRight); + } + } } /*! \internal - + Event handler for when a mouse button is pressed on the axis rect. If the left mouse button is pressed, the range dragging interaction is initialized (the actual range manipulation happens in the \ref mouseMoveEvent). The mDragging flag is set to true and some anchor points are set that are needed to determine the distance the mouse was dragged in the mouse move/release events later. - + \see mouseMoveEvent, mouseReleaseEvent */ void QCPAxisRect::mousePressEvent(QMouseEvent *event, const QVariant &details) { - Q_UNUSED(details) - if (event->buttons() & Qt::LeftButton) - { - mDragging = true; - // initialize antialiasing backup in case we start dragging: - if (mParentPlot->noAntialiasingOnDrag()) - { - mAADragBackup = mParentPlot->antialiasedElements(); - mNotAADragBackup = mParentPlot->notAntialiasedElements(); + Q_UNUSED(details) + if (event->buttons() & Qt::LeftButton) { + mDragging = true; + // initialize antialiasing backup in case we start dragging: + if (mParentPlot->noAntialiasingOnDrag()) { + mAADragBackup = mParentPlot->antialiasedElements(); + mNotAADragBackup = mParentPlot->notAntialiasedElements(); + } + // Mouse range dragging interaction: + if (mParentPlot->interactions().testFlag(QCP::iRangeDrag)) { + mDragStartHorzRange.clear(); + foreach (QPointer axis, mRangeDragHorzAxis) { + mDragStartHorzRange.append(axis.isNull() ? QCPRange() : axis->range()); + } + mDragStartVertRange.clear(); + foreach (QPointer axis, mRangeDragVertAxis) { + mDragStartVertRange.append(axis.isNull() ? QCPRange() : axis->range()); + } + } } - // Mouse range dragging interaction: - if (mParentPlot->interactions().testFlag(QCP::iRangeDrag)) - { - mDragStartHorzRange.clear(); - foreach (QPointer axis, mRangeDragHorzAxis) - mDragStartHorzRange.append(axis.isNull() ? QCPRange() : axis->range()); - mDragStartVertRange.clear(); - foreach (QPointer axis, mRangeDragVertAxis) - mDragStartVertRange.append(axis.isNull() ? QCPRange() : axis->range()); - } - } } /*! \internal - + Event handler for when the mouse is moved on the axis rect. If range dragging was activated in a preceding \ref mousePressEvent, the range is moved accordingly. - + \see mousePressEvent, mouseReleaseEvent */ 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)) - { - for (int i=0; i= mDragStartHorzRange.size()) - break; - if (ax->mScaleType == QCPAxis::stLinear) - { - double diff = ax->pixelToCoord(startPos.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 = ax->pixelToCoord(startPos.x()) / ax->pixelToCoord(event->pos().x()); - ax->setRange(mDragStartHorzRange.at(i).lower*diff, mDragStartHorzRange.at(i).upper*diff); + Q_UNUSED(startPos) + // Mouse range dragging interaction: + if (mDragging && mParentPlot->interactions().testFlag(QCP::iRangeDrag)) { + + if (mRangeDrag.testFlag(Qt::Horizontal)) { + for (int i = 0; i < mRangeDragHorzAxis.size(); ++i) { + QCPAxis *ax = mRangeDragHorzAxis.at(i).data(); + if (!ax) { + continue; + } + if (i >= mDragStartHorzRange.size()) { + break; + } + if (ax->mScaleType == QCPAxis::stLinear) { + double diff = ax->pixelToCoord(startPos.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 = ax->pixelToCoord(startPos.x()) / ax->pixelToCoord(event->pos().x()); + ax->setRange(mDragStartHorzRange.at(i).lower * diff, mDragStartHorzRange.at(i).upper * diff); + } + } } - } - } - - if (mRangeDrag.testFlag(Qt::Vertical)) - { - for (int i=0; i= mDragStartVertRange.size()) - break; - if (ax->mScaleType == QCPAxis::stLinear) - { - double diff = ax->pixelToCoord(startPos.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 = ax->pixelToCoord(startPos.y()) / ax->pixelToCoord(event->pos().y()); - ax->setRange(mDragStartVertRange.at(i).lower*diff, mDragStartVertRange.at(i).upper*diff); + + if (mRangeDrag.testFlag(Qt::Vertical)) { + for (int i = 0; i < mRangeDragVertAxis.size(); ++i) { + QCPAxis *ax = mRangeDragVertAxis.at(i).data(); + if (!ax) { + continue; + } + if (i >= mDragStartVertRange.size()) { + break; + } + if (ax->mScaleType == QCPAxis::stLinear) { + double diff = ax->pixelToCoord(startPos.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 = ax->pixelToCoord(startPos.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(QCustomPlot::rpQueuedReplot); + } + } - - if (mRangeDrag != 0) // if either vertical or horizontal drag was enabled, do a replot - { - if (mParentPlot->noAntialiasingOnDrag()) - mParentPlot->setNotAntialiasedElements(QCP::aeAll); - mParentPlot->replot(QCustomPlot::rpQueuedReplot); - } - - } } /* inherits documentation from base class */ void QCPAxisRect::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos) { - Q_UNUSED(event) - Q_UNUSED(startPos) - mDragging = false; - if (mParentPlot->noAntialiasingOnDrag()) - { - mParentPlot->setAntialiasedElements(mAADragBackup); - mParentPlot->setNotAntialiasedElements(mNotAADragBackup); - } + Q_UNUSED(event) + Q_UNUSED(startPos) + mDragging = false; + if (mParentPlot->noAntialiasingOnDrag()) { + mParentPlot->setAntialiasedElements(mAADragBackup); + mParentPlot->setNotAntialiasedElements(mNotAADragBackup); + } } /*! \internal - + 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 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->angleDelta() is usually +/-120 for single rotation steps. However, if the mouse wheel is turned rapidly, many steps may bunch up to one event, so the delta may then be multiples of 120. This is taken into account here, by calculating \a wheelSteps and using it as exponent of @@ -18642,45 +18728,41 @@ void QCPAxisRect::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos) void QCPAxisRect::wheelEvent(QWheelEvent *event) { #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) - const double delta = event->delta(); + const double delta = event->delta(); #else - const double delta = event->angleDelta().y(); + const double delta = event->angleDelta().y(); #endif - + #if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) - const QPointF pos = event->pos(); + const QPointF pos = event->pos(); #else - const QPointF pos = event->position(); + const QPointF pos = event->position(); #endif - - // Mouse range zooming interaction: - if (mParentPlot->interactions().testFlag(QCP::iRangeZoom)) - { - if (mRangeZoom != 0) - { - double factor; - double wheelSteps = delta/120.0; // a single step delta is +/-120 usually - if (mRangeZoom.testFlag(Qt::Horizontal)) - { - factor = qPow(mRangeZoomFactorHorz, wheelSteps); - foreach (QPointer axis, mRangeZoomHorzAxis) - { - if (!axis.isNull()) - axis->scaleRange(factor, axis->pixelToCoord(pos.x())); + + // Mouse range zooming interaction: + if (mParentPlot->interactions().testFlag(QCP::iRangeZoom)) { + if (mRangeZoom != 0) { + double factor; + double wheelSteps = delta / 120.0; // a single step delta is +/-120 usually + if (mRangeZoom.testFlag(Qt::Horizontal)) { + factor = qPow(mRangeZoomFactorHorz, wheelSteps); + foreach (QPointer axis, mRangeZoomHorzAxis) { + if (!axis.isNull()) { + axis->scaleRange(factor, axis->pixelToCoord(pos.x())); + } + } + } + if (mRangeZoom.testFlag(Qt::Vertical)) { + factor = qPow(mRangeZoomFactorVert, wheelSteps); + foreach (QPointer axis, mRangeZoomVertAxis) { + if (!axis.isNull()) { + axis->scaleRange(factor, axis->pixelToCoord(pos.y())); + } + } + } + mParentPlot->replot(); } - } - if (mRangeZoom.testFlag(Qt::Vertical)) - { - factor = qPow(mRangeZoomFactorVert, wheelSteps); - foreach (QPointer axis, mRangeZoomVertAxis) - { - if (!axis.isNull()) - axis->scaleRange(factor, axis->pixelToCoord(pos.y())); - } - } - mParentPlot->replot(); } - } } /* end of 'src/layoutelements/layoutelement-axisrect.cpp' */ @@ -18694,16 +18776,16 @@ void QCPAxisRect::wheelEvent(QWheelEvent *event) /*! \class QCPAbstractLegendItem \brief The abstract base class for all entries in a QCPLegend. - + It defines a very basic interface for entries in a QCPLegend. For representing plottables in the legend, the subclass \ref QCPPlottableLegendItem is more suitable. - + Only derive directly from this class when you need absolute freedom (e.g. a custom legend entry that's not even associated with a plottable). You must implement the following pure virtual functions: \li \ref draw (from QCPLayerable) - + You inherit the following members you may use: @@ -18719,7 +18801,7 @@ void QCPAxisRect::wheelEvent(QWheelEvent *event) /* start of documentation of signals */ /*! \fn void QCPAbstractLegendItem::selectionChanged(bool selected) - + This signal is emitted when the selection state of this legend item has changed, either by user interaction or by a direct call to \ref setSelected. */ @@ -18731,142 +18813,144 @@ void QCPAxisRect::wheelEvent(QWheelEvent *event) cause the item to be added to \a parent, so \ref QCPLegend::addItem must be called separately. */ QCPAbstractLegendItem::QCPAbstractLegendItem(QCPLegend *parent) : - QCPLayoutElement(parent->parentPlot()), - mParentLegend(parent), - mFont(parent->font()), - mTextColor(parent->textColor()), - mSelectedFont(parent->selectedFont()), - mSelectedTextColor(parent->selectedTextColor()), - mSelectable(true), - mSelected(false) + QCPLayoutElement(parent->parentPlot()), + mParentLegend(parent), + mFont(parent->font()), + mTextColor(parent->textColor()), + mSelectedFont(parent->selectedFont()), + mSelectedTextColor(parent->selectedTextColor()), + mSelectable(true), + mSelected(false) { - setLayer(QLatin1String("legend")); - setMargins(QMargins(0, 0, 0, 0)); + setLayer(QLatin1String("legend")); + setMargins(QMargins(0, 0, 0, 0)); } /*! Sets the default font of this specific legend item to \a font. - + \see setTextColor, QCPLegend::setFont */ void QCPAbstractLegendItem::setFont(const QFont &font) { - mFont = font; + mFont = font; } /*! Sets the default text color of this specific legend item to \a color. - + \see setFont, QCPLegend::setTextColor */ void QCPAbstractLegendItem::setTextColor(const QColor &color) { - mTextColor = color; + mTextColor = color; } /*! When this legend item is selected, \a font is used to draw generic text, instead of the normal font set with \ref setFont. - + \see setFont, QCPLegend::setSelectedFont */ void QCPAbstractLegendItem::setSelectedFont(const QFont &font) { - mSelectedFont = font; + mSelectedFont = font; } /*! When this legend item is selected, \a color is used to draw generic text, instead of the normal color set with \ref setTextColor. - + \see setTextColor, QCPLegend::setSelectedTextColor */ void QCPAbstractLegendItem::setSelectedTextColor(const QColor &color) { - mSelectedTextColor = color; + mSelectedTextColor = color; } /*! Sets whether this specific legend item is selectable. - + \see setSelectedParts, QCustomPlot::setInteractions */ void QCPAbstractLegendItem::setSelectable(bool selectable) { - if (mSelectable != selectable) - { - mSelectable = selectable; - emit selectableChanged(mSelectable); - } + if (mSelectable != selectable) { + mSelectable = selectable; + emit selectableChanged(mSelectable); + } } /*! Sets whether this specific legend item is selected. - + It is possible to set the selection state of this item by calling this function directly, even if setSelectable is set to false. - + \see setSelectableParts, QCustomPlot::setInteractions */ void QCPAbstractLegendItem::setSelected(bool selected) { - if (mSelected != selected) - { - mSelected = selected; - emit selectionChanged(mSelected); - } + if (mSelected != selected) { + mSelected = selected; + emit selectionChanged(mSelected); + } } /* inherits documentation from base class */ double QCPAbstractLegendItem::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { - Q_UNUSED(details) - if (!mParentPlot) return -1; - if (onlySelectable && (!mSelectable || !mParentLegend->selectableParts().testFlag(QCPLegend::spItems))) - return -1; - - if (mRect.contains(pos.toPoint())) - return mParentPlot->selectionTolerance()*0.99; - else - return -1; + Q_UNUSED(details) + if (!mParentPlot) { + return -1; + } + if (onlySelectable && (!mSelectable || !mParentLegend->selectableParts().testFlag(QCPLegend::spItems))) { + return -1; + } + + if (mRect.contains(pos.toPoint())) { + return mParentPlot->selectionTolerance() * 0.99; + } else { + return -1; + } } /* inherits documentation from base class */ void QCPAbstractLegendItem::applyDefaultAntialiasingHint(QCPPainter *painter) const { - applyAntialiasingHint(painter, mAntialiased, QCP::aeLegendItems); + applyAntialiasingHint(painter, mAntialiased, QCP::aeLegendItems); } /* inherits documentation from base class */ QRect QCPAbstractLegendItem::clipRect() const { - return mOuterRect; + return mOuterRect; } /* inherits documentation from base class */ void QCPAbstractLegendItem::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) { - Q_UNUSED(event) - Q_UNUSED(details) - if (mSelectable && mParentLegend->selectableParts().testFlag(QCPLegend::spItems)) - { - bool selBefore = mSelected; - setSelected(additive ? !mSelected : true); - if (selectionStateChanged) - *selectionStateChanged = mSelected != selBefore; - } + Q_UNUSED(event) + Q_UNUSED(details) + if (mSelectable && mParentLegend->selectableParts().testFlag(QCPLegend::spItems)) { + bool selBefore = mSelected; + setSelected(additive ? !mSelected : true); + if (selectionStateChanged) { + *selectionStateChanged = mSelected != selBefore; + } + } } /* inherits documentation from base class */ void QCPAbstractLegendItem::deselectEvent(bool *selectionStateChanged) { - if (mSelectable && mParentLegend->selectableParts().testFlag(QCPLegend::spItems)) - { - bool selBefore = mSelected; - setSelected(false); - if (selectionStateChanged) - *selectionStateChanged = mSelected != selBefore; - } + if (mSelectable && mParentLegend->selectableParts().testFlag(QCPLegend::spItems)) { + bool selBefore = mSelected; + setSelected(false); + if (selectionStateChanged) { + *selectionStateChanged = mSelected != selBefore; + } + } } //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -18875,13 +18959,13 @@ void QCPAbstractLegendItem::deselectEvent(bool *selectionStateChanged) /*! \class QCPPlottableLegendItem \brief A legend item representing a plottable with an icon and the plottable name. - + This is the standard legend item for plottables. It displays an icon of the plottable next to the plottable name. The icon is drawn by the respective plottable itself (\ref QCPAbstractPlottable::drawLegendIcon), and tries to give an intuitive symbol for the plottable. For example, the QCPGraph draws a centered horizontal line and/or a single scatter point in the middle. - + Legend items of this type are always associated with one plottable (retrievable via the plottable() function and settable with the constructor). You may change the font of the plottable name with \ref setFont. Icon padding and border pen is taken from the parent QCPLegend, see \ref @@ -18889,7 +18973,7 @@ void QCPAbstractLegendItem::deselectEvent(bool *selectionStateChanged) The function \ref QCPAbstractPlottable::addToLegend/\ref QCPAbstractPlottable::removeFromLegend creates/removes legend items of this type. - + Since QCPLegend is based on QCPLayoutGrid, a legend item itself is just a subclass of QCPLayoutElement. While it could be added to a legend (or any other layout) via the normal layout interface, QCPLegend has specialized functions for handling legend items conveniently, see the @@ -18898,101 +18982,103 @@ void QCPAbstractLegendItem::deselectEvent(bool *selectionStateChanged) /*! Creates a new legend item associated with \a plottable. - + Once it's created, it can be added to the legend via \ref QCPLegend::addItem. - + A more convenient way of adding/removing a plottable to/from the legend is via the functions \ref QCPAbstractPlottable::addToLegend and \ref QCPAbstractPlottable::removeFromLegend. */ QCPPlottableLegendItem::QCPPlottableLegendItem(QCPLegend *parent, QCPAbstractPlottable *plottable) : - QCPAbstractLegendItem(parent), - mPlottable(plottable) + QCPAbstractLegendItem(parent), + mPlottable(plottable) { - setAntialiased(false); + setAntialiased(false); } /*! \internal - + Returns the pen that shall be used to draw the icon border, taking into account the selection state of this item. */ QPen QCPPlottableLegendItem::getIconBorderPen() const { - return mSelected ? mParentLegend->selectedIconBorderPen() : mParentLegend->iconBorderPen(); + return mSelected ? mParentLegend->selectedIconBorderPen() : mParentLegend->iconBorderPen(); } /*! \internal - + Returns the text color that shall be used to draw text, taking into account the selection state of this item. */ QColor QCPPlottableLegendItem::getTextColor() const { - return mSelected ? mSelectedTextColor : mTextColor; + return mSelected ? mSelectedTextColor : mTextColor; } /*! \internal - + Returns the font that shall be used to draw text, taking into account the selection state of this item. */ QFont QCPPlottableLegendItem::getFont() const { - return mSelected ? mSelectedFont : mFont; + return mSelected ? mSelectedFont : mFont; } /*! \internal - + Draws the item with \a painter. The size and position of the drawn legend item is defined by the parent layout (typically a \ref QCPLegend) and the \ref minimumOuterSizeHint and \ref maximumOuterSizeHint of this legend item. */ void QCPPlottableLegendItem::draw(QCPPainter *painter) { - if (!mPlottable) return; - painter->setFont(getFont()); - painter->setPen(QPen(getTextColor())); - QSize iconSize = mParentLegend->iconSize(); - QRect textRect = painter->fontMetrics().boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPlottable->name()); - QRect iconRect(mRect.topLeft(), iconSize); - int textHeight = qMax(textRect.height(), iconSize.height()); // if text has smaller height than icon, center text vertically in icon height, else align tops - painter->drawText(mRect.x()+iconSize.width()+mParentLegend->iconTextPadding(), mRect.y(), textRect.width(), textHeight, Qt::TextDontClip, mPlottable->name()); - // draw icon: - painter->save(); - painter->setClipRect(iconRect, Qt::IntersectClip); - mPlottable->drawLegendIcon(painter, iconRect); - painter->restore(); - // draw icon border: - if (getIconBorderPen().style() != Qt::NoPen) - { - 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); - } + if (!mPlottable) { + return; + } + painter->setFont(getFont()); + painter->setPen(QPen(getTextColor())); + QSize iconSize = mParentLegend->iconSize(); + QRect textRect = painter->fontMetrics().boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPlottable->name()); + QRect iconRect(mRect.topLeft(), iconSize); + int textHeight = qMax(textRect.height(), iconSize.height()); // if text has smaller height than icon, center text vertically in icon height, else align tops + painter->drawText(mRect.x() + iconSize.width() + mParentLegend->iconTextPadding(), mRect.y(), textRect.width(), textHeight, Qt::TextDontClip, mPlottable->name()); + // draw icon: + painter->save(); + painter->setClipRect(iconRect, Qt::IntersectClip); + mPlottable->drawLegendIcon(painter, iconRect); + painter->restore(); + // draw icon border: + if (getIconBorderPen().style() != Qt::NoPen) { + 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); + } } /*! \internal - + Calculates and returns the size of this item. This includes the icon, the text and the padding in between. - + \seebaseclassmethod */ QSize QCPPlottableLegendItem::minimumOuterSizeHint() const { - if (!mPlottable) return {}; - QSize result(0, 0); - QRect textRect; - QFontMetrics fontMetrics(getFont()); - QSize iconSize = mParentLegend->iconSize(); - textRect = fontMetrics.boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPlottable->name()); - result.setWidth(iconSize.width() + mParentLegend->iconTextPadding() + textRect.width()); - result.setHeight(qMax(textRect.height(), iconSize.height())); - result.rwidth() += mMargins.left()+mMargins.right(); - result.rheight() += mMargins.top()+mMargins.bottom(); - return result; + if (!mPlottable) + return {}; + QSize result(0, 0); + QRect textRect; + QFontMetrics fontMetrics(getFont()); + QSize iconSize = mParentLegend->iconSize(); + textRect = fontMetrics.boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPlottable->name()); + result.setWidth(iconSize.width() + mParentLegend->iconTextPadding() + textRect.width()); + result.setHeight(qMax(textRect.height(), iconSize.height())); + result.rwidth() += mMargins.left() + mMargins.right(); + result.rheight() += mMargins.top() + mMargins.bottom(); + return result; } @@ -19039,7 +19125,7 @@ QSize QCPPlottableLegendItem::minimumOuterSizeHint() const /*! \fn void QCPLegend::selectionChanged(QCPLegend::SelectableParts selection); This signal is emitted when the selection state of this legend has changed. - + \see setSelectedParts, setSelectableParts */ @@ -19047,61 +19133,61 @@ QSize QCPPlottableLegendItem::minimumOuterSizeHint() const /*! Constructs a new QCPLegend instance with default values. - + Note that by default, QCustomPlot already contains a legend ready to be used as \ref QCustomPlot::legend */ QCPLegend::QCPLegend() : - mIconTextPadding{} + mIconTextPadding{} { - setFillOrder(QCPLayoutGrid::foRowsFirst); - setWrap(0); - - setRowSpacing(3); - setColumnSpacing(8); - setMargins(QMargins(7, 5, 7, 4)); - setAntialiased(false); - setIconSize(32, 18); - - setIconTextPadding(7); - - setSelectableParts(spLegendBox | spItems); - setSelectedParts(spNone); - - setBorderPen(QPen(Qt::black, 0)); - setSelectedBorderPen(QPen(Qt::blue, 2)); - setIconBorderPen(Qt::NoPen); - setSelectedIconBorderPen(QPen(Qt::blue, 2)); - setBrush(Qt::white); - setSelectedBrush(Qt::white); - setTextColor(Qt::black); - setSelectedTextColor(Qt::blue); + setFillOrder(QCPLayoutGrid::foRowsFirst); + setWrap(0); + + setRowSpacing(3); + setColumnSpacing(8); + setMargins(QMargins(7, 5, 7, 4)); + setAntialiased(false); + setIconSize(32, 18); + + setIconTextPadding(7); + + setSelectableParts(spLegendBox | spItems); + setSelectedParts(spNone); + + setBorderPen(QPen(Qt::black, 0)); + setSelectedBorderPen(QPen(Qt::blue, 2)); + setIconBorderPen(Qt::NoPen); + setSelectedIconBorderPen(QPen(Qt::blue, 2)); + setBrush(Qt::white); + setSelectedBrush(Qt::white); + setTextColor(Qt::black); + setSelectedTextColor(Qt::blue); } QCPLegend::~QCPLegend() { - clearItems(); - if (qobject_cast(mParentPlot)) // make sure this isn't called from QObject dtor when QCustomPlot is already destructed (happens when the legend is not in any layout and thus QObject-child of QCustomPlot) - mParentPlot->legendRemoved(this); + clearItems(); + if (qobject_cast(mParentPlot)) { // make sure this isn't called from QObject dtor when QCustomPlot is already destructed (happens when the legend is not in any layout and thus QObject-child of QCustomPlot) + mParentPlot->legendRemoved(this); + } } /* no doc for getter, see setSelectedParts */ QCPLegend::SelectableParts QCPLegend::selectedParts() const { - // check whether any legend elements selected, if yes, add spItems to return value - bool hasSelectedItems = false; - for (int i=0; iselected()) - { - hasSelectedItems = true; - break; + // check whether any legend elements selected, if yes, add spItems to return value + bool hasSelectedItems = false; + for (int i = 0; i < itemCount(); ++i) { + if (item(i) && item(i)->selected()) { + hasSelectedItems = true; + break; + } + } + if (hasSelectedItems) { + return mSelectedParts | spItems; + } else { + return mSelectedParts & ~spItems; } - } - if (hasSelectedItems) - return mSelectedParts | spItems; - else - return mSelectedParts & ~spItems; } /*! @@ -19109,7 +19195,7 @@ QCPLegend::SelectableParts QCPLegend::selectedParts() const */ void QCPLegend::setBorderPen(const QPen &pen) { - mBorderPen = pen; + mBorderPen = pen; } /*! @@ -19117,45 +19203,45 @@ void QCPLegend::setBorderPen(const QPen &pen) */ void QCPLegend::setBrush(const QBrush &brush) { - mBrush = brush; + mBrush = brush; } /*! Sets the default font of legend text. Legend items that draw text (e.g. the name of a graph) will use this font by default. However, a different font can be specified on a per-item-basis by accessing the specific legend item. - + This function will also set \a font on all already existing legend items. - + \see QCPAbstractLegendItem::setFont */ void QCPLegend::setFont(const QFont &font) { - mFont = font; - for (int i=0; isetFont(mFont); - } + mFont = font; + for (int i = 0; i < itemCount(); ++i) { + if (item(i)) { + item(i)->setFont(mFont); + } + } } /*! Sets the default color of legend text. Legend items that draw text (e.g. the name of a graph) will use this color by default. However, a different colors can be specified on a per-item-basis by accessing the specific legend item. - + This function will also set \a color on all already existing legend items. - + \see QCPAbstractLegendItem::setTextColor */ void QCPLegend::setTextColor(const QColor &color) { - mTextColor = color; - for (int i=0; isetTextColor(color); - } + mTextColor = color; + for (int i = 0; i < itemCount(); ++i) { + if (item(i)) { + item(i)->setTextColor(color); + } + } } /*! @@ -19164,15 +19250,15 @@ void QCPLegend::setTextColor(const QColor &color) */ void QCPLegend::setIconSize(const QSize &size) { - mIconSize = size; + mIconSize = size; } /*! \overload */ void QCPLegend::setIconSize(int width, int height) { - mIconSize.setWidth(width); - mIconSize.setHeight(height); + mIconSize.setWidth(width); + mIconSize.setHeight(height); } /*! @@ -19182,83 +19268,79 @@ void QCPLegend::setIconSize(int width, int height) */ void QCPLegend::setIconTextPadding(int padding) { - mIconTextPadding = padding; + mIconTextPadding = padding; } /*! Sets the pen used to draw a border around each legend icon. Legend items that draw an icon (e.g. a visual representation of the graph) will use this pen by default. - + If no border is wanted, set this to \a Qt::NoPen. */ void QCPLegend::setIconBorderPen(const QPen &pen) { - mIconBorderPen = pen; + mIconBorderPen = pen; } /*! Sets whether the user can (de-)select the parts in \a selectable by clicking on the QCustomPlot surface. (When \ref QCustomPlot::setInteractions contains \ref QCP::iSelectLegend.) - + However, even when \a selectable is set to a value not allowing the selection of a specific part, it is still possible to set the selection of this part manually, by calling \ref setSelectedParts directly. - + \see SelectablePart, setSelectedParts */ void QCPLegend::setSelectableParts(const SelectableParts &selectable) { - if (mSelectableParts != selectable) - { - mSelectableParts = selectable; - emit selectableChanged(mSelectableParts); - } + if (mSelectableParts != selectable) { + mSelectableParts = selectable; + emit selectableChanged(mSelectableParts); + } } /*! Sets the selected state of the respective legend parts described by \ref SelectablePart. When a part is selected, it uses a different pen/font and brush. If some legend items are selected and \a selected doesn't contain \ref spItems, those items become deselected. - + The entire selection mechanism is handled automatically when \ref QCustomPlot::setInteractions contains iSelectLegend. You only need to call this function when you wish to change the selection state manually. - + This function can change the selection state of a part even when \ref setSelectableParts was set to a value that actually excludes the part. - + emits the \ref selectionChanged signal when \a selected is different from the previous selection state. - + Note that it doesn't make sense to set the selected state \ref spItems here when it wasn't set before, because there's no way to specify which exact items to newly select. Do this by calling \ref QCPAbstractLegendItem::setSelected directly on the legend item you wish to select. - + \see SelectablePart, setSelectableParts, selectTest, setSelectedBorderPen, setSelectedIconBorderPen, setSelectedBrush, setSelectedFont */ void QCPLegend::setSelectedParts(const SelectableParts &selected) { - SelectableParts newSelected = selected; - mSelectedParts = this->selectedParts(); // update mSelectedParts in case item selection changed + SelectableParts newSelected = selected; + mSelectedParts = this->selectedParts(); // update mSelectedParts in case item selection changed - if (mSelectedParts != newSelected) - { - if (!mSelectedParts.testFlag(spItems) && newSelected.testFlag(spItems)) // attempt to set spItems flag (can't do that) - { - qDebug() << Q_FUNC_INFO << "spItems flag can not be set, it can only be unset with this function"; - newSelected &= ~spItems; + if (mSelectedParts != newSelected) { + if (!mSelectedParts.testFlag(spItems) && newSelected.testFlag(spItems)) { // attempt to set spItems flag (can't do that) + qDebug() << Q_FUNC_INFO << "spItems flag can not be set, it can only be unset with this function"; + newSelected &= ~spItems; + } + if (mSelectedParts.testFlag(spItems) && !newSelected.testFlag(spItems)) { // spItems flag was unset, so clear item selection + for (int i = 0; i < itemCount(); ++i) { + if (item(i)) { + item(i)->setSelected(false); + } + } + } + mSelectedParts = newSelected; + emit selectionChanged(mSelectedParts); } - if (mSelectedParts.testFlag(spItems) && !newSelected.testFlag(spItems)) // spItems flag was unset, so clear item selection - { - for (int i=0; isetSelected(false); - } - } - mSelectedParts = newSelected; - emit selectionChanged(mSelectedParts); - } } /*! @@ -19269,7 +19351,7 @@ void QCPLegend::setSelectedParts(const SelectableParts &selected) */ void QCPLegend::setSelectedBorderPen(const QPen &pen) { - mSelectedBorderPen = pen; + mSelectedBorderPen = pen; } /*! @@ -19279,7 +19361,7 @@ void QCPLegend::setSelectedBorderPen(const QPen &pen) */ void QCPLegend::setSelectedIconBorderPen(const QPen &pen) { - mSelectedIconBorderPen = pen; + mSelectedIconBorderPen = pen; } /*! @@ -19290,41 +19372,41 @@ void QCPLegend::setSelectedIconBorderPen(const QPen &pen) */ void QCPLegend::setSelectedBrush(const QBrush &brush) { - mSelectedBrush = brush; + mSelectedBrush = brush; } /*! Sets the default font that is used by legend items when they are selected. - + This function will also set \a font on all already existing legend items. \see setFont, QCPAbstractLegendItem::setSelectedFont */ void QCPLegend::setSelectedFont(const QFont &font) { - mSelectedFont = font; - for (int i=0; isetSelectedFont(font); - } + mSelectedFont = font; + for (int i = 0; i < itemCount(); ++i) { + if (item(i)) { + item(i)->setSelectedFont(font); + } + } } /*! Sets the default text color that is used by legend items when they are selected. - + This function will also set \a color on all already existing legend items. \see setTextColor, QCPAbstractLegendItem::setSelectedTextColor */ void QCPLegend::setSelectedTextColor(const QColor &color) { - mSelectedTextColor = color; - for (int i=0; isetSelectedTextColor(color); - } + mSelectedTextColor = color; + for (int i = 0; i < itemCount(); ++i) { + if (item(i)) { + item(i)->setSelectedTextColor(color); + } + } } /*! @@ -19337,26 +19419,25 @@ void QCPLegend::setSelectedTextColor(const QColor &color) */ QCPAbstractLegendItem *QCPLegend::item(int index) const { - return qobject_cast(elementAt(index)); + return qobject_cast(elementAt(index)); } /*! Returns the QCPPlottableLegendItem which is associated with \a plottable (e.g. a \ref QCPGraph*). If such an item isn't in the legend, returns \c nullptr. - + \see hasItemWithPlottable */ QCPPlottableLegendItem *QCPLegend::itemWithPlottable(const QCPAbstractPlottable *plottable) const { - for (int i=0; i(item(i))) - { - if (pli->plottable() == plottable) - return pli; + for (int i = 0; i < itemCount(); ++i) { + if (QCPPlottableLegendItem *pli = qobject_cast(item(i))) { + if (pli->plottable() == plottable) { + return pli; + } + } } - } - return nullptr; + return nullptr; } /*! @@ -19371,33 +19452,33 @@ QCPPlottableLegendItem *QCPLegend::itemWithPlottable(const QCPAbstractPlottable */ int QCPLegend::itemCount() const { - return elementCount(); + return elementCount(); } /*! Returns whether the legend contains \a item. - + \see hasItemWithPlottable */ bool QCPLegend::hasItem(QCPAbstractLegendItem *item) const { - for (int i=0; iitem(i)) - return true; - } - return false; + for (int i = 0; i < itemCount(); ++i) { + if (item == this->item(i)) { + return true; + } + } + return false; } /*! Returns whether the legend contains a QCPPlottableLegendItem which is associated with \a plottable (e.g. a \ref QCPGraph*). If such an item isn't in the legend, returns false. - + \see itemWithPlottable */ bool QCPLegend::hasItemWithPlottable(const QCPAbstractPlottable *plottable) const { - return itemWithPlottable(plottable); + return itemWithPlottable(plottable); } /*! @@ -19412,7 +19493,7 @@ bool QCPLegend::hasItemWithPlottable(const QCPAbstractPlottable *plottable) cons */ bool QCPLegend::addItem(QCPAbstractLegendItem *item) { - return addElement(item); + return addElement(item); } /*! \overload @@ -19430,14 +19511,15 @@ bool QCPLegend::addItem(QCPAbstractLegendItem *item) */ bool QCPLegend::removeItem(int index) { - if (QCPAbstractLegendItem *ali = item(index)) - { - bool success = remove(ali); - if (success) - setFillOrder(fillOrder(), true); // gets rid of empty cell by reordering - return success; - } else - return false; + if (QCPAbstractLegendItem *ali = item(index)) { + bool success = remove(ali); + if (success) { + setFillOrder(fillOrder(), true); // gets rid of empty cell by reordering + } + return success; + } else { + return false; + } } /*! \overload @@ -19454,10 +19536,11 @@ bool QCPLegend::removeItem(int index) */ bool QCPLegend::removeItem(QCPAbstractLegendItem *item) { - bool success = remove(item); - if (success) - setFillOrder(fillOrder(), true); // gets rid of empty cell by reordering - return success; + bool success = remove(item); + if (success) { + setFillOrder(fillOrder(), true); // gets rid of empty cell by reordering + } + return success; } /*! @@ -19465,32 +19548,31 @@ bool QCPLegend::removeItem(QCPAbstractLegendItem *item) */ void QCPLegend::clearItems() { - for (int i=elementCount()-1; i>=0; --i) - { - if (item(i)) - removeAt(i); // don't use removeItem() because it would unnecessarily reorder the whole legend for each item - } - setFillOrder(fillOrder(), true); // get rid of empty cells by reordering once after all items are removed + for (int i = elementCount() - 1; i >= 0; --i) { + if (item(i)) { + removeAt(i); // don't use removeItem() because it would unnecessarily reorder the whole legend for each item + } + } + setFillOrder(fillOrder(), true); // get rid of empty cells by reordering once after all items are removed } /*! Returns the legend items that are currently selected. If no items are selected, the list is empty. - + \see QCPAbstractLegendItem::setSelected, setSelectable */ QList QCPLegend::selectedItems() const { - QList result; - for (int i=0; iselected()) - result.append(ali); + QList result; + for (int i = 0; i < itemCount(); ++i) { + if (QCPAbstractLegendItem *ali = item(i)) { + if (ali->selected()) { + result.append(ali); + } + } } - } - return result; + return result; } /*! \internal @@ -19499,112 +19581,117 @@ QList QCPLegend::selectedItems() const before drawing main legend elements. This is the antialiasing state the painter passed to the \ref draw method is in by default. - + 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. - + \seebaseclassmethod - + \see setAntialiased */ void QCPLegend::applyDefaultAntialiasingHint(QCPPainter *painter) const { - applyAntialiasingHint(painter, mAntialiased, QCP::aeLegend); + applyAntialiasingHint(painter, mAntialiased, QCP::aeLegend); } /*! \internal - + Returns the pen used to paint the border of the legend, taking into account the selection state of the legend box. */ QPen QCPLegend::getBorderPen() const { - return mSelectedParts.testFlag(spLegendBox) ? mSelectedBorderPen : mBorderPen; + return mSelectedParts.testFlag(spLegendBox) ? mSelectedBorderPen : mBorderPen; } /*! \internal - + Returns the brush used to paint the background of the legend, taking into account the selection state of the legend box. */ QBrush QCPLegend::getBrush() const { - return mSelectedParts.testFlag(spLegendBox) ? mSelectedBrush : mBrush; + return mSelectedParts.testFlag(spLegendBox) ? mSelectedBrush : mBrush; } /*! \internal - + Draws the legend box with the provided \a painter. The individual legend items are layerables themselves, thus are drawn independently. */ void QCPLegend::draw(QCPPainter *painter) { - // draw background rect: - painter->setBrush(getBrush()); - painter->setPen(getBorderPen()); - painter->drawRect(mOuterRect); + // draw background rect: + painter->setBrush(getBrush()); + painter->setPen(getBorderPen()); + painter->drawRect(mOuterRect); } /* inherits documentation from base class */ double QCPLegend::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { - if (!mParentPlot) return -1; - if (onlySelectable && !mSelectableParts.testFlag(spLegendBox)) + if (!mParentPlot) { + return -1; + } + if (onlySelectable && !mSelectableParts.testFlag(spLegendBox)) { + return -1; + } + + if (mOuterRect.contains(pos.toPoint())) { + if (details) { + details->setValue(spLegendBox); + } + return mParentPlot->selectionTolerance() * 0.99; + } return -1; - - if (mOuterRect.contains(pos.toPoint())) - { - if (details) details->setValue(spLegendBox); - return mParentPlot->selectionTolerance()*0.99; - } - return -1; } /* inherits documentation from base class */ void QCPLegend::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) { - Q_UNUSED(event) - mSelectedParts = selectedParts(); // in case item selection has changed - if (details.value() == spLegendBox && mSelectableParts.testFlag(spLegendBox)) - { - SelectableParts selBefore = mSelectedParts; - setSelectedParts(additive ? mSelectedParts^spLegendBox : mSelectedParts|spLegendBox); // no need to unset spItems in !additive case, because they will be deselected by QCustomPlot (they're normal QCPLayerables with own deselectEvent) - if (selectionStateChanged) - *selectionStateChanged = mSelectedParts != selBefore; - } + Q_UNUSED(event) + mSelectedParts = selectedParts(); // in case item selection has changed + if (details.value() == spLegendBox && mSelectableParts.testFlag(spLegendBox)) { + SelectableParts selBefore = mSelectedParts; + setSelectedParts(additive ? mSelectedParts ^spLegendBox : mSelectedParts | spLegendBox); // no need to unset spItems in !additive case, because they will be deselected by QCustomPlot (they're normal QCPLayerables with own deselectEvent) + if (selectionStateChanged) { + *selectionStateChanged = mSelectedParts != selBefore; + } + } } /* inherits documentation from base class */ void QCPLegend::deselectEvent(bool *selectionStateChanged) { - mSelectedParts = selectedParts(); // in case item selection has changed - if (mSelectableParts.testFlag(spLegendBox)) - { - SelectableParts selBefore = mSelectedParts; - setSelectedParts(selectedParts() & ~spLegendBox); - if (selectionStateChanged) - *selectionStateChanged = mSelectedParts != selBefore; - } + mSelectedParts = selectedParts(); // in case item selection has changed + if (mSelectableParts.testFlag(spLegendBox)) { + SelectableParts selBefore = mSelectedParts; + setSelectedParts(selectedParts() & ~spLegendBox); + if (selectionStateChanged) { + *selectionStateChanged = mSelectedParts != selBefore; + } + } } /* inherits documentation from base class */ QCP::Interaction QCPLegend::selectionCategory() const { - return QCP::iSelectLegend; + return QCP::iSelectLegend; } /* inherits documentation from base class */ QCP::Interaction QCPAbstractLegendItem::selectionCategory() const { - return QCP::iSelectLegend; + return QCP::iSelectLegend; } /* inherits documentation from base class */ void QCPLegend::parentPlotInitialized(QCustomPlot *parentPlot) { - if (parentPlot && !parentPlot->legend) - parentPlot->legend = this; + if (parentPlot && !parentPlot->legend) { + parentPlot->legend = this; + } } /* end of 'src/layoutelements/layoutelement-legend.cpp' */ @@ -19629,10 +19716,10 @@ void QCPLegend::parentPlotInitialized(QCustomPlot *parentPlot) /* start documentation of signals */ /*! \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. - + \see setSelected, setSelectable */ @@ -19653,137 +19740,134 @@ void QCPLegend::parentPlotInitialized(QCustomPlot *parentPlot) /* end documentation of signals */ /*! \overload - + Creates a new QCPTextElement instance and sets default values. The initial text is empty (\ref setText). */ QCPTextElement::QCPTextElement(QCustomPlot *parentPlot) : - QCPLayoutElement(parentPlot), - mText(), - mTextFlags(Qt::AlignCenter), - mFont(QFont(QLatin1String("sans serif"), 12)), // will be taken from parentPlot if available, see below - mTextColor(Qt::black), - mSelectedFont(QFont(QLatin1String("sans serif"), 12)), // will be taken from parentPlot if available, see below - mSelectedTextColor(Qt::blue), - mSelectable(false), - mSelected(false) + QCPLayoutElement(parentPlot), + mText(), + mTextFlags(Qt::AlignCenter), + mFont(QFont(QLatin1String("sans serif"), 12)), // will be taken from parentPlot if available, see below + mTextColor(Qt::black), + mSelectedFont(QFont(QLatin1String("sans serif"), 12)), // will be taken from parentPlot if available, see below + mSelectedTextColor(Qt::blue), + mSelectable(false), + mSelected(false) { - if (parentPlot) - { - mFont = parentPlot->font(); - mSelectedFont = parentPlot->font(); - } - setMargins(QMargins(2, 2, 2, 2)); + 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. */ QCPTextElement::QCPTextElement(QCustomPlot *parentPlot, const QString &text) : - QCPLayoutElement(parentPlot), - mText(text), - mTextFlags(Qt::AlignCenter), - mFont(QFont(QLatin1String("sans serif"), 12)), // will be taken from parentPlot if available, see below - mTextColor(Qt::black), - mSelectedFont(QFont(QLatin1String("sans serif"), 12)), // will be taken from parentPlot if available, see below - mSelectedTextColor(Qt::blue), - mSelectable(false), - mSelected(false) + QCPLayoutElement(parentPlot), + mText(text), + mTextFlags(Qt::AlignCenter), + mFont(QFont(QLatin1String("sans serif"), 12)), // will be taken from parentPlot if available, see below + mTextColor(Qt::black), + mSelectedFont(QFont(QLatin1String("sans serif"), 12)), // will be taken from parentPlot if available, see below + mSelectedTextColor(Qt::blue), + mSelectable(false), + mSelected(false) { - if (parentPlot) - { - mFont = parentPlot->font(); - mSelectedFont = parentPlot->font(); - } - setMargins(QMargins(2, 2, 2, 2)); + 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), - mFont(QFont(QLatin1String("sans serif"), int(pointSize))), // will be taken from parentPlot if available, see below - mTextColor(Qt::black), - mSelectedFont(QFont(QLatin1String("sans serif"), int(pointSize))), // will be taken from parentPlot if available, see below - mSelectedTextColor(Qt::blue), - mSelectable(false), - mSelected(false) + QCPLayoutElement(parentPlot), + mText(text), + mTextFlags(Qt::AlignCenter), + mFont(QFont(QLatin1String("sans serif"), int(pointSize))), // will be taken from parentPlot if available, see below + mTextColor(Qt::black), + mSelectedFont(QFont(QLatin1String("sans serif"), int(pointSize))), // will be taken from parentPlot if available, see below + mSelectedTextColor(Qt::blue), + mSelectable(false), + mSelected(false) { - mFont.setPointSizeF(pointSize); // set here again as floating point, because constructor above only takes integer - if (parentPlot) - { - mFont = parentPlot->font(); - mFont.setPointSizeF(pointSize); - mSelectedFont = parentPlot->font(); - mSelectedFont.setPointSizeF(pointSize); - } - setMargins(QMargins(2, 2, 2, 2)); + mFont.setPointSizeF(pointSize); // set here again as floating point, because constructor above only takes integer + 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), - mFont(QFont(fontFamily, int(pointSize))), - mTextColor(Qt::black), - mSelectedFont(QFont(fontFamily, int(pointSize))), - mSelectedTextColor(Qt::blue), - mSelectable(false), - mSelected(false) + QCPLayoutElement(parentPlot), + mText(text), + mTextFlags(Qt::AlignCenter), + mFont(QFont(fontFamily, int(pointSize))), + mTextColor(Qt::black), + mSelectedFont(QFont(fontFamily, int(pointSize))), + mSelectedTextColor(Qt::blue), + mSelectable(false), + mSelected(false) { - mFont.setPointSizeF(pointSize); // set here again as floating point, because constructor above only takes integer - setMargins(QMargins(2, 2, 2, 2)); + mFont.setPointSizeF(pointSize); // set here again as floating point, because constructor above only takes integer + 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), - mFont(font), - mTextColor(Qt::black), - mSelectedFont(font), - mSelectedTextColor(Qt::blue), - mSelectable(false), - mSelected(false) + QCPLayoutElement(parentPlot), + mText(text), + mTextFlags(Qt::AlignCenter), + mFont(font), + mTextColor(Qt::black), + mSelectedFont(font), + mSelectedTextColor(Qt::blue), + mSelectable(false), + mSelected(false) { - setMargins(QMargins(2, 2, 2, 2)); + 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, setTextFlags */ void QCPTextElement::setText(const QString &text) { - mText = text; + mText = 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 @@ -19802,47 +19886,47 @@ void QCPTextElement::setText(const QString &text) */ void QCPTextElement::setTextFlags(int flags) { - mTextFlags = flags; + mTextFlags = flags; } /*! Sets the \a font of the text. - + \see setTextColor, setSelectedFont */ void QCPTextElement::setFont(const QFont &font) { - mFont = font; + mFont = font; } /*! Sets the \a color of the text. - + \see setFont, setSelectedTextColor */ void QCPTextElement::setTextColor(const QColor &color) { - mTextColor = color; + mTextColor = color; } /*! Sets the \a font of the text that will be used if the text element is selected (\ref setSelected). - + \see setFont */ void QCPTextElement::setSelectedFont(const QFont &font) { - mSelectedFont = font; + mSelectedFont = font; } /*! Sets the \a color of the text that will be used if the text element is selected (\ref setSelected). - + \see setTextColor */ void QCPTextElement::setSelectedTextColor(const QColor &color) { - mSelectedTextColor = color; + mSelectedTextColor = color; } /*! @@ -19853,87 +19937,85 @@ void QCPTextElement::setSelectedTextColor(const QColor &color) */ void QCPTextElement::setSelectable(bool selectable) { - if (mSelectable != selectable) - { - mSelectable = selectable; - emit selectableChanged(mSelectable); - } + if (mSelectable != selectable) { + mSelectable = selectable; + emit selectableChanged(mSelectable); + } } /*! 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 QCPTextElement::setSelected(bool selected) { - if (mSelected != selected) - { - mSelected = selected; - emit selectionChanged(mSelected); - } + if (mSelected != selected) { + mSelected = selected; + emit selectionChanged(mSelected); + } } /* inherits documentation from base class */ void QCPTextElement::applyDefaultAntialiasingHint(QCPPainter *painter) const { - applyAntialiasingHint(painter, mAntialiased, QCP::aeOther); + applyAntialiasingHint(painter, mAntialiased, QCP::aeOther); } /* inherits documentation from base class */ void QCPTextElement::draw(QCPPainter *painter) { - painter->setFont(mainFont()); - painter->setPen(QPen(mainTextColor())); - painter->drawText(mRect, mTextFlags, mText, &mTextBoundingRect); + painter->setFont(mainFont()); + painter->setPen(QPen(mainTextColor())); + painter->drawText(mRect, mTextFlags, mText, &mTextBoundingRect); } /* inherits documentation from base class */ QSize QCPTextElement::minimumOuterSizeHint() const { - QFontMetrics metrics(mFont); - QSize result(metrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip, mText).size()); - result.rwidth() += mMargins.left()+mMargins.right(); - result.rheight() += mMargins.top()+mMargins.bottom(); - return result; + QFontMetrics metrics(mFont); + QSize result(metrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip, mText).size()); + result.rwidth() += mMargins.left() + mMargins.right(); + result.rheight() += mMargins.top() + mMargins.bottom(); + return result; } /* inherits documentation from base class */ QSize QCPTextElement::maximumOuterSizeHint() const { - QFontMetrics metrics(mFont); - QSize result(metrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip, mText).size()); - result.setWidth(QWIDGETSIZE_MAX); - result.rheight() += mMargins.top()+mMargins.bottom(); - return result; + QFontMetrics metrics(mFont); + QSize result(metrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip, mText).size()); + result.setWidth(QWIDGETSIZE_MAX); + result.rheight() += mMargins.top() + mMargins.bottom(); + return result; } /* inherits documentation from base class */ void QCPTextElement::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) { - Q_UNUSED(event) - Q_UNUSED(details) - if (mSelectable) - { - bool selBefore = mSelected; - setSelected(additive ? !mSelected : true); - if (selectionStateChanged) - *selectionStateChanged = mSelected != selBefore; - } + Q_UNUSED(event) + Q_UNUSED(details) + if (mSelectable) { + bool selBefore = mSelected; + setSelected(additive ? !mSelected : true); + if (selectionStateChanged) { + *selectionStateChanged = mSelected != selBefore; + } + } } /* inherits documentation from base class */ void QCPTextElement::deselectEvent(bool *selectionStateChanged) { - if (mSelectable) - { - bool selBefore = mSelected; - setSelected(false); - if (selectionStateChanged) - *selectionStateChanged = mSelected != selBefore; - } + if (mSelectable) { + bool selBefore = mSelected; + setSelected(false); + if (selectionStateChanged) { + *selectionStateChanged = mSelected != selBefore; + } + } } /*! @@ -19948,14 +20030,16 @@ void QCPTextElement::deselectEvent(bool *selectionStateChanged) */ double QCPTextElement::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { - Q_UNUSED(details) - if (onlySelectable && !mSelectable) - return -1; - - if (mTextBoundingRect.contains(pos.toPoint())) - return mParentPlot->selectionTolerance()*0.99; - else - return -1; + Q_UNUSED(details) + if (onlySelectable && !mSelectable) { + return -1; + } + + if (mTextBoundingRect.contains(pos.toPoint())) { + return mParentPlot->selectionTolerance() * 0.99; + } else { + return -1; + } } /*! @@ -19966,8 +20050,8 @@ double QCPTextElement::selectTest(const QPointF &pos, bool onlySelectable, QVari */ void QCPTextElement::mousePressEvent(QMouseEvent *event, const QVariant &details) { - Q_UNUSED(details) - event->accept(); + Q_UNUSED(details) + event->accept(); } /*! @@ -19978,8 +20062,9 @@ void QCPTextElement::mousePressEvent(QMouseEvent *event, const QVariant &details */ void QCPTextElement::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos) { - if ((QPointF(event->pos())-startPos).manhattanLength() <= 3) - emit clicked(event); + if ((QPointF(event->pos()) - startPos).manhattanLength() <= 3) { + emit clicked(event); + } } /*! @@ -19989,28 +20074,28 @@ void QCPTextElement::mouseReleaseEvent(QMouseEvent *event, const QPointF &startP */ void QCPTextElement::mouseDoubleClickEvent(QMouseEvent *event, const QVariant &details) { - Q_UNUSED(details) - emit doubleClicked(event); + 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 QCPTextElement::mainFont() const { - return mSelected ? mSelectedFont : mFont; + return mSelected ? mSelectedFont : mFont; } /*! \internal - + Returns the main color to be used. This is mSelectedTextColor if \ref setSelected is set to true, else mTextColor is returned. */ QColor QCPTextElement::mainTextColor() const { - return mSelected ? mSelectedTextColor : mTextColor; + return mSelected ? mSelectedTextColor : mTextColor; } /* end of 'src/layoutelements/layoutelement-textelement.cpp' */ @@ -20025,35 +20110,35 @@ QColor QCPTextElement::mainTextColor() const /*! \class QCPColorScale \brief A color scale for use with color coding data such as QCPColorMap - + This layout element can be placed on the plot to correlate a color gradient with data values. It is usually used in combination with one or multiple \ref QCPColorMap "QCPColorMaps". \image html QCPColorScale.png - + The color scale can be either horizontal or vertical, as shown in the image above. The orientation and the side where the numbers appear is controlled with \ref setType. - + Use \ref QCPColorMap::setColorScale to connect a color map with a color scale. Once they are connected, they share their gradient, data range and data scale type (\ref setGradient, \ref setDataRange, \ref setDataScaleType). Multiple color maps may be associated with a single color scale, to make them all synchronize these properties. - + 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-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 In this case we have placed it to the right of the default axis rect, so it wasn't necessary to call \ref setType, since \ref QCPAxis::atRight is already the default. The text next to the color scale can be set with \ref setLabel. - + For optimum appearance (like in the image above), it may be desirable to line up the axis rect and the borders of the color scale. Use a \ref QCPMarginGroup to achieve this: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolorscale-margingroup - + Color scales are initialized with a non-zero minimum top and bottom margin (\ref setMinimumMargins), because vertical color scales are most common and the minimum top/bottom margin makes sure it keeps some distance to the top/bottom widget border. So if you change to a @@ -20064,14 +20149,14 @@ QColor QCPTextElement::mainTextColor() const /* start documentation of inline functions */ /*! \fn QCPAxis *QCPColorScale::axis() const - + Returns the internal \ref QCPAxis instance of this color scale. You can access it to alter the appearance and behaviour of the axis. \ref QCPColorScale duplicates some properties in its interface for convenience. Those are \ref setDataRange (\ref QCPAxis::setRange), \ref setDataScaleType (\ref QCPAxis::setScaleType), and the method \ref setLabel (\ref QCPAxis::setLabel). As they each are connected, it does not matter whether you use the method on the QCPColorScale or on its QCPAxis. - + If the type of the color scale is changed with \ref setType, the axis returned by this method will change, too, to either the left, right, bottom or top axis, depending on which type was set. */ @@ -20080,23 +20165,23 @@ QColor QCPTextElement::mainTextColor() const /* start documentation of signals */ /*! \fn void QCPColorScale::dataRangeChanged(const QCPRange &newRange); - + This signal is emitted when the data range changes. - + \see setDataRange */ /*! \fn void QCPColorScale::dataScaleTypeChanged(QCPAxis::ScaleType scaleType); - + This signal is emitted when the data scale type changes. - + \see setDataScaleType */ /*! \fn void QCPColorScale::gradientChanged(const QCPColorGradient &newGradient); - + This signal is emitted when the gradient changes. - + \see setGradient */ @@ -20106,183 +20191,176 @@ QColor QCPTextElement::mainTextColor() const Constructs a new QCPColorScale. */ QCPColorScale::QCPColorScale(QCustomPlot *parentPlot) : - QCPLayoutElement(parentPlot), - mType(QCPAxis::atTop), // set to atTop such that setType(QCPAxis::atRight) below doesn't skip work because it thinks it's already atRight - mDataScaleType(QCPAxis::stLinear), - mGradient(QCPColorGradient::gpCold), - mBarWidth(20), - mAxisRect(new QCPColorScaleAxisRectPrivate(this)) + QCPLayoutElement(parentPlot), + mType(QCPAxis::atTop), // set to atTop such that setType(QCPAxis::atRight) below doesn't skip work because it thinks it's already atRight + mDataScaleType(QCPAxis::stLinear), + mGradient(QCPColorGradient::gpCold), + mBarWidth(20), + mAxisRect(new QCPColorScaleAxisRectPrivate(this)) { - setMinimumMargins(QMargins(0, 6, 0, 6)); // for default right color scale types, keep some room at bottom and top (important if no margin group is used) - setType(QCPAxis::atRight); - setDataRange(QCPRange(0, 6)); + setMinimumMargins(QMargins(0, 6, 0, 6)); // for default right color scale types, keep some room at bottom and top (important if no margin group is used) + setType(QCPAxis::atRight); + setDataRange(QCPRange(0, 6)); } QCPColorScale::~QCPColorScale() { - delete mAxisRect; + delete mAxisRect; } /* undocumented getter */ QString QCPColorScale::label() const { - if (!mColorAxis) - { - qDebug() << Q_FUNC_INFO << "internal color axis undefined"; - return QString(); - } - - return mColorAxis.data()->label(); + if (!mColorAxis) { + qDebug() << Q_FUNC_INFO << "internal color axis undefined"; + return QString(); + } + + return mColorAxis.data()->label(); } /* undocumented getter */ bool QCPColorScale::rangeDrag() const { - if (!mAxisRect) - { - qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; - return false; - } - - return mAxisRect.data()->rangeDrag().testFlag(QCPAxis::orientation(mType)) && - mAxisRect.data()->rangeDragAxis(QCPAxis::orientation(mType)) && - mAxisRect.data()->rangeDragAxis(QCPAxis::orientation(mType))->orientation() == QCPAxis::orientation(mType); + if (!mAxisRect) { + qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; + return false; + } + + return mAxisRect.data()->rangeDrag().testFlag(QCPAxis::orientation(mType)) && + mAxisRect.data()->rangeDragAxis(QCPAxis::orientation(mType)) && + mAxisRect.data()->rangeDragAxis(QCPAxis::orientation(mType))->orientation() == QCPAxis::orientation(mType); } /* undocumented getter */ bool QCPColorScale::rangeZoom() const { - if (!mAxisRect) - { - qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; - return false; - } - - return mAxisRect.data()->rangeZoom().testFlag(QCPAxis::orientation(mType)) && - mAxisRect.data()->rangeZoomAxis(QCPAxis::orientation(mType)) && - mAxisRect.data()->rangeZoomAxis(QCPAxis::orientation(mType))->orientation() == QCPAxis::orientation(mType); + if (!mAxisRect) { + qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; + return false; + } + + return mAxisRect.data()->rangeZoom().testFlag(QCPAxis::orientation(mType)) && + mAxisRect.data()->rangeZoomAxis(QCPAxis::orientation(mType)) && + mAxisRect.data()->rangeZoomAxis(QCPAxis::orientation(mType))->orientation() == QCPAxis::orientation(mType); } /*! Sets at which side of the color scale the axis is placed, and thus also its orientation. - + 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, label and ticker (the latter will be shared and not copied). */ void QCPColorScale::setType(QCPAxis::AxisType type) { - if (!mAxisRect) - { - qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; - return; - } - if (mType != type) - { - mType = type; - QCPRange rangeTransfer(0, 6); - QString labelTransfer; - QSharedPointer tickerTransfer; - // transfer/revert some settings on old axis if it exists: - bool doTransfer = !mColorAxis.isNull(); - if (doTransfer) - { - rangeTransfer = mColorAxis.data()->range(); - labelTransfer = mColorAxis.data()->label(); - 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))); + if (!mAxisRect) { + qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; + return; } - const QList allAxisTypes = QList() << QCPAxis::atLeft << QCPAxis::atRight << QCPAxis::atBottom << QCPAxis::atTop; - foreach (QCPAxis::AxisType atype, allAxisTypes) - { - mAxisRect.data()->axis(atype)->setTicks(atype == mType); - mAxisRect.data()->axis(atype)->setTickLabels(atype== mType); + if (mType != type) { + mType = type; + QCPRange rangeTransfer(0, 6); + QString labelTransfer; + QSharedPointer tickerTransfer; + // transfer/revert some settings on old axis if it exists: + bool doTransfer = !mColorAxis.isNull(); + if (doTransfer) { + rangeTransfer = mColorAxis.data()->range(); + labelTransfer = mColorAxis.data()->label(); + 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))); + } + const QList allAxisTypes = QList() << QCPAxis::atLeft << QCPAxis::atRight << QCPAxis::atBottom << QCPAxis::atTop; + foreach (QCPAxis::AxisType atype, allAxisTypes) { + mAxisRect.data()->axis(atype)->setTicks(atype == mType); + mAxisRect.data()->axis(atype)->setTickLabels(atype == mType); + } + // set new mColorAxis pointer: + mColorAxis = mAxisRect.data()->axis(mType); + // transfer settings to new axis: + 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(QList() << mColorAxis.data()); } - // set new mColorAxis pointer: - mColorAxis = mAxisRect.data()->axis(mType); - // transfer settings to new axis: - 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(QList() << mColorAxis.data()); - } } /*! Sets the range spanned by the color gradient and that is shown by the axis in the color scale. - + It is equivalent to calling QCPColorMap::setDataRange on any of the connected color maps. It is also equivalent to directly accessing the \ref axis and setting its range with \ref QCPAxis::setRange. - + \see setDataScaleType, setGradient, rescaleDataRange */ void QCPColorScale::setDataRange(const QCPRange &dataRange) { - if (mDataRange.lower != dataRange.lower || mDataRange.upper != dataRange.upper) - { - mDataRange = dataRange; - if (mColorAxis) - mColorAxis.data()->setRange(mDataRange); - emit dataRangeChanged(mDataRange); - } + if (mDataRange.lower != dataRange.lower || mDataRange.upper != dataRange.upper) { + mDataRange = dataRange; + if (mColorAxis) { + mColorAxis.data()->setRange(mDataRange); + } + emit dataRangeChanged(mDataRange); + } } /*! Sets the scale type of the color scale, i.e. whether values are associated with colors linearly or logarithmically. - + It is equivalent to calling QCPColorMap::setDataScaleType on any of the connected color maps. It is also equivalent to directly accessing the \ref axis and setting its scale type with \ref QCPAxis::setScaleType. - + Note that this method controls the coordinate transformation. For logarithmic scales, you will likely also want to use a logarithmic tick spacing and labeling, which can be achieved by setting the color scale's \ref axis ticker to an instance of \ref QCPAxisTickerLog : - + \snippet documentation/doc-code-snippets/mainwindow.cpp qcpaxisticker-log-colorscale - + See the documentation of \ref QCPAxisTickerLog about the details of logarithmic axis tick creation. - + \see setDataRange, setGradient */ void QCPColorScale::setDataScaleType(QCPAxis::ScaleType scaleType) { - if (mDataScaleType != scaleType) - { - mDataScaleType = scaleType; - if (mColorAxis) - mColorAxis.data()->setScaleType(mDataScaleType); - if (mDataScaleType == QCPAxis::stLogarithmic) - setDataRange(mDataRange.sanitizedForLogScale()); - emit dataScaleTypeChanged(mDataScaleType); - } + if (mDataScaleType != scaleType) { + mDataScaleType = scaleType; + if (mColorAxis) { + mColorAxis.data()->setScaleType(mDataScaleType); + } + if (mDataScaleType == QCPAxis::stLogarithmic) { + setDataRange(mDataRange.sanitizedForLogScale()); + } + emit dataScaleTypeChanged(mDataScaleType); + } } /*! Sets the color gradient that will be used to represent data values. - + It is equivalent to calling QCPColorMap::setGradient on any of the connected color maps. - + \see setDataRange, setDataScaleType */ void QCPColorScale::setGradient(const QCPColorGradient &gradient) { - if (mGradient != gradient) - { - mGradient = gradient; - if (mAxisRect) - mAxisRect.data()->mGradientImageInvalidated = true; - emit gradientChanged(mGradient); - } + if (mGradient != gradient) { + mGradient = gradient; + if (mAxisRect) { + mAxisRect.data()->mGradientImageInvalidated = true; + } + emit gradientChanged(mGradient); + } } /*! @@ -20291,13 +20369,12 @@ void QCPColorScale::setGradient(const QCPColorGradient &gradient) */ void QCPColorScale::setLabel(const QString &str) { - if (!mColorAxis) - { - qDebug() << Q_FUNC_INFO << "internal color axis undefined"; - return; - } - - mColorAxis.data()->setLabel(str); + if (!mColorAxis) { + qDebug() << Q_FUNC_INFO << "internal color axis undefined"; + return; + } + + mColorAxis.data()->setLabel(str); } /*! @@ -20306,227 +20383,208 @@ void QCPColorScale::setLabel(const QString &str) */ void QCPColorScale::setBarWidth(int width) { - mBarWidth = width; + mBarWidth = width; } /*! Sets whether the user can drag the data range (\ref setDataRange). - + Note that \ref QCP::iRangeDrag must be in the QCustomPlot's interactions (\ref QCustomPlot::setInteractions) to allow range dragging. */ void QCPColorScale::setRangeDrag(bool enabled) { - if (!mAxisRect) - { - qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; - return; - } - - if (enabled) - { - mAxisRect.data()->setRangeDrag(QCPAxis::orientation(mType)); - } else - { + if (!mAxisRect) { + qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; + return; + } + + if (enabled) { + mAxisRect.data()->setRangeDrag(QCPAxis::orientation(mType)); + } else { #if QT_VERSION < QT_VERSION_CHECK(5, 2, 0) - mAxisRect.data()->setRangeDrag(nullptr); + mAxisRect.data()->setRangeDrag(nullptr); #else - mAxisRect.data()->setRangeDrag({}); + mAxisRect.data()->setRangeDrag({}); #endif - } + } } /*! Sets whether the user can zoom the data range (\ref setDataRange) by scrolling the mouse wheel. - + Note that \ref QCP::iRangeZoom must be in the QCustomPlot's interactions (\ref QCustomPlot::setInteractions) to allow range dragging. */ void QCPColorScale::setRangeZoom(bool enabled) { - if (!mAxisRect) - { - qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; - return; - } - - if (enabled) - { - mAxisRect.data()->setRangeZoom(QCPAxis::orientation(mType)); - } else - { + if (!mAxisRect) { + qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; + return; + } + + if (enabled) { + mAxisRect.data()->setRangeZoom(QCPAxis::orientation(mType)); + } else { #if QT_VERSION < QT_VERSION_CHECK(5, 2, 0) - mAxisRect.data()->setRangeDrag(nullptr); + mAxisRect.data()->setRangeDrag(nullptr); #else - mAxisRect.data()->setRangeZoom({}); + mAxisRect.data()->setRangeZoom({}); #endif - } + } } /*! Returns a list of all the color maps associated with this color scale. */ -QList QCPColorScale::colorMaps() const +QList QCPColorScale::colorMaps() const { - QList result; - for (int i=0; iplottableCount(); ++i) - { - if (QCPColorMap *cm = qobject_cast(mParentPlot->plottable(i))) - if (cm->colorScale() == this) - result.append(cm); - } - return result; + QList result; + for (int i = 0; i < mParentPlot->plottableCount(); ++i) { + if (QCPColorMap *cm = qobject_cast(mParentPlot->plottable(i))) + if (cm->colorScale() == this) { + result.append(cm); + } + } + return result; } /*! Changes the data range such that all color maps associated with this color scale are fully mapped to the gradient in the data dimension. - + \see setDataRange */ void QCPColorScale::rescaleDataRange(bool onlyVisibleMaps) { - QList maps = colorMaps(); - QCPRange newRange; - bool haveRange = false; - QCP::SignDomain sign = QCP::sdBoth; - if (mDataScaleType == QCPAxis::stLogarithmic) - sign = (mDataRange.upper < 0 ? QCP::sdNegative : QCP::sdPositive); - foreach (QCPColorMap *map, maps) - { - if (!map->realVisibility() && onlyVisibleMaps) - continue; - QCPRange mapRange; - if (map->colorScale() == this) - { - bool currentFoundRange = true; - mapRange = map->data()->dataBounds(); - 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 == QCP::sdNegative) - { - if (mapRange.upper >= 0 && mapRange.lower < 0) - mapRange.upper = mapRange.lower*1e-3; - else if (mapRange.upper >= 0 && mapRange.lower >= 0) - currentFoundRange = false; - } - if (currentFoundRange) - { - if (!haveRange) - newRange = mapRange; - else - newRange.expand(mapRange); - haveRange = true; - } + QList maps = colorMaps(); + QCPRange newRange; + bool haveRange = false; + QCP::SignDomain sign = QCP::sdBoth; + if (mDataScaleType == QCPAxis::stLogarithmic) { + sign = (mDataRange.upper < 0 ? QCP::sdNegative : QCP::sdPositive); } - } - if (haveRange) - { - if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this dimension), shift current range to at least center the data - { - double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason - if (mDataScaleType == QCPAxis::stLinear) - { - newRange.lower = center-mDataRange.size()/2.0; - newRange.upper = center+mDataRange.size()/2.0; - } else // mScaleType == stLogarithmic - { - newRange.lower = center/qSqrt(mDataRange.upper/mDataRange.lower); - newRange.upper = center*qSqrt(mDataRange.upper/mDataRange.lower); - } + foreach (QCPColorMap *map, maps) { + if (!map->realVisibility() && onlyVisibleMaps) { + continue; + } + QCPRange mapRange; + if (map->colorScale() == this) { + bool currentFoundRange = true; + mapRange = map->data()->dataBounds(); + 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 == QCP::sdNegative) { + if (mapRange.upper >= 0 && mapRange.lower < 0) { + mapRange.upper = mapRange.lower * 1e-3; + } else if (mapRange.upper >= 0 && mapRange.lower >= 0) { + currentFoundRange = false; + } + } + if (currentFoundRange) { + if (!haveRange) { + newRange = mapRange; + } else { + newRange.expand(mapRange); + } + haveRange = true; + } + } + } + if (haveRange) { + if (!QCPRange::validRange(newRange)) { // likely due to range being zero (plottable has only constant data in this dimension), shift current range to at least center the data + double center = (newRange.lower + newRange.upper) * 0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason + if (mDataScaleType == QCPAxis::stLinear) { + newRange.lower = center - mDataRange.size() / 2.0; + newRange.upper = center + mDataRange.size() / 2.0; + } else { // mScaleType == stLogarithmic + newRange.lower = center / qSqrt(mDataRange.upper / mDataRange.lower); + newRange.upper = center * qSqrt(mDataRange.upper / mDataRange.lower); + } + } + setDataRange(newRange); } - setDataRange(newRange); - } } /* inherits documentation from base class */ void QCPColorScale::update(UpdatePhase phase) { - QCPLayoutElement::update(phase); - if (!mAxisRect) - { - qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; - return; - } - - mAxisRect.data()->update(phase); - - switch (phase) - { - case upMargins: - { - if (mType == QCPAxis::atBottom || mType == QCPAxis::atTop) - { - setMaximumSize(QWIDGETSIZE_MAX, mBarWidth+mAxisRect.data()->margins().top()+mAxisRect.data()->margins().bottom()); - setMinimumSize(0, mBarWidth+mAxisRect.data()->margins().top()+mAxisRect.data()->margins().bottom()); - } else - { - setMaximumSize(mBarWidth+mAxisRect.data()->margins().left()+mAxisRect.data()->margins().right(), QWIDGETSIZE_MAX); - setMinimumSize(mBarWidth+mAxisRect.data()->margins().left()+mAxisRect.data()->margins().right(), 0); - } - break; + QCPLayoutElement::update(phase); + if (!mAxisRect) { + qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; + return; } - case upLayout: - { - mAxisRect.data()->setOuterRect(rect()); - break; + + mAxisRect.data()->update(phase); + + switch (phase) { + case upMargins: { + if (mType == QCPAxis::atBottom || mType == QCPAxis::atTop) { + setMaximumSize(QWIDGETSIZE_MAX, mBarWidth + mAxisRect.data()->margins().top() + mAxisRect.data()->margins().bottom()); + setMinimumSize(0, mBarWidth + mAxisRect.data()->margins().top() + mAxisRect.data()->margins().bottom()); + } else { + setMaximumSize(mBarWidth + mAxisRect.data()->margins().left() + mAxisRect.data()->margins().right(), QWIDGETSIZE_MAX); + setMinimumSize(mBarWidth + mAxisRect.data()->margins().left() + mAxisRect.data()->margins().right(), 0); + } + break; + } + case upLayout: { + mAxisRect.data()->setOuterRect(rect()); + break; + } + default: + break; } - default: break; - } } /* inherits documentation from base class */ void QCPColorScale::applyDefaultAntialiasingHint(QCPPainter *painter) const { - painter->setAntialiasing(false); + painter->setAntialiasing(false); } /* inherits documentation from base class */ void QCPColorScale::mousePressEvent(QMouseEvent *event, const QVariant &details) { - if (!mAxisRect) - { - qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; - return; - } - mAxisRect.data()->mousePressEvent(event, details); + if (!mAxisRect) { + qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; + return; + } + mAxisRect.data()->mousePressEvent(event, details); } /* inherits documentation from base class */ void QCPColorScale::mouseMoveEvent(QMouseEvent *event, const QPointF &startPos) { - if (!mAxisRect) - { - qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; - return; - } - mAxisRect.data()->mouseMoveEvent(event, startPos); + if (!mAxisRect) { + qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; + return; + } + mAxisRect.data()->mouseMoveEvent(event, startPos); } /* inherits documentation from base class */ void QCPColorScale::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos) { - if (!mAxisRect) - { - qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; - return; - } - mAxisRect.data()->mouseReleaseEvent(event, startPos); + if (!mAxisRect) { + qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; + return; + } + mAxisRect.data()->mouseReleaseEvent(event, startPos); } /* inherits documentation from base class */ void QCPColorScale::wheelEvent(QWheelEvent *event) { - if (!mAxisRect) - { - qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; - return; - } - mAxisRect.data()->wheelEvent(event); + if (!mAxisRect) { + qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; + return; + } + mAxisRect.data()->wheelEvent(event); } //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -20537,9 +20595,9 @@ void QCPColorScale::wheelEvent(QWheelEvent *event) \internal \brief An axis rect subclass for use in a QCPColorScale - + This is a private class and not part of the public QCustomPlot interface. - + It provides the axis rect functionality for the QCPColorScale class. */ @@ -20548,60 +20606,60 @@ void QCPColorScale::wheelEvent(QWheelEvent *event) Creates a new instance, as a child of \a parentColorScale. */ QCPColorScaleAxisRectPrivate::QCPColorScaleAxisRectPrivate(QCPColorScale *parentColorScale) : - QCPAxisRect(parentColorScale->parentPlot(), true), - mParentColorScale(parentColorScale), - mGradientImageInvalidated(true) + QCPAxisRect(parentColorScale->parentPlot(), true), + mParentColorScale(parentColorScale), + mGradientImageInvalidated(true) { - setParentLayerable(parentColorScale); - setMinimumMargins(QMargins(0, 0, 0, 0)); - const QList allAxisTypes = QList() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight; - foreach (QCPAxis::AxisType type, allAxisTypes) - { - axis(type)->setVisible(true); - axis(type)->grid()->setVisible(false); - axis(type)->setPadding(0); - connect(axis(type), SIGNAL(selectionChanged(QCPAxis::SelectableParts)), this, SLOT(axisSelectionChanged(QCPAxis::SelectableParts))); - connect(axis(type), SIGNAL(selectableChanged(QCPAxis::SelectableParts)), this, SLOT(axisSelectableChanged(QCPAxis::SelectableParts))); - } + setParentLayerable(parentColorScale); + setMinimumMargins(QMargins(0, 0, 0, 0)); + const QList allAxisTypes = QList() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight; + foreach (QCPAxis::AxisType type, allAxisTypes) { + axis(type)->setVisible(true); + axis(type)->grid()->setVisible(false); + axis(type)->setPadding(0); + connect(axis(type), SIGNAL(selectionChanged(QCPAxis::SelectableParts)), this, SLOT(axisSelectionChanged(QCPAxis::SelectableParts))); + connect(axis(type), SIGNAL(selectableChanged(QCPAxis::SelectableParts)), this, SLOT(axisSelectableChanged(QCPAxis::SelectableParts))); + } - connect(axis(QCPAxis::atLeft), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atRight), SLOT(setRange(QCPRange))); - connect(axis(QCPAxis::atRight), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atLeft), SLOT(setRange(QCPRange))); - connect(axis(QCPAxis::atBottom), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atTop), SLOT(setRange(QCPRange))); - connect(axis(QCPAxis::atTop), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atBottom), SLOT(setRange(QCPRange))); - connect(axis(QCPAxis::atLeft), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atRight), SLOT(setScaleType(QCPAxis::ScaleType))); - connect(axis(QCPAxis::atRight), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atLeft), SLOT(setScaleType(QCPAxis::ScaleType))); - connect(axis(QCPAxis::atBottom), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atTop), SLOT(setScaleType(QCPAxis::ScaleType))); - connect(axis(QCPAxis::atTop), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atBottom), SLOT(setScaleType(QCPAxis::ScaleType))); - - // make layer transfers of color scale transfer to axis rect and axes - // the axes must be set after axis rect, such that they appear above color gradient drawn by axis rect: - connect(parentColorScale, SIGNAL(layerChanged(QCPLayer*)), this, SLOT(setLayer(QCPLayer*))); - foreach (QCPAxis::AxisType type, allAxisTypes) - connect(parentColorScale, SIGNAL(layerChanged(QCPLayer*)), axis(type), SLOT(setLayer(QCPLayer*))); + connect(axis(QCPAxis::atLeft), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atRight), SLOT(setRange(QCPRange))); + connect(axis(QCPAxis::atRight), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atLeft), SLOT(setRange(QCPRange))); + connect(axis(QCPAxis::atBottom), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atTop), SLOT(setRange(QCPRange))); + connect(axis(QCPAxis::atTop), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atBottom), SLOT(setRange(QCPRange))); + connect(axis(QCPAxis::atLeft), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atRight), SLOT(setScaleType(QCPAxis::ScaleType))); + connect(axis(QCPAxis::atRight), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atLeft), SLOT(setScaleType(QCPAxis::ScaleType))); + connect(axis(QCPAxis::atBottom), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atTop), SLOT(setScaleType(QCPAxis::ScaleType))); + connect(axis(QCPAxis::atTop), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atBottom), SLOT(setScaleType(QCPAxis::ScaleType))); + + // make layer transfers of color scale transfer to axis rect and axes + // the axes must be set after axis rect, such that they appear above color gradient drawn by axis rect: + connect(parentColorScale, SIGNAL(layerChanged(QCPLayer *)), this, SLOT(setLayer(QCPLayer *))); + foreach (QCPAxis::AxisType type, allAxisTypes) { + connect(parentColorScale, SIGNAL(layerChanged(QCPLayer *)), axis(type), SLOT(setLayer(QCPLayer *))); + } } /*! \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) { - if (mGradientImageInvalidated) - updateGradientImage(); - - bool mirrorHorz = false; - bool mirrorVert = false; - if (mParentColorScale->mColorAxis) - { - mirrorHorz = mParentColorScale->mColorAxis.data()->rangeReversed() && (mParentColorScale->type() == QCPAxis::atBottom || mParentColorScale->type() == QCPAxis::atTop); - mirrorVert = mParentColorScale->mColorAxis.data()->rangeReversed() && (mParentColorScale->type() == QCPAxis::atLeft || mParentColorScale->type() == QCPAxis::atRight); - } - - painter->drawImage(rect().adjusted(0, -1, 0, -1), mGradientImage.mirrored(mirrorHorz, mirrorVert)); - QCPAxisRect::draw(painter); + if (mGradientImageInvalidated) { + updateGradientImage(); + } + + bool mirrorHorz = false; + bool mirrorVert = false; + if (mParentColorScale->mColorAxis) { + mirrorHorz = mParentColorScale->mColorAxis.data()->rangeReversed() && (mParentColorScale->type() == QCPAxis::atBottom || mParentColorScale->type() == QCPAxis::atTop); + mirrorVert = mParentColorScale->mColorAxis.data()->rangeReversed() && (mParentColorScale->type() == QCPAxis::atLeft || mParentColorScale->type() == QCPAxis::atRight); + } + + painter->drawImage(rect().adjusted(0, -1, 0, -1), mGradientImage.mirrored(mirrorHorz, mirrorVert)); + QCPAxisRect::draw(painter); } /*! \internal @@ -20611,40 +20669,42 @@ void QCPColorScaleAxisRectPrivate::draw(QCPPainter *painter) */ 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); - for (int i=0; imType == QCPAxis::atBottom || mParentColorScale->mType == QCPAxis::atTop) - { - w = n; - h = rect().height(); - mGradientImage = QImage(w, h, format); - QVector pixels; - for (int y=0; y(mGradientImage.scanLine(y))); - mParentColorScale->mGradient.colorize(data.constData(), QCPRange(0, n-1), pixels.first(), n); - for (int y=1; y(mGradientImage.scanLine(y)); - const QRgb lineColor = mParentColorScale->mGradient.color(data[h-1-y], QCPRange(0, n-1)); - for (int x=0; xmGradient.levelCount(); + int w, h; + QVector data(n); + for (int i = 0; i < n; ++i) { + data[i] = i; + } + if (mParentColorScale->mType == QCPAxis::atBottom || mParentColorScale->mType == QCPAxis::atTop) { + w = n; + h = rect().height(); + mGradientImage = QImage(w, h, format); + QVector pixels; + for (int y = 0; y < h; ++y) { + pixels.append(reinterpret_cast(mGradientImage.scanLine(y))); + } + mParentColorScale->mGradient.colorize(data.constData(), QCPRange(0, n - 1), pixels.first(), n); + for (int y = 1; y < h; ++y) { + memcpy(pixels.at(y), pixels.first(), size_t(n)*sizeof(QRgb)); + } + } else { + w = rect().width(); + h = n; + mGradientImage = QImage(w, h, format); + for (int y = 0; y < h; ++y) { + QRgb *pixels = reinterpret_cast(mGradientImage.scanLine(y)); + const QRgb lineColor = mParentColorScale->mGradient.color(data[h - 1 - y], QCPRange(0, n - 1)); + for (int x = 0; x < w; ++x) { + pixels[x] = lineColor; + } + } + } + mGradientImageInvalidated = false; } /*! \internal @@ -20654,22 +20714,22 @@ void QCPColorScaleAxisRectPrivate::updateGradientImage() */ void QCPColorScaleAxisRectPrivate::axisSelectionChanged(QCPAxis::SelectableParts selectedParts) { - // axis bases of four axes shall always (de-)selected synchronously: - const QList allAxisTypes = QList() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight; - foreach (QCPAxis::AxisType type, allAxisTypes) - { - if (QCPAxis *senderAxis = qobject_cast(sender())) - if (senderAxis->axisType() == type) - continue; - - if (axis(type)->selectableParts().testFlag(QCPAxis::spAxis)) - { - if (selectedParts.testFlag(QCPAxis::spAxis)) - axis(type)->setSelectedParts(axis(type)->selectedParts() | QCPAxis::spAxis); - else - axis(type)->setSelectedParts(axis(type)->selectedParts() & ~QCPAxis::spAxis); + // axis bases of four axes shall always (de-)selected synchronously: + const QList allAxisTypes = QList() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight; + foreach (QCPAxis::AxisType type, allAxisTypes) { + if (QCPAxis *senderAxis = qobject_cast(sender())) + if (senderAxis->axisType() == type) { + continue; + } + + if (axis(type)->selectableParts().testFlag(QCPAxis::spAxis)) { + if (selectedParts.testFlag(QCPAxis::spAxis)) { + axis(type)->setSelectedParts(axis(type)->selectedParts() | QCPAxis::spAxis); + } else { + axis(type)->setSelectedParts(axis(type)->selectedParts() & ~QCPAxis::spAxis); + } + } } - } } /*! \internal @@ -20679,22 +20739,22 @@ void QCPColorScaleAxisRectPrivate::axisSelectionChanged(QCPAxis::SelectableParts */ void QCPColorScaleAxisRectPrivate::axisSelectableChanged(QCPAxis::SelectableParts selectableParts) { - // synchronize axis base selectability: - const QList allAxisTypes = QList() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight; - foreach (QCPAxis::AxisType type, allAxisTypes) - { - if (QCPAxis *senderAxis = qobject_cast(sender())) - if (senderAxis->axisType() == type) - continue; - - if (axis(type)->selectableParts().testFlag(QCPAxis::spAxis)) - { - if (selectableParts.testFlag(QCPAxis::spAxis)) - axis(type)->setSelectableParts(axis(type)->selectableParts() | QCPAxis::spAxis); - else - axis(type)->setSelectableParts(axis(type)->selectableParts() & ~QCPAxis::spAxis); + // synchronize axis base selectability: + const QList allAxisTypes = QList() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight; + foreach (QCPAxis::AxisType type, allAxisTypes) { + if (QCPAxis *senderAxis = qobject_cast(sender())) + if (senderAxis->axisType() == type) { + continue; + } + + if (axis(type)->selectableParts().testFlag(QCPAxis::spAxis)) { + if (selectableParts.testFlag(QCPAxis::spAxis)) { + axis(type)->setSelectableParts(axis(type)->selectableParts() | QCPAxis::spAxis); + } else { + axis(type)->setSelectableParts(axis(type)->selectableParts() & ~QCPAxis::spAxis); + } + } } - } } /* end of 'src/layoutelements/layoutelement-colorscale.cpp' */ @@ -20708,65 +20768,65 @@ void QCPColorScaleAxisRectPrivate::axisSelectableChanged(QCPAxis::SelectablePart /*! \class QCPGraphData \brief Holds the data of one single data point for QCPGraph. - + 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 value: coordinate on the value axis of this data point (this is the \a mainValue) - + The container for storing multiple data points is \ref QCPGraphDataContainer. It is a typedef for \ref QCPDataContainer with \ref QCPGraphData as the DataType template parameter. See the documentation there for an explanation regarding the data type's generic methods. - + \see QCPGraphDataContainer */ /* start documentation of inline functions */ /*! \fn double QCPGraphData::sortKey() const - + Returns the \a key member of this data point. - + For a general explanation of what this method is good for in the context of the data container, see the documentation of \ref QCPDataContainer. */ /*! \fn static QCPGraphData QCPGraphData::fromSortKey(double sortKey) - + Returns a data point with the specified \a sortKey. All other members are set to zero. - + For a general explanation of what this method is good for in the context of the data container, see the documentation of \ref QCPDataContainer. */ /*! \fn static static bool QCPGraphData::sortKeyIsMainKey() - + Since the member \a key is both the data point key coordinate and the data ordering parameter, this method returns true. - + For a general explanation of what this method is good for in the context of the data container, see the documentation of \ref QCPDataContainer. */ /*! \fn double QCPGraphData::mainKey() const - + Returns the \a key member of this data point. - + For a general explanation of what this method is good for in the context of the data container, see the documentation of \ref QCPDataContainer. */ /*! \fn double QCPGraphData::mainValue() const - + Returns the \a value member of this data point. - + For a general explanation of what this method is good for in the context of the data container, see the documentation of \ref QCPDataContainer. */ /*! \fn QCPRange QCPGraphData::valueRange() const - + Returns a QCPRange with both lower and upper boundary set to \a value of this data point. - + For a general explanation of what this method is good for in the context of the data container, see the documentation of \ref QCPDataContainer. */ @@ -20777,8 +20837,8 @@ void QCPColorScaleAxisRectPrivate::axisSelectableChanged(QCPAxis::SelectablePart Constructs a data point with key and value set to zero. */ QCPGraphData::QCPGraphData() : - key(0), - value(0) + key(0), + value(0) { } @@ -20786,8 +20846,8 @@ QCPGraphData::QCPGraphData() : Constructs a data point with the specified \a key and \a value. */ QCPGraphData::QCPGraphData(double key, double value) : - key(key), - value(value) + key(key), + value(value) { } @@ -20800,33 +20860,33 @@ QCPGraphData::QCPGraphData(double key, double value) : \brief A plottable representing a graph in a plot. \image html QCPGraph.png - + 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 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 want to plot non-single-valued curves, rather use the QCPCurve plottable. - + Gaps in the graph line can be created by adding data points with NaN as value (qQNaN() or std::numeric_limits::quiet_NaN()) in between the two data points that shall be separated. - + \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). - + \subsection filling Filling under or between graphs - + QCPGraph knows two types of fills: Normal graph fills towards the zero-value-line parallel to the key axis of the graph, and fills between two graphs, called channel fills. To enable a fill, just set a brush with \ref setBrush which is neither Qt::NoBrush nor fully transparent. - + By default, a normal fill towards the zero-value-line will be drawn. To set up a channel fill between this graph and another one, call \ref setChannelFillGraph with the other graph as parameter. @@ -20837,7 +20897,7 @@ QCPGraphData::QCPGraphData(double key, double value) : /* start of documentation of inline functions */ /*! \fn QSharedPointer QCPGraph::data() const - + 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. @@ -20850,29 +20910,29 @@ QCPGraphData::QCPGraphData(double key, double 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 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) : - QCPAbstractPlottable1D(keyAxis, valueAxis), - mLineStyle{}, - mScatterSkip{}, - mAdaptiveSampling{} + QCPAbstractPlottable1D(keyAxis, valueAxis), + mLineStyle{}, + mScatterSkip{}, + mAdaptiveSampling{} { - // special handling for QCPGraphs to maintain the simple graph interface: - mParentPlot->registerGraph(this); + // special handling for QCPGraphs to maintain the simple graph interface: + mParentPlot->registerGraph(this); - setPen(QPen(Qt::blue, 0)); - setBrush(Qt::NoBrush); - - setLineStyle(lsLine); - setScatterSkip(0); - setChannelFillGraph(nullptr); - setAdaptiveSampling(true); + setPen(QPen(Qt::blue, 0)); + setBrush(Qt::NoBrush); + + setLineStyle(lsLine); + setScatterSkip(0); + setChannelFillGraph(nullptr); + setAdaptiveSampling(true); } QCPGraph::~QCPGraph() @@ -20880,62 +20940,62 @@ QCPGraph::~QCPGraph() } /*! \overload - + 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; + 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 QCPGraph::setData(const QVector &keys, const QVector &values, bool alreadySorted) { - mDataContainer->clear(); - addData(keys, values, alreadySorted); + mDataContainer->clear(); + addData(keys, values, alreadySorted); } /*! Sets how the single data points are connected in the plot. For scatter-only plots, set \a ls to \ref lsNone and \ref setScatterStyle to the desired scatter style. - + \see setScatterStyle */ void QCPGraph::setLineStyle(LineStyle ls) { - mLineStyle = ls; + mLineStyle = ls; } /*! Sets the visual appearance of single data points in the plot. If set to \ref QCPScatterStyle::ssNone, no scatter points are drawn (e.g. for line-only-plots with appropriate line style). - + \see QCPScatterStyle, setLineStyle */ void QCPGraph::setScatterStyle(const QCPScatterStyle &style) { - mScatterStyle = style; + mScatterStyle = style; } /*! @@ -20951,13 +21011,13 @@ void QCPGraph::setScatterStyle(const QCPScatterStyle &style) */ void QCPGraph::setScatterSkip(int skip) { - mScatterSkip = qMax(0, skip); + mScatterSkip = qMax(0, skip); } /*! Sets the target graph for filling the area between this graph and \a targetGraph with the current brush (\ref setBrush). - + When \a targetGraph is set to 0, a normal graph fill to the zero-value-line will be shown. To disable any filling, set the brush to Qt::NoBrush. @@ -20965,41 +21025,39 @@ void QCPGraph::setScatterSkip(int skip) */ void QCPGraph::setChannelFillGraph(QCPGraph *targetGraph) { - // prevent setting channel target to this graph itself: - if (targetGraph == this) - { - qDebug() << Q_FUNC_INFO << "targetGraph is this graph itself"; - mChannelFillGraph = nullptr; - return; - } - // prevent setting channel target to a graph not in the plot: - if (targetGraph && targetGraph->mParentPlot != mParentPlot) - { - qDebug() << Q_FUNC_INFO << "targetGraph not in same plot"; - mChannelFillGraph = nullptr; - return; - } - - mChannelFillGraph = targetGraph; + // prevent setting channel target to this graph itself: + if (targetGraph == this) { + qDebug() << Q_FUNC_INFO << "targetGraph is this graph itself"; + mChannelFillGraph = nullptr; + return; + } + // prevent setting channel target to a graph not in the plot: + if (targetGraph && targetGraph->mParentPlot != mParentPlot) { + qDebug() << Q_FUNC_INFO << "targetGraph not in same plot"; + mChannelFillGraph = nullptr; + return; + } + + mChannelFillGraph = targetGraph; } /*! Sets whether adaptive sampling shall be used when plotting this graph. QCustomPlot's adaptive sampling technique can drastically improve the replot performance for graphs with a larger number of points (e.g. above 10,000), without notably changing the appearance of the graph. - + By default, adaptive sampling is enabled. Even if enabled, QCustomPlot decides whether adaptive sampling shall actually be used on a per-graph basis. So leaving adaptive sampling enabled has no disadvantage in almost all cases. - + \image html adaptive-sampling-line.png "A line plot of 500,000 points without and with adaptive sampling" - + As can be seen, line plots experience no visual degradation from adaptive sampling. Outliers are reproduced reliably, as well as the overall shape of the data set. The replot time reduces dramatically though. This allows QCustomPlot to display large amounts of data in realtime. - + \image html adaptive-sampling-scatter.png "A scatter plot of 100,000 points without and with adaptive sampling" - + Care must be taken when using high-density scatter plots in combination with adaptive sampling. The adaptive sampling algorithm treats scatter plots more carefully than line plots which still gives a significant reduction of replot times, but not quite as much as for line plots. This is @@ -21008,7 +21066,7 @@ void QCPGraph::setChannelFillGraph(QCPGraph *targetGraph) identical, as banding occurs for the outer data points. This is in fact intentional, such that the boundaries of the data cloud stay visible to the viewer. How strong the banding appears, depends on the point density, i.e. the number of points in the plot. - + For some situations with scatter plots it might thus be desirable to manually turn adaptive sampling off. For example, when saving the plot to disk. This can be achieved by setting \a enabled to false before issuing a command like \ref QCustomPlot::savePng, and setting \a enabled @@ -21016,50 +21074,50 @@ void QCPGraph::setChannelFillGraph(QCPGraph *targetGraph) */ void QCPGraph::setAdaptiveSampling(bool enabled) { - mAdaptiveSampling = enabled; + mAdaptiveSampling = enabled; } /*! \overload - + 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 QCPGraph::addData(const QVector &keys, const QVector &values, bool alreadySorted) { - 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 + 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 data point as \a key and \a value to the current data. - + Alternatively, you can also access and modify the data directly via the \ref data method, which returns a pointer to the internal data container. */ void QCPGraph::addData(double key, double value) { - mDataContainer->add(QCPGraphData(key, value)); + mDataContainer->add(QCPGraphData(key, value)); } /*! @@ -21067,143 +21125,148 @@ void QCPGraph::addData(double key, double value) If \a details is not 0, it will be set to a \ref QCPDataSelection, describing the closest data point to \a pos. - + \seebaseclassmethod \ref QCPAbstractPlottable::selectTest */ double QCPGraph::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { - if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty()) - return -1; - if (!mKeyAxis || !mValueAxis) - return -1; - - if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()) || mParentPlot->interactions().testFlag(QCP::iSelectPlottablesBeyondAxisRect)) - { - QCPGraphDataContainer::const_iterator closestDataPoint = mDataContainer->constEnd(); - double result = pointDistance(pos, closestDataPoint); - if (details) - { - int pointIndex = int(closestDataPoint-mDataContainer->constBegin()); - details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1))); + if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty()) { + return -1; + } + if (!mKeyAxis || !mValueAxis) { + return -1; + } + + if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()) || mParentPlot->interactions().testFlag(QCP::iSelectPlottablesBeyondAxisRect)) { + QCPGraphDataContainer::const_iterator closestDataPoint = mDataContainer->constEnd(); + double result = pointDistance(pos, closestDataPoint); + if (details) { + int pointIndex = int(closestDataPoint - mDataContainer->constBegin()); + details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex + 1))); + } + return result; + } else { + return -1; } - return result; - } else - return -1; } /* inherits documentation from base class */ QCPRange QCPGraph::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const { - return mDataContainer->keyRange(foundRange, inSignDomain); + return mDataContainer->keyRange(foundRange, inSignDomain); } /* inherits documentation from base class */ QCPRange QCPGraph::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const { - return mDataContainer->valueRange(foundRange, inSignDomain, inKeyRange); + 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 || mDataContainer->isEmpty()) return; - if (mLineStyle == lsNone && mScatterStyle.isNone()) return; - - QVector lines, scatters; // line and (if necessary) scatter pixel coordinates will be stored here while iterating over segments - - // 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: + if (!mKeyAxis || !mValueAxis) { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + return; + } + if (mKeyAxis.data()->range().size() <= 0 || mDataContainer->isEmpty()) { + return; + } + if (mLineStyle == lsNone && mScatterStyle.isNone()) { + return; + } + + QVector lines, scatters; // line and (if necessary) scatter pixel coordinates will be stored here while iterating over segments + + // loop over and draw segments of unselected/selected data: + QList selectedSegments, unselectedSegments, allSegments; + getDataSegments(selectedSegments, unselectedSegments); + allSegments << unselectedSegments << selectedSegments; + for (int i = 0; i < allSegments.size(); ++i) { + bool isSelectedSegment = i >= unselectedSegments.size(); + // get line pixel points appropriate to line style: + QCPDataRange lineDataRange = isSelectedSegment ? allSegments.at(i) : allSegments.at(i).adjusted(-1, 1); // unselected segments extend lines to bordering selected data point (safe to exceed total data bounds in first/last segment, getLines takes care) + getLines(&lines, lineDataRange); + + // check data validity if flag set: #ifdef QCUSTOMPLOT_CHECK_DATA - QCPGraphDataContainer::const_iterator it; - for (it = mDataContainer->constBegin(); it != mDataContainer->constEnd(); ++it) - { - if (QCP::isInvalidData(it->key, it->value)) - qDebug() << Q_FUNC_INFO << "Data point at" << it->key << "invalid." << "Plottable name:" << name(); - } + 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: - 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 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 scatters: - QCPScatterStyle finalScatterStyle = mScatterStyle; - if (isSelectedSegment && mSelectionDecorator) - finalScatterStyle = mSelectionDecorator->getFinalScatterStyle(mScatterStyle); - if (!finalScatterStyle.isNone()) - { - getScatters(&scatters, allSegments.at(i)); - drawScatterPlot(painter, scatters, finalScatterStyle); + + // draw other selection decoration that isn't just line/scatter pens and brushes: + if (mSelectionDecorator) { + mSelectionDecorator->drawDecoration(painter, selection()); } - } - - // 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 QCPGraph::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const { - // draw fill: - if (mBrush.style() != Qt::NoBrush) - { - applyFillAntialiasingHint(painter); - painter->fillRect(QRectF(rect.left(), rect.top()+rect.height()/2.0, rect.width(), rect.height()/3.0), mBrush); - } - // draw line vertically centered: - if (mLineStyle != lsNone) - { - applyDefaultAntialiasingHint(painter); - painter->setPen(mPen); - painter->drawLine(QLineF(rect.left(), rect.top()+rect.height()/2.0, rect.right()+5, rect.top()+rect.height()/2.0)); // +5 on x2 else last segment is missing from dashed/dotted pens - } - // draw scatter symbol: - if (!mScatterStyle.isNone()) - { - applyScattersAntialiasingHint(painter); - // scale scatter pixmap if it's too large to fit in legend icon rect: - if (mScatterStyle.shape() == QCPScatterStyle::ssPixmap && (mScatterStyle.pixmap().size().width() > rect.width() || mScatterStyle.pixmap().size().height() > rect.height())) - { - QCPScatterStyle scaledStyle(mScatterStyle); - scaledStyle.setPixmap(scaledStyle.pixmap().scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation)); - scaledStyle.applyTo(painter, mPen); - scaledStyle.drawShape(painter, QRectF(rect).center()); - } else - { - mScatterStyle.applyTo(painter, mPen); - mScatterStyle.drawShape(painter, QRectF(rect).center()); + // draw fill: + if (mBrush.style() != Qt::NoBrush) { + applyFillAntialiasingHint(painter); + painter->fillRect(QRectF(rect.left(), rect.top() + rect.height() / 2.0, rect.width(), rect.height() / 3.0), mBrush); + } + // draw line vertically centered: + if (mLineStyle != lsNone) { + applyDefaultAntialiasingHint(painter); + painter->setPen(mPen); + painter->drawLine(QLineF(rect.left(), rect.top() + rect.height() / 2.0, rect.right() + 5, rect.top() + rect.height() / 2.0)); // +5 on x2 else last segment is missing from dashed/dotted pens + } + // draw scatter symbol: + if (!mScatterStyle.isNone()) { + applyScattersAntialiasingHint(painter); + // scale scatter pixmap if it's too large to fit in legend icon rect: + if (mScatterStyle.shape() == QCPScatterStyle::ssPixmap && (mScatterStyle.pixmap().size().width() > rect.width() || mScatterStyle.pixmap().size().height() > rect.height())) { + QCPScatterStyle scaledStyle(mScatterStyle); + scaledStyle.setPixmap(scaledStyle.pixmap().scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation)); + scaledStyle.applyTo(painter, mPen); + scaledStyle.drawShape(painter, QRectF(rect).center()); + } else { + mScatterStyle.applyTo(painter, mPen); + mScatterStyle.drawShape(painter, QRectF(rect).center()); + } } - } } /*! \internal @@ -21228,31 +21291,45 @@ void QCPGraph::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const */ void QCPGraph::getLines(QVector *lines, const QCPDataRange &dataRange) const { - if (!lines) return; - QCPGraphDataContainer::const_iterator begin, end; - getVisibleDataBounds(begin, end, dataRange); - if (begin == end) - { - lines->clear(); - return; - } - - QVector lineData; - if (mLineStyle != lsNone) - getOptimizedLineData(&lineData, begin, end); - - if (mKeyAxis->rangeReversed() != (mKeyAxis->orientation() == Qt::Vertical)) // make sure key pixels are sorted ascending in lineData (significantly simplifies following processing) - std::reverse(lineData.begin(), lineData.end()); + if (!lines) { + return; + } + QCPGraphDataContainer::const_iterator begin, end; + getVisibleDataBounds(begin, end, dataRange); + if (begin == end) { + lines->clear(); + return; + } - 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; - } + QVector lineData; + if (mLineStyle != lsNone) { + getOptimizedLineData(&lineData, begin, end); + } + + if (mKeyAxis->rangeReversed() != (mKeyAxis->orientation() == Qt::Vertical)) { // make sure key pixels are sorted ascending in lineData (significantly simplifies following processing) + std::reverse(lineData.begin(), lineData.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 @@ -21269,54 +21346,54 @@ void QCPGraph::getLines(QVector *lines, const QCPDataRange &dataRange) */ 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"; scatters->clear(); return; } - - QCPGraphDataContainer::const_iterator begin, end; - getVisibleDataBounds(begin, end, dataRange); - if (begin == end) - { - scatters->clear(); - return; - } - - QVector data; - getOptimizedScatterData(&data, begin, end); - - if (mKeyAxis->rangeReversed() != (mKeyAxis->orientation() == Qt::Vertical)) // make sure key pixels are sorted ascending in data (significantly simplifies following processing) - std::reverse(data.begin(), data.end()); - - scatters->resize(data.size()); - if (keyAxis->orientation() == Qt::Vertical) - { - for (int i=0; icoordToPixel(data.at(i).value)); - (*scatters)[i].setY(keyAxis->coordToPixel(data.at(i).key)); - } + if (!scatters) { + return; } - } else - { - for (int i=0; icoordToPixel(data.at(i).key)); - (*scatters)[i].setY(valueAxis->coordToPixel(data.at(i).value)); - } + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + scatters->clear(); + return; + } + + QCPGraphDataContainer::const_iterator begin, end; + getVisibleDataBounds(begin, end, dataRange); + if (begin == end) { + scatters->clear(); + return; + } + + QVector data; + getOptimizedScatterData(&data, begin, end); + + if (mKeyAxis->rangeReversed() != (mKeyAxis->orientation() == Qt::Vertical)) { // make sure key pixels are sorted ascending in data (significantly simplifies following processing) + std::reverse(data.begin(), data.end()); + } + + scatters->resize(data.size()); + if (keyAxis->orientation() == Qt::Vertical) { + for (int i = 0; i < data.size(); ++i) { + if (!qIsNaN(data.at(i).value)) { + (*scatters)[i].setX(valueAxis->coordToPixel(data.at(i).value)); + (*scatters)[i].setY(keyAxis->coordToPixel(data.at(i).key)); + } + } + } else { + for (int i = 0; i < data.size(); ++i) { + if (!qIsNaN(data.at(i).value)) { + (*scatters)[i].setX(keyAxis->coordToPixel(data.at(i).key)); + (*scatters)[i].setY(valueAxis->coordToPixel(data.at(i).value)); + } + } } - } } /*! \internal 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. - + The source of \a data is usually \ref getOptimizedLineData, and this method is called in \a getLines if the line style is set accordingly. @@ -21324,37 +21401,36 @@ void QCPGraph::getScatters(QVector *scatters, const QCPDataRange &dataR */ 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; } + 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()); - - // 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)); + result.resize(data.size()); + + // transform data points to pixels: + if (keyAxis->orientation() == Qt::Vertical) { + for (int i = 0; i < data.size(); ++i) { + result[i].setX(valueAxis->coordToPixel(data.at(i).value)); + result[i].setY(keyAxis->coordToPixel(data.at(i).key)); + } + } else { // key axis is horizontal + for (int i = 0; i < data.size(); ++i) { + result[i].setX(keyAxis->coordToPixel(data.at(i).key)); + result[i].setY(valueAxis->coordToPixel(data.at(i).value)); + } } - } 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; + 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. @@ -21362,47 +21438,46 @@ QVector QCPGraph::dataToLines(const QVector &data) const */ 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.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); + QVector result; + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + return result; } - } 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); + + 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; i < data.size(); ++i) { + const double key = keyAxis->coordToPixel(data.at(i).key); + result[i * 2 + 0].setX(lastValue); + result[i * 2 + 0].setY(key); + lastValue = valueAxis->coordToPixel(data.at(i).value); + result[i * 2 + 1].setX(lastValue); + result[i * 2 + 1].setY(key); + } + } else { // key axis is horizontal + double lastValue = valueAxis->coordToPixel(data.first().value); + for (int i = 0; i < data.size(); ++i) { + const double key = keyAxis->coordToPixel(data.at(i).key); + result[i * 2 + 0].setX(key); + result[i * 2 + 0].setY(lastValue); + lastValue = valueAxis->coordToPixel(data.at(i).value); + result[i * 2 + 1].setX(key); + result[i * 2 + 1].setY(lastValue); + } } - } - return result; + 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. @@ -21410,47 +21485,46 @@ QVector QCPGraph::dataToStepLeftLines(const QVector &data */ 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.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); + QVector result; + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + return result; } - } 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); + + 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; i < data.size(); ++i) { + const double value = valueAxis->coordToPixel(data.at(i).value); + result[i * 2 + 0].setX(value); + result[i * 2 + 0].setY(lastKey); + lastKey = keyAxis->coordToPixel(data.at(i).key); + result[i * 2 + 1].setX(value); + result[i * 2 + 1].setY(lastKey); + } + } else { // key axis is horizontal + double lastKey = keyAxis->coordToPixel(data.first().key); + for (int i = 0; i < data.size(); ++i) { + const double value = valueAxis->coordToPixel(data.at(i).value); + result[i * 2 + 0].setX(lastKey); + result[i * 2 + 0].setY(value); + lastKey = keyAxis->coordToPixel(data.at(i).key); + result[i * 2 + 1].setX(lastKey); + result[i * 2 + 1].setY(value); + } } - } - return result; + 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. @@ -21458,59 +21532,58 @@ QVector QCPGraph::dataToStepRightLines(const QVector &dat */ 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.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); + 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[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.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; i < data.size(); ++i) { + const double key = (keyAxis->coordToPixel(data.at(i).key) + lastKey) * 0.5; + result[i * 2 - 1].setX(lastValue); + result[i * 2 - 1].setY(key); + lastValue = valueAxis->coordToPixel(data.at(i).value); + lastKey = keyAxis->coordToPixel(data.at(i).key); + result[i * 2 + 0].setX(lastValue); + result[i * 2 + 0].setY(key); + } + result[data.size() * 2 - 1].setX(lastValue); + result[data.size() * 2 - 1].setY(lastKey); + } else { // key axis is horizontal + double lastKey = keyAxis->coordToPixel(data.first().key); + double lastValue = valueAxis->coordToPixel(data.first().value); + result[0].setX(lastKey); + result[0].setY(lastValue); + for (int i = 1; i < data.size(); ++i) { + const double key = (keyAxis->coordToPixel(data.at(i).key) + lastKey) * 0.5; + result[i * 2 - 1].setX(key); + result[i * 2 - 1].setY(lastValue); + lastValue = valueAxis->coordToPixel(data.at(i).value); + lastKey = keyAxis->coordToPixel(data.at(i).key); + result[i * 2 + 0].setX(key); + result[i * 2 + 0].setY(lastValue); + } + result[data.size() * 2 - 1].setX(lastKey); + result[data.size() * 2 - 1].setY(lastValue); } - result[data.size()*2-1].setX(lastKey); - result[data.size()*2-1].setY(lastValue); - } - return result; + 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. @@ -21518,80 +21591,91 @@ QVector QCPGraph::dataToStepCenterLines(const QVector &da */ 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); - - // 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); + QVector result; + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + return result; } - } 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)); + + result.resize(data.size() * 2); + + // transform data points to pixels: + if (keyAxis->orientation() == Qt::Vertical) { + for (int i = 0; i < data.size(); ++i) { + const double key = keyAxis->coordToPixel(data.at(i).key); + result[i * 2 + 0].setX(valueAxis->coordToPixel(0)); + result[i * 2 + 0].setY(key); + result[i * 2 + 1].setX(valueAxis->coordToPixel(data.at(i).value)); + result[i * 2 + 1].setY(key); + } + } else { // key axis is horizontal + for (int i = 0; i < data.size(); ++i) { + const double key = keyAxis->coordToPixel(data.at(i).key); + result[i * 2 + 0].setX(key); + result[i * 2 + 0].setY(valueAxis->coordToPixel(0)); + result[i * 2 + 1].setX(key); + result[i * 2 + 1].setY(valueAxis->coordToPixel(data.at(i).value)); + } } - } - return result; + return result; +} + +void QCPGraph::setSmooth(int smooth) +{ + this->smooth = smooth; } /*! \internal - + Draws the fill of the graph using the specified \a painter, with the currently set brush. - + Depending on whether a normal fill or a channel fill (\ref setChannelFillGraph) is needed, \ref getFillPolygon or \ref getChannelFillPolygon are used to find the according fill polygons. - + In order to handle NaN Data points correctly (the fill needs to be split into disjoint areas), this method first determines a list of non-NaN segments with \ref getNonNanSegments, on which to operate. In the channel fill case, \ref getOverlappingSegments is used to consolidate the non-NaN segments of the two involved graphs, before passing the overlapping pairs to \ref getChannelFillPolygon. - + Pass the points of this graph's line as \a lines, in pixel coordinates. \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 (painter->brush().style() == Qt::NoBrush || painter->brush().color().alpha() == 0) return; - - applyFillAntialiasingHint(painter); - const QVector segments = getNonNanSegments(lines, keyAxis()->orientation()); - if (!mChannelFillGraph) - { - // draw base fill under graph, fill goes all the way to the zero-value-line: - foreach (QCPDataRange segment, segments) - painter->drawPolygon(getFillPolygon(lines, segment)); - } else - { - // draw fill between this graph and mChannelFillGraph: - QVector otherLines; - mChannelFillGraph->getLines(&otherLines, QCPDataRange(0, mChannelFillGraph->dataCount())); - if (!otherLines.isEmpty()) - { - QVector otherSegments = getNonNanSegments(&otherLines, mChannelFillGraph->keyAxis()->orientation()); - QVector > segmentPairs = getOverlappingSegments(segments, lines, otherSegments, &otherLines); - for (int i=0; idrawPolygon(getChannelFillPolygon(lines, segmentPairs.at(i).first, &otherLines, segmentPairs.at(i).second)); + if (mLineStyle == lsImpulse) { + return; // fill doesn't make sense for impulse plot + } + if (painter->brush().style() == Qt::NoBrush || painter->brush().color().alpha() == 0) { + return; + } + + applyFillAntialiasingHint(painter); + const QVector segments = getNonNanSegments(lines, keyAxis()->orientation()); + if (!mChannelFillGraph) { + // draw base fill under graph, fill goes all the way to the zero-value-line: + foreach (QCPDataRange segment, segments) { + if (smooth > 0) { + painter->drawPath(getFillPath(lines, segment)); + } else { + painter->drawPolygon(getFillPolygon(lines, segment)); + } + } + } else { + // draw fill between this graph and mChannelFillGraph: + QVector otherLines; + mChannelFillGraph->getLines(&otherLines, QCPDataRange(0, mChannelFillGraph->dataCount())); + if (!otherLines.isEmpty()) { + QVector otherSegments = getNonNanSegments(&otherLines, mChannelFillGraph->keyAxis()->orientation()); + QVector > segmentPairs = getOverlappingSegments(segments, lines, otherSegments, &otherLines); + for (int i = 0; i < segmentPairs.size(); ++i) { + painter->drawPolygon(getChannelFillPolygon(lines, segmentPairs.at(i).first, &otherLines, segmentPairs.at(i).second)); + } + } } - } } /*! \internal @@ -21603,25 +21687,35 @@ void QCPGraph::drawFill(QCPPainter *painter, QVector *lines) const */ void QCPGraph::drawScatterPlot(QCPPainter *painter, const QVector &scatters, const QCPScatterStyle &style) const { - applyScattersAntialiasingHint(painter); - style.applyTo(painter, mPen); - foreach (const QPointF &scatter, scatters) - style.drawShape(painter, scatter.x(), scatter.y()); + applyScattersAntialiasingHint(painter); + style.applyTo(painter, mPen); + foreach (const QPointF &scatter, scatters) { + style.drawShape(painter, scatter.x(), scatter.y()); + } } /*! \internal - + Draws lines between the points in \a lines, given in pixel coordinates. - + \see drawScatterPlot, drawImpulsePlot, QCPAbstractPlottable1D::drawPolyline */ void QCPGraph::drawLinePlot(QCPPainter *painter, const QVector &lines) const { - if (painter->pen().style() != Qt::NoPen && painter->pen().color().alpha() != 0) - { - applyDefaultAntialiasingHint(painter); - drawPolyline(painter, lines); - } + if (painter->pen().style() != Qt::NoPen && painter->pen().color().alpha() != 0) { + applyDefaultAntialiasingHint(painter); + //开启了平滑曲线则应用对应算法绘制平滑路径 + if (mLineStyle == lsLine) { + if (smooth == 1) { + painter->drawPath(SmoothCurve::createSmoothCurve(lines)); + return; + } else if (smooth == 2) { + painter->drawPath(SmoothCurve::createSmoothCurve2(lines)); + return; + } + } + drawPolyline(painter, lines); + } } /*! \internal @@ -21634,16 +21728,15 @@ void QCPGraph::drawLinePlot(QCPPainter *painter, const QVector &lines) */ void QCPGraph::drawImpulsePlot(QCPPainter *painter, const QVector &lines) const { - if (painter->pen().style() != Qt::NoPen && painter->pen().color().alpha() != 0) - { - applyDefaultAntialiasingHint(painter); - 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); - } + if (painter->pen().style() != Qt::NoPen && painter->pen().color().alpha() != 0) { + applyDefaultAntialiasingHint(painter); + 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 @@ -21660,82 +21753,89 @@ void QCPGraph::drawImpulsePlot(QCPPainter *painter, const QVector &line */ 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; } - if (begin == end) return; - - int dataCount = int(end-begin); - int maxCount = (std::numeric_limits::max)(); - if (mAdaptiveSampling) - { - double keyPixelSpan = qAbs(keyAxis->coordToPixel(begin->key)-keyAxis->coordToPixel((end-1)->key)); - if (2*keyPixelSpan+2 < static_cast((std::numeric_limits::max)())) - maxCount = int(2*keyPixelSpan+2); - } - - if (mAdaptiveSampling && dataCount >= maxCount) // use adaptive sampling only if there are at least two points per pixel on average - { - QCPGraphDataContainer::const_iterator it = begin; - double minValue = it->value; - double maxValue = it->value; - QCPGraphDataContainer::const_iterator currentIntervalFirstPoint = it; - int reversedFactor = keyAxis->pixelOrientation(); // is used to calculate keyEpsilon pixel into the correct direction - int reversedRound = reversedFactor==-1 ? 1 : 0; // is used to switch between floor (normal) and ceil (reversed) rounding of currentIntervalStartKey - double currentIntervalStartKey = keyAxis->pixelToCoord(int(keyAxis->coordToPixel(begin->key)+reversedRound)); - double lastIntervalEndKey = currentIntervalStartKey; - double keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor)); // interval of one pixel on screen when mapped to plot key coordinates - bool keyEpsilonVariable = keyAxis->scaleType() == QCPAxis::stLogarithmic; // indicates whether keyEpsilon needs to be updated after every interval (for log axes) - int intervalDataCount = 1; - ++it; // advance iterator to second data point because adaptive sampling works in 1 point retrospect - while (it != end) - { - if (it->key < currentIntervalStartKey+keyEpsilon) // data point is still within same pixel, so skip it and expand value span of this cluster if necessary - { - if (it->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 (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; - } - ++it; + if (!lineData) { + return; + } + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + return; + } + if (begin == end) { + return; + } + + int dataCount = int(end - begin); + int maxCount = (std::numeric_limits::max)(); + if (mAdaptiveSampling) { + double keyPixelSpan = qAbs(keyAxis->coordToPixel(begin->key) - keyAxis->coordToPixel((end - 1)->key)); + if (2 * keyPixelSpan + 2 < static_cast((std::numeric_limits::max)())) { + maxCount = int(2 * keyPixelSpan + 2); + } + } + + if (mAdaptiveSampling && dataCount >= maxCount) { // use adaptive sampling only if there are at least two points per pixel on average + QCPGraphDataContainer::const_iterator it = begin; + double minValue = it->value; + double maxValue = it->value; + QCPGraphDataContainer::const_iterator currentIntervalFirstPoint = it; + int reversedFactor = keyAxis->pixelOrientation(); // is used to calculate keyEpsilon pixel into the correct direction + int reversedRound = reversedFactor == -1 ? 1 : 0; // is used to switch between floor (normal) and ceil (reversed) rounding of currentIntervalStartKey + double currentIntervalStartKey = keyAxis->pixelToCoord(int(keyAxis->coordToPixel(begin->key) + reversedRound)); + double lastIntervalEndKey = currentIntervalStartKey; + double keyEpsilon = qAbs(currentIntervalStartKey - keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey) + 1.0 * reversedFactor)); // interval of one pixel on screen when mapped to plot key coordinates + bool keyEpsilonVariable = keyAxis->scaleType() == QCPAxis::stLogarithmic; // indicates whether keyEpsilon needs to be updated after every interval (for log axes) + int intervalDataCount = 1; + ++it; // advance iterator to second data point because adaptive sampling works in 1 point retrospect + while (it != end) { + if (it->key < currentIntervalStartKey + keyEpsilon) { // data point is still within same pixel, so skip it and expand value span of this cluster if necessary + if (it->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 (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; + } + ++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)); + } + + } else { // don't use adaptive sampling algorithm, transfer points one-to-one from the data container into the output + lineData->resize(dataCount); + std::copy(begin, end, lineData->begin()); } - // 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)); - - } else // don't use adaptive sampling algorithm, transfer points one-to-one from the data container into the output - { - lineData->resize(dataCount); - std::copy(begin, end, lineData->begin()); - } } /*! \internal @@ -21752,174 +21852,165 @@ void QCPGraph::getOptimizedLineData(QVector *lineData, const QCPGr */ void QCPGraph::getOptimizedScatterData(QVector *scatterData, QCPGraphDataContainer::const_iterator begin, QCPGraphDataContainer::const_iterator end) const { - if (!scatterData) return; - QCPAxis *keyAxis = mKeyAxis.data(); - QCPAxis *valueAxis = mValueAxis.data(); - if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } - - const int scatterModulo = mScatterSkip+1; - const bool doScatterSkip = mScatterSkip > 0; - int beginIndex = int(begin-mDataContainer->constBegin()); - int endIndex = int(end-mDataContainer->constBegin()); - while (doScatterSkip && begin != end && beginIndex % scatterModulo != 0) // advance begin iterator to first non-skipped scatter - { - ++beginIndex; - ++begin; - } - if (begin == end) return; - int dataCount = int(end-begin); - int maxCount = (std::numeric_limits::max)(); - if (mAdaptiveSampling) - { - int keyPixelSpan = int(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 = int(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 - { - itIndex += scatterModulo; - if (itIndex < endIndex) // make sure we didn't jump over end - it += scatterModulo; - else - { - it = end; - itIndex = endIndex; - } + if (!scatterData) { + return; } - // main loop over data points: - while (it != end) - { - if (it->key < currentIntervalStartKey+keyEpsilon) // data point is still within same pixel, so skip it and expand value span of this pixel if necessary - { - if (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; - } - } + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + return; } - // 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 = int(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; - } - } + + const int scatterModulo = mScatterSkip + 1; + const bool doScatterSkip = mScatterSkip > 0; + int beginIndex = int(begin - mDataContainer->constBegin()); + int endIndex = int(end - mDataContainer->constBegin()); + while (doScatterSkip && begin != end && beginIndex % scatterModulo != 0) { // advance begin iterator to first non-skipped scatter + ++beginIndex; + ++begin; + } + if (begin == end) { + return; + } + int dataCount = int(end - begin); + int maxCount = (std::numeric_limits::max)(); + if (mAdaptiveSampling) { + int keyPixelSpan = int(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 = int(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 { + itIndex += scatterModulo; + if (itIndex < endIndex) { // make sure we didn't jump over end + it += scatterModulo; + } else { + it = end; + itIndex = endIndex; + } + } + // main loop over data points: + while (it != end) { + if (it->key < currentIntervalStartKey + keyEpsilon) { // data point is still within same pixel, so skip it and expand value span of this pixel if necessary + if (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 = int(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; + } + } + } } - } } /*! @@ -21933,179 +22024,178 @@ void QCPGraph::getOptimizedScatterData(QVector *scatterData, QCPGr */ void QCPGraph::getVisibleDataBounds(QCPGraphDataContainer::const_iterator &begin, QCPGraphDataContainer::const_iterator &end, const QCPDataRange &rangeRestriction) const { - if (rangeRestriction.isEmpty()) - { - 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 - } + if (rangeRestriction.isEmpty()) { + 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 + } } /*! \internal - + This method goes through the passed points in \a lineData and returns a list of the segments which don't contain NaN data points. - + \a keyOrientation defines whether the \a x or \a y member of the passed QPointF is used to check for NaN. If \a keyOrientation is \c Qt::Horizontal, the \a y member is checked, if it is \c Qt::Vertical, the \a x member is checked. - + \see getOverlappingSegments, drawFill */ QVector QCPGraph::getNonNanSegments(const QVector *lineData, Qt::Orientation keyOrientation) const { - QVector result; - const int n = lineData->size(); - - QCPDataRange currentSegment(-1, -1); - int i = 0; - - if (keyOrientation == Qt::Horizontal) - { - while (i < n) - { - while (i < n && qIsNaN(lineData->at(i).y())) // seek next non-NaN data point - ++i; - if (i == n) - break; - currentSegment.setBegin(i++); - while (i < n && !qIsNaN(lineData->at(i).y())) // seek next NaN data point or end of data - ++i; - currentSegment.setEnd(i++); - result.append(currentSegment); + QVector result; + const int n = lineData->size(); + + QCPDataRange currentSegment(-1, -1); + int i = 0; + + if (keyOrientation == Qt::Horizontal) { + while (i < n) { + while (i < n && qIsNaN(lineData->at(i).y())) { // seek next non-NaN data point + ++i; + } + if (i == n) { + break; + } + currentSegment.setBegin(i++); + while (i < n && !qIsNaN(lineData->at(i).y())) { // seek next NaN data point or end of data + ++i; + } + currentSegment.setEnd(i++); + result.append(currentSegment); + } + } else { // keyOrientation == Qt::Vertical + while (i < n) { + while (i < n && qIsNaN(lineData->at(i).x())) { // seek next non-NaN data point + ++i; + } + if (i == n) { + break; + } + currentSegment.setBegin(i++); + while (i < n && !qIsNaN(lineData->at(i).x())) { // seek next NaN data point or end of data + ++i; + } + currentSegment.setEnd(i++); + result.append(currentSegment); + } } - } else // keyOrientation == Qt::Vertical - { - while (i < n) - { - while (i < n && qIsNaN(lineData->at(i).x())) // seek next non-NaN data point - ++i; - if (i == n) - break; - currentSegment.setBegin(i++); - while (i < n && !qIsNaN(lineData->at(i).x())) // seek next NaN data point or end of data - ++i; - currentSegment.setEnd(i++); - result.append(currentSegment); - } - } - return result; + return result; } /*! \internal - + This method takes two segment lists (e.g. created by \ref getNonNanSegments) \a thisSegments and \a otherSegments, and their associated point data \a thisData and \a otherData. It returns all pairs of segments (the first from \a thisSegments, the second from \a otherSegments), which overlap in plot coordinates. - + This method is useful in the case of a channel fill between two graphs, when only those non-NaN segments which actually overlap in their key coordinate shall be considered for drawing a channel fill polygon. - + It is assumed that the passed segments in \a thisSegments are ordered ascending by index, and that the segments don't overlap themselves. The same is assumed for the segments in \a otherSegments. This is fulfilled when the segments are obtained via \ref getNonNanSegments. - + \see getNonNanSegments, segmentsIntersect, drawFill, getChannelFillPolygon */ QVector > QCPGraph::getOverlappingSegments(QVector thisSegments, const QVector *thisData, QVector otherSegments, const QVector *otherData) const { - QVector > result; - if (thisData->isEmpty() || otherData->isEmpty() || thisSegments.isEmpty() || otherSegments.isEmpty()) + QVector > result; + if (thisData->isEmpty() || otherData->isEmpty() || thisSegments.isEmpty() || otherSegments.isEmpty()) { + return result; + } + + int thisIndex = 0; + int otherIndex = 0; + const bool verticalKey = mKeyAxis->orientation() == Qt::Vertical; + while (thisIndex < thisSegments.size() && otherIndex < otherSegments.size()) { + if (thisSegments.at(thisIndex).size() < 2) { // segments with fewer than two points won't have a fill anyhow + ++thisIndex; + continue; + } + if (otherSegments.at(otherIndex).size() < 2) { // segments with fewer than two points won't have a fill anyhow + ++otherIndex; + continue; + } + double thisLower, thisUpper, otherLower, otherUpper; + if (!verticalKey) { + thisLower = thisData->at(thisSegments.at(thisIndex).begin()).x(); + thisUpper = thisData->at(thisSegments.at(thisIndex).end() - 1).x(); + otherLower = otherData->at(otherSegments.at(otherIndex).begin()).x(); + otherUpper = otherData->at(otherSegments.at(otherIndex).end() - 1).x(); + } else { + thisLower = thisData->at(thisSegments.at(thisIndex).begin()).y(); + thisUpper = thisData->at(thisSegments.at(thisIndex).end() - 1).y(); + otherLower = otherData->at(otherSegments.at(otherIndex).begin()).y(); + otherUpper = otherData->at(otherSegments.at(otherIndex).end() - 1).y(); + } + + int bPrecedence; + if (segmentsIntersect(thisLower, thisUpper, otherLower, otherUpper, bPrecedence)) { + result.append(QPair(thisSegments.at(thisIndex), otherSegments.at(otherIndex))); + } + + if (bPrecedence <= 0) { // otherSegment doesn't reach as far as thisSegment, so continue with next otherSegment, keeping current thisSegment + ++otherIndex; + } else { // otherSegment reaches further than thisSegment, so continue with next thisSegment, keeping current otherSegment + ++thisIndex; + } + } + return result; - - int thisIndex = 0; - int otherIndex = 0; - const bool verticalKey = mKeyAxis->orientation() == Qt::Vertical; - while (thisIndex < thisSegments.size() && otherIndex < otherSegments.size()) - { - if (thisSegments.at(thisIndex).size() < 2) // segments with fewer than two points won't have a fill anyhow - { - ++thisIndex; - continue; - } - if (otherSegments.at(otherIndex).size() < 2) // segments with fewer than two points won't have a fill anyhow - { - ++otherIndex; - continue; - } - double thisLower, thisUpper, otherLower, otherUpper; - if (!verticalKey) - { - thisLower = thisData->at(thisSegments.at(thisIndex).begin()).x(); - thisUpper = thisData->at(thisSegments.at(thisIndex).end()-1).x(); - otherLower = otherData->at(otherSegments.at(otherIndex).begin()).x(); - otherUpper = otherData->at(otherSegments.at(otherIndex).end()-1).x(); - } else - { - thisLower = thisData->at(thisSegments.at(thisIndex).begin()).y(); - thisUpper = thisData->at(thisSegments.at(thisIndex).end()-1).y(); - otherLower = otherData->at(otherSegments.at(otherIndex).begin()).y(); - otherUpper = otherData->at(otherSegments.at(otherIndex).end()-1).y(); - } - - int bPrecedence; - if (segmentsIntersect(thisLower, thisUpper, otherLower, otherUpper, bPrecedence)) - result.append(QPair(thisSegments.at(thisIndex), otherSegments.at(otherIndex))); - - if (bPrecedence <= 0) // otherSegment doesn't reach as far as thisSegment, so continue with next otherSegment, keeping current thisSegment - ++otherIndex; - else // otherSegment reaches further than thisSegment, so continue with next thisSegment, keeping current otherSegment - ++thisIndex; - } - - return result; } /*! \internal - + Returns whether the segments defined by the coordinates (aLower, aUpper) and (bLower, bUpper) have overlap. - + The output parameter \a bPrecedence indicates whether the \a b segment reaches farther than the \a a segment or not. If \a bPrecedence returns 1, segment \a b reaches the farthest to higher coordinates (i.e. bUpper > aUpper). If it returns -1, segment \a a reaches the farthest. Only if both segment's upper bounds are identical, 0 is returned as \a bPrecedence. - + It is assumed that the lower bounds always have smaller or equal values than the upper bounds. - + \see getOverlappingSegments */ bool QCPGraph::segmentsIntersect(double aLower, double aUpper, double bLower, double bUpper, int &bPrecedence) const { - bPrecedence = 0; - if (aLower > bUpper) - { - bPrecedence = -1; - return false; - } else if (bLower > aUpper) - { - bPrecedence = 1; - return false; - } else - { - if (aUpper > bUpper) - bPrecedence = -1; - else if (aUpper < bUpper) - bPrecedence = 1; - - return true; - } + bPrecedence = 0; + if (aLower > bUpper) { + bPrecedence = -1; + return false; + } else if (bLower > aUpper) { + bPrecedence = 1; + return false; + } else { + if (aUpper > bUpper) { + bPrecedence = -1; + } else if (aUpper < bUpper) { + bPrecedence = 1; + } + + return true; + } } /*! \internal - + Returns the point which closes the fill polygon on the zero-value-line parallel to the key axis. The logarithmic axis scale case is a bit special, since the zero-value-line in pixel coordinates is in positive or negative infinity. So this case is handled separately by just closing the fill @@ -22117,195 +22207,250 @@ bool QCPGraph::segmentsIntersect(double aLower, double aUpper, double bLower, do */ QPointF QCPGraph::getFillBasePoint(QPointF matchingDataPoint) const { - QCPAxis *keyAxis = mKeyAxis.data(); - QCPAxis *valueAxis = mValueAxis.data(); - if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return {}; } - - QPointF result; - if (valueAxis->scaleType() == QCPAxis::stLinear) - { - if (keyAxis->orientation() == Qt::Horizontal) - { - result.setX(matchingDataPoint.x()); - result.setY(valueAxis->coordToPixel(0)); - } else // keyAxis->orientation() == Qt::Vertical - { - result.setX(valueAxis->coordToPixel(0)); - result.setY(matchingDataPoint.y()); + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + return {}; } - } else // valueAxis->mScaleType == QCPAxis::stLogarithmic - { - // In logarithmic scaling we can't just draw to value 0 so we just fill all the way - // to the axis which is in the direction towards 0 - if (keyAxis->orientation() == Qt::Vertical) - { - if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) || - (valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis - result.setX(keyAxis->axisRect()->right()); - else - result.setX(keyAxis->axisRect()->left()); - result.setY(matchingDataPoint.y()); - } else if (keyAxis->axisType() == QCPAxis::atTop || keyAxis->axisType() == QCPAxis::atBottom) - { - result.setX(matchingDataPoint.x()); - if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) || - (valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis - result.setY(keyAxis->axisRect()->top()); - else - result.setY(keyAxis->axisRect()->bottom()); + + QPointF result; + if (valueAxis->scaleType() == QCPAxis::stLinear) { + if (keyAxis->orientation() == Qt::Horizontal) { + result.setX(matchingDataPoint.x()); + result.setY(valueAxis->coordToPixel(0)); + } else { // keyAxis->orientation() == Qt::Vertical + result.setX(valueAxis->coordToPixel(0)); + result.setY(matchingDataPoint.y()); + } + } else { // valueAxis->mScaleType == QCPAxis::stLogarithmic + // In logarithmic scaling we can't just draw to value 0 so we just fill all the way + // to the axis which is in the direction towards 0 + if (keyAxis->orientation() == Qt::Vertical) { + if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) || + (valueAxis->range().upper > 0 && valueAxis->rangeReversed())) { // if range is negative, zero is on opposite side of key axis + result.setX(keyAxis->axisRect()->right()); + } else { + result.setX(keyAxis->axisRect()->left()); + } + result.setY(matchingDataPoint.y()); + } else if (keyAxis->axisType() == QCPAxis::atTop || keyAxis->axisType() == QCPAxis::atBottom) { + result.setX(matchingDataPoint.x()); + if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) || + (valueAxis->range().upper > 0 && valueAxis->rangeReversed())) { // if range is negative, zero is on opposite side of key axis + result.setY(keyAxis->axisRect()->top()); + } else { + result.setY(keyAxis->axisRect()->bottom()); + } + } } - } - return result; + return result; } /*! \internal - + Returns the polygon needed for drawing normal fills between this graph and the key axis. - + Pass the graph's data points (in pixel coordinates) as \a lineData, and specify the \a segment which shall be used for the fill. The collection of \a lineData points described by \a segment must not contain NaN data points (see \ref getNonNanSegments). - + The returned fill polygon will be closed at the key axis (the zero-value line) for linear value axes. For logarithmic value axes the polygon will reach just beyond the corresponding axis rect side (see \ref getFillBasePoint). For increased performance (due to implicit sharing), keep the returned QPolygonF const. - + \see drawFill, getNonNanSegments */ const QPolygonF QCPGraph::getFillPolygon(const QVector *lineData, QCPDataRange segment) const { - if (segment.size() < 2) - return QPolygonF(); - QPolygonF result(segment.size()+2); - - result[0] = getFillBasePoint(lineData->at(segment.begin())); - std::copy(lineData->constBegin()+segment.begin(), lineData->constBegin()+segment.end(), result.begin()+1); - result[result.size()-1] = getFillBasePoint(lineData->at(segment.end()-1)); - - return result; + if (segment.size() < 2) { + return QPolygonF(); + } + QPolygonF result(segment.size() + 2); + + result[0] = getFillBasePoint(lineData->at(segment.begin())); + std::copy(lineData->constBegin() + segment.begin(), lineData->constBegin() + segment.end(), result.begin() + 1); + result[result.size() - 1] = getFillBasePoint(lineData->at(segment.end() - 1)); + + return result; +} + +const QPainterPath QCPGraph::getFillPath(const QVector *lineData, QCPDataRange segment) const +{ + if (segment.size() < 2) { + return QPainterPath(); + } + + QPointF start = getFillBasePoint(lineData->at(segment.begin())); + QPointF end = getFillBasePoint(lineData->at(segment.end() - 1)); + + QPainterPath path; + if (smooth == 1) { + path = SmoothCurve::createSmoothCurve(*lineData); + } else if (smooth == 2) { + path = SmoothCurve::createSmoothCurve2(*lineData); + } + + path.lineTo(end); + path.lineTo(start); + path.lineTo(lineData->at(segment.begin())); + return path; } /*! \internal - + Returns the polygon needed for drawing (partial) channel fills between this graph and the graph specified by \ref setChannelFillGraph. - + The data points of this graph are passed as pixel coordinates via \a thisData, the data of the other graph as \a otherData. The returned polygon will be calculated for the specified data segments \a thisSegment and \a otherSegment, pertaining to the respective \a thisData and \a otherData, respectively. - + The passed \a thisSegment and \a otherSegment should correspond to the segment pairs returned by \ref getOverlappingSegments, to make sure only segments that actually have key coordinate overlap need to be processed here. - + For increased performance due to implicit sharing, keep the returned QPolygonF const. - + \see drawFill, getOverlappingSegments, getNonNanSegments */ const QPolygonF QCPGraph::getChannelFillPolygon(const QVector *thisData, QCPDataRange thisSegment, const QVector *otherData, QCPDataRange otherSegment) const { - if (!mChannelFillGraph) - return QPolygonF(); - - QCPAxis *keyAxis = mKeyAxis.data(); - QCPAxis *valueAxis = mValueAxis.data(); - if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPolygonF(); } - if (!mChannelFillGraph.data()->mKeyAxis) { qDebug() << Q_FUNC_INFO << "channel fill target key axis invalid"; return QPolygonF(); } - - 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 (thisData->isEmpty()) return QPolygonF(); - QVector thisSegmentData(thisSegment.size()); - QVector otherSegmentData(otherSegment.size()); - std::copy(thisData->constBegin()+thisSegment.begin(), thisData->constBegin()+thisSegment.end(), thisSegmentData.begin()); - std::copy(otherData->constBegin()+otherSegment.begin(), otherData->constBegin()+otherSegment.end(), otherSegmentData.begin()); - // pointers to be able to swap them, depending which data range needs cropping: - QVector *staticData = &thisSegmentData; - QVector *croppedData = &otherSegmentData; - - // crop both vectors to ranges in which the keys overlap (which coord is key, depends on axisType): - if (keyAxis->orientation() == Qt::Horizontal) - { - // x is key - // crop lower bound: - if (staticData->first().x() < croppedData->first().x()) // other one must be cropped - qSwap(staticData, croppedData); - const int lowBound = findIndexBelowX(croppedData, staticData->first().x()); - if (lowBound == -1) return QPolygonF(); // key ranges have no overlap - croppedData->remove(0, lowBound); - // set lowest point of cropped data to fit exactly key position of first static data point via linear interpolation: - if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation - double slope; - if (!qFuzzyCompare(croppedData->at(1).x(), croppedData->at(0).x())) - slope = (croppedData->at(1).y()-croppedData->at(0).y())/(croppedData->at(1).x()-croppedData->at(0).x()); - else - slope = 0; - (*croppedData)[0].setY(croppedData->at(0).y()+slope*(staticData->first().x()-croppedData->at(0).x())); - (*croppedData)[0].setX(staticData->first().x()); - - // crop upper bound: - if (staticData->last().x() > croppedData->last().x()) // other one must be cropped - qSwap(staticData, croppedData); - int highBound = findIndexAboveX(croppedData, staticData->last().x()); - if (highBound == -1) return QPolygonF(); // key ranges have no overlap - croppedData->remove(highBound+1, croppedData->size()-(highBound+1)); - // set highest point of cropped data to fit exactly key position of last static data point via linear interpolation: - if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation - const int li = croppedData->size()-1; // last index - if (!qFuzzyCompare(croppedData->at(li).x(), croppedData->at(li-1).x())) - slope = (croppedData->at(li).y()-croppedData->at(li-1).y())/(croppedData->at(li).x()-croppedData->at(li-1).x()); - else - slope = 0; - (*croppedData)[li].setY(croppedData->at(li-1).y()+slope*(staticData->last().x()-croppedData->at(li-1).x())); - (*croppedData)[li].setX(staticData->last().x()); - } else // mKeyAxis->orientation() == Qt::Vertical - { - // y is key - // crop lower bound: - if (staticData->first().y() < croppedData->first().y()) // other one must be cropped - qSwap(staticData, croppedData); - int lowBound = findIndexBelowY(croppedData, staticData->first().y()); - if (lowBound == -1) return QPolygonF(); // key ranges have no overlap - croppedData->remove(0, lowBound); - // set lowest point of cropped data to fit exactly key position of first static data point via linear interpolation: - if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation - double slope; - if (!qFuzzyCompare(croppedData->at(1).y(), croppedData->at(0).y())) // avoid division by zero in step plots - slope = (croppedData->at(1).x()-croppedData->at(0).x())/(croppedData->at(1).y()-croppedData->at(0).y()); - else - slope = 0; - (*croppedData)[0].setX(croppedData->at(0).x()+slope*(staticData->first().y()-croppedData->at(0).y())); - (*croppedData)[0].setY(staticData->first().y()); - - // crop upper bound: - if (staticData->last().y() > croppedData->last().y()) // other one must be cropped - qSwap(staticData, croppedData); - int highBound = findIndexAboveY(croppedData, staticData->last().y()); - if (highBound == -1) return QPolygonF(); // key ranges have no overlap - croppedData->remove(highBound+1, croppedData->size()-(highBound+1)); - // set highest point of cropped data to fit exactly key position of last static data point via linear interpolation: - if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation - int li = croppedData->size()-1; // last index - if (!qFuzzyCompare(croppedData->at(li).y(), croppedData->at(li-1).y())) // avoid division by zero in step plots - slope = (croppedData->at(li).x()-croppedData->at(li-1).x())/(croppedData->at(li).y()-croppedData->at(li-1).y()); - else - slope = 0; - (*croppedData)[li].setX(croppedData->at(li-1).x()+slope*(staticData->last().y()-croppedData->at(li-1).y())); - (*croppedData)[li].setY(staticData->last().y()); - } - - // return joined: - for (int i=otherSegmentData.size()-1; i>=0; --i) // insert reversed, otherwise the polygon will be twisted - thisSegmentData << otherSegmentData.at(i); - return QPolygonF(thisSegmentData); + if (!mChannelFillGraph) { + return QPolygonF(); + } + + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + return QPolygonF(); + } + if (!mChannelFillGraph.data()->mKeyAxis) { + qDebug() << Q_FUNC_INFO << "channel fill target key axis invalid"; + return QPolygonF(); + } + + 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 (thisData->isEmpty()) { + return QPolygonF(); + } + QVector thisSegmentData(thisSegment.size()); + QVector otherSegmentData(otherSegment.size()); + std::copy(thisData->constBegin() + thisSegment.begin(), thisData->constBegin() + thisSegment.end(), thisSegmentData.begin()); + std::copy(otherData->constBegin() + otherSegment.begin(), otherData->constBegin() + otherSegment.end(), otherSegmentData.begin()); + // pointers to be able to swap them, depending which data range needs cropping: + QVector *staticData = &thisSegmentData; + QVector *croppedData = &otherSegmentData; + + // crop both vectors to ranges in which the keys overlap (which coord is key, depends on axisType): + if (keyAxis->orientation() == Qt::Horizontal) { + // x is key + // crop lower bound: + if (staticData->first().x() < croppedData->first().x()) { // other one must be cropped + qSwap(staticData, croppedData); + } + const int lowBound = findIndexBelowX(croppedData, staticData->first().x()); + if (lowBound == -1) { + return QPolygonF(); // key ranges have no overlap + } + croppedData->remove(0, lowBound); + // set lowest point of cropped data to fit exactly key position of first static data point via linear interpolation: + if (croppedData->size() < 2) { + return QPolygonF(); // need at least two points for interpolation + } + double slope; + if (!qFuzzyCompare(croppedData->at(1).x(), croppedData->at(0).x())) { + slope = (croppedData->at(1).y() - croppedData->at(0).y()) / (croppedData->at(1).x() - croppedData->at(0).x()); + } else { + slope = 0; + } + (*croppedData)[0].setY(croppedData->at(0).y() + slope * (staticData->first().x() - croppedData->at(0).x())); + (*croppedData)[0].setX(staticData->first().x()); + + // crop upper bound: + if (staticData->last().x() > croppedData->last().x()) { // other one must be cropped + qSwap(staticData, croppedData); + } + int highBound = findIndexAboveX(croppedData, staticData->last().x()); + if (highBound == -1) { + return QPolygonF(); // key ranges have no overlap + } + croppedData->remove(highBound + 1, croppedData->size() - (highBound + 1)); + // set highest point of cropped data to fit exactly key position of last static data point via linear interpolation: + if (croppedData->size() < 2) { + return QPolygonF(); // need at least two points for interpolation + } + const int li = croppedData->size() - 1; // last index + if (!qFuzzyCompare(croppedData->at(li).x(), croppedData->at(li - 1).x())) { + slope = (croppedData->at(li).y() - croppedData->at(li - 1).y()) / (croppedData->at(li).x() - croppedData->at(li - 1).x()); + } else { + slope = 0; + } + (*croppedData)[li].setY(croppedData->at(li - 1).y() + slope * (staticData->last().x() - croppedData->at(li - 1).x())); + (*croppedData)[li].setX(staticData->last().x()); + } else { // mKeyAxis->orientation() == Qt::Vertical + // y is key + // crop lower bound: + if (staticData->first().y() < croppedData->first().y()) { // other one must be cropped + qSwap(staticData, croppedData); + } + int lowBound = findIndexBelowY(croppedData, staticData->first().y()); + if (lowBound == -1) { + return QPolygonF(); // key ranges have no overlap + } + croppedData->remove(0, lowBound); + // set lowest point of cropped data to fit exactly key position of first static data point via linear interpolation: + if (croppedData->size() < 2) { + return QPolygonF(); // need at least two points for interpolation + } + double slope; + if (!qFuzzyCompare(croppedData->at(1).y(), croppedData->at(0).y())) { // avoid division by zero in step plots + slope = (croppedData->at(1).x() - croppedData->at(0).x()) / (croppedData->at(1).y() - croppedData->at(0).y()); + } else { + slope = 0; + } + (*croppedData)[0].setX(croppedData->at(0).x() + slope * (staticData->first().y() - croppedData->at(0).y())); + (*croppedData)[0].setY(staticData->first().y()); + + // crop upper bound: + if (staticData->last().y() > croppedData->last().y()) { // other one must be cropped + qSwap(staticData, croppedData); + } + int highBound = findIndexAboveY(croppedData, staticData->last().y()); + if (highBound == -1) { + return QPolygonF(); // key ranges have no overlap + } + croppedData->remove(highBound + 1, croppedData->size() - (highBound + 1)); + // set highest point of cropped data to fit exactly key position of last static data point via linear interpolation: + if (croppedData->size() < 2) { + return QPolygonF(); // need at least two points for interpolation + } + int li = croppedData->size() - 1; // last index + if (!qFuzzyCompare(croppedData->at(li).y(), croppedData->at(li - 1).y())) { // avoid division by zero in step plots + slope = (croppedData->at(li).x() - croppedData->at(li - 1).x()) / (croppedData->at(li).y() - croppedData->at(li - 1).y()); + } else { + slope = 0; + } + (*croppedData)[li].setX(croppedData->at(li - 1).x() + slope * (staticData->last().y() - croppedData->at(li - 1).y())); + (*croppedData)[li].setY(staticData->last().y()); + } + + // return joined: + for (int i = otherSegmentData.size() - 1; i >= 0; --i) { // insert reversed, otherwise the polygon will be twisted + thisSegmentData << otherSegmentData.at(i); + } + return QPolygonF(thisSegmentData); } /*! \internal - + Finds the smallest index of \a data, whose points x value is just above \a x. Assumes x values in \a data points are ordered ascending, as is ensured by \ref getLines/\ref getScatters if the key axis is horizontal. @@ -22314,126 +22459,123 @@ const QPolygonF QCPGraph::getChannelFillPolygon(const QVector *thisData */ int QCPGraph::findIndexAboveX(const QVector *data, double x) const { - for (int i=data->size()-1; i>=0; --i) - { - if (data->at(i).x() < x) - { - if (isize()-1) - return i+1; - else - return data->size()-1; + for (int i = data->size() - 1; i >= 0; --i) { + if (data->at(i).x() < x) { + if (i < data->size() - 1) { + return i + 1; + } else { + return data->size() - 1; + } + } } - } - return -1; + return -1; } /*! \internal - + Finds the highest index of \a data, whose points x value is just below \a x. Assumes x values in \a data points are ordered ascending, as is ensured by \ref getLines/\ref getScatters if the key axis is horizontal. - + Used to calculate the channel fill polygon, see \ref getChannelFillPolygon. */ int QCPGraph::findIndexBelowX(const QVector *data, double x) const { - for (int i=0; isize(); ++i) - { - if (data->at(i).x() > x) - { - if (i>0) - return i-1; - else - return 0; + for (int i = 0; i < data->size(); ++i) { + if (data->at(i).x() > x) { + if (i > 0) { + return i - 1; + } else { + return 0; + } + } } - } - return -1; + return -1; } /*! \internal - + Finds the smallest index of \a data, whose points y value is just above \a y. Assumes y values in \a data points are ordered ascending, as is ensured by \ref getLines/\ref getScatters if the key axis is vertical. - + Used to calculate the channel fill polygon, see \ref getChannelFillPolygon. */ int QCPGraph::findIndexAboveY(const QVector *data, double y) const { - for (int i=data->size()-1; i>=0; --i) - { - if (data->at(i).y() < y) - { - if (isize()-1) - return i+1; - else - return data->size()-1; + for (int i = data->size() - 1; i >= 0; --i) { + if (data->at(i).y() < y) { + if (i < data->size() - 1) { + return i + 1; + } else { + return data->size() - 1; + } + } } - } - return -1; + return -1; } /*! \internal - + 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, QCPGraphDataContainer::const_iterator &closestData) const { - closestData = mDataContainer->constEnd(); - if (mDataContainer->isEmpty()) - return -1.0; - if (mLineStyle == lsNone && mScatterStyle.isNone()) - return -1.0; - - // 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) - { - const double currentDistSqr = QCPVector2D(coordsToPixels(it->key, it->value)-pixelPoint).lengthSquared(); - if (currentDistSqr < minDistSqr) - { - minDistSqr = currentDistSqr; - closestData = it; + closestData = mDataContainer->constEnd(); + if (mDataContainer->isEmpty()) { + return -1.0; } - } - - // calculate distance to graph line if there is one (if so, will probably be smaller than distance to closest data point): - if (mLineStyle != lsNone) - { - // line displayed, calculate distance to line segments: - QVector lineData; - getLines(&lineData, QCPDataRange(0, dataCount())); // don't limit data range further since with sharp data spikes, line segments may be closer to test point than segments with closer key coordinate - 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)(); + // determine which key range comes into question, taking selection tolerance around pos into account: + double posKeyMin, posKeyMax, dummy; + pixelsToCoords(pixelPoint - QPointF(mParentPlot->selectionTolerance(), mParentPlot->selectionTolerance()), posKeyMin, dummy); + pixelsToCoords(pixelPoint + QPointF(mParentPlot->selectionTolerance(), mParentPlot->selectionTolerance()), posKeyMax, dummy); + if (posKeyMin > posKeyMax) { + qSwap(posKeyMin, posKeyMax); + } + // iterate over found data points and then choose the one with the shortest distance to pos: + QCPGraphDataContainer::const_iterator begin = mDataContainer->findBegin(posKeyMin, true); + QCPGraphDataContainer::const_iterator end = mDataContainer->findEnd(posKeyMax, true); + for (QCPGraphDataContainer::const_iterator it = begin; it != end; ++it) { + const double currentDistSqr = QCPVector2D(coordsToPixels(it->key, it->value) - pixelPoint).lengthSquared(); + if (currentDistSqr < minDistSqr) { + minDistSqr = currentDistSqr; + closestData = it; + } + } + + // calculate distance to graph line if there is one (if so, will probably be smaller than distance to closest data point): + if (mLineStyle != lsNone) { + // line displayed, calculate distance to line segments: + QVector lineData; + getLines(&lineData, QCPDataRange(0, dataCount())); // don't limit data range further since with sharp data spikes, line segments may be closer to test point than segments with closer key coordinate + QCPVector2D p(pixelPoint); + const int step = mLineStyle == lsImpulse ? 2 : 1; // impulse plot differs from other line styles in that the lineData points are only pairwise connected + for (int i = 0; i < lineData.size() - 1; i += step) { + const double currentDistSqr = p.distanceSquaredToLine(lineData.at(i), lineData.at(i + 1)); + if (currentDistSqr < minDistSqr) { + minDistSqr = currentDistSqr; + } + } + } + + return qSqrt(minDistSqr); } /*! \internal - + Finds the highest index of \a data, whose points y value is just below \a y. Assumes y values in \a data points are ordered ascending, as is ensured by \ref getLines/\ref getScatters if the key axis is vertical. @@ -22442,17 +22584,16 @@ double QCPGraph::pointDistance(const QPointF &pixelPoint, QCPGraphDataContainer: */ int QCPGraph::findIndexBelowY(const QVector *data, double y) const { - for (int i=0; isize(); ++i) - { - if (data->at(i).y() > y) - { - if (i>0) - return i-1; - else - return 0; + for (int i = 0; i < data->size(); ++i) { + if (data->at(i).y() > y) { + if (i > 0) { + return i - 1; + } else { + return 0; + } + } } - } - return -1; + return -1; } /* end of 'src/plottables/plottable-graph.cpp' */ @@ -22466,67 +22607,67 @@ int QCPGraph::findIndexBelowY(const QVector *data, double y) const /*! \class QCPCurveData \brief Holds the data of one single data point for QCPCurve. - + The stored data is: \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) - + 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. */ @@ -22537,9 +22678,9 @@ int QCPGraph::findIndexBelowY(const QVector *data, double y) const Constructs a curve data point with t, key and value set to zero. */ QCPCurveData::QCPCurveData() : - t(0), - key(0), - value(0) + t(0), + key(0), + value(0) { } @@ -22547,9 +22688,9 @@ QCPCurveData::QCPCurveData() : Constructs a curve data point with the specified \a t, \a key and \a value. */ QCPCurveData::QCPCurveData(double t, double key, double value) : - t(t), - key(key), - value(value) + t(t), + key(key), + value(value) { } @@ -22560,9 +22701,9 @@ QCPCurveData::QCPCurveData(double t, double key, double value) : /*! \class QCPCurve \brief A plottable representing a parametric curve in a plot. - + \image html QCPCurve.png - + Unlike QCPGraph, plottables of this type may have multiple points with the same key coordinate, so their visual representation can have \a loops. This is realized by introducing a third coordinate \a t, which defines the order of the points described by the other two coordinates \a @@ -22571,21 +22712,21 @@ QCPCurveData::QCPCurveData(double t, double key, double value) : 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 qcpcurve-appearance Changing the appearance - + The appearance of the curve is determined by the pen and the brush (\ref setPen, \ref setBrush). - + \section qcpcurve-usage Usage - + Like all data representing objects in QCustomPlot, the QCPCurve is a plottable (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies (QCustomPlot::plottable, QCustomPlot::removePlottable, etc.) - + Usually, you first create an instance: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcurve-creation-1 which registers it with the QCustomPlot instance of the passed axes. Note that this QCustomPlot instance takes @@ -22597,7 +22738,7 @@ QCPCurveData::QCPCurveData(double t, double key, double value) : /* 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. @@ -22610,23 +22751,23 @@ QCPCurveData::QCPCurveData(double t, double key, double 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 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) : - QCPAbstractPlottable1D(keyAxis, valueAxis), - mScatterSkip{}, - mLineStyle{} + QCPAbstractPlottable1D(keyAxis, valueAxis), + mScatterSkip{}, + mLineStyle{} { - // modify inherited properties from abstract plottable: - setPen(QPen(Qt::blue, 0)); - setBrush(Qt::NoBrush); - - setScatterStyle(QCPScatterStyle()); - setLineStyle(lsLine); - setScatterSkip(0); + // modify inherited properties from abstract plottable: + setPen(QPen(Qt::blue, 0)); + setBrush(Qt::NoBrush); + + setScatterStyle(QCPScatterStyle()); + setLineStyle(lsLine); + setScatterSkip(0); } QCPCurve::~QCPCurve() @@ -22634,70 +22775,70 @@ QCPCurve::~QCPCurve() } /*! \overload - + 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(QSharedPointer data) { - mDataContainer = data; + mDataContainer = data; } /*! \overload - + 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 &t, const QVector &keys, const QVector &values, bool alreadySorted) { - mDataContainer->clear(); - addData(t, keys, values, alreadySorted); + 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); + mDataContainer->clear(); + addData(keys, values); } /*! Sets the visual appearance of single data points in the plot. If set to \ref QCPScatterStyle::ssNone, no scatter points are drawn (e.g. for line-only plots with appropriate line style). - + \see QCPScatterStyle, setLineStyle */ void QCPCurve::setScatterStyle(const QCPScatterStyle &style) { - mScatterStyle = style; + mScatterStyle = style; } /*! @@ -22713,117 +22854,119 @@ void QCPCurve::setScatterStyle(const QCPScatterStyle &style) */ void QCPCurve::setScatterSkip(int skip) { - mScatterSkip = qMax(0, skip); + mScatterSkip = qMax(0, skip); } /*! Sets how the single data points are connected in the plot or how they are represented visually apart from the scatter symbol. For scatter-only plots, set \a style to \ref lsNone and \ref setScatterStyle to the desired scatter style. - + \see setScatterStyle */ void QCPCurve::setLineStyle(QCPCurve::LineStyle style) { - mLineStyle = style; + mLineStyle = style; } /*! \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 QVector &t, const QVector &keys, const QVector &values, bool alreadySorted) { - 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 + 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 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 QVector &keys, const QVector &values) { - 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 + 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 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) { - mDataContainer->add(QCPCurveData(t, key, value)); + mDataContainer->add(QCPCurveData(t, key, value)); } /*! \overload - + Adds the provided data point as \a key and \a value to the current data. - + 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) { - if (!mDataContainer->isEmpty()) - mDataContainer->add(QCPCurveData((mDataContainer->constEnd()-1)->t + 1.0, key, value)); - else - mDataContainer->add(QCPCurveData(0.0, key, value)); + if (!mDataContainer->isEmpty()) { + mDataContainer->add(QCPCurveData((mDataContainer->constEnd() - 1)->t + 1.0, key, value)); + } else { + mDataContainer->add(QCPCurveData(0.0, key, value)); + } } /*! @@ -22831,143 +22974,143 @@ void QCPCurve::addData(double key, double value) If \a details is not 0, it will be set to a \ref QCPDataSelection, describing the closest data point to \a pos. - + \seebaseclassmethod \ref QCPAbstractPlottable::selectTest */ double QCPCurve::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { - if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty()) - return -1; - if (!mKeyAxis || !mValueAxis) - return -1; - - if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()) || mParentPlot->interactions().testFlag(QCP::iSelectPlottablesBeyondAxisRect)) - { - QCPCurveDataContainer::const_iterator closestDataPoint = mDataContainer->constEnd(); - double result = pointDistance(pos, closestDataPoint); - if (details) - { - int pointIndex = int( closestDataPoint-mDataContainer->constBegin() ); - details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1))); + if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty()) { + return -1; + } + if (!mKeyAxis || !mValueAxis) { + return -1; + } + + if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()) || mParentPlot->interactions().testFlag(QCP::iSelectPlottablesBeyondAxisRect)) { + QCPCurveDataContainer::const_iterator closestDataPoint = mDataContainer->constEnd(); + double result = pointDistance(pos, closestDataPoint); + if (details) { + int pointIndex = int(closestDataPoint - mDataContainer->constBegin()); + details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex + 1))); + } + return result; + } else { + return -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); + 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); + return mDataContainer->valueRange(foundRange, inSignDomain, inKeyRange); } /* inherits documentation from base class */ void QCPCurve::draw(QCPPainter *painter) { - if (mDataContainer->isEmpty()) return; - - // allocate line vector: - QVector lines, scatters; - - // 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(); + if (mDataContainer->isEmpty()) { + return; } - #endif - - // draw curve fill: - applyFillAntialiasingHint(painter); - if (isSelectedSegment && mSelectionDecorator) - mSelectionDecorator->applyBrush(painter); - else - painter->setBrush(mBrush); - painter->setPen(Qt::NoPen); - if (painter->brush().style() != Qt::NoBrush && painter->brush().color().alpha() != 0) - painter->drawPolygon(QPolygonF(lines)); - - // draw curve line: - if (mLineStyle != lsNone) - { - painter->setPen(finalCurvePen); - painter->setBrush(Qt::NoBrush); - drawCurveLine(painter, lines); + + // allocate line vector: + QVector lines, scatters; + + // loop over and draw segments of unselected/selected data: + QList selectedSegments, unselectedSegments, allSegments; + getDataSegments(selectedSegments, unselectedSegments); + allSegments << unselectedSegments << selectedSegments; + for (int i = 0; i < allSegments.size(); ++i) { + bool isSelectedSegment = i >= unselectedSegments.size(); + + // fill with curve data: + QPen finalCurvePen = mPen; // determine the final pen already here, because the line optimization depends on its stroke width + if (isSelectedSegment && mSelectionDecorator) { + finalCurvePen = mSelectionDecorator->pen(); + } + + QCPDataRange lineDataRange = isSelectedSegment ? allSegments.at(i) : allSegments.at(i).adjusted(-1, 1); // unselected segments extend lines to bordering selected data point (safe to exceed total data bounds in first/last segment, getCurveLines takes care) + getCurveLines(&lines, lineDataRange, finalCurvePen.widthF()); + + // check data validity if flag set: +#ifdef QCUSTOMPLOT_CHECK_DATA + for (QCPCurveDataContainer::const_iterator it = mDataContainer->constBegin(); it != mDataContainer->constEnd(); ++it) { + if (QCP::isInvalidData(it->t) || + QCP::isInvalidData(it->key, it->value)) { + qDebug() << Q_FUNC_INFO << "Data point at" << it->key << "invalid." << "Plottable name:" << name(); + } + } +#endif + + // draw curve fill: + applyFillAntialiasingHint(painter); + if (isSelectedSegment && mSelectionDecorator) { + mSelectionDecorator->applyBrush(painter); + } else { + painter->setBrush(mBrush); + } + painter->setPen(Qt::NoPen); + if (painter->brush().style() != Qt::NoBrush && painter->brush().color().alpha() != 0) { + painter->drawPolygon(QPolygonF(lines)); + } + + // draw curve line: + if (mLineStyle != lsNone) { + painter->setPen(finalCurvePen); + painter->setBrush(Qt::NoBrush); + drawCurveLine(painter, lines); + } + + // draw scatters: + QCPScatterStyle finalScatterStyle = mScatterStyle; + if (isSelectedSegment && mSelectionDecorator) { + finalScatterStyle = mSelectionDecorator->getFinalScatterStyle(mScatterStyle); + } + if (!finalScatterStyle.isNone()) { + getScatters(&scatters, allSegments.at(i), finalScatterStyle.size()); + drawScatterPlot(painter, scatters, finalScatterStyle); + } } - - // draw scatters: - QCPScatterStyle finalScatterStyle = mScatterStyle; - if (isSelectedSegment && mSelectionDecorator) - finalScatterStyle = mSelectionDecorator->getFinalScatterStyle(mScatterStyle); - if (!finalScatterStyle.isNone()) - { - getScatters(&scatters, allSegments.at(i), finalScatterStyle.size()); - drawScatterPlot(painter, scatters, finalScatterStyle); + + // draw other selection decoration that isn't just line/scatter pens and brushes: + if (mSelectionDecorator) { + mSelectionDecorator->drawDecoration(painter, selection()); } - } - - // 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 QCPCurve::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const { - // draw fill: - if (mBrush.style() != Qt::NoBrush) - { - applyFillAntialiasingHint(painter); - painter->fillRect(QRectF(rect.left(), rect.top()+rect.height()/2.0, rect.width(), rect.height()/3.0), mBrush); - } - // draw line vertically centered: - if (mLineStyle != lsNone) - { - applyDefaultAntialiasingHint(painter); - painter->setPen(mPen); - painter->drawLine(QLineF(rect.left(), rect.top()+rect.height()/2.0, rect.right()+5, rect.top()+rect.height()/2.0)); // +5 on x2 else last segment is missing from dashed/dotted pens - } - // draw scatter symbol: - if (!mScatterStyle.isNone()) - { - applyScattersAntialiasingHint(painter); - // scale scatter pixmap if it's too large to fit in legend icon rect: - if (mScatterStyle.shape() == QCPScatterStyle::ssPixmap && (mScatterStyle.pixmap().size().width() > rect.width() || mScatterStyle.pixmap().size().height() > rect.height())) - { - QCPScatterStyle scaledStyle(mScatterStyle); - scaledStyle.setPixmap(scaledStyle.pixmap().scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation)); - scaledStyle.applyTo(painter, mPen); - scaledStyle.drawShape(painter, QRectF(rect).center()); - } else - { - mScatterStyle.applyTo(painter, mPen); - mScatterStyle.drawShape(painter, QRectF(rect).center()); + // draw fill: + if (mBrush.style() != Qt::NoBrush) { + applyFillAntialiasingHint(painter); + painter->fillRect(QRectF(rect.left(), rect.top() + rect.height() / 2.0, rect.width(), rect.height() / 3.0), mBrush); + } + // draw line vertically centered: + if (mLineStyle != lsNone) { + applyDefaultAntialiasingHint(painter); + painter->setPen(mPen); + painter->drawLine(QLineF(rect.left(), rect.top() + rect.height() / 2.0, rect.right() + 5, rect.top() + rect.height() / 2.0)); // +5 on x2 else last segment is missing from dashed/dotted pens + } + // draw scatter symbol: + if (!mScatterStyle.isNone()) { + applyScattersAntialiasingHint(painter); + // scale scatter pixmap if it's too large to fit in legend icon rect: + if (mScatterStyle.shape() == QCPScatterStyle::ssPixmap && (mScatterStyle.pixmap().size().width() > rect.width() || mScatterStyle.pixmap().size().height() > rect.height())) { + QCPScatterStyle scaledStyle(mScatterStyle); + scaledStyle.setPixmap(scaledStyle.pixmap().scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation)); + scaledStyle.applyTo(painter, mPen); + scaledStyle.drawShape(painter, QRectF(rect).center()); + } else { + mScatterStyle.applyTo(painter, mPen); + mScatterStyle.drawShape(painter, QRectF(rect).center()); + } } - } } /*! \internal @@ -22978,11 +23121,10 @@ void QCPCurve::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const */ void QCPCurve::drawCurveLine(QCPPainter *painter, const QVector &lines) const { - if (painter->pen().style() != Qt::NoPen && painter->pen().color().alpha() != 0) - { - applyDefaultAntialiasingHint(painter); - drawPolyline(painter, lines); - } + if (painter->pen().style() != Qt::NoPen && painter->pen().color().alpha() != 0) { + applyDefaultAntialiasingHint(painter); + drawPolyline(painter, lines); + } } /*! \internal @@ -22994,12 +23136,13 @@ void QCPCurve::drawCurveLine(QCPPainter *painter, const QVector &lines) */ void QCPCurve::drawScatterPlot(QCPPainter *painter, const QVector &points, const QCPScatterStyle &style) const { - // draw scatter point symbols: - applyScattersAntialiasingHint(painter); - style.applyTo(painter, mPen); - foreach (const QPointF &point, points) - if (!qIsNaN(point.x()) && !qIsNaN(point.y())) - style.drawShape(painter, point); + // draw scatter point symbols: + applyScattersAntialiasingHint(painter); + style.applyTo(painter, mPen); + foreach (const QPointF &point, points) + if (!qIsNaN(point.x()) && !qIsNaN(point.y())) { + style.drawShape(painter, point); + } } /*! \internal @@ -23032,85 +23175,80 @@ void QCPCurve::drawScatterPlot(QCPPainter *painter, const QVector &poin */ 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 - 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 != itEnd) - { - 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 - { - QPointF crossA, crossB; - if (prevRegion == 5) // we're coming from R, so add this point optimized - { - 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 - *lines << getOptimizedCornerPoints(prevRegion, currentRegion, prevIt->key, prevIt->value, it->key, it->value, keyMin, valueMax, keyMax, valueMin); - } else if (mayTraverse(prevRegion, currentRegion) && - 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, keyMin, valueMax, keyMax, valueMin, beforeTraverseCornerPoints, afterTraverseCornerPoints); - if (it != itBegin) - { - *lines << beforeTraverseCornerPoints; - lines->append(crossA); - lines->append(crossB); - *lines << afterTraverseCornerPoints; - } else - { - 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) - { - *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 == 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 - 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 - { - 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... - } + if (!lines) { + return; } - prevIt = it; - prevRegion = currentRegion; - ++it; - } - *lines << trailingPoints; + 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 + 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 != itEnd) { + 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 + QPointF crossA, crossB; + if (prevRegion == 5) { // we're coming from R, so add this point optimized + 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 + *lines << getOptimizedCornerPoints(prevRegion, currentRegion, prevIt->key, prevIt->value, it->key, it->value, keyMin, valueMax, keyMax, valueMin); + } else if (mayTraverse(prevRegion, currentRegion) && + 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, keyMin, valueMax, keyMax, valueMin, beforeTraverseCornerPoints, afterTraverseCornerPoints); + if (it != itBegin) { + *lines << beforeTraverseCornerPoints; + lines->append(crossA); + lines->append(crossB); + *lines << afterTraverseCornerPoints; + } else { + 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) + *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 == 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 { + 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 + 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... + } + } + prevIt = it; + prevRegion = currentRegion; + ++it; + } + *lines << trailingPoints; } /*! \internal @@ -23135,81 +23273,80 @@ void QCPCurve::getCurveLines(QVector *lines, const QCPDataRange &dataRa */ 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; } - - 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 = int( end-mDataContainer->constBegin() ); - - 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 = int( 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; - } - } + if (!scatters) { + return; } - } 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; - } - } + scatters->clear(); + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + return; + } + + 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 = int(end - mDataContainer->constBegin()); + + 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 = int(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 @@ -23233,43 +23370,43 @@ void QCPCurve::getScatters(QVector *scatters, const QCPDataRange &dataR */ int QCPCurve::getRegion(double key, double value, double keyMin, double valueMax, double keyMax, double valueMin) const { - if (key < keyMin) // region 123 - { - if (value > valueMax) - return 1; - else if (value < valueMin) - return 3; - else - return 2; - } else if (key > keyMax) // region 789 - { - if (value > valueMax) - return 7; - else if (value < valueMin) - return 9; - else - return 8; - } else // region 456 - { - if (value > valueMax) - return 4; - else if (value < valueMin) - return 6; - else - return 5; - } + if (key < keyMin) { // region 123 + if (value > valueMax) { + return 1; + } else if (value < valueMin) { + return 3; + } else { + return 2; + } + } else if (key > keyMax) { // region 789 + if (value > valueMax) { + return 7; + } else if (value < valueMin) { + return 9; + } else { + return 8; + } + } else { // region 456 + if (value > valueMax) { + return 4; + } else if (value < valueMin) { + return 6; + } else { + return 5; + } + } } /*! \internal - + 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 the line connecting (\a key, \a value) with (\a otherKey, \a otherValue). - + It returns the intersection point of the segment with the border of region 5. - + For this function it doesn't matter whether (\a key, \a value) is the point inside region 5 or whether it's (\a otherKey, \a otherValue), i.e. whether the segment is coming from region 5 or leaving it. It is important though that \a otherRegion correctly identifies the other region not @@ -23277,113 +23414,99 @@ int QCPCurve::getRegion(double key, double value, double keyMin, double valueMax */ QPointF QCPCurve::getOptimizedPoint(int otherRegion, double otherKey, double otherValue, double key, double value, double keyMin, double valueMax, double keyMax, double valueMin) const { - // The intersection point interpolation here is done in pixel coordinates, so we don't need to - // differentiate between different axis scale types. Note that the nomenclature - // top/left/bottom/right/min/max is with respect to the rect in plot coordinates, wich may be - // different in pixel coordinates (horz/vert key axes, reversed ranges) - - const double keyMinPx = mKeyAxis->coordToPixel(keyMin); - const double keyMaxPx = mKeyAxis->coordToPixel(keyMax); - const double valueMinPx = mValueAxis->coordToPixel(valueMin); - const double valueMaxPx = mValueAxis->coordToPixel(valueMax); - const double otherValuePx = mValueAxis->coordToPixel(otherValue); - const double valuePx = mValueAxis->coordToPixel(value); - const double otherKeyPx = mKeyAxis->coordToPixel(otherKey); - const double keyPx = mKeyAxis->coordToPixel(key); - double intersectKeyPx = keyMinPx; // initial key just a fail-safe - double intersectValuePx = valueMinPx; // initial value just a fail-safe - switch (otherRegion) - { - case 1: // top and left edge - { - intersectValuePx = valueMaxPx; - intersectKeyPx = otherKeyPx + (keyPx-otherKeyPx)/(valuePx-otherValuePx)*(intersectValuePx-otherValuePx); - if (intersectKeyPx < qMin(keyMinPx, keyMaxPx) || intersectKeyPx > qMax(keyMinPx, keyMaxPx)) // check whether top edge is not intersected, then it must be left edge (qMin/qMax necessary since axes may be reversed) - { - intersectKeyPx = keyMinPx; - intersectValuePx = otherValuePx + (valuePx-otherValuePx)/(keyPx-otherKeyPx)*(intersectKeyPx-otherKeyPx); - } - break; + // The intersection point interpolation here is done in pixel coordinates, so we don't need to + // differentiate between different axis scale types. Note that the nomenclature + // top/left/bottom/right/min/max is with respect to the rect in plot coordinates, wich may be + // different in pixel coordinates (horz/vert key axes, reversed ranges) + + const double keyMinPx = mKeyAxis->coordToPixel(keyMin); + const double keyMaxPx = mKeyAxis->coordToPixel(keyMax); + const double valueMinPx = mValueAxis->coordToPixel(valueMin); + const double valueMaxPx = mValueAxis->coordToPixel(valueMax); + const double otherValuePx = mValueAxis->coordToPixel(otherValue); + const double valuePx = mValueAxis->coordToPixel(value); + const double otherKeyPx = mKeyAxis->coordToPixel(otherKey); + const double keyPx = mKeyAxis->coordToPixel(key); + double intersectKeyPx = keyMinPx; // initial key just a fail-safe + double intersectValuePx = valueMinPx; // initial value just a fail-safe + switch (otherRegion) { + case 1: { // top and left edge + intersectValuePx = valueMaxPx; + intersectKeyPx = otherKeyPx + (keyPx - otherKeyPx) / (valuePx - otherValuePx) * (intersectValuePx - otherValuePx); + if (intersectKeyPx < qMin(keyMinPx, keyMaxPx) || intersectKeyPx > qMax(keyMinPx, keyMaxPx)) { // check whether top edge is not intersected, then it must be left edge (qMin/qMax necessary since axes may be reversed) + intersectKeyPx = keyMinPx; + intersectValuePx = otherValuePx + (valuePx - otherValuePx) / (keyPx - otherKeyPx) * (intersectKeyPx - otherKeyPx); + } + break; + } + case 2: { // left edge + intersectKeyPx = keyMinPx; + intersectValuePx = otherValuePx + (valuePx - otherValuePx) / (keyPx - otherKeyPx) * (intersectKeyPx - otherKeyPx); + break; + } + case 3: { // bottom and left edge + intersectValuePx = valueMinPx; + intersectKeyPx = otherKeyPx + (keyPx - otherKeyPx) / (valuePx - otherValuePx) * (intersectValuePx - otherValuePx); + if (intersectKeyPx < qMin(keyMinPx, keyMaxPx) || intersectKeyPx > qMax(keyMinPx, keyMaxPx)) { // check whether bottom edge is not intersected, then it must be left edge (qMin/qMax necessary since axes may be reversed) + intersectKeyPx = keyMinPx; + intersectValuePx = otherValuePx + (valuePx - otherValuePx) / (keyPx - otherKeyPx) * (intersectKeyPx - otherKeyPx); + } + break; + } + case 4: { // top edge + intersectValuePx = valueMaxPx; + intersectKeyPx = otherKeyPx + (keyPx - otherKeyPx) / (valuePx - otherValuePx) * (intersectValuePx - otherValuePx); + break; + } + case 5: { + break; // case 5 shouldn't happen for this function but we add it anyway to prevent potential discontinuity in branch table + } + case 6: { // bottom edge + intersectValuePx = valueMinPx; + intersectKeyPx = otherKeyPx + (keyPx - otherKeyPx) / (valuePx - otherValuePx) * (intersectValuePx - otherValuePx); + break; + } + case 7: { // top and right edge + intersectValuePx = valueMaxPx; + intersectKeyPx = otherKeyPx + (keyPx - otherKeyPx) / (valuePx - otherValuePx) * (intersectValuePx - otherValuePx); + if (intersectKeyPx < qMin(keyMinPx, keyMaxPx) || intersectKeyPx > qMax(keyMinPx, keyMaxPx)) { // check whether top edge is not intersected, then it must be right edge (qMin/qMax necessary since axes may be reversed) + intersectKeyPx = keyMaxPx; + intersectValuePx = otherValuePx + (valuePx - otherValuePx) / (keyPx - otherKeyPx) * (intersectKeyPx - otherKeyPx); + } + break; + } + case 8: { // right edge + intersectKeyPx = keyMaxPx; + intersectValuePx = otherValuePx + (valuePx - otherValuePx) / (keyPx - otherKeyPx) * (intersectKeyPx - otherKeyPx); + break; + } + case 9: { // bottom and right edge + intersectValuePx = valueMinPx; + intersectKeyPx = otherKeyPx + (keyPx - otherKeyPx) / (valuePx - otherValuePx) * (intersectValuePx - otherValuePx); + if (intersectKeyPx < qMin(keyMinPx, keyMaxPx) || intersectKeyPx > qMax(keyMinPx, keyMaxPx)) { // check whether bottom edge is not intersected, then it must be right edge (qMin/qMax necessary since axes may be reversed) + intersectKeyPx = keyMaxPx; + intersectValuePx = otherValuePx + (valuePx - otherValuePx) / (keyPx - otherKeyPx) * (intersectKeyPx - otherKeyPx); + } + break; + } } - case 2: // left edge - { - intersectKeyPx = keyMinPx; - intersectValuePx = otherValuePx + (valuePx-otherValuePx)/(keyPx-otherKeyPx)*(intersectKeyPx-otherKeyPx); - break; - } - case 3: // bottom and left edge - { - intersectValuePx = valueMinPx; - intersectKeyPx = otherKeyPx + (keyPx-otherKeyPx)/(valuePx-otherValuePx)*(intersectValuePx-otherValuePx); - if (intersectKeyPx < qMin(keyMinPx, keyMaxPx) || intersectKeyPx > qMax(keyMinPx, keyMaxPx)) // check whether bottom edge is not intersected, then it must be left edge (qMin/qMax necessary since axes may be reversed) - { - intersectKeyPx = keyMinPx; - intersectValuePx = otherValuePx + (valuePx-otherValuePx)/(keyPx-otherKeyPx)*(intersectKeyPx-otherKeyPx); - } - break; - } - case 4: // top edge - { - intersectValuePx = valueMaxPx; - intersectKeyPx = otherKeyPx + (keyPx-otherKeyPx)/(valuePx-otherValuePx)*(intersectValuePx-otherValuePx); - break; - } - case 5: - { - break; // case 5 shouldn't happen for this function but we add it anyway to prevent potential discontinuity in branch table - } - case 6: // bottom edge - { - intersectValuePx = valueMinPx; - intersectKeyPx = otherKeyPx + (keyPx-otherKeyPx)/(valuePx-otherValuePx)*(intersectValuePx-otherValuePx); - break; - } - case 7: // top and right edge - { - intersectValuePx = valueMaxPx; - intersectKeyPx = otherKeyPx + (keyPx-otherKeyPx)/(valuePx-otherValuePx)*(intersectValuePx-otherValuePx); - if (intersectKeyPx < qMin(keyMinPx, keyMaxPx) || intersectKeyPx > qMax(keyMinPx, keyMaxPx)) // check whether top edge is not intersected, then it must be right edge (qMin/qMax necessary since axes may be reversed) - { - intersectKeyPx = keyMaxPx; - intersectValuePx = otherValuePx + (valuePx-otherValuePx)/(keyPx-otherKeyPx)*(intersectKeyPx-otherKeyPx); - } - break; - } - case 8: // right edge - { - intersectKeyPx = keyMaxPx; - intersectValuePx = otherValuePx + (valuePx-otherValuePx)/(keyPx-otherKeyPx)*(intersectKeyPx-otherKeyPx); - break; - } - case 9: // bottom and right edge - { - intersectValuePx = valueMinPx; - intersectKeyPx = otherKeyPx + (keyPx-otherKeyPx)/(valuePx-otherValuePx)*(intersectValuePx-otherValuePx); - if (intersectKeyPx < qMin(keyMinPx, keyMaxPx) || intersectKeyPx > qMax(keyMinPx, keyMaxPx)) // check whether bottom edge is not intersected, then it must be right edge (qMin/qMax necessary since axes may be reversed) - { - intersectKeyPx = keyMaxPx; - intersectValuePx = otherValuePx + (valuePx-otherValuePx)/(keyPx-otherKeyPx)*(intersectKeyPx-otherKeyPx); - } - break; - } - } - if (mKeyAxis->orientation() == Qt::Horizontal) - return {intersectKeyPx, intersectValuePx}; - else - return {intersectValuePx, intersectKeyPx}; + if (mKeyAxis->orientation() == Qt::Horizontal) + return {intersectKeyPx, intersectValuePx}; + else + return {intersectValuePx, intersectKeyPx}; } /*! \internal - + 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 doesn't unintentionally cut through the visible area of the axis rect and create plot artifacts. This method provides these points that must be added, assuming the original segment doesn't start, end, or traverse region 5. (Corner points where region 5 is traversed are calculated by \ref getTraverseCornerPoints.) - + For example, consider a segment which directly goes from region 4 to 2 but originally is far out to the top left such that it doesn't cross region 5. Naively optimizing these points by projecting them on the top and left borders of region 5 will create a segment that surely crosses @@ -23393,524 +23516,759 @@ QPointF QCPCurve::getOptimizedPoint(int otherRegion, double otherKey, double oth */ 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) - { - case 1: - { - switch (currentRegion) - { - 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)*(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(keyMin, valueMax) << coordsToPixels(keyMax, valueMax); result.append(result.last()); result << coordsToPixels(keyMax, valueMin); } - break; + QVector result; + switch (prevRegion) { + case 1: { + switch (currentRegion) { + 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) * (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(keyMin, valueMax) << coordsToPixels(keyMax, valueMax); + result.append(result.last()); + result << coordsToPixels(keyMax, valueMin); + } + break; + } + } + break; } - } - break; - } - case 2: - { - switch (currentRegion) - { - 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; - } - case 3: - { - switch (currentRegion) - { - 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)*(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(keyMin, valueMin) << coordsToPixels(keyMin, valueMax); result.append(result.last()); result << coordsToPixels(keyMax, valueMax); } - break; + case 2: { + switch (currentRegion) { + 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; } - } - break; - } - case 4: - { - switch (currentRegion) - { - 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; - } - case 5: - { - switch (currentRegion) - { - 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; - } - case 6: - { - switch (currentRegion) - { - 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; - } - case 7: - { - switch (currentRegion) - { - 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)*(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(keyMax, valueMax) << coordsToPixels(keyMin, valueMax); result.append(result.last()); result << coordsToPixels(keyMin, valueMin); } - break; + case 3: { + switch (currentRegion) { + 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) * (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(keyMin, valueMin) << coordsToPixels(keyMin, valueMax); + result.append(result.last()); + result << coordsToPixels(keyMax, valueMax); + } + break; + } + } + break; } - } - break; - } - case 8: - { - switch (currentRegion) - { - 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; - } - case 9: - { - switch (currentRegion) - { - 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)*(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(keyMax, valueMin) << coordsToPixels(keyMax, valueMax); result.append(result.last()); result << coordsToPixels(keyMin, valueMax); } - break; + case 4: { + switch (currentRegion) { + 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; + } + case 5: { + switch (currentRegion) { + 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; + } + case 6: { + switch (currentRegion) { + 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; + } + case 7: { + switch (currentRegion) { + 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) * (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(keyMax, valueMax) << coordsToPixels(keyMin, valueMax); + result.append(result.last()); + result << coordsToPixels(keyMin, valueMin); + } + break; + } + } + break; + } + case 8: { + switch (currentRegion) { + 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; + } + case 9: { + switch (currentRegion) { + 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) * (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(keyMax, valueMin) << coordsToPixels(keyMax, valueMax); + result.append(result.last()); + result << coordsToPixels(keyMin, valueMax); + } + break; + } + } + break; } - } - break; } - } - return result; + return result; } /*! \internal - + 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 nor \a currentRegion is 5 itself. - + If this method returns false, the segment for sure doesn't pass region 5. If it returns true, the segment may or may not pass region 5 and a more fine-grained calculation must be used (\ref getTraverse). */ bool QCPCurve::mayTraverse(int prevRegion, int currentRegion) const { - switch (prevRegion) - { - case 1: - { - switch (currentRegion) - { - case 4: - case 7: - case 2: - case 3: return false; - default: return true; - } + switch (prevRegion) { + case 1: { + switch (currentRegion) { + case 4: + case 7: + case 2: + case 3: + return false; + default: + return true; + } + } + case 2: { + switch (currentRegion) { + case 1: + case 3: + return false; + default: + return true; + } + } + case 3: { + switch (currentRegion) { + case 1: + case 2: + case 6: + case 9: + return false; + default: + return true; + } + } + case 4: { + switch (currentRegion) { + case 1: + case 7: + return false; + default: + return true; + } + } + case 5: + return false; // should never occur + case 6: { + switch (currentRegion) { + case 3: + case 9: + return false; + default: + return true; + } + } + case 7: { + switch (currentRegion) { + case 1: + case 4: + case 8: + case 9: + return false; + default: + return true; + } + } + case 8: { + switch (currentRegion) { + case 7: + case 9: + return false; + default: + return true; + } + } + case 9: { + switch (currentRegion) { + case 3: + case 6: + case 8: + case 7: + return false; + default: + return true; + } + } + default: + return true; } - case 2: - { - switch (currentRegion) - { - case 1: - case 3: return false; - default: return true; - } - } - case 3: - { - switch (currentRegion) - { - case 1: - case 2: - case 6: - case 9: return false; - default: return true; - } - } - case 4: - { - switch (currentRegion) - { - case 1: - case 7: return false; - default: return true; - } - } - case 5: return false; // should never occur - case 6: - { - switch (currentRegion) - { - case 3: - case 9: return false; - default: return true; - } - } - case 7: - { - switch (currentRegion) - { - case 1: - case 4: - case 8: - case 9: return false; - default: return true; - } - } - case 8: - { - switch (currentRegion) - { - case 7: - case 9: return false; - default: return true; - } - } - case 9: - { - switch (currentRegion) - { - case 3: - case 6: - case 8: - case 7: return false; - default: return true; - } - } - default: return true; - } } /*! \internal - + 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 region 5. - + The return value of this method indicates whether the segment actually traverses region 5 or not. - + 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 keyMin, double valueMax, double keyMax, double valueMin, QPointF &crossA, QPointF &crossB) const { - // The intersection point interpolation here is done in pixel coordinates, so we don't need to - // differentiate between different axis scale types. Note that the nomenclature - // top/left/bottom/right/min/max is with respect to the rect in plot coordinates, wich may be - // different in pixel coordinates (horz/vert key axes, reversed ranges) - - QList intersections; - const double valueMinPx = mValueAxis->coordToPixel(valueMin); - const double valueMaxPx = mValueAxis->coordToPixel(valueMax); - const double keyMinPx = mKeyAxis->coordToPixel(keyMin); - const double keyMaxPx = mKeyAxis->coordToPixel(keyMax); - const double keyPx = mKeyAxis->coordToPixel(key); - const double valuePx = mValueAxis->coordToPixel(value); - const double prevKeyPx = mKeyAxis->coordToPixel(prevKey); - const double prevValuePx = mValueAxis->coordToPixel(prevValue); - if (qFuzzyIsNull(keyPx-prevKeyPx)) // line is parallel to value axis - { - // due to region filter in mayTraverse(), if line is parallel to value or key axis, region 5 is traversed here - intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyPx, valueMinPx) : QPointF(valueMinPx, keyPx)); // direction will be taken care of at end of method - intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyPx, valueMaxPx) : QPointF(valueMaxPx, keyPx)); - } else if (qFuzzyIsNull(valuePx-prevValuePx)) // line is parallel to key axis - { - // due to region filter in mayTraverse(), if line is parallel to value or key axis, region 5 is traversed here - intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyMinPx, valuePx) : QPointF(valuePx, keyMinPx)); // direction will be taken care of at end of method - intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyMaxPx, valuePx) : QPointF(valuePx, keyMaxPx)); - } else // line is skewed - { - double gamma; - double keyPerValuePx = (keyPx-prevKeyPx)/(valuePx-prevValuePx); - // check top of rect: - gamma = prevKeyPx + (valueMaxPx-prevValuePx)*keyPerValuePx; - if (gamma >= qMin(keyMinPx, keyMaxPx) && gamma <= qMax(keyMinPx, keyMaxPx)) // qMin/qMax necessary since axes may be reversed - intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(gamma, valueMaxPx) : QPointF(valueMaxPx, gamma)); - // check bottom of rect: - gamma = prevKeyPx + (valueMinPx-prevValuePx)*keyPerValuePx; - if (gamma >= qMin(keyMinPx, keyMaxPx) && gamma <= qMax(keyMinPx, keyMaxPx)) // qMin/qMax necessary since axes may be reversed - intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(gamma, valueMinPx) : QPointF(valueMinPx, gamma)); - const double valuePerKeyPx = 1.0/keyPerValuePx; - // check left of rect: - gamma = prevValuePx + (keyMinPx-prevKeyPx)*valuePerKeyPx; - if (gamma >= qMin(valueMinPx, valueMaxPx) && gamma <= qMax(valueMinPx, valueMaxPx)) // qMin/qMax necessary since axes may be reversed - intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyMinPx, gamma) : QPointF(gamma, keyMinPx)); - // check right of rect: - gamma = prevValuePx + (keyMaxPx-prevKeyPx)*valuePerKeyPx; - if (gamma >= qMin(valueMinPx, valueMaxPx) && gamma <= qMax(valueMinPx, valueMaxPx)) // qMin/qMax necessary since axes may be reversed - intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyMaxPx, gamma) : QPointF(gamma, keyMaxPx)); - } - - // handle cases where found points isn't exactly 2: - if (intersections.size() > 2) - { - // line probably goes through corner of rect, and we got duplicate points there. single out the point pair with greatest distance in between: - double distSqrMax = 0; - QPointF pv1, pv2; - for (int i=0; i distSqrMax) - { - pv1 = intersections.at(i); - pv2 = intersections.at(k); - distSqrMax = distSqr; + // The intersection point interpolation here is done in pixel coordinates, so we don't need to + // differentiate between different axis scale types. Note that the nomenclature + // top/left/bottom/right/min/max is with respect to the rect in plot coordinates, wich may be + // different in pixel coordinates (horz/vert key axes, reversed ranges) + + QList intersections; + const double valueMinPx = mValueAxis->coordToPixel(valueMin); + const double valueMaxPx = mValueAxis->coordToPixel(valueMax); + const double keyMinPx = mKeyAxis->coordToPixel(keyMin); + const double keyMaxPx = mKeyAxis->coordToPixel(keyMax); + const double keyPx = mKeyAxis->coordToPixel(key); + const double valuePx = mValueAxis->coordToPixel(value); + const double prevKeyPx = mKeyAxis->coordToPixel(prevKey); + const double prevValuePx = mValueAxis->coordToPixel(prevValue); + if (qFuzzyIsNull(keyPx - prevKeyPx)) { // line is parallel to value axis + // due to region filter in mayTraverse(), if line is parallel to value or key axis, region 5 is traversed here + intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyPx, valueMinPx) : QPointF(valueMinPx, keyPx)); // direction will be taken care of at end of method + intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyPx, valueMaxPx) : QPointF(valueMaxPx, keyPx)); + } else if (qFuzzyIsNull(valuePx - prevValuePx)) { // line is parallel to key axis + // due to region filter in mayTraverse(), if line is parallel to value or key axis, region 5 is traversed here + intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyMinPx, valuePx) : QPointF(valuePx, keyMinPx)); // direction will be taken care of at end of method + intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyMaxPx, valuePx) : QPointF(valuePx, keyMaxPx)); + } else { // line is skewed + double gamma; + double keyPerValuePx = (keyPx - prevKeyPx) / (valuePx - prevValuePx); + // check top of rect: + gamma = prevKeyPx + (valueMaxPx - prevValuePx) * keyPerValuePx; + if (gamma >= qMin(keyMinPx, keyMaxPx) && gamma <= qMax(keyMinPx, keyMaxPx)) { // qMin/qMax necessary since axes may be reversed + intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(gamma, valueMaxPx) : QPointF(valueMaxPx, gamma)); + } + // check bottom of rect: + gamma = prevKeyPx + (valueMinPx - prevValuePx) * keyPerValuePx; + if (gamma >= qMin(keyMinPx, keyMaxPx) && gamma <= qMax(keyMinPx, keyMaxPx)) { // qMin/qMax necessary since axes may be reversed + intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(gamma, valueMinPx) : QPointF(valueMinPx, gamma)); + } + const double valuePerKeyPx = 1.0 / keyPerValuePx; + // check left of rect: + gamma = prevValuePx + (keyMinPx - prevKeyPx) * valuePerKeyPx; + if (gamma >= qMin(valueMinPx, valueMaxPx) && gamma <= qMax(valueMinPx, valueMaxPx)) { // qMin/qMax necessary since axes may be reversed + intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyMinPx, gamma) : QPointF(gamma, keyMinPx)); + } + // check right of rect: + gamma = prevValuePx + (keyMaxPx - prevKeyPx) * valuePerKeyPx; + if (gamma >= qMin(valueMinPx, valueMaxPx) && gamma <= qMax(valueMinPx, valueMaxPx)) { // qMin/qMax necessary since axes may be reversed + intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyMaxPx, gamma) : QPointF(gamma, keyMaxPx)); } - } } - intersections = QList() << pv1 << pv2; - } else if (intersections.size() != 2) - { - // one or even zero points found (shouldn't happen unless line perfectly tangent to corner), no need to draw segment - return false; - } - - // possibly re-sort points so optimized point segment has same direction as original segment: - double xDelta = keyPx-prevKeyPx; - double yDelta = valuePx-prevValuePx; - if (mKeyAxis->orientation() != Qt::Horizontal) - qSwap(xDelta, yDelta); - if (xDelta*(intersections.at(1).x()-intersections.at(0).x()) + yDelta*(intersections.at(1).y()-intersections.at(0).y()) < 0) // scalar product of both segments < 0 -> opposite direction - intersections.move(0, 1); - crossA = intersections.at(0); - crossB = intersections.at(1); - return true; + + // handle cases where found points isn't exactly 2: + if (intersections.size() > 2) { + // line probably goes through corner of rect, and we got duplicate points there. single out the point pair with greatest distance in between: + double distSqrMax = 0; + QPointF pv1, pv2; + for (int i = 0; i < intersections.size() - 1; ++i) { + for (int k = i + 1; k < intersections.size(); ++k) { + QPointF distPoint = intersections.at(i) - intersections.at(k); + double distSqr = distPoint.x() * distPoint.x() + distPoint.y() + distPoint.y(); + if (distSqr > distSqrMax) { + pv1 = intersections.at(i); + pv2 = intersections.at(k); + distSqrMax = distSqr; + } + } + } + intersections = QList() << pv1 << pv2; + } else if (intersections.size() != 2) { + // one or even zero points found (shouldn't happen unless line perfectly tangent to corner), no need to draw segment + return false; + } + + // possibly re-sort points so optimized point segment has same direction as original segment: + double xDelta = keyPx - prevKeyPx; + double yDelta = valuePx - prevValuePx; + if (mKeyAxis->orientation() != Qt::Horizontal) { + qSwap(xDelta, yDelta); + } + if (xDelta * (intersections.at(1).x() - intersections.at(0).x()) + yDelta * (intersections.at(1).y() - intersections.at(0).y()) < 0) { // scalar product of both segments < 0 -> opposite direction + intersections.move(0, 1); + } + crossA = intersections.at(0); + crossB = intersections.at(1); + return true; } /*! \internal - + 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. - + In certain situations it is not sufficient to merely generate the entry and exit points of the segment into/out of region 5, as \ref getTraverse provides. It may happen that a single segment, in addition to traversing region 5, skips another region outside of region 5, which makes it necessary to add an optimized corner point there (very similar to the job \ref getOptimizedCornerPoints does for segments that are completely in outside regions and don't traverse 5). - + As an example, consider a segment going from region 1 to region 6, traversing the lower left corner of region 5. In this configuration, the segment additionally crosses the border between region 1 and 2 before entering region 5. This makes it necessary to add an additional point in the top left corner, before adding the optimized traverse points. So in this case, the output parameter \a beforeTraverse will contain the top left corner point, and \a afterTraverse will be empty. - + In some cases, such as when going from region 1 to 9, it may even be necessary to add additional 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 keyMin, double valueMax, double keyMax, double valueMin, QVector &beforeTraverse, QVector &afterTraverse) const { - switch (prevRegion) - { - case 1: - { - switch (currentRegion) - { - 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; + switch (prevRegion) { + case 1: { + switch (currentRegion) { + 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; + } + case 2: { + switch (currentRegion) { + case 7: { + afterTraverse << coordsToPixels(keyMax, valueMax); + break; + } + case 9: { + afterTraverse << coordsToPixels(keyMax, valueMin); + break; + } + } + break; + } + case 3: { + switch (currentRegion) { + 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; + } + case 4: { + switch (currentRegion) { + case 3: { + afterTraverse << coordsToPixels(keyMin, valueMin); + break; + } + case 9: { + afterTraverse << coordsToPixels(keyMax, valueMin); + break; + } + } + break; + } + case 5: { + break; // shouldn't happen because this method only handles full traverses + } + case 6: { + switch (currentRegion) { + case 1: { + afterTraverse << coordsToPixels(keyMin, valueMax); + break; + } + case 7: { + afterTraverse << coordsToPixels(keyMax, valueMax); + break; + } + } + break; + } + case 7: { + switch (currentRegion) { + 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; + } + case 8: { + switch (currentRegion) { + case 1: { + afterTraverse << coordsToPixels(keyMin, valueMax); + break; + } + case 3: { + afterTraverse << coordsToPixels(keyMin, valueMin); + break; + } + } + break; + } + case 9: { + switch (currentRegion) { + 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; + } } - case 2: - { - switch (currentRegion) - { - case 7: { afterTraverse << coordsToPixels(keyMax, valueMax); break; } - case 9: { afterTraverse << coordsToPixels(keyMax, valueMin); break; } - } - break; - } - case 3: - { - switch (currentRegion) - { - 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; - } - case 4: - { - switch (currentRegion) - { - case 3: { afterTraverse << coordsToPixels(keyMin, valueMin); break; } - case 9: { afterTraverse << coordsToPixels(keyMax, valueMin); break; } - } - break; - } - case 5: { break; } // shouldn't happen because this method only handles full traverses - case 6: - { - switch (currentRegion) - { - case 1: { afterTraverse << coordsToPixels(keyMin, valueMax); break; } - case 7: { afterTraverse << coordsToPixels(keyMax, valueMax); break; } - } - break; - } - case 7: - { - switch (currentRegion) - { - 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; - } - case 8: - { - switch (currentRegion) - { - case 1: { afterTraverse << coordsToPixels(keyMin, valueMax); break; } - case 3: { afterTraverse << coordsToPixels(keyMin, valueMin); break; } - } - break; - } - case 9: - { - switch (currentRegion) - { - 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; - } - } } /*! \internal - + 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. 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, QCPCurveDataContainer::const_iterator &closestData) const { - closestData = mDataContainer->constEnd(); - if (mDataContainer->isEmpty()) - return -1.0; - if (mLineStyle == lsNone && mScatterStyle.isNone()) - return -1.0; - - if (mDataContainer->size() == 1) - { - QPointF dataPoint = coordsToPixels(mDataContainer->constBegin()->key, mDataContainer->constBegin()->value); - closestData = mDataContainer->constBegin(); - return QCPVector2D(dataPoint-pixelPoint).length(); - } - - // calculate minimum distances to curve data points and find closestData iterator: - double minDistSqr = (std::numeric_limits::max)(); - // 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) - { - const double currentDistSqr = QCPVector2D(coordsToPixels(it->key, it->value)-pixelPoint).lengthSquared(); - if (currentDistSqr < minDistSqr) - { - minDistSqr = currentDistSqr; - closestData = it; + closestData = mDataContainer->constEnd(); + if (mDataContainer->isEmpty()) { + return -1.0; } - } - - // 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; isize() == 1) { + QPointF dataPoint = coordsToPixels(mDataContainer->constBegin()->key, mDataContainer->constBegin()->value); + closestData = mDataContainer->constBegin(); + return QCPVector2D(dataPoint - pixelPoint).length(); + } + + // calculate minimum distances to curve data points and find closestData iterator: + double minDistSqr = (std::numeric_limits::max)(); + // 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) { + const double currentDistSqr = QCPVector2D(coordsToPixels(it->key, it->value) - pixelPoint).lengthSquared(); + if (currentDistSqr < minDistSqr) { + minDistSqr = currentDistSqr; + closestData = it; + } + } + + // 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; i < lines.size() - 1; ++i) { + double currentDistSqr = QCPVector2D(pixelPoint).distanceSquaredToLine(lines.at(i), lines.at(i + 1)); + if (currentDistSqr < minDistSqr) { + minDistSqr = currentDistSqr; + } + } + } + + return qSqrt(minDistSqr); } /* end of 'src/plottables/plottable-curve.cpp' */ @@ -23925,34 +24283,34 @@ double QCPCurve::pointDistance(const QPointF &pixelPoint, QCPCurveDataContainer: /*! \class QCPBarsGroup \brief Groups multiple QCPBars together so they appear side by side - + \image html QCPBarsGroup.png - + When showing multiple QCPBars in one plot which have bars at identical keys, it may be desirable to have them appearing next to each other at each key. This is what adding the respective QCPBars plottables to a QCPBarsGroup achieves. (An alternative approach is to stack them on top of each other, see \ref QCPBars::moveAbove.) - + \section qcpbarsgroup-usage Usage - + To add a QCPBars plottable to the group, create a new group and then add the respective bars intances: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpbarsgroup-creation Alternatively to appending to the group like shown above, you can also set the group on the QCPBars plottable via \ref QCPBars::setBarsGroup. - + The spacing between the bars can be configured via \ref setSpacingType and \ref setSpacing. The bars in this group appear in the plot in the order they were appended. To insert a bars plottable at a certain index position, or to reposition a bars plottable which is already in the group, use \ref insert. - + To remove specific bars from the group, use either \ref remove or call \ref QCPBars::setBarsGroup "QCPBars::setBarsGroup(0)" on the respective bars plottable. - + To clear the entire group, call \ref clear, or simply delete the group. - + \section qcpbarsgroup-example Example - + The image above is generated with the following code: \snippet documentation/doc-image-generator/mainwindow.cpp qcpbarsgroup-example */ @@ -23960,29 +24318,29 @@ double QCPCurve::pointDistance(const QPointF &pixelPoint, QCPCurveDataContainer: /* start of documentation of inline functions */ /*! \fn QList QCPBarsGroup::bars() const - + Returns all bars currently in this group. - + \see bars(int index) */ /*! \fn int QCPBarsGroup::size() const - + Returns the number of QCPBars plottables that are part of this group. - + */ /*! \fn bool QCPBarsGroup::isEmpty() const - + Returns whether this bars group is empty. - + \see size */ /*! \fn bool QCPBarsGroup::contains(QCPBars *bars) - + Returns whether the specified \a bars plottable is part of this group. - + */ /* end of documentation of inline functions */ @@ -23991,28 +24349,28 @@ double QCPCurve::pointDistance(const QPointF &pixelPoint, QCPCurveDataContainer: Constructs a new bars group for the specified QCustomPlot instance. */ QCPBarsGroup::QCPBarsGroup(QCustomPlot *parentPlot) : - QObject(parentPlot), - mParentPlot(parentPlot), - mSpacingType(stAbsolute), - mSpacing(4) + QObject(parentPlot), + mParentPlot(parentPlot), + mSpacingType(stAbsolute), + mSpacing(4) { } QCPBarsGroup::~QCPBarsGroup() { - clear(); + clear(); } /*! Sets how the spacing between adjacent bars is interpreted. See \ref SpacingType. - + The actual spacing can then be specified with \ref setSpacing. \see setSpacing */ void QCPBarsGroup::setSpacingType(SpacingType spacingType) { - mSpacingType = spacingType; + mSpacingType = spacingType; } /*! @@ -24023,7 +24381,7 @@ void QCPBarsGroup::setSpacingType(SpacingType spacingType) */ void QCPBarsGroup::setSpacing(double spacing) { - mSpacing = spacing; + mSpacing = spacing; } /*! @@ -24034,14 +24392,12 @@ void QCPBarsGroup::setSpacing(double spacing) */ QCPBars *QCPBarsGroup::bars(int index) const { - if (index >= 0 && index < mBars.size()) - { - return mBars.at(index); - } else - { - qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; - return nullptr; - } + if (index >= 0 && index < mBars.size()) { + return mBars.at(index); + } else { + qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; + return nullptr; + } } /*! @@ -24051,9 +24407,10 @@ QCPBars *QCPBarsGroup::bars(int index) const */ void QCPBarsGroup::clear() { - const QList oldBars = mBars; - foreach (QCPBars *bars, oldBars) - bars->setBarsGroup(nullptr); // removes itself from mBars via removeBars + const QList oldBars = mBars; + foreach (QCPBars *bars, oldBars) { + bars->setBarsGroup(nullptr); // removes itself from mBars via removeBars + } } /*! @@ -24064,22 +24421,22 @@ void QCPBarsGroup::clear() */ void QCPBarsGroup::append(QCPBars *bars) { - if (!bars) - { - qDebug() << Q_FUNC_INFO << "bars is 0"; - return; - } - - if (!mBars.contains(bars)) - bars->setBarsGroup(this); - else - qDebug() << Q_FUNC_INFO << "bars plottable is already in this bars group:" << reinterpret_cast(bars); + if (!bars) { + qDebug() << Q_FUNC_INFO << "bars is 0"; + return; + } + + if (!mBars.contains(bars)) { + bars->setBarsGroup(this); + } else { + qDebug() << Q_FUNC_INFO << "bars plottable is already in this bars group:" << reinterpret_cast(bars); + } } /*! Inserts the specified \a bars plottable into this group at the specified index position \a i. This gives you full control over the ordering of the bars. - + \a bars may already be part of this group. In that case, \a bars is just moved to the new index position. @@ -24087,130 +24444,127 @@ void QCPBarsGroup::append(QCPBars *bars) */ void QCPBarsGroup::insert(int i, QCPBars *bars) { - if (!bars) - { - qDebug() << Q_FUNC_INFO << "bars is 0"; - return; - } - - // first append to bars list normally: - if (!mBars.contains(bars)) - bars->setBarsGroup(this); - // then move to according position: - mBars.move(mBars.indexOf(bars), qBound(0, i, mBars.size()-1)); + if (!bars) { + qDebug() << Q_FUNC_INFO << "bars is 0"; + return; + } + + // first append to bars list normally: + if (!mBars.contains(bars)) { + bars->setBarsGroup(this); + } + // then move to according position: + mBars.move(mBars.indexOf(bars), qBound(0, i, mBars.size() - 1)); } /*! Removes the specified \a bars plottable from this group. - + \see contains, clear */ void QCPBarsGroup::remove(QCPBars *bars) { - if (!bars) - { - qDebug() << Q_FUNC_INFO << "bars is 0"; - return; - } - - if (mBars.contains(bars)) - bars->setBarsGroup(nullptr); - else - qDebug() << Q_FUNC_INFO << "bars plottable is not in this bars group:" << reinterpret_cast(bars); + if (!bars) { + qDebug() << Q_FUNC_INFO << "bars is 0"; + return; + } + + if (mBars.contains(bars)) { + bars->setBarsGroup(nullptr); + } else { + qDebug() << Q_FUNC_INFO << "bars plottable is not in this bars group:" << reinterpret_cast(bars); + } } /*! \internal - + Adds the specified \a bars to the internal mBars list of bars. This method does not change the barsGroup property on \a bars. - + \see unregisterBars */ void QCPBarsGroup::registerBars(QCPBars *bars) { - if (!mBars.contains(bars)) - mBars.append(bars); + if (!mBars.contains(bars)) { + mBars.append(bars); + } } /*! \internal - + Removes the specified \a bars from the internal mBars list of bars. This method does not change the barsGroup property on \a bars. - + \see registerBars */ void QCPBarsGroup::unregisterBars(QCPBars *bars) { - mBars.removeOne(bars); + mBars.removeOne(bars); } /*! \internal - + Returns the pixel offset in the key dimension the specified \a bars plottable should have at the given key coordinate \a keyCoord. The offset is relative to the pixel position of the key coordinate \a keyCoord. */ double QCPBarsGroup::keyPixelOffset(const QCPBars *bars, double keyCoord) { - // find list of all base bars in case some mBars are stacked: - QList baseBars; - foreach (const QCPBars *b, mBars) - { - while (b->barBelow()) - b = b->barBelow(); - if (!baseBars.contains(b)) - baseBars.append(b); - } - // find base bar this "bars" is stacked on: - const QCPBars *thisBase = bars; - while (thisBase->barBelow()) - thisBase = thisBase->barBelow(); - - // determine key pixel offset of this base bars considering all other base bars in this barsgroup: - double result = 0; - int index = baseBars.indexOf(thisBase); - if (index >= 0) - { - if (baseBars.size() % 2 == 1 && index == (baseBars.size()-1)/2) // is center bar (int division on purpose) - { - return result; - } 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 + (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+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; i != index; i += dir) // 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; - // correct sign of result depending on orientation and direction of key axis: - result *= dir*thisBase->keyAxis()->pixelOrientation(); + // find list of all base bars in case some mBars are stacked: + QList baseBars; + foreach (const QCPBars *b, mBars) { + while (b->barBelow()) { + b = b->barBelow(); + } + if (!baseBars.contains(b)) { + baseBars.append(b); + } } - } - return result; + // find base bar this "bars" is stacked on: + const QCPBars *thisBase = bars; + while (thisBase->barBelow()) { + thisBase = thisBase->barBelow(); + } + + // determine key pixel offset of this base bars considering all other base bars in this barsgroup: + double result = 0; + int index = baseBars.indexOf(thisBase); + if (index >= 0) { + if (baseBars.size() % 2 == 1 && index == (baseBars.size() - 1) / 2) { // is center bar (int division on purpose) + return result; + } 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 + (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 + 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; i != index; i += dir) { // 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; + // correct sign of result depending on orientation and direction of key axis: + result *= dir * thisBase->keyAxis()->pixelOrientation(); + } + } + return result; } /*! \internal - + Returns the spacing in pixels which is between this \a bars and the following one, both at the 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 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 @@ -24218,26 +24572,23 @@ double QCPBarsGroup::keyPixelOffset(const QCPBars *bars, double keyCoord) */ double QCPBarsGroup::getPixelSpacing(const QCPBars *bars, double keyCoord) { - switch (mSpacingType) - { - case stAbsolute: - { - return mSpacing; + switch (mSpacingType) { + case stAbsolute: { + return mSpacing; + } + case stAxisRectRatio: { + if (bars->keyAxis()->orientation() == Qt::Horizontal) { + return bars->keyAxis()->axisRect()->width() * mSpacing; + } else { + return bars->keyAxis()->axisRect()->height() * mSpacing; + } + } + case stPlotCoords: { + double keyPixel = bars->keyAxis()->coordToPixel(keyCoord); + return qAbs(bars->keyAxis()->coordToPixel(keyCoord + mSpacing) - keyPixel); + } } - case stAxisRectRatio: - { - if (bars->keyAxis()->orientation() == Qt::Horizontal) - return bars->keyAxis()->axisRect()->width()*mSpacing; - else - return bars->keyAxis()->axisRect()->height()*mSpacing; - } - case stPlotCoords: - { - double keyPixel = bars->keyAxis()->coordToPixel(keyCoord); - return qAbs(bars->keyAxis()->coordToPixel(keyCoord+mSpacing)-keyPixel); - } - } - return 0; + return 0; } @@ -24247,65 +24598,65 @@ double QCPBarsGroup::getPixelSpacing(const QCPBars *bars, double keyCoord) /*! \class QCPBarsData \brief Holds the data of one single data point (one bar) for QCPBars. - + The stored data is: \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) - + 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. */ @@ -24316,8 +24667,8 @@ double QCPBarsGroup::getPixelSpacing(const QCPBars *bars, double keyCoord) Constructs a bar data point with key and value set to zero. */ QCPBarsData::QCPBarsData() : - key(0), - value(0) + key(0), + value(0) { } @@ -24325,8 +24676,8 @@ QCPBarsData::QCPBarsData() : Constructs a bar data point with the specified \a key and \a value. */ QCPBarsData::QCPBarsData(double key, double value) : - key(key), - value(value) + key(key), + value(value) { } @@ -24339,29 +24690,29 @@ QCPBarsData::QCPBarsData(double key, double value) : \brief A plottable representing a bar chart in a plot. \image html QCPBars.png - + To plot data, assign it with the \ref setData or \ref addData functions. - + \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. - + Bar charts are stackable. This means, two QCPBars plottables can be placed on top of each other (see \ref QCPBars::moveAbove). So when two bars are at the same key position, they will appear stacked. - + If you would like to group multiple QCPBars plottables together so they appear side by side as shown below, use QCPBarsGroup. - + \image html QCPBarsGroup.png - + \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::removePlottable, etc.) - + Usually, you first create an instance: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpbars-creation-1 which registers it with the QCustomPlot instance of the passed axes. Note that this QCustomPlot instance takes @@ -24373,7 +24724,7 @@ QCPBarsData::QCPBarsData(double key, double value) : /* 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. @@ -24382,14 +24733,14 @@ QCPBarsData::QCPBarsData(double key, double value) : /*! \fn QCPBars *QCPBars::barBelow() const Returns the bars plottable that is directly below this bars plottable. If there is no such plottable, returns \c nullptr. - + \see barAbove, moveBelow, moveAbove */ /*! \fn QCPBars *QCPBars::barAbove() const Returns the bars plottable that is directly above this bars plottable. If there is no such plottable, returns \c nullptr. - + \see barBelow, moveBelow, moveAbove */ @@ -24400,69 +24751,70 @@ QCPBarsData::QCPBarsData(double key, double 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 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) : - QCPAbstractPlottable1D(keyAxis, valueAxis), - mWidth(0.75), - mWidthType(wtPlotCoords), - mBarsGroup(nullptr), - mBaseValue(0), - mStackingGap(1) + QCPAbstractPlottable1D(keyAxis, valueAxis), + mWidth(0.75), + mWidthType(wtPlotCoords), + mBarsGroup(nullptr), + mBaseValue(0), + mStackingGap(1) { - // 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); - mSelectionDecorator->setBrush(QBrush(QColor(160, 160, 255))); + // 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); + mSelectionDecorator->setBrush(QBrush(QColor(160, 160, 255))); } QCPBars::~QCPBars() { - setBarsGroup(nullptr); - if (mBarBelow || mBarAbove) - connectBars(mBarBelow.data(), mBarAbove.data()); // take this bar out of any stacking + setBarsGroup(nullptr); + if (mBarBelow || mBarAbove) { + connectBars(mBarBelow.data(), mBarAbove.data()); // take this bar out of any stacking + } } /*! \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; + 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); + mDataContainer->clear(); + addData(keys, values, alreadySorted); } /*! @@ -24473,37 +24825,39 @@ void QCPBars::setData(const QVector &keys, const QVector &values */ void QCPBars::setWidth(double width) { - mWidth = width; + mWidth = width; } /*! Sets how the width of the 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 QCPBars::setWidthType(QCPBars::WidthType widthType) { - mWidthType = widthType; + mWidthType = widthType; } /*! Sets to which QCPBarsGroup this QCPBars instance belongs to. Alternatively, you can also use \ref QCPBarsGroup::append. - + To remove this QCPBars from any group, set \a barsGroup to \c nullptr. */ void QCPBars::setBarsGroup(QCPBarsGroup *barsGroup) { - // deregister at old group: - if (mBarsGroup) - mBarsGroup->unregisterBars(this); - mBarsGroup = barsGroup; - // register at new group: - if (mBarsGroup) - mBarsGroup->registerBars(this); + // deregister at old group: + if (mBarsGroup) { + mBarsGroup->unregisterBars(this); + } + mBarsGroup = barsGroup; + // register at new group: + if (mBarsGroup) { + mBarsGroup->registerBars(this); + } } /*! @@ -24513,14 +24867,14 @@ void QCPBars::setBarsGroup(QCPBarsGroup *barsGroup) the base value is given by their individual value data. For example, if the base value is set to 1, a bar with data value 2 will have its lowest point at value coordinate 1 and highest point at 3. - + For stacked bars, only the base value of the bottom-most QCPBars has meaning. - + The default base value is 0. */ void QCPBars::setBaseValue(double baseValue) { - mBaseValue = baseValue; + mBaseValue = baseValue; } /*! @@ -24530,115 +24884,117 @@ void QCPBars::setBaseValue(double baseValue) */ void QCPBars::setStackingGap(double pixels) { - mStackingGap = pixels; + mStackingGap = pixels; } /*! \overload - + 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::addData(const QVector &keys, const QVector &values, bool alreadySorted) { - 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 + 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 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)); + mDataContainer->add(QCPBarsData(key, value)); } /*! Moves this bars plottable below \a bars. In other words, the bars of this plottable will appear below the bars of \a bars. The move target \a bars must use the same key and value axis as this 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 is already between two other bars, the two other bars will be stacked on top of each other after the operation. - + To remove this bars plottable from any stacking, set \a bars to \c nullptr. - + \see moveBelow, barAbove, barBelow */ void QCPBars::moveBelow(QCPBars *bars) { - if (bars == this) return; - if (bars && (bars->keyAxis() != mKeyAxis.data() || bars->valueAxis() != mValueAxis.data())) - { - qDebug() << Q_FUNC_INFO << "passed QCPBars* doesn't have same key and value axis as this QCPBars"; - return; - } - // remove from stacking: - connectBars(mBarBelow.data(), mBarAbove.data()); // Note: also works if one (or both) of them is 0 - // if new bar given, insert this bar below it: - if (bars) - { - if (bars->mBarBelow) - connectBars(bars->mBarBelow.data(), this); - connectBars(this, bars); - } + if (bars == this) { + return; + } + if (bars && (bars->keyAxis() != mKeyAxis.data() || bars->valueAxis() != mValueAxis.data())) { + qDebug() << Q_FUNC_INFO << "passed QCPBars* doesn't have same key and value axis as this QCPBars"; + return; + } + // remove from stacking: + connectBars(mBarBelow.data(), mBarAbove.data()); // Note: also works if one (or both) of them is 0 + // if new bar given, insert this bar below it: + if (bars) { + if (bars->mBarBelow) { + connectBars(bars->mBarBelow.data(), this); + } + connectBars(this, bars); + } } /*! Moves this bars plottable above \a bars. In other words, the bars of this plottable will appear above the bars of \a bars. The move target \a bars must use the same key and value axis as this plottable. - + Inserting into and removing from existing bar stacking is handled gracefully. If \a bars already 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. - + To remove this bars plottable from any stacking, set \a bars to \c nullptr. - + \see moveBelow, barBelow, barAbove */ void QCPBars::moveAbove(QCPBars *bars) { - if (bars == this) return; - if (bars && (bars->keyAxis() != mKeyAxis.data() || bars->valueAxis() != mValueAxis.data())) - { - qDebug() << Q_FUNC_INFO << "passed QCPBars* doesn't have same key and value axis as this QCPBars"; - return; - } - // remove from stacking: - connectBars(mBarBelow.data(), mBarAbove.data()); // Note: also works if one (or both) of them is 0 - // if new bar given, insert this bar above it: - if (bars) - { - if (bars->mBarAbove) - connectBars(this, bars->mBarAbove.data()); - connectBars(bars, this); - } + if (bars == this) { + return; + } + if (bars && (bars->keyAxis() != mKeyAxis.data() || bars->valueAxis() != mValueAxis.data())) { + qDebug() << Q_FUNC_INFO << "passed QCPBars* doesn't have same key and value axis as this QCPBars"; + return; + } + // remove from stacking: + connectBars(mBarBelow.data(), mBarAbove.data()); // Note: also works if one (or both) of them is 0 + // if new bar given, insert this bar above it: + if (bars) { + if (bars->mBarAbove) { + connectBars(this, bars->mBarAbove.data()); + } + connectBars(bars, this); + } } /*! @@ -24646,22 +25002,24 @@ void QCPBars::moveAbove(QCPBars *bars) */ QCPDataSelection QCPBars::selectTestRect(const QRectF &rect, bool onlySelectable) const { - QCPDataSelection result; - if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty()) + QCPDataSelection result; + if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty()) { + return result; + } + if (!mKeyAxis || !mValueAxis) { + return result; + } + + QCPBarsDataContainer::const_iterator visibleBegin, visibleEnd; + getVisibleDataBounds(visibleBegin, visibleEnd); + + for (QCPBarsDataContainer::const_iterator it = visibleBegin; it != visibleEnd; ++it) { + if (rect.intersects(getBarRect(it->key, it->value))) { + result.addDataRange(QCPDataRange(int(it - mDataContainer->constBegin()), int(it - mDataContainer->constBegin() + 1)), false); + } + } + result.simplify(); return result; - if (!mKeyAxis || !mValueAxis) - return result; - - QCPBarsDataContainer::const_iterator visibleBegin, visibleEnd; - getVisibleDataBounds(visibleBegin, visibleEnd); - - for (QCPBarsDataContainer::const_iterator it=visibleBegin; it!=visibleEnd; ++it) - { - if (rect.intersects(getBarRect(it->key, it->value))) - result.addDataRange(QCPDataRange(int(it-mDataContainer->constBegin()), int(it-mDataContainer->constBegin()+1)), false); - } - result.simplify(); - return result; } /*! @@ -24669,424 +25027,430 @@ QCPDataSelection QCPBars::selectTestRect(const QRectF &rect, bool onlySelectable If \a details is not 0, it will be set to a \ref QCPDataSelection, describing the closest data point to \a pos. - + \seebaseclassmethod \ref QCPAbstractPlottable::selectTest */ double QCPBars::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { - Q_UNUSED(details) - if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty()) - return -1; - if (!mKeyAxis || !mValueAxis) - return -1; - - if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()) || mParentPlot->interactions().testFlag(QCP::iSelectPlottablesBeyondAxisRect)) - { - // get visible data range: - QCPBarsDataContainer::const_iterator visibleBegin, visibleEnd; - getVisibleDataBounds(visibleBegin, visibleEnd); - for (QCPBarsDataContainer::const_iterator it=visibleBegin; it!=visibleEnd; ++it) - { - if (getBarRect(it->key, it->value).contains(pos)) - { - if (details) - { - int pointIndex = int(it-mDataContainer->constBegin()); - details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1))); - } - return mParentPlot->selectionTolerance()*0.99; - } + Q_UNUSED(details) + if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty()) { + return -1; } - } - return -1; + if (!mKeyAxis || !mValueAxis) { + return -1; + } + + if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()) || mParentPlot->interactions().testFlag(QCP::iSelectPlottablesBeyondAxisRect)) { + // get visible data range: + QCPBarsDataContainer::const_iterator visibleBegin, visibleEnd; + getVisibleDataBounds(visibleBegin, visibleEnd); + for (QCPBarsDataContainer::const_iterator it = visibleBegin; it != visibleEnd; ++it) { + if (getBarRect(it->key, it->value).contains(pos)) { + if (details) { + int pointIndex = int(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; + /* 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, false); - itEnd = mDataContainer->findEnd(inKeyRange.upper, false); - } - 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; - } + // 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, false); + itEnd = mDataContainer->findEnd(inKeyRange.upper, false); } - } - - foundRange = true; // return true because bar charts always have the 0-line visible - return range; + 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 {}; } - - 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 {keyPixel, valuePixel}; - else - return {valuePixel, keyPixel}; - } else - { - qDebug() << Q_FUNC_INFO << "Index out of bounds" << index; - return {}; - } + 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 {}; + } + + 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 {keyPixel, valuePixel}; + else + return {valuePixel, keyPixel}; + } else { + qDebug() << Q_FUNC_INFO << "Index out of bounds" << index; + return {}; + } } /* inherits documentation from base class */ void QCPBars::draw(QCPPainter *painter) { - if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } - if (mDataContainer->isEmpty()) return; - - 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->key, it->value)) - qDebug() << Q_FUNC_INFO << "Data point at" << it->key << "of drawn range invalid." << "Plottable name:" << name(); -#endif - // draw bar: - if (isSelectedSegment && mSelectionDecorator) - { - mSelectionDecorator->applyBrush(painter); - mSelectionDecorator->applyPen(painter); - } else - { - painter->setBrush(mBrush); - painter->setPen(mPen); - } - applyDefaultAntialiasingHint(painter); - painter->drawPolygon(getBarRect(it->key, it->value)); + if (!mKeyAxis || !mValueAxis) { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + return; + } + if (mDataContainer->isEmpty()) { + return; + } + + 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 < allSegments.size(); ++i) { + bool isSelectedSegment = 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->key, it->value)) { + qDebug() << Q_FUNC_INFO << "Data point at" << it->key << "of drawn range invalid." << "Plottable name:" << name(); + } +#endif + // draw bar: + if (isSelectedSegment && mSelectionDecorator) { + mSelectionDecorator->applyBrush(painter); + mSelectionDecorator->applyPen(painter); + } else { + painter->setBrush(mBrush); + painter->setPen(mPen); + } + applyDefaultAntialiasingHint(painter); + 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()); } - } - - // 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 QCPBars::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const { - // draw filled rect: - applyDefaultAntialiasingHint(painter); - painter->setBrush(mBrush); - painter->setPen(mPen); - QRectF r = QRectF(0, 0, rect.width()*0.67, rect.height()*0.67); - r.moveCenter(rect.center()); - painter->drawRect(r); + // draw filled rect: + applyDefaultAntialiasingHint(painter); + painter->setBrush(mBrush); + painter->setPen(mPen); + QRectF r = QRectF(0, 0, rect.width() * 0.67, rect.height() * 0.67); + r.moveCenter(rect.center()); + painter->drawRect(r); } /*! \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 QCPBars::getVisibleDataBounds(QCPBarsDataContainer::const_iterator &begin, QCPBarsDataContainer::const_iterator &end) const { - if (!mKeyAxis) - { - 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 - 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 begin to find lower bar that actually is completely outside visible pixel range: - QCPBarsDataContainer::const_iterator it = begin; - while (it != mDataContainer->constBegin()) - { - --it; - const QRectF barRect = getBarRect(it->key, it->value); - if (mKeyAxis.data()->orientation() == Qt::Horizontal) - isVisible = ((!mKeyAxis.data()->rangeReversed() && barRect.right() >= lowerPixelBound) || (mKeyAxis.data()->rangeReversed() && barRect.left() <= lowerPixelBound)); - else // keyaxis is vertical - isVisible = ((!mKeyAxis.data()->rangeReversed() && barRect.top() <= lowerPixelBound) || (mKeyAxis.data()->rangeReversed() && barRect.bottom() >= lowerPixelBound)); - if (isVisible) - begin = it; - else - break; - } - // walk right from ubound to find upper bar that actually is completely outside visible pixel range: - it = end; - while (it != mDataContainer->constEnd()) - { - const QRectF barRect = getBarRect(it->key, it->value); - if (mKeyAxis.data()->orientation() == Qt::Horizontal) - isVisible = ((!mKeyAxis.data()->rangeReversed() && barRect.left() <= upperPixelBound) || (mKeyAxis.data()->rangeReversed() && barRect.right() >= upperPixelBound)); - else // keyaxis is vertical - isVisible = ((!mKeyAxis.data()->rangeReversed() && barRect.bottom() >= upperPixelBound) || (mKeyAxis.data()->rangeReversed() && barRect.top() <= upperPixelBound)); - if (isVisible) - end = it+1; - else - break; - ++it; - } + if (!mKeyAxis) { + 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 + 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 begin to find lower bar that actually is completely outside visible pixel range: + QCPBarsDataContainer::const_iterator it = begin; + while (it != mDataContainer->constBegin()) { + --it; + const QRectF barRect = getBarRect(it->key, it->value); + if (mKeyAxis.data()->orientation() == Qt::Horizontal) { + isVisible = ((!mKeyAxis.data()->rangeReversed() && barRect.right() >= lowerPixelBound) || (mKeyAxis.data()->rangeReversed() && barRect.left() <= lowerPixelBound)); + } else { // keyaxis is vertical + isVisible = ((!mKeyAxis.data()->rangeReversed() && barRect.top() <= lowerPixelBound) || (mKeyAxis.data()->rangeReversed() && barRect.bottom() >= lowerPixelBound)); + } + if (isVisible) { + begin = it; + } else { + break; + } + } + // walk right from ubound to find upper bar that actually is completely outside visible pixel range: + it = end; + while (it != mDataContainer->constEnd()) { + const QRectF barRect = getBarRect(it->key, it->value); + if (mKeyAxis.data()->orientation() == Qt::Horizontal) { + isVisible = ((!mKeyAxis.data()->rangeReversed() && barRect.left() <= upperPixelBound) || (mKeyAxis.data()->rangeReversed() && barRect.right() >= upperPixelBound)); + } else { // keyaxis is vertical + isVisible = ((!mKeyAxis.data()->rangeReversed() && barRect.bottom() >= upperPixelBound) || (mKeyAxis.data()->rangeReversed() && barRect.top() <= upperPixelBound)); + } + if (isVisible) { + end = it + 1; + } else { + break; + } + ++it; + } } /*! \internal - + 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. */ 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 {}; } - - double lowerPixelWidth, upperPixelWidth; - getPixelWidth(key, lowerPixelWidth, upperPixelWidth); - double base = getStackedBaseValue(key, value >= 0); - double basePixel = valueAxis->coordToPixel(base); - double valuePixel = valueAxis->coordToPixel(base+value); - 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) - { - return QRectF(QPointF(keyPixel+lowerPixelWidth, valuePixel), QPointF(keyPixel+upperPixelWidth, basePixel+bottomOffset)).normalized(); - } else - { - return QRectF(QPointF(basePixel+bottomOffset, keyPixel+lowerPixelWidth), QPointF(valuePixel, keyPixel+upperPixelWidth)).normalized(); - } + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + return {}; + } + + double lowerPixelWidth, upperPixelWidth; + getPixelWidth(key, lowerPixelWidth, upperPixelWidth); + double base = getStackedBaseValue(key, value >= 0); + double basePixel = valueAxis->coordToPixel(base); + double valuePixel = valueAxis->coordToPixel(base + value); + 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) { + return QRectF(QPointF(keyPixel + lowerPixelWidth, valuePixel), QPointF(keyPixel + upperPixelWidth, basePixel + bottomOffset)).normalized(); + } else { + return QRectF(QPointF(basePixel + bottomOffset, keyPixel + lowerPixelWidth), QPointF(valuePixel, keyPixel + upperPixelWidth)).normalized(); + } } /*! \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). - + The output parameters \a lower and \a upper return the number of pixels the bar extends to lower and higher keys, relative to the \a key coordinate (so with a non-reversed horizontal axis, \a lower is negative and \a upper positive). */ void QCPBars::getPixelWidth(double key, double &lower, double &upper) const { - lower = 0; - upper = 0; - switch (mWidthType) - { - case wtAbsolute: - { - upper = mWidth*0.5*mKeyAxis.data()->pixelOrientation(); - lower = -upper; - break; + lower = 0; + upper = 0; + switch (mWidthType) { + case wtAbsolute: { + upper = mWidth * 0.5 * mKeyAxis.data()->pixelOrientation(); + lower = -upper; + break; + } + case wtAxisRectRatio: { + if (mKeyAxis && mKeyAxis.data()->axisRect()) { + if (mKeyAxis.data()->orientation() == Qt::Horizontal) { + upper = mKeyAxis.data()->axisRect()->width() * mWidth * 0.5 * mKeyAxis.data()->pixelOrientation(); + } else { + upper = mKeyAxis.data()->axisRect()->height() * mWidth * 0.5 * mKeyAxis.data()->pixelOrientation(); + } + lower = -upper; + } else { + qDebug() << Q_FUNC_INFO << "No key axis or axis rect defined"; + } + break; + } + case wtPlotCoords: { + if (mKeyAxis) { + double keyPixel = mKeyAxis.data()->coordToPixel(key); + upper = mKeyAxis.data()->coordToPixel(key + mWidth * 0.5) - keyPixel; + lower = mKeyAxis.data()->coordToPixel(key - mWidth * 0.5) - keyPixel; + // no need to qSwap(lower, higher) when range reversed, because higher/lower are gained by + // coordinate transform which includes range direction + } else { + qDebug() << Q_FUNC_INFO << "No key axis defined"; + } + break; + } } - case wtAxisRectRatio: - { - if (mKeyAxis && mKeyAxis.data()->axisRect()) - { - if (mKeyAxis.data()->orientation() == Qt::Horizontal) - upper = mKeyAxis.data()->axisRect()->width()*mWidth*0.5*mKeyAxis.data()->pixelOrientation(); - else - upper = mKeyAxis.data()->axisRect()->height()*mWidth*0.5*mKeyAxis.data()->pixelOrientation(); - lower = -upper; - } else - qDebug() << Q_FUNC_INFO << "No key axis or axis rect defined"; - break; - } - case wtPlotCoords: - { - if (mKeyAxis) - { - double keyPixel = mKeyAxis.data()->coordToPixel(key); - upper = mKeyAxis.data()->coordToPixel(key+mWidth*0.5)-keyPixel; - lower = mKeyAxis.data()->coordToPixel(key-mWidth*0.5)-keyPixel; - // no need to qSwap(lower, higher) when range reversed, because higher/lower are gained by - // coordinate transform which includes range direction - } else - qDebug() << Q_FUNC_INFO << "No key axis defined"; - break; - } - } } /*! \internal - + This function is called to find at which value to start drawing the base of a bar at \a key, when it is stacked on top of another QCPBars (e.g. with \ref moveAbove). - + positive and negative bars are separated per stack (positive are stacked above baseValue upwards, negative are stacked below baseValue downwards). This can be indicated with \a positive. So if the bar for which we need the base value is negative, set \a positive to false. */ double QCPBars::getStackedBaseValue(double key, bool positive) const { - if (mBarBelow) - { - 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)*(sizeof(key)==4 ? 1e-6 : 1e-14); // should be safe even when changed to use float at some point - if (key == 0) - 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 (it->key > key-epsilon && it->key < key+epsilon) - { - if ((positive && it->value > max) || - (!positive && it->value < max)) - max = it->value; - } - ++it; + if (mBarBelow) { + 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) * (sizeof(key) == 4 ? 1e-6 : 1e-14); // should be safe even when changed to use float at some point + if (key == 0) { + 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 (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: + return max + mBarBelow.data()->getStackedBaseValue(key, positive); + } else { + return mBaseValue; } - // recurse down the bar-stack to find the total height: - return max + mBarBelow.data()->getStackedBaseValue(key, positive); - } else - return mBaseValue; } /*! \internal Connects \a below and \a above to each other via their mBarAbove/mBarBelow properties. The bar(s) currently above lower and below upper will become disconnected to lower/upper. - + If lower is zero, upper will be disconnected at the bottom. If upper is zero, lower will be disconnected at the top. */ void QCPBars::connectBars(QCPBars *lower, QCPBars *upper) { - if (!lower && !upper) return; - - if (!lower) // disconnect upper at bottom - { - // disconnect old bar below upper: - if (upper->mBarBelow && upper->mBarBelow.data()->mBarAbove.data() == upper) - upper->mBarBelow.data()->mBarAbove = nullptr; - upper->mBarBelow = nullptr; - } else if (!upper) // disconnect lower at top - { - // disconnect old bar above lower: - if (lower->mBarAbove && lower->mBarAbove.data()->mBarBelow.data() == lower) - lower->mBarAbove.data()->mBarBelow = nullptr; - lower->mBarAbove = nullptr; - } else // connect lower and upper - { - // disconnect old bar above lower: - if (lower->mBarAbove && lower->mBarAbove.data()->mBarBelow.data() == lower) - lower->mBarAbove.data()->mBarBelow = nullptr; - // disconnect old bar below upper: - if (upper->mBarBelow && upper->mBarBelow.data()->mBarAbove.data() == upper) - upper->mBarBelow.data()->mBarAbove = nullptr; - lower->mBarAbove = upper; - upper->mBarBelow = lower; - } + if (!lower && !upper) { + return; + } + + if (!lower) { // disconnect upper at bottom + // disconnect old bar below upper: + if (upper->mBarBelow && upper->mBarBelow.data()->mBarAbove.data() == upper) { + upper->mBarBelow.data()->mBarAbove = nullptr; + } + upper->mBarBelow = nullptr; + } else if (!upper) { // disconnect lower at top + // disconnect old bar above lower: + if (lower->mBarAbove && lower->mBarAbove.data()->mBarBelow.data() == lower) { + lower->mBarAbove.data()->mBarBelow = nullptr; + } + lower->mBarAbove = nullptr; + } else { // connect lower and upper + // disconnect old bar above lower: + if (lower->mBarAbove && lower->mBarAbove.data()->mBarBelow.data() == lower) { + lower->mBarAbove.data()->mBarBelow = nullptr; + } + // disconnect old bar below upper: + if (upper->mBarBelow && upper->mBarBelow.data()->mBarAbove.data() == upper) { + upper->mBarBelow.data()->mBarAbove = nullptr; + } + lower->mBarAbove = upper; + upper->mBarBelow = lower; + } } /* end of 'src/plottables/plottable-bars.cpp' */ @@ -25100,87 +25464,87 @@ void QCPBars::connectBars(QCPBars *lower, QCPBars *upper) /*! \class QCPStatisticalBoxData \brief Holds the data of one single data point for QCPStatisticalBox. - + 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. */ @@ -25191,12 +25555,12 @@ void QCPBars::connectBars(QCPBars *lower, QCPBars *upper) 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) + key(0), + minimum(0), + lowerQuartile(0), + median(0), + upperQuartile(0), + maximum(0) { } @@ -25205,13 +25569,13 @@ QCPStatisticalBoxData::QCPStatisticalBoxData() : 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) + key(key), + minimum(minimum), + lowerQuartile(lowerQuartile), + median(median), + upperQuartile(upperQuartile), + maximum(maximum), + outliers(outliers) { } @@ -25224,19 +25588,19 @@ QCPStatisticalBoxData::QCPStatisticalBoxData(double key, double minimum, double \brief A plottable representing a single statistical box in a plot. \image html QCPStatisticalBox.png - + 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 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 qcpstatisticalbox-appearance Changing the appearance - + 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. @@ -25248,18 +25612,18 @@ QCPStatisticalBoxData::QCPStatisticalBoxData(double key, double minimum, double 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 inside the box has its own pen, \ref setMedianPen. - + The outlier data points are drawn as normal scatter points. Their look can be controlled with \ref setOutlierStyle - + \section qcpstatisticalbox-usage Usage - + 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 which registers it with the QCustomPlot instance of the passed axes. Note that this QCustomPlot instance takes @@ -25271,7 +25635,7 @@ QCPStatisticalBoxData::QCPStatisticalBoxData(double key, double minimum, double /* 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. @@ -25284,113 +25648,113 @@ QCPStatisticalBoxData::QCPStatisticalBoxData(double key, double minimum, double 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 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) : - 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) + 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) { - setPen(QPen(Qt::black)); - setBrush(Qt::NoBrush); + setPen(QPen(Qt::black)); + setBrush(Qt::NoBrush); } /*! \overload - + Replaces the current data container with the provided \a data container. - + 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 - + 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 addData */ void QCPStatisticalBox::setData(QSharedPointer data) { - mDataContainer = data; + mDataContainer = data; } /*! \overload - + 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. - + 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 QCPStatisticalBox::setData(const QVector &keys, const QVector &minimum, const QVector &lowerQuartile, const QVector &median, const QVector &upperQuartile, const QVector &maximum, bool alreadySorted) { - mDataContainer->clear(); - addData(keys, minimum, lowerQuartile, median, upperQuartile, maximum, alreadySorted); + mDataContainer->clear(); + addData(keys, minimum, lowerQuartile, median, upperQuartile, maximum, alreadySorted); } /*! Sets the width of the boxes in key coordinates. - + \see setWhiskerWidth */ void QCPStatisticalBox::setWidth(double width) { - mWidth = width; + mWidth = width; } /*! 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 */ void QCPStatisticalBox::setWhiskerWidth(double width) { - mWhiskerWidth = width; + mWhiskerWidth = width; } /*! Sets the pen used for drawing the whisker backbone. - + 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 */ void QCPStatisticalBox::setWhiskerPen(const QPen &pen) { - mWhiskerPen = pen; + mWhiskerPen = 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. - + Whiskers are the lines which reach from the upper quartile to the maximum, and from the lower quartile to the minimum. - + \see setWhiskerPen */ void QCPStatisticalBox::setWhiskerBarPen(const QPen &pen) { - mWhiskerBarPen = pen; + mWhiskerBarPen = pen; } /*! @@ -25401,7 +25765,7 @@ void QCPStatisticalBox::setWhiskerBarPen(const QPen &pen) */ void QCPStatisticalBox::setWhiskerAntialiased(bool enabled) { - mWhiskerAntialiased = enabled; + mWhiskerAntialiased = enabled; } /*! @@ -25409,7 +25773,7 @@ void QCPStatisticalBox::setWhiskerAntialiased(bool enabled) */ void QCPStatisticalBox::setMedianPen(const QPen &pen) { - mMedianPen = pen; + mMedianPen = pen; } /*! @@ -25420,57 +25784,56 @@ void QCPStatisticalBox::setMedianPen(const QPen &pen) */ void QCPStatisticalBox::setOutlierStyle(const QCPScatterStyle &style) { - mOutlierStyle = style; + mOutlierStyle = style; } /*! \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) { - 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 + 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)); + mDataContainer->add(QCPStatisticalBoxData(key, minimum, lowerQuartile, median, upperQuartile, maximum, outliers)); } /*! @@ -25478,22 +25841,24 @@ void QCPStatisticalBox::addData(double key, double minimum, double lowerQuartile */ QCPDataSelection QCPStatisticalBox::selectTestRect(const QRectF &rect, bool onlySelectable) const { - QCPDataSelection result; - if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty()) + 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(int(it - mDataContainer->constBegin()), int(it - mDataContainer->constBegin() + 1)), false); + } + } + result.simplify(); 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(int(it-mDataContainer->constBegin()), int(it-mDataContainer->constBegin()+1)), false); - } - result.simplify(); - return result; } /*! @@ -25501,148 +25866,149 @@ QCPDataSelection QCPStatisticalBox::selectTestRect(const QRectF &rect, bool only If \a details is not 0, it will be set to a \ref QCPDataSelection, describing the closest data point to \a pos. - + \seebaseclassmethod \ref QCPAbstractPlottable::selectTest */ double QCPStatisticalBox::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { - Q_UNUSED(details) - if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty()) - return -1; - if (!mKeyAxis || !mValueAxis) - return -1; - - if (mKeyAxis->axisRect()->rect().contains(pos.toPoint()) || mParentPlot->interactions().testFlag(QCP::iSelectPlottablesBeyondAxisRect)) - { - // 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); - const QCPVector2D posVec(pos); - foreach (const QLineF &backbone, whiskerBackbones) - { - double currentDistSqr = posVec.distanceSquaredToLine(backbone); - if (currentDistSqr < minDistSqr) - { - minDistSqr = currentDistSqr; - closestDataPoint = it; - } - } - } + Q_UNUSED(details) + if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty()) { + return -1; } - if (details) - { - int pointIndex = int(closestDataPoint-mDataContainer->constBegin()); - details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1))); + if (!mKeyAxis || !mValueAxis) { + return -1; } - return qSqrt(minDistSqr); - } - return -1; + + if (mKeyAxis->axisRect()->rect().contains(pos.toPoint()) || mParentPlot->interactions().testFlag(QCP::iSelectPlottablesBeyondAxisRect)) { + // 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); + const QCPVector2D posVec(pos); + foreach (const QLineF &backbone, whiskerBackbones) { + double currentDistSqr = posVec.distanceSquaredToLine(backbone); + if (currentDistSqr < minDistSqr) { + minDistSqr = currentDistSqr; + closestDataPoint = it; + } + } + } + } + if (details) { + int pointIndex = int(closestDataPoint - mDataContainer->constBegin()); + 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; + 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); + return mDataContainer->valueRange(foundRange, inSignDomain, inKeyRange); } /* inherits documentation from base class */ void QCPStatisticalBox::draw(QCPPainter *painter) { - if (mDataContainer->isEmpty()) return; - QCPAxis *keyAxis = mKeyAxis.data(); - QCPAxis *valueAxis = mValueAxis.data(); - if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } - - QCPStatisticalBoxDataContainer::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(); - 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); + if (mDataContainer->isEmpty()) { + return; + } + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + return; + } + + QCPStatisticalBoxDataContainer::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 < allSegments.size(); ++i) { + bool isSelectedSegment = 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; i < it->outliers.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); + } + } + + // draw other selection decoration that isn't just line/scatter pens and brushes: + if (mSelectionDecorator) { + mSelectionDecorator->drawDecoration(painter, selection()); } - } - - // 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 QCPStatisticalBox::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const { - // draw filled rect: - applyDefaultAntialiasingHint(painter); - painter->setPen(mPen); - painter->setBrush(mBrush); - QRectF r = QRectF(0, 0, rect.width()*0.67, rect.height()*0.67); - r.moveCenter(rect.center()); - painter->drawRect(r); + // draw filled rect: + applyDefaultAntialiasingHint(painter); + painter->setPen(mPen); + painter->setBrush(mBrush); + QRectF r = QRectF(0, 0, rect.width() * 0.67, rect.height() * 0.67); + r.moveCenter(rect.center()); + painter->drawRect(r); } /*! @@ -25655,54 +26021,54 @@ void QCPStatisticalBox::drawLegendIcon(QCPPainter *painter, const QRectF &rect) */ void QCPStatisticalBox::drawStatisticalBox(QCPPainter *painter, QCPStatisticalBoxDataContainer::const_iterator it, const QCPScatterStyle &outlierStyle) const { - // 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(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->drawLines(getWhiskerBackboneLines(it)); - painter->setPen(mWhiskerBarPen); - painter->drawLines(getWhiskerBarLines(it)); - // draw outliers: - applyScattersAntialiasingHint(painter); - outlierStyle.applyTo(painter, mPen); - for (int i=0; ioutliers.size(); ++i) - outlierStyle.drawShape(painter, coordsToPixels(it->key, it->outliers.at(i))); + // 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(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->drawLines(getWhiskerBackboneLines(it)); + painter->setPen(mWhiskerBarPen); + painter->drawLines(getWhiskerBarLines(it)); + // draw outliers: + applyScattersAntialiasingHint(painter); + outlierStyle.applyTo(painter, mPen); + for (int i = 0; i < it->outliers.size(); ++i) { + outlierStyle.drawShape(painter, coordsToPixels(it->key, it->outliers.at(i))); + } } /*! \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 { - if (!mKeyAxis) - { - 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 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 + if (!mKeyAxis) { + 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 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 } /*! \internal @@ -25714,10 +26080,10 @@ void QCPStatisticalBox::getVisibleDataBounds(QCPStatisticalBoxDataContainer::con */ QRectF QCPStatisticalBox::getQuartileBox(QCPStatisticalBoxDataContainer::const_iterator it) const { - QRectF result; - result.setTopLeft(coordsToPixels(it->key-mWidth*0.5, it->upperQuartile)); - result.setBottomRight(coordsToPixels(it->key+mWidth*0.5, it->lowerQuartile)); - return result; + 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 @@ -25730,10 +26096,10 @@ QRectF QCPStatisticalBox::getQuartileBox(QCPStatisticalBoxDataContainer::const_i */ 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; + 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 @@ -25745,10 +26111,10 @@ QVector QCPStatisticalBox::getWhiskerBackboneLines(QCPStatisticalBoxData */ 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; + 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' */ @@ -25762,25 +26128,25 @@ QVector QCPStatisticalBox::getWhiskerBarLines(QCPStatisticalBoxDataConta /*! \class QCPColorMapData \brief Holds the two-dimensional data of a QCPColorMap plottable. - + This class is a data storage for \ref QCPColorMap. It holds a two-dimensional array, which \ref QCPColorMap then displays as a 2D image in the plot, where the array values are represented by a color, depending on the value. - + The size of the array can be controlled via \ref setSize (or \ref setKeySize, \ref setValueSize). Which plot coordinates these cells correspond to can be configured with \ref setRange (or \ref setKeyRange, \ref setValueRange). - + The data cells can be accessed in two ways: They can be directly addressed by an integer index with \ref setCell. This is the fastest method. Alternatively, they can be addressed by their plot 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, @@ -25796,7 +26162,7 @@ QVector QCPStatisticalBox::getWhiskerBarLines(QCPStatisticalBoxDataConta /* start of documentation of inline functions */ /*! \fn bool QCPColorMapData::isEmpty() const - + Returns whether this instance carries no data. This is equivalent to having a size where at least one of the dimensions is 0 (see \ref setSize). */ @@ -25807,41 +26173,41 @@ QVector QCPStatisticalBox::getWhiskerBarLines(QCPStatisticalBoxDataConta Constructs a new QCPColorMapData instance. The instance has \a keySize cells in the key direction and \a valueSize cells in the value direction. These cells will be displayed by the \ref QCPColorMap at the coordinates \a keyRange and \a valueRange. - + \see setSize, setKeySize, setValueSize, setRange, setKeyRange, setValueRange */ QCPColorMapData::QCPColorMapData(int keySize, int valueSize, const QCPRange &keyRange, const QCPRange &valueRange) : - mKeySize(0), - mValueSize(0), - mKeyRange(keyRange), - mValueRange(valueRange), - mIsEmpty(true), - mData(nullptr), - mAlpha(nullptr), - mDataModified(true) + mKeySize(0), + mValueSize(0), + mKeyRange(keyRange), + mValueRange(valueRange), + mIsEmpty(true), + mData(nullptr), + mAlpha(nullptr), + mDataModified(true) { - setSize(keySize, valueSize); - fill(0); + setSize(keySize, valueSize); + fill(0); } QCPColorMapData::~QCPColorMapData() { - delete[] mData; - delete[] mAlpha; + delete[] mData; + delete[] mAlpha; } /*! Constructs a new QCPColorMapData instance copying the data and range of \a other. */ QCPColorMapData::QCPColorMapData(const QCPColorMapData &other) : - mKeySize(0), - mValueSize(0), - mIsEmpty(true), - mData(nullptr), - mAlpha(nullptr), - mDataModified(true) + mKeySize(0), + mValueSize(0), + mIsEmpty(true), + mData(nullptr), + mAlpha(nullptr), + mDataModified(true) { - *this = other; + *this = other; } /*! @@ -25850,46 +26216,49 @@ QCPColorMapData::QCPColorMapData(const QCPColorMapData &other) : */ QCPColorMapData &QCPColorMapData::operator=(const QCPColorMapData &other) { - if (&other != this) - { - 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 (!isEmpty()) - { - memcpy(mData, other.mData, sizeof(mData[0])*size_t(keySize*valueSize)); - if (mAlpha) - memcpy(mAlpha, other.mAlpha, sizeof(mAlpha[0])*size_t(keySize*valueSize)); + if (&other != this) { + 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 (!isEmpty()) { + memcpy(mData, other.mData, sizeof(mData[0])*size_t(keySize * valueSize)); + if (mAlpha) { + memcpy(mAlpha, other.mAlpha, sizeof(mAlpha[0])*size_t(keySize * valueSize)); + } + } + mDataBounds = other.mDataBounds; + mDataModified = true; } - mDataBounds = other.mDataBounds; - mDataModified = true; - } - return *this; + return *this; } /* undocumented getter */ double QCPColorMapData::data(double key, double value) { - int keyCell = int( (key-mKeyRange.lower)/(mKeyRange.upper-mKeyRange.lower)*(mKeySize-1)+0.5 ); - int valueCell = int( (value-mValueRange.lower)/(mValueRange.upper-mValueRange.lower)*(mValueSize-1)+0.5 ); - if (keyCell >= 0 && keyCell < mKeySize && valueCell >= 0 && valueCell < mValueSize) - return mData[valueCell*mKeySize + keyCell]; - else - return 0; + int keyCell = int((key - mKeyRange.lower) / (mKeyRange.upper - mKeyRange.lower) * (mKeySize - 1) + 0.5); + int valueCell = int((value - mValueRange.lower) / (mValueRange.upper - mValueRange.lower) * (mValueSize - 1) + 0.5); + if (keyCell >= 0 && keyCell < mKeySize && valueCell >= 0 && valueCell < mValueSize) { + return mData[valueCell * mKeySize + keyCell]; + } else { + return 0; + } } /* undocumented getter */ double QCPColorMapData::cell(int keyIndex, int valueIndex) { - if (keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize) - return mData[valueIndex*mKeySize + keyIndex]; - else - return 0; + if (keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize) { + return mData[valueIndex * mKeySize + keyIndex]; + } else { + return 0; + } } /*! @@ -25902,10 +26271,11 @@ double QCPColorMapData::cell(int keyIndex, int valueIndex) */ 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; + if (mAlpha && keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize) { + return mAlpha[valueIndex * mKeySize + keyIndex]; + } else { + return 255; + } } /*! @@ -25914,7 +26284,7 @@ unsigned char QCPColorMapData::alpha(int keyIndex, int valueIndex) The current data is discarded and the map cells are set to 0, unless the map had already the requested size. - + Setting at least one of \a keySize or \a valueSize to zero frees the internal data array and \ref isEmpty returns true. @@ -25922,33 +26292,36 @@ unsigned char QCPColorMapData::alpha(int keyIndex, int valueIndex) */ void QCPColorMapData::setSize(int keySize, int valueSize) { - if (keySize != mKeySize || valueSize != mValueSize) - { - mKeySize = keySize; - mValueSize = valueSize; - delete[] mData; - mIsEmpty = mKeySize == 0 || mValueSize == 0; - if (!mIsEmpty) - { + if (keySize != mKeySize || valueSize != mValueSize) { + mKeySize = keySize; + mValueSize = valueSize; + delete[] mData; + mIsEmpty = mKeySize == 0 || mValueSize == 0; + if (!mIsEmpty) { #ifdef __EXCEPTIONS - try { // 2D arrays get memory intensive fast. So if the allocation fails, at least output debug message + try { // 2D arrays get memory intensive fast. So if the allocation fails, at least output debug message #endif - mData = new double[size_t(mKeySize*mValueSize)]; + mData = new double[size_t(mKeySize * mValueSize)]; #ifdef __EXCEPTIONS - } catch (...) { mData = nullptr; } + } catch (...) { + mData = nullptr; + } #endif - if (mData) - fill(0); - else - qDebug() << Q_FUNC_INFO << "out of memory for data dimensions "<< mKeySize << "*" << mValueSize; - } else - mData = nullptr; - - if (mAlpha) // if we had an alpha map, recreate it with new size - createAlpha(); - - mDataModified = true; - } + if (mData) { + fill(0); + } else { + qDebug() << Q_FUNC_INFO << "out of memory for data dimensions " << mKeySize << "*" << mValueSize; + } + } else { + mData = nullptr; + } + + if (mAlpha) { // if we had an alpha map, recreate it with new size + createAlpha(); + } + + mDataModified = true; + } } /*! @@ -25956,14 +26329,14 @@ void QCPColorMapData::setSize(int keySize, int valueSize) The current data is discarded and the map cells are set to 0, unless the map had already the requested size. - + Setting \a keySize to zero frees the internal data array and \ref isEmpty returns true. \see setKeyRange, setSize, setValueSize */ void QCPColorMapData::setKeySize(int keySize) { - setSize(keySize, mValueSize); + setSize(keySize, mValueSize); } /*! @@ -25971,112 +26344,115 @@ void QCPColorMapData::setKeySize(int keySize) The current data is discarded and the map cells are set to 0, unless the map had already the requested size. - + Setting \a valueSize to zero frees the internal data array and \ref isEmpty returns true. \see setValueRange, setSize, setKeySize */ void QCPColorMapData::setValueSize(int valueSize) { - setSize(mKeySize, valueSize); + setSize(mKeySize, valueSize); } /*! Sets the coordinate ranges the data shall be distributed over. This defines the rectangular area covered by the color map in plot coordinates. - + The outer cells will be centered on the range boundaries given to this function. For example, if the key size (\ref setKeySize) is 3 and \a keyRange is set to QCPRange(2, 3) there will be cells centered on the key coordinates 2, 2.5 and 3. - + \see setSize */ void QCPColorMapData::setRange(const QCPRange &keyRange, const QCPRange &valueRange) { - setKeyRange(keyRange); - setValueRange(valueRange); + setKeyRange(keyRange); + setValueRange(valueRange); } /*! Sets the coordinate range the data shall be distributed over in the key dimension. Together with the value range, This defines the rectangular area covered by the color map in plot coordinates. - + The outer cells will be centered on the range boundaries given to this function. For example, if the key size (\ref setKeySize) is 3 and \a keyRange is set to QCPRange(2, 3) there will be cells centered on the key coordinates 2, 2.5 and 3. - + \see setRange, setValueRange, setSize */ void QCPColorMapData::setKeyRange(const QCPRange &keyRange) { - mKeyRange = keyRange; + mKeyRange = keyRange; } /*! Sets the coordinate range the data shall be distributed over in the value dimension. Together with the key range, This defines the rectangular area covered by the color map in plot coordinates. - + The outer cells will be centered on the range boundaries given to this function. For example, if the value size (\ref setValueSize) is 3 and \a valueRange is set to QCPRange(2, 3) there will be cells centered on the value coordinates 2, 2.5 and 3. - + \see setRange, setKeyRange, setSize */ void QCPColorMapData::setValueRange(const QCPRange &valueRange) { - mValueRange = valueRange; + mValueRange = valueRange; } /*! Sets the data of the cell, which lies at the plot coordinates given by \a key and \a value, to \a z. - + \note The QCPColorMap always displays the data at equal key/value intervals, even if the key or value axis is set to a logarithmic scaling. If you want to use QCPColorMap with logarithmic axes, you shouldn't use the \ref QCPColorMapData::setData method as it uses a linear transformation to determine the cell index. Rather directly access the cell index with \ref QCPColorMapData::setCell. - + \see setCell, setRange */ void QCPColorMapData::setData(double key, double value, double z) { - int keyCell = int( (key-mKeyRange.lower)/(mKeyRange.upper-mKeyRange.lower)*(mKeySize-1)+0.5 ); - int valueCell = int( (value-mValueRange.lower)/(mValueRange.upper-mValueRange.lower)*(mValueSize-1)+0.5 ); - if (keyCell >= 0 && keyCell < mKeySize && valueCell >= 0 && valueCell < mValueSize) - { - mData[valueCell*mKeySize + keyCell] = z; - if (z < mDataBounds.lower) - mDataBounds.lower = z; - if (z > mDataBounds.upper) - mDataBounds.upper = z; - mDataModified = true; - } + int keyCell = int((key - mKeyRange.lower) / (mKeyRange.upper - mKeyRange.lower) * (mKeySize - 1) + 0.5); + int valueCell = int((value - mValueRange.lower) / (mValueRange.upper - mValueRange.lower) * (mValueSize - 1) + 0.5); + if (keyCell >= 0 && keyCell < mKeySize && valueCell >= 0 && valueCell < mValueSize) { + mData[valueCell * mKeySize + keyCell] = z; + if (z < mDataBounds.lower) { + mDataBounds.lower = z; + } + if (z > mDataBounds.upper) { + mDataBounds.upper = z; + } + mDataModified = true; + } } /*! Sets the data of the cell with indices \a keyIndex and \a valueIndex to \a z. The indices enumerate the cells starting from zero, up to the map's size-1 in the respective dimension (see \ref setSize). - + In the standard plot configuration (horizontal key axis and vertical value axis, both not range-reversed), the cell with indices (0, 0) is in the bottom left corner and the cell with indices (keySize-1, valueSize-1) is in the top right corner of the color map. - + \see setData, setSize */ void QCPColorMapData::setCell(int keyIndex, int valueIndex, double z) { - if (keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize) - { - mData[valueIndex*mKeySize + keyIndex] = z; - if (z < mDataBounds.lower) - mDataBounds.lower = z; - if (z > mDataBounds.upper) - mDataBounds.upper = z; - mDataModified = true; - } else - qDebug() << Q_FUNC_INFO << "index out of bounds:" << keyIndex << valueIndex; + if (keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize) { + mData[valueIndex * mKeySize + keyIndex] = z; + if (z < mDataBounds.lower) { + mDataBounds.lower = z; + } + if (z > mDataBounds.upper) { + mDataBounds.upper = z; + } + mDataModified = true; + } else { + qDebug() << Q_FUNC_INFO << "index out of bounds:" << keyIndex << valueIndex; + } } /*! @@ -26096,57 +26472,56 @@ void QCPColorMapData::setCell(int keyIndex, int valueIndex, double z) */ 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; + 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; } - } else - qDebug() << Q_FUNC_INFO << "index out of bounds:" << keyIndex << valueIndex; } /*! Goes through the data and updates the buffered minimum and maximum data values. - + Calling this method is only advised if you are about to call \ref QCPColorMap::rescaleDataRange and can not guarantee that the cells holding the maximum or minimum data haven't been overwritten with a smaller or larger value respectively, since the buffered maximum/minimum values have been updated the last time. Why this is the case is explained in the class description (\ref QCPColorMapData). - + Note that the method \ref QCPColorMap::rescaleDataRange provides a parameter \a recalculateDataBounds for convenience. Setting this to true will call this method for you, before doing the rescale. */ void QCPColorMapData::recalculateDataBounds() { - if (mKeySize > 0 && mValueSize > 0) - { - double minHeight = mData[0]; - double maxHeight = mData[0]; - const int dataCount = mValueSize*mKeySize; - for (int i=0; i maxHeight) - maxHeight = mData[i]; - if (mData[i] < minHeight) - minHeight = mData[i]; + if (mKeySize > 0 && mValueSize > 0) { + double minHeight = mData[0]; + double maxHeight = mData[0]; + const int dataCount = mValueSize * mKeySize; + for (int i = 0; i < dataCount; ++i) { + if (mData[i] > maxHeight) { + maxHeight = mData[i]; + } + if (mData[i] < minHeight) { + minHeight = mData[i]; + } + } + mDataBounds.lower = minHeight; + mDataBounds.upper = maxHeight; } - mDataBounds.lower = minHeight; - mDataBounds.upper = maxHeight; - } } /*! Frees the internal data memory. - + This is equivalent to calling \ref setSize "setSize(0, 0)". */ void QCPColorMapData::clear() { - setSize(0, 0); + setSize(0, 0); } /*! @@ -26154,12 +26529,11 @@ void QCPColorMapData::clear() */ void QCPColorMapData::clearAlpha() { - if (mAlpha) - { - delete[] mAlpha; - mAlpha = nullptr; - mDataModified = true; - } + if (mAlpha) { + delete[] mAlpha; + mAlpha = nullptr; + mDataModified = true; + } } /*! @@ -26167,11 +26541,12 @@ void QCPColorMapData::clearAlpha() */ void QCPColorMapData::fill(double z) { - const int dataCount = mValueSize*mKeySize; - for (int i=0; i(data); - return; - } - if (copy) - { - *mMapData = *data; - } else - { - delete mMapData; - mMapData = data; - } - mMapImageInvalidated = true; + if (mMapData == data) { + qDebug() << Q_FUNC_INFO << "The data pointer is already in (and owned by) this plottable" << reinterpret_cast(data); + return; + } + if (copy) { + *mMapData = *data; + } else { + delete mMapData; + mMapData = data; + } + mMapImageInvalidated = true; } /*! Sets the data range of this color map to \a dataRange. The data range defines which data values are mapped to the color gradient. - + To make the data range span the full range of the data set, use \ref rescaleDataRange. - + \see QCPColorScale::setDataRange */ void QCPColorMap::setDataRange(const QCPRange &dataRange) { - if (!QCPRange::validRange(dataRange)) return; - if (mDataRange.lower != dataRange.lower || mDataRange.upper != dataRange.upper) - { - if (mDataScaleType == QCPAxis::stLogarithmic) - mDataRange = dataRange.sanitizedForLogScale(); - else - mDataRange = dataRange.sanitizedForLinScale(); - mMapImageInvalidated = true; - emit dataRangeChanged(mDataRange); - } + if (!QCPRange::validRange(dataRange)) { + return; + } + if (mDataRange.lower != dataRange.lower || mDataRange.upper != dataRange.upper) { + if (mDataScaleType == QCPAxis::stLogarithmic) { + mDataRange = dataRange.sanitizedForLogScale(); + } else { + mDataRange = dataRange.sanitizedForLinScale(); + } + mMapImageInvalidated = true; + emit dataRangeChanged(mDataRange); + } } /*! Sets whether the data is correlated with the color gradient linearly or logarithmically. - + \see QCPColorScale::setDataScaleType */ void QCPColorMap::setDataScaleType(QCPAxis::ScaleType scaleType) { - if (mDataScaleType != scaleType) - { - mDataScaleType = scaleType; - mMapImageInvalidated = true; - emit dataScaleTypeChanged(mDataScaleType); - if (mDataScaleType == QCPAxis::stLogarithmic) - setDataRange(mDataRange.sanitizedForLogScale()); - } + if (mDataScaleType != scaleType) { + mDataScaleType = scaleType; + mMapImageInvalidated = true; + emit dataScaleTypeChanged(mDataScaleType); + if (mDataScaleType == QCPAxis::stLogarithmic) { + setDataRange(mDataRange.sanitizedForLogScale()); + } + } } /*! Sets the color gradient that is used to represent the data. For more details on how to create an own gradient or use one of the preset gradients, see \ref QCPColorGradient. - + The colors defined by the gradient will be used to represent data values in the currently set data range, see \ref setDataRange. Data points that are outside this data range will either be colored uniformly with the respective gradient boundary color, or the gradient will repeat, depending on \ref QCPColorGradient::setPeriodic. - + \see QCPColorScale::setGradient */ void QCPColorMap::setGradient(const QCPColorGradient &gradient) { - if (mGradient != gradient) - { - mGradient = gradient; - mMapImageInvalidated = true; - emit gradientChanged(mGradient); - } + if (mGradient != gradient) { + mGradient = gradient; + mMapImageInvalidated = true; + emit gradientChanged(mGradient); + } } /*! Sets whether the color map image shall use bicubic interpolation when displaying the color map shrinked or expanded, and not at a 1:1 pixel-to-data scale. - + \image html QCPColorMap-interpolate.png "A 10*10 color map, with interpolation and without interpolation enabled" */ void QCPColorMap::setInterpolate(bool enabled) { - mInterpolate = enabled; - mMapImageInvalidated = true; // because oversampling factors might need to change + mInterpolate = enabled; + mMapImageInvalidated = true; // because oversampling factors might need to change } /*! Sets whether the outer most data rows and columns are clipped to the specified key and value range (see \ref QCPColorMapData::setKeyRange, \ref QCPColorMapData::setValueRange). - + if \a enabled is set to false, the data points at the border of the color map are drawn with the same width and height as all other data points. Since the data points are represented by rectangles of one color centered on the data coordinate, this means that the shown color map extends by half a data point over the specified key/value range in each direction. - + \image html QCPColorMap-tightboundary.png "A color map, with tight boundary enabled and disabled" */ void QCPColorMap::setTightBoundary(bool enabled) { - mTightBoundary = enabled; + mTightBoundary = enabled; } /*! Associates the color scale \a colorScale with this color map. - + This means that both the color scale and the color map synchronize their gradient, data range and data scale type (\ref setGradient, \ref setDataRange, \ref setDataScaleType). Multiple color maps can be associated with one single color scale. This causes the color maps to also synchronize those properties, via the mutual color scale. - + This function causes the color map to adopt the current color gradient, data range and data scale type of \a colorScale. After this call, you may change these properties at either the color map or the color scale, and the setting will be applied to both. - + Pass \c nullptr as \a colorScale to disconnect the color scale from this color map again. */ void QCPColorMap::setColorScale(QCPColorScale *colorScale) { - if (mColorScale) // unconnect signals from old color scale - { - disconnect(this, SIGNAL(dataRangeChanged(QCPRange)), mColorScale.data(), SLOT(setDataRange(QCPRange))); - disconnect(this, SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), mColorScale.data(), SLOT(setDataScaleType(QCPAxis::ScaleType))); - disconnect(this, SIGNAL(gradientChanged(QCPColorGradient)), mColorScale.data(), SLOT(setGradient(QCPColorGradient))); - disconnect(mColorScale.data(), SIGNAL(dataRangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange))); - disconnect(mColorScale.data(), SIGNAL(gradientChanged(QCPColorGradient)), this, SLOT(setGradient(QCPColorGradient))); - disconnect(mColorScale.data(), SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType))); - } - mColorScale = colorScale; - if (mColorScale) // connect signals to new color scale - { - setGradient(mColorScale.data()->gradient()); - setDataRange(mColorScale.data()->dataRange()); - setDataScaleType(mColorScale.data()->dataScaleType()); - connect(this, SIGNAL(dataRangeChanged(QCPRange)), mColorScale.data(), SLOT(setDataRange(QCPRange))); - connect(this, SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), mColorScale.data(), SLOT(setDataScaleType(QCPAxis::ScaleType))); - connect(this, SIGNAL(gradientChanged(QCPColorGradient)), mColorScale.data(), SLOT(setGradient(QCPColorGradient))); - connect(mColorScale.data(), SIGNAL(dataRangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange))); - connect(mColorScale.data(), SIGNAL(gradientChanged(QCPColorGradient)), this, SLOT(setGradient(QCPColorGradient))); - connect(mColorScale.data(), SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType))); - } + if (mColorScale) { // unconnect signals from old color scale + disconnect(this, SIGNAL(dataRangeChanged(QCPRange)), mColorScale.data(), SLOT(setDataRange(QCPRange))); + disconnect(this, SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), mColorScale.data(), SLOT(setDataScaleType(QCPAxis::ScaleType))); + disconnect(this, SIGNAL(gradientChanged(QCPColorGradient)), mColorScale.data(), SLOT(setGradient(QCPColorGradient))); + disconnect(mColorScale.data(), SIGNAL(dataRangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange))); + disconnect(mColorScale.data(), SIGNAL(gradientChanged(QCPColorGradient)), this, SLOT(setGradient(QCPColorGradient))); + disconnect(mColorScale.data(), SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType))); + } + mColorScale = colorScale; + if (mColorScale) { // connect signals to new color scale + setGradient(mColorScale.data()->gradient()); + setDataRange(mColorScale.data()->dataRange()); + setDataScaleType(mColorScale.data()->dataScaleType()); + connect(this, SIGNAL(dataRangeChanged(QCPRange)), mColorScale.data(), SLOT(setDataRange(QCPRange))); + connect(this, SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), mColorScale.data(), SLOT(setDataScaleType(QCPAxis::ScaleType))); + connect(this, SIGNAL(gradientChanged(QCPColorGradient)), mColorScale.data(), SLOT(setGradient(QCPColorGradient))); + connect(mColorScale.data(), SIGNAL(dataRangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange))); + connect(mColorScale.data(), SIGNAL(gradientChanged(QCPColorGradient)), this, SLOT(setGradient(QCPColorGradient))); + connect(mColorScale.data(), SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType))); + } } /*! Sets the data range (\ref setDataRange) to span the minimum and maximum values that occur in the current data set. This corresponds to the \ref rescaleKeyAxis or \ref rescaleValueAxis methods, only for the third data dimension of the color map. - + The minimum and maximum values of the data set are buffered in the internal QCPColorMapData instance (\ref data). As data is updated via its \ref QCPColorMapData::setCell or \ref QCPColorMapData::setData, the buffered minimum and maximum values are updated, too. For @@ -26591,128 +26968,128 @@ void QCPColorMap::setColorScale(QCPColorScale *colorScale) QCPColorMapData::recalculateDataBounds can be used. For convenience, setting the parameter \a recalculateDataBounds calls this method before setting the data range to the buffered minimum and maximum. - + \see setDataRange */ void QCPColorMap::rescaleDataRange(bool recalculateDataBounds) { - if (recalculateDataBounds) - mMapData->recalculateDataBounds(); - setDataRange(mMapData->dataBounds()); + if (recalculateDataBounds) { + mMapData->recalculateDataBounds(); + } + setDataRange(mMapData->dataBounds()); } /*! Takes the current appearance of the color map and updates the legend icon, which is used to represent this color map in the legend (see \ref QCPLegend). - + The \a transformMode specifies whether the rescaling is done by a faster, low quality image scaling algorithm (Qt::FastTransformation) or by a slower, higher quality algorithm (Qt::SmoothTransformation). - + The current color map appearance is scaled down to \a thumbSize. Ideally, this should be equal to the size of the legend icon (see \ref QCPLegend::setIconSize). If it isn't exactly the configured legend icon size, the thumb will be rescaled during drawing of the legend item. - + \see setDataRange */ void QCPColorMap::updateLegendIcon(Qt::TransformationMode transformMode, const QSize &thumbSize) { - if (mMapImage.isNull() && !data()->isEmpty()) - updateMapImage(); // try to update map image if it's null (happens if no draw has happened yet) - - if (!mMapImage.isNull()) // might still be null, e.g. if data is empty, so check here again - { - bool mirrorX = (keyAxis()->orientation() == Qt::Horizontal ? keyAxis() : valueAxis())->rangeReversed(); - bool mirrorY = (valueAxis()->orientation() == Qt::Vertical ? valueAxis() : keyAxis())->rangeReversed(); - mLegendIcon = QPixmap::fromImage(mMapImage.mirrored(mirrorX, mirrorY)).scaled(thumbSize, Qt::KeepAspectRatio, transformMode); - } + if (mMapImage.isNull() && !data()->isEmpty()) { + updateMapImage(); // try to update map image if it's null (happens if no draw has happened yet) + } + + if (!mMapImage.isNull()) { // might still be null, e.g. if data is empty, so check here again + bool mirrorX = (keyAxis()->orientation() == Qt::Horizontal ? keyAxis() : valueAxis())->rangeReversed(); + bool mirrorY = (valueAxis()->orientation() == Qt::Vertical ? valueAxis() : keyAxis())->rangeReversed(); + mLegendIcon = QPixmap::fromImage(mMapImage.mirrored(mirrorX, mirrorY)).scaled(thumbSize, Qt::KeepAspectRatio, transformMode); + } } /* inherits documentation from base class */ double QCPColorMap::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { - Q_UNUSED(details) - if ((onlySelectable && mSelectable == QCP::stNone) || mMapData->isEmpty()) - return -1; - if (!mKeyAxis || !mValueAxis) - return -1; - - if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()) || mParentPlot->interactions().testFlag(QCP::iSelectPlottablesBeyondAxisRect)) - { - 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; + Q_UNUSED(details) + if ((onlySelectable && mSelectable == QCP::stNone) || mMapData->isEmpty()) { + return -1; } - } - return -1; + if (!mKeyAxis || !mValueAxis) { + return -1; + } + + if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()) || mParentPlot->interactions().testFlag(QCP::iSelectPlottablesBeyondAxisRect)) { + 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; + 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 {}; + if (inKeyRange != QCPRange()) { + if (mMapData->keyRange().upper < inKeyRange.lower || mMapData->keyRange().lower > inKeyRange.upper) { + foundRange = false; + return {}; + } } - } - - 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; + + 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 turning the data values into color pixels with \ref QCPColorGradient::colorize. - + This method is called by \ref QCPColorMap::draw if either the data has been modified or the map image has been invalidated for a different reason (e.g. a change of the data range with \ref setDataRange). - + If the map cell count is low, the image created will be oversampled in order to avoid a QPainter::drawImage bug which makes inner pixel boundaries jitter when stretch-drawing images without smooth transform enabled. Accordingly, oversampling isn't performed if \ref @@ -26720,168 +27097,174 @@ QCPRange QCPColorMap::getValueRange(bool &foundRange, QCP::SignDomain inSignDoma */ void QCPColorMap::updateMapImage() { - QCPAxis *keyAxis = mKeyAxis.data(); - 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 - int valueOversamplingFactor = mInterpolate ? 1 : int(1.0+100.0/double(valueSize)); // make mMapImage have at least size 100, factor becomes 1 if size > 200 or interpolation is on - - // 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), format); - else if (keyAxis->orientation() == Qt::Vertical && (mMapImage.width() != valueSize*valueOversamplingFactor || mMapImage.height() != keySize*keyOversamplingFactor)) - mMapImage = QImage(QSize(valueSize*valueOversamplingFactor, keySize*keyOversamplingFactor), format); - - if (mMapImage.isNull()) - { - qDebug() << Q_FUNC_INFO << "Couldn't create map image (possibly too large for memory)"; - mMapImage = QImage(QSize(10, 10), format); - mMapImage.fill(Qt::black); - } else - { - 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), format); - else if (keyAxis->orientation() == Qt::Vertical && (mUndersampledMapImage.width() != valueSize || mUndersampledMapImage.height() != keySize)) - 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; - const int rowCount = keySize; - 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) - 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 - { - const int lineCount = keySize; - const int rowCount = valueSize; - 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) - 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); - } + QCPAxis *keyAxis = mKeyAxis.data(); + if (!keyAxis) { + return; } - - if (keyOversamplingFactor > 1 || valueOversamplingFactor > 1) - { - if (keyAxis->orientation() == Qt::Horizontal) - mMapImage = mUndersampledMapImage.scaled(keySize*keyOversamplingFactor, valueSize*valueOversamplingFactor, Qt::IgnoreAspectRatio, Qt::FastTransformation); - else - mMapImage = mUndersampledMapImage.scaled(valueSize*valueOversamplingFactor, keySize*keyOversamplingFactor, Qt::IgnoreAspectRatio, Qt::FastTransformation); + if (mMapData->isEmpty()) { + return; } - } - mMapData->mDataModified = false; - mMapImageInvalidated = false; + + 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 + int valueOversamplingFactor = mInterpolate ? 1 : int(1.0 + 100.0 / double(valueSize)); // make mMapImage have at least size 100, factor becomes 1 if size > 200 or interpolation is on + + // 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), format); + } else if (keyAxis->orientation() == Qt::Vertical && (mMapImage.width() != valueSize * valueOversamplingFactor || mMapImage.height() != keySize * keyOversamplingFactor)) { + mMapImage = QImage(QSize(valueSize * valueOversamplingFactor, keySize * keyOversamplingFactor), format); + } + + if (mMapImage.isNull()) { + qDebug() << Q_FUNC_INFO << "Couldn't create map image (possibly too large for memory)"; + mMapImage = QImage(QSize(10, 10), format); + mMapImage.fill(Qt::black); + } else { + 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), format); + } else if (keyAxis->orientation() == Qt::Vertical && (mUndersampledMapImage.width() != valueSize || mUndersampledMapImage.height() != keySize)) { + 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; + const int rowCount = keySize; + for (int line = 0; line < lineCount; ++line) { + QRgb *pixels = reinterpret_cast(localMapImage->scanLine(lineCount - 1 - line)); // invert scanline index because QImage counts scanlines from top, but our vertical index counts from bottom (mathematical coordinate system) + 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 + const int lineCount = keySize; + const int rowCount = valueSize; + for (int line = 0; line < lineCount; ++line) { + QRgb *pixels = reinterpret_cast(localMapImage->scanLine(lineCount - 1 - line)); // invert scanline index because QImage counts scanlines from top, but our vertical index counts from bottom (mathematical coordinate system) + 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); + } + } + } + + if (keyOversamplingFactor > 1 || valueOversamplingFactor > 1) { + if (keyAxis->orientation() == Qt::Horizontal) { + mMapImage = mUndersampledMapImage.scaled(keySize * keyOversamplingFactor, valueSize * valueOversamplingFactor, Qt::IgnoreAspectRatio, Qt::FastTransformation); + } else { + mMapImage = mUndersampledMapImage.scaled(valueSize * valueOversamplingFactor, keySize * keyOversamplingFactor, Qt::IgnoreAspectRatio, Qt::FastTransformation); + } + } + } + mMapData->mDataModified = false; + mMapImageInvalidated = false; } /* inherits documentation from base class */ void QCPColorMap::draw(QCPPainter *painter) { - if (mMapData->isEmpty()) return; - if (!mKeyAxis || !mValueAxis) return; - applyDefaultAntialiasingHint(painter); - - if (mMapData->mDataModified || mMapImageInvalidated) - updateMapImage(); - - // use buffer if painting vectorized (PDF): - 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; - 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); - localPainter = new QCPPainter(&mapBuffer); - localPainter->scale(mapBufferPixelRatio, mapBufferPixelRatio); - localPainter->translate(-mapBufferTarget.topLeft()); - } - - QRectF imageRect = QRectF(coordsToPixels(mMapData->keyRange().lower, mMapData->valueRange().lower), - coordsToPixels(mMapData->keyRange().upper, mMapData->valueRange().upper)).normalized(); - // extend imageRect to contain outer halves/quarters of bordering/cornering pixels (cells are centered on map range boundary): - double halfCellWidth = 0; // in pixels - double halfCellHeight = 0; // in pixels - if (keyAxis()->orientation() == Qt::Horizontal) - { - if (mMapData->keySize() > 1) - halfCellWidth = 0.5*imageRect.width()/double(mMapData->keySize()-1); - if (mMapData->valueSize() > 1) - halfCellHeight = 0.5*imageRect.height()/double(mMapData->valueSize()-1); - } else // keyAxis orientation is Qt::Vertical - { - if (mMapData->keySize() > 1) - halfCellHeight = 0.5*imageRect.height()/double(mMapData->keySize()-1); - if (mMapData->valueSize() > 1) - halfCellWidth = 0.5*imageRect.width()/double(mMapData->valueSize()-1); - } - imageRect.adjust(-halfCellWidth, -halfCellHeight, halfCellWidth, halfCellHeight); - 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) - { - clipBackup = localPainter->clipRegion(); - QRectF tightClipRect = QRectF(coordsToPixels(mMapData->keyRange().lower, mMapData->valueRange().lower), - coordsToPixels(mMapData->keyRange().upper, mMapData->valueRange().upper)).normalized(); - localPainter->setClipRect(tightClipRect, Qt::IntersectClip); - } - localPainter->drawImage(imageRect, mMapImage.mirrored(mirrorX, mirrorY)); - if (mTightBoundary) - localPainter->setClipRegion(clipBackup); - localPainter->setRenderHint(QPainter::SmoothPixmapTransform, smoothBackup); - - if (useBuffer) // localPainter painted to mapBuffer, so now draw buffer with original painter - { - delete localPainter; - painter->drawPixmap(mapBufferTarget.toRect(), mapBuffer); - } + if (mMapData->isEmpty()) { + return; + } + if (!mKeyAxis || !mValueAxis) { + return; + } + applyDefaultAntialiasingHint(painter); + + if (mMapData->mDataModified || mMapImageInvalidated) { + updateMapImage(); + } + + // use buffer if painting vectorized (PDF): + 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; + 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); + localPainter = new QCPPainter(&mapBuffer); + localPainter->scale(mapBufferPixelRatio, mapBufferPixelRatio); + localPainter->translate(-mapBufferTarget.topLeft()); + } + + QRectF imageRect = QRectF(coordsToPixels(mMapData->keyRange().lower, mMapData->valueRange().lower), + coordsToPixels(mMapData->keyRange().upper, mMapData->valueRange().upper)).normalized(); + // extend imageRect to contain outer halves/quarters of bordering/cornering pixels (cells are centered on map range boundary): + double halfCellWidth = 0; // in pixels + double halfCellHeight = 0; // in pixels + if (keyAxis()->orientation() == Qt::Horizontal) { + if (mMapData->keySize() > 1) { + halfCellWidth = 0.5 * imageRect.width() / double(mMapData->keySize() - 1); + } + if (mMapData->valueSize() > 1) { + halfCellHeight = 0.5 * imageRect.height() / double(mMapData->valueSize() - 1); + } + } else { // keyAxis orientation is Qt::Vertical + if (mMapData->keySize() > 1) { + halfCellHeight = 0.5 * imageRect.height() / double(mMapData->keySize() - 1); + } + if (mMapData->valueSize() > 1) { + halfCellWidth = 0.5 * imageRect.width() / double(mMapData->valueSize() - 1); + } + } + imageRect.adjust(-halfCellWidth, -halfCellHeight, halfCellWidth, halfCellHeight); + 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) { + clipBackup = localPainter->clipRegion(); + QRectF tightClipRect = QRectF(coordsToPixels(mMapData->keyRange().lower, mMapData->valueRange().lower), + coordsToPixels(mMapData->keyRange().upper, mMapData->valueRange().upper)).normalized(); + localPainter->setClipRect(tightClipRect, Qt::IntersectClip); + } + localPainter->drawImage(imageRect, mMapImage.mirrored(mirrorX, mirrorY)); + if (mTightBoundary) { + localPainter->setClipRegion(clipBackup); + } + localPainter->setRenderHint(QPainter::SmoothPixmapTransform, smoothBackup); + + if (useBuffer) { // localPainter painted to mapBuffer, so now draw buffer with original painter + delete localPainter; + painter->drawPixmap(mapBufferTarget.toRect(), mapBuffer); + } } /* inherits documentation from base class */ void QCPColorMap::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const { - applyDefaultAntialiasingHint(painter); - // draw map thumbnail: - if (!mLegendIcon.isNull()) - { - QPixmap scaledIcon = mLegendIcon.scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::FastTransformation); - QRectF iconRect = QRectF(0, 0, scaledIcon.width(), scaledIcon.height()); - iconRect.moveCenter(rect.center()); - painter->drawPixmap(iconRect.topLeft(), scaledIcon); - } - /* - // draw frame: - painter->setBrush(Qt::NoBrush); - painter->setPen(Qt::black); - painter->drawRect(rect.adjusted(1, 1, 0, 0)); - */ + applyDefaultAntialiasingHint(painter); + // draw map thumbnail: + if (!mLegendIcon.isNull()) { + QPixmap scaledIcon = mLegendIcon.scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::FastTransformation); + QRectF iconRect = QRectF(0, 0, scaledIcon.width(), scaledIcon.height()); + iconRect.moveCenter(rect.center()); + painter->drawPixmap(iconRect.topLeft(), scaledIcon); + } + /* + // draw frame: + painter->setBrush(Qt::NoBrush); + painter->setPen(Qt::black); + painter->drawRect(rect.adjusted(1, 1, 0, 0)); + */ } /* end of 'src/plottables/plottable-colormap.cpp' */ @@ -26895,68 +27278,68 @@ void QCPColorMap::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const /*! \class QCPFinancialData \brief Holds the data of one single data point for QCPFinancial. - + 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 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 - + 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. */ @@ -26967,11 +27350,11 @@ void QCPColorMap::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const Constructs a data point with key and all values set to zero. */ QCPFinancialData::QCPFinancialData() : - key(0), - open(0), - high(0), - low(0), - close(0) + key(0), + open(0), + high(0), + low(0), + close(0) { } @@ -26979,11 +27362,11 @@ QCPFinancialData::QCPFinancialData() : Constructs a data point with the specified \a key and OHLC values. */ QCPFinancialData::QCPFinancialData(double key, double open, double high, double low, double close) : - key(key), - open(open), - high(high), - low(low), - close(close) + key(key), + open(open), + high(high), + low(low), + close(close) { } @@ -27044,7 +27427,7 @@ QCPFinancialData::QCPFinancialData(double key, double open, double high, double /* start of documentation of inline functions */ /*! \fn QCPFinancialDataContainer *QCPFinancial::data() const - + 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. @@ -27057,23 +27440,23 @@ QCPFinancialData::QCPFinancialData(double key, double open, double high, double 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 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) : - QCPAbstractPlottable1D(keyAxis, valueAxis), - mChartStyle(csCandlestick), - mWidth(0.5), - 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))) + QCPAbstractPlottable1D(keyAxis, valueAxis), + mChartStyle(csCandlestick), + mWidth(0.5), + 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))) { - mSelectionDecorator->setBrush(QBrush(QColor(160, 160, 255))); + mSelectionDecorator->setBrush(QBrush(QColor(160, 160, 255))); } QCPFinancial::~QCPFinancial() @@ -27081,40 +27464,40 @@ QCPFinancial::~QCPFinancial() } /*! \overload - + Replaces the current data container with the provided \a data container. - + 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(QSharedPointer data) { - mDataContainer = data; + 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); + mDataContainer->clear(); + addData(keys, open, high, low, close, alreadySorted); } /*! @@ -27122,17 +27505,17 @@ void QCPFinancial::setData(const QVector &keys, const QVector &o */ void QCPFinancial::setChartStyle(QCPFinancial::ChartStyle style) { - mChartStyle = style; + mChartStyle = style; } /*! Sets the width of the individual bars/candlesticks to \a width in plot key coordinates. - + A typical choice is to set it to (or slightly less than) one bin interval width. */ void QCPFinancial::setWidth(double width) { - mWidth = width; + mWidth = width; } /*! @@ -27145,128 +27528,128 @@ void QCPFinancial::setWidth(double width) */ void QCPFinancial::setWidthType(QCPFinancial::WidthType widthType) { - mWidthType = 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. - + If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref setBrush). - + \see setPenPositive, setPenNegative, setBrushPositive, setBrushNegative */ void QCPFinancial::setTwoColored(bool twoColored) { - mTwoColored = twoColored; + mTwoColored = twoColored; } /*! If \ref setTwoColored is set to true, this function controls the brush that is used to draw fills of data points with a positive trend (i.e. bars/candlesticks with close >= open). - + If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref setBrush). - + \see setBrushNegative, setPenPositive, setPenNegative */ void QCPFinancial::setBrushPositive(const QBrush &brush) { - mBrushPositive = brush; + mBrushPositive = brush; } /*! If \ref setTwoColored is set to true, this function controls the brush that is used to draw fills of data points with a negative trend (i.e. bars/candlesticks with close < open). - + If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref setBrush). - + \see setBrushPositive, setPenNegative, setPenPositive */ void QCPFinancial::setBrushNegative(const QBrush &brush) { - mBrushNegative = brush; + mBrushNegative = brush; } /*! If \ref setTwoColored is set to true, this function controls the pen that is used to draw outlines of data points with a positive trend (i.e. bars/candlesticks with close >= open). - + If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref setBrush). - + \see setPenNegative, setBrushPositive, setBrushNegative */ void QCPFinancial::setPenPositive(const QPen &pen) { - mPenPositive = pen; + mPenPositive = pen; } /*! If \ref setTwoColored is set to true, this function controls the pen that is used to draw outlines of data points with a negative trend (i.e. bars/candlesticks with close < open). - + If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref setBrush). - + \see setPenPositive, setBrushNegative, setBrushPositive */ void QCPFinancial::setPenNegative(const QPen &pen) { - mPenNegative = pen; + mPenNegative = pen; } /*! \overload - + 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. - + 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 QVector &keys, const QVector &open, const QVector &high, const QVector &low, const QVector &close, bool alreadySorted) { - 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 + 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 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 directly via the \ref data method, which returns a pointer to the internal data container. - + \see timeSeriesToOhlc */ void QCPFinancial::addData(double key, double open, double high, double low, double close) { - mDataContainer->add(QCPFinancialData(key, open, high, low, close)); + mDataContainer->add(QCPFinancialData(key, open, high, low, close)); } /*! @@ -27274,22 +27657,24 @@ void QCPFinancial::addData(double key, double open, double high, double low, dou */ QCPDataSelection QCPFinancial::selectTestRect(const QRectF &rect, bool onlySelectable) const { - QCPDataSelection result; - if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty()) + QCPDataSelection result; + if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty()) { + return result; + } + if (!mKeyAxis || !mValueAxis) { + return result; + } + + QCPFinancialDataContainer::const_iterator visibleBegin, visibleEnd; + getVisibleDataBounds(visibleBegin, visibleEnd); + + for (QCPFinancialDataContainer::const_iterator it = visibleBegin; it != visibleEnd; ++it) { + if (rect.intersects(selectionHitBox(it))) { + result.addDataRange(QCPDataRange(int(it - mDataContainer->constBegin()), int(it - mDataContainer->constBegin() + 1)), false); + } + } + result.simplify(); return result; - if (!mKeyAxis || !mValueAxis) - return result; - - QCPFinancialDataContainer::const_iterator visibleBegin, visibleEnd; - getVisibleDataBounds(visibleBegin, visibleEnd); - - for (QCPFinancialDataContainer::const_iterator it=visibleBegin; it!=visibleEnd; ++it) - { - if (rect.intersects(selectionHitBox(it))) - result.addDataRange(QCPDataRange(int(it-mDataContainer->constBegin()), int(it-mDataContainer->constBegin()+1)), false); - } - result.simplify(); - return result; } /*! @@ -27297,73 +27682,75 @@ QCPDataSelection QCPFinancial::selectTestRect(const QRectF &rect, bool onlySelec If \a details is not 0, it will be set to a \ref QCPDataSelection, describing the closest data point to \a pos. - + \seebaseclassmethod \ref QCPAbstractPlottable::selectTest */ double QCPFinancial::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { - Q_UNUSED(details) - if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty()) - return -1; - if (!mKeyAxis || !mValueAxis) - return -1; - - if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()) || mParentPlot->interactions().testFlag(QCP::iSelectPlottablesBeyondAxisRect)) - { - // get visible data range: - 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: - result = ohlcSelectTest(pos, visibleBegin, visibleEnd, closestDataPoint); break; - case QCPFinancial::csCandlestick: - result = candlestickSelectTest(pos, visibleBegin, visibleEnd, closestDataPoint); break; + Q_UNUSED(details) + if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty()) { + return -1; } - if (details) - { - int pointIndex = int(closestDataPoint-mDataContainer->constBegin()); - details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1))); + if (!mKeyAxis || !mValueAxis) { + return -1; } - return result; - } - - return -1; + + if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()) || mParentPlot->interactions().testFlag(QCP::iSelectPlottablesBeyondAxisRect)) { + // get visible data range: + 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: + result = ohlcSelectTest(pos, visibleBegin, visibleEnd, closestDataPoint); + break; + case QCPFinancial::csCandlestick: + result = candlestickSelectTest(pos, visibleBegin, visibleEnd, closestDataPoint); + break; + } + if (details) { + int pointIndex = int(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; + 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); + 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 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 each, set \a timeBinSize to 3600. - + \a timeBinOffset allows to control precisely at what \a time coordinate a bin should start. The value passed as \a timeBinOffset doesn't need to be in the range encompassed by the \a time keys. It merely defines the mathematical offset/phase of the bins that will be used to process the @@ -27371,263 +27758,254 @@ QCPRange QCPFinancial::getValueRange(bool &foundRange, QCP::SignDomain inSignDom */ QCPFinancialDataContainer QCPFinancial::timeSeriesToOhlc(const QVector &time, const QVector &value, double timeBinSize, double timeBinOffset) { - QCPFinancialDataContainer data; - int count = qMin(time.size(), value.size()); - if (count == 0) - return QCPFinancialDataContainer(); - - QCPFinancialData currentBinData(0, value.first(), value.first(), value.first(), value.first()); - int currentBinIndex = qFloor((time.first()-timeBinOffset)/timeBinSize+0.5); - for (int i=0; i currentBinData.high) currentBinData.high = value.at(i); - if (i == count-1) // last data point is in current bin, finalize bin: - { - currentBinData.close = value.at(i); - currentBinData.key = timeBinOffset+(index)*timeBinSize; - 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; - data.add(currentBinData); - // start next bin: - currentBinIndex = index; - currentBinData.open = value.at(i); - currentBinData.high = value.at(i); - currentBinData.low = value.at(i); + QCPFinancialDataContainer data; + int count = qMin(time.size(), value.size()); + if (count == 0) { + return QCPFinancialDataContainer(); } - } - - return data; + + QCPFinancialData currentBinData(0, value.first(), value.first(), value.first(), value.first()); + int currentBinIndex = qFloor((time.first() - timeBinOffset) / timeBinSize + 0.5); + for (int i = 0; i < count; ++i) { + int index = qFloor((time.at(i) - timeBinOffset) / timeBinSize + 0.5); + if (currentBinIndex == index) { // data point still in current bin, extend high/low: + if (value.at(i) < currentBinData.low) { + currentBinData.low = value.at(i); + } + if (value.at(i) > currentBinData.high) { + currentBinData.high = value.at(i); + } + if (i == count - 1) { // last data point is in current bin, finalize bin: + currentBinData.close = value.at(i); + currentBinData.key = timeBinOffset + (index) * timeBinSize; + 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; + data.add(currentBinData); + // start next bin: + currentBinIndex = index; + currentBinData.open = value.at(i); + currentBinData.high = value.at(i); + currentBinData.low = value.at(i); + } + } + + return data; } /* inherits documentation from base class */ void QCPFinancial::draw(QCPPainter *painter) { - // get visible data range: - QCPFinancialDataContainer::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(); - 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; + // get visible data range: + QCPFinancialDataContainer::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 < allSegments.size(); ++i) { + bool isSelectedSegment = 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()); } - } - - // 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 QCPFinancial::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const { - painter->setAntialiasing(false); // legend icon especially of csCandlestick looks better without antialiasing - if (mChartStyle == csOhlc) - { - if (mTwoColored) - { - // draw upper left half icon with positive color: - painter->setBrush(mBrushPositive); - painter->setPen(mPenPositive); - painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.topLeft().toPoint())); - 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 half icon with negative color: - painter->setBrush(mBrushNegative); - painter->setPen(mPenNegative); - painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.bottomRight().toPoint())); - 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())); - } else - { - painter->setBrush(mBrush); - painter->setPen(mPen); - 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())); + painter->setAntialiasing(false); // legend icon especially of csCandlestick looks better without antialiasing + if (mChartStyle == csOhlc) { + if (mTwoColored) { + // draw upper left half icon with positive color: + painter->setBrush(mBrushPositive); + painter->setPen(mPenPositive); + painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.topLeft().toPoint())); + 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 half icon with negative color: + painter->setBrush(mBrushNegative); + painter->setPen(mPenNegative); + painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.bottomRight().toPoint())); + 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())); + } else { + painter->setBrush(mBrush); + painter->setPen(mPen); + 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())); + } + } else if (mChartStyle == csCandlestick) { + if (mTwoColored) { + // draw upper left half icon with positive color: + painter->setBrush(mBrushPositive); + painter->setPen(mPenPositive); + painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.topLeft().toPoint())); + 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 half icon with negative color: + painter->setBrush(mBrushNegative); + painter->setPen(mPenNegative); + painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.bottomRight().toPoint())); + 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())); + } else { + painter->setBrush(mBrush); + painter->setPen(mPen); + 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())); + } } - } else if (mChartStyle == csCandlestick) - { - if (mTwoColored) - { - // draw upper left half icon with positive color: - painter->setBrush(mBrushPositive); - painter->setPen(mPenPositive); - painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.topLeft().toPoint())); - 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 half icon with negative color: - painter->setBrush(mBrushNegative); - painter->setPen(mPenNegative); - painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.bottomRight().toPoint())); - 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())); - } else - { - painter->setBrush(mBrush); - painter->setPen(mPen); - 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())); - } - } } /*! \internal - + 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 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; } - - if (keyAxis->orientation() == Qt::Horizontal) - { - for (QCPFinancialDataContainer::const_iterator it = begin; it != end; ++it) - { - if (isSelected && mSelectionDecorator) - mSelectionDecorator->applyPen(painter); - else if (mTwoColored) - painter->setPen(it->close >= it->open ? mPenPositive : mPenNegative); - else - 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->high)), QPointF(keyPixel, valueAxis->coordToPixel(it->low))); - // draw open: - 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+pixelWidth, closePixel)); + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + return; } - } else - { - for (QCPFinancialDataContainer::const_iterator it = begin; it != end; ++it) - { - if (isSelected && mSelectionDecorator) - mSelectionDecorator->applyPen(painter); - else if (mTwoColored) - painter->setPen(it->close >= it->open ? mPenPositive : mPenNegative); - else - 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->high), keyPixel), QPointF(valueAxis->coordToPixel(it->low), keyPixel)); - // draw open: - 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+pixelWidth)); + + if (keyAxis->orientation() == Qt::Horizontal) { + for (QCPFinancialDataContainer::const_iterator it = begin; it != end; ++it) { + if (isSelected && mSelectionDecorator) { + mSelectionDecorator->applyPen(painter); + } else if (mTwoColored) { + painter->setPen(it->close >= it->open ? mPenPositive : mPenNegative); + } else { + 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->high)), QPointF(keyPixel, valueAxis->coordToPixel(it->low))); + // draw open: + 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 + pixelWidth, closePixel)); + } + } else { + for (QCPFinancialDataContainer::const_iterator it = begin; it != end; ++it) { + if (isSelected && mSelectionDecorator) { + mSelectionDecorator->applyPen(painter); + } else if (mTwoColored) { + painter->setPen(it->close >= it->open ? mPenPositive : mPenNegative); + } else { + 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->high), keyPixel), QPointF(valueAxis->coordToPixel(it->low), keyPixel)); + // draw open: + 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 + pixelWidth)); + } } - } } /*! \internal - + 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 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; } - - if (keyAxis->orientation() == Qt::Horizontal) - { - for (QCPFinancialDataContainer::const_iterator it = begin; it != end; ++it) - { - if (isSelected && mSelectionDecorator) - { - mSelectionDecorator->applyPen(painter); - mSelectionDecorator->applyBrush(painter); - } else if (mTwoColored) - { - painter->setPen(it->close >= it->open ? mPenPositive : mPenNegative); - painter->setBrush(it->close >= it->open ? mBrushPositive : mBrushNegative); - } else - { - painter->setPen(mPen); - painter->setBrush(mBrush); - } - 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->high)), QPointF(keyPixel, valueAxis->coordToPixel(qMax(it->open, it->close)))); - // draw low: - painter->drawLine(QPointF(keyPixel, valueAxis->coordToPixel(it->low)), QPointF(keyPixel, valueAxis->coordToPixel(qMin(it->open, it->close)))); - // draw open-close box: - double pixelWidth = getPixelWidth(it->key, keyPixel); - painter->drawRect(QRectF(QPointF(keyPixel-pixelWidth, closePixel), QPointF(keyPixel+pixelWidth, openPixel))); + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + return; } - } else // keyAxis->orientation() == Qt::Vertical - { - for (QCPFinancialDataContainer::const_iterator it = begin; it != end; ++it) - { - if (isSelected && mSelectionDecorator) - { - mSelectionDecorator->applyPen(painter); - mSelectionDecorator->applyBrush(painter); - } else if (mTwoColored) - { - painter->setPen(it->close >= it->open ? mPenPositive : mPenNegative); - painter->setBrush(it->close >= it->open ? mBrushPositive : mBrushNegative); - } else - { - painter->setPen(mPen); - painter->setBrush(mBrush); - } - 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->high), keyPixel), QPointF(valueAxis->coordToPixel(qMax(it->open, it->close)), keyPixel)); - // draw low: - painter->drawLine(QPointF(valueAxis->coordToPixel(it->low), keyPixel), QPointF(valueAxis->coordToPixel(qMin(it->open, it->close)), keyPixel)); - // draw open-close box: - double pixelWidth = getPixelWidth(it->key, keyPixel); - painter->drawRect(QRectF(QPointF(closePixel, keyPixel-pixelWidth), QPointF(openPixel, keyPixel+pixelWidth))); + + if (keyAxis->orientation() == Qt::Horizontal) { + for (QCPFinancialDataContainer::const_iterator it = begin; it != end; ++it) { + if (isSelected && mSelectionDecorator) { + mSelectionDecorator->applyPen(painter); + mSelectionDecorator->applyBrush(painter); + } else if (mTwoColored) { + painter->setPen(it->close >= it->open ? mPenPositive : mPenNegative); + painter->setBrush(it->close >= it->open ? mBrushPositive : mBrushNegative); + } else { + painter->setPen(mPen); + painter->setBrush(mBrush); + } + 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->high)), QPointF(keyPixel, valueAxis->coordToPixel(qMax(it->open, it->close)))); + // draw low: + painter->drawLine(QPointF(keyPixel, valueAxis->coordToPixel(it->low)), QPointF(keyPixel, valueAxis->coordToPixel(qMin(it->open, it->close)))); + // draw open-close box: + double pixelWidth = getPixelWidth(it->key, keyPixel); + painter->drawRect(QRectF(QPointF(keyPixel - pixelWidth, closePixel), QPointF(keyPixel + pixelWidth, openPixel))); + } + } else { // keyAxis->orientation() == Qt::Vertical + for (QCPFinancialDataContainer::const_iterator it = begin; it != end; ++it) { + if (isSelected && mSelectionDecorator) { + mSelectionDecorator->applyPen(painter); + mSelectionDecorator->applyBrush(painter); + } else if (mTwoColored) { + painter->setPen(it->close >= it->open ? mPenPositive : mPenNegative); + painter->setBrush(it->close >= it->open ? mBrushPositive : mBrushNegative); + } else { + painter->setPen(mPen); + painter->setBrush(mBrush); + } + 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->high), keyPixel), QPointF(valueAxis->coordToPixel(qMax(it->open, it->close)), keyPixel)); + // draw low: + painter->drawLine(QPointF(valueAxis->coordToPixel(it->low), keyPixel), QPointF(valueAxis->coordToPixel(qMin(it->open, it->close)), keyPixel)); + // draw open-close box: + double pixelWidth = getPixelWidth(it->key, keyPixel); + painter->drawRect(QRectF(QPointF(closePixel, keyPixel - pixelWidth), QPointF(openPixel, keyPixel + pixelWidth))); + } } - } } /*! \internal @@ -27644,185 +28022,173 @@ void QCPFinancial::drawCandlestickPlot(QCPPainter *painter, const QCPFinancialDa */ 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; + 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; + } } - 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; + 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 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; } + 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)(); - if (keyAxis->orientation() == Qt::Horizontal) - { - for (QCPFinancialDataContainer::const_iterator it=begin; it!=end; ++it) - { - double keyPixel = keyAxis->coordToPixel(it->key); - // calculate distance to backbone: - double currentDistSqr = QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(keyPixel, valueAxis->coordToPixel(it->high)), QCPVector2D(keyPixel, valueAxis->coordToPixel(it->low))); - if (currentDistSqr < minDistSqr) - { - minDistSqr = currentDistSqr; - closestDataPoint = it; - } + double minDistSqr = (std::numeric_limits::max)(); + if (keyAxis->orientation() == Qt::Horizontal) { + for (QCPFinancialDataContainer::const_iterator it = begin; it != end; ++it) { + double keyPixel = keyAxis->coordToPixel(it->key); + // calculate distance to backbone: + 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 (QCPFinancialDataContainer::const_iterator it = begin; it != end; ++it) { + double keyPixel = keyAxis->coordToPixel(it->key); + // calculate distance to backbone: + double currentDistSqr = QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(valueAxis->coordToPixel(it->high), keyPixel), QCPVector2D(valueAxis->coordToPixel(it->low), keyPixel)); + if (currentDistSqr < minDistSqr) { + minDistSqr = currentDistSqr; + closestDataPoint = it; + } + } } - } else // keyAxis->orientation() == Qt::Vertical - { - for (QCPFinancialDataContainer::const_iterator it=begin; it!=end; ++it) - { - double keyPixel = keyAxis->coordToPixel(it->key); - // calculate distance to backbone: - 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); + return qSqrt(minDistSqr); } /*! \internal - + 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 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; } + 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)(); - if (keyAxis->orientation() == Qt::Horizontal) - { - for (QCPFinancialDataContainer::const_iterator it=begin; it!=end; ++it) - { - double currentDistSqr; - // determine whether pos is in open-close-box: - 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 - { - currentDistSqr = mParentPlot->selectionTolerance()*0.99 * mParentPlot->selectionTolerance()*0.99; - } else - { - // calculate distance to high/low lines: - 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; - } + double minDistSqr = (std::numeric_limits::max)(); + if (keyAxis->orientation() == Qt::Horizontal) { + for (QCPFinancialDataContainer::const_iterator it = begin; it != end; ++it) { + double currentDistSqr; + // determine whether pos is in open-close-box: + 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 + currentDistSqr = mParentPlot->selectionTolerance() * 0.99 * mParentPlot->selectionTolerance() * 0.99; + } else { + // calculate distance to high/low lines: + 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 (QCPFinancialDataContainer::const_iterator it = begin; it != end; ++it) { + double currentDistSqr; + // determine whether pos is in open-close-box: + 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 + currentDistSqr = mParentPlot->selectionTolerance() * 0.99 * mParentPlot->selectionTolerance() * 0.99; + } else { + // calculate distance to high/low lines: + 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; + } + } } - } else // keyAxis->orientation() == Qt::Vertical - { - for (QCPFinancialDataContainer::const_iterator it=begin; it!=end; ++it) - { - double currentDistSqr; - // determine whether pos is in open-close-box: - 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 - { - currentDistSqr = mParentPlot->selectionTolerance()*0.99 * mParentPlot->selectionTolerance()*0.99; - } else - { - // calculate distance to high/low lines: - 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); + return qSqrt(minDistSqr); } /*! \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 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 begin may still be just outside 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 begin and \a end point to \c constEnd. */ void QCPFinancial::getVisibleDataBounds(QCPFinancialDataContainer::const_iterator &begin, QCPFinancialDataContainer::const_iterator &end) const { - if (!mKeyAxis) - { - 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 + if (!mKeyAxis) { + 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 @@ -27832,18 +28198,22 @@ void QCPFinancial::getVisibleDataBounds(QCPFinancialDataContainer::const_iterato */ 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 {}; } - - 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(); + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + return {}; + } + + 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' */ @@ -27874,8 +28244,8 @@ QRectF QCPFinancial::selectionHitBox(QCPFinancialDataContainer::const_iterator i Constructs an error bar with errors set to zero. */ QCPErrorBarsData::QCPErrorBarsData() : - errorMinus(0), - errorPlus(0) + errorMinus(0), + errorPlus(0) { } @@ -27883,8 +28253,8 @@ QCPErrorBarsData::QCPErrorBarsData() : Constructs an error bar with equal \a error in both negative and positive direction. */ QCPErrorBarsData::QCPErrorBarsData(double error) : - errorMinus(error), - errorPlus(error) + errorMinus(error), + errorPlus(error) { } @@ -27893,8 +28263,8 @@ QCPErrorBarsData::QCPErrorBarsData(double error) : respectively. */ QCPErrorBarsData::QCPErrorBarsData(double errorMinus, double errorPlus) : - errorMinus(errorMinus), - errorPlus(errorPlus) + errorMinus(errorMinus), + errorPlus(errorPlus) { } @@ -27957,14 +28327,14 @@ QCPErrorBarsData::QCPErrorBarsData(double errorMinus, double errorPlus) : 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) + QCPAbstractPlottable(keyAxis, valueAxis), + mDataContainer(new QVector), + mErrorType(etValueError), + mWhiskerWidth(9), + mSymbolGap(10) { - setPen(QPen(Qt::black, 0)); - setBrush(Qt::NoBrush); + setPen(QPen(Qt::black, 0)); + setBrush(Qt::NoBrush); } QCPErrorBars::~QCPErrorBars() @@ -27991,7 +28361,7 @@ QCPErrorBars::~QCPErrorBars() */ void QCPErrorBars::setData(QSharedPointer data) { - mDataContainer = data; + mDataContainer = data; } /*! \overload @@ -28005,8 +28375,8 @@ void QCPErrorBars::setData(QSharedPointer data) */ void QCPErrorBars::setData(const QVector &error) { - mDataContainer->clear(); - addData(error); + mDataContainer->clear(); + addData(error); } /*! \overload @@ -28021,8 +28391,8 @@ void QCPErrorBars::setData(const QVector &error) */ void QCPErrorBars::setData(const QVector &errorMinus, const QVector &errorPlus) { - mDataContainer->clear(); - addData(errorMinus, errorPlus); + mDataContainer->clear(); + addData(errorMinus, errorPlus); } /*! @@ -28041,20 +28411,18 @@ void QCPErrorBars::setData(const QVector &errorMinus, const QVector(plottable)) - { - mDataPlottable = nullptr; - qDebug() << Q_FUNC_INFO << "can't set another QCPErrorBars instance as data plottable"; - return; - } - if (plottable && !plottable->interface1D()) - { - mDataPlottable = nullptr; - qDebug() << Q_FUNC_INFO << "passed plottable doesn't implement 1d interface, can't associate with QCPErrorBars"; - return; - } - - mDataPlottable = plottable; + if (plottable && qobject_cast(plottable)) { + mDataPlottable = nullptr; + qDebug() << Q_FUNC_INFO << "can't set another QCPErrorBars instance as data plottable"; + return; + } + if (plottable && !plottable->interface1D()) { + mDataPlottable = nullptr; + qDebug() << Q_FUNC_INFO << "passed plottable doesn't implement 1d interface, can't associate with QCPErrorBars"; + return; + } + + mDataPlottable = plottable; } /*! @@ -28063,7 +28431,7 @@ void QCPErrorBars::setDataPlottable(QCPAbstractPlottable *plottable) */ void QCPErrorBars::setErrorType(ErrorType type) { - mErrorType = type; + mErrorType = type; } /*! @@ -28072,7 +28440,7 @@ void QCPErrorBars::setErrorType(ErrorType type) */ void QCPErrorBars::setWhiskerWidth(double pixels) { - mWhiskerWidth = pixels; + mWhiskerWidth = pixels; } /*! @@ -28082,7 +28450,7 @@ void QCPErrorBars::setWhiskerWidth(double pixels) */ void QCPErrorBars::setSymbolGap(double pixels) { - mSymbolGap = pixels; + mSymbolGap = pixels; } /*! \overload @@ -28096,7 +28464,7 @@ void QCPErrorBars::setSymbolGap(double pixels) */ void QCPErrorBars::addData(const QVector &error) { - addData(error, error); + addData(error, error); } /*! \overload @@ -28111,12 +28479,14 @@ void QCPErrorBars::addData(const QVector &error) */ 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))); + 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; i < n; ++i) { + mDataContainer->append(QCPErrorBarsData(errorMinus.at(i), errorPlus.at(i))); + } } /*! \overload @@ -28130,7 +28500,7 @@ void QCPErrorBars::addData(const QVector &errorMinus, const QVectorappend(QCPErrorBarsData(error)); + mDataContainer->append(QCPErrorBarsData(error)); } /*! \overload @@ -28145,83 +28515,83 @@ void QCPErrorBars::addData(double error) */ void QCPErrorBars::addData(double errorMinus, double errorPlus) { - mDataContainer->append(QCPErrorBarsData(errorMinus, errorPlus)); + mDataContainer->append(QCPErrorBarsData(errorMinus, errorPlus)); } /* inherits documentation from base class */ int QCPErrorBars::dataCount() const { - return mDataContainer->size(); + 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; + 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; + 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; + 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 {value-mDataContainer->at(index).errorMinus, value+mDataContainer->at(index).errorPlus}; - else - return {value, value}; - } else - { - qDebug() << Q_FUNC_INFO << "no data plottable set"; - return {}; - } + if (mDataPlottable) { + const double value = mDataPlottable->interface1D()->dataMainValue(index); + if (index >= 0 && index < mDataContainer->size() && mErrorType == etValueError) + return {value - mDataContainer->at(index).errorMinus, value + mDataContainer->at(index).errorPlus}; + else + return {value, value}; + } else { + qDebug() << Q_FUNC_INFO << "no data plottable set"; + return {}; + } } /* 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 {}; + if (mDataPlottable) { + return mDataPlottable->interface1D()->dataPixelPosition(index); + } else { + qDebug() << Q_FUNC_INFO << "no data plottable set"; + } + return {}; } /* 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; - } + if (mDataPlottable) { + return mDataPlottable->interface1D()->sortKeyIsMainKey(); + } else { + qDebug() << Q_FUNC_INFO << "no data plottable set"; + return true; + } } /*! @@ -28229,66 +28599,70 @@ bool QCPErrorBars::sortKeyIsMainKey() const */ 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); - foreach (const QLineF &backbone, backbones) - { - if (rectIntersectsLine(rect, backbone)) - { - result.addDataRange(QCPDataRange(int(it-mDataContainer->constBegin()), int(it-mDataContainer->constBegin()+1)), false); - break; - } + QCPDataSelection result; + if (!mDataPlottable) { + return result; } - } - result.simplify(); - 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); + foreach (const QLineF &backbone, backbones) { + if (rectIntersectsLine(rect, backbone)) { + result.addDataRange(QCPDataRange(int(it - mDataContainer->constBegin()), int(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; + 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; + 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; } /*! @@ -28296,271 +28670,261 @@ int QCPErrorBars::findEnd(double sortKey, bool expandedRange) const If \a details is not 0, it will be set to a \ref QCPDataSelection, describing the closest data point to \a pos. - + \seebaseclassmethod \ref QCPAbstractPlottable::selectTest */ 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()) || mParentPlot->interactions().testFlag(QCP::iSelectPlottablesBeyondAxisRect)) - { - QCPErrorBarsDataContainer::const_iterator closestDataPoint = mDataContainer->constEnd(); - double result = pointDistance(pos, closestDataPoint); - if (details) - { - int pointIndex = int(closestDataPoint-mDataContainer->constBegin()); - details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1))); + 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()) || mParentPlot->interactions().testFlag(QCP::iSelectPlottablesBeyondAxisRect)) { + QCPErrorBarsDataContainer::const_iterator closestDataPoint = mDataContainer->constEnd(); + double result = pointDistance(pos, closestDataPoint); + if (details) { + int pointIndex = int(closestDataPoint - mDataContainer->constBegin()); + details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex + 1))); + } + return result; + } else { + return -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(); - + 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(); - } + 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); + + 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 < allSegments.size(); ++i) { + QCPErrorBarsDataContainer::const_iterator begin, end; + getVisibleDataBounds(begin, end, allSegments.at(i)); + if (begin == end) { + continue; + } + + bool isSelectedSegment = 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(int(it - mDataContainer->constBegin()))) { + getErrorBarLines(it, backbones, whiskers); + } + } + painter->drawLines(backbones); + painter->drawLines(whiskers); } - backbones.clear(); - whiskers.clear(); - for (QCPErrorBarsDataContainer::const_iterator it=begin; it!=end; ++it) - { - if (!checkPointVisibility || errorBarVisible(int(it-mDataContainer->constBegin()))) - getErrorBarLines(it, backbones, whiskers); + + // draw other selection decoration that isn't just line/scatter pens and brushes: + if (mSelectionDecorator) { + mSelectionDecorator->drawDecoration(painter, selection()); } - 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)); - } + 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 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(int(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(int(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 (!mDataPlottable) { + foundRange = false; + return {}; } - } - - if (haveUpper && !haveLower) - { - range.lower = range.upper; - haveLower = true; - } else if (haveLower && !haveUpper) - { - range.upper = range.lower; - haveUpper = true; - } - - foundRange = haveLower && haveUpper; - return range; + + 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(int(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(int(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 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, false); - itEnd = mDataContainer->constBegin()+findEnd(inKeyRange.upper, false); - } - for (QCPErrorBarsDataContainer::const_iterator it = itBegin; it != itEnd; ++it) - { - if (restrictKeyRange) - { - const double dataKey = mDataPlottable->interface1D()->dataMainKey(int(it-mDataContainer->constBegin())); - if (dataKey < inKeyRange.lower || dataKey > inKeyRange.upper) - continue; + if (!mDataPlottable) { + foundRange = false; + return {}; } - if (mErrorType == etValueError) - { - const double dataValue = mDataPlottable->interface1D()->dataMainValue(int(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(int(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; - } - } + + 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, false); + itEnd = mDataContainer->constBegin() + findEnd(inKeyRange.upper, false); } - } - - if (haveUpper && !haveLower) - { - range.lower = range.upper; - haveLower = true; - } else if (haveLower && !haveUpper) - { - range.upper = range.lower; - haveUpper = true; - } - - foundRange = haveLower && haveUpper; - return range; + for (QCPErrorBarsDataContainer::const_iterator it = itBegin; it != itEnd; ++it) { + if (restrictKeyRange) { + const double dataKey = mDataPlottable->interface1D()->dataMainKey(int(it - mDataContainer->constBegin())); + if (dataKey < inKeyRange.lower || dataKey > inKeyRange.upper) { + continue; + } + } + if (mErrorType == etValueError) { + const double dataValue = mDataPlottable->interface1D()->dataMainValue(int(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(int(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 @@ -28576,53 +28940,54 @@ QCPRange QCPErrorBars::getValueRange(bool &foundRange, QCP::SignDomain inSignDom */ void QCPErrorBars::getErrorBarLines(QCPErrorBarsDataContainer::const_iterator it, QVector &backbones, QVector &whiskers) const { - if (!mDataPlottable) return; - - int index = int(it-mDataContainer->constBegin()); - QPointF centerPixel = mDataPlottable->interface1D()->dataPixelPosition(index); - if (qIsNaN(centerPixel.x()) || qIsNaN(centerPixel.y())) - return; - QCPAxis *errorAxis = mErrorType == etValueError ? mValueAxis.data() : mKeyAxis.data(); - QCPAxis *orthoAxis = mErrorType == etValueError ? mKeyAxis.data() : mValueAxis.data(); - 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)); + if (!mDataPlottable) { + return; } - } - // 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)); + + int index = int(it - mDataContainer->constBegin()); + QPointF centerPixel = mDataPlottable->interface1D()->dataPixelPosition(index); + if (qIsNaN(centerPixel.x()) || qIsNaN(centerPixel.y())) { + return; + } + QCPAxis *errorAxis = mErrorType == etValueError ? mValueAxis.data() : mKeyAxis.data(); + QCPAxis *orthoAxis = mErrorType == etValueError ? mKeyAxis.data() : mValueAxis.data(); + 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 @@ -28645,55 +29010,52 @@ void QCPErrorBars::getErrorBarLines(QCPErrorBarsDataContainer::const_iterator it */ 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(); + 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 @@ -28704,35 +29066,32 @@ void QCPErrorBars::getVisibleDataBounds(QCPErrorBarsDataContainer::const_iterato */ double QCPErrorBars::pointDistance(const QPointF &pixelPoint, QCPErrorBarsDataContainer::const_iterator &closestData) const { - closestData = mDataContainer->constEnd(); - if (!mDataPlottable || mDataContainer->isEmpty()) - return -1.0; - if (!mKeyAxis || !mValueAxis) - { - qDebug() << Q_FUNC_INFO << "invalid key or value axis"; - 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); - foreach (const QLineF &backbone, backbones) - { - const double currentDistSqr = QCPVector2D(pixelPoint).distanceSquaredToLine(backbone); - if (currentDistSqr < minDistSqr) - { - minDistSqr = currentDistSqr; - closestData = it; - } + closestData = mDataContainer->constEnd(); + if (!mDataPlottable || mDataContainer->isEmpty()) { + return -1.0; } - } - return qSqrt(minDistSqr); + if (!mKeyAxis || !mValueAxis) { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + 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); + foreach (const QLineF &backbone, backbones) { + const double currentDistSqr = QCPVector2D(pixelPoint).distanceSquaredToLine(backbone); + if (currentDistSqr < minDistSqr) { + minDistSqr = currentDistSqr; + closestData = it; + } + } + } + return qSqrt(minDistSqr); } /*! \internal @@ -28744,21 +29103,20 @@ double QCPErrorBars::pointDistance(const QPointF &pixelPoint, QCPErrorBarsDataCo */ void QCPErrorBars::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(); - } + 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 @@ -28772,25 +29130,24 @@ void QCPErrorBars::getDataSegments(QList &selectedSegments, QList< */ 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)); + 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 @@ -28802,16 +29159,17 @@ bool QCPErrorBars::errorBarVisible(int index) const */ 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; + 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' */ @@ -28833,20 +29191,20 @@ bool QCPErrorBars::rectIntersectsLine(const QRectF &pixelRect, const QLineF &lin /*! Creates a straight line item and sets default values. - + 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), - point1(createPosition(QLatin1String("point1"))), - point2(createPosition(QLatin1String("point2"))) + QCPAbstractItem(parentPlot), + point1(createPosition(QLatin1String("point1"))), + point2(createPosition(QLatin1String("point2"))) { - point1->setCoords(0, 0); - point2->setCoords(1, 1); - - setPen(QPen(Qt::black)); - setSelectedPen(QPen(Qt::blue,2)); + point1->setCoords(0, 0); + point2->setCoords(1, 1); + + setPen(QPen(Qt::black)); + setSelectedPen(QPen(Qt::blue, 2)); } QCPItemStraightLine::~QCPItemStraightLine() @@ -28855,134 +29213,133 @@ QCPItemStraightLine::~QCPItemStraightLine() /*! Sets the pen that will be used to draw the line - + \see setSelectedPen */ void QCPItemStraightLine::setPen(const QPen &pen) { - mPen = pen; + mPen = pen; } /*! Sets the pen that will be used to draw the line when selected - + \see setPen, setSelected */ void QCPItemStraightLine::setSelectedPen(const QPen &pen) { - mSelectedPen = pen; + mSelectedPen = pen; } /* inherits documentation from base class */ double QCPItemStraightLine::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { - Q_UNUSED(details) - if (onlySelectable && !mSelectable) - return -1; - - return QCPVector2D(pos).distanceToStraightLine(point1->pixelPosition(), point2->pixelPosition()-point1->pixelPosition()); + Q_UNUSED(details) + if (onlySelectable && !mSelectable) { + return -1; + } + + return QCPVector2D(pos).distanceToStraightLine(point1->pixelPosition(), point2->pixelPosition() - point1->pixelPosition()); } /* inherits documentation from base class */ void QCPItemStraightLine::draw(QCPPainter *painter) { - QCPVector2D start(point1->pixelPosition()); - QCPVector2D end(point2->pixelPosition()); - // get visible segment of straight line inside clipRect: - int clipPad = qCeil(mainPen().widthF()); - QLineF line = getRectClippedStraightLine(start, end-start, clipRect().adjusted(-clipPad, -clipPad, clipPad, clipPad)); - // paint visible segment, if existent: - if (!line.isNull()) - { - painter->setPen(mainPen()); - painter->drawLine(line); - } + QCPVector2D start(point1->pixelPosition()); + QCPVector2D end(point2->pixelPosition()); + // get visible segment of straight line inside clipRect: + int clipPad = qCeil(mainPen().widthF()); + QLineF line = getRectClippedStraightLine(start, end - start, clipRect().adjusted(-clipPad, -clipPad, clipPad, clipPad)); + // paint visible segment, if existent: + if (!line.isNull()) { + painter->setPen(mainPen()); + painter->drawLine(line); + } } /*! \internal Returns the section of the straight line defined by \a base and direction vector \a vec, that is visible in the specified \a rect. - + This is a helper function for \ref draw. */ QLineF QCPItemStraightLine::getRectClippedStraightLine(const QCPVector2D &base, const QCPVector2D &vec, const QRect &rect) const { - double bx, by; - double gamma; - QLineF result; - if (vec.x() == 0 && vec.y() == 0) - return result; - if (qFuzzyIsNull(vec.x())) // line is vertical - { - // 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()) - result.setLine(bx+gamma, rect.top(), bx+gamma, rect.bottom()); // no need to check bottom because we know line is vertical - } else if (qFuzzyIsNull(vec.y())) // line is horizontal - { - // 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()) - 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; - // 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(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(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(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(QCPVector2D(bx, by+gamma)); - - // evaluate points: - if (pointVectors.size() == 2) - { - result.setPoints(pointVectors.at(0).toPointF(), pointVectors.at(1).toPointF()); - } else if (pointVectors.size() > 2) - { - // line probably goes through corner of rect, and we got two points there. single out the point pair with greatest distance: - double distSqrMax = 0; - QCPVector2D pv1, pv2; - for (int i=0; i distSqrMax) - { - pv1 = pointVectors.at(i); - pv2 = pointVectors.at(k); - distSqrMax = distSqr; - } - } - } - result.setPoints(pv1.toPointF(), pv2.toPointF()); + double bx, by; + double gamma; + QLineF result; + if (vec.x() == 0 && vec.y() == 0) { + return result; } - } - return result; + if (qFuzzyIsNull(vec.x())) { // line is vertical + // 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()) { + result.setLine(bx + gamma, rect.top(), bx + gamma, rect.bottom()); // no need to check bottom because we know line is vertical + } + } else if (qFuzzyIsNull(vec.y())) { // line is horizontal + // 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()) { + 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; + // 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(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(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(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(QCPVector2D(bx, by + gamma)); + } + + // evaluate points: + if (pointVectors.size() == 2) { + result.setPoints(pointVectors.at(0).toPointF(), pointVectors.at(1).toPointF()); + } else if (pointVectors.size() > 2) { + // line probably goes through corner of rect, and we got two points there. single out the point pair with greatest distance: + double distSqrMax = 0; + QCPVector2D pv1, pv2; + for (int i = 0; i < pointVectors.size() - 1; ++i) { + for (int k = i + 1; k < pointVectors.size(); ++k) { + double distSqr = (pointVectors.at(i) - pointVectors.at(k)).lengthSquared(); + if (distSqr > distSqrMax) { + pv1 = pointVectors.at(i); + pv2 = pointVectors.at(k); + distSqrMax = distSqr; + } + } + } + result.setPoints(pv1.toPointF(), pv2.toPointF()); + } + } + return result; } /*! \internal @@ -28992,7 +29349,7 @@ QLineF QCPItemStraightLine::getRectClippedStraightLine(const QCPVector2D &base, */ QPen QCPItemStraightLine::mainPen() const { - return mSelected ? mSelectedPen : mPen; + return mSelected ? mSelectedPen : mPen; } /* end of 'src/items/item-straightline.cpp' */ @@ -29010,26 +29367,26 @@ QPen QCPItemStraightLine::mainPen() const \image html QCPItemLine.png "Line example. Blue dotted circles are anchors, solid blue discs are positions." It has two positions, \a start and \a end, which define the end points of the line. - + With \ref setHead and \ref setTail you may set different line ending styles, e.g. to create an arrow. */ /*! Creates a line item and sets default values. - + 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. */ QCPItemLine::QCPItemLine(QCustomPlot *parentPlot) : - QCPAbstractItem(parentPlot), - start(createPosition(QLatin1String("start"))), - end(createPosition(QLatin1String("end"))) + QCPAbstractItem(parentPlot), + start(createPosition(QLatin1String("start"))), + end(createPosition(QLatin1String("end"))) { - start->setCoords(0, 0); - end->setCoords(1, 1); - - setPen(QPen(Qt::black)); - setSelectedPen(QPen(Qt::blue,2)); + start->setCoords(0, 0); + end->setCoords(1, 1); + + setPen(QPen(Qt::black)); + setSelectedPen(QPen(Qt::blue, 2)); } QCPItemLine::~QCPItemLine() @@ -29038,182 +29395,180 @@ QCPItemLine::~QCPItemLine() /*! Sets the pen that will be used to draw the line - + \see setSelectedPen */ void QCPItemLine::setPen(const QPen &pen) { - mPen = pen; + mPen = pen; } /*! Sets the pen that will be used to draw the line when selected - + \see setPen, setSelected */ void QCPItemLine::setSelectedPen(const QPen &pen) { - mSelectedPen = pen; + mSelectedPen = pen; } /*! Sets the line ending style of the head. The head corresponds to the \a end position. - + Note that due to the overloaded QCPLineEnding constructor, you may directly specify a QCPLineEnding::EndingStyle here, e.g. \code setHead(QCPLineEnding::esSpikeArrow) \endcode - + \see setTail */ void QCPItemLine::setHead(const QCPLineEnding &head) { - mHead = head; + mHead = head; } /*! Sets the line ending style of the tail. The tail corresponds to the \a start position. - + Note that due to the overloaded QCPLineEnding constructor, you may directly specify a QCPLineEnding::EndingStyle here, e.g. \code setTail(QCPLineEnding::esSpikeArrow) \endcode - + \see setHead */ void QCPItemLine::setTail(const QCPLineEnding &tail) { - mTail = tail; + mTail = tail; } /* inherits documentation from base class */ double QCPItemLine::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { - Q_UNUSED(details) - if (onlySelectable && !mSelectable) - return -1; - - return qSqrt(QCPVector2D(pos).distanceSquaredToLine(start->pixelPosition(), end->pixelPosition())); + Q_UNUSED(details) + if (onlySelectable && !mSelectable) { + return -1; + } + + return qSqrt(QCPVector2D(pos).distanceSquaredToLine(start->pixelPosition(), end->pixelPosition())); } /* inherits documentation from base class */ void QCPItemLine::draw(QCPPainter *painter) { - QCPVector2D startVec(start->pixelPosition()); - QCPVector2D endVec(end->pixelPosition()); - if (qFuzzyIsNull((startVec-endVec).lengthSquared())) - return; - // get visible segment of straight line inside clipRect: - int clipPad = int(qMax(mHead.boundingDistance(), mTail.boundingDistance())); - clipPad = qMax(clipPad, qCeil(mainPen().widthF())); - QLineF line = getRectClippedLine(startVec, endVec, clipRect().adjusted(-clipPad, -clipPad, clipPad, clipPad)); - // paint visible segment, if existent: - if (!line.isNull()) - { - painter->setPen(mainPen()); - painter->drawLine(line); - painter->setBrush(Qt::SolidPattern); - if (mTail.style() != QCPLineEnding::esNone) - mTail.draw(painter, startVec, startVec-endVec); - if (mHead.style() != QCPLineEnding::esNone) - mHead.draw(painter, endVec, endVec-startVec); - } + QCPVector2D startVec(start->pixelPosition()); + QCPVector2D endVec(end->pixelPosition()); + if (qFuzzyIsNull((startVec - endVec).lengthSquared())) { + return; + } + // get visible segment of straight line inside clipRect: + int clipPad = int(qMax(mHead.boundingDistance(), mTail.boundingDistance())); + clipPad = qMax(clipPad, qCeil(mainPen().widthF())); + QLineF line = getRectClippedLine(startVec, endVec, clipRect().adjusted(-clipPad, -clipPad, clipPad, clipPad)); + // paint visible segment, if existent: + if (!line.isNull()) { + painter->setPen(mainPen()); + painter->drawLine(line); + painter->setBrush(Qt::SolidPattern); + if (mTail.style() != QCPLineEnding::esNone) { + mTail.draw(painter, startVec, startVec - endVec); + } + if (mHead.style() != QCPLineEnding::esNone) { + mHead.draw(painter, endVec, endVec - startVec); + } + } } /*! \internal Returns the section of the line defined by \a start and \a end, that is visible in the specified \a rect. - + This is a helper function for \ref draw. */ QLineF QCPItemLine::getRectClippedLine(const QCPVector2D &start, const QCPVector2D &end, const QRect &rect) const { - bool containsStart = rect.contains(qRound(start.x()), qRound(start.y())); - bool containsEnd = rect.contains(qRound(end.x()), qRound(end.y())); - if (containsStart && containsEnd) - return {start.toPointF(), end.toPointF()}; - - QCPVector2D base = start; - QCPVector2D vec = end-start; - double bx, by; - double gamma, mu; - QLineF result; - QList pointVectors; + bool containsStart = rect.contains(qRound(start.x()), qRound(start.y())); + bool containsEnd = rect.contains(qRound(end.x()), qRound(end.y())); + if (containsStart && containsEnd) + return {start.toPointF(), end.toPointF()}; - if (!qFuzzyIsNull(vec.y())) // line is not horizontal - { - // check top of rect: - bx = rect.left(); - by = rect.top(); - mu = (by-base.y())/vec.y(); - if (mu >= 0 && mu <= 1) - { - gamma = base.x()-bx + mu*vec.x(); - if (gamma >= 0 && gamma <= rect.width()) - pointVectors.append(QCPVector2D(bx+gamma, by)); - } - // check bottom of rect: - bx = rect.left(); - by = rect.bottom(); - mu = (by-base.y())/vec.y(); - if (mu >= 0 && mu <= 1) - { - gamma = base.x()-bx + mu*vec.x(); - if (gamma >= 0 && gamma <= rect.width()) - pointVectors.append(QCPVector2D(bx+gamma, by)); - } - } - if (!qFuzzyIsNull(vec.x())) // line is not vertical - { - // check left of rect: - bx = rect.left(); - by = rect.top(); - mu = (bx-base.x())/vec.x(); - if (mu >= 0 && mu <= 1) - { - gamma = base.y()-by + mu*vec.y(); - if (gamma >= 0 && gamma <= rect.height()) - pointVectors.append(QCPVector2D(bx, by+gamma)); - } - // check right of rect: - bx = rect.right(); - by = rect.top(); - mu = (bx-base.x())/vec.x(); - if (mu >= 0 && mu <= 1) - { - gamma = base.y()-by + mu*vec.y(); - if (gamma >= 0 && gamma <= rect.height()) - pointVectors.append(QCPVector2D(bx, by+gamma)); - } - } - - if (containsStart) - pointVectors.append(start); - if (containsEnd) - pointVectors.append(end); - - // evaluate points: - if (pointVectors.size() == 2) - { - result.setPoints(pointVectors.at(0).toPointF(), pointVectors.at(1).toPointF()); - } else if (pointVectors.size() > 2) - { - // line probably goes through corner of rect, and we got two points there. single out the point pair with greatest distance: - double distSqrMax = 0; - QCPVector2D pv1, pv2; - for (int i=0; i distSqrMax) - { - pv1 = pointVectors.at(i); - pv2 = pointVectors.at(k); - distSqrMax = distSqr; + QCPVector2D base = start; + QCPVector2D vec = end - start; + double bx, by; + double gamma, mu; + QLineF result; + QList pointVectors; + + if (!qFuzzyIsNull(vec.y())) { // line is not horizontal + // check top of rect: + bx = rect.left(); + by = rect.top(); + mu = (by - base.y()) / vec.y(); + if (mu >= 0 && mu <= 1) { + gamma = base.x() - bx + mu * vec.x(); + if (gamma >= 0 && gamma <= rect.width()) { + pointVectors.append(QCPVector2D(bx + gamma, by)); + } + } + // check bottom of rect: + bx = rect.left(); + by = rect.bottom(); + mu = (by - base.y()) / vec.y(); + if (mu >= 0 && mu <= 1) { + gamma = base.x() - bx + mu * vec.x(); + if (gamma >= 0 && gamma <= rect.width()) { + pointVectors.append(QCPVector2D(bx + gamma, by)); + } } - } } - result.setPoints(pv1.toPointF(), pv2.toPointF()); - } - return result; + if (!qFuzzyIsNull(vec.x())) { // line is not vertical + // check left of rect: + bx = rect.left(); + by = rect.top(); + mu = (bx - base.x()) / vec.x(); + if (mu >= 0 && mu <= 1) { + gamma = base.y() - by + mu * vec.y(); + if (gamma >= 0 && gamma <= rect.height()) { + pointVectors.append(QCPVector2D(bx, by + gamma)); + } + } + // check right of rect: + bx = rect.right(); + by = rect.top(); + mu = (bx - base.x()) / vec.x(); + if (mu >= 0 && mu <= 1) { + gamma = base.y() - by + mu * vec.y(); + if (gamma >= 0 && gamma <= rect.height()) { + pointVectors.append(QCPVector2D(bx, by + gamma)); + } + } + } + + if (containsStart) { + pointVectors.append(start); + } + if (containsEnd) { + pointVectors.append(end); + } + + // evaluate points: + if (pointVectors.size() == 2) { + result.setPoints(pointVectors.at(0).toPointF(), pointVectors.at(1).toPointF()); + } else if (pointVectors.size() > 2) { + // line probably goes through corner of rect, and we got two points there. single out the point pair with greatest distance: + double distSqrMax = 0; + QCPVector2D pv1, pv2; + for (int i = 0; i < pointVectors.size() - 1; ++i) { + for (int k = i + 1; k < pointVectors.size(); ++k) { + double distSqr = (pointVectors.at(i) - pointVectors.at(k)).lengthSquared(); + if (distSqr > distSqrMax) { + pv1 = pointVectors.at(i); + pv2 = pointVectors.at(k); + distSqrMax = distSqr; + } + } + } + result.setPoints(pv1.toPointF(), pv2.toPointF()); + } + return result; } /*! \internal @@ -29223,7 +29578,7 @@ QLineF QCPItemLine::getRectClippedLine(const QCPVector2D &start, const QCPVector */ QPen QCPItemLine::mainPen() const { - return mSelected ? mSelectedPen : mPen; + return mSelected ? mSelectedPen : mPen; } /* end of 'src/items/item-line.cpp' */ @@ -29243,10 +29598,10 @@ QPen QCPItemLine::mainPen() const It has four positions, \a start and \a end, which define the end points of the line, and two control points which define the direction the line exits from the start and the direction from which it approaches the end: \a startDir and \a endDir. - + With \ref setHead and \ref setTail you may set different line ending styles, e.g. to create an arrow. - + Often it is desirable for the control points to stay at fixed relative positions to the start/end point. This can be achieved by setting the parent anchor e.g. of \a startDir simply to \a start, and then specify the desired pixel offset with QCPItemPosition::setCoords on \a startDir. @@ -29254,24 +29609,24 @@ QPen QCPItemLine::mainPen() const /*! Creates a curve item and sets default values. - + 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. */ QCPItemCurve::QCPItemCurve(QCustomPlot *parentPlot) : - QCPAbstractItem(parentPlot), - start(createPosition(QLatin1String("start"))), - startDir(createPosition(QLatin1String("startDir"))), - endDir(createPosition(QLatin1String("endDir"))), - end(createPosition(QLatin1String("end"))) + QCPAbstractItem(parentPlot), + start(createPosition(QLatin1String("start"))), + startDir(createPosition(QLatin1String("startDir"))), + endDir(createPosition(QLatin1String("endDir"))), + end(createPosition(QLatin1String("end"))) { - start->setCoords(0, 0); - startDir->setCoords(0.5, 0); - endDir->setCoords(0, 0.5); - end->setCoords(1, 1); - - setPen(QPen(Qt::black)); - setSelectedPen(QPen(Qt::blue,2)); + start->setCoords(0, 0); + startDir->setCoords(0.5, 0); + endDir->setCoords(0, 0.5); + end->setCoords(1, 1); + + setPen(QPen(Qt::black)); + setSelectedPen(QPen(Qt::blue, 2)); } QCPItemCurve::~QCPItemCurve() @@ -29280,109 +29635,114 @@ QCPItemCurve::~QCPItemCurve() /*! Sets the pen that will be used to draw the line - + \see setSelectedPen */ void QCPItemCurve::setPen(const QPen &pen) { - mPen = pen; + mPen = pen; } /*! Sets the pen that will be used to draw the line when selected - + \see setPen, setSelected */ void QCPItemCurve::setSelectedPen(const QPen &pen) { - mSelectedPen = pen; + mSelectedPen = pen; } /*! Sets the line ending style of the head. The head corresponds to the \a end position. - + Note that due to the overloaded QCPLineEnding constructor, you may directly specify a QCPLineEnding::EndingStyle here, e.g. \code setHead(QCPLineEnding::esSpikeArrow) \endcode - + \see setTail */ void QCPItemCurve::setHead(const QCPLineEnding &head) { - mHead = head; + mHead = head; } /*! Sets the line ending style of the tail. The tail corresponds to the \a start position. - + Note that due to the overloaded QCPLineEnding constructor, you may directly specify a QCPLineEnding::EndingStyle here, e.g. \code setTail(QCPLineEnding::esSpikeArrow) \endcode - + \see setHead */ void QCPItemCurve::setTail(const QCPLineEnding &tail) { - mTail = tail; + mTail = tail; } /* inherits documentation from base class */ double QCPItemCurve::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { - Q_UNUSED(details) - if (onlySelectable && !mSelectable) - return -1; - - QPointF startVec(start->pixelPosition()); - QPointF startDirVec(startDir->pixelPosition()); - QPointF endDirVec(endDir->pixelPosition()); - QPointF endVec(end->pixelPosition()); + Q_UNUSED(details) + if (onlySelectable && !mSelectable) { + return -1; + } - QPainterPath cubicPath(startVec); - cubicPath.cubicTo(startDirVec, endDirVec, endVec); - - QList polygons = cubicPath.toSubpathPolygons(); - if (polygons.isEmpty()) - return -1; - const QPolygonF polygon = polygons.first(); - QCPVector2D p(pos); - double minDistSqr = (std::numeric_limits::max)(); - for (int i=1; ipixelPosition()); + QPointF startDirVec(startDir->pixelPosition()); + QPointF endDirVec(endDir->pixelPosition()); + QPointF endVec(end->pixelPosition()); + + QPainterPath cubicPath(startVec); + cubicPath.cubicTo(startDirVec, endDirVec, endVec); + + QList polygons = cubicPath.toSubpathPolygons(); + if (polygons.isEmpty()) { + return -1; + } + const QPolygonF polygon = polygons.first(); + QCPVector2D p(pos); + double minDistSqr = (std::numeric_limits::max)(); + for (int i = 1; i < polygon.size(); ++i) { + double distSqr = p.distanceSquaredToLine(polygon.at(i - 1), polygon.at(i)); + if (distSqr < minDistSqr) { + minDistSqr = distSqr; + } + } + return qSqrt(minDistSqr); } /* inherits documentation from base class */ void QCPItemCurve::draw(QCPPainter *painter) { - 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; + 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.toPointF()); - cubicPath.cubicTo(startDirVec.toPointF(), endDirVec.toPointF(), endVec.toPointF()); + QPainterPath cubicPath(startVec.toPointF()); + cubicPath.cubicTo(startDirVec.toPointF(), endDirVec.toPointF(), endVec.toPointF()); - // paint visible segment, if existent: - const int clipEnlarge = qCeil(mainPen().widthF()); - QRect clip = clipRect().adjusted(-clipEnlarge, -clipEnlarge, clipEnlarge, clipEnlarge); - QRect cubicRect = cubicPath.controlPointRect().toRect(); - if (cubicRect.isEmpty()) // may happen when start and end exactly on same x or y position - cubicRect.adjust(0, 0, 1, 1); - if (clip.intersects(cubicRect)) - { - painter->setPen(mainPen()); - painter->drawPath(cubicPath); - painter->setBrush(Qt::SolidPattern); - if (mTail.style() != QCPLineEnding::esNone) - mTail.draw(painter, startVec, M_PI-cubicPath.angleAtPercent(0)/180.0*M_PI); - if (mHead.style() != QCPLineEnding::esNone) - mHead.draw(painter, endVec, -cubicPath.angleAtPercent(1)/180.0*M_PI); - } + // paint visible segment, if existent: + const int clipEnlarge = qCeil(mainPen().widthF()); + QRect clip = clipRect().adjusted(-clipEnlarge, -clipEnlarge, clipEnlarge, clipEnlarge); + QRect cubicRect = cubicPath.controlPointRect().toRect(); + if (cubicRect.isEmpty()) { // may happen when start and end exactly on same x or y position + cubicRect.adjust(0, 0, 1, 1); + } + if (clip.intersects(cubicRect)) { + painter->setPen(mainPen()); + painter->drawPath(cubicPath); + painter->setBrush(Qt::SolidPattern); + if (mTail.style() != QCPLineEnding::esNone) { + mTail.draw(painter, startVec, M_PI - cubicPath.angleAtPercent(0) / 180.0 * M_PI); + } + if (mHead.style() != QCPLineEnding::esNone) { + mHead.draw(painter, endVec, -cubicPath.angleAtPercent(1) / 180.0 * M_PI); + } + } } /*! \internal @@ -29392,7 +29752,7 @@ void QCPItemCurve::draw(QCPPainter *painter) */ QPen QCPItemCurve::mainPen() const { - return mSelected ? mSelectedPen : mPen; + return mSelected ? mSelectedPen : mPen; } /* end of 'src/items/item-curve.cpp' */ @@ -29414,28 +29774,28 @@ QPen QCPItemCurve::mainPen() const /*! Creates a rectangle item and sets default values. - + 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), - topLeft(createPosition(QLatin1String("topLeft"))), - bottomRight(createPosition(QLatin1String("bottomRight"))), - top(createAnchor(QLatin1String("top"), aiTop)), - topRight(createAnchor(QLatin1String("topRight"), aiTopRight)), - right(createAnchor(QLatin1String("right"), aiRight)), - bottom(createAnchor(QLatin1String("bottom"), aiBottom)), - bottomLeft(createAnchor(QLatin1String("bottomLeft"), aiBottomLeft)), - left(createAnchor(QLatin1String("left"), aiLeft)) + QCPAbstractItem(parentPlot), + topLeft(createPosition(QLatin1String("topLeft"))), + bottomRight(createPosition(QLatin1String("bottomRight"))), + top(createAnchor(QLatin1String("top"), aiTop)), + topRight(createAnchor(QLatin1String("topRight"), aiTopRight)), + right(createAnchor(QLatin1String("right"), aiRight)), + bottom(createAnchor(QLatin1String("bottom"), aiBottom)), + bottomLeft(createAnchor(QLatin1String("bottomLeft"), aiBottomLeft)), + left(createAnchor(QLatin1String("left"), aiLeft)) { - topLeft->setCoords(0, 1); - bottomRight->setCoords(1, 0); - - setPen(QPen(Qt::black)); - setSelectedPen(QPen(Qt::blue,2)); - setBrush(Qt::NoBrush); - setSelectedBrush(Qt::NoBrush); + topLeft->setCoords(0, 1); + bottomRight->setCoords(1, 0); + + setPen(QPen(Qt::black)); + setSelectedPen(QPen(Qt::blue, 2)); + setBrush(Qt::NoBrush); + setSelectedBrush(Qt::NoBrush); } QCPItemRect::~QCPItemRect() @@ -29444,92 +29804,98 @@ QCPItemRect::~QCPItemRect() /*! Sets the pen that will be used to draw the line of the rectangle - + \see setSelectedPen, setBrush */ void QCPItemRect::setPen(const QPen &pen) { - mPen = pen; + mPen = pen; } /*! Sets the pen that will be used to draw the line of the rectangle when selected - + \see setPen, setSelected */ void QCPItemRect::setSelectedPen(const QPen &pen) { - mSelectedPen = pen; + mSelectedPen = pen; } /*! Sets the brush that will be used to fill the rectangle. To disable filling, set \a brush to Qt::NoBrush. - + \see setSelectedBrush, setPen */ void QCPItemRect::setBrush(const QBrush &brush) { - mBrush = brush; + mBrush = brush; } /*! Sets the brush that will be used to fill the rectangle when selected. To disable filling, set \a brush to Qt::NoBrush. - + \see setBrush */ void QCPItemRect::setSelectedBrush(const QBrush &brush) { - mSelectedBrush = brush; + mSelectedBrush = brush; } /* inherits documentation from base class */ double QCPItemRect::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { - Q_UNUSED(details) - if (onlySelectable && !mSelectable) - return -1; - - QRectF rect = QRectF(topLeft->pixelPosition(), bottomRight->pixelPosition()).normalized(); - bool filledRect = mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0; - return rectDistance(rect, pos, filledRect); + Q_UNUSED(details) + if (onlySelectable && !mSelectable) { + return -1; + } + + QRectF rect = QRectF(topLeft->pixelPosition(), bottomRight->pixelPosition()).normalized(); + bool filledRect = mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0; + return rectDistance(rect, pos, filledRect); } /* inherits documentation from base class */ void QCPItemRect::draw(QCPPainter *painter) { - QPointF p1 = topLeft->pixelPosition(); - QPointF p2 = bottomRight->pixelPosition(); - if (p1.toPoint() == p2.toPoint()) - return; - QRectF rect = QRectF(p1, p2).normalized(); - double clipPad = mainPen().widthF(); - QRectF boundingRect = rect.adjusted(-clipPad, -clipPad, clipPad, clipPad); - if (boundingRect.intersects(clipRect())) // only draw if bounding rect of rect item is visible in cliprect - { - painter->setPen(mainPen()); - painter->setBrush(mainBrush()); - painter->drawRect(rect); - } + QPointF p1 = topLeft->pixelPosition(); + QPointF p2 = bottomRight->pixelPosition(); + if (p1.toPoint() == p2.toPoint()) { + return; + } + QRectF rect = QRectF(p1, p2).normalized(); + double clipPad = mainPen().widthF(); + QRectF boundingRect = rect.adjusted(-clipPad, -clipPad, clipPad, clipPad); + if (boundingRect.intersects(clipRect())) { // only draw if bounding rect of rect item is visible in cliprect + painter->setPen(mainPen()); + painter->setBrush(mainBrush()); + painter->drawRect(rect); + } } /* inherits documentation from base class */ QPointF QCPItemRect::anchorPixelPosition(int anchorId) const { - QRectF rect = QRectF(topLeft->pixelPosition(), bottomRight->pixelPosition()); - switch (anchorId) - { - case aiTop: return (rect.topLeft()+rect.topRight())*0.5; - case aiTopRight: return rect.topRight(); - case aiRight: return (rect.topRight()+rect.bottomRight())*0.5; - case aiBottom: return (rect.bottomLeft()+rect.bottomRight())*0.5; - case aiBottomLeft: return rect.bottomLeft(); - case aiLeft: return (rect.topLeft()+rect.bottomLeft())*0.5; - } - - qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId; - return {}; + QRectF rect = QRectF(topLeft->pixelPosition(), bottomRight->pixelPosition()); + switch (anchorId) { + case aiTop: + return (rect.topLeft() + rect.topRight()) * 0.5; + case aiTopRight: + return rect.topRight(); + case aiRight: + return (rect.topRight() + rect.bottomRight()) * 0.5; + case aiBottom: + return (rect.bottomLeft() + rect.bottomRight()) * 0.5; + case aiBottomLeft: + return rect.bottomLeft(); + case aiLeft: + return (rect.topLeft() + rect.bottomLeft()) * 0.5; + } + + qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId; + return {}; } /*! \internal @@ -29539,7 +29905,7 @@ QPointF QCPItemRect::anchorPixelPosition(int anchorId) const */ QPen QCPItemRect::mainPen() const { - return mSelected ? mSelectedPen : mPen; + return mSelected ? mSelectedPen : mPen; } /*! \internal @@ -29549,7 +29915,7 @@ QPen QCPItemRect::mainPen() const */ QBrush QCPItemRect::mainBrush() const { - return mSelected ? mSelectedBrush : mBrush; + return mSelected ? mSelectedBrush : mBrush; } /* end of 'src/items/item-rect.cpp' */ @@ -29568,43 +29934,43 @@ QBrush QCPItemRect::mainBrush() const Its position is defined by the member \a position and the setting of \ref setPositionAlignment. The latter controls which part of the text rect shall be aligned with \a position. - + The text alignment itself (i.e. left, center, right) can be controlled with \ref setTextAlignment. - + The text may be rotated around the \a position point with \ref setRotation. */ /*! Creates a text item and sets default values. - + 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), - position(createPosition(QLatin1String("position"))), - topLeft(createAnchor(QLatin1String("topLeft"), aiTopLeft)), - top(createAnchor(QLatin1String("top"), aiTop)), - topRight(createAnchor(QLatin1String("topRight"), aiTopRight)), - right(createAnchor(QLatin1String("right"), aiRight)), - bottomRight(createAnchor(QLatin1String("bottomRight"), aiBottomRight)), - bottom(createAnchor(QLatin1String("bottom"), aiBottom)), - bottomLeft(createAnchor(QLatin1String("bottomLeft"), aiBottomLeft)), - left(createAnchor(QLatin1String("left"), aiLeft)), - mText(QLatin1String("text")), - mPositionAlignment(Qt::AlignCenter), - mTextAlignment(Qt::AlignTop|Qt::AlignHCenter), - mRotation(0) + QCPAbstractItem(parentPlot), + position(createPosition(QLatin1String("position"))), + topLeft(createAnchor(QLatin1String("topLeft"), aiTopLeft)), + top(createAnchor(QLatin1String("top"), aiTop)), + topRight(createAnchor(QLatin1String("topRight"), aiTopRight)), + right(createAnchor(QLatin1String("right"), aiRight)), + bottomRight(createAnchor(QLatin1String("bottomRight"), aiBottomRight)), + bottom(createAnchor(QLatin1String("bottom"), aiBottom)), + bottomLeft(createAnchor(QLatin1String("bottomLeft"), aiBottomLeft)), + left(createAnchor(QLatin1String("left"), aiLeft)), + mText(QLatin1String("text")), + mPositionAlignment(Qt::AlignCenter), + mTextAlignment(Qt::AlignTop | Qt::AlignHCenter), + mRotation(0) { - position->setCoords(0, 0); - - setPen(Qt::NoPen); - setSelectedPen(Qt::NoPen); - setBrush(Qt::NoBrush); - setSelectedBrush(Qt::NoBrush); - setColor(Qt::black); - setSelectedColor(Qt::blue); + position->setCoords(0, 0); + + setPen(Qt::NoPen); + setSelectedPen(Qt::NoPen); + setBrush(Qt::NoBrush); + setSelectedBrush(Qt::NoBrush); + setColor(Qt::black); + setSelectedColor(Qt::blue); } QCPItemText::~QCPItemText() @@ -29616,7 +29982,7 @@ QCPItemText::~QCPItemText() */ void QCPItemText::setColor(const QColor &color) { - mColor = color; + mColor = color; } /*! @@ -29624,99 +29990,99 @@ void QCPItemText::setColor(const QColor &color) */ void QCPItemText::setSelectedColor(const QColor &color) { - mSelectedColor = color; + mSelectedColor = color; } /*! Sets the pen that will be used do draw a rectangular border around the text. To disable the border, set \a pen to Qt::NoPen. - + \see setSelectedPen, setBrush, setPadding */ void QCPItemText::setPen(const QPen &pen) { - mPen = pen; + mPen = pen; } /*! Sets the pen that will be used do draw a rectangular border around the text, when the item is selected. To disable the border, set \a pen to Qt::NoPen. - + \see setPen */ void QCPItemText::setSelectedPen(const QPen &pen) { - mSelectedPen = pen; + mSelectedPen = pen; } /*! Sets the brush that will be used do fill the background of the text. To disable the background, set \a brush to Qt::NoBrush. - + \see setSelectedBrush, setPen, setPadding */ void QCPItemText::setBrush(const QBrush &brush) { - mBrush = brush; + mBrush = brush; } /*! Sets the brush that will be used do fill the background of the text, when the item is selected. To disable the background, set \a brush to Qt::NoBrush. - + \see setBrush */ void QCPItemText::setSelectedBrush(const QBrush &brush) { - mSelectedBrush = brush; + mSelectedBrush = brush; } /*! Sets the font of the text. - + \see setSelectedFont, setColor */ void QCPItemText::setFont(const QFont &font) { - mFont = font; + mFont = font; } /*! Sets the font of the text that will be used when the item is selected. - + \see setFont */ void QCPItemText::setSelectedFont(const QFont &font) { - mSelectedFont = font; + mSelectedFont = font; } /*! Sets the text that will be displayed. Multi-line texts are supported by inserting a line break character, e.g. '\n'. - + \see setFont, setColor, setTextAlignment */ void QCPItemText::setText(const QString &text) { - mText = text; + mText = text; } /*! Sets which point of the text rect shall be aligned with \a position. - + Examples: \li If \a alignment is Qt::AlignHCenter | Qt::AlignTop, the text will be positioned such that the top of the text rect will be horizontally centered on \a position. \li If \a alignment is Qt::AlignLeft | Qt::AlignBottom, \a position will indicate the bottom left corner of the text rect. - + If you want to control the alignment of (multi-lined) text within the text rect, use \ref setTextAlignment. */ void QCPItemText::setPositionAlignment(Qt::Alignment alignment) { - mPositionAlignment = alignment; + mPositionAlignment = alignment; } /*! @@ -29724,7 +30090,7 @@ void QCPItemText::setPositionAlignment(Qt::Alignment alignment) */ void QCPItemText::setTextAlignment(Qt::Alignment alignment) { - mTextAlignment = alignment; + mTextAlignment = alignment; } /*! @@ -29733,7 +30099,7 @@ void QCPItemText::setTextAlignment(Qt::Alignment alignment) */ void QCPItemText::setRotation(double degrees) { - mRotation = degrees; + mRotation = degrees; } /*! @@ -29742,122 +30108,133 @@ void QCPItemText::setRotation(double degrees) */ void QCPItemText::setPadding(const QMargins &padding) { - mPadding = padding; + mPadding = padding; } /* inherits documentation from base class */ double QCPItemText::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { - Q_UNUSED(details) - if (onlySelectable && !mSelectable) - 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 rectDistance function for non-rotated rects: - QPointF positionPixels(position->pixelPosition()); - QTransform inputTransform; - inputTransform.translate(positionPixels.x(), positionPixels.y()); - inputTransform.rotate(-mRotation); - inputTransform.translate(-positionPixels.x(), -positionPixels.y()); - QPointF rotatedPos = inputTransform.map(pos); - QFontMetrics fontMetrics(mFont); - QRect textRect = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip|mTextAlignment, mText); - QRect textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom()); - QPointF textPos = getTextDrawPoint(positionPixels, textBoxRect, mPositionAlignment); - textBoxRect.moveTopLeft(textPos.toPoint()); + Q_UNUSED(details) + if (onlySelectable && !mSelectable) { + return -1; + } - return rectDistance(textBoxRect, rotatedPos, true); + // The rect may be rotated, so we transform the actual clicked pos to the rotated + // 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); + inputTransform.translate(-positionPixels.x(), -positionPixels.y()); + QPointF rotatedPos = inputTransform.map(pos); + QFontMetrics fontMetrics(mFont); + QRect textRect = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip | mTextAlignment, mText); + QRect textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom()); + QPointF textPos = getTextDrawPoint(positionPixels, textBoxRect, mPositionAlignment); + textBoxRect.moveTopLeft(textPos.toPoint()); + + return rectDistance(textBoxRect, rotatedPos, true); } /* inherits documentation from base class */ void QCPItemText::draw(QCPPainter *painter) { - QPointF pos(position->pixelPosition()); - QTransform transform = painter->transform(); - transform.translate(pos.x(), pos.y()); - if (!qFuzzyIsNull(mRotation)) - transform.rotate(mRotation); - painter->setFont(mainFont()); - QRect textRect = painter->fontMetrics().boundingRect(0, 0, 0, 0, Qt::TextDontClip|mTextAlignment, mText); - QRect textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom()); - QPointF textPos = getTextDrawPoint(QPointF(0, 0), textBoxRect, mPositionAlignment); // 0, 0 because the transform does the translation - textRect.moveTopLeft(textPos.toPoint()+QPoint(mPadding.left(), mPadding.top())); - textBoxRect.moveTopLeft(textPos.toPoint()); - int clipPad = qCeil(mainPen().widthF()); - QRect boundingRect = textBoxRect.adjusted(-clipPad, -clipPad, clipPad, clipPad); - if (transform.mapRect(boundingRect).intersects(painter->transform().mapRect(clipRect()))) - { - painter->setTransform(transform); - if ((mainBrush().style() != Qt::NoBrush && mainBrush().color().alpha() != 0) || - (mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0)) - { - painter->setPen(mainPen()); - painter->setBrush(mainBrush()); - painter->drawRect(textBoxRect); + QPointF pos(position->pixelPosition()); + QTransform transform = painter->transform(); + transform.translate(pos.x(), pos.y()); + if (!qFuzzyIsNull(mRotation)) { + transform.rotate(mRotation); + } + painter->setFont(mainFont()); + QRect textRect = painter->fontMetrics().boundingRect(0, 0, 0, 0, Qt::TextDontClip | mTextAlignment, mText); + QRect textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom()); + QPointF textPos = getTextDrawPoint(QPointF(0, 0), textBoxRect, mPositionAlignment); // 0, 0 because the transform does the translation + textRect.moveTopLeft(textPos.toPoint() + QPoint(mPadding.left(), mPadding.top())); + textBoxRect.moveTopLeft(textPos.toPoint()); + int clipPad = qCeil(mainPen().widthF()); + QRect boundingRect = textBoxRect.adjusted(-clipPad, -clipPad, clipPad, clipPad); + if (transform.mapRect(boundingRect).intersects(painter->transform().mapRect(clipRect()))) { + painter->setTransform(transform); + if ((mainBrush().style() != Qt::NoBrush && mainBrush().color().alpha() != 0) || + (mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0)) { + painter->setPen(mainPen()); + painter->setBrush(mainBrush()); + painter->drawRect(textBoxRect); + } + painter->setBrush(Qt::NoBrush); + painter->setPen(QPen(mainColor())); + painter->drawText(textRect, Qt::TextDontClip | mTextAlignment, mText); } - painter->setBrush(Qt::NoBrush); - painter->setPen(QPen(mainColor())); - painter->drawText(textRect, Qt::TextDontClip|mTextAlignment, mText); - } } /* inherits documentation from base class */ QPointF QCPItemText::anchorPixelPosition(int anchorId) const { - // get actual rect points (pretty much copied from draw function): - QPointF pos(position->pixelPosition()); - QTransform transform; - transform.translate(pos.x(), pos.y()); - if (!qFuzzyIsNull(mRotation)) - transform.rotate(mRotation); - QFontMetrics fontMetrics(mainFont()); - QRect textRect = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip|mTextAlignment, mText); - QRectF textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom()); - QPointF textPos = getTextDrawPoint(QPointF(0, 0), textBoxRect, mPositionAlignment); // 0, 0 because the transform does the translation - textBoxRect.moveTopLeft(textPos.toPoint()); - QPolygonF rectPoly = transform.map(QPolygonF(textBoxRect)); - - switch (anchorId) - { - case aiTopLeft: return rectPoly.at(0); - case aiTop: return (rectPoly.at(0)+rectPoly.at(1))*0.5; - case aiTopRight: return rectPoly.at(1); - case aiRight: return (rectPoly.at(1)+rectPoly.at(2))*0.5; - case aiBottomRight: return rectPoly.at(2); - case aiBottom: return (rectPoly.at(2)+rectPoly.at(3))*0.5; - case aiBottomLeft: return rectPoly.at(3); - case aiLeft: return (rectPoly.at(3)+rectPoly.at(0))*0.5; - } - - qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId; - return {}; + // get actual rect points (pretty much copied from draw function): + QPointF pos(position->pixelPosition()); + QTransform transform; + transform.translate(pos.x(), pos.y()); + if (!qFuzzyIsNull(mRotation)) { + transform.rotate(mRotation); + } + QFontMetrics fontMetrics(mainFont()); + QRect textRect = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip | mTextAlignment, mText); + QRectF textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom()); + QPointF textPos = getTextDrawPoint(QPointF(0, 0), textBoxRect, mPositionAlignment); // 0, 0 because the transform does the translation + textBoxRect.moveTopLeft(textPos.toPoint()); + QPolygonF rectPoly = transform.map(QPolygonF(textBoxRect)); + + switch (anchorId) { + case aiTopLeft: + return rectPoly.at(0); + case aiTop: + return (rectPoly.at(0) + rectPoly.at(1)) * 0.5; + case aiTopRight: + return rectPoly.at(1); + case aiRight: + return (rectPoly.at(1) + rectPoly.at(2)) * 0.5; + case aiBottomRight: + return rectPoly.at(2); + case aiBottom: + return (rectPoly.at(2) + rectPoly.at(3)) * 0.5; + case aiBottomLeft: + return rectPoly.at(3); + case aiLeft: + return (rectPoly.at(3) + rectPoly.at(0)) * 0.5; + } + + qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId; + return {}; } /*! \internal - + Returns the point that must be given to the QPainter::drawText function (which expects the top left point of the text rect), according to the position \a pos, the text bounding box \a rect and the requested \a positionAlignment. - + For example, if \a positionAlignment is Qt::AlignLeft | Qt::AlignBottom the returned point will be shifted upward by the height of \a rect, starting from \a pos. So if the text is finally drawn at that point, the lower left corner of the resulting text rect is at \a pos. */ QPointF QCPItemText::getTextDrawPoint(const QPointF &pos, const QRectF &rect, Qt::Alignment positionAlignment) const { - if (positionAlignment == 0 || positionAlignment == (Qt::AlignLeft|Qt::AlignTop)) - return pos; - - QPointF result = pos; // start at top left - if (positionAlignment.testFlag(Qt::AlignHCenter)) - result.rx() -= rect.width()/2.0; - else if (positionAlignment.testFlag(Qt::AlignRight)) - result.rx() -= rect.width(); - if (positionAlignment.testFlag(Qt::AlignVCenter)) - result.ry() -= rect.height()/2.0; - else if (positionAlignment.testFlag(Qt::AlignBottom)) - result.ry() -= rect.height(); - return result; + if (positionAlignment == 0 || positionAlignment == (Qt::AlignLeft | Qt::AlignTop)) { + return pos; + } + + QPointF result = pos; // start at top left + if (positionAlignment.testFlag(Qt::AlignHCenter)) { + result.rx() -= rect.width() / 2.0; + } else if (positionAlignment.testFlag(Qt::AlignRight)) { + result.rx() -= rect.width(); + } + if (positionAlignment.testFlag(Qt::AlignVCenter)) { + result.ry() -= rect.height() / 2.0; + } else if (positionAlignment.testFlag(Qt::AlignBottom)) { + result.ry() -= rect.height(); + } + return result; } /*! \internal @@ -29867,7 +30244,7 @@ QPointF QCPItemText::getTextDrawPoint(const QPointF &pos, const QRectF &rect, Qt */ QFont QCPItemText::mainFont() const { - return mSelected ? mSelectedFont : mFont; + return mSelected ? mSelectedFont : mFont; } /*! \internal @@ -29877,7 +30254,7 @@ QFont QCPItemText::mainFont() const */ QColor QCPItemText::mainColor() const { - return mSelected ? mSelectedColor : mColor; + return mSelected ? mSelectedColor : mColor; } /*! \internal @@ -29887,7 +30264,7 @@ QColor QCPItemText::mainColor() const */ QPen QCPItemText::mainPen() const { - return mSelected ? mSelectedPen : mPen; + return mSelected ? mSelectedPen : mPen; } /*! \internal @@ -29897,7 +30274,7 @@ QPen QCPItemText::mainPen() const */ QBrush QCPItemText::mainBrush() const { - return mSelected ? mSelectedBrush : mBrush; + return mSelected ? mSelectedBrush : mBrush; } /* end of 'src/items/item-text.cpp' */ @@ -29919,31 +30296,31 @@ QBrush QCPItemText::mainBrush() const /*! Creates an ellipse item and sets default values. - + 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), - topLeft(createPosition(QLatin1String("topLeft"))), - bottomRight(createPosition(QLatin1String("bottomRight"))), - topLeftRim(createAnchor(QLatin1String("topLeftRim"), aiTopLeftRim)), - top(createAnchor(QLatin1String("top"), aiTop)), - topRightRim(createAnchor(QLatin1String("topRightRim"), aiTopRightRim)), - right(createAnchor(QLatin1String("right"), aiRight)), - bottomRightRim(createAnchor(QLatin1String("bottomRightRim"), aiBottomRightRim)), - bottom(createAnchor(QLatin1String("bottom"), aiBottom)), - bottomLeftRim(createAnchor(QLatin1String("bottomLeftRim"), aiBottomLeftRim)), - left(createAnchor(QLatin1String("left"), aiLeft)), - center(createAnchor(QLatin1String("center"), aiCenter)) + QCPAbstractItem(parentPlot), + topLeft(createPosition(QLatin1String("topLeft"))), + bottomRight(createPosition(QLatin1String("bottomRight"))), + topLeftRim(createAnchor(QLatin1String("topLeftRim"), aiTopLeftRim)), + top(createAnchor(QLatin1String("top"), aiTop)), + topRightRim(createAnchor(QLatin1String("topRightRim"), aiTopRightRim)), + right(createAnchor(QLatin1String("right"), aiRight)), + bottomRightRim(createAnchor(QLatin1String("bottomRightRim"), aiBottomRightRim)), + bottom(createAnchor(QLatin1String("bottom"), aiBottom)), + bottomLeftRim(createAnchor(QLatin1String("bottomLeftRim"), aiBottomLeftRim)), + left(createAnchor(QLatin1String("left"), aiLeft)), + center(createAnchor(QLatin1String("center"), aiCenter)) { - topLeft->setCoords(0, 1); - bottomRight->setCoords(1, 0); - - setPen(QPen(Qt::black)); - setSelectedPen(QPen(Qt::blue, 2)); - setBrush(Qt::NoBrush); - setSelectedBrush(Qt::NoBrush); + topLeft->setCoords(0, 1); + bottomRight->setCoords(1, 0); + + setPen(QPen(Qt::black)); + setSelectedPen(QPen(Qt::blue, 2)); + setBrush(Qt::NoBrush); + setSelectedBrush(Qt::NoBrush); } QCPItemEllipse::~QCPItemEllipse() @@ -29952,121 +30329,128 @@ QCPItemEllipse::~QCPItemEllipse() /*! Sets the pen that will be used to draw the line of the ellipse - + \see setSelectedPen, setBrush */ void QCPItemEllipse::setPen(const QPen &pen) { - mPen = pen; + mPen = pen; } /*! Sets the pen that will be used to draw the line of the ellipse when selected - + \see setPen, setSelected */ void QCPItemEllipse::setSelectedPen(const QPen &pen) { - mSelectedPen = pen; + mSelectedPen = pen; } /*! Sets the brush that will be used to fill the ellipse. To disable filling, set \a brush to Qt::NoBrush. - + \see setSelectedBrush, setPen */ void QCPItemEllipse::setBrush(const QBrush &brush) { - mBrush = brush; + mBrush = brush; } /*! Sets the brush that will be used to fill the ellipse when selected. To disable filling, set \a brush to Qt::NoBrush. - + \see setBrush */ void QCPItemEllipse::setSelectedBrush(const QBrush &brush) { - mSelectedBrush = brush; + mSelectedBrush = brush; } /* inherits documentation from base class */ double QCPItemEllipse::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { - Q_UNUSED(details) - if (onlySelectable && !mSelectable) - return -1; - - 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; - double x = pos.x()-center.x(); - double y = pos.y()-center.y(); - - // distance to border: - double c = 1.0/qSqrt(x*x/(a*a)+y*y/(b*b)); - 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) - { - if (x*x/(a*a) + y*y/(b*b) <= 1) - result = mParentPlot->selectionTolerance()*0.99; - } - return result; + Q_UNUSED(details) + if (onlySelectable && !mSelectable) { + return -1; + } + + 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; + double x = pos.x() - center.x(); + double y = pos.y() - center.y(); + + // distance to border: + double c = 1.0 / qSqrt(x * x / (a * a) + y * y / (b * b)); + 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) { + if (x * x / (a * a) + y * y / (b * b) <= 1) { + result = mParentPlot->selectionTolerance() * 0.99; + } + } + return result; } /* inherits documentation from base class */ void QCPItemEllipse::draw(QCPPainter *painter) { - QPointF p1 = topLeft->pixelPosition(); - QPointF p2 = bottomRight->pixelPosition(); - if (p1.toPoint() == p2.toPoint()) - return; - QRectF ellipseRect = QRectF(p1, p2).normalized(); - const int clipEnlarge = qCeil(mainPen().widthF()); - QRect clip = clipRect().adjusted(-clipEnlarge, -clipEnlarge, clipEnlarge, clipEnlarge); - if (ellipseRect.intersects(clip)) // only draw if bounding rect of ellipse is visible in cliprect - { - painter->setPen(mainPen()); - painter->setBrush(mainBrush()); -#ifdef __EXCEPTIONS - try // drawEllipse sometimes throws exceptions if ellipse is too big - { -#endif - painter->drawEllipse(ellipseRect); -#ifdef __EXCEPTIONS - } catch (...) - { - qDebug() << Q_FUNC_INFO << "Item too large for memory, setting invisible"; - setVisible(false); + QPointF p1 = topLeft->pixelPosition(); + QPointF p2 = bottomRight->pixelPosition(); + if (p1.toPoint() == p2.toPoint()) { + return; } + QRectF ellipseRect = QRectF(p1, p2).normalized(); + const int clipEnlarge = qCeil(mainPen().widthF()); + QRect clip = clipRect().adjusted(-clipEnlarge, -clipEnlarge, clipEnlarge, clipEnlarge); + if (ellipseRect.intersects(clip)) { // only draw if bounding rect of ellipse is visible in cliprect + painter->setPen(mainPen()); + painter->setBrush(mainBrush()); +#ifdef __EXCEPTIONS + try { // drawEllipse sometimes throws exceptions if ellipse is too big #endif - } + painter->drawEllipse(ellipseRect); +#ifdef __EXCEPTIONS + } catch (...) { + qDebug() << Q_FUNC_INFO << "Item too large for memory, setting invisible"; + setVisible(false); + } +#endif + } } /* inherits documentation from base class */ QPointF QCPItemEllipse::anchorPixelPosition(int anchorId) const { - QRectF rect = QRectF(topLeft->pixelPosition(), bottomRight->pixelPosition()); - switch (anchorId) - { - case aiTopLeftRim: return rect.center()+(rect.topLeft()-rect.center())*1/qSqrt(2); - case aiTop: return (rect.topLeft()+rect.topRight())*0.5; - case aiTopRightRim: return rect.center()+(rect.topRight()-rect.center())*1/qSqrt(2); - case aiRight: return (rect.topRight()+rect.bottomRight())*0.5; - case aiBottomRightRim: return rect.center()+(rect.bottomRight()-rect.center())*1/qSqrt(2); - case aiBottom: return (rect.bottomLeft()+rect.bottomRight())*0.5; - case aiBottomLeftRim: return rect.center()+(rect.bottomLeft()-rect.center())*1/qSqrt(2); - case aiLeft: return (rect.topLeft()+rect.bottomLeft())*0.5; - case aiCenter: return (rect.topLeft()+rect.bottomRight())*0.5; - } - - qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId; - return {}; + QRectF rect = QRectF(topLeft->pixelPosition(), bottomRight->pixelPosition()); + switch (anchorId) { + case aiTopLeftRim: + return rect.center() + (rect.topLeft() - rect.center()) * 1 / qSqrt(2); + case aiTop: + return (rect.topLeft() + rect.topRight()) * 0.5; + case aiTopRightRim: + return rect.center() + (rect.topRight() - rect.center()) * 1 / qSqrt(2); + case aiRight: + return (rect.topRight() + rect.bottomRight()) * 0.5; + case aiBottomRightRim: + return rect.center() + (rect.bottomRight() - rect.center()) * 1 / qSqrt(2); + case aiBottom: + return (rect.bottomLeft() + rect.bottomRight()) * 0.5; + case aiBottomLeftRim: + return rect.center() + (rect.bottomLeft() - rect.center()) * 1 / qSqrt(2); + case aiLeft: + return (rect.topLeft() + rect.bottomLeft()) * 0.5; + case aiCenter: + return (rect.topLeft() + rect.bottomRight()) * 0.5; + } + + qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId; + return {}; } /*! \internal @@ -30076,7 +30460,7 @@ QPointF QCPItemEllipse::anchorPixelPosition(int anchorId) const */ QPen QCPItemEllipse::mainPen() const { - return mSelected ? mSelectedPen : mPen; + return mSelected ? mSelectedPen : mPen; } /*! \internal @@ -30086,7 +30470,7 @@ QPen QCPItemEllipse::mainPen() const */ QBrush QCPItemEllipse::mainBrush() const { - return mSelected ? mSelectedBrush : mBrush; + return mSelected ? mSelectedBrush : mBrush; } /* end of 'src/items/item-ellipse.cpp' */ @@ -30106,7 +30490,7 @@ QBrush QCPItemEllipse::mainBrush() const It has two positions, \a topLeft and \a bottomRight, which define the rectangle the pixmap will be drawn in. Depending on the scale setting (\ref setScaled), the pixmap will be either scaled to fit the rectangle or be drawn aligned to the topLeft position. - + If scaling is enabled and \a topLeft is further to the bottom/right than \a bottomRight (as shown on the right side of the example image), the pixmap will be flipped in the respective orientations. @@ -30114,30 +30498,30 @@ QBrush QCPItemEllipse::mainBrush() const /*! Creates a rectangle item and sets default values. - + 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), - topLeft(createPosition(QLatin1String("topLeft"))), - bottomRight(createPosition(QLatin1String("bottomRight"))), - top(createAnchor(QLatin1String("top"), aiTop)), - topRight(createAnchor(QLatin1String("topRight"), aiTopRight)), - right(createAnchor(QLatin1String("right"), aiRight)), - bottom(createAnchor(QLatin1String("bottom"), aiBottom)), - bottomLeft(createAnchor(QLatin1String("bottomLeft"), aiBottomLeft)), - left(createAnchor(QLatin1String("left"), aiLeft)), - mScaled(false), - mScaledPixmapInvalidated(true), - mAspectRatioMode(Qt::KeepAspectRatio), - mTransformationMode(Qt::SmoothTransformation) + QCPAbstractItem(parentPlot), + topLeft(createPosition(QLatin1String("topLeft"))), + bottomRight(createPosition(QLatin1String("bottomRight"))), + top(createAnchor(QLatin1String("top"), aiTop)), + topRight(createAnchor(QLatin1String("topRight"), aiTopRight)), + right(createAnchor(QLatin1String("right"), aiRight)), + bottom(createAnchor(QLatin1String("bottom"), aiBottom)), + bottomLeft(createAnchor(QLatin1String("bottomLeft"), aiBottomLeft)), + 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)); + topLeft->setCoords(0, 1); + bottomRight->setCoords(1, 0); + + setPen(Qt::NoPen); + setSelectedPen(QPen(Qt::blue)); } QCPItemPixmap::~QCPItemPixmap() @@ -30149,10 +30533,11 @@ QCPItemPixmap::~QCPItemPixmap() */ void QCPItemPixmap::setPixmap(const QPixmap &pixmap) { - mPixmap = pixmap; - mScaledPixmapInvalidated = true; - if (mPixmap.isNull()) - qDebug() << Q_FUNC_INFO << "pixmap is null"; + mPixmap = pixmap; + mScaledPixmapInvalidated = true; + if (mPixmap.isNull()) { + qDebug() << Q_FUNC_INFO << "pixmap is null"; + } } /*! @@ -30161,192 +30546,198 @@ void QCPItemPixmap::setPixmap(const QPixmap &pixmap) */ void QCPItemPixmap::setScaled(bool scaled, Qt::AspectRatioMode aspectRatioMode, Qt::TransformationMode transformationMode) { - mScaled = scaled; - mAspectRatioMode = aspectRatioMode; - mTransformationMode = transformationMode; - mScaledPixmapInvalidated = true; + mScaled = scaled; + mAspectRatioMode = aspectRatioMode; + mTransformationMode = transformationMode; + mScaledPixmapInvalidated = true; } /*! Sets the pen that will be used to draw a border around the pixmap. - + \see setSelectedPen, setBrush */ void QCPItemPixmap::setPen(const QPen &pen) { - mPen = pen; + mPen = pen; } /*! Sets the pen that will be used to draw a border around the pixmap when selected - + \see setPen, setSelected */ void QCPItemPixmap::setSelectedPen(const QPen &pen) { - mSelectedPen = pen; + mSelectedPen = pen; } /* inherits documentation from base class */ double QCPItemPixmap::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { - Q_UNUSED(details) - if (onlySelectable && !mSelectable) - return -1; - - return rectDistance(getFinalRect(), pos, true); + Q_UNUSED(details) + if (onlySelectable && !mSelectable) { + return -1; + } + + return rectDistance(getFinalRect(), pos, true); } /* inherits documentation from base class */ void QCPItemPixmap::draw(QCPPainter *painter) { - bool flipHorz = false; - bool flipVert = false; - QRect rect = getFinalRect(&flipHorz, &flipVert); - int clipPad = mainPen().style() == Qt::NoPen ? 0 : qCeil(mainPen().widthF()); - QRect boundingRect = rect.adjusted(-clipPad, -clipPad, clipPad, clipPad); - if (boundingRect.intersects(clipRect())) - { - updateScaledPixmap(rect, flipHorz, flipVert); - painter->drawPixmap(rect.topLeft(), mScaled ? mScaledPixmap : mPixmap); - QPen pen = mainPen(); - if (pen.style() != Qt::NoPen) - { - painter->setPen(pen); - painter->setBrush(Qt::NoBrush); - painter->drawRect(rect); + bool flipHorz = false; + bool flipVert = false; + QRect rect = getFinalRect(&flipHorz, &flipVert); + int clipPad = mainPen().style() == Qt::NoPen ? 0 : qCeil(mainPen().widthF()); + QRect boundingRect = rect.adjusted(-clipPad, -clipPad, clipPad, clipPad); + if (boundingRect.intersects(clipRect())) { + updateScaledPixmap(rect, flipHorz, flipVert); + painter->drawPixmap(rect.topLeft(), mScaled ? mScaledPixmap : mPixmap); + QPen pen = mainPen(); + if (pen.style() != Qt::NoPen) { + painter->setPen(pen); + painter->setBrush(Qt::NoBrush); + painter->drawRect(rect); + } } - } } /* inherits documentation from base class */ QPointF QCPItemPixmap::anchorPixelPosition(int anchorId) const { - bool flipHorz = false; - bool flipVert = false; - QRect rect = getFinalRect(&flipHorz, &flipVert); - // we actually want denormal rects (negative width/height) here, so restore - // the flipped state: - if (flipHorz) - rect.adjust(rect.width(), 0, -rect.width(), 0); - if (flipVert) - rect.adjust(0, rect.height(), 0, -rect.height()); - - switch (anchorId) - { - case aiTop: return (rect.topLeft()+rect.topRight())*0.5; - case aiTopRight: return rect.topRight(); - case aiRight: return (rect.topRight()+rect.bottomRight())*0.5; - case aiBottom: return (rect.bottomLeft()+rect.bottomRight())*0.5; - case aiBottomLeft: return rect.bottomLeft(); - case aiLeft: return (rect.topLeft()+rect.bottomLeft())*0.5; - } - - qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId; - return {}; + bool flipHorz = false; + bool flipVert = false; + QRect rect = getFinalRect(&flipHorz, &flipVert); + // we actually want denormal rects (negative width/height) here, so restore + // the flipped state: + if (flipHorz) { + rect.adjust(rect.width(), 0, -rect.width(), 0); + } + if (flipVert) { + rect.adjust(0, rect.height(), 0, -rect.height()); + } + + switch (anchorId) { + case aiTop: + return (rect.topLeft() + rect.topRight()) * 0.5; + case aiTopRight: + return rect.topRight(); + case aiRight: + return (rect.topRight() + rect.bottomRight()) * 0.5; + case aiBottom: + return (rect.bottomLeft() + rect.bottomRight()) * 0.5; + case aiBottomLeft: + return rect.bottomLeft(); + case aiLeft: + return (rect.topLeft() + rect.bottomLeft()) * 0.5; + } + + qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId; + return {}; } /*! \internal - + Creates the buffered scaled image (\a mScaledPixmap) to fit the specified \a finalRect. The parameters \a flipHorz and \a flipVert control whether the resulting image shall be flipped horizontally or vertically. (This is used when \a topLeft is further to the bottom/right than \a bottomRight.) - + This function only creates the scaled pixmap when the buffered pixmap has a different size than the expected result, so calling this function repeatedly, e.g. in the \ref draw function, does not cause expensive rescaling every time. - + If scaling is disabled, sets mScaledPixmap to a null QPixmap. */ void QCPItemPixmap::updateScaledPixmap(QRect finalRect, bool flipHorz, bool flipVert) { - if (mPixmap.isNull()) - return; - - if (mScaled) - { -#ifdef QCP_DEVICEPIXELRATIO_SUPPORTED - double devicePixelRatio = mPixmap.devicePixelRatio(); -#else - double devicePixelRatio = 1.0; -#endif - if (finalRect.isNull()) - finalRect = getFinalRect(&flipHorz, &flipVert); - if (mScaledPixmapInvalidated || finalRect.size() != mScaledPixmap.size()/devicePixelRatio) - { - 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 + if (mPixmap.isNull()) { + return; } - } else if (!mScaledPixmap.isNull()) - mScaledPixmap = QPixmap(); - mScaledPixmapInvalidated = false; + + if (mScaled) { +#ifdef QCP_DEVICEPIXELRATIO_SUPPORTED + double devicePixelRatio = mPixmap.devicePixelRatio(); +#else + double devicePixelRatio = 1.0; +#endif + if (finalRect.isNull()) { + finalRect = getFinalRect(&flipHorz, &flipVert); + } + if (mScaledPixmapInvalidated || finalRect.size() != mScaledPixmap.size() / devicePixelRatio) { + 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 - + Returns the final (tight) rect the pixmap is drawn in, depending on the current item positions and scaling settings. - + The output parameters \a flippedHorz and \a flippedVert return whether the pixmap should be drawn flipped horizontally or vertically in the returned rect. (The returned rect itself is always normalized, i.e. the top left corner of the rect is actually further to the top/left than the bottom right corner). This is the case when the item position \a topLeft is further to the bottom/right than \a bottomRight. - + If scaling is disabled, returns a rect with size of the original pixmap and the top left corner aligned with the item position \a topLeft. The position \a bottomRight is ignored. */ QRect QCPItemPixmap::getFinalRect(bool *flippedHorz, bool *flippedVert) const { - QRect result; - bool flipHorz = false; - bool flipVert = false; - QPoint p1 = topLeft->pixelPosition().toPoint(); - QPoint p2 = bottomRight->pixelPosition().toPoint(); - if (p1 == p2) - return {p1, QSize(0, 0)}; - if (mScaled) - { - QSize newSize = QSize(p2.x()-p1.x(), p2.y()-p1.y()); - QPoint topLeft = p1; - if (newSize.width() < 0) - { - flipHorz = true; - newSize.rwidth() *= -1; - topLeft.setX(p2.x()); - } - if (newSize.height() < 0) - { - flipVert = true; - newSize.rheight() *= -1; - topLeft.setY(p2.y()); - } - QSize scaledSize = mPixmap.size(); + QRect result; + bool flipHorz = false; + bool flipVert = false; + QPoint p1 = topLeft->pixelPosition().toPoint(); + QPoint p2 = bottomRight->pixelPosition().toPoint(); + if (p1 == p2) + return {p1, QSize(0, 0)}; + if (mScaled) { + QSize newSize = QSize(p2.x() - p1.x(), p2.y() - p1.y()); + QPoint topLeft = p1; + if (newSize.width() < 0) { + flipHorz = true; + newSize.rwidth() *= -1; + topLeft.setX(p2.x()); + } + if (newSize.height() < 0) { + flipVert = true; + newSize.rheight() *= -1; + topLeft.setY(p2.y()); + } + QSize scaledSize = mPixmap.size(); #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED - scaledSize /= mPixmap.devicePixelRatio(); - scaledSize.scale(newSize*mPixmap.devicePixelRatio(), mAspectRatioMode); + scaledSize /= mPixmap.devicePixelRatio(); + scaledSize.scale(newSize * mPixmap.devicePixelRatio(), mAspectRatioMode); #else - scaledSize.scale(newSize, mAspectRatioMode); + scaledSize.scale(newSize, mAspectRatioMode); #endif - result = QRect(topLeft, scaledSize); - } else - { + result = QRect(topLeft, scaledSize); + } else { #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED - result = QRect(p1, mPixmap.size()/mPixmap.devicePixelRatio()); + result = QRect(p1, mPixmap.size() / mPixmap.devicePixelRatio()); #else - result = QRect(p1, mPixmap.size()); + result = QRect(p1, mPixmap.size()); #endif - } - if (flippedHorz) - *flippedHorz = flipHorz; - if (flippedVert) - *flippedVert = flipVert; - return result; + } + if (flippedHorz) { + *flippedHorz = flipHorz; + } + if (flippedVert) { + *flippedVert = flipVert; + } + return result; } /*! \internal @@ -30356,7 +30747,7 @@ QRect QCPItemPixmap::getFinalRect(bool *flippedHorz, bool *flippedVert) const */ QPen QCPItemPixmap::mainPen() const { - return mSelected ? mSelectedPen : mPen; + return mSelected ? mSelectedPen : mPen; } /* end of 'src/items/item-pixmap.cpp' */ @@ -30379,19 +30770,19 @@ QPen QCPItemPixmap::mainPen() const QCPGraph is connected, note that setting the coordinates of the tracer item directly via \a position will have no effect because they will be overriden in the next redraw (this is when the coordinate update happens). - + If the specified key in \ref setGraphKey is outside the key bounds of the graph, the tracer will stay at the corresponding end of the graph. - + With \ref setInterpolating you may specify whether the tracer may only stay exactly on data points or whether it interpolates data points linearly, if given a key that lies between two data points of the graph. - + The tracer has different visual styles, see \ref setStyle. It is also possible to make the tracer have no own visual appearance (set the style to \ref tsNone), and just connect other item positions to the tracer \a position (used as an anchor) via \ref 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 position coordinates of the tracer are retrieved, they will not reflect the updated data of the graph. In this case \ref @@ -30400,25 +30791,25 @@ QPen QCPItemPixmap::mainPen() const /*! Creates a tracer item and sets default values. - + 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"))), - mSize(6), - mStyle(tsCrosshair), - mGraph(nullptr), - mGraphKey(0), - mInterpolating(false) + QCPAbstractItem(parentPlot), + position(createPosition(QLatin1String("position"))), + mSize(6), + mStyle(tsCrosshair), + mGraph(nullptr), + mGraphKey(0), + mInterpolating(false) { - position->setCoords(0, 0); + position->setCoords(0, 0); - setBrush(Qt::NoBrush); - setSelectedBrush(Qt::NoBrush); - setPen(QPen(Qt::black)); - setSelectedPen(QPen(Qt::blue, 2)); + setBrush(Qt::NoBrush); + setSelectedBrush(Qt::NoBrush); + setPen(QPen(Qt::black)); + setSelectedPen(QPen(Qt::blue, 2)); } QCPItemTracer::~QCPItemTracer() @@ -30427,42 +30818,42 @@ QCPItemTracer::~QCPItemTracer() /*! Sets the pen that will be used to draw the line of the tracer - + \see setSelectedPen, setBrush */ void QCPItemTracer::setPen(const QPen &pen) { - mPen = pen; + mPen = pen; } /*! Sets the pen that will be used to draw the line of the tracer when selected - + \see setPen, setSelected */ void QCPItemTracer::setSelectedPen(const QPen &pen) { - mSelectedPen = pen; + mSelectedPen = pen; } /*! Sets the brush that will be used to draw any fills of the tracer - + \see setSelectedBrush, setPen */ void QCPItemTracer::setBrush(const QBrush &brush) { - mBrush = brush; + mBrush = brush; } /*! Sets the brush that will be used to draw any fills of the tracer, when selected. - + \see setBrush, setSelected */ void QCPItemTracer::setSelectedBrush(const QBrush &brush) { - mSelectedBrush = brush; + mSelectedBrush = brush; } /*! @@ -30471,242 +30862,232 @@ void QCPItemTracer::setSelectedBrush(const QBrush &brush) */ void QCPItemTracer::setSize(double size) { - mSize = size; + mSize = size; } /*! Sets the style/visual appearance of the tracer. - + If you only want to use the tracer \a position as an anchor for other items, set \a style to \ref tsNone. */ void QCPItemTracer::setStyle(QCPItemTracer::TracerStyle style) { - mStyle = style; + mStyle = style; } /*! Sets the QCPGraph this tracer sticks to. The tracer \a position will be set to type QCPItemPosition::ptPlotCoords and the axes will be set to the axes of \a graph. - + To free the tracer from any graph, set \a graph to \c nullptr. The tracer \a position can then be placed freely like any other item position. This is the state the tracer will assume when its graph gets deleted while still attached to it. - + \see setGraphKey */ void QCPItemTracer::setGraph(QCPGraph *graph) { - if (graph) - { - if (graph->parentPlot() == mParentPlot) - { - position->setType(QCPItemPosition::ptPlotCoords); - position->setAxes(graph->keyAxis(), graph->valueAxis()); - mGraph = graph; - updatePosition(); - } else - qDebug() << Q_FUNC_INFO << "graph isn't in same QCustomPlot instance as this item"; - } else - { - mGraph = nullptr; - } + if (graph) { + if (graph->parentPlot() == mParentPlot) { + position->setType(QCPItemPosition::ptPlotCoords); + position->setAxes(graph->keyAxis(), graph->valueAxis()); + mGraph = graph; + updatePosition(); + } else { + qDebug() << Q_FUNC_INFO << "graph isn't in same QCustomPlot instance as this item"; + } + } else { + mGraph = nullptr; + } } /*! Sets the key of the graph's data point the tracer will be positioned at. This is the only free coordinate of a tracer when attached to a graph. - + Depending on \ref setInterpolating, the tracer will be either positioned on the data point closest to \a key, or will stay exactly at \a key and interpolate the value linearly. - + \see setGraph, setInterpolating */ void QCPItemTracer::setGraphKey(double key) { - mGraphKey = key; + mGraphKey = key; } /*! Sets whether the value of the graph's data points shall be interpolated, when positioning the tracer. - + If \a enabled is set to false and a key is given with \ref setGraphKey, the tracer is placed on the data point of the graph which is closest to the key, but which is not necessarily exactly there. If \a enabled is true, the tracer will be positioned exactly at the specified key, and the appropriate value will be interpolated from the graph's data points linearly. - + \see setGraph, setGraphKey */ void QCPItemTracer::setInterpolating(bool enabled) { - mInterpolating = enabled; + mInterpolating = enabled; } /* inherits documentation from base class */ double QCPItemTracer::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { - Q_UNUSED(details) - if (onlySelectable && !mSelectable) - return -1; + Q_UNUSED(details) + if (onlySelectable && !mSelectable) { + return -1; + } - QPointF center(position->pixelPosition()); - double w = mSize/2.0; - QRect clip = clipRect(); - switch (mStyle) - { - case tsNone: return -1; - case tsPlus: - { - if (clipRect().intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect())) - 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(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 = QCPVector2D(center-pos).length(); - double circleLine = w; - double result = qAbs(centerDist-circleLine); - // filled ellipse, allow click inside to count as hit: - if (result > mParentPlot->selectionTolerance()*0.99 && mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0) - { - if (centerDist <= circleLine) - result = mParentPlot->selectionTolerance()*0.99; + QPointF center(position->pixelPosition()); + double w = mSize / 2.0; + QRect clip = clipRect(); + switch (mStyle) { + case tsNone: + return -1; + case tsPlus: { + if (clipRect().intersects(QRectF(center - QPointF(w, w), center + QPointF(w, w)).toRect())) + 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(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 = QCPVector2D(center - pos).length(); + double circleLine = w; + double result = qAbs(centerDist - circleLine); + // filled ellipse, allow click inside to count as hit: + if (result > mParentPlot->selectionTolerance() * 0.99 && mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0) { + if (centerDist <= circleLine) { + result = mParentPlot->selectionTolerance() * 0.99; + } + } + return result; + } + break; + } + case tsSquare: { + if (clip.intersects(QRectF(center - QPointF(w, w), center + QPointF(w, w)).toRect())) { + QRectF rect = QRectF(center - QPointF(w, w), center + QPointF(w, w)); + bool filledRect = mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0; + return rectDistance(rect, pos, filledRect); + } + break; } - return result; - } - break; } - case tsSquare: - { - if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect())) - { - QRectF rect = QRectF(center-QPointF(w, w), center+QPointF(w, w)); - bool filledRect = mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0; - return rectDistance(rect, pos, filledRect); - } - break; - } - } - return -1; + return -1; } /* inherits documentation from base class */ void QCPItemTracer::draw(QCPPainter *painter) { - updatePosition(); - if (mStyle == tsNone) - return; + updatePosition(); + if (mStyle == tsNone) { + return; + } - painter->setPen(mainPen()); - painter->setBrush(mainBrush()); - QPointF center(position->pixelPosition()); - double w = mSize/2.0; - QRect clip = clipRect(); - switch (mStyle) - { - case tsNone: return; - case tsPlus: - { - if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect())) - { - painter->drawLine(QLineF(center+QPointF(-w, 0), center+QPointF(w, 0))); - painter->drawLine(QLineF(center+QPointF(0, -w), center+QPointF(0, w))); - } - break; + painter->setPen(mainPen()); + painter->setBrush(mainBrush()); + QPointF center(position->pixelPosition()); + double w = mSize / 2.0; + QRect clip = clipRect(); + switch (mStyle) { + case tsNone: + return; + case tsPlus: { + if (clip.intersects(QRectF(center - QPointF(w, w), center + QPointF(w, w)).toRect())) { + painter->drawLine(QLineF(center + QPointF(-w, 0), center + QPointF(w, 0))); + painter->drawLine(QLineF(center + QPointF(0, -w), center + QPointF(0, w))); + } + break; + } + case tsCrosshair: { + if (center.y() > clip.top() && center.y() < clip.bottom()) { + painter->drawLine(QLineF(clip.left(), center.y(), clip.right(), center.y())); + } + if (center.x() > clip.left() && center.x() < clip.right()) { + painter->drawLine(QLineF(center.x(), clip.top(), center.x(), clip.bottom())); + } + break; + } + case tsCircle: { + if (clip.intersects(QRectF(center - QPointF(w, w), center + QPointF(w, w)).toRect())) { + painter->drawEllipse(center, w, w); + } + break; + } + case tsSquare: { + if (clip.intersects(QRectF(center - QPointF(w, w), center + QPointF(w, w)).toRect())) { + painter->drawRect(QRectF(center - QPointF(w, w), center + QPointF(w, w))); + } + break; + } } - case tsCrosshair: - { - if (center.y() > clip.top() && center.y() < clip.bottom()) - painter->drawLine(QLineF(clip.left(), center.y(), clip.right(), center.y())); - if (center.x() > clip.left() && center.x() < clip.right()) - painter->drawLine(QLineF(center.x(), clip.top(), center.x(), clip.bottom())); - break; - } - case tsCircle: - { - if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect())) - painter->drawEllipse(center, w, w); - break; - } - case tsSquare: - { - if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect())) - painter->drawRect(QRectF(center-QPointF(w, w), center+QPointF(w, w))); - break; - } - } } /*! If the tracer is connected with a graph (\ref setGraph), this function updates the tracer's \a position to reside on the graph data, depending on the configured key (\ref setGraphKey). - + It is called automatically on every redraw and normally doesn't need to be called manually. One exception is when you want to read the tracer coordinates via \a position and are not sure that the graph's data (or the tracer key with \ref setGraphKey) hasn't changed since the last redraw. In that situation, call this function before accessing \a position, to make sure you don't get out-of-date coordinates. - + If there is no graph set on this tracer, this function does nothing. */ void QCPItemTracer::updatePosition() { - if (mGraph) - { - if (mParentPlot->hasPlottable(mGraph)) - { - if (mGraph->data()->size() > 1) - { - 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 - { - QCPGraphDataContainer::const_iterator it = mGraph->data()->findBegin(mGraphKey); - if (it != mGraph->data()->constEnd()) // mGraphKey is not exactly on last iterator, but somewhere between iterators - { - 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-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) - position->setCoords(prevIt->key, prevIt->value); - else + if (mGraph) { + if (mParentPlot->hasPlottable(mGraph)) { + if (mGraph->data()->size() > 1) { + 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 { + QCPGraphDataContainer::const_iterator it = mGraph->data()->findBegin(mGraphKey); + if (it != mGraph->data()->constEnd()) { // mGraphKey is not exactly on last iterator, but somewhere between iterators + 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 - 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) { + position->setCoords(prevIt->key, prevIt->value); + } else { + position->setCoords(it->key, it->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) { + QCPGraphDataContainer::const_iterator it = mGraph->data()->constBegin(); position->setCoords(it->key, it->value); + } else { + qDebug() << Q_FUNC_INFO << "graph has no data"; } - } 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 { + qDebug() << Q_FUNC_INFO << "graph not contained in QCustomPlot instance (anymore)"; } - } else if (mGraph->data()->size() == 1) - { - QCPGraphDataContainer::const_iterator it = mGraph->data()->constBegin(); - position->setCoords(it->key, it->value); - } else - qDebug() << Q_FUNC_INFO << "graph has no data"; - } else - qDebug() << Q_FUNC_INFO << "graph not contained in QCustomPlot instance (anymore)"; - } + } } /*! \internal @@ -30716,7 +31097,7 @@ void QCPItemTracer::updatePosition() */ QPen QCPItemTracer::mainPen() const { - return mSelected ? mSelectedPen : mPen; + return mSelected ? mSelectedPen : mPen; } /*! \internal @@ -30726,7 +31107,7 @@ QPen QCPItemTracer::mainPen() const */ QBrush QCPItemTracer::mainBrush() const { - return mSelected ? mSelectedBrush : mBrush; + return mSelected ? mSelectedBrush : mBrush; } /* end of 'src/items/item-tracer.cpp' */ @@ -30746,37 +31127,37 @@ QBrush QCPItemTracer::mainBrush() const It has two positions, \a left and \a right, which define the span of the bracket. If \a left is actually farther to the left than \a right, the bracket is opened to the bottom, as shown in the example image. - + The bracket supports multiple styles via \ref setStyle. The length, i.e. how far the bracket stretches away from the embraced span, can be controlled with \ref setLength. - + \image html QCPItemBracket-length.png
Demonstrating the effect of different values for \ref setLength, for styles \ref bsCalligraphic and \ref bsSquare. Anchors and positions are displayed for reference.
- + It provides an anchor \a center, to allow connection of other items, e.g. an arrow (QCPItemLine or QCPItemCurve) or a text label (QCPItemText), to the bracket. */ /*! Creates a bracket item and sets default values. - + 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)), - mLength(8), - mStyle(bsCalligraphic) + QCPAbstractItem(parentPlot), + left(createPosition(QLatin1String("left"))), + right(createPosition(QLatin1String("right"))), + 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)); + left->setCoords(0, 0); + right->setCoords(1, 1); + + setPen(QPen(Qt::black)); + setSelectedPen(QPen(Qt::blue, 2)); } QCPItemBracket::~QCPItemBracket() @@ -30785,179 +31166,173 @@ QCPItemBracket::~QCPItemBracket() /*! Sets the pen that will be used to draw the bracket. - + Note that when the style is \ref bsCalligraphic, only the color will be taken from the pen, the stroke and width are ignored. To change the apparent stroke width of a calligraphic bracket, use \ref setLength, which has a similar effect. - + \see setSelectedPen */ void QCPItemBracket::setPen(const QPen &pen) { - mPen = pen; + mPen = pen; } /*! Sets the pen that will be used to draw the bracket when selected - + \see setPen, setSelected */ void QCPItemBracket::setSelectedPen(const QPen &pen) { - mSelectedPen = pen; + mSelectedPen = pen; } /*! Sets the \a length in pixels how far the bracket extends in the direction towards the embraced span of the bracket (i.e. perpendicular to the left-right-direction) - + \image html QCPItemBracket-length.png
Demonstrating the effect of different values for \ref setLength, for styles \ref bsCalligraphic and \ref bsSquare. Anchors and positions are displayed for reference.
*/ void QCPItemBracket::setLength(double length) { - mLength = length; + mLength = length; } /*! Sets the style of the bracket, i.e. the shape/visual appearance. - + \see setPen */ void QCPItemBracket::setStyle(QCPItemBracket::BracketStyle style) { - mStyle = style; + mStyle = style; } /* inherits documentation from base class */ double QCPItemBracket::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { - Q_UNUSED(details) - if (onlySelectable && !mSelectable) - return -1; - - QCPVector2D p(pos); - QCPVector2D leftVec(left->pixelPosition()); - QCPVector2D rightVec(right->pixelPosition()); - if (leftVec.toPoint() == rightVec.toPoint()) - return -1; - - 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 = 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)); + Q_UNUSED(details) + if (onlySelectable && !mSelectable) { + return -1; } - case QCPItemBracket::bsCurly: - case QCPItemBracket::bsCalligraphic: - { - 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))); + + QCPVector2D p(pos); + QCPVector2D leftVec(left->pixelPosition()); + QCPVector2D rightVec(right->pixelPosition()); + if (leftVec.toPoint() == rightVec.toPoint()) { + return -1; } - } - return -1; + + 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 = 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 = 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))); + } + } + return -1; } /* inherits documentation from base class */ void QCPItemBracket::draw(QCPPainter *painter) { - QCPVector2D leftVec(left->pixelPosition()); - QCPVector2D rightVec(right->pixelPosition()); - if (leftVec.toPoint() == rightVec.toPoint()) - return; - - 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() - << (rightVec-lengthVec).toPoint() << (leftVec-lengthVec).toPoint(); - const int clipEnlarge = qCeil(mainPen().widthF()); - QRect clip = clipRect().adjusted(-clipEnlarge, -clipEnlarge, clipEnlarge, clipEnlarge); - if (clip.intersects(boundingPoly.boundingRect())) - { - painter->setPen(mainPen()); - switch (mStyle) - { - case bsSquare: - { - painter->drawLine((centerVec+widthVec).toPointF(), (centerVec-widthVec).toPointF()); - painter->drawLine((centerVec+widthVec).toPointF(), (centerVec+widthVec+lengthVec).toPointF()); - painter->drawLine((centerVec-widthVec).toPointF(), (centerVec-widthVec+lengthVec).toPointF()); - break; - } - case bsRound: - { - painter->setBrush(Qt::NoBrush); - QPainterPath path; - path.moveTo((centerVec+widthVec+lengthVec).toPointF()); - path.cubicTo((centerVec+widthVec).toPointF(), (centerVec+widthVec).toPointF(), centerVec.toPointF()); - path.cubicTo((centerVec-widthVec).toPointF(), (centerVec-widthVec).toPointF(), (centerVec-widthVec+lengthVec).toPointF()); - painter->drawPath(path); - break; - } - case bsCurly: - { - painter->setBrush(Qt::NoBrush); - QPainterPath path; - path.moveTo((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; - } - case bsCalligraphic: - { - painter->setPen(Qt::NoPen); - painter->setBrush(QBrush(mainPen().color())); - QPainterPath path; - path.moveTo((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.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; - } + QCPVector2D leftVec(left->pixelPosition()); + QCPVector2D rightVec(right->pixelPosition()); + if (leftVec.toPoint() == rightVec.toPoint()) { + return; + } + + 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() + << (rightVec - lengthVec).toPoint() << (leftVec - lengthVec).toPoint(); + const int clipEnlarge = qCeil(mainPen().widthF()); + QRect clip = clipRect().adjusted(-clipEnlarge, -clipEnlarge, clipEnlarge, clipEnlarge); + if (clip.intersects(boundingPoly.boundingRect())) { + painter->setPen(mainPen()); + switch (mStyle) { + case bsSquare: { + painter->drawLine((centerVec + widthVec).toPointF(), (centerVec - widthVec).toPointF()); + painter->drawLine((centerVec + widthVec).toPointF(), (centerVec + widthVec + lengthVec).toPointF()); + painter->drawLine((centerVec - widthVec).toPointF(), (centerVec - widthVec + lengthVec).toPointF()); + break; + } + case bsRound: { + painter->setBrush(Qt::NoBrush); + QPainterPath path; + path.moveTo((centerVec + widthVec + lengthVec).toPointF()); + path.cubicTo((centerVec + widthVec).toPointF(), (centerVec + widthVec).toPointF(), centerVec.toPointF()); + path.cubicTo((centerVec - widthVec).toPointF(), (centerVec - widthVec).toPointF(), (centerVec - widthVec + lengthVec).toPointF()); + painter->drawPath(path); + break; + } + case bsCurly: { + painter->setBrush(Qt::NoBrush); + QPainterPath path; + path.moveTo((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; + } + case bsCalligraphic: { + painter->setPen(Qt::NoPen); + painter->setBrush(QBrush(mainPen().color())); + QPainterPath path; + path.moveTo((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.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; + } + } } - } } /* inherits documentation from base class */ QPointF QCPItemBracket::anchorPixelPosition(int anchorId) const { - QCPVector2D leftVec(left->pixelPosition()); - QCPVector2D rightVec(right->pixelPosition()); - if (leftVec.toPoint() == rightVec.toPoint()) - return leftVec.toPointF(); - - QCPVector2D widthVec = (rightVec-leftVec)*0.5; - QCPVector2D lengthVec = widthVec.perpendicular().normalized()*mLength; - QCPVector2D centerVec = (rightVec+leftVec)*0.5-lengthVec; - - switch (anchorId) - { - case aiCenter: - return centerVec.toPointF(); - } - qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId; - return {}; + QCPVector2D leftVec(left->pixelPosition()); + QCPVector2D rightVec(right->pixelPosition()); + if (leftVec.toPoint() == rightVec.toPoint()) { + return leftVec.toPointF(); + } + + QCPVector2D widthVec = (rightVec - leftVec) * 0.5; + QCPVector2D lengthVec = widthVec.perpendicular().normalized() * mLength; + QCPVector2D centerVec = (rightVec + leftVec) * 0.5 - lengthVec; + + switch (anchorId) { + case aiCenter: + return centerVec.toPointF(); + } + qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId; + return {}; } /*! \internal @@ -30983,10 +31358,10 @@ QPen QCPItemBracket::mainPen() const /*! \class QCPPolarAxisRadial \brief The radial axis inside a radial plot - + \warning In this QCustomPlot version, polar plots are a tech preview. Expect documentation and functionality to be incomplete, as well as changing public interfaces in the future. - + 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 @@ -31019,7 +31394,7 @@ QPen QCPItemBracket::mainPen() const This signal is emitted when the range of this axis has changed. You can connect it to the \ref setRange slot of another axis to communicate the new range to the other axis, in order for it to be synchronized. - + 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 (see \ref QCPRange::bounded). For example, the following @@ -31031,24 +31406,24 @@ QPen QCPItemBracket::mainPen() const /*! \fn void QCPPolarAxisRadial::rangeChanged(const QCPRange &newRange, const QCPRange &oldRange) \overload - + Additionally to the new range, this signal also provides the previous range held by the axis as \a oldRange. */ /*! \fn void QCPPolarAxisRadial::scaleTypeChanged(QCPPolarAxisRadial::ScaleType scaleType); - + This signal is emitted when the scale type changes, by calls to \ref setScaleType */ /*! \fn void QCPPolarAxisRadial::selectionChanged(QCPPolarAxisRadial::SelectableParts selection) - + This signal is emitted when the selection state of this axis has changed, either by user interaction or by a direct call to \ref setSelectedParts. */ /*! \fn void QCPPolarAxisRadial::selectableChanged(const QCPPolarAxisRadial::SelectableParts &parts); - + This signal is emitted when the selectability changes, by calls to \ref setSelectableParts */ @@ -31056,71 +31431,71 @@ QPen QCPItemBracket::mainPen() const /*! Constructs an Axis instance of Type \a type for the axis rect \a parent. - + Usually it isn't necessary to instantiate axes directly, because you can let QCustomPlot create them for you with \ref QCPAxisRect::addAxis. If you want to use own QCPAxis-subclasses however, create them manually and then inject them also via \ref QCPAxisRect::addAxis. */ QCPPolarAxisRadial::QCPPolarAxisRadial(QCPPolarAxisAngular *parent) : - QCPLayerable(parent->parentPlot(), QString(), parent), - mRangeDrag(true), - mRangeZoom(true), - mRangeZoomFactor(0.85), - // axis base: - mAngularAxis(parent), - mAngle(45), - mAngleReference(arAngularAxis), - mSelectableParts(spAxis | spTickLabels | spAxisLabel), - mSelectedParts(spNone), - mBasePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), - mSelectedBasePen(QPen(Qt::blue, 2)), - // axis label: - mLabelPadding(0), - mLabel(), - mLabelFont(mParentPlot->font()), - mSelectedLabelFont(QFont(mLabelFont.family(), mLabelFont.pointSize(), QFont::Bold)), - mLabelColor(Qt::black), - mSelectedLabelColor(Qt::blue), - // tick labels: - // mTickLabelPadding(0), in label painter - mTickLabels(true), - // mTickLabelRotation(0), in label painter - mTickLabelFont(mParentPlot->font()), - mSelectedTickLabelFont(QFont(mTickLabelFont.family(), mTickLabelFont.pointSize(), QFont::Bold)), - mTickLabelColor(Qt::black), - mSelectedTickLabelColor(Qt::blue), - mNumberPrecision(6), - mNumberFormatChar('g'), - mNumberBeautifulPowers(true), - mNumberMultiplyCross(false), - // ticks and subticks: - mTicks(true), - mSubTicks(true), - mTickLengthIn(5), - mTickLengthOut(0), - mSubTickLengthIn(2), - mSubTickLengthOut(0), - mTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), - mSelectedTickPen(QPen(Qt::blue, 2)), - mSubTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), - mSelectedSubTickPen(QPen(Qt::blue, 2)), - // scale and range: - mRange(0, 5), - mRangeReversed(false), - mScaleType(stLinear), - // internal members: - mRadius(1), // non-zero initial value, will be overwritten in ::update() according to inner rect - mTicker(new QCPAxisTicker), - mLabelPainter(mParentPlot) + QCPLayerable(parent->parentPlot(), QString(), parent), + mRangeDrag(true), + mRangeZoom(true), + mRangeZoomFactor(0.85), + // axis base: + mAngularAxis(parent), + mAngle(45), + mAngleReference(arAngularAxis), + mSelectableParts(spAxis | spTickLabels | spAxisLabel), + mSelectedParts(spNone), + mBasePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), + mSelectedBasePen(QPen(Qt::blue, 2)), + // axis label: + mLabelPadding(0), + mLabel(), + mLabelFont(mParentPlot->font()), + mSelectedLabelFont(QFont(mLabelFont.family(), mLabelFont.pointSize(), QFont::Bold)), + mLabelColor(Qt::black), + mSelectedLabelColor(Qt::blue), + // tick labels: + // mTickLabelPadding(0), in label painter + mTickLabels(true), + // mTickLabelRotation(0), in label painter + mTickLabelFont(mParentPlot->font()), + mSelectedTickLabelFont(QFont(mTickLabelFont.family(), mTickLabelFont.pointSize(), QFont::Bold)), + mTickLabelColor(Qt::black), + mSelectedTickLabelColor(Qt::blue), + mNumberPrecision(6), + mNumberFormatChar('g'), + mNumberBeautifulPowers(true), + mNumberMultiplyCross(false), + // ticks and subticks: + mTicks(true), + mSubTicks(true), + mTickLengthIn(5), + mTickLengthOut(0), + mSubTickLengthIn(2), + mSubTickLengthOut(0), + mTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), + mSelectedTickPen(QPen(Qt::blue, 2)), + mSubTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), + mSelectedSubTickPen(QPen(Qt::blue, 2)), + // scale and range: + mRange(0, 5), + mRangeReversed(false), + mScaleType(stLinear), + // internal members: + mRadius(1), // non-zero initial value, will be overwritten in ::update() according to inner rect + mTicker(new QCPAxisTicker), + mLabelPainter(mParentPlot) { - setParent(parent); - setAntialiased(true); - - setTickLabelPadding(5); - setTickLabelRotation(0); - setTickLabelMode(lmUpright); - mLabelPainter.setAnchorReferenceType(QCPLabelPainterPrivate::artTangent); - mLabelPainter.setAbbreviateDecimalPowers(false); + setParent(parent); + setAntialiased(true); + + setTickLabelPadding(5); + setTickLabelRotation(0); + setTickLabelMode(lmUpright); + mLabelPainter.setAnchorReferenceType(QCPLabelPainterPrivate::artTangent); + mLabelPainter.setAbbreviateDecimalPowers(false); } QCPPolarAxisRadial::~QCPPolarAxisRadial() @@ -31129,203 +31504,206 @@ QCPPolarAxisRadial::~QCPPolarAxisRadial() QCPPolarAxisRadial::LabelMode QCPPolarAxisRadial::tickLabelMode() const { - switch (mLabelPainter.anchorMode()) - { - case QCPLabelPainterPrivate::amSkewedUpright: return lmUpright; - case QCPLabelPainterPrivate::amSkewedRotated: return lmRotated; - default: qDebug() << Q_FUNC_INFO << "invalid mode for polar axis"; break; - } - return lmUpright; + switch (mLabelPainter.anchorMode()) { + case QCPLabelPainterPrivate::amSkewedUpright: + return lmUpright; + case QCPLabelPainterPrivate::amSkewedRotated: + return lmRotated; + default: + qDebug() << Q_FUNC_INFO << "invalid mode for polar axis"; + break; + } + return lmUpright; } /* No documentation as it is a property getter */ QString QCPPolarAxisRadial::numberFormat() const { - QString result; - result.append(mNumberFormatChar); - if (mNumberBeautifulPowers) - { - result.append(QLatin1Char('b')); - if (mNumberMultiplyCross) - result.append(QLatin1Char('c')); - } - return result; + QString result; + result.append(mNumberFormatChar); + if (mNumberBeautifulPowers) { + result.append(QLatin1Char('b')); + if (mNumberMultiplyCross) { + result.append(QLatin1Char('c')); + } + } + return result; } /* No documentation as it is a property getter */ int QCPPolarAxisRadial::tickLengthIn() const { - return mTickLengthIn; + return mTickLengthIn; } /* No documentation as it is a property getter */ int QCPPolarAxisRadial::tickLengthOut() const { - return mTickLengthOut; + return mTickLengthOut; } /* No documentation as it is a property getter */ int QCPPolarAxisRadial::subTickLengthIn() const { - return mSubTickLengthIn; + return mSubTickLengthIn; } /* No documentation as it is a property getter */ int QCPPolarAxisRadial::subTickLengthOut() const { - return mSubTickLengthOut; + return mSubTickLengthOut; } /* No documentation as it is a property getter */ int QCPPolarAxisRadial::labelPadding() const { - return mLabelPadding; + return mLabelPadding; } void QCPPolarAxisRadial::setRangeDrag(bool enabled) { - mRangeDrag = enabled; + mRangeDrag = enabled; } void QCPPolarAxisRadial::setRangeZoom(bool enabled) { - mRangeZoom = enabled; + mRangeZoom = enabled; } void QCPPolarAxisRadial::setRangeZoomFactor(double factor) { - mRangeZoomFactor = factor; + mRangeZoomFactor = factor; } /*! Sets whether the axis uses a linear scale or a logarithmic scale. - + Note that this method controls the coordinate transformation. For logarithmic scales, you will likely also want to use a logarithmic tick spacing and labeling, which can be achieved by setting the axis ticker to an instance of \ref QCPAxisTickerLog : - + \snippet documentation/doc-code-snippets/mainwindow.cpp qcpaxisticker-log-creation - + See the documentation of \ref QCPAxisTickerLog about the details of logarithmic axis tick creation. - + \ref setNumberPrecision */ void QCPPolarAxisRadial::setScaleType(QCPPolarAxisRadial::ScaleType type) { - if (mScaleType != type) - { - mScaleType = type; - if (mScaleType == stLogarithmic) - setRange(mRange.sanitizedForLogScale()); - //mCachedMarginValid = false; - emit scaleTypeChanged(mScaleType); - } + if (mScaleType != type) { + mScaleType = type; + if (mScaleType == stLogarithmic) { + setRange(mRange.sanitizedForLogScale()); + } + //mCachedMarginValid = false; + emit scaleTypeChanged(mScaleType); + } } /*! Sets the range of the axis. - + This slot may be connected with the \ref rangeChanged signal of another axis so this axis is always synchronized with the other axis range, when it changes. - + To invert the direction of an axis, use \ref setRangeReversed. */ void QCPPolarAxisRadial::setRange(const QCPRange &range) { - if (range.lower == mRange.lower && range.upper == mRange.upper) - return; - - if (!QCPRange::validRange(range)) return; - QCPRange oldRange = mRange; - if (mScaleType == stLogarithmic) - { - mRange = range.sanitizedForLogScale(); - } else - { - mRange = range.sanitizedForLinScale(); - } - emit rangeChanged(mRange); - emit rangeChanged(mRange, oldRange); + if (range.lower == mRange.lower && range.upper == mRange.upper) { + return; + } + + if (!QCPRange::validRange(range)) { + return; + } + QCPRange oldRange = mRange; + if (mScaleType == stLogarithmic) { + mRange = range.sanitizedForLogScale(); + } else { + mRange = range.sanitizedForLinScale(); + } + emit rangeChanged(mRange); + emit rangeChanged(mRange, oldRange); } /*! Sets whether the user can (de-)select the parts in \a selectable by clicking on the QCustomPlot surface. (When \ref QCustomPlot::setInteractions contains iSelectAxes.) - + However, even when \a selectable is set to a value not allowing the selection of a specific part, it is still possible to set the selection of this part manually, by calling \ref setSelectedParts directly. - + \see SelectablePart, setSelectedParts */ void QCPPolarAxisRadial::setSelectableParts(const SelectableParts &selectable) { - if (mSelectableParts != selectable) - { - mSelectableParts = selectable; - emit selectableChanged(mSelectableParts); - } + if (mSelectableParts != selectable) { + mSelectableParts = selectable; + emit selectableChanged(mSelectableParts); + } } /*! Sets the selected state of the respective axis parts described by \ref SelectablePart. When a part is selected, it uses a different pen/font. - + The entire selection mechanism for axes is handled automatically when \ref QCustomPlot::setInteractions contains iSelectAxes. You only need to call this function when you wish to change the selection state manually. - + This function can change the selection state of a part, independent of the \ref setSelectableParts setting. - + emits the \ref selectionChanged signal when \a selected is different from the previous selection state. - + \see SelectablePart, setSelectableParts, selectTest, setSelectedBasePen, setSelectedTickPen, setSelectedSubTickPen, setSelectedTickLabelFont, setSelectedLabelFont, setSelectedTickLabelColor, setSelectedLabelColor */ void QCPPolarAxisRadial::setSelectedParts(const SelectableParts &selected) { - if (mSelectedParts != selected) - { - mSelectedParts = selected; - emit selectionChanged(mSelectedParts); - } + if (mSelectedParts != selected) { + mSelectedParts = selected; + emit selectionChanged(mSelectedParts); + } } /*! \overload - + Sets the lower and upper bound of the axis range. - + To invert the direction of an axis, use \ref setRangeReversed. - + There is also a slot to set a range, see \ref setRange(const QCPRange &range). */ void QCPPolarAxisRadial::setRange(double lower, double upper) { - if (lower == mRange.lower && upper == mRange.upper) - return; - - if (!QCPRange::validRange(lower, upper)) return; - QCPRange oldRange = mRange; - mRange.lower = lower; - mRange.upper = upper; - if (mScaleType == stLogarithmic) - { - mRange = mRange.sanitizedForLogScale(); - } else - { - mRange = mRange.sanitizedForLinScale(); - } - emit rangeChanged(mRange); - emit rangeChanged(mRange, oldRange); + if (lower == mRange.lower && upper == mRange.upper) { + return; + } + + if (!QCPRange::validRange(lower, upper)) { + return; + } + QCPRange oldRange = mRange; + mRange.lower = lower; + mRange.upper = upper; + if (mScaleType == stLogarithmic) { + mRange = mRange.sanitizedForLogScale(); + } else { + mRange = mRange.sanitizedForLinScale(); + } + emit rangeChanged(mRange); + emit rangeChanged(mRange, oldRange); } /*! \overload - + Sets the range of the axis. - + The \a position coordinate indicates together with the \a alignment parameter, where the new range will be positioned. \a size defines the size of the new axis range. \a alignment may be Qt::AlignLeft, Qt::AlignRight or Qt::AlignCenter. This will cause the left border, right border, @@ -31334,12 +31712,13 @@ void QCPPolarAxisRadial::setRange(double lower, double upper) */ void QCPPolarAxisRadial::setRange(double position, double size, Qt::AlignmentFlag alignment) { - if (alignment == Qt::AlignLeft) - setRange(position, position+size); - else if (alignment == Qt::AlignRight) - setRange(position-size, position); - else // alignment == Qt::AlignCenter - setRange(position-size/2.0, position+size/2.0); + if (alignment == Qt::AlignLeft) { + setRange(position, position + size); + } else if (alignment == Qt::AlignRight) { + setRange(position - size, position); + } else { // alignment == Qt::AlignCenter + setRange(position - size / 2.0, position + size / 2.0); + } } /*! @@ -31348,20 +31727,19 @@ void QCPPolarAxisRadial::setRange(double position, double size, Qt::AlignmentFla */ void QCPPolarAxisRadial::setRangeLower(double lower) { - if (mRange.lower == lower) - return; - - QCPRange oldRange = mRange; - mRange.lower = lower; - if (mScaleType == stLogarithmic) - { - mRange = mRange.sanitizedForLogScale(); - } else - { - mRange = mRange.sanitizedForLinScale(); - } - emit rangeChanged(mRange); - emit rangeChanged(mRange, oldRange); + if (mRange.lower == lower) { + return; + } + + QCPRange oldRange = mRange; + mRange.lower = lower; + if (mScaleType == stLogarithmic) { + mRange = mRange.sanitizedForLogScale(); + } else { + mRange = mRange.sanitizedForLinScale(); + } + emit rangeChanged(mRange); + emit rangeChanged(mRange, oldRange); } /*! @@ -31370,20 +31748,19 @@ void QCPPolarAxisRadial::setRangeLower(double lower) */ void QCPPolarAxisRadial::setRangeUpper(double upper) { - if (mRange.upper == upper) - return; - - QCPRange oldRange = mRange; - mRange.upper = upper; - if (mScaleType == stLogarithmic) - { - mRange = mRange.sanitizedForLogScale(); - } else - { - mRange = mRange.sanitizedForLinScale(); - } - emit rangeChanged(mRange); - emit rangeChanged(mRange, oldRange); + if (mRange.upper == upper) { + return; + } + + QCPRange oldRange = mRange; + mRange.upper = upper; + if (mScaleType == stLogarithmic) { + mRange = mRange.sanitizedForLogScale(); + } else { + mRange = mRange.sanitizedForLinScale(); + } + emit rangeChanged(mRange); + emit rangeChanged(mRange, oldRange); } /*! @@ -31397,39 +31774,40 @@ void QCPPolarAxisRadial::setRangeUpper(double upper) */ void QCPPolarAxisRadial::setRangeReversed(bool reversed) { - mRangeReversed = reversed; + mRangeReversed = reversed; } void QCPPolarAxisRadial::setAngle(double degrees) { - mAngle = degrees; + mAngle = degrees; } void QCPPolarAxisRadial::setAngleReference(AngleReference reference) { - mAngleReference = reference; + mAngleReference = reference; } /*! 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. - + 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. - + 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 ticker */ void QCPPolarAxisRadial::setTicker(QSharedPointer ticker) { - 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 + 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 } /*! @@ -31437,16 +31815,15 @@ void QCPPolarAxisRadial::setTicker(QSharedPointer ticker) 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 QCPPolarAxisRadial::setTicks(bool show) { - if (mTicks != show) - { - mTicks = show; - //mCachedMarginValid = false; - } + if (mTicks != show) { + mTicks = show; + //mCachedMarginValid = false; + } } /*! @@ -31454,13 +31831,13 @@ void QCPPolarAxisRadial::setTicks(bool show) */ void QCPPolarAxisRadial::setTickLabels(bool show) { - if (mTickLabels != show) - { - mTickLabels = show; - //mCachedMarginValid = false; - if (!mTickLabels) - mTickVectorLabels.clear(); - } + if (mTickLabels != show) { + mTickLabels = show; + //mCachedMarginValid = false; + if (!mTickLabels) { + mTickVectorLabels.clear(); + } + } } /*! @@ -31469,65 +31846,67 @@ void QCPPolarAxisRadial::setTickLabels(bool show) */ void QCPPolarAxisRadial::setTickLabelPadding(int padding) { - mLabelPainter.setPadding(padding); + mLabelPainter.setPadding(padding); } /*! Sets the font of the tick labels. - + \see setTickLabels, setTickLabelColor */ void QCPPolarAxisRadial::setTickLabelFont(const QFont &font) { - if (font != mTickLabelFont) - { - mTickLabelFont = font; - //mCachedMarginValid = false; - } + if (font != mTickLabelFont) { + mTickLabelFont = font; + //mCachedMarginValid = false; + } } /*! Sets the color of the tick labels. - + \see setTickLabels, setTickLabelFont */ void QCPPolarAxisRadial::setTickLabelColor(const QColor &color) { - mTickLabelColor = color; + mTickLabelColor = color; } /*! Sets the rotation of the tick labels. If \a degrees is zero, the labels are drawn normally. Else, the tick labels are drawn rotated by \a degrees clockwise. The specified angle is bound to values from -90 to 90 degrees. - + If \a degrees is exactly -90, 0 or 90, the tick labels are centered on the tick coordinate. For other angles, the label is drawn with an offset such that it seems to point toward or away from the tick mark. */ void QCPPolarAxisRadial::setTickLabelRotation(double degrees) { - mLabelPainter.setRotation(degrees); + mLabelPainter.setRotation(degrees); } void QCPPolarAxisRadial::setTickLabelMode(LabelMode mode) { - switch (mode) - { - case lmUpright: mLabelPainter.setAnchorMode(QCPLabelPainterPrivate::amSkewedUpright); break; - case lmRotated: mLabelPainter.setAnchorMode(QCPLabelPainterPrivate::amSkewedRotated); break; - } + switch (mode) { + case lmUpright: + mLabelPainter.setAnchorMode(QCPLabelPainterPrivate::amSkewedUpright); + break; + case lmRotated: + mLabelPainter.setAnchorMode(QCPLabelPainterPrivate::amSkewedRotated); + break; + } } /*! 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. - + \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. "5.5e9", which is ugly in a plot. So when the second char of \a formatCode is set to 'b' (for @@ -31536,7 +31915,7 @@ void QCPPolarAxisRadial::setTickLabelMode(LabelMode mode) If instead a cross should be shown (as is usual in the USA), the third char of \a formatCode can be set to 'c'. The inserted multiplication signs are the UTF-8 characters 215 (0xD7) for the cross and 183 (0xB7) for the dot. - + 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 @@ -31551,52 +31930,47 @@ void QCPPolarAxisRadial::setTickLabelMode(LabelMode mode) */ void QCPPolarAxisRadial::setNumberFormat(const QString &formatCode) { - if (formatCode.isEmpty()) - { - qDebug() << Q_FUNC_INFO << "Passed formatCode is empty"; - return; - } - //mCachedMarginValid = false; - - // interpret first char as number format char: - QString allowedFormatChars(QLatin1String("eEfgG")); - if (allowedFormatChars.contains(formatCode.at(0))) - { - mNumberFormatChar = QLatin1Char(formatCode.at(0).toLatin1()); - } else - { - qDebug() << Q_FUNC_INFO << "Invalid number format code (first char not in 'eEfgG'):" << formatCode; - return; - } - - if (formatCode.length() < 2) - { - mNumberBeautifulPowers = false; - mNumberMultiplyCross = false; - } else - { - // interpret second char as indicator for beautiful decimal powers: - if (formatCode.at(1) == QLatin1Char('b') && (mNumberFormatChar == QLatin1Char('e') || mNumberFormatChar == QLatin1Char('g'))) - mNumberBeautifulPowers = true; - else - qDebug() << Q_FUNC_INFO << "Invalid number format code (second char not 'b' or first char neither 'e' nor 'g'):" << formatCode; - - if (formatCode.length() < 3) - { - mNumberMultiplyCross = false; - } else - { - // interpret third char as indicator for dot or cross multiplication symbol: - if (formatCode.at(2) == QLatin1Char('c')) - mNumberMultiplyCross = true; - else if (formatCode.at(2) == QLatin1Char('d')) - mNumberMultiplyCross = false; - else - qDebug() << Q_FUNC_INFO << "Invalid number format code (third char neither 'c' nor 'd'):" << formatCode; + if (formatCode.isEmpty()) { + qDebug() << Q_FUNC_INFO << "Passed formatCode is empty"; + return; } - } - mLabelPainter.setSubstituteExponent(mNumberBeautifulPowers); - mLabelPainter.setMultiplicationSymbol(mNumberMultiplyCross ? QCPLabelPainterPrivate::SymbolCross : QCPLabelPainterPrivate::SymbolDot); + //mCachedMarginValid = false; + + // interpret first char as number format char: + QString allowedFormatChars(QLatin1String("eEfgG")); + if (allowedFormatChars.contains(formatCode.at(0))) { + mNumberFormatChar = QLatin1Char(formatCode.at(0).toLatin1()); + } else { + qDebug() << Q_FUNC_INFO << "Invalid number format code (first char not in 'eEfgG'):" << formatCode; + return; + } + + if (formatCode.length() < 2) { + mNumberBeautifulPowers = false; + mNumberMultiplyCross = false; + } else { + // interpret second char as indicator for beautiful decimal powers: + if (formatCode.at(1) == QLatin1Char('b') && (mNumberFormatChar == QLatin1Char('e') || mNumberFormatChar == QLatin1Char('g'))) { + mNumberBeautifulPowers = true; + } else { + qDebug() << Q_FUNC_INFO << "Invalid number format code (second char not 'b' or first char neither 'e' nor 'g'):" << formatCode; + } + + if (formatCode.length() < 3) { + mNumberMultiplyCross = false; + } else { + // interpret third char as indicator for dot or cross multiplication symbol: + if (formatCode.at(2) == QLatin1Char('c')) { + mNumberMultiplyCross = true; + } else if (formatCode.at(2) == QLatin1Char('d')) { + mNumberMultiplyCross = false; + } else { + qDebug() << Q_FUNC_INFO << "Invalid number format code (third char neither 'c' nor 'd'):" << formatCode; + } + } + } + mLabelPainter.setSubstituteExponent(mNumberBeautifulPowers); + mLabelPainter.setMultiplicationSymbol(mNumberMultiplyCross ? QCPLabelPainterPrivate::SymbolCross : QCPLabelPainterPrivate::SymbolDot); } /*! @@ -31606,11 +31980,10 @@ void QCPPolarAxisRadial::setNumberFormat(const QString &formatCode) */ void QCPPolarAxisRadial::setNumberPrecision(int precision) { - if (mNumberPrecision != precision) - { - mNumberPrecision = precision; - //mCachedMarginValid = false; - } + if (mNumberPrecision != precision) { + mNumberPrecision = precision; + //mCachedMarginValid = false; + } } /*! @@ -31618,59 +31991,56 @@ void QCPPolarAxisRadial::setNumberPrecision(int precision) plot and \a outside is the length they will reach outside the plot. If \a outside is greater than zero, the tick labels and axis label will increase their distance to the axis accordingly, so they won't collide with the ticks. - + \see setSubTickLength, setTickLengthIn, setTickLengthOut */ void QCPPolarAxisRadial::setTickLength(int inside, int outside) { - setTickLengthIn(inside); - setTickLengthOut(outside); + setTickLengthIn(inside); + setTickLengthOut(outside); } /*! Sets the length of the inward ticks in pixels. \a inside is the length the ticks will reach inside the plot. - + \see setTickLengthOut, setTickLength, setSubTickLength */ void QCPPolarAxisRadial::setTickLengthIn(int inside) { - if (mTickLengthIn != inside) - { - mTickLengthIn = inside; - } + if (mTickLengthIn != inside) { + mTickLengthIn = inside; + } } /*! Sets the length of the outward ticks in pixels. \a outside is the length the ticks will reach outside the plot. If \a outside is greater than zero, the tick labels and axis label will increase their distance to the axis accordingly, so they won't collide with the ticks. - + \see setTickLengthIn, setTickLength, setSubTickLength */ void QCPPolarAxisRadial::setTickLengthOut(int outside) { - if (mTickLengthOut != outside) - { - mTickLengthOut = outside; - //mCachedMarginValid = false; // only outside tick length can change margin - } + if (mTickLengthOut != outside) { + mTickLengthOut = outside; + //mCachedMarginValid = false; // only outside tick length can change margin + } } /*! Sets whether sub tick marks are displayed. - + Sub ticks are only potentially visible if (major) ticks are also visible (see \ref setTicks) - + \see setTicks */ void QCPPolarAxisRadial::setSubTicks(bool show) { - if (mSubTicks != show) - { - mSubTicks = show; - //mCachedMarginValid = false; - } + if (mSubTicks != show) { + mSubTicks = show; + //mCachedMarginValid = false; + } } /*! @@ -31678,97 +32048,94 @@ void QCPPolarAxisRadial::setSubTicks(bool show) the plot and \a outside is the length they will reach outside the plot. If \a outside is greater than zero, the tick labels and axis label will increase their distance to the axis accordingly, so they won't collide with the ticks. - + \see setTickLength, setSubTickLengthIn, setSubTickLengthOut */ void QCPPolarAxisRadial::setSubTickLength(int inside, int outside) { - setSubTickLengthIn(inside); - setSubTickLengthOut(outside); + setSubTickLengthIn(inside); + setSubTickLengthOut(outside); } /*! Sets the length of the inward subticks in pixels. \a inside is the length the subticks will reach inside the plot. - + \see setSubTickLengthOut, setSubTickLength, setTickLength */ void QCPPolarAxisRadial::setSubTickLengthIn(int inside) { - if (mSubTickLengthIn != inside) - { - mSubTickLengthIn = inside; - } + if (mSubTickLengthIn != inside) { + mSubTickLengthIn = inside; + } } /*! Sets the length of the outward subticks in pixels. \a outside is the length the subticks will reach outside the plot. If \a outside is greater than zero, the tick labels will increase their distance to the axis accordingly, so they won't collide with the ticks. - + \see setSubTickLengthIn, setSubTickLength, setTickLength */ void QCPPolarAxisRadial::setSubTickLengthOut(int outside) { - if (mSubTickLengthOut != outside) - { - mSubTickLengthOut = outside; - //mCachedMarginValid = false; // only outside tick length can change margin - } + if (mSubTickLengthOut != outside) { + mSubTickLengthOut = outside; + //mCachedMarginValid = false; // only outside tick length can change margin + } } /*! Sets the pen, the axis base line is drawn with. - + \see setTickPen, setSubTickPen */ void QCPPolarAxisRadial::setBasePen(const QPen &pen) { - mBasePen = pen; + mBasePen = pen; } /*! Sets the pen, tick marks will be drawn with. - + \see setTickLength, setBasePen */ void QCPPolarAxisRadial::setTickPen(const QPen &pen) { - mTickPen = pen; + mTickPen = pen; } /*! Sets the pen, subtick marks will be drawn with. - + \see setSubTickCount, setSubTickLength, setBasePen */ void QCPPolarAxisRadial::setSubTickPen(const QPen &pen) { - mSubTickPen = pen; + mSubTickPen = pen; } /*! Sets the font of the axis label. - + \see setLabelColor */ void QCPPolarAxisRadial::setLabelFont(const QFont &font) { - if (mLabelFont != font) - { - mLabelFont = font; - //mCachedMarginValid = false; - } + if (mLabelFont != font) { + mLabelFont = font; + //mCachedMarginValid = false; + } } /*! Sets the color of the axis label. - + \see setLabelFont */ void QCPPolarAxisRadial::setLabelColor(const QColor &color) { - mLabelColor = color; + mLabelColor = color; } /*! @@ -31777,126 +32144,120 @@ void QCPPolarAxisRadial::setLabelColor(const QColor &color) */ void QCPPolarAxisRadial::setLabel(const QString &str) { - if (mLabel != str) - { - mLabel = str; - //mCachedMarginValid = false; - } + if (mLabel != str) { + mLabel = str; + //mCachedMarginValid = false; + } } /*! Sets the distance between the tick labels and the axis label. - + \see setTickLabelPadding, setPadding */ void QCPPolarAxisRadial::setLabelPadding(int padding) { - if (mLabelPadding != padding) - { - mLabelPadding = padding; - //mCachedMarginValid = false; - } + if (mLabelPadding != padding) { + mLabelPadding = padding; + //mCachedMarginValid = false; + } } /*! Sets the font that is used for tick labels when they are selected. - + \see setTickLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPPolarAxisRadial::setSelectedTickLabelFont(const QFont &font) { - if (font != mSelectedTickLabelFont) - { - mSelectedTickLabelFont = font; - // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts - } + if (font != mSelectedTickLabelFont) { + mSelectedTickLabelFont = font; + // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts + } } /*! Sets the font that is used for the axis label when it is selected. - + \see setLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPPolarAxisRadial::setSelectedLabelFont(const QFont &font) { - mSelectedLabelFont = font; - // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts + mSelectedLabelFont = font; + // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts } /*! Sets the color that is used for tick labels when they are selected. - + \see setTickLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPPolarAxisRadial::setSelectedTickLabelColor(const QColor &color) { - if (color != mSelectedTickLabelColor) - { - mSelectedTickLabelColor = color; - } + if (color != mSelectedTickLabelColor) { + mSelectedTickLabelColor = color; + } } /*! Sets the color that is used for the axis label when it is selected. - + \see setLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPPolarAxisRadial::setSelectedLabelColor(const QColor &color) { - mSelectedLabelColor = color; + mSelectedLabelColor = color; } /*! Sets the pen that is used to draw the axis base line when selected. - + \see setBasePen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPPolarAxisRadial::setSelectedBasePen(const QPen &pen) { - mSelectedBasePen = pen; + mSelectedBasePen = pen; } /*! Sets the pen that is used to draw the (major) ticks when selected. - + \see setTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPPolarAxisRadial::setSelectedTickPen(const QPen &pen) { - mSelectedTickPen = pen; + mSelectedTickPen = pen; } /*! Sets the pen that is used to draw the subticks when selected. - + \see setSubTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPPolarAxisRadial::setSelectedSubTickPen(const QPen &pen) { - mSelectedSubTickPen = pen; + mSelectedSubTickPen = pen; } /*! If the scale type (\ref setScaleType) is \ref stLinear, \a diff is added to the lower and upper bounds of the range. The range is simply moved by \a diff. - + If the scale type is \ref stLogarithmic, the range bounds are multiplied by \a diff. This corresponds to an apparent "linear" move in logarithmic scaling by a distance of log(diff). */ void QCPPolarAxisRadial::moveRange(double diff) { - QCPRange oldRange = mRange; - if (mScaleType == stLinear) - { - mRange.lower += diff; - mRange.upper += diff; - } else // mScaleType == stLogarithmic - { - mRange.lower *= diff; - mRange.upper *= diff; - } - emit rangeChanged(mRange); - emit rangeChanged(mRange, oldRange); + QCPRange oldRange = mRange; + if (mScaleType == stLinear) { + mRange.lower += diff; + mRange.upper += diff; + } else { // mScaleType == stLogarithmic + mRange.lower *= diff; + mRange.upper *= diff; + } + emit rangeChanged(mRange); + emit rangeChanged(mRange, oldRange); } /*! @@ -31910,7 +32271,7 @@ void QCPPolarAxisRadial::moveRange(double diff) */ void QCPPolarAxisRadial::scaleRange(double factor) { - scaleRange(factor, range().center()); + scaleRange(factor, range().center()); } /*! \overload @@ -31924,45 +32285,45 @@ void QCPPolarAxisRadial::scaleRange(double factor) */ void QCPPolarAxisRadial::scaleRange(double factor, double center) { - QCPRange oldRange = mRange; - if (mScaleType == stLinear) - { - QCPRange newRange; - newRange.lower = (mRange.lower-center)*factor + center; - newRange.upper = (mRange.upper-center)*factor + center; - if (QCPRange::validRange(newRange)) - mRange = newRange.sanitizedForLinScale(); - } else // mScaleType == stLogarithmic - { - if ((mRange.upper < 0 && center < 0) || (mRange.upper > 0 && center > 0)) // make sure center has same sign as range - { - QCPRange newRange; - newRange.lower = qPow(mRange.lower/center, factor)*center; - newRange.upper = qPow(mRange.upper/center, factor)*center; - if (QCPRange::validRange(newRange)) - mRange = newRange.sanitizedForLogScale(); - } else - qDebug() << Q_FUNC_INFO << "Center of scaling operation doesn't lie in same logarithmic sign domain as range:" << center; - } - emit rangeChanged(mRange); - emit rangeChanged(mRange, oldRange); + QCPRange oldRange = mRange; + if (mScaleType == stLinear) { + QCPRange newRange; + newRange.lower = (mRange.lower - center) * factor + center; + newRange.upper = (mRange.upper - center) * factor + center; + if (QCPRange::validRange(newRange)) { + mRange = newRange.sanitizedForLinScale(); + } + } else { // mScaleType == stLogarithmic + if ((mRange.upper < 0 && center < 0) || (mRange.upper > 0 && center > 0)) { // make sure center has same sign as range + QCPRange newRange; + newRange.lower = qPow(mRange.lower / center, factor) * center; + newRange.upper = qPow(mRange.upper / center, factor) * center; + if (QCPRange::validRange(newRange)) { + mRange = newRange.sanitizedForLogScale(); + } + } else { + qDebug() << Q_FUNC_INFO << "Center of scaling operation doesn't lie in same logarithmic sign domain as range:" << center; + } + } + emit rangeChanged(mRange); + emit rangeChanged(mRange, oldRange); } /*! Changes the axis range such that all plottables associated with this axis are fully visible in that dimension. - + \see QCPAbstractPlottable::rescaleAxes, QCustomPlot::rescaleAxes */ void QCPPolarAxisRadial::rescale(bool onlyVisiblePlottables) { - Q_UNUSED(onlyVisiblePlottables) - /* TODO - QList p = plottables(); - QCPRange newRange; - bool haveRange = false; - for (int i=0; i p = plottables(); + QCPRange newRange; + bool haveRange = false; + for (int i=0; irealVisibility() && onlyVisiblePlottables) continue; QCPRange plottableRange; @@ -31982,9 +32343,9 @@ void QCPPolarAxisRadial::rescale(bool onlyVisiblePlottables) newRange.expand(plottableRange); haveRange = true; } - } - if (haveRange) - { + } + if (haveRange) + { if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable { double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason @@ -31999,8 +32360,8 @@ void QCPPolarAxisRadial::rescale(bool onlyVisiblePlottables) } } setRange(newRange); - } - */ + } + */ } /*! @@ -32008,9 +32369,9 @@ void QCPPolarAxisRadial::rescale(bool onlyVisiblePlottables) */ void QCPPolarAxisRadial::pixelToCoord(QPointF pixelPos, double &angleCoord, double &radiusCoord) const { - QCPVector2D posVector(pixelPos-mCenter); - radiusCoord = radiusToCoord(posVector.length()); - angleCoord = mAngularAxis->angleRadToCoord(posVector.angle()); + QCPVector2D posVector(pixelPos - mCenter); + radiusCoord = radiusToCoord(posVector.length()); + angleCoord = mAngularAxis->angleRadToCoord(posVector.angle()); } /*! @@ -32018,50 +32379,49 @@ void QCPPolarAxisRadial::pixelToCoord(QPointF pixelPos, double &angleCoord, doub */ QPointF QCPPolarAxisRadial::coordToPixel(double angleCoord, double radiusCoord) const { - const double radiusPixel = coordToRadius(radiusCoord); - const double angleRad = mAngularAxis->coordToAngleRad(angleCoord); - return QPointF(mCenter.x()+qCos(angleRad)*radiusPixel, mCenter.y()+qSin(angleRad)*radiusPixel); + const double radiusPixel = coordToRadius(radiusCoord); + const double angleRad = mAngularAxis->coordToAngleRad(angleCoord); + return QPointF(mCenter.x() + qCos(angleRad) * radiusPixel, mCenter.y() + qSin(angleRad) * radiusPixel); } double QCPPolarAxisRadial::coordToRadius(double coord) const { - if (mScaleType == stLinear) - { - if (!mRangeReversed) - return (coord-mRange.lower)/mRange.size()*mRadius; - else - return (mRange.upper-coord)/mRange.size()*mRadius; - } else // mScaleType == stLogarithmic - { - if (coord >= 0.0 && mRange.upper < 0.0) // invalid value for logarithmic scale, just return outside visible range - return !mRangeReversed ? mRadius+200 : mRadius-200; - else if (coord <= 0.0 && mRange.upper >= 0.0) // invalid value for logarithmic scale, just return outside visible range - return !mRangeReversed ? mRadius-200 :mRadius+200; - else - { - if (!mRangeReversed) - return qLn(coord/mRange.lower)/qLn(mRange.upper/mRange.lower)*mRadius; - else - return qLn(mRange.upper/coord)/qLn(mRange.upper/mRange.lower)*mRadius; + if (mScaleType == stLinear) { + if (!mRangeReversed) { + return (coord - mRange.lower) / mRange.size() * mRadius; + } else { + return (mRange.upper - coord) / mRange.size() * mRadius; + } + } else { // mScaleType == stLogarithmic + if (coord >= 0.0 && mRange.upper < 0.0) { // invalid value for logarithmic scale, just return outside visible range + return !mRangeReversed ? mRadius + 200 : mRadius - 200; + } else if (coord <= 0.0 && mRange.upper >= 0.0) { // invalid value for logarithmic scale, just return outside visible range + return !mRangeReversed ? mRadius - 200 : mRadius + 200; + } else { + if (!mRangeReversed) { + return qLn(coord / mRange.lower) / qLn(mRange.upper / mRange.lower) * mRadius; + } else { + return qLn(mRange.upper / coord) / qLn(mRange.upper / mRange.lower) * mRadius; + } + } } - } } double QCPPolarAxisRadial::radiusToCoord(double radius) const { - if (mScaleType == stLinear) - { - if (!mRangeReversed) - return (radius)/mRadius*mRange.size()+mRange.lower; - else - return -(radius)/mRadius*mRange.size()+mRange.upper; - } else // mScaleType == stLogarithmic - { - if (!mRangeReversed) - return qPow(mRange.upper/mRange.lower, (radius)/mRadius)*mRange.lower; - else - return qPow(mRange.upper/mRange.lower, (-radius)/mRadius)*mRange.upper; - } + if (mScaleType == stLinear) { + if (!mRangeReversed) { + return (radius) / mRadius * mRange.size() + mRange.lower; + } else { + return -(radius) / mRadius * mRange.size() + mRange.upper; + } + } else { // mScaleType == stLogarithmic + if (!mRangeReversed) { + return qPow(mRange.upper / mRange.lower, (radius) / mRadius) * mRange.lower; + } else { + return qPow(mRange.upper / mRange.lower, (-radius) / mRadius) * mRange.upper; + } + } } @@ -32069,67 +32429,73 @@ double QCPPolarAxisRadial::radiusToCoord(double radius) const Returns the part of the axis that is hit by \a pos (in pixels). The return value of this function is independent of the user-selectable parts defined with \ref setSelectableParts. Further, this function does not change the current selection state of the axis. - + If the axis is not visible (\ref setVisible), this function always returns \ref spNone. - + \see setSelectedParts, setSelectableParts, QCustomPlot::setInteractions */ QCPPolarAxisRadial::SelectablePart QCPPolarAxisRadial::getPartAt(const QPointF &pos) const { - Q_UNUSED(pos) // TODO remove later - if (!mVisible) - return spNone; - - /* + Q_UNUSED(pos) // TODO remove later + if (!mVisible) { + return spNone; + } + + /* TODO: - if (mAxisPainter->axisSelectionBox().contains(pos.toPoint())) + if (mAxisPainter->axisSelectionBox().contains(pos.toPoint())) return spAxis; - else if (mAxisPainter->tickLabelsSelectionBox().contains(pos.toPoint())) + else if (mAxisPainter->tickLabelsSelectionBox().contains(pos.toPoint())) return spTickLabels; - else if (mAxisPainter->labelSelectionBox().contains(pos.toPoint())) + else if (mAxisPainter->labelSelectionBox().contains(pos.toPoint())) return spAxisLabel; - else */ + else */ return spNone; } /* inherits documentation from base class */ double QCPPolarAxisRadial::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { - if (!mParentPlot) return -1; - SelectablePart part = getPartAt(pos); - if ((onlySelectable && !mSelectableParts.testFlag(part)) || part == spNone) - return -1; - - if (details) - details->setValue(part); - return mParentPlot->selectionTolerance()*0.99; + if (!mParentPlot) { + return -1; + } + SelectablePart part = getPartAt(pos); + if ((onlySelectable && !mSelectableParts.testFlag(part)) || part == spNone) { + return -1; + } + + if (details) { + details->setValue(part); + } + return mParentPlot->selectionTolerance() * 0.99; } /* inherits documentation from base class */ void QCPPolarAxisRadial::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) { - Q_UNUSED(event) - SelectablePart part = details.value(); - if (mSelectableParts.testFlag(part)) - { - SelectableParts selBefore = mSelectedParts; - setSelectedParts(additive ? mSelectedParts^part : part); - if (selectionStateChanged) - *selectionStateChanged = mSelectedParts != selBefore; - } + Q_UNUSED(event) + SelectablePart part = details.value(); + if (mSelectableParts.testFlag(part)) { + SelectableParts selBefore = mSelectedParts; + setSelectedParts(additive ? mSelectedParts ^part : part); + if (selectionStateChanged) { + *selectionStateChanged = mSelectedParts != selBefore; + } + } } /* inherits documentation from base class */ void QCPPolarAxisRadial::deselectEvent(bool *selectionStateChanged) { - SelectableParts selBefore = mSelectedParts; - setSelectedParts(mSelectedParts & ~mSelectableParts); - if (selectionStateChanged) - *selectionStateChanged = mSelectedParts != selBefore; + SelectableParts selBefore = mSelectedParts; + setSelectedParts(mSelectedParts & ~mSelectableParts); + if (selectionStateChanged) { + *selectionStateChanged = mSelectedParts != selBefore; + } } /*! \internal - + This mouse event reimplementation provides the functionality to let the user drag individual axes exclusively, by startig the drag on top of the axis. @@ -32137,100 +32503,97 @@ void QCPPolarAxisRadial::deselectEvent(bool *selectionStateChanged) must be configured accordingly, i.e. it must allow range dragging in the orientation of this axis (\ref QCPAxisRect::setRangeDrag) and this axis must be a draggable axis (\ref QCPAxisRect::setRangeDragAxes) - + \seebaseclassmethod - + \note The dragging of possibly multiple axes at once by starting the drag anywhere in the axis rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::mousePressEvent. */ void QCPPolarAxisRadial::mousePressEvent(QMouseEvent *event, const QVariant &details) { - Q_UNUSED(details) - if (!mParentPlot->interactions().testFlag(QCP::iRangeDrag)) - { - event->ignore(); - return; - } - - if (event->buttons() & Qt::LeftButton) - { - mDragging = true; - // initialize antialiasing backup in case we start dragging: - if (mParentPlot->noAntialiasingOnDrag()) - { - mAADragBackup = mParentPlot->antialiasedElements(); - mNotAADragBackup = mParentPlot->notAntialiasedElements(); + Q_UNUSED(details) + if (!mParentPlot->interactions().testFlag(QCP::iRangeDrag)) { + event->ignore(); + return; + } + + if (event->buttons() & Qt::LeftButton) { + mDragging = true; + // initialize antialiasing backup in case we start dragging: + if (mParentPlot->noAntialiasingOnDrag()) { + mAADragBackup = mParentPlot->antialiasedElements(); + mNotAADragBackup = mParentPlot->notAntialiasedElements(); + } + // Mouse range dragging interaction: + if (mParentPlot->interactions().testFlag(QCP::iRangeDrag)) { + mDragStartRange = mRange; + } } - // Mouse range dragging interaction: - if (mParentPlot->interactions().testFlag(QCP::iRangeDrag)) - mDragStartRange = mRange; - } } /*! \internal - + This mouse event reimplementation provides the functionality to let the user drag individual axes exclusively, by startig the drag on top of the axis. - + \seebaseclassmethod - + \note The dragging of possibly multiple axes at once by starting the drag anywhere in the axis rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::mousePressEvent. - + \see QCPAxis::mousePressEvent */ void QCPPolarAxisRadial::mouseMoveEvent(QMouseEvent *event, const QPointF &startPos) { - Q_UNUSED(event) // TODO remove later - Q_UNUSED(startPos) // TODO remove later - if (mDragging) - { - /* TODO - const double startPixel = orientation() == Qt::Horizontal ? startPos.x() : startPos.y(); - const double currentPixel = orientation() == Qt::Horizontal ? event->pos().x() : event->pos().y(); - if (mScaleType == QCPPolarAxisRadial::stLinear) - { - const double diff = pixelToCoord(startPixel) - pixelToCoord(currentPixel); - setRange(mDragStartRange.lower+diff, mDragStartRange.upper+diff); - } else if (mScaleType == QCPPolarAxisRadial::stLogarithmic) - { - const double diff = pixelToCoord(startPixel) / pixelToCoord(currentPixel); - setRange(mDragStartRange.lower*diff, mDragStartRange.upper*diff); + Q_UNUSED(event) // TODO remove later + Q_UNUSED(startPos) // TODO remove later + if (mDragging) { + /* TODO + const double startPixel = orientation() == Qt::Horizontal ? startPos.x() : startPos.y(); + const double currentPixel = orientation() == Qt::Horizontal ? event->pos().x() : event->pos().y(); + if (mScaleType == QCPPolarAxisRadial::stLinear) + { + const double diff = pixelToCoord(startPixel) - pixelToCoord(currentPixel); + setRange(mDragStartRange.lower+diff, mDragStartRange.upper+diff); + } else if (mScaleType == QCPPolarAxisRadial::stLogarithmic) + { + const double diff = pixelToCoord(startPixel) / pixelToCoord(currentPixel); + setRange(mDragStartRange.lower*diff, mDragStartRange.upper*diff); + } + */ + + if (mParentPlot->noAntialiasingOnDrag()) { + mParentPlot->setNotAntialiasedElements(QCP::aeAll); + } + mParentPlot->replot(QCustomPlot::rpQueuedReplot); } - */ - - if (mParentPlot->noAntialiasingOnDrag()) - mParentPlot->setNotAntialiasedElements(QCP::aeAll); - mParentPlot->replot(QCustomPlot::rpQueuedReplot); - } } /*! \internal - + This mouse event reimplementation provides the functionality to let the user drag individual axes exclusively, by startig the drag on top of the axis. - + \seebaseclassmethod - + \note The dragging of possibly multiple axes at once by starting the drag anywhere in the axis rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::mousePressEvent. - + \see QCPAxis::mousePressEvent */ void QCPPolarAxisRadial::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos) { - Q_UNUSED(event) - Q_UNUSED(startPos) - mDragging = false; - if (mParentPlot->noAntialiasingOnDrag()) - { - mParentPlot->setAntialiasedElements(mAADragBackup); - mParentPlot->setNotAntialiasedElements(mNotAADragBackup); - } + Q_UNUSED(event) + Q_UNUSED(startPos) + mDragging = false; + if (mParentPlot->noAntialiasingOnDrag()) { + mParentPlot->setAntialiasedElements(mAADragBackup); + mParentPlot->setNotAntialiasedElements(mNotAADragBackup); + } } /*! \internal - + This mouse event reimplementation provides the functionality to let the user zoom individual axes exclusively, by performing the wheel event on top of the axis. @@ -32238,33 +32601,34 @@ void QCPPolarAxisRadial::mouseReleaseEvent(QMouseEvent *event, const QPointF &st must be configured accordingly, i.e. it must allow range zooming in the orientation of this axis (\ref QCPAxisRect::setRangeZoom) and this axis must be a zoomable axis (\ref QCPAxisRect::setRangeZoomAxes) - + \seebaseclassmethod - + \note The zooming of possibly multiple axes at once by performing the wheel event anywhere in the axis rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::wheelEvent. */ void QCPPolarAxisRadial::wheelEvent(QWheelEvent *event) { - // Mouse range zooming interaction: - if (!mParentPlot->interactions().testFlag(QCP::iRangeZoom)) - { - event->ignore(); - return; - } - - // TODO: - //const double wheelSteps = event->delta()/120.0; // a single step delta is +/-120 usually - //const double factor = qPow(mRangeZoomFactor, wheelSteps); - //scaleRange(factor, pixelToCoord(orientation() == Qt::Horizontal ? event->pos().x() : event->pos().y())); - mParentPlot->replot(); + // Mouse range zooming interaction: + if (!mParentPlot->interactions().testFlag(QCP::iRangeZoom)) { + event->ignore(); + return; + } + + // TODO: + //const double wheelSteps = event->delta()/120.0; // a single step delta is +/-120 usually + //const double factor = qPow(mRangeZoomFactor, wheelSteps); + //scaleRange(factor, pixelToCoord(orientation() == Qt::Horizontal ? event->pos().x() : event->pos().y())); + mParentPlot->replot(); } void QCPPolarAxisRadial::updateGeometry(const QPointF ¢er, double radius) { - mCenter = center; - mRadius = radius; - if (mRadius < 1) mRadius = 1; + mCenter = center; + mRadius = radius; + if (mRadius < 1) { + mRadius = 1; + } } /*! \internal @@ -32273,162 +32637,162 @@ void QCPPolarAxisRadial::updateGeometry(const QPointF ¢er, double radius) before drawing axis lines. This is the antialiasing state the painter passed to the \ref draw method is in by default. - + 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. - + \seebaseclassmethod - + \see setAntialiased */ void QCPPolarAxisRadial::applyDefaultAntialiasingHint(QCPPainter *painter) const { - applyAntialiasingHint(painter, mAntialiased, QCP::aeAxes); + applyAntialiasingHint(painter, mAntialiased, QCP::aeAxes); } /*! \internal - + Draws the axis with the specified \a painter, using the internal QCPAxisPainterPrivate instance. \seebaseclassmethod */ void QCPPolarAxisRadial::draw(QCPPainter *painter) { - const double axisAngleRad = (mAngle+(mAngleReference==arAngularAxis ? mAngularAxis->angle() : 0))/180.0*M_PI; - const QPointF axisVector(qCos(axisAngleRad), qSin(axisAngleRad)); // semantically should be QCPVector2D, but we save time in loops when we keep it as QPointF - const QPointF tickNormal = QCPVector2D(axisVector).perpendicular().toPointF(); // semantically should be QCPVector2D, but we save time in loops when we keep it as QPointF - - // draw baseline: - painter->setPen(getBasePen()); - painter->drawLine(QLineF(mCenter, mCenter+axisVector*(mRadius-0.5))); - - // draw subticks: - if (!mSubTickVector.isEmpty()) - { - painter->setPen(getSubTickPen()); - for (int i=0; idrawLine(QLineF(tickPosition-tickNormal*mSubTickLengthIn, tickPosition+tickNormal*mSubTickLengthOut)); + const double axisAngleRad = (mAngle + (mAngleReference == arAngularAxis ? mAngularAxis->angle() : 0)) / 180.0 * M_PI; + const QPointF axisVector(qCos(axisAngleRad), qSin(axisAngleRad)); // semantically should be QCPVector2D, but we save time in loops when we keep it as QPointF + const QPointF tickNormal = QCPVector2D(axisVector).perpendicular().toPointF(); // semantically should be QCPVector2D, but we save time in loops when we keep it as QPointF + + // draw baseline: + painter->setPen(getBasePen()); + painter->drawLine(QLineF(mCenter, mCenter + axisVector * (mRadius - 0.5))); + + // draw subticks: + if (!mSubTickVector.isEmpty()) { + painter->setPen(getSubTickPen()); + for (int i = 0; i < mSubTickVector.size(); ++i) { + const QPointF tickPosition = mCenter + axisVector * coordToRadius(mSubTickVector.at(i)); + painter->drawLine(QLineF(tickPosition - tickNormal * mSubTickLengthIn, tickPosition + tickNormal * mSubTickLengthOut)); + } } - } - - // draw ticks and labels: - if (!mTickVector.isEmpty()) - { - mLabelPainter.setAnchorReference(mCenter-axisVector); // subtract (normalized) axisVector, just to prevent degenerate tangents for tick label at exact lower axis range - mLabelPainter.setFont(getTickLabelFont()); - mLabelPainter.setColor(getTickLabelColor()); - const QPen ticksPen = getTickPen(); - painter->setPen(ticksPen); - for (int i=0; idrawLine(QLineF(tickPosition-tickNormal*mTickLengthIn, tickPosition+tickNormal*mTickLengthOut)); - // possibly draw tick labels: - if (!mTickVectorLabels.isEmpty()) - { - if ((!mRangeReversed && (i < mTickVectorLabels.count()-1 || mRadius-r > 10)) || - (mRangeReversed && (i > 0 || mRadius-r > 10))) // skip last label if it's closer than 10 pixels to angular axis - mLabelPainter.drawTickLabel(painter, tickPosition+tickNormal*mSubTickLengthOut, mTickVectorLabels.at(i)); - } + + // draw ticks and labels: + if (!mTickVector.isEmpty()) { + mLabelPainter.setAnchorReference(mCenter - axisVector); // subtract (normalized) axisVector, just to prevent degenerate tangents for tick label at exact lower axis range + mLabelPainter.setFont(getTickLabelFont()); + mLabelPainter.setColor(getTickLabelColor()); + const QPen ticksPen = getTickPen(); + painter->setPen(ticksPen); + for (int i = 0; i < mTickVector.size(); ++i) { + const double r = coordToRadius(mTickVector.at(i)); + const QPointF tickPosition = mCenter + axisVector * r; + painter->drawLine(QLineF(tickPosition - tickNormal * mTickLengthIn, tickPosition + tickNormal * mTickLengthOut)); + // possibly draw tick labels: + if (!mTickVectorLabels.isEmpty()) { + if ((!mRangeReversed && (i < mTickVectorLabels.count() - 1 || mRadius - r > 10)) || + (mRangeReversed && (i > 0 || mRadius - r > 10))) { // skip last label if it's closer than 10 pixels to angular axis + mLabelPainter.drawTickLabel(painter, tickPosition + tickNormal * mSubTickLengthOut, mTickVectorLabels.at(i)); + } + } + } } - } } /*! \internal - + Prepares the internal tick vector, sub tick vector and tick label vector. This is done by calling QCPAxisTicker::generate on the currently installed ticker. - + 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 QCPPolarAxisRadial::setupTickVectors() { - if (!mParentPlot) return; - if ((!mTicks && !mTickLabels) || mRange.size() <= 0) return; - - mTicker->generate(mRange, mParentPlot->locale(), mNumberFormatChar, mNumberPrecision, mTickVector, mSubTicks ? &mSubTickVector : 0, mTickLabels ? &mTickVectorLabels : 0); + if (!mParentPlot) { + return; + } + if ((!mTicks && !mTickLabels) || mRange.size() <= 0) { + return; + } + + mTicker->generate(mRange, mParentPlot->locale(), mNumberFormatChar, mNumberPrecision, mTickVector, mSubTicks ? &mSubTickVector : 0, mTickLabels ? &mTickVectorLabels : 0); } /*! \internal - + Returns the pen that is used to draw the axis base line. Depending on the selection state, this is either mSelectedBasePen or mBasePen. */ QPen QCPPolarAxisRadial::getBasePen() const { - return mSelectedParts.testFlag(spAxis) ? mSelectedBasePen : mBasePen; + return mSelectedParts.testFlag(spAxis) ? mSelectedBasePen : mBasePen; } /*! \internal - + Returns the pen that is used to draw the (major) ticks. Depending on the selection state, this is either mSelectedTickPen or mTickPen. */ QPen QCPPolarAxisRadial::getTickPen() const { - return mSelectedParts.testFlag(spAxis) ? mSelectedTickPen : mTickPen; + return mSelectedParts.testFlag(spAxis) ? mSelectedTickPen : mTickPen; } /*! \internal - + Returns the pen that is used to draw the subticks. Depending on the selection state, this is either mSelectedSubTickPen or mSubTickPen. */ QPen QCPPolarAxisRadial::getSubTickPen() const { - return mSelectedParts.testFlag(spAxis) ? mSelectedSubTickPen : mSubTickPen; + return mSelectedParts.testFlag(spAxis) ? mSelectedSubTickPen : mSubTickPen; } /*! \internal - + Returns the font that is used to draw the tick labels. Depending on the selection state, this is either mSelectedTickLabelFont or mTickLabelFont. */ QFont QCPPolarAxisRadial::getTickLabelFont() const { - return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelFont : mTickLabelFont; + return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelFont : mTickLabelFont; } /*! \internal - + Returns the font that is used to draw the axis label. Depending on the selection state, this is either mSelectedLabelFont or mLabelFont. */ QFont QCPPolarAxisRadial::getLabelFont() const { - return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelFont : mLabelFont; + return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelFont : mLabelFont; } /*! \internal - + Returns the color that is used to draw the tick labels. Depending on the selection state, this is either mSelectedTickLabelColor or mTickLabelColor. */ QColor QCPPolarAxisRadial::getTickLabelColor() const { - return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelColor : mTickLabelColor; + return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelColor : mTickLabelColor; } /*! \internal - + Returns the color that is used to draw the axis label. Depending on the selection state, this is either mSelectedLabelColor or mLabelColor. */ QColor QCPPolarAxisRadial::getLabelColor() const { - return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelColor : mLabelColor; + return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelColor : mLabelColor; } /* inherits documentation from base class */ QCP::Interaction QCPPolarAxisRadial::selectionCategory() const { - return QCP::iSelectAxes; + return QCP::iSelectAxes; } /* end of 'src/polar/radialaxis.cpp' */ @@ -32451,81 +32815,81 @@ QCP::Interaction QCPPolarAxisRadial::selectionCategory() const /* start documentation of inline functions */ /*! \fn QCPLayoutInset *QCPPolarAxisAngular::insetLayout() const - + Returns the inset layout of this axis rect. It can be used to place other layout elements (or even layouts with multiple other elements) inside/on top of an axis rect. - + \see QCPLayoutInset */ /*! \fn int QCPPolarAxisAngular::left() const - + Returns the pixel position of the left border of this axis rect. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn int QCPPolarAxisAngular::right() const - + Returns the pixel position of the right border of this axis rect. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn int QCPPolarAxisAngular::top() const - + Returns the pixel position of the top border of this axis rect. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn int QCPPolarAxisAngular::bottom() const - + Returns the pixel position of the bottom border of this axis rect. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn int QCPPolarAxisAngular::width() const - + Returns the pixel width of this axis rect. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn int QCPPolarAxisAngular::height() const - + Returns the pixel height of this axis rect. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn QSize QCPPolarAxisAngular::size() const - + Returns the pixel size of this axis rect. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn QPoint QCPPolarAxisAngular::topLeft() const - + Returns the top left corner of this axis rect in pixels. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn QPoint QCPPolarAxisAngular::topRight() const - + Returns the top right corner of this axis rect in pixels. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn QPoint QCPPolarAxisAngular::bottomLeft() const - + Returns the bottom left corner of this axis rect in pixels. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn QPoint QCPPolarAxisAngular::bottomRight() const - + Returns the bottom right corner of this axis rect in pixels. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn QPoint QCPPolarAxisAngular::center() const - + Returns the center of this axis rect in pixels. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ @@ -32537,163 +32901,164 @@ QCP::Interaction QCPPolarAxisRadial::selectionCategory() const sides, the top and right axes are set invisible initially. */ QCPPolarAxisAngular::QCPPolarAxisAngular(QCustomPlot *parentPlot) : - QCPLayoutElement(parentPlot), - mBackgroundBrush(Qt::NoBrush), - mBackgroundScaled(true), - mBackgroundScaledMode(Qt::KeepAspectRatioByExpanding), - mInsetLayout(new QCPLayoutInset), - mRangeDrag(false), - mRangeZoom(false), - mRangeZoomFactor(0.85), - // axis base: - mAngle(-90), - mAngleRad(mAngle/180.0*M_PI), - mSelectableParts(spAxis | spTickLabels | spAxisLabel), - mSelectedParts(spNone), - mBasePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), - mSelectedBasePen(QPen(Qt::blue, 2)), - // axis label: - mLabelPadding(0), - mLabel(), - mLabelFont(mParentPlot->font()), - mSelectedLabelFont(QFont(mLabelFont.family(), mLabelFont.pointSize(), QFont::Bold)), - mLabelColor(Qt::black), - mSelectedLabelColor(Qt::blue), - // tick labels: - //mTickLabelPadding(0), in label painter - mTickLabels(true), - //mTickLabelRotation(0), in label painter - mTickLabelFont(mParentPlot->font()), - mSelectedTickLabelFont(QFont(mTickLabelFont.family(), mTickLabelFont.pointSize(), QFont::Bold)), - mTickLabelColor(Qt::black), - mSelectedTickLabelColor(Qt::blue), - mNumberPrecision(6), - mNumberFormatChar('g'), - mNumberBeautifulPowers(true), - mNumberMultiplyCross(false), - // ticks and subticks: - mTicks(true), - mSubTicks(true), - mTickLengthIn(5), - mTickLengthOut(0), - mSubTickLengthIn(2), - mSubTickLengthOut(0), - mTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), - mSelectedTickPen(QPen(Qt::blue, 2)), - mSubTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), - mSelectedSubTickPen(QPen(Qt::blue, 2)), - // scale and range: - mRange(0, 360), - mRangeReversed(false), - // internal members: - mRadius(1), // non-zero initial value, will be overwritten in ::update() according to inner rect - mGrid(new QCPPolarGrid(this)), - mTicker(new QCPAxisTickerFixed), - mDragging(false), - mLabelPainter(parentPlot) + QCPLayoutElement(parentPlot), + mBackgroundBrush(Qt::NoBrush), + mBackgroundScaled(true), + mBackgroundScaledMode(Qt::KeepAspectRatioByExpanding), + mInsetLayout(new QCPLayoutInset), + mRangeDrag(false), + mRangeZoom(false), + mRangeZoomFactor(0.85), + // axis base: + mAngle(-90), + mAngleRad(mAngle / 180.0 * M_PI), + mSelectableParts(spAxis | spTickLabels | spAxisLabel), + mSelectedParts(spNone), + mBasePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), + mSelectedBasePen(QPen(Qt::blue, 2)), + // axis label: + mLabelPadding(0), + mLabel(), + mLabelFont(mParentPlot->font()), + mSelectedLabelFont(QFont(mLabelFont.family(), mLabelFont.pointSize(), QFont::Bold)), + mLabelColor(Qt::black), + mSelectedLabelColor(Qt::blue), + // tick labels: + //mTickLabelPadding(0), in label painter + mTickLabels(true), + //mTickLabelRotation(0), in label painter + mTickLabelFont(mParentPlot->font()), + mSelectedTickLabelFont(QFont(mTickLabelFont.family(), mTickLabelFont.pointSize(), QFont::Bold)), + mTickLabelColor(Qt::black), + mSelectedTickLabelColor(Qt::blue), + mNumberPrecision(6), + mNumberFormatChar('g'), + mNumberBeautifulPowers(true), + mNumberMultiplyCross(false), + // ticks and subticks: + mTicks(true), + mSubTicks(true), + mTickLengthIn(5), + mTickLengthOut(0), + mSubTickLengthIn(2), + mSubTickLengthOut(0), + mTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), + mSelectedTickPen(QPen(Qt::blue, 2)), + mSubTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), + mSelectedSubTickPen(QPen(Qt::blue, 2)), + // scale and range: + mRange(0, 360), + mRangeReversed(false), + // internal members: + mRadius(1), // non-zero initial value, will be overwritten in ::update() according to inner rect + mGrid(new QCPPolarGrid(this)), + mTicker(new QCPAxisTickerFixed), + mDragging(false), + mLabelPainter(parentPlot) { - // TODO: - //mInsetLayout->initializeParentPlot(mParentPlot); - //mInsetLayout->setParentLayerable(this); - //mInsetLayout->setParent(this); - - if (QCPAxisTickerFixed *fixedTicker = mTicker.dynamicCast().data()) - { - fixedTicker->setTickStep(30); - } - setAntialiased(true); - 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 - - setTickLabelPadding(5); - setTickLabelRotation(0); - setTickLabelMode(lmUpright); - mLabelPainter.setAnchorReferenceType(QCPLabelPainterPrivate::artNormal); - mLabelPainter.setAbbreviateDecimalPowers(false); - mLabelPainter.setCacheSize(24); // so we can cache up to 15-degree intervals, polar angular axis uses a bit larger cache than normal axes - - setMinimumSize(50, 50); - setMinimumMargins(QMargins(30, 30, 30, 30)); - - addRadialAxis(); - mGrid->setRadialAxis(radialAxis()); + // TODO: + //mInsetLayout->initializeParentPlot(mParentPlot); + //mInsetLayout->setParentLayerable(this); + //mInsetLayout->setParent(this); + + if (QCPAxisTickerFixed *fixedTicker = mTicker.dynamicCast().data()) { + fixedTicker->setTickStep(30); + } + setAntialiased(true); + 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 + + setTickLabelPadding(5); + setTickLabelRotation(0); + setTickLabelMode(lmUpright); + mLabelPainter.setAnchorReferenceType(QCPLabelPainterPrivate::artNormal); + mLabelPainter.setAbbreviateDecimalPowers(false); + mLabelPainter.setCacheSize(24); // so we can cache up to 15-degree intervals, polar angular axis uses a bit larger cache than normal axes + + setMinimumSize(50, 50); + setMinimumMargins(QMargins(30, 30, 30, 30)); + + addRadialAxis(); + mGrid->setRadialAxis(radialAxis()); } QCPPolarAxisAngular::~QCPPolarAxisAngular() { - delete mGrid; // delete grid here instead of via parent ~QObject for better defined deletion order - mGrid = 0; - - delete mInsetLayout; - mInsetLayout = 0; - - QList radialAxesList = radialAxes(); - for (int i=0; i radialAxesList = radialAxes(); + for (int i = 0; i < radialAxesList.size(); ++i) { + removeRadialAxis(radialAxesList.at(i)); + } } QCPPolarAxisAngular::LabelMode QCPPolarAxisAngular::tickLabelMode() const { - switch (mLabelPainter.anchorMode()) - { - case QCPLabelPainterPrivate::amSkewedUpright: return lmUpright; - case QCPLabelPainterPrivate::amSkewedRotated: return lmRotated; - default: qDebug() << Q_FUNC_INFO << "invalid mode for polar axis"; break; - } - return lmUpright; + switch (mLabelPainter.anchorMode()) { + case QCPLabelPainterPrivate::amSkewedUpright: + return lmUpright; + case QCPLabelPainterPrivate::amSkewedRotated: + return lmRotated; + default: + qDebug() << Q_FUNC_INFO << "invalid mode for polar axis"; + break; + } + return lmUpright; } /* No documentation as it is a property getter */ QString QCPPolarAxisAngular::numberFormat() const { - QString result; - result.append(mNumberFormatChar); - if (mNumberBeautifulPowers) - { - result.append(QLatin1Char('b')); - if (mLabelPainter.multiplicationSymbol() == QCPLabelPainterPrivate::SymbolCross) - result.append(QLatin1Char('c')); - } - return result; + QString result; + result.append(mNumberFormatChar); + if (mNumberBeautifulPowers) { + result.append(QLatin1Char('b')); + if (mLabelPainter.multiplicationSymbol() == QCPLabelPainterPrivate::SymbolCross) { + result.append(QLatin1Char('c')); + } + } + return result; } /*! Returns the number of axes on the axis rect side specified with \a type. - + \see axis */ int QCPPolarAxisAngular::radialAxisCount() const { - return mRadialAxes.size(); + return mRadialAxes.size(); } /*! Returns the axis with the given \a index on the axis rect side specified with \a type. - + \see axisCount, axes */ QCPPolarAxisRadial *QCPPolarAxisAngular::radialAxis(int index) const { - if (index >= 0 && index < mRadialAxes.size()) - { - return mRadialAxes.at(index); - } else - { - qDebug() << Q_FUNC_INFO << "Axis index out of bounds:" << index; - return 0; - } + if (index >= 0 && index < mRadialAxes.size()) { + return mRadialAxes.at(index); + } else { + qDebug() << Q_FUNC_INFO << "Axis index out of bounds:" << index; + return 0; + } } /*! Returns all axes on the axis rect sides specified with \a types. - + \a types may be a single \ref QCPAxis::AxisType or an or-combination, to get the axes of multiple sides. - + \see axis */ -QList QCPPolarAxisAngular::radialAxes() const +QList QCPPolarAxisAngular::radialAxes() const { - return mRadialAxes; + return mRadialAxes; } @@ -32719,67 +33084,61 @@ QList QCPPolarAxisAngular::radialAxes() const */ QCPPolarAxisRadial *QCPPolarAxisAngular::addRadialAxis(QCPPolarAxisRadial *axis) { - QCPPolarAxisRadial *newAxis = axis; - if (!newAxis) - { - newAxis = new QCPPolarAxisRadial(this); - } else // user provided existing axis instance, do some sanity checks - { - if (newAxis->angularAxis() != this) - { - qDebug() << Q_FUNC_INFO << "passed radial axis doesn't have this angular axis as parent angular axis"; - return 0; + QCPPolarAxisRadial *newAxis = axis; + if (!newAxis) { + newAxis = new QCPPolarAxisRadial(this); + } else { // user provided existing axis instance, do some sanity checks + if (newAxis->angularAxis() != this) { + qDebug() << Q_FUNC_INFO << "passed radial axis doesn't have this angular axis as parent angular axis"; + return 0; + } + if (radialAxes().contains(newAxis)) { + qDebug() << Q_FUNC_INFO << "passed axis is already owned by this angular axis"; + return 0; + } } - if (radialAxes().contains(newAxis)) - { - qDebug() << Q_FUNC_INFO << "passed axis is already owned by this angular axis"; - return 0; - } - } - mRadialAxes.append(newAxis); - return newAxis; + mRadialAxes.append(newAxis); + return newAxis; } /*! Removes the specified \a axis from the axis rect and deletes it. - + Returns true on success, i.e. if \a axis was a valid axis in this axis rect. - + \see addAxis */ bool QCPPolarAxisAngular::removeRadialAxis(QCPPolarAxisRadial *radialAxis) { - if (mRadialAxes.contains(radialAxis)) - { - mRadialAxes.removeOne(radialAxis); - delete radialAxis; - return true; - } else - { - qDebug() << Q_FUNC_INFO << "Radial axis isn't associated with this angular axis:" << reinterpret_cast(radialAxis); - return false; - } + if (mRadialAxes.contains(radialAxis)) { + mRadialAxes.removeOne(radialAxis); + delete radialAxis; + return true; + } else { + qDebug() << Q_FUNC_INFO << "Radial axis isn't associated with this angular axis:" << reinterpret_cast(radialAxis); + return false; + } } QRegion QCPPolarAxisAngular::exactClipRegion() const { - return QRegion(mCenter.x()-mRadius, mCenter.y()-mRadius, qRound(2*mRadius), qRound(2*mRadius), QRegion::Ellipse); + return QRegion(mCenter.x() - mRadius, mCenter.y() - mRadius, qRound(2 * mRadius), qRound(2 * mRadius), QRegion::Ellipse); } /*! If the scale type (\ref setScaleType) is \ref stLinear, \a diff is added to the lower and upper bounds of the range. The range is simply moved by \a diff. - + If the scale type is \ref stLogarithmic, the range bounds are multiplied by \a diff. This corresponds to an apparent "linear" move in logarithmic scaling by a distance of log(diff). */ void QCPPolarAxisAngular::moveRange(double diff) { - QCPRange oldRange = mRange; - mRange.lower += diff; - mRange.upper += diff; - emit rangeChanged(mRange); - emit rangeChanged(mRange, oldRange); + QCPRange oldRange = mRange; + mRange.lower += diff; + mRange.upper += diff; + emit rangeChanged(mRange); + emit rangeChanged(mRange, oldRange); } /*! @@ -32793,7 +33152,7 @@ void QCPPolarAxisAngular::moveRange(double diff) */ void QCPPolarAxisAngular::scaleRange(double factor) { - scaleRange(factor, range().center()); + scaleRange(factor, range().center()); } /*! \overload @@ -32807,55 +33166,55 @@ void QCPPolarAxisAngular::scaleRange(double factor) */ void QCPPolarAxisAngular::scaleRange(double factor, double center) { - QCPRange oldRange = mRange; - QCPRange newRange; - newRange.lower = (mRange.lower-center)*factor + center; - newRange.upper = (mRange.upper-center)*factor + center; - if (QCPRange::validRange(newRange)) - mRange = newRange.sanitizedForLinScale(); - emit rangeChanged(mRange); - emit rangeChanged(mRange, oldRange); + QCPRange oldRange = mRange; + QCPRange newRange; + newRange.lower = (mRange.lower - center) * factor + center; + newRange.upper = (mRange.upper - center) * factor + center; + if (QCPRange::validRange(newRange)) { + mRange = newRange.sanitizedForLinScale(); + } + emit rangeChanged(mRange); + emit rangeChanged(mRange, oldRange); } /*! Changes the axis range such that all plottables associated with this axis are fully visible in that dimension. - + \see QCPAbstractPlottable::rescaleAxes, QCustomPlot::rescaleAxes */ void QCPPolarAxisAngular::rescale(bool onlyVisiblePlottables) { - QCPRange newRange; - bool haveRange = false; - for (int i=0; irealVisibility() && onlyVisiblePlottables) - continue; - QCPRange range; - bool currentFoundRange; - if (mGraphs.at(i)->keyAxis() == this) - range = mGraphs.at(i)->getKeyRange(currentFoundRange, QCP::sdBoth); - else - range = mGraphs.at(i)->getValueRange(currentFoundRange, QCP::sdBoth); - if (currentFoundRange) - { - if (!haveRange) - newRange = range; - else - newRange.expand(range); - haveRange = true; + QCPRange newRange; + bool haveRange = false; + for (int i = 0; i < mGraphs.size(); ++i) { + if (!mGraphs.at(i)->realVisibility() && onlyVisiblePlottables) { + continue; + } + QCPRange range; + bool currentFoundRange; + if (mGraphs.at(i)->keyAxis() == this) { + range = mGraphs.at(i)->getKeyRange(currentFoundRange, QCP::sdBoth); + } else { + range = mGraphs.at(i)->getValueRange(currentFoundRange, QCP::sdBoth); + } + if (currentFoundRange) { + if (!haveRange) { + newRange = range; + } else { + newRange.expand(range); + } + haveRange = true; + } } - } - if (haveRange) - { - if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable - { - double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason - newRange.lower = center-mRange.size()/2.0; - newRange.upper = center+mRange.size()/2.0; + if (haveRange) { + if (!QCPRange::validRange(newRange)) { // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable + double center = (newRange.lower + newRange.upper) * 0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason + newRange.lower = center - mRange.size() / 2.0; + newRange.upper = center + mRange.size() / 2.0; + } + setRange(newRange); } - setRange(newRange); - } } /*! @@ -32863,10 +33222,11 @@ void QCPPolarAxisAngular::rescale(bool onlyVisiblePlottables) */ void QCPPolarAxisAngular::pixelToCoord(QPointF pixelPos, double &angleCoord, double &radiusCoord) const { - if (!mRadialAxes.isEmpty()) - mRadialAxes.first()->pixelToCoord(pixelPos, angleCoord, radiusCoord); - else - qDebug() << Q_FUNC_INFO << "no radial axis configured"; + if (!mRadialAxes.isEmpty()) { + mRadialAxes.first()->pixelToCoord(pixelPos, angleCoord, radiusCoord); + } else { + qDebug() << Q_FUNC_INFO << "no radial axis configured"; + } } /*! @@ -32874,198 +33234,194 @@ void QCPPolarAxisAngular::pixelToCoord(QPointF pixelPos, double &angleCoord, dou */ QPointF QCPPolarAxisAngular::coordToPixel(double angleCoord, double radiusCoord) const { - if (!mRadialAxes.isEmpty()) - { - return mRadialAxes.first()->coordToPixel(angleCoord, radiusCoord); - } else - { - qDebug() << Q_FUNC_INFO << "no radial axis configured"; - return QPointF(); - } + if (!mRadialAxes.isEmpty()) { + return mRadialAxes.first()->coordToPixel(angleCoord, radiusCoord); + } else { + qDebug() << Q_FUNC_INFO << "no radial axis configured"; + return QPointF(); + } } /*! Returns the part of the axis that is hit by \a pos (in pixels). The return value of this function is independent of the user-selectable parts defined with \ref setSelectableParts. Further, this function does not change the current selection state of the axis. - + If the axis is not visible (\ref setVisible), this function always returns \ref spNone. - + \see setSelectedParts, setSelectableParts, QCustomPlot::setInteractions */ QCPPolarAxisAngular::SelectablePart QCPPolarAxisAngular::getPartAt(const QPointF &pos) const { - Q_UNUSED(pos) // TODO remove later - - if (!mVisible) - return spNone; - - /* + Q_UNUSED(pos) // TODO remove later + + if (!mVisible) { + return spNone; + } + + /* TODO: - if (mAxisPainter->axisSelectionBox().contains(pos.toPoint())) + if (mAxisPainter->axisSelectionBox().contains(pos.toPoint())) return spAxis; - else if (mAxisPainter->tickLabelsSelectionBox().contains(pos.toPoint())) + else if (mAxisPainter->tickLabelsSelectionBox().contains(pos.toPoint())) return spTickLabels; - else if (mAxisPainter->labelSelectionBox().contains(pos.toPoint())) + else if (mAxisPainter->labelSelectionBox().contains(pos.toPoint())) return spAxisLabel; - else */ + else */ return spNone; } /* inherits documentation from base class */ double QCPPolarAxisAngular::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { - /* - if (!mParentPlot) return -1; - SelectablePart part = getPartAt(pos); - if ((onlySelectable && !mSelectableParts.testFlag(part)) || part == spNone) + /* + if (!mParentPlot) return -1; + SelectablePart part = getPartAt(pos); + if ((onlySelectable && !mSelectableParts.testFlag(part)) || part == spNone) return -1; - - if (details) + + if (details) details->setValue(part); - return mParentPlot->selectionTolerance()*0.99; - */ - - Q_UNUSED(details) - - if (onlySelectable) - return -1; - - if (QRectF(mOuterRect).contains(pos)) - { - if (mParentPlot) - return mParentPlot->selectionTolerance()*0.99; - else - { - qDebug() << Q_FUNC_INFO << "parent plot not defined"; - return -1; + return mParentPlot->selectionTolerance()*0.99; + */ + + Q_UNUSED(details) + + if (onlySelectable) { + return -1; + } + + if (QRectF(mOuterRect).contains(pos)) { + if (mParentPlot) { + return mParentPlot->selectionTolerance() * 0.99; + } else { + qDebug() << Q_FUNC_INFO << "parent plot not defined"; + return -1; + } + } else { + return -1; } - } else - return -1; } /*! This method is called automatically upon replot and doesn't need to be called by users of QCPPolarAxisAngular. - + 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 QCPPolarAxisAngular::update(UpdatePhase phase) { - QCPLayoutElement::update(phase); - - switch (phase) - { - case upPreparation: - { - setupTickVectors(); - for (int i=0; isetupTickVectors(); - break; + QCPLayoutElement::update(phase); + + switch (phase) { + case upPreparation: { + setupTickVectors(); + for (int i = 0; i < mRadialAxes.size(); ++i) { + mRadialAxes.at(i)->setupTickVectors(); + } + break; + } + case upLayout: { + mCenter = mRect.center(); + mRadius = 0.5 * qMin(qAbs(mRect.width()), qAbs(mRect.height())); + if (mRadius < 1) { + mRadius = 1; // prevent cases where radius might become 0 which causes trouble + } + for (int i = 0; i < mRadialAxes.size(); ++i) { + mRadialAxes.at(i)->updateGeometry(mCenter, mRadius); + } + + mInsetLayout->setOuterRect(rect()); + break; + } + default: + break; } - case upLayout: - { - mCenter = mRect.center(); - mRadius = 0.5*qMin(qAbs(mRect.width()), qAbs(mRect.height())); - if (mRadius < 1) mRadius = 1; // prevent cases where radius might become 0 which causes trouble - for (int i=0; iupdateGeometry(mCenter, mRadius); - - mInsetLayout->setOuterRect(rect()); - break; - } - default: break; - } - - // pass update call on to inset layout (doesn't happen automatically, because QCPPolarAxis doesn't derive from QCPLayout): - mInsetLayout->update(phase); + + // pass update call on to inset layout (doesn't happen automatically, because QCPPolarAxis doesn't derive from QCPLayout): + mInsetLayout->update(phase); } /* inherits documentation from base class */ -QList QCPPolarAxisAngular::elements(bool recursive) const +QList QCPPolarAxisAngular::elements(bool recursive) const { - QList result; - if (mInsetLayout) - { - result << mInsetLayout; - if (recursive) - result << mInsetLayout->elements(recursive); - } - return result; + QList result; + if (mInsetLayout) { + result << mInsetLayout; + if (recursive) { + result << mInsetLayout->elements(recursive); + } + } + return result; } bool QCPPolarAxisAngular::removeGraph(QCPPolarGraph *graph) { - if (!mGraphs.contains(graph)) - { - qDebug() << Q_FUNC_INFO << "graph not in list:" << reinterpret_cast(graph); - return false; - } - - // remove plottable from legend: - graph->removeFromLegend(); - // remove plottable: - delete graph; - mGraphs.removeOne(graph); - return true; + if (!mGraphs.contains(graph)) { + qDebug() << Q_FUNC_INFO << "graph not in list:" << reinterpret_cast(graph); + return false; + } + + // remove plottable from legend: + graph->removeFromLegend(); + // remove plottable: + delete graph; + mGraphs.removeOne(graph); + return true; } /* inherits documentation from base class */ void QCPPolarAxisAngular::applyDefaultAntialiasingHint(QCPPainter *painter) const { - applyAntialiasingHint(painter, mAntialiased, QCP::aeAxes); + applyAntialiasingHint(painter, mAntialiased, QCP::aeAxes); } /* inherits documentation from base class */ void QCPPolarAxisAngular::draw(QCPPainter *painter) { - drawBackground(painter, mCenter, mRadius); - - // draw baseline circle: - painter->setPen(getBasePen()); - painter->drawEllipse(mCenter, mRadius, mRadius); - - // draw subticks: - if (!mSubTickVector.isEmpty()) - { - painter->setPen(getSubTickPen()); - for (int i=0; idrawLine(mCenter+mSubTickVectorCosSin.at(i)*(mRadius-mSubTickLengthIn), - mCenter+mSubTickVectorCosSin.at(i)*(mRadius+mSubTickLengthOut)); + drawBackground(painter, mCenter, mRadius); + + // draw baseline circle: + painter->setPen(getBasePen()); + painter->drawEllipse(mCenter, mRadius, mRadius); + + // draw subticks: + if (!mSubTickVector.isEmpty()) { + painter->setPen(getSubTickPen()); + for (int i = 0; i < mSubTickVector.size(); ++i) { + painter->drawLine(mCenter + mSubTickVectorCosSin.at(i) * (mRadius - mSubTickLengthIn), + mCenter + mSubTickVectorCosSin.at(i) * (mRadius + mSubTickLengthOut)); + } } - } - - // draw ticks and labels: - if (!mTickVector.isEmpty()) - { - mLabelPainter.setAnchorReference(mCenter); - mLabelPainter.setFont(getTickLabelFont()); - mLabelPainter.setColor(getTickLabelColor()); - const QPen ticksPen = getTickPen(); - painter->setPen(ticksPen); - for (int i=0; idrawLine(mCenter+mTickVectorCosSin.at(i)*(mRadius-mTickLengthIn), outerTick); - // draw tick labels: - if (!mTickVectorLabels.isEmpty()) - { - if (i < mTickVectorLabels.count()-1 || (mTickVectorCosSin.at(i)-mTickVectorCosSin.first()).manhattanLength() > 5/180.0*M_PI) // skip last label if it's closer than approx 5 degrees to first - mLabelPainter.drawTickLabel(painter, outerTick, mTickVectorLabels.at(i)); - } + + // draw ticks and labels: + if (!mTickVector.isEmpty()) { + mLabelPainter.setAnchorReference(mCenter); + mLabelPainter.setFont(getTickLabelFont()); + mLabelPainter.setColor(getTickLabelColor()); + const QPen ticksPen = getTickPen(); + painter->setPen(ticksPen); + for (int i = 0; i < mTickVector.size(); ++i) { + const QPointF outerTick = mCenter + mTickVectorCosSin.at(i) * (mRadius + mTickLengthOut); + painter->drawLine(mCenter + mTickVectorCosSin.at(i) * (mRadius - mTickLengthIn), outerTick); + // draw tick labels: + if (!mTickVectorLabels.isEmpty()) { + if (i < mTickVectorLabels.count() - 1 || (mTickVectorCosSin.at(i) - mTickVectorCosSin.first()).manhattanLength() > 5 / 180.0 * M_PI) { // skip last label if it's closer than approx 5 degrees to first + mLabelPainter.drawTickLabel(painter, outerTick, mTickVectorLabels.at(i)); + } + } + } } - } } /* inherits documentation from base class */ QCP::Interaction QCPPolarAxisAngular::selectionCategory() const { - return QCP::iSelectAxes; + return QCP::iSelectAxes; } @@ -33081,17 +33437,17 @@ QCP::Interaction QCPPolarAxisAngular::selectionCategory() const Below the pixmap, the axis rect may be optionally filled with a brush, if specified with \ref setBackground(const QBrush &brush). - + \see setBackgroundScaled, setBackgroundScaledMode, setBackground(const QBrush &brush) */ void QCPPolarAxisAngular::setBackground(const QPixmap &pm) { - mBackgroundPixmap = pm; - mScaledBackgroundPixmap = QPixmap(); + mBackgroundPixmap = pm; + mScaledBackgroundPixmap = QPixmap(); } /*! \overload - + Sets \a brush as the background brush. The axis rect background will be filled with this brush. Since axis rects place themselves on the "background" layer by default, the axis rect backgrounds are usually drawn below everything else. @@ -33100,16 +33456,16 @@ void QCPPolarAxisAngular::setBackground(const QPixmap &pm) setBackground(const QPixmap &pm). To disable drawing of a background brush, set \a brush to Qt::NoBrush. - + \see setBackground(const QPixmap &pm) */ void QCPPolarAxisAngular::setBackground(const QBrush &brush) { - mBackgroundBrush = brush; + mBackgroundBrush = brush; } /*! \overload - + Allows setting the background pixmap of the axis rect, whether it shall be scaled and how it shall be scaled in one call. @@ -33117,25 +33473,25 @@ void QCPPolarAxisAngular::setBackground(const QBrush &brush) */ void QCPPolarAxisAngular::setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode) { - mBackgroundPixmap = pm; - mScaledBackgroundPixmap = QPixmap(); - mBackgroundScaled = scaled; - mBackgroundScaledMode = mode; + mBackgroundPixmap = pm; + mScaledBackgroundPixmap = QPixmap(); + mBackgroundScaled = scaled; + mBackgroundScaledMode = mode; } /*! Sets whether the axis background pixmap shall be scaled to fit the axis rect or not. If \a scaled is set to true, you may control whether and how the aspect ratio of the original pixmap is preserved with \ref setBackgroundScaledMode. - + Note that the scaled version of the original pixmap is buffered, so there is no performance penalty on replots. (Except when the axis rect dimensions are changed continuously.) - + \see setBackground, setBackgroundScaledMode */ void QCPPolarAxisAngular::setBackgroundScaled(bool scaled) { - mBackgroundScaled = scaled; + mBackgroundScaled = scaled; } /*! @@ -33145,22 +33501,22 @@ void QCPPolarAxisAngular::setBackgroundScaled(bool scaled) */ void QCPPolarAxisAngular::setBackgroundScaledMode(Qt::AspectRatioMode mode) { - mBackgroundScaledMode = mode; + mBackgroundScaledMode = mode; } void QCPPolarAxisAngular::setRangeDrag(bool enabled) { - mRangeDrag = enabled; + mRangeDrag = enabled; } void QCPPolarAxisAngular::setRangeZoom(bool enabled) { - mRangeZoom = enabled; + mRangeZoom = enabled; } void QCPPolarAxisAngular::setRangeZoomFactor(double factor) { - mRangeZoomFactor = factor; + mRangeZoomFactor = factor; } @@ -33171,95 +33527,99 @@ void QCPPolarAxisAngular::setRangeZoomFactor(double factor) /*! Sets the range of the axis. - + This slot may be connected with the \ref rangeChanged signal of another axis so this axis is always synchronized with the other axis range, when it changes. - + To invert the direction of an axis, use \ref setRangeReversed. */ void QCPPolarAxisAngular::setRange(const QCPRange &range) { - if (range.lower == mRange.lower && range.upper == mRange.upper) - return; - - if (!QCPRange::validRange(range)) return; - QCPRange oldRange = mRange; - mRange = range.sanitizedForLinScale(); - emit rangeChanged(mRange); - emit rangeChanged(mRange, oldRange); + if (range.lower == mRange.lower && range.upper == mRange.upper) { + return; + } + + if (!QCPRange::validRange(range)) { + return; + } + QCPRange oldRange = mRange; + mRange = range.sanitizedForLinScale(); + emit rangeChanged(mRange); + emit rangeChanged(mRange, oldRange); } /*! Sets whether the user can (de-)select the parts in \a selectable by clicking on the QCustomPlot surface. (When \ref QCustomPlot::setInteractions contains iSelectAxes.) - + However, even when \a selectable is set to a value not allowing the selection of a specific part, it is still possible to set the selection of this part manually, by calling \ref setSelectedParts directly. - + \see SelectablePart, setSelectedParts */ void QCPPolarAxisAngular::setSelectableParts(const SelectableParts &selectable) { - if (mSelectableParts != selectable) - { - mSelectableParts = selectable; - emit selectableChanged(mSelectableParts); - } + if (mSelectableParts != selectable) { + mSelectableParts = selectable; + emit selectableChanged(mSelectableParts); + } } /*! Sets the selected state of the respective axis parts described by \ref SelectablePart. When a part is selected, it uses a different pen/font. - + The entire selection mechanism for axes is handled automatically when \ref QCustomPlot::setInteractions contains iSelectAxes. You only need to call this function when you wish to change the selection state manually. - + This function can change the selection state of a part, independent of the \ref setSelectableParts setting. - + emits the \ref selectionChanged signal when \a selected is different from the previous selection state. - + \see SelectablePart, setSelectableParts, selectTest, setSelectedBasePen, setSelectedTickPen, setSelectedSubTickPen, setSelectedTickLabelFont, setSelectedLabelFont, setSelectedTickLabelColor, setSelectedLabelColor */ void QCPPolarAxisAngular::setSelectedParts(const SelectableParts &selected) { - if (mSelectedParts != selected) - { - mSelectedParts = selected; - emit selectionChanged(mSelectedParts); - } + if (mSelectedParts != selected) { + mSelectedParts = selected; + emit selectionChanged(mSelectedParts); + } } /*! \overload - + Sets the lower and upper bound of the axis range. - + To invert the direction of an axis, use \ref setRangeReversed. - + There is also a slot to set a range, see \ref setRange(const QCPRange &range). */ void QCPPolarAxisAngular::setRange(double lower, double upper) { - if (lower == mRange.lower && upper == mRange.upper) - return; - - if (!QCPRange::validRange(lower, upper)) return; - QCPRange oldRange = mRange; - mRange.lower = lower; - mRange.upper = upper; - mRange = mRange.sanitizedForLinScale(); - emit rangeChanged(mRange); - emit rangeChanged(mRange, oldRange); + if (lower == mRange.lower && upper == mRange.upper) { + return; + } + + if (!QCPRange::validRange(lower, upper)) { + return; + } + QCPRange oldRange = mRange; + mRange.lower = lower; + mRange.upper = upper; + mRange = mRange.sanitizedForLinScale(); + emit rangeChanged(mRange); + emit rangeChanged(mRange, oldRange); } /*! \overload - + Sets the range of the axis. - + The \a position coordinate indicates together with the \a alignment parameter, where the new range will be positioned. \a size defines the size of the new axis range. \a alignment may be Qt::AlignLeft, Qt::AlignRight or Qt::AlignCenter. This will cause the left border, right border, @@ -33268,12 +33628,13 @@ void QCPPolarAxisAngular::setRange(double lower, double upper) */ void QCPPolarAxisAngular::setRange(double position, double size, Qt::AlignmentFlag alignment) { - if (alignment == Qt::AlignLeft) - setRange(position, position+size); - else if (alignment == Qt::AlignRight) - setRange(position-size, position); - else // alignment == Qt::AlignCenter - setRange(position-size/2.0, position+size/2.0); + if (alignment == Qt::AlignLeft) { + setRange(position, position + size); + } else if (alignment == Qt::AlignRight) { + setRange(position - size, position); + } else { // alignment == Qt::AlignCenter + setRange(position - size / 2.0, position + size / 2.0); + } } /*! @@ -33282,14 +33643,15 @@ void QCPPolarAxisAngular::setRange(double position, double size, Qt::AlignmentFl */ void QCPPolarAxisAngular::setRangeLower(double lower) { - if (mRange.lower == lower) - return; - - QCPRange oldRange = mRange; - mRange.lower = lower; - mRange = mRange.sanitizedForLinScale(); - emit rangeChanged(mRange); - emit rangeChanged(mRange, oldRange); + if (mRange.lower == lower) { + return; + } + + QCPRange oldRange = mRange; + mRange.lower = lower; + mRange = mRange.sanitizedForLinScale(); + emit rangeChanged(mRange); + emit rangeChanged(mRange, oldRange); } /*! @@ -33298,14 +33660,15 @@ void QCPPolarAxisAngular::setRangeLower(double lower) */ void QCPPolarAxisAngular::setRangeUpper(double upper) { - if (mRange.upper == upper) - return; - - QCPRange oldRange = mRange; - mRange.upper = upper; - mRange = mRange.sanitizedForLinScale(); - emit rangeChanged(mRange); - emit rangeChanged(mRange, oldRange); + if (mRange.upper == upper) { + return; + } + + QCPRange oldRange = mRange; + mRange.upper = upper; + mRange = mRange.sanitizedForLinScale(); + emit rangeChanged(mRange); + emit rangeChanged(mRange, oldRange); } /*! @@ -33319,35 +33682,36 @@ void QCPPolarAxisAngular::setRangeUpper(double upper) */ void QCPPolarAxisAngular::setRangeReversed(bool reversed) { - mRangeReversed = reversed; + mRangeReversed = reversed; } void QCPPolarAxisAngular::setAngle(double degrees) { - mAngle = degrees; - mAngleRad = mAngle/180.0*M_PI; + mAngle = degrees; + mAngleRad = mAngle / 180.0 * M_PI; } /*! 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. - + 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. - + 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 ticker */ void QCPPolarAxisAngular::setTicker(QSharedPointer ticker) { - 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 + 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 } /*! @@ -33355,16 +33719,15 @@ void QCPPolarAxisAngular::setTicker(QSharedPointer ticker) 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 QCPPolarAxisAngular::setTicks(bool show) { - if (mTicks != show) - { - mTicks = show; - //mCachedMarginValid = false; - } + if (mTicks != show) { + mTicks = show; + //mCachedMarginValid = false; + } } /*! @@ -33372,13 +33735,13 @@ void QCPPolarAxisAngular::setTicks(bool show) */ void QCPPolarAxisAngular::setTickLabels(bool show) { - if (mTickLabels != show) - { - mTickLabels = show; - //mCachedMarginValid = false; - if (!mTickLabels) - mTickVectorLabels.clear(); - } + if (mTickLabels != show) { + mTickLabels = show; + //mCachedMarginValid = false; + if (!mTickLabels) { + mTickVectorLabels.clear(); + } + } } /*! @@ -33387,61 +33750,64 @@ void QCPPolarAxisAngular::setTickLabels(bool show) */ void QCPPolarAxisAngular::setTickLabelPadding(int padding) { - mLabelPainter.setPadding(padding); + mLabelPainter.setPadding(padding); } /*! Sets the font of the tick labels. - + \see setTickLabels, setTickLabelColor */ void QCPPolarAxisAngular::setTickLabelFont(const QFont &font) { - mTickLabelFont = font; + mTickLabelFont = font; } /*! Sets the color of the tick labels. - + \see setTickLabels, setTickLabelFont */ void QCPPolarAxisAngular::setTickLabelColor(const QColor &color) { - mTickLabelColor = color; + mTickLabelColor = color; } /*! Sets the rotation of the tick labels. If \a degrees is zero, the labels are drawn normally. Else, the tick labels are drawn rotated by \a degrees clockwise. The specified angle is bound to values from -90 to 90 degrees. - + If \a degrees is exactly -90, 0 or 90, the tick labels are centered on the tick coordinate. For other angles, the label is drawn with an offset such that it seems to point toward or away from the tick mark. */ void QCPPolarAxisAngular::setTickLabelRotation(double degrees) { - mLabelPainter.setRotation(degrees); + mLabelPainter.setRotation(degrees); } void QCPPolarAxisAngular::setTickLabelMode(LabelMode mode) { - switch (mode) - { - case lmUpright: mLabelPainter.setAnchorMode(QCPLabelPainterPrivate::amSkewedUpright); break; - case lmRotated: mLabelPainter.setAnchorMode(QCPLabelPainterPrivate::amSkewedRotated); break; - } + switch (mode) { + case lmUpright: + mLabelPainter.setAnchorMode(QCPLabelPainterPrivate::amSkewedUpright); + break; + case lmRotated: + mLabelPainter.setAnchorMode(QCPLabelPainterPrivate::amSkewedRotated); + break; + } } /*! 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. - + \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. "5.5e9", which might be visually unappealing in a plot. So when the second char of \a formatCode is set to 'b' (for @@ -33450,7 +33816,7 @@ void QCPPolarAxisAngular::setTickLabelMode(LabelMode mode) If instead a cross should be shown (as is usual in the USA), the third char of \a formatCode can be set to 'c'. The inserted multiplication signs are the UTF-8 characters 215 (0xD7) for the cross and 183 (0xB7) for the dot. - + 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 @@ -33465,52 +33831,47 @@ void QCPPolarAxisAngular::setTickLabelMode(LabelMode mode) */ void QCPPolarAxisAngular::setNumberFormat(const QString &formatCode) { - if (formatCode.isEmpty()) - { - qDebug() << Q_FUNC_INFO << "Passed formatCode is empty"; - return; - } - //mCachedMarginValid = false; - - // interpret first char as number format char: - QString allowedFormatChars(QLatin1String("eEfgG")); - if (allowedFormatChars.contains(formatCode.at(0))) - { - mNumberFormatChar = QLatin1Char(formatCode.at(0).toLatin1()); - } else - { - qDebug() << Q_FUNC_INFO << "Invalid number format code (first char not in 'eEfgG'):" << formatCode; - return; - } - - if (formatCode.length() < 2) - { - mNumberBeautifulPowers = false; - mNumberMultiplyCross = false; - } else - { - // interpret second char as indicator for beautiful decimal powers: - if (formatCode.at(1) == QLatin1Char('b') && (mNumberFormatChar == QLatin1Char('e') || mNumberFormatChar == QLatin1Char('g'))) - mNumberBeautifulPowers = true; - else - qDebug() << Q_FUNC_INFO << "Invalid number format code (second char not 'b' or first char neither 'e' nor 'g'):" << formatCode; - - if (formatCode.length() < 3) - { - mNumberMultiplyCross = false; - } else - { - // interpret third char as indicator for dot or cross multiplication symbol: - if (formatCode.at(2) == QLatin1Char('c')) - mNumberMultiplyCross = true; - else if (formatCode.at(2) == QLatin1Char('d')) - mNumberMultiplyCross = false; - else - qDebug() << Q_FUNC_INFO << "Invalid number format code (third char neither 'c' nor 'd'):" << formatCode; + if (formatCode.isEmpty()) { + qDebug() << Q_FUNC_INFO << "Passed formatCode is empty"; + return; } - } - mLabelPainter.setSubstituteExponent(mNumberBeautifulPowers); - mLabelPainter.setMultiplicationSymbol(mNumberMultiplyCross ? QCPLabelPainterPrivate::SymbolCross : QCPLabelPainterPrivate::SymbolDot); + //mCachedMarginValid = false; + + // interpret first char as number format char: + QString allowedFormatChars(QLatin1String("eEfgG")); + if (allowedFormatChars.contains(formatCode.at(0))) { + mNumberFormatChar = QLatin1Char(formatCode.at(0).toLatin1()); + } else { + qDebug() << Q_FUNC_INFO << "Invalid number format code (first char not in 'eEfgG'):" << formatCode; + return; + } + + if (formatCode.length() < 2) { + mNumberBeautifulPowers = false; + mNumberMultiplyCross = false; + } else { + // interpret second char as indicator for beautiful decimal powers: + if (formatCode.at(1) == QLatin1Char('b') && (mNumberFormatChar == QLatin1Char('e') || mNumberFormatChar == QLatin1Char('g'))) { + mNumberBeautifulPowers = true; + } else { + qDebug() << Q_FUNC_INFO << "Invalid number format code (second char not 'b' or first char neither 'e' nor 'g'):" << formatCode; + } + + if (formatCode.length() < 3) { + mNumberMultiplyCross = false; + } else { + // interpret third char as indicator for dot or cross multiplication symbol: + if (formatCode.at(2) == QLatin1Char('c')) { + mNumberMultiplyCross = true; + } else if (formatCode.at(2) == QLatin1Char('d')) { + mNumberMultiplyCross = false; + } else { + qDebug() << Q_FUNC_INFO << "Invalid number format code (third char neither 'c' nor 'd'):" << formatCode; + } + } + } + mLabelPainter.setSubstituteExponent(mNumberBeautifulPowers); + mLabelPainter.setMultiplicationSymbol(mNumberMultiplyCross ? QCPLabelPainterPrivate::SymbolCross : QCPLabelPainterPrivate::SymbolDot); } /*! @@ -33520,11 +33881,10 @@ void QCPPolarAxisAngular::setNumberFormat(const QString &formatCode) */ void QCPPolarAxisAngular::setNumberPrecision(int precision) { - if (mNumberPrecision != precision) - { - mNumberPrecision = precision; - //mCachedMarginValid = false; - } + if (mNumberPrecision != precision) { + mNumberPrecision = precision; + //mCachedMarginValid = false; + } } /*! @@ -33532,59 +33892,56 @@ void QCPPolarAxisAngular::setNumberPrecision(int precision) plot and \a outside is the length they will reach outside the plot. If \a outside is greater than zero, the tick labels and axis label will increase their distance to the axis accordingly, so they won't collide with the ticks. - + \see setSubTickLength, setTickLengthIn, setTickLengthOut */ void QCPPolarAxisAngular::setTickLength(int inside, int outside) { - setTickLengthIn(inside); - setTickLengthOut(outside); + setTickLengthIn(inside); + setTickLengthOut(outside); } /*! Sets the length of the inward ticks in pixels. \a inside is the length the ticks will reach inside the plot. - + \see setTickLengthOut, setTickLength, setSubTickLength */ void QCPPolarAxisAngular::setTickLengthIn(int inside) { - if (mTickLengthIn != inside) - { - mTickLengthIn = inside; - } + if (mTickLengthIn != inside) { + mTickLengthIn = inside; + } } /*! Sets the length of the outward ticks in pixels. \a outside is the length the ticks will reach outside the plot. If \a outside is greater than zero, the tick labels and axis label will increase their distance to the axis accordingly, so they won't collide with the ticks. - + \see setTickLengthIn, setTickLength, setSubTickLength */ void QCPPolarAxisAngular::setTickLengthOut(int outside) { - if (mTickLengthOut != outside) - { - mTickLengthOut = outside; - //mCachedMarginValid = false; // only outside tick length can change margin - } + if (mTickLengthOut != outside) { + mTickLengthOut = outside; + //mCachedMarginValid = false; // only outside tick length can change margin + } } /*! Sets whether sub tick marks are displayed. - + Sub ticks are only potentially visible if (major) ticks are also visible (see \ref setTicks) - + \see setTicks */ void QCPPolarAxisAngular::setSubTicks(bool show) { - if (mSubTicks != show) - { - mSubTicks = show; - //mCachedMarginValid = false; - } + if (mSubTicks != show) { + mSubTicks = show; + //mCachedMarginValid = false; + } } /*! @@ -33592,97 +33949,94 @@ void QCPPolarAxisAngular::setSubTicks(bool show) the plot and \a outside is the length they will reach outside the plot. If \a outside is greater than zero, the tick labels and axis label will increase their distance to the axis accordingly, so they won't collide with the ticks. - + \see setTickLength, setSubTickLengthIn, setSubTickLengthOut */ void QCPPolarAxisAngular::setSubTickLength(int inside, int outside) { - setSubTickLengthIn(inside); - setSubTickLengthOut(outside); + setSubTickLengthIn(inside); + setSubTickLengthOut(outside); } /*! Sets the length of the inward subticks in pixels. \a inside is the length the subticks will reach inside the plot. - + \see setSubTickLengthOut, setSubTickLength, setTickLength */ void QCPPolarAxisAngular::setSubTickLengthIn(int inside) { - if (mSubTickLengthIn != inside) - { - mSubTickLengthIn = inside; - } + if (mSubTickLengthIn != inside) { + mSubTickLengthIn = inside; + } } /*! Sets the length of the outward subticks in pixels. \a outside is the length the subticks will reach outside the plot. If \a outside is greater than zero, the tick labels will increase their distance to the axis accordingly, so they won't collide with the ticks. - + \see setSubTickLengthIn, setSubTickLength, setTickLength */ void QCPPolarAxisAngular::setSubTickLengthOut(int outside) { - if (mSubTickLengthOut != outside) - { - mSubTickLengthOut = outside; - //mCachedMarginValid = false; // only outside tick length can change margin - } + if (mSubTickLengthOut != outside) { + mSubTickLengthOut = outside; + //mCachedMarginValid = false; // only outside tick length can change margin + } } /*! Sets the pen, the axis base line is drawn with. - + \see setTickPen, setSubTickPen */ void QCPPolarAxisAngular::setBasePen(const QPen &pen) { - mBasePen = pen; + mBasePen = pen; } /*! Sets the pen, tick marks will be drawn with. - + \see setTickLength, setBasePen */ void QCPPolarAxisAngular::setTickPen(const QPen &pen) { - mTickPen = pen; + mTickPen = pen; } /*! Sets the pen, subtick marks will be drawn with. - + \see setSubTickCount, setSubTickLength, setBasePen */ void QCPPolarAxisAngular::setSubTickPen(const QPen &pen) { - mSubTickPen = pen; + mSubTickPen = pen; } /*! Sets the font of the axis label. - + \see setLabelColor */ void QCPPolarAxisAngular::setLabelFont(const QFont &font) { - if (mLabelFont != font) - { - mLabelFont = font; - //mCachedMarginValid = false; - } + if (mLabelFont != font) { + mLabelFont = font; + //mCachedMarginValid = false; + } } /*! Sets the color of the axis label. - + \see setLabelFont */ void QCPPolarAxisAngular::setLabelColor(const QColor &color) { - mLabelColor = color; + mLabelColor = color; } /*! @@ -33691,113 +34045,109 @@ void QCPPolarAxisAngular::setLabelColor(const QColor &color) */ void QCPPolarAxisAngular::setLabel(const QString &str) { - if (mLabel != str) - { - mLabel = str; - //mCachedMarginValid = false; - } + if (mLabel != str) { + mLabel = str; + //mCachedMarginValid = false; + } } /*! Sets the distance between the tick labels and the axis label. - + \see setTickLabelPadding, setPadding */ void QCPPolarAxisAngular::setLabelPadding(int padding) { - if (mLabelPadding != padding) - { - mLabelPadding = padding; - //mCachedMarginValid = false; - } + if (mLabelPadding != padding) { + mLabelPadding = padding; + //mCachedMarginValid = false; + } } /*! Sets the font that is used for tick labels when they are selected. - + \see setTickLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPPolarAxisAngular::setSelectedTickLabelFont(const QFont &font) { - if (font != mSelectedTickLabelFont) - { - mSelectedTickLabelFont = font; - // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts - } + if (font != mSelectedTickLabelFont) { + mSelectedTickLabelFont = font; + // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts + } } /*! Sets the font that is used for the axis label when it is selected. - + \see setLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPPolarAxisAngular::setSelectedLabelFont(const QFont &font) { - mSelectedLabelFont = font; - // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts + mSelectedLabelFont = font; + // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts } /*! Sets the color that is used for tick labels when they are selected. - + \see setTickLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPPolarAxisAngular::setSelectedTickLabelColor(const QColor &color) { - if (color != mSelectedTickLabelColor) - { - mSelectedTickLabelColor = color; - } + if (color != mSelectedTickLabelColor) { + mSelectedTickLabelColor = color; + } } /*! Sets the color that is used for the axis label when it is selected. - + \see setLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPPolarAxisAngular::setSelectedLabelColor(const QColor &color) { - mSelectedLabelColor = color; + mSelectedLabelColor = color; } /*! Sets the pen that is used to draw the axis base line when selected. - + \see setBasePen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPPolarAxisAngular::setSelectedBasePen(const QPen &pen) { - mSelectedBasePen = pen; + mSelectedBasePen = pen; } /*! Sets the pen that is used to draw the (major) ticks when selected. - + \see setTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPPolarAxisAngular::setSelectedTickPen(const QPen &pen) { - mSelectedTickPen = pen; + mSelectedTickPen = pen; } /*! Sets the pen that is used to draw the subticks when selected. - + \see setSubTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPPolarAxisAngular::setSelectedSubTickPen(const QPen &pen) { - mSelectedSubTickPen = pen; + mSelectedSubTickPen = pen; } /*! \internal - + Draws the background of this axis rect. It may consist of a background fill (a QBrush) and a pixmap. - + If a brush was given via \ref setBackground(const QBrush &brush), this function first draws an according filling inside the axis rect with the provided \a painter. - + Then, if a pixmap was provided via \ref setBackground, this function buffers the scaled version depending on \ref setBackgroundScaled and \ref setBackgroundScaledMode and then draws it inside the axis rect with the provided \a painter. The scaled version is buffered in @@ -33805,255 +34155,246 @@ void QCPPolarAxisAngular::setSelectedSubTickPen(const QPen &pen) the axis rect has changed in a way that requires a rescale of the background pixmap (this is dependent on the \ref setBackgroundScaledMode), or when a differend axis background pixmap was set. - + \see setBackground, setBackgroundScaled, setBackgroundScaledMode */ void QCPPolarAxisAngular::drawBackground(QCPPainter *painter, const QPointF ¢er, double radius) { - // draw background fill (don't use circular clip, looks bad): - if (mBackgroundBrush != Qt::NoBrush) - { - QPainterPath ellipsePath; - ellipsePath.addEllipse(center, radius, radius); - painter->fillPath(ellipsePath, mBackgroundBrush); - } - - // draw background pixmap (on top of fill, if brush specified): - if (!mBackgroundPixmap.isNull()) - { - QRegion clipCircle(center.x()-radius, center.y()-radius, qRound(2*radius), qRound(2*radius), QRegion::Ellipse); - QRegion originalClip = painter->clipRegion(); - painter->setClipRegion(clipCircle); - if (mBackgroundScaled) - { - // check whether mScaledBackground needs to be updated: - QSize scaledSize(mBackgroundPixmap.size()); - scaledSize.scale(mRect.size(), mBackgroundScaledMode); - if (mScaledBackgroundPixmap.size() != scaledSize) - mScaledBackgroundPixmap = mBackgroundPixmap.scaled(mRect.size(), mBackgroundScaledMode, Qt::SmoothTransformation); - painter->drawPixmap(mRect.topLeft()+QPoint(0, -1), mScaledBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height()) & mScaledBackgroundPixmap.rect()); - } else - { - painter->drawPixmap(mRect.topLeft()+QPoint(0, -1), mBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height())); + // draw background fill (don't use circular clip, looks bad): + if (mBackgroundBrush != Qt::NoBrush) { + QPainterPath ellipsePath; + ellipsePath.addEllipse(center, radius, radius); + painter->fillPath(ellipsePath, mBackgroundBrush); + } + + // draw background pixmap (on top of fill, if brush specified): + if (!mBackgroundPixmap.isNull()) { + QRegion clipCircle(center.x() - radius, center.y() - radius, qRound(2 * radius), qRound(2 * radius), QRegion::Ellipse); + QRegion originalClip = painter->clipRegion(); + painter->setClipRegion(clipCircle); + if (mBackgroundScaled) { + // check whether mScaledBackground needs to be updated: + QSize scaledSize(mBackgroundPixmap.size()); + scaledSize.scale(mRect.size(), mBackgroundScaledMode); + if (mScaledBackgroundPixmap.size() != scaledSize) { + mScaledBackgroundPixmap = mBackgroundPixmap.scaled(mRect.size(), mBackgroundScaledMode, Qt::SmoothTransformation); + } + painter->drawPixmap(mRect.topLeft() + QPoint(0, -1), mScaledBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height()) & mScaledBackgroundPixmap.rect()); + } else { + painter->drawPixmap(mRect.topLeft() + QPoint(0, -1), mBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height())); + } + painter->setClipRegion(originalClip); } - painter->setClipRegion(originalClip); - } } /*! \internal - + Prepares the internal tick vector, sub tick vector and tick label vector. This is done by calling QCPAxisTicker::generate on the currently installed ticker. - + 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 QCPPolarAxisAngular::setupTickVectors() { - if (!mParentPlot) return; - if ((!mTicks && !mTickLabels && !mGrid->visible()) || mRange.size() <= 0) return; - - mSubTickVector.clear(); // since we might not pass it to mTicker->generate(), and we don't want old data in there - mTicker->generate(mRange, mParentPlot->locale(), mNumberFormatChar, mNumberPrecision, mTickVector, mSubTicks ? &mSubTickVector : 0, mTickLabels ? &mTickVectorLabels : 0); - - // fill cos/sin buffers which will be used by draw() and QCPPolarGrid::draw(), so we don't have to calculate it twice: - mTickVectorCosSin.resize(mTickVector.size()); - for (int i=0; ivisible()) || mRange.size() <= 0) { + return; + } + + mSubTickVector.clear(); // since we might not pass it to mTicker->generate(), and we don't want old data in there + mTicker->generate(mRange, mParentPlot->locale(), mNumberFormatChar, mNumberPrecision, mTickVector, mSubTicks ? &mSubTickVector : 0, mTickLabels ? &mTickVectorLabels : 0); + + // fill cos/sin buffers which will be used by draw() and QCPPolarGrid::draw(), so we don't have to calculate it twice: + mTickVectorCosSin.resize(mTickVector.size()); + for (int i = 0; i < mTickVector.size(); ++i) { + const double theta = coordToAngleRad(mTickVector.at(i)); + mTickVectorCosSin[i] = QPointF(qCos(theta), qSin(theta)); + } + mSubTickVectorCosSin.resize(mSubTickVector.size()); + for (int i = 0; i < mSubTickVector.size(); ++i) { + const double theta = coordToAngleRad(mSubTickVector.at(i)); + mSubTickVectorCosSin[i] = QPointF(qCos(theta), qSin(theta)); + } } /*! \internal - + Returns the pen that is used to draw the axis base line. Depending on the selection state, this is either mSelectedBasePen or mBasePen. */ QPen QCPPolarAxisAngular::getBasePen() const { - return mSelectedParts.testFlag(spAxis) ? mSelectedBasePen : mBasePen; + return mSelectedParts.testFlag(spAxis) ? mSelectedBasePen : mBasePen; } /*! \internal - + Returns the pen that is used to draw the (major) ticks. Depending on the selection state, this is either mSelectedTickPen or mTickPen. */ QPen QCPPolarAxisAngular::getTickPen() const { - return mSelectedParts.testFlag(spAxis) ? mSelectedTickPen : mTickPen; + return mSelectedParts.testFlag(spAxis) ? mSelectedTickPen : mTickPen; } /*! \internal - + Returns the pen that is used to draw the subticks. Depending on the selection state, this is either mSelectedSubTickPen or mSubTickPen. */ QPen QCPPolarAxisAngular::getSubTickPen() const { - return mSelectedParts.testFlag(spAxis) ? mSelectedSubTickPen : mSubTickPen; + return mSelectedParts.testFlag(spAxis) ? mSelectedSubTickPen : mSubTickPen; } /*! \internal - + Returns the font that is used to draw the tick labels. Depending on the selection state, this is either mSelectedTickLabelFont or mTickLabelFont. */ QFont QCPPolarAxisAngular::getTickLabelFont() const { - return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelFont : mTickLabelFont; + return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelFont : mTickLabelFont; } /*! \internal - + Returns the font that is used to draw the axis label. Depending on the selection state, this is either mSelectedLabelFont or mLabelFont. */ QFont QCPPolarAxisAngular::getLabelFont() const { - return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelFont : mLabelFont; + return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelFont : mLabelFont; } /*! \internal - + Returns the color that is used to draw the tick labels. Depending on the selection state, this is either mSelectedTickLabelColor or mTickLabelColor. */ QColor QCPPolarAxisAngular::getTickLabelColor() const { - return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelColor : mTickLabelColor; + return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelColor : mTickLabelColor; } /*! \internal - + Returns the color that is used to draw the axis label. Depending on the selection state, this is either mSelectedLabelColor or mLabelColor. */ QColor QCPPolarAxisAngular::getLabelColor() const { - return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelColor : mLabelColor; + return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelColor : mLabelColor; } /*! \internal - + Event handler for when a mouse button is pressed on the axis rect. If the left mouse button is pressed, the range dragging interaction is initialized (the actual range manipulation happens in the \ref mouseMoveEvent). The mDragging flag is set to true and some anchor points are set that are needed to determine the distance the mouse was dragged in the mouse move/release events later. - + \see mouseMoveEvent, mouseReleaseEvent */ void QCPPolarAxisAngular::mousePressEvent(QMouseEvent *event, const QVariant &details) { - Q_UNUSED(details) - if (event->buttons() & Qt::LeftButton) - { - mDragging = true; - // initialize antialiasing backup in case we start dragging: - if (mParentPlot->noAntialiasingOnDrag()) - { - mAADragBackup = mParentPlot->antialiasedElements(); - mNotAADragBackup = mParentPlot->notAntialiasedElements(); + Q_UNUSED(details) + if (event->buttons() & Qt::LeftButton) { + mDragging = true; + // initialize antialiasing backup in case we start dragging: + if (mParentPlot->noAntialiasingOnDrag()) { + mAADragBackup = mParentPlot->antialiasedElements(); + mNotAADragBackup = mParentPlot->notAntialiasedElements(); + } + // Mouse range dragging interaction: + if (mParentPlot->interactions().testFlag(QCP::iRangeDrag)) { + mDragAngularStart = range(); + mDragRadialStart.clear(); + for (int i = 0; i < mRadialAxes.size(); ++i) { + mDragRadialStart.append(mRadialAxes.at(i)->range()); + } + } } - // Mouse range dragging interaction: - if (mParentPlot->interactions().testFlag(QCP::iRangeDrag)) - { - mDragAngularStart = range(); - mDragRadialStart.clear(); - for (int i=0; irange()); - } - } } /*! \internal - + Event handler for when the mouse is moved on the axis rect. If range dragging was activated in a preceding \ref mousePressEvent, the range is moved accordingly. - + \see mousePressEvent, mouseReleaseEvent */ void QCPPolarAxisAngular::mouseMoveEvent(QMouseEvent *event, const QPointF &startPos) { - Q_UNUSED(startPos) - bool doReplot = false; - // Mouse range dragging interaction: - if (mDragging && mParentPlot->interactions().testFlag(QCP::iRangeDrag)) - { - if (mRangeDrag) - { - doReplot = true; - double angleCoordStart, radiusCoordStart; - double angleCoord, radiusCoord; - pixelToCoord(startPos, angleCoordStart, radiusCoordStart); - pixelToCoord(event->pos(), angleCoord, radiusCoord); - double diff = angleCoordStart - angleCoord; - setRange(mDragAngularStart.lower+diff, mDragAngularStart.upper+diff); - } - - for (int i=0; irangeDrag()) - continue; - doReplot = true; - double angleCoordStart, radiusCoordStart; - double angleCoord, radiusCoord; - ax->pixelToCoord(startPos, angleCoordStart, radiusCoordStart); - ax->pixelToCoord(event->pos(), angleCoord, radiusCoord); - if (ax->scaleType() == QCPPolarAxisRadial::stLinear) - { - double diff = radiusCoordStart - radiusCoord; - ax->setRange(mDragRadialStart.at(i).lower+diff, mDragRadialStart.at(i).upper+diff); - } else if (ax->scaleType() == QCPPolarAxisRadial::stLogarithmic) - { - if (radiusCoord != 0) - { - double diff = radiusCoordStart/radiusCoord; - ax->setRange(mDragRadialStart.at(i).lower*diff, mDragRadialStart.at(i).upper*diff); + Q_UNUSED(startPos) + bool doReplot = false; + // Mouse range dragging interaction: + if (mDragging && mParentPlot->interactions().testFlag(QCP::iRangeDrag)) { + if (mRangeDrag) { + doReplot = true; + double angleCoordStart, radiusCoordStart; + double angleCoord, radiusCoord; + pixelToCoord(startPos, angleCoordStart, radiusCoordStart); + pixelToCoord(event->pos(), angleCoord, radiusCoord); + double diff = angleCoordStart - angleCoord; + setRange(mDragAngularStart.lower + diff, mDragAngularStart.upper + diff); + } + + for (int i = 0; i < mRadialAxes.size(); ++i) { + QCPPolarAxisRadial *ax = mRadialAxes.at(i); + if (!ax->rangeDrag()) { + continue; + } + doReplot = true; + double angleCoordStart, radiusCoordStart; + double angleCoord, radiusCoord; + ax->pixelToCoord(startPos, angleCoordStart, radiusCoordStart); + ax->pixelToCoord(event->pos(), angleCoord, radiusCoord); + if (ax->scaleType() == QCPPolarAxisRadial::stLinear) { + double diff = radiusCoordStart - radiusCoord; + ax->setRange(mDragRadialStart.at(i).lower + diff, mDragRadialStart.at(i).upper + diff); + } else if (ax->scaleType() == QCPPolarAxisRadial::stLogarithmic) { + if (radiusCoord != 0) { + double diff = radiusCoordStart / radiusCoord; + ax->setRange(mDragRadialStart.at(i).lower * diff, mDragRadialStart.at(i).upper * diff); + } + } + } + + if (doReplot) { // if either vertical or horizontal drag was enabled, do a replot + if (mParentPlot->noAntialiasingOnDrag()) { + mParentPlot->setNotAntialiasedElements(QCP::aeAll); + } + mParentPlot->replot(QCustomPlot::rpQueuedReplot); } - } } - - if (doReplot) // if either vertical or horizontal drag was enabled, do a replot - { - if (mParentPlot->noAntialiasingOnDrag()) - mParentPlot->setNotAntialiasedElements(QCP::aeAll); - mParentPlot->replot(QCustomPlot::rpQueuedReplot); - } - } } /* inherits documentation from base class */ void QCPPolarAxisAngular::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos) { - Q_UNUSED(event) - Q_UNUSED(startPos) - mDragging = false; - if (mParentPlot->noAntialiasingOnDrag()) - { - mParentPlot->setAntialiasedElements(mAADragBackup); - mParentPlot->setNotAntialiasedElements(mNotAADragBackup); - } + Q_UNUSED(event) + Q_UNUSED(startPos) + mDragging = false; + if (mParentPlot->noAntialiasingOnDrag()) { + mParentPlot->setAntialiasedElements(mAADragBackup); + mParentPlot->setNotAntialiasedElements(mNotAADragBackup); + } } /*! \internal - + 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 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 wheel is turned rapidly, many steps may bunch up to one event, so the event->delta() may then be multiples of 120. This is taken into account here, by calculating \a wheelSteps and using it as @@ -34062,64 +34403,63 @@ void QCPPolarAxisAngular::mouseReleaseEvent(QMouseEvent *event, const QPointF &s */ void QCPPolarAxisAngular::wheelEvent(QWheelEvent *event) { - bool doReplot = false; - // Mouse range zooming interaction: - if (mParentPlot->interactions().testFlag(QCP::iRangeZoom)) - { + bool doReplot = false; + // Mouse range zooming interaction: + if (mParentPlot->interactions().testFlag(QCP::iRangeZoom)) { #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) - const double delta = event->delta(); + const double delta = event->delta(); #else - const double delta = event->angleDelta().y(); + const double delta = event->angleDelta().y(); #endif #if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) - const QPointF pos = event->pos(); + const QPointF pos = event->pos(); #else - const QPointF pos = event->position(); + const QPointF pos = event->position(); #endif - const double wheelSteps = delta/120.0; // a single step delta is +/-120 usually - if (mRangeZoom) - { - double angleCoord, radiusCoord; - pixelToCoord(pos, angleCoord, radiusCoord); - scaleRange(qPow(mRangeZoomFactor, wheelSteps), angleCoord); - } + const double wheelSteps = delta / 120.0; // a single step delta is +/-120 usually + if (mRangeZoom) { + double angleCoord, radiusCoord; + pixelToCoord(pos, angleCoord, radiusCoord); + scaleRange(qPow(mRangeZoomFactor, wheelSteps), angleCoord); + } - for (int i=0; irangeZoom()) - continue; - doReplot = true; - double angleCoord, radiusCoord; - ax->pixelToCoord(pos, angleCoord, radiusCoord); - ax->scaleRange(qPow(ax->rangeZoomFactor(), wheelSteps), radiusCoord); + for (int i = 0; i < mRadialAxes.size(); ++i) { + QCPPolarAxisRadial *ax = mRadialAxes.at(i); + if (!ax->rangeZoom()) { + continue; + } + doReplot = true; + double angleCoord, radiusCoord; + ax->pixelToCoord(pos, angleCoord, radiusCoord); + ax->scaleRange(qPow(ax->rangeZoomFactor(), wheelSteps), radiusCoord); + } + } + if (doReplot) { + mParentPlot->replot(); } - } - if (doReplot) - mParentPlot->replot(); } bool QCPPolarAxisAngular::registerPolarGraph(QCPPolarGraph *graph) { - if (mGraphs.contains(graph)) - { - qDebug() << Q_FUNC_INFO << "plottable already added:" << reinterpret_cast(graph); - return false; - } - if (graph->keyAxis() != this) - { - qDebug() << Q_FUNC_INFO << "plottable not created with this as axis:" << reinterpret_cast(graph); - return false; - } - - mGraphs.append(graph); - // possibly add plottable to legend: - if (mParentPlot->autoAddPlottableToLegend()) - graph->addToLegend(); - if (!graph->layer()) // usually the layer is already set in the constructor of the plottable (via QCPLayerable constructor) - graph->setLayer(mParentPlot->currentLayer()); - return true; + if (mGraphs.contains(graph)) { + qDebug() << Q_FUNC_INFO << "plottable already added:" << reinterpret_cast(graph); + return false; + } + if (graph->keyAxis() != this) { + qDebug() << Q_FUNC_INFO << "plottable not created with this as axis:" << reinterpret_cast(graph); + return false; + } + + mGraphs.append(graph); + // possibly add plottable to legend: + if (mParentPlot->autoAddPlottableToLegend()) { + graph->addToLegend(); + } + if (!graph->layer()) { // usually the layer is already set in the constructor of the plottable (via QCPLayerable constructor) + graph->setLayer(mParentPlot->currentLayer()); + } + return true; } /* end of 'src/polar/layoutelement-angularaxis.cpp' */ @@ -34141,45 +34481,45 @@ bool QCPPolarAxisAngular::registerPolarGraph(QCPPolarGraph *graph) /*! Creates a QCPPolarGrid instance and sets default values. - + You shouldn't instantiate grids on their own, since every axis brings its own grid. */ QCPPolarGrid::QCPPolarGrid(QCPPolarAxisAngular *parentAxis) : - QCPLayerable(parentAxis->parentPlot(), QString(), parentAxis), - mType(gtNone), - mSubGridType(gtNone), - mAntialiasedSubGrid(true), - mAntialiasedZeroLine(true), - mParentAxis(parentAxis) + QCPLayerable(parentAxis->parentPlot(), QString(), parentAxis), + mType(gtNone), + mSubGridType(gtNone), + mAntialiasedSubGrid(true), + mAntialiasedZeroLine(true), + mParentAxis(parentAxis) { - // warning: this is called in QCPPolarAxisAngular constructor, so parentAxis members should not be accessed/called - setParent(parentAxis); - setType(gtAll); - setSubGridType(gtNone); - - setAngularPen(QPen(QColor(200,200,200), 0, Qt::DotLine)); - setAngularSubGridPen(QPen(QColor(220,220,220), 0, Qt::DotLine)); - - setRadialPen(QPen(QColor(200,200,200), 0, Qt::DotLine)); - setRadialSubGridPen(QPen(QColor(220,220,220), 0, Qt::DotLine)); - setRadialZeroLinePen(QPen(QColor(200,200,200), 0, Qt::SolidLine)); - - setAntialiased(true); + // warning: this is called in QCPPolarAxisAngular constructor, so parentAxis members should not be accessed/called + setParent(parentAxis); + setType(gtAll); + setSubGridType(gtNone); + + setAngularPen(QPen(QColor(200, 200, 200), 0, Qt::DotLine)); + setAngularSubGridPen(QPen(QColor(220, 220, 220), 0, Qt::DotLine)); + + setRadialPen(QPen(QColor(200, 200, 200), 0, Qt::DotLine)); + setRadialSubGridPen(QPen(QColor(220, 220, 220), 0, Qt::DotLine)); + setRadialZeroLinePen(QPen(QColor(200, 200, 200), 0, Qt::SolidLine)); + + setAntialiased(true); } void QCPPolarGrid::setRadialAxis(QCPPolarAxisRadial *axis) { - mRadialAxis = axis; + mRadialAxis = axis; } void QCPPolarGrid::setType(GridTypes type) { - mType = type; + mType = type; } void QCPPolarGrid::setSubGridType(GridTypes type) { - mSubGridType = type; + mSubGridType = type; } /*! @@ -34187,7 +34527,7 @@ void QCPPolarGrid::setSubGridType(GridTypes type) */ void QCPPolarGrid::setAntialiasedSubGrid(bool enabled) { - mAntialiasedSubGrid = enabled; + mAntialiasedSubGrid = enabled; } /*! @@ -34195,7 +34535,7 @@ void QCPPolarGrid::setAntialiasedSubGrid(bool enabled) */ void QCPPolarGrid::setAntialiasedZeroLine(bool enabled) { - mAntialiasedZeroLine = enabled; + mAntialiasedZeroLine = enabled; } /*! @@ -34203,7 +34543,7 @@ void QCPPolarGrid::setAntialiasedZeroLine(bool enabled) */ void QCPPolarGrid::setAngularPen(const QPen &pen) { - mAngularPen = pen; + mAngularPen = pen; } /*! @@ -34211,22 +34551,22 @@ void QCPPolarGrid::setAngularPen(const QPen &pen) */ void QCPPolarGrid::setAngularSubGridPen(const QPen &pen) { - mAngularSubGridPen = pen; + mAngularSubGridPen = pen; } void QCPPolarGrid::setRadialPen(const QPen &pen) { - mRadialPen = pen; + mRadialPen = pen; } void QCPPolarGrid::setRadialSubGridPen(const QPen &pen) { - mRadialSubGridPen = pen; + mRadialSubGridPen = pen; } void QCPPolarGrid::setRadialZeroLinePen(const QPen &pen) { - mRadialZeroLinePen = pen; + mRadialZeroLinePen = pen; } /*! \internal @@ -34235,79 +34575,90 @@ void QCPPolarGrid::setRadialZeroLinePen(const QPen &pen) before drawing the major grid lines. This is the antialiasing state the painter passed to the \ref draw method is in by default. - + 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 */ void QCPPolarGrid::applyDefaultAntialiasingHint(QCPPainter *painter) const { - applyAntialiasingHint(painter, mAntialiased, QCP::aeGrid); + applyAntialiasingHint(painter, mAntialiased, QCP::aeGrid); } /*! \internal - + Draws grid lines and sub grid lines at the positions of (sub) ticks of the parent axis, spanning over the complete axis rect. Also draws the zero line, if appropriate (\ref setZeroLinePen). */ void QCPPolarGrid::draw(QCPPainter *painter) { - if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; } - - const QPointF center = mParentAxis->mCenter; - const double radius = mParentAxis->mRadius; - - painter->setBrush(Qt::NoBrush); - // draw main angular grid: - if (mType.testFlag(gtAngular)) - drawAngularGrid(painter, center, radius, mParentAxis->mTickVectorCosSin, mAngularPen); - // draw main radial grid: - if (mType.testFlag(gtRadial) && mRadialAxis) - drawRadialGrid(painter, center, mRadialAxis->tickVector(), mRadialPen, mRadialZeroLinePen); - - applyAntialiasingHint(painter, mAntialiasedSubGrid, QCP::aeGrid); - // draw sub angular grid: - if (mSubGridType.testFlag(gtAngular)) - drawAngularGrid(painter, center, radius, mParentAxis->mSubTickVectorCosSin, mAngularSubGridPen); - // draw sub radial grid: - if (mSubGridType.testFlag(gtRadial) && mRadialAxis) - drawRadialGrid(painter, center, mRadialAxis->subTickVector(), mRadialSubGridPen); + if (!mParentAxis) { + qDebug() << Q_FUNC_INFO << "invalid parent axis"; + return; + } + + const QPointF center = mParentAxis->mCenter; + const double radius = mParentAxis->mRadius; + + painter->setBrush(Qt::NoBrush); + // draw main angular grid: + if (mType.testFlag(gtAngular)) { + drawAngularGrid(painter, center, radius, mParentAxis->mTickVectorCosSin, mAngularPen); + } + // draw main radial grid: + if (mType.testFlag(gtRadial) && mRadialAxis) { + drawRadialGrid(painter, center, mRadialAxis->tickVector(), mRadialPen, mRadialZeroLinePen); + } + + applyAntialiasingHint(painter, mAntialiasedSubGrid, QCP::aeGrid); + // draw sub angular grid: + if (mSubGridType.testFlag(gtAngular)) { + drawAngularGrid(painter, center, radius, mParentAxis->mSubTickVectorCosSin, mAngularSubGridPen); + } + // draw sub radial grid: + if (mSubGridType.testFlag(gtRadial) && mRadialAxis) { + drawRadialGrid(painter, center, mRadialAxis->subTickVector(), mRadialSubGridPen); + } } void QCPPolarGrid::drawRadialGrid(QCPPainter *painter, const QPointF ¢er, const QVector &coords, const QPen &pen, const QPen &zeroPen) { - if (!mRadialAxis) return; - if (coords.isEmpty()) return; - const bool drawZeroLine = zeroPen != Qt::NoPen; - const double zeroLineEpsilon = qAbs(coords.last()-coords.first())*1e-6; - - painter->setPen(pen); - for (int i=0; icoordToRadius(coords.at(i)); - if (drawZeroLine && qAbs(coords.at(i)) < zeroLineEpsilon) - { - applyAntialiasingHint(painter, mAntialiasedZeroLine, QCP::aeZeroLine); - painter->setPen(zeroPen); - painter->drawEllipse(center, r, r); - painter->setPen(pen); - applyDefaultAntialiasingHint(painter); - } else - { - painter->drawEllipse(center, r, r); + if (!mRadialAxis) { + return; + } + if (coords.isEmpty()) { + return; + } + const bool drawZeroLine = zeroPen != Qt::NoPen; + const double zeroLineEpsilon = qAbs(coords.last() - coords.first()) * 1e-6; + + painter->setPen(pen); + for (int i = 0; i < coords.size(); ++i) { + const double r = mRadialAxis->coordToRadius(coords.at(i)); + if (drawZeroLine && qAbs(coords.at(i)) < zeroLineEpsilon) { + applyAntialiasingHint(painter, mAntialiasedZeroLine, QCP::aeZeroLine); + painter->setPen(zeroPen); + painter->drawEllipse(center, r, r); + painter->setPen(pen); + applyDefaultAntialiasingHint(painter); + } else { + painter->drawEllipse(center, r, r); + } } - } } void QCPPolarGrid::drawAngularGrid(QCPPainter *painter, const QPointF ¢er, double radius, const QVector &ticksCosSin, const QPen &pen) { - if (ticksCosSin.isEmpty()) return; - - painter->setPen(pen); - for (int i=0; idrawLine(center, center+ticksCosSin.at(i)*radius); + if (ticksCosSin.isEmpty()) { + return; + } + + painter->setPen(pen); + for (int i = 0; i < ticksCosSin.size(); ++i) { + painter->drawLine(center, center + ticksCosSin.at(i)*radius); + } } /* end of 'src/polar/polargrid.cpp' */ @@ -34327,66 +34678,69 @@ void QCPPolarGrid::drawAngularGrid(QCPPainter *painter, const QPointF ¢er, d functionality to be incomplete, as well as changing public interfaces in the future. */ QCPPolarLegendItem::QCPPolarLegendItem(QCPLegend *parent, QCPPolarGraph *graph) : - QCPAbstractLegendItem(parent), - mPolarGraph(graph) + QCPAbstractLegendItem(parent), + mPolarGraph(graph) { - setAntialiased(false); + setAntialiased(false); } void QCPPolarLegendItem::draw(QCPPainter *painter) { - if (!mPolarGraph) return; - painter->setFont(getFont()); - painter->setPen(QPen(getTextColor())); - QSizeF iconSize = mParentLegend->iconSize(); - QRectF textRect = painter->fontMetrics().boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPolarGraph->name()); - QRectF iconRect(mRect.topLeft(), iconSize); - int textHeight = qMax(textRect.height(), iconSize.height()); // if text has smaller height than icon, center text vertically in icon height, else align tops - painter->drawText(mRect.x()+iconSize.width()+mParentLegend->iconTextPadding(), mRect.y(), textRect.width(), textHeight, Qt::TextDontClip, mPolarGraph->name()); - // draw icon: - painter->save(); - painter->setClipRect(iconRect, Qt::IntersectClip); - mPolarGraph->drawLegendIcon(painter, iconRect); - painter->restore(); - // draw icon border: - if (getIconBorderPen().style() != Qt::NoPen) - { - 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); - } + if (!mPolarGraph) { + return; + } + painter->setFont(getFont()); + painter->setPen(QPen(getTextColor())); + QSizeF iconSize = mParentLegend->iconSize(); + QRectF textRect = painter->fontMetrics().boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPolarGraph->name()); + QRectF iconRect(mRect.topLeft(), iconSize); + int textHeight = qMax(textRect.height(), iconSize.height()); // if text has smaller height than icon, center text vertically in icon height, else align tops + painter->drawText(mRect.x() + iconSize.width() + mParentLegend->iconTextPadding(), mRect.y(), textRect.width(), textHeight, Qt::TextDontClip, mPolarGraph->name()); + // draw icon: + painter->save(); + painter->setClipRect(iconRect, Qt::IntersectClip); + mPolarGraph->drawLegendIcon(painter, iconRect); + painter->restore(); + // draw icon border: + if (getIconBorderPen().style() != Qt::NoPen) { + 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); + } } QSize QCPPolarLegendItem::minimumOuterSizeHint() const { - if (!mPolarGraph) return QSize(); - QSize result(0, 0); - QRect textRect; - QFontMetrics fontMetrics(getFont()); - QSize iconSize = mParentLegend->iconSize(); - textRect = fontMetrics.boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPolarGraph->name()); - result.setWidth(iconSize.width() + mParentLegend->iconTextPadding() + textRect.width()); - result.setHeight(qMax(textRect.height(), iconSize.height())); - result.rwidth() += mMargins.left()+mMargins.right(); - result.rheight() += mMargins.top()+mMargins.bottom(); - return result; + if (!mPolarGraph) { + return QSize(); + } + QSize result(0, 0); + QRect textRect; + QFontMetrics fontMetrics(getFont()); + QSize iconSize = mParentLegend->iconSize(); + textRect = fontMetrics.boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPolarGraph->name()); + result.setWidth(iconSize.width() + mParentLegend->iconTextPadding() + textRect.width()); + result.setHeight(qMax(textRect.height(), iconSize.height())); + result.rwidth() += mMargins.left() + mMargins.right(); + result.rheight() += mMargins.top() + mMargins.bottom(); + return result; } QPen QCPPolarLegendItem::getIconBorderPen() const { - return mSelected ? mParentLegend->selectedIconBorderPen() : mParentLegend->iconBorderPen(); + return mSelected ? mParentLegend->selectedIconBorderPen() : mParentLegend->iconBorderPen(); } QColor QCPPolarLegendItem::getTextColor() const { - return mSelected ? mSelectedTextColor : mTextColor; + return mSelected ? mSelectedTextColor : mTextColor; } QFont QCPPolarLegendItem::getFont() const { - return mSelected ? mSelectedFont : mFont; + return mSelected ? mSelectedFont : mFont; } @@ -34421,40 +34775,41 @@ QFont QCPPolarLegendItem::getFont() const method. */ QCPPolarGraph::QCPPolarGraph(QCPPolarAxisAngular *keyAxis, QCPPolarAxisRadial *valueAxis) : - QCPLayerable(keyAxis->parentPlot(), QString(), keyAxis), - mDataContainer(new QCPGraphDataContainer), - mName(), - mAntialiasedFill(true), - mAntialiasedScatters(true), - mPen(Qt::black), - mBrush(Qt::NoBrush), - mPeriodic(true), - mKeyAxis(keyAxis), - mValueAxis(valueAxis), - mSelectable(QCP::stWhole) - //mSelectionDecorator(0) // TODO + QCPLayerable(keyAxis->parentPlot(), QString(), keyAxis), + mDataContainer(new QCPGraphDataContainer), + mName(), + mAntialiasedFill(true), + mAntialiasedScatters(true), + mPen(Qt::black), + mBrush(Qt::NoBrush), + mPeriodic(true), + mKeyAxis(keyAxis), + mValueAxis(valueAxis), + mSelectable(QCP::stWhole) + //mSelectionDecorator(0) // TODO { - if (keyAxis->parentPlot() != valueAxis->parentPlot()) - qDebug() << Q_FUNC_INFO << "Parent plot of keyAxis is not the same as that of valueAxis."; - - mKeyAxis->registerPolarGraph(this); - - //setSelectionDecorator(new QCPSelectionDecorator); // TODO - - setPen(QPen(Qt::blue, 0)); - setBrush(Qt::NoBrush); - setLineStyle(lsLine); + if (keyAxis->parentPlot() != valueAxis->parentPlot()) { + qDebug() << Q_FUNC_INFO << "Parent plot of keyAxis is not the same as that of valueAxis."; + } + + mKeyAxis->registerPolarGraph(this); + + //setSelectionDecorator(new QCPSelectionDecorator); // TODO + + setPen(QPen(Qt::blue, 0)); + setBrush(Qt::NoBrush); + setLineStyle(lsLine); } QCPPolarGraph::~QCPPolarGraph() { - /* TODO - if (mSelectionDecorator) - { + /* TODO + if (mSelectionDecorator) + { delete mSelectionDecorator; mSelectionDecorator = 0; - } - */ + } + */ } /*! @@ -34463,48 +34818,48 @@ QCPPolarGraph::~QCPPolarGraph() */ void QCPPolarGraph::setName(const QString &name) { - mName = name; + mName = name; } /*! Sets whether fills of this plottable are drawn antialiased or not. - + Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref QCustomPlot::setNotAntialiasedElements. */ void QCPPolarGraph::setAntialiasedFill(bool enabled) { - mAntialiasedFill = enabled; + mAntialiasedFill = enabled; } /*! Sets whether the scatter symbols of this plottable are drawn antialiased or not. - + Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref QCustomPlot::setNotAntialiasedElements. */ void QCPPolarGraph::setAntialiasedScatters(bool enabled) { - mAntialiasedScatters = enabled; + mAntialiasedScatters = enabled; } /*! The pen is used to draw basic lines that make up the plottable representation in the plot. - + For example, the \ref QCPGraph subclass draws its graph lines with this pen. \see setBrush */ void QCPPolarGraph::setPen(const QPen &pen) { - mPen = pen; + mPen = 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. - + For example, the \ref QCPGraph subclass draws the fill under the graph with this brush, when it's not set to Qt::NoBrush. @@ -34512,12 +34867,12 @@ void QCPPolarGraph::setPen(const QPen &pen) */ void QCPPolarGraph::setBrush(const QBrush &brush) { - mBrush = brush; + mBrush = brush; } void QCPPolarGraph::setPeriodic(bool enabled) { - mPeriodic = enabled; + mPeriodic = enabled; } /*! @@ -34525,7 +34880,7 @@ void QCPPolarGraph::setPeriodic(bool enabled) to the plottable's value axis. This function performs no checks to make sure this is the case. The typical mathematical choice is to use the x-axis (QCustomPlot::xAxis) as key axis and the y-axis (QCustomPlot::yAxis) as value axis. - + Normally, the key and value axes are set in the constructor of the plottable (or \ref QCustomPlot::addGraph when working with QCPGraphs through the dedicated graph interface). @@ -34533,7 +34888,7 @@ void QCPPolarGraph::setPeriodic(bool enabled) */ void QCPPolarGraph::setKeyAxis(QCPPolarAxisAngular *axis) { - mKeyAxis = axis; + mKeyAxis = axis; } /*! @@ -34544,12 +34899,12 @@ void QCPPolarGraph::setKeyAxis(QCPPolarAxisAngular *axis) Normally, the key and value axes are set in the constructor of the plottable (or \ref QCustomPlot::addGraph when working with QCPGraphs through the dedicated graph interface). - + \see setKeyAxis */ void QCPPolarGraph::setValueAxis(QCPPolarAxisRadial *axis) { - mValueAxis = axis; + mValueAxis = axis; } /*! @@ -34559,144 +34914,141 @@ void QCPPolarGraph::setValueAxis(QCPPolarAxisRadial *axis) 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 QCPPolarGraph::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); + if (mSelectable != selectable) { + mSelectable = selectable; + QCPDataSelection oldSelection = mSelection; + mSelection.enforceType(mSelectable); + emit selectableChanged(mSelectable); + if (mSelection != oldSelection) { + emit selectionChanged(selected()); + emit selectionChanged(mSelection); + } } - } } /*! 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 programmatically. - + Using \ref setSelectable you can further specify for each plottable whether and to which granularity it is selectable. If \a selection is not compatible with the current \ref QCP::SelectionType set via \ref setSelectable, the resulting selection will be adjusted accordingly (see \ref QCPDataSelection::enforceType). - + emits the \ref selectionChanged signal when \a selected is different from the previous selection state. - + \see setSelectable, selectTest */ void QCPPolarGraph::setSelection(QCPDataSelection selection) { - selection.enforceType(mSelectable); - if (mSelection != selection) - { - mSelection = selection; - emit selectionChanged(selected()); - emit selectionChanged(mSelection); - } + selection.enforceType(mSelectable); + if (mSelection != selection) { + mSelection = selection; + emit selectionChanged(selected()); + emit selectionChanged(mSelection); + } } /*! \overload - + Replaces the current data container with the provided \a data container. - + Since a QSharedPointer is used, multiple QCPPolarGraphs 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 QCPPolarGraph-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 QCPPolarGraph-datasharing-2 - + \see addData */ void QCPPolarGraph::setData(QSharedPointer data) { - mDataContainer = 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 QCPPolarGraph::setData(const QVector &keys, const QVector &values, bool alreadySorted) { - mDataContainer->clear(); - addData(keys, values, alreadySorted); + mDataContainer->clear(); + addData(keys, values, alreadySorted); } /*! Sets how the single data points are connected in the plot. For scatter-only plots, set \a ls to \ref lsNone and \ref setScatterStyle to the desired scatter style. - + \see setScatterStyle */ void QCPPolarGraph::setLineStyle(LineStyle ls) { - mLineStyle = ls; + mLineStyle = ls; } /*! Sets the visual appearance of single data points in the plot. If set to \ref QCPScatterStyle::ssNone, no scatter points are drawn (e.g. for line-only-plots with appropriate line style). - + \see QCPScatterStyle, setLineStyle */ void QCPPolarGraph::setScatterStyle(const QCPScatterStyle &style) { - mScatterStyle = style; + mScatterStyle = style; } void QCPPolarGraph::addData(const QVector &keys, const QVector &values, bool alreadySorted) { - 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 + 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 } void QCPPolarGraph::addData(double key, double value) { - mDataContainer->add(QCPGraphData(key, value)); + mDataContainer->add(QCPGraphData(key, value)); } /*! 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. */ /* @@ -34720,376 +35072,374 @@ void QCPPolarGraph::setSelectionDecorator(QCPSelectionDecorator *decorator) void QCPPolarGraph::coordsToPixels(double key, double value, double &x, double &y) const { - if (mValueAxis) - { - const QPointF point = mValueAxis->coordToPixel(key, value); - x = point.x(); - y = point.y(); - } else - { - qDebug() << Q_FUNC_INFO << "invalid key or value axis"; - } + if (mValueAxis) { + const QPointF point = mValueAxis->coordToPixel(key, value); + x = point.x(); + y = point.y(); + } else { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + } } const QPointF QCPPolarGraph::coordsToPixels(double key, double value) const { - if (mValueAxis) - { - return mValueAxis->coordToPixel(key, value); - } else - { - qDebug() << Q_FUNC_INFO << "invalid key or value axis"; - return QPointF(); - } + if (mValueAxis) { + return mValueAxis->coordToPixel(key, value); + } else { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + return QPointF(); + } } void QCPPolarGraph::pixelsToCoords(double x, double y, double &key, double &value) const { - if (mValueAxis) - { - mValueAxis->pixelToCoord(QPointF(x, y), key, value); - } else - { - qDebug() << Q_FUNC_INFO << "invalid key or value axis"; - } + if (mValueAxis) { + mValueAxis->pixelToCoord(QPointF(x, y), key, value); + } else { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + } } void QCPPolarGraph::pixelsToCoords(const QPointF &pixelPos, double &key, double &value) const { - if (mValueAxis) - { - mValueAxis->pixelToCoord(pixelPos, key, value); - } else - { - qDebug() << Q_FUNC_INFO << "invalid key or value axis"; - } + if (mValueAxis) { + mValueAxis->pixelToCoord(pixelPos, key, value); + } else { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + } } void QCPPolarGraph::rescaleAxes(bool onlyEnlarge) const { - rescaleKeyAxis(onlyEnlarge); - rescaleValueAxis(onlyEnlarge); + rescaleKeyAxis(onlyEnlarge); + rescaleValueAxis(onlyEnlarge); } void QCPPolarGraph::rescaleKeyAxis(bool onlyEnlarge) const { - QCPPolarAxisAngular *keyAxis = mKeyAxis.data(); - if (!keyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; } - - bool foundRange; - QCPRange newRange = getKeyRange(foundRange, QCP::sdBoth); - if (foundRange) - { - if (onlyEnlarge) - newRange.expand(keyAxis->range()); - if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable - { - double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason - newRange.lower = center-keyAxis->range().size()/2.0; - newRange.upper = center+keyAxis->range().size()/2.0; + QCPPolarAxisAngular *keyAxis = mKeyAxis.data(); + if (!keyAxis) { + qDebug() << Q_FUNC_INFO << "invalid key axis"; + return; + } + + bool foundRange; + QCPRange newRange = getKeyRange(foundRange, QCP::sdBoth); + if (foundRange) { + if (onlyEnlarge) { + newRange.expand(keyAxis->range()); + } + if (!QCPRange::validRange(newRange)) { // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable + double center = (newRange.lower + newRange.upper) * 0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason + newRange.lower = center - keyAxis->range().size() / 2.0; + newRange.upper = center + keyAxis->range().size() / 2.0; + } + keyAxis->setRange(newRange); } - keyAxis->setRange(newRange); - } } void QCPPolarGraph::rescaleValueAxis(bool onlyEnlarge, bool inKeyRange) const { - QCPPolarAxisAngular *keyAxis = mKeyAxis.data(); - QCPPolarAxisRadial *valueAxis = mValueAxis.data(); - if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } - - QCP::SignDomain signDomain = QCP::sdBoth; - if (valueAxis->scaleType() == QCPPolarAxisRadial::stLogarithmic) - signDomain = (valueAxis->range().upper < 0 ? QCP::sdNegative : QCP::sdPositive); - - bool foundRange; - QCPRange newRange = getValueRange(foundRange, signDomain, inKeyRange ? keyAxis->range() : QCPRange()); - if (foundRange) - { - if (onlyEnlarge) - newRange.expand(valueAxis->range()); - if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable - { - double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason - if (valueAxis->scaleType() == QCPPolarAxisRadial::stLinear) - { - newRange.lower = center-valueAxis->range().size()/2.0; - newRange.upper = center+valueAxis->range().size()/2.0; - } else // scaleType() == stLogarithmic - { - newRange.lower = center/qSqrt(valueAxis->range().upper/valueAxis->range().lower); - newRange.upper = center*qSqrt(valueAxis->range().upper/valueAxis->range().lower); - } + QCPPolarAxisAngular *keyAxis = mKeyAxis.data(); + QCPPolarAxisRadial *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + return; + } + + QCP::SignDomain signDomain = QCP::sdBoth; + if (valueAxis->scaleType() == QCPPolarAxisRadial::stLogarithmic) { + signDomain = (valueAxis->range().upper < 0 ? QCP::sdNegative : QCP::sdPositive); + } + + bool foundRange; + QCPRange newRange = getValueRange(foundRange, signDomain, inKeyRange ? keyAxis->range() : QCPRange()); + if (foundRange) { + if (onlyEnlarge) { + newRange.expand(valueAxis->range()); + } + if (!QCPRange::validRange(newRange)) { // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable + double center = (newRange.lower + newRange.upper) * 0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason + if (valueAxis->scaleType() == QCPPolarAxisRadial::stLinear) { + newRange.lower = center - valueAxis->range().size() / 2.0; + newRange.upper = center + valueAxis->range().size() / 2.0; + } else { // scaleType() == stLogarithmic + newRange.lower = center / qSqrt(valueAxis->range().upper / valueAxis->range().lower); + newRange.upper = center * qSqrt(valueAxis->range().upper / valueAxis->range().lower); + } + } + valueAxis->setRange(newRange); } - valueAxis->setRange(newRange); - } } bool QCPPolarGraph::addToLegend(QCPLegend *legend) { - if (!legend) - { - qDebug() << Q_FUNC_INFO << "passed legend is null"; - return false; - } - if (legend->parentPlot() != mParentPlot) - { - qDebug() << Q_FUNC_INFO << "passed legend isn't in the same QCustomPlot as this plottable"; - return false; - } - - //if (!legend->hasItemWithPlottable(this)) // TODO - //{ + if (!legend) { + qDebug() << Q_FUNC_INFO << "passed legend is null"; + return false; + } + if (legend->parentPlot() != mParentPlot) { + qDebug() << Q_FUNC_INFO << "passed legend isn't in the same QCustomPlot as this plottable"; + return false; + } + + //if (!legend->hasItemWithPlottable(this)) // TODO + //{ legend->addItem(new QCPPolarLegendItem(legend, this)); return true; - //} else - // return false; + //} else + // return false; } bool QCPPolarGraph::addToLegend() { - if (!mParentPlot || !mParentPlot->legend) - return false; - else - return addToLegend(mParentPlot->legend); + if (!mParentPlot || !mParentPlot->legend) { + return false; + } else { + return addToLegend(mParentPlot->legend); + } } bool QCPPolarGraph::removeFromLegend(QCPLegend *legend) const { - if (!legend) - { - qDebug() << Q_FUNC_INFO << "passed legend is null"; - return false; - } - - - QCPPolarLegendItem *removableItem = 0; - for (int i=0; iitemCount(); ++i) // TODO: reduce this to code in QCPAbstractPlottable::removeFromLegend once unified - { - if (QCPPolarLegendItem *pli = qobject_cast(legend->item(i))) - { - if (pli->polarGraph() == this) - { - removableItem = pli; - break; - } + if (!legend) { + qDebug() << Q_FUNC_INFO << "passed legend is null"; + return false; + } + + + QCPPolarLegendItem *removableItem = 0; + for (int i = 0; i < legend->itemCount(); ++i) { // TODO: reduce this to code in QCPAbstractPlottable::removeFromLegend once unified + if (QCPPolarLegendItem *pli = qobject_cast(legend->item(i))) { + if (pli->polarGraph() == this) { + removableItem = pli; + break; + } + } + } + + if (removableItem) { + return legend->removeItem(removableItem); + } else { + return false; } - } - - if (removableItem) - return legend->removeItem(removableItem); - else - return false; } bool QCPPolarGraph::removeFromLegend() const { - if (!mParentPlot || !mParentPlot->legend) - return false; - else - return removeFromLegend(mParentPlot->legend); + if (!mParentPlot || !mParentPlot->legend) { + return false; + } else { + return removeFromLegend(mParentPlot->legend); + } } double QCPPolarGraph::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { - if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty()) - return -1; - if (!mKeyAxis || !mValueAxis) - return -1; - - if (mKeyAxis->rect().contains(pos.toPoint())) - { - 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))); + if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty()) { + return -1; + } + if (!mKeyAxis || !mValueAxis) { + return -1; + } + + if (mKeyAxis->rect().contains(pos.toPoint())) { + 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; } - return result; - } else - return -1; } /* inherits documentation from base class */ QCPRange QCPPolarGraph::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const { - return mDataContainer->keyRange(foundRange, inSignDomain); + return mDataContainer->keyRange(foundRange, inSignDomain); } /* inherits documentation from base class */ QCPRange QCPPolarGraph::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const { - return mDataContainer->valueRange(foundRange, inSignDomain, inKeyRange); + return mDataContainer->valueRange(foundRange, inSignDomain, inKeyRange); } /* inherits documentation from base class */ QRect QCPPolarGraph::clipRect() const { - if (mKeyAxis) - return mKeyAxis.data()->rect(); - else - return QRect(); + if (mKeyAxis) { + return mKeyAxis.data()->rect(); + } else { + return QRect(); + } } void QCPPolarGraph::draw(QCPPainter *painter) { - if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } - if (mKeyAxis.data()->range().size() <= 0 || mDataContainer->isEmpty()) return; - if (mLineStyle == lsNone && mScatterStyle.isNone()) return; - - painter->setClipRegion(mKeyAxis->exactClipRegion()); - - QVector lines, scatters; // line and (if necessary) scatter pixel coordinates will be stored here while iterating over segments - - // 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: + if (!mKeyAxis || !mValueAxis) { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + return; + } + if (mKeyAxis.data()->range().size() <= 0 || mDataContainer->isEmpty()) { + return; + } + if (mLineStyle == lsNone && mScatterStyle.isNone()) { + return; + } + + painter->setClipRegion(mKeyAxis->exactClipRegion()); + + QVector lines, scatters; // line and (if necessary) scatter pixel coordinates will be stored here while iterating over segments + + // loop over and draw segments of unselected/selected data: + QList selectedSegments, unselectedSegments, allSegments; + getDataSegments(selectedSegments, unselectedSegments); + allSegments << unselectedSegments << selectedSegments; + for (int i = 0; i < allSegments.size(); ++i) { + bool isSelectedSegment = i >= unselectedSegments.size(); + // get line pixel points appropriate to line style: + QCPDataRange lineDataRange = isSelectedSegment ? allSegments.at(i) : allSegments.at(i).adjusted(-1, 1); // unselected segments extend lines to bordering selected data point (safe to exceed total data bounds in first/last segment, getLines takes care) + getLines(&lines, lineDataRange); + + // check data validity if flag set: #ifdef QCUSTOMPLOT_CHECK_DATA - QCPGraphDataContainer::const_iterator it; - for (it = mDataContainer->constBegin(); it != mDataContainer->constEnd(); ++it) - { - if (QCP::isInvalidData(it->key, it->value)) - qDebug() << Q_FUNC_INFO << "Data point at" << it->key << "invalid." << "Plottable name:" << name(); - } + 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: - //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); - drawLinePlot(painter, lines); + + // 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); + drawLinePlot(painter, lines); + } + + // 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 scatters: - - QCPScatterStyle finalScatterStyle = mScatterStyle; - //if (isSelectedSegment && mSelectionDecorator) - // finalScatterStyle = mSelectionDecorator->getFinalScatterStyle(mScatterStyle); - if (!finalScatterStyle.isNone()) - { - getScatters(&scatters, allSegments.at(i)); - drawScatterPlot(painter, scatters, finalScatterStyle); - } - } - - // draw other selection decoration that isn't just line/scatter pens and brushes: - //if (mSelectionDecorator) - // mSelectionDecorator->drawDecoration(painter, selection()); + + // draw other selection decoration that isn't just line/scatter pens and brushes: + //if (mSelectionDecorator) + // mSelectionDecorator->drawDecoration(painter, selection()); } QCP::Interaction QCPPolarGraph::selectionCategory() const { - return QCP::iSelectPlottables; + return QCP::iSelectPlottables; } void QCPPolarGraph::applyDefaultAntialiasingHint(QCPPainter *painter) const { - applyAntialiasingHint(painter, mAntialiased, QCP::aePlottables); + applyAntialiasingHint(painter, mAntialiased, QCP::aePlottables); } /* inherits documentation from base class */ void QCPPolarGraph::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) { - Q_UNUSED(event) - - if (mSelectable != QCP::stNone) - { - 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 = mSelection != selectionBefore; - } + Q_UNUSED(event) + + if (mSelectable != QCP::stNone) { + 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 = mSelection != selectionBefore; + } + } } /* inherits documentation from base class */ void QCPPolarGraph::deselectEvent(bool *selectionStateChanged) { - if (mSelectable != QCP::stNone) - { - QCPDataSelection selectionBefore = mSelection; - setSelection(QCPDataSelection()); - if (selectionStateChanged) - *selectionStateChanged = mSelection != selectionBefore; - } + if (mSelectable != QCP::stNone) { + QCPDataSelection selectionBefore = mSelection; + setSelection(QCPDataSelection()); + if (selectionStateChanged) { + *selectionStateChanged = mSelection != selectionBefore; + } + } } /*! \internal - + Draws lines between the points in \a lines, given in pixel coordinates. - + \see drawScatterPlot, drawImpulsePlot, QCPAbstractPlottable1D::drawPolyline */ void QCPPolarGraph::drawLinePlot(QCPPainter *painter, const QVector &lines) const { - if (painter->pen().style() != Qt::NoPen && painter->pen().color().alpha() != 0) - { - applyDefaultAntialiasingHint(painter); - drawPolyline(painter, lines); - } + if (painter->pen().style() != Qt::NoPen && painter->pen().color().alpha() != 0) { + applyDefaultAntialiasingHint(painter); + drawPolyline(painter, lines); + } } /*! \internal - + Draws the fill of the graph using the specified \a painter, with the currently set brush. - + Depending on whether a normal fill or a channel fill (\ref setChannelFillGraph) is needed, \ref getFillPolygon or \ref getChannelFillPolygon are used to find the according fill polygons. - + In order to handle NaN Data points correctly (the fill needs to be split into disjoint areas), this method first determines a list of non-NaN segments with \ref getNonNanSegments, on which to operate. In the channel fill case, \ref getOverlappingSegments is used to consolidate the non-NaN segments of the two involved graphs, before passing the overlapping pairs to \ref getChannelFillPolygon. - + Pass the points of this graph's line as \a lines, in pixel coordinates. \see drawLinePlot, drawImpulsePlot, drawScatterPlot */ void QCPPolarGraph::drawFill(QCPPainter *painter, QVector *lines) const { - applyFillAntialiasingHint(painter); - if (painter->brush().style() != Qt::NoBrush && painter->brush().color().alpha() != 0) - painter->drawPolygon(QPolygonF(*lines)); + applyFillAntialiasingHint(painter); + if (painter->brush().style() != Qt::NoBrush && painter->brush().color().alpha() != 0) { + painter->drawPolygon(QPolygonF(*lines)); + } } /*! \internal @@ -35101,196 +35451,187 @@ void QCPPolarGraph::drawFill(QCPPainter *painter, QVector *lines) const */ void QCPPolarGraph::drawScatterPlot(QCPPainter *painter, const QVector &scatters, const QCPScatterStyle &style) const { - applyScattersAntialiasingHint(painter); - style.applyTo(painter, mPen); - for (int i=0; ifillRect(QRectF(rect.left(), rect.top()+rect.height()/2.0, rect.width(), rect.height()/3.0), mBrush); - } - // draw line vertically centered: - if (mLineStyle != lsNone) - { - applyDefaultAntialiasingHint(painter); - painter->setPen(mPen); - painter->drawLine(QLineF(rect.left(), rect.top()+rect.height()/2.0, rect.right()+5, rect.top()+rect.height()/2.0)); // +5 on x2 else last segment is missing from dashed/dotted pens - } - // draw scatter symbol: - if (!mScatterStyle.isNone()) - { - applyScattersAntialiasingHint(painter); - // scale scatter pixmap if it's too large to fit in legend icon rect: - if (mScatterStyle.shape() == QCPScatterStyle::ssPixmap && (mScatterStyle.pixmap().size().width() > rect.width() || mScatterStyle.pixmap().size().height() > rect.height())) - { - QCPScatterStyle scaledStyle(mScatterStyle); - scaledStyle.setPixmap(scaledStyle.pixmap().scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation)); - scaledStyle.applyTo(painter, mPen); - scaledStyle.drawShape(painter, QRectF(rect).center()); - } else - { - mScatterStyle.applyTo(painter, mPen); - mScatterStyle.drawShape(painter, QRectF(rect).center()); + // draw fill: + if (mBrush.style() != Qt::NoBrush) { + applyFillAntialiasingHint(painter); + painter->fillRect(QRectF(rect.left(), rect.top() + rect.height() / 2.0, rect.width(), rect.height() / 3.0), mBrush); + } + // draw line vertically centered: + if (mLineStyle != lsNone) { + applyDefaultAntialiasingHint(painter); + painter->setPen(mPen); + painter->drawLine(QLineF(rect.left(), rect.top() + rect.height() / 2.0, rect.right() + 5, rect.top() + rect.height() / 2.0)); // +5 on x2 else last segment is missing from dashed/dotted pens + } + // draw scatter symbol: + if (!mScatterStyle.isNone()) { + applyScattersAntialiasingHint(painter); + // scale scatter pixmap if it's too large to fit in legend icon rect: + if (mScatterStyle.shape() == QCPScatterStyle::ssPixmap && (mScatterStyle.pixmap().size().width() > rect.width() || mScatterStyle.pixmap().size().height() > rect.height())) { + QCPScatterStyle scaledStyle(mScatterStyle); + scaledStyle.setPixmap(scaledStyle.pixmap().scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation)); + scaledStyle.applyTo(painter, mPen); + scaledStyle.drawShape(painter, QRectF(rect).center()); + } else { + mScatterStyle.applyTo(painter, mPen); + mScatterStyle.drawShape(painter, QRectF(rect).center()); + } } - } } void QCPPolarGraph::applyFillAntialiasingHint(QCPPainter *painter) const { - applyAntialiasingHint(painter, mAntialiasedFill, QCP::aeFills); + applyAntialiasingHint(painter, mAntialiasedFill, QCP::aeFills); } void QCPPolarGraph::applyScattersAntialiasingHint(QCPPainter *painter) const { - applyAntialiasingHint(painter, mAntialiasedScatters, QCP::aeScatters); + applyAntialiasingHint(painter, mAntialiasedScatters, QCP::aeScatters); } double QCPPolarGraph::pointDistance(const QPointF &pixelPoint, QCPGraphDataContainer::const_iterator &closestData) const { - closestData = mDataContainer->constEnd(); - if (mDataContainer->isEmpty()) - return -1.0; - if (mLineStyle == lsNone && mScatterStyle.isNone()) - return -1.0; - - // 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) - { - const double currentDistSqr = QCPVector2D(coordsToPixels(it->key, it->value)-pixelPoint).lengthSquared(); - if (currentDistSqr < minDistSqr) - { - minDistSqr = currentDistSqr; - closestData = it; + closestData = mDataContainer->constEnd(); + if (mDataContainer->isEmpty()) { + return -1.0; } - } - - // calculate distance to graph line if there is one (if so, will probably be smaller than distance to closest data point): - if (mLineStyle != lsNone) - { - // line displayed, calculate distance to line segments: - QVector lineData; - getLines(&lineData, QCPDataRange(0, dataCount())); - QCPVector2D p(pixelPoint); - for (int i=0; i::max)(); + // determine which key range comes into question, taking selection tolerance around pos into account: + double posKeyMin, posKeyMax, dummy; + pixelsToCoords(pixelPoint - QPointF(mParentPlot->selectionTolerance(), mParentPlot->selectionTolerance()), posKeyMin, dummy); + pixelsToCoords(pixelPoint + QPointF(mParentPlot->selectionTolerance(), mParentPlot->selectionTolerance()), posKeyMax, dummy); + if (posKeyMin > posKeyMax) { + qSwap(posKeyMin, posKeyMax); + } + // iterate over found data points and then choose the one with the shortest distance to pos: + QCPGraphDataContainer::const_iterator begin = mDataContainer->findBegin(posKeyMin, true); + QCPGraphDataContainer::const_iterator end = mDataContainer->findEnd(posKeyMax, true); + for (QCPGraphDataContainer::const_iterator it = begin; it != end; ++it) { + const double currentDistSqr = QCPVector2D(coordsToPixels(it->key, it->value) - pixelPoint).lengthSquared(); + if (currentDistSqr < minDistSqr) { + minDistSqr = currentDistSqr; + closestData = it; + } + } + + // calculate distance to graph line if there is one (if so, will probably be smaller than distance to closest data point): + if (mLineStyle != lsNone) { + // line displayed, calculate distance to line segments: + QVector lineData; + getLines(&lineData, QCPDataRange(0, dataCount())); + QCPVector2D p(pixelPoint); + for (int i = 0; i < lineData.size() - 1; ++i) { + const double currentDistSqr = p.distanceSquaredToLine(lineData.at(i), lineData.at(i + 1)); + if (currentDistSqr < minDistSqr) { + minDistSqr = currentDistSqr; + } + } + } + + return qSqrt(minDistSqr); } int QCPPolarGraph::dataCount() const { - return mDataContainer->size(); + return mDataContainer->size(); } void QCPPolarGraph::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(); - } + 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(); + } } void QCPPolarGraph::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; + // 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); } - } 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); - } } void QCPPolarGraph::getVisibleDataBounds(QCPGraphDataContainer::const_iterator &begin, QCPGraphDataContainer::const_iterator &end, const QCPDataRange &rangeRestriction) const { - if (rangeRestriction.isEmpty()) - { - end = mDataContainer->constEnd(); - begin = end; - } else - { - QCPPolarAxisAngular *keyAxis = mKeyAxis.data(); - QCPPolarAxisRadial *valueAxis = mValueAxis.data(); - if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } - // get visible data range: - if (mPeriodic) - { - begin = mDataContainer->constBegin(); - end = mDataContainer->constEnd(); - } else - { - begin = mDataContainer->findBegin(keyAxis->range().lower); - end = mDataContainer->findEnd(keyAxis->range().upper); + if (rangeRestriction.isEmpty()) { + end = mDataContainer->constEnd(); + begin = end; + } else { + QCPPolarAxisAngular *keyAxis = mKeyAxis.data(); + QCPPolarAxisRadial *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + return; + } + // get visible data range: + if (mPeriodic) { + begin = mDataContainer->constBegin(); + end = mDataContainer->constEnd(); + } else { + 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 } - // limit lower/upperEnd to rangeRestriction: - mDataContainer->limitIteratorsToDataRange(begin, end, rangeRestriction); // this also ensures rangeRestriction outside data bounds doesn't break anything - } } /*! \internal @@ -35315,164 +35656,165 @@ void QCPPolarGraph::getVisibleDataBounds(QCPGraphDataContainer::const_iterator & */ void QCPPolarGraph::getLines(QVector *lines, const QCPDataRange &dataRange) const { - if (!lines) return; - QCPGraphDataContainer::const_iterator begin, end; - getVisibleDataBounds(begin, end, dataRange); - if (begin == end) - { - lines->clear(); - return; - } - - QVector lineData; - if (mLineStyle != lsNone) - getOptimizedLineData(&lineData, begin, end); + if (!lines) { + return; + } + QCPGraphDataContainer::const_iterator begin, end; + getVisibleDataBounds(begin, end, dataRange); + if (begin == end) { + lines->clear(); + return; + } - switch (mLineStyle) - { - case lsNone: lines->clear(); break; - case lsLine: *lines = dataToLines(lineData); break; - } + QVector lineData; + if (mLineStyle != lsNone) { + getOptimizedLineData(&lineData, begin, end); + } + + switch (mLineStyle) { + case lsNone: + lines->clear(); + break; + case lsLine: + *lines = dataToLines(lineData); + break; + } } void QCPPolarGraph::getScatters(QVector *scatters, const QCPDataRange &dataRange) const { - QCPPolarAxisAngular *keyAxis = mKeyAxis.data(); - QCPPolarAxisRadial *valueAxis = mValueAxis.data(); - if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } - - if (!scatters) return; - QCPGraphDataContainer::const_iterator begin, end; - getVisibleDataBounds(begin, end, dataRange); - if (begin == end) - { - scatters->clear(); - return; - } - - QVector data; - getOptimizedScatterData(&data, begin, end); - - scatters->resize(data.size()); - for (int i=0; icoordToPixel(data.at(i).key, data.at(i).value); - } + QCPPolarAxisAngular *keyAxis = mKeyAxis.data(); + QCPPolarAxisRadial *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + return; + } + + if (!scatters) { + return; + } + QCPGraphDataContainer::const_iterator begin, end; + getVisibleDataBounds(begin, end, dataRange); + if (begin == end) { + scatters->clear(); + return; + } + + QVector data; + getOptimizedScatterData(&data, begin, end); + + scatters->resize(data.size()); + for (int i = 0; i < data.size(); ++i) { + if (!qIsNaN(data.at(i).value)) { + (*scatters)[i] = valueAxis->coordToPixel(data.at(i).key, data.at(i).value); + } + } } void QCPPolarGraph::getOptimizedLineData(QVector *lineData, const QCPGraphDataContainer::const_iterator &begin, const QCPGraphDataContainer::const_iterator &end) const { - lineData->clear(); - - // TODO: fix for log axes and thick line style - - const QCPRange range = mValueAxis->range(); - bool reversed = mValueAxis->rangeReversed(); - const double clipMargin = range.size()*0.05; // extra distance from visible circle, so optimized outside lines can cover more angle before having to place a dummy point to prevent tangents - const double upperClipValue = range.upper + (reversed ? 0 : range.size()*0.05+clipMargin); // clip slightly outside of actual range to avoid line thicknesses to peek into visible circle - const double lowerClipValue = range.lower - (reversed ? range.size()*0.05+clipMargin : 0); // clip slightly outside of actual range to avoid line thicknesses to peek into visible circle - const double maxKeySkip = qAsin(qSqrt(clipMargin*(clipMargin+2*range.size()))/(range.size()+clipMargin))/M_PI*mKeyAxis->range().size(); // the maximum angle between two points on outer circle (r=clipValue+clipMargin) before connecting line becomes tangent to inner circle (r=clipValue) - double skipBegin = 0; - bool belowRange = false; - bool aboveRange = false; - QCPGraphDataContainer::const_iterator it = begin; - while (it != end) - { - if (it->value < lowerClipValue) - { - if (aboveRange) // jumped directly from above to below visible range, draw previous point so entry angle is correct - { - aboveRange = false; - if (!reversed) // TODO: with inner radius, we'll need else case here with projected border point - lineData->append(*(it-1)); - } - if (!belowRange) - { - skipBegin = it->key; - lineData->append(QCPGraphData(it->key, lowerClipValue)); - belowRange = true; - } - if (it->key-skipBegin > maxKeySkip) // add dummy point if we're exceeding the maximum skippable angle (to prevent unintentional intersections with visible circle) - { - skipBegin += maxKeySkip; - lineData->append(QCPGraphData(skipBegin, lowerClipValue)); - } - } else if (it->value > upperClipValue) - { - if (belowRange) // jumped directly from below to above visible range, draw previous point so entry angle is correct (if lower means outer, so if reversed axis) - { - belowRange = false; - if (reversed) - lineData->append(*(it-1)); - } - if (!aboveRange) - { - skipBegin = it->key; - lineData->append(QCPGraphData(it->key, upperClipValue)); - aboveRange = true; - } - if (it->key-skipBegin > maxKeySkip) // add dummy point if we're exceeding the maximum skippable angle (to prevent unintentional intersections with visible circle) - { - skipBegin += maxKeySkip; - lineData->append(QCPGraphData(skipBegin, upperClipValue)); - } - } else // value within bounds where we don't optimize away points - { - if (aboveRange) - { - aboveRange = false; - if (!reversed) - lineData->append(*(it-1)); // just entered from above, draw previous point so entry angle is correct (if above means outer, so if not reversed axis) - } - if (belowRange) - { - belowRange = false; - if (reversed) - lineData->append(*(it-1)); // just entered from below, draw previous point so entry angle is correct (if below means outer, so if reversed axis) - } - lineData->append(*it); // inside visible circle, add point normally + lineData->clear(); + + // TODO: fix for log axes and thick line style + + const QCPRange range = mValueAxis->range(); + bool reversed = mValueAxis->rangeReversed(); + const double clipMargin = range.size() * 0.05; // extra distance from visible circle, so optimized outside lines can cover more angle before having to place a dummy point to prevent tangents + const double upperClipValue = range.upper + (reversed ? 0 : range.size() * 0.05 + clipMargin); // clip slightly outside of actual range to avoid line thicknesses to peek into visible circle + const double lowerClipValue = range.lower - (reversed ? range.size() * 0.05 + clipMargin : 0); // clip slightly outside of actual range to avoid line thicknesses to peek into visible circle + const double maxKeySkip = qAsin(qSqrt(clipMargin * (clipMargin + 2 * range.size())) / (range.size() + clipMargin)) / M_PI * mKeyAxis->range().size(); // the maximum angle between two points on outer circle (r=clipValue+clipMargin) before connecting line becomes tangent to inner circle (r=clipValue) + double skipBegin = 0; + bool belowRange = false; + bool aboveRange = false; + QCPGraphDataContainer::const_iterator it = begin; + while (it != end) { + if (it->value < lowerClipValue) { + if (aboveRange) { // jumped directly from above to below visible range, draw previous point so entry angle is correct + aboveRange = false; + if (!reversed) { // TODO: with inner radius, we'll need else case here with projected border point + lineData->append(*(it - 1)); + } + } + if (!belowRange) { + skipBegin = it->key; + lineData->append(QCPGraphData(it->key, lowerClipValue)); + belowRange = true; + } + if (it->key - skipBegin > maxKeySkip) { // add dummy point if we're exceeding the maximum skippable angle (to prevent unintentional intersections with visible circle) + skipBegin += maxKeySkip; + lineData->append(QCPGraphData(skipBegin, lowerClipValue)); + } + } else if (it->value > upperClipValue) { + if (belowRange) { // jumped directly from below to above visible range, draw previous point so entry angle is correct (if lower means outer, so if reversed axis) + belowRange = false; + if (reversed) { + lineData->append(*(it - 1)); + } + } + if (!aboveRange) { + skipBegin = it->key; + lineData->append(QCPGraphData(it->key, upperClipValue)); + aboveRange = true; + } + if (it->key - skipBegin > maxKeySkip) { // add dummy point if we're exceeding the maximum skippable angle (to prevent unintentional intersections with visible circle) + skipBegin += maxKeySkip; + lineData->append(QCPGraphData(skipBegin, upperClipValue)); + } + } else { // value within bounds where we don't optimize away points + if (aboveRange) { + aboveRange = false; + if (!reversed) { + lineData->append(*(it - 1)); // just entered from above, draw previous point so entry angle is correct (if above means outer, so if not reversed axis) + } + } + if (belowRange) { + belowRange = false; + if (reversed) { + lineData->append(*(it - 1)); // just entered from below, draw previous point so entry angle is correct (if below means outer, so if reversed axis) + } + } + lineData->append(*it); // inside visible circle, add point normally + } + ++it; + } + // to make fill not erratic, add last point normally if it was outside visible circle: + if (aboveRange) { + aboveRange = false; + if (!reversed) { + lineData->append(*(it - 1)); // just entered from above, draw previous point so entry angle is correct (if above means outer, so if not reversed axis) + } + } + if (belowRange) { + belowRange = false; + if (reversed) { + lineData->append(*(it - 1)); // just entered from below, draw previous point so entry angle is correct (if below means outer, so if reversed axis) + } } - ++it; - } - // to make fill not erratic, add last point normally if it was outside visible circle: - if (aboveRange) - { - aboveRange = false; - if (!reversed) - lineData->append(*(it-1)); // just entered from above, draw previous point so entry angle is correct (if above means outer, so if not reversed axis) - } - if (belowRange) - { - belowRange = false; - if (reversed) - lineData->append(*(it-1)); // just entered from below, draw previous point so entry angle is correct (if below means outer, so if reversed axis) - } } void QCPPolarGraph::getOptimizedScatterData(QVector *scatterData, QCPGraphDataContainer::const_iterator begin, QCPGraphDataContainer::const_iterator end) const { - scatterData->clear(); - - const QCPRange range = mValueAxis->range(); - bool reversed = mValueAxis->rangeReversed(); - const double clipMargin = range.size()*0.05; - const double upperClipValue = range.upper + (reversed ? 0 : clipMargin); // clip slightly outside of actual range to avoid scatter size to peek into visible circle - const double lowerClipValue = range.lower - (reversed ? clipMargin : 0); // clip slightly outside of actual range to avoid scatter size to peek into visible circle - QCPGraphDataContainer::const_iterator it = begin; - while (it != end) - { - if (it->value > lowerClipValue && it->value < upperClipValue) - scatterData->append(*it); - ++it; - } + scatterData->clear(); + + const QCPRange range = mValueAxis->range(); + bool reversed = mValueAxis->rangeReversed(); + const double clipMargin = range.size() * 0.05; + const double upperClipValue = range.upper + (reversed ? 0 : clipMargin); // clip slightly outside of actual range to avoid scatter size to peek into visible circle + const double lowerClipValue = range.lower - (reversed ? clipMargin : 0); // clip slightly outside of actual range to avoid scatter size to peek into visible circle + QCPGraphDataContainer::const_iterator it = begin; + while (it != end) { + if (it->value > lowerClipValue && it->value < upperClipValue) { + scatterData->append(*it); + } + ++it; + } } /*! \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 lsLine. - + The source of \a data is usually \ref getOptimizedLineData, and this method is called in \a getLines if the line style is set accordingly. @@ -35480,16 +35822,20 @@ void QCPPolarGraph::getOptimizedScatterData(QVector *scatterData, */ QVector QCPPolarGraph::dataToLines(const QVector &data) const { - QVector result; - QCPPolarAxisAngular *keyAxis = mKeyAxis.data(); - QCPPolarAxisRadial *valueAxis = mValueAxis.data(); - if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return result; } + QVector result; + QCPPolarAxisAngular *keyAxis = mKeyAxis.data(); + QCPPolarAxisRadial *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { + qDebug() << Q_FUNC_INFO << "invalid key or value axis"; + return result; + } - // transform data points to pixels: - result.resize(data.size()); - for (int i=0; icoordToPixel(data.at(i).key, data.at(i).value); - return result; + // transform data points to pixels: + result.resize(data.size()); + for (int i = 0; i < data.size(); ++i) { + result[i] = mValueAxis->coordToPixel(data.at(i).key, data.at(i).value); + } + return result; } /* end of 'src/polar/polargraph.cpp' */ diff --git a/third/3rd_qcustomplot/v2_1/qcustomplot.h b/third/3rd_qcustomplot/v2_1/qcustomplot.h index 8f0f78b..a953a03 100644 --- a/third/3rd_qcustomplot/v2_1/qcustomplot.h +++ b/third/3rd_qcustomplot/v2_1/qcustomplot.h @@ -1,4 +1,4 @@ -/*************************************************************************** +/*************************************************************************** ** ** ** QCustomPlot, an easy to use, modern plotting widget for Qt ** ** Copyright (C) 2011-2021 Emanuel Eichhammer ** @@ -153,229 +153,240 @@ class QCPPolarGraph; /*! 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. */ #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) +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. +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 +\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) +, 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. +Defines how cosmetic pens (pens with numerical width 0) are handled during export. - \see QCustomPlot::savePdf +\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) +, 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. +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 +, 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. - - \see QCPLayoutElement::setAutoMargins, QCPAxisRect::setAutoMargins +Defines the sides of a rectangular entity to which margins can be applied. + +\see QCPLayoutElement::setAutoMargins, QCPAxisRect::setAutoMargins */ enum MarginSide { msLeft = 0x01 ///< 0x01 left margin - ,msRight = 0x02 ///< 0x02 right margin - ,msTop = 0x04 ///< 0x04 top margin - ,msBottom = 0x08 ///< 0x08 bottom margin - ,msAll = 0xFF ///< 0xFF all margins - ,msNone = 0x00 ///< 0x00 no margin +, msRight = 0x02 ///< 0x02 right margin +, msTop = 0x04 ///< 0x04 top margin +, msBottom = 0x08 ///< 0x08 bottom margin +, msAll = 0xFF ///< 0xFF all margins +, msNone = 0x00 ///< 0x00 no margin }; Q_DECLARE_FLAGS(MarginSides, MarginSide) /*! - Defines what objects of a plot can be forcibly drawn antialiased/not antialiased. If an object is - neither forcibly drawn antialiased nor forcibly drawn not antialiased, it is up to the respective - element how it is drawn. Typically it provides a \a setAntialiased function for this. - - \c AntialiasedElements is a flag of or-combined elements of this enum type. - - \see QCustomPlot::setAntialiasedElements, QCustomPlot::setNotAntialiasedElements +Defines what objects of a plot can be forcibly drawn antialiased/not antialiased. If an object is +neither forcibly drawn antialiased nor forcibly drawn not antialiased, it is up to the respective +element how it is drawn. Typically it provides a \a setAntialiased function for this. + +\c AntialiasedElements is a flag of or-combined elements of this enum type. + +\see QCustomPlot::setAntialiasedElements, QCustomPlot::setNotAntialiasedElements */ enum AntialiasedElement { aeAxes = 0x0001 ///< 0x0001 Axis base line and tick marks - ,aeGrid = 0x0002 ///< 0x0002 Grid lines - ,aeSubGrid = 0x0004 ///< 0x0004 Sub grid lines - ,aeLegend = 0x0008 ///< 0x0008 Legend box - ,aeLegendItems = 0x0010 ///< 0x0010 Legend items - ,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) - ,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 +, aeGrid = 0x0002 ///< 0x0002 Grid lines +, aeSubGrid = 0x0004 ///< 0x0004 Sub grid lines +, aeLegend = 0x0008 ///< 0x0008 Legend box +, aeLegendItems = 0x0010 ///< 0x0010 Legend items +, 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) +, 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 }; Q_DECLARE_FLAGS(AntialiasedElements, AntialiasedElement) /*! - Defines plotting hints that control various aspects of the quality and speed of plotting. - - \see QCustomPlot::setPlottingHints +Defines plotting hints that control various aspects of the quality and speed of plotting. + +\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, 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. +, 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) /*! - Defines the mouse interactions possible with QCustomPlot. - - \c Interactions is a flag of or-combined elements of this enum type. - - \see QCustomPlot::setInteractions +Defines the mouse interactions possible with QCustomPlot. + +\c Interactions is a flag of or-combined elements of this enum type. + +\see QCustomPlot::setInteractions */ enum Interaction { iNone = 0x000 ///< 0x000 None of the interactions are possible - ,iRangeDrag = 0x001 ///< 0x001 Axis ranges are draggable (see \ref QCPAxisRect::setRangeDrag, \ref QCPAxisRect::setRangeDragAxes) - ,iRangeZoom = 0x002 ///< 0x002 Axis ranges are zoomable with the mouse wheel (see \ref QCPAxisRect::setRangeZoom, \ref QCPAxisRect::setRangeZoomAxes) - ,iMultiSelect = 0x004 ///< 0x004 The user can select multiple objects by holding the modifier set by \ref QCustomPlot::setMultiSelectModifier while clicking - ,iSelectPlottables = 0x008 ///< 0x008 Plottables are selectable (e.g. graphs, curves, bars,... see QCPAbstractPlottable) - ,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, other layout elements,...) - ,iSelectPlottablesBeyondAxisRect = 0x100 ///< 0x100 When performing plottable selection/hit tests, this flag extends the sensitive area beyond the axis rect +, iRangeDrag = 0x001 ///< 0x001 Axis ranges are draggable (see \ref QCPAxisRect::setRangeDrag, \ref QCPAxisRect::setRangeDragAxes) +, iRangeZoom = 0x002 ///< 0x002 Axis ranges are zoomable with the mouse wheel (see \ref QCPAxisRect::setRangeZoom, \ref QCPAxisRect::setRangeZoomAxes) +, iMultiSelect = 0x004 ///< 0x004 The user can select multiple objects by holding the modifier set by \ref QCustomPlot::setMultiSelectModifier while clicking +, iSelectPlottables = 0x008 ///< 0x008 Plottables are selectable (e.g. graphs, curves, bars,... see QCPAbstractPlottable) +, 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, other layout elements,...) +, iSelectPlottablesBeyondAxisRect = 0x100 ///< 0x100 When performing plottable selection/hit tests, this flag extends the sensitive area beyond the axis rect }; Q_DECLARE_FLAGS(Interactions, Interaction) /*! - Defines the behaviour of the selection rect. - - \see QCustomPlot::setSelectionRectMode, QCustomPlot::selectionRect, QCPSelectionRect +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. +, 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 +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 - }; +, 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. - is \e nan or \e +/-inf). This function is used to check data validity upon replots, when the - compiler flag \c QCUSTOMPLOT_CHECK_DATA is set. + +Returns whether the specified \a value is considered an invalid data value for plottables (i.e. +is \e nan or \e +/-inf). This function is used to check data validity upon replots, when the +compiler flag \c QCUSTOMPLOT_CHECK_DATA is set. */ -inline bool isInvalidData(double value) -{ - return qIsNaN(value) || qIsInf(value); +inline bool isInvalidData(double value) { + return qIsNaN(value) || qIsInf(value); } /*! \internal - \overload - - Checks two arguments instead of one. +\overload + +Checks two arguments instead of one. */ -inline bool isInvalidData(double value1, double value2) -{ - return isInvalidData(value1) || isInvalidData(value2); +inline bool isInvalidData(double value1, double value2) { + return isInvalidData(value1) || isInvalidData(value2); } /*! \internal - - Sets the specified \a side of \a margins to \a value - - \see getMarginValue + +Sets the specified \a side of \a margins to \a value + +\see getMarginValue */ -inline void setMarginValue(QMargins &margins, QCP::MarginSide side, int value) -{ - switch (side) - { - case QCP::msLeft: margins.setLeft(value); break; - case QCP::msRight: margins.setRight(value); break; - case QCP::msTop: margins.setTop(value); break; - case QCP::msBottom: margins.setBottom(value); break; - case QCP::msAll: margins = QMargins(value, value, value, value); break; - default: break; - } +inline void setMarginValue(QMargins &margins, QCP::MarginSide side, int value) { + switch (side) { + case QCP::msLeft: + margins.setLeft(value); + break; + case QCP::msRight: + margins.setRight(value); + break; + case QCP::msTop: + margins.setTop(value); + break; + case QCP::msBottom: + margins.setBottom(value); + break; + case QCP::msAll: + margins = QMargins(value, value, value, value); + break; + default: + break; + } } /*! \internal - - Returns the value of the specified \a side of \a margins. If \a side is \ref QCP::msNone or - \ref QCP::msAll, returns 0. - - \see setMarginValue + +Returns the value of the specified \a side of \a margins. If \a side is \ref QCP::msNone or +\ref QCP::msAll, returns 0. + +\see setMarginValue */ -inline int getMarginValue(const QMargins &margins, QCP::MarginSide side) -{ - switch (side) - { - case QCP::msLeft: return margins.left(); - case QCP::msRight: return margins.right(); - case QCP::msTop: return margins.top(); - case QCP::msBottom: return margins.bottom(); - default: break; - } - return 0; +inline int getMarginValue(const QMargins &margins, QCP::MarginSide side) { + switch (side) { + case QCP::msLeft: + return margins.left(); + case QCP::msRight: + return margins.right(); + case QCP::msTop: + return margins.top(); + case QCP::msBottom: + return margins.bottom(); + default: + break; + } + return 0; } @@ -405,61 +416,107 @@ Q_DECLARE_METATYPE(QCP::SelectionType) class QCP_LIB_DECL QCPVector2D { public: - QCPVector2D(); - QCPVector2D(double x, double y); - QCPVector2D(const QPoint &point); - QCPVector2D(const QPointF &point); - - // getters: - double x() const { return mX; } - double y() const { return mY; } - double &rx() { return mX; } - double &ry() { return mY; } - - // 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; } - double angle() const { return qAtan2(mY, mX); } - QPoint toPoint() const { return QPoint(int(mX), int(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); - + QCPVector2D(); + QCPVector2D(double x, double y); + QCPVector2D(const QPoint &point); + QCPVector2D(const QPointF &point); + + // getters: + double x() const { + return mX; + } + double y() const { + return mY; + } + double &rx() { + return mX; + } + double &ry() { + return mY; + } + + // 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; + } + double angle() const { + return qAtan2(mY, mX); + } + QPoint toPoint() const { + return QPoint(int(mX), int(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); + // 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(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); } +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 @@ -479,53 +536,59 @@ inline QDebug operator<< (QDebug d, const QCPVector2D &vec) class QCP_LIB_DECL QCPPainter : public QPainter { - Q_GADGET + Q_GADGET public: - /*! + /*! Defines special modes the painter can operate in. They disable or enable certain subsets of features/fixes/workarounds, depending on whether they are wanted on the respective output device. - */ - enum PainterMode { pmDefault = 0x00 ///< 0x00 Default mode for painting on screen devices - ,pmVectorized = 0x01 ///< 0x01 Mode for vectorized painting (e.g. PDF export). For example, this prevents some antialiasing fixes. - ,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_ENUMS(PainterMode) - Q_FLAGS(PainterModes) - Q_DECLARE_FLAGS(PainterModes, PainterMode) - - QCPPainter(); - explicit QCPPainter(QPaintDevice *device); - - // getters: - bool antialiasing() const { return testRenderHint(QPainter::Antialiasing); } - PainterModes modes() const { return mModes; } + */ + enum PainterMode { pmDefault = 0x00 ///< 0x00 Default mode for painting on screen devices + , pmVectorized = 0x01 ///< 0x01 Mode for vectorized painting (e.g. PDF export). For example, this prevents some antialiasing fixes. + , 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_ENUMS(PainterMode) + Q_FLAGS(PainterModes) + Q_DECLARE_FLAGS(PainterModes, PainterMode) - // setters: - void setAntialiasing(bool enabled); - void setMode(PainterMode mode, bool enabled=true); - void setModes(PainterModes modes); + QCPPainter(); + explicit QCPPainter(QPaintDevice *device); + + // getters: + bool antialiasing() const { + return testRenderHint(QPainter::Antialiasing); + } + PainterModes modes() const { + return mModes; + } + + // setters: + void setAntialiasing(bool enabled); + void setMode(PainterMode mode, bool enabled = true); + void setModes(PainterModes modes); + + // methods hiding non-virtual base class functions (QPainter bug workarounds): + bool begin(QPaintDevice *device); + void setPen(const QPen &pen); + void setPen(const QColor &color); + void setPen(Qt::PenStyle penStyle); + void drawLine(const QLineF &line); + void drawLine(const QPointF &p1, const QPointF &p2) { + drawLine(QLineF(p1, p2)); + } + void save(); + void restore(); + + // non-virtual methods: + void makeNonCosmetic(); - // methods hiding non-virtual base class functions (QPainter bug workarounds): - bool begin(QPaintDevice *device); - void setPen(const QPen &pen); - void setPen(const QColor &color); - void setPen(Qt::PenStyle penStyle); - void drawLine(const QLineF &line); - void drawLine(const QPointF &p1, const QPointF &p2) {drawLine(QLineF(p1, p2));} - void save(); - void restore(); - - // non-virtual methods: - void makeNonCosmetic(); - protected: - // property members: - PainterModes mModes; - bool mIsAntialiasing; - - // non-property members: - QStack mAntialiasingStack; + // property members: + PainterModes mModes; + bool mIsAntialiasing; + + // non-property members: + QStack mAntialiasingStack; }; Q_DECLARE_OPERATORS_FOR_FLAGS(QCPPainter::PainterModes) Q_DECLARE_METATYPE(QCPPainter::PainterMode) @@ -539,55 +602,61 @@ Q_DECLARE_METATYPE(QCPPainter::PainterMode) 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; - + 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; + // 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() Q_DECL_OVERRIDE; - - // 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; - + explicit QCPPaintBufferPixmap(const QSize &size, double devicePixelRatio); + virtual ~QCPPaintBufferPixmap() Q_DECL_OVERRIDE; + + // 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; + // non-property members: + QPixmap mBuffer; + + // reimplemented virtual methods: + virtual void reallocateBuffer() Q_DECL_OVERRIDE; }; @@ -595,21 +664,21 @@ protected: class QCP_LIB_DECL QCPPaintBufferGlPbuffer : public QCPAbstractPaintBuffer { public: - explicit QCPPaintBufferGlPbuffer(const QSize &size, double devicePixelRatio, int multisamples); - virtual ~QCPPaintBufferGlPbuffer() Q_DECL_OVERRIDE; - - // 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; - + explicit QCPPaintBufferGlPbuffer(const QSize &size, double devicePixelRatio, int multisamples); + virtual ~QCPPaintBufferGlPbuffer() Q_DECL_OVERRIDE; + + // 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; + // non-property members: + QGLPixelBuffer *mGlPBuffer; + int mMultisamples; + + // reimplemented virtual methods: + virtual void reallocateBuffer() Q_DECL_OVERRIDE; }; #endif // QCP_OPENGL_PBUFFER @@ -618,23 +687,23 @@ protected: class QCP_LIB_DECL QCPPaintBufferGlFbo : public QCPAbstractPaintBuffer { public: - explicit QCPPaintBufferGlFbo(const QSize &size, double devicePixelRatio, QWeakPointer glContext, QWeakPointer glPaintDevice); - virtual ~QCPPaintBufferGlFbo() Q_DECL_OVERRIDE; - - // 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; - + explicit QCPPaintBufferGlFbo(const QSize &size, double devicePixelRatio, QWeakPointer glContext, QWeakPointer glPaintDevice); + virtual ~QCPPaintBufferGlFbo() Q_DECL_OVERRIDE; + + // 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; + // non-property members: + QWeakPointer mGlContext; + QWeakPointer mGlPaintDevice; + QOpenGLFramebufferObject *mGlFrameBuffer; + + // reimplemented virtual methods: + virtual void reallocateBuffer() Q_DECL_OVERRIDE; }; #endif // QCP_OPENGL_FBO @@ -646,145 +715,166 @@ protected: class QCP_LIB_DECL QCPLayer : public QObject { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QCustomPlot* parentPlot READ parentPlot) - Q_PROPERTY(QString name READ name) - 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 + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(QCustomPlot *parentPlot READ parentPlot) + Q_PROPERTY(QString name READ name) + 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); - virtual ~QCPLayer(); - - // getters: - QCustomPlot *parentPlot() const { return mParentPlot; } - QString name() const { return mName; } - 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(); - + */ + 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); + virtual ~QCPLayer(); + + // getters: + QCustomPlot *parentPlot() const { + return mParentPlot; + } + QString name() const { + return mName; + } + 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: - QCustomPlot *mParentPlot; - QString mName; - 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); - + // property members: + QCustomPlot *mParentPlot; + QString mName; + 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); + private: - Q_DISABLE_COPY(QCPLayer) - - friend class QCustomPlot; - friend class QCPLayerable; + Q_DISABLE_COPY(QCPLayer) + + friend class QCustomPlot; + friend class QCPLayerable; }; Q_DECLARE_METATYPE(QCPLayer::LayerMode) class QCP_LIB_DECL QCPLayerable : public QObject { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(bool visible READ visible WRITE setVisible) - Q_PROPERTY(QCustomPlot* parentPlot READ parentPlot) - Q_PROPERTY(QCPLayerable* parentLayerable READ parentLayerable) - Q_PROPERTY(QCPLayer* layer READ layer WRITE setLayer NOTIFY layerChanged) - Q_PROPERTY(bool antialiased READ antialiased WRITE setAntialiased) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(bool visible READ visible WRITE setVisible) + Q_PROPERTY(QCustomPlot *parentPlot READ parentPlot) + Q_PROPERTY(QCPLayerable *parentLayerable READ parentLayerable) + Q_PROPERTY(QCPLayer *layer READ layer WRITE setLayer NOTIFY layerChanged) + Q_PROPERTY(bool antialiased READ antialiased WRITE setAntialiased) + /// \endcond public: - QCPLayerable(QCustomPlot *plot, QString targetLayer=QString(), QCPLayerable *parentLayerable=nullptr); - virtual ~QCPLayerable(); - - // getters: - bool visible() const { return mVisible; } - QCustomPlot *parentPlot() const { return mParentPlot; } - QCPLayerable *parentLayerable() const { return mParentLayerable.data(); } - QCPLayer *layer() const { return mLayer; } - bool antialiased() const { return mAntialiased; } - - // setters: - void setVisible(bool on); - Q_SLOT bool setLayer(QCPLayer *layer); - bool setLayer(const QString &layerName); - void setAntialiased(bool enabled); - - // introduced virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const; + QCPLayerable(QCustomPlot *plot, QString targetLayer = QString(), QCPLayerable *parentLayerable = nullptr); + virtual ~QCPLayerable(); + + // getters: + bool visible() const { + return mVisible; + } + QCustomPlot *parentPlot() const { + return mParentPlot; + } + QCPLayerable *parentLayerable() const { + return mParentLayerable.data(); + } + QCPLayer *layer() const { + return mLayer; + } + bool antialiased() const { + return mAntialiased; + } + + // setters: + void setVisible(bool on); + Q_SLOT bool setLayer(QCPLayer *layer); + bool setLayer(const QString &layerName); + void setAntialiased(bool enabled); + + // introduced virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = nullptr) const; + + // non-property methods: + bool realVisibility() const; - // non-property methods: - bool realVisibility() const; - signals: - void layerChanged(QCPLayer *newLayer); - + void layerChanged(QCPLayer *newLayer); + protected: - // property members: - bool mVisible; - QCustomPlot *mParentPlot; - QPointer mParentLayerable; - QCPLayer *mLayer; - bool mAntialiased; - - // introduced virtual methods: - virtual void parentPlotInitialized(QCustomPlot *parentPlot); - virtual QCP::Interaction selectionCategory() const; - virtual QRect clipRect() const; - virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const = 0; - virtual void draw(QCPPainter *painter) = 0; - // 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); - void setParentLayerable(QCPLayerable* parentLayerable); - bool moveToLayer(QCPLayer *layer, bool prepend); - void applyAntialiasingHint(QCPPainter *painter, bool localAntialiased, QCP::AntialiasedElement overrideElement) const; - + // property members: + bool mVisible; + QCustomPlot *mParentPlot; + QPointer mParentLayerable; + QCPLayer *mLayer; + bool mAntialiased; + + // introduced virtual methods: + virtual void parentPlotInitialized(QCustomPlot *parentPlot); + virtual QCP::Interaction selectionCategory() const; + virtual QRect clipRect() const; + virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const = 0; + virtual void draw(QCPPainter *painter) = 0; + // 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); + void setParentLayerable(QCPLayerable *parentLayerable); + bool moveToLayer(QCPLayer *layer, bool prepend); + void applyAntialiasingHint(QCPPainter *painter, bool localAntialiased, QCP::AntialiasedElement overrideElement) const; + private: - Q_DISABLE_COPY(QCPLayerable) - - friend class QCustomPlot; - friend class QCPLayer; - friend class QCPAxisRect; + Q_DISABLE_COPY(QCPLayerable) + + friend class QCustomPlot; + friend class QCPLayer; + friend class QCPAxisRect; }; /* end of 'src/layer.h' */ @@ -796,42 +886,72 @@ private: class QCP_LIB_DECL QCPRange { public: - double lower, upper; - - QCPRange(); - QCPRange(double lower, double upper); - - bool operator==(const QCPRange& other) const { return lower == other.lower && upper == other.upper; } - bool operator!=(const QCPRange& other) const { return !(*this == other); } - - QCPRange &operator+=(const double& value) { lower+=value; upper+=value; return *this; } - QCPRange &operator-=(const double& value) { lower-=value; upper-=value; return *this; } - QCPRange &operator*=(const double& value) { lower*=value; upper*=value; return *this; } - QCPRange &operator/=(const double& value) { lower/=value; upper/=value; return *this; } - friend inline const QCPRange operator+(const QCPRange&, double); - friend inline const QCPRange operator+(double, const QCPRange&); - friend inline const QCPRange operator-(const QCPRange& range, double value); - friend inline const QCPRange operator*(const QCPRange& range, double value); - friend inline const QCPRange operator*(double value, const QCPRange& range); - friend inline const QCPRange operator/(const QCPRange& range, double value); - - 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 { return value >= lower && value <= upper; } - - static bool validRange(double lower, double upper); - static bool validRange(const QCPRange &range); - static const double minRange; - static const double maxRange; - + double lower, upper; + + QCPRange(); + QCPRange(double lower, double upper); + + bool operator==(const QCPRange &other) const { + return lower == other.lower && upper == other.upper; + } + bool operator!=(const QCPRange &other) const { + return !(*this == other); + } + + QCPRange &operator+=(const double &value) { + lower += value; + upper += value; + return *this; + } + QCPRange &operator-=(const double &value) { + lower -= value; + upper -= value; + return *this; + } + QCPRange &operator*=(const double &value) { + lower *= value; + upper *= value; + return *this; + } + QCPRange &operator/=(const double &value) { + lower /= value; + upper /= value; + return *this; + } + friend inline const QCPRange operator+(const QCPRange &, double); + friend inline const QCPRange operator+(double, const QCPRange &); + friend inline const QCPRange operator-(const QCPRange &range, double value); + friend inline const QCPRange operator*(const QCPRange &range, double value); + friend inline const QCPRange operator*(double value, const QCPRange &range); + friend inline const QCPRange operator/(const QCPRange &range, double value); + + 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 { + return value >= lower && value <= upper; + } + + static bool validRange(double lower, double upper); + static bool validRange(const QCPRange &range); + static const double minRange; + static const double maxRange; + }; Q_DECLARE_TYPEINFO(QCPRange, Q_MOVABLE_TYPE); @@ -848,61 +968,61 @@ inline QDebug operator<< (QDebug d, const QCPRange &range) /*! Adds \a value to both boundaries of the range. */ -inline const QCPRange operator+(const QCPRange& range, double value) +inline const QCPRange operator+(const QCPRange &range, double value) { - QCPRange result(range); - result += value; - return result; + QCPRange result(range); + result += value; + return result; } /*! Adds \a value to both boundaries of the range. */ -inline const QCPRange operator+(double value, const QCPRange& range) +inline const QCPRange operator+(double value, const QCPRange &range) { - QCPRange result(range); - result += value; - return result; + QCPRange result(range); + result += value; + return result; } /*! Subtracts \a value from both boundaries of the range. */ -inline const QCPRange operator-(const QCPRange& range, double value) +inline const QCPRange operator-(const QCPRange &range, double value) { - QCPRange result(range); - result -= value; - return result; + QCPRange result(range); + result -= value; + return result; } /*! Multiplies both boundaries of the range by \a value. */ -inline const QCPRange operator*(const QCPRange& range, double value) +inline const QCPRange operator*(const QCPRange &range, double value) { - QCPRange result(range); - result *= value; - return result; + QCPRange result(range); + result *= value; + return result; } /*! Multiplies both boundaries of the range by \a value. */ -inline const QCPRange operator*(double value, const QCPRange& range) +inline const QCPRange operator*(double value, const QCPRange &range) { - QCPRange result(range); - result *= value; - return result; + QCPRange result(range); + result *= value; + return result; } /*! Divides both boundaries of the range by \a value. */ -inline const QCPRange operator/(const QCPRange& range, double value) +inline const QCPRange operator/(const QCPRange &range, double value) { - QCPRange result(range); - result /= value; - return result; + QCPRange result(range); + result /= value; + return result; } /* end of 'src/axis/range.h' */ @@ -914,35 +1034,57 @@ inline const QCPRange operator/(const QCPRange& range, double value) 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; - + 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; + // property members: + int mBegin, mEnd; }; Q_DECLARE_TYPEINFO(QCPDataRange, Q_MOVABLE_TYPE); @@ -951,47 +1093,57 @@ 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; - + 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(); } + // property members: + QList mDataRanges; + + inline static bool lessThanDataRangeBegin(const QCPDataRange &a, const QCPDataRange &b) { + return a.begin() < b.begin(); + } }; Q_DECLARE_METATYPE(QCPDataSelection) @@ -1000,84 +1152,84 @@ 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) +inline const QCPDataSelection operator+(const QCPDataSelection &a, const QCPDataSelection &b) { - QCPDataSelection result(a); - result += b; - return result; + 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) +inline const QCPDataSelection operator+(const QCPDataRange &a, const QCPDataSelection &b) { - QCPDataSelection result(a); - result += b; - return result; + 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) +inline const QCPDataSelection operator+(const QCPDataSelection &a, const QCPDataRange &b) { - QCPDataSelection result(a); - result += b; - return result; + 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) +inline const QCPDataSelection operator+(const QCPDataRange &a, const QCPDataRange &b) { - QCPDataSelection result(a); - result += b; - return result; + 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) +inline const QCPDataSelection operator-(const QCPDataSelection &a, const QCPDataSelection &b) { - QCPDataSelection result(a); - result -= b; - return result; + 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) +inline const QCPDataSelection operator-(const QCPDataRange &a, const QCPDataSelection &b) { - QCPDataSelection result(a); - result -= b; - return result; + 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) +inline const QCPDataSelection operator-(const QCPDataSelection &a, const QCPDataRange &b) { - QCPDataSelection result(a); - result -= b; - return result; + 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) +inline const QCPDataSelection operator-(const QCPDataRange &a, const QCPDataRange &b) { - QCPDataSelection result(a); - result -= b; - return result; + QCPDataSelection result(a); + result -= b; + return result; } /*! \relates QCPDataRange @@ -1086,8 +1238,8 @@ inline const QCPDataSelection operator-(const QCPDataRange& a, const QCPDataRang */ inline QDebug operator<< (QDebug d, const QCPDataRange &dataRange) { - d.nospace() << "QCPDataRange(" << dataRange.begin() << ", " << dataRange.end() << ")"; - return d; + d.nospace() << "QCPDataRange(" << dataRange.begin() << ", " << dataRange.end() << ")"; + return d; } /*! \relates QCPDataSelection @@ -1097,11 +1249,11 @@ inline QDebug operator<< (QDebug d, const QCPDataRange &dataRange) 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); } - bool isEmpty() const; - void clear(); - + explicit QCPMarginGroup(QCustomPlot *parentPlot); + virtual ~QCPMarginGroup(); + + // non-virtual methods: + QList elements(QCP::MarginSide side) const { + return mChildren.value(side); + } + bool isEmpty() const; + void clear(); + protected: - // non-property members: - QCustomPlot *mParentPlot; - QHash > mChildren; - - // introduced virtual methods: - virtual int commonMargin(QCP::MarginSide side) const; - - // non-virtual methods: - void addChild(QCP::MarginSide side, QCPLayoutElement *element); - void removeChild(QCP::MarginSide side, QCPLayoutElement *element); - + // non-property members: + QCustomPlot *mParentPlot; + QHash > mChildren; + + // introduced virtual methods: + virtual int commonMargin(QCP::MarginSide side) const; + + // non-virtual methods: + void addChild(QCP::MarginSide side, QCPLayoutElement *element); + void removeChild(QCP::MarginSide side, QCPLayoutElement *element); + private: - Q_DISABLE_COPY(QCPMarginGroup) - - friend class QCPLayoutElement; + Q_DISABLE_COPY(QCPMarginGroup) + + friend class QCPLayoutElement; }; class QCP_LIB_DECL QCPLayoutElement : public QCPLayerable { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QCPLayout* layout READ layout) - Q_PROPERTY(QRect rect READ rect) - Q_PROPERTY(QRect outerRect READ outerRect WRITE setOuterRect) - Q_PROPERTY(QMargins margins READ margins WRITE setMargins) - Q_PROPERTY(QMargins minimumMargins READ minimumMargins WRITE setMinimumMargins) - Q_PROPERTY(QSize minimumSize READ minimumSize WRITE setMinimumSize) - Q_PROPERTY(QSize maximumSize READ maximumSize WRITE setMaximumSize) - Q_PROPERTY(SizeConstraintRect sizeConstraintRect READ sizeConstraintRect WRITE setSizeConstraintRect) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(QCPLayout *layout READ layout) + Q_PROPERTY(QRect rect READ rect) + Q_PROPERTY(QRect outerRect READ outerRect WRITE setOuterRect) + Q_PROPERTY(QMargins margins READ margins WRITE setMargins) + Q_PROPERTY(QMargins minimumMargins READ minimumMargins WRITE setMinimumMargins) + Q_PROPERTY(QSize minimumSize READ minimumSize WRITE setMinimumSize) + Q_PROPERTY(QSize maximumSize READ maximumSize WRITE setMaximumSize) + Q_PROPERTY(SizeConstraintRect sizeConstraintRect READ sizeConstraintRect WRITE setSizeConstraintRect) + /// \endcond public: - /*! + /*! Defines the phases of the update process, that happens just before a replot. At each phase, \ref update is called with the according UpdatePhase value. - */ - enum UpdatePhase { upPreparation ///< Phase used for any type of preparation that needs to be done before margin calculation and layout - ,upMargins ///< Phase in which the margins are calculated and set - ,upLayout ///< Final phase in which the layout system places the rects of the elements - }; - Q_ENUMS(UpdatePhase) - - /*! + */ + enum UpdatePhase { upPreparation ///< Phase used for any type of preparation that needs to be done before margin calculation and layout + , upMargins ///< Phase in which the margins are calculated and set + , upLayout ///< Final phase in which the layout system places the rects of the elements + }; + Q_ENUMS(UpdatePhase) + + /*! Defines to which rect of a layout element the size constraints that can be set via \ref setMinimumSize and \ref setMaximumSize apply. The outer rect (\ref outerRect) includes the margins (e.g. in the case of a QCPAxisRect the axis labels), whereas the inner rect (\ref rect) does not. - - \see setSizeConstraintRect - */ - enum SizeConstraintRect { scrInnerRect ///< Minimum/Maximum size constraints apply to inner rect - , scrOuterRect ///< Minimum/Maximum size constraints apply to outer rect, thus include layout element margins - }; - Q_ENUMS(SizeConstraintRect) - explicit QCPLayoutElement(QCustomPlot *parentPlot=nullptr); - virtual ~QCPLayoutElement() Q_DECL_OVERRIDE; - - // getters: - QCPLayout *layout() const { return mParentLayout; } - QRect rect() const { return mRect; } - QRect outerRect() const { return mOuterRect; } - QMargins margins() const { return mMargins; } - QMargins minimumMargins() const { return mMinimumMargins; } - QCP::MarginSides autoMargins() const { return mAutoMargins; } - QSize minimumSize() const { return mMinimumSize; } - QSize maximumSize() const { return mMaximumSize; } - SizeConstraintRect sizeConstraintRect() const { return mSizeConstraintRect; } - QCPMarginGroup *marginGroup(QCP::MarginSide side) const { return mMarginGroups.value(side, nullptr); } - QHash marginGroups() const { return mMarginGroups; } - - // setters: - void setOuterRect(const QRect &rect); - void setMargins(const QMargins &margins); - void setMinimumMargins(const QMargins &margins); - void setAutoMargins(QCP::MarginSides sides); - void setMinimumSize(const QSize &size); - void setMinimumSize(int width, int height); - void setMaximumSize(const QSize &size); - void setMaximumSize(int width, int height); - void setSizeConstraintRect(SizeConstraintRect constraintRect); - void setMarginGroup(QCP::MarginSides sides, QCPMarginGroup *group); - - // introduced virtual methods: - virtual void update(UpdatePhase phase); - virtual QSize minimumOuterSizeHint() const; - virtual QSize maximumOuterSizeHint() const; - virtual QList elements(bool recursive) const; - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE; - + \see setSizeConstraintRect + */ + enum SizeConstraintRect { scrInnerRect ///< Minimum/Maximum size constraints apply to inner rect + , scrOuterRect ///< Minimum/Maximum size constraints apply to outer rect, thus include layout element margins + }; + Q_ENUMS(SizeConstraintRect) + + explicit QCPLayoutElement(QCustomPlot *parentPlot = nullptr); + virtual ~QCPLayoutElement() Q_DECL_OVERRIDE; + + // getters: + QCPLayout *layout() const { + return mParentLayout; + } + QRect rect() const { + return mRect; + } + QRect outerRect() const { + return mOuterRect; + } + QMargins margins() const { + return mMargins; + } + QMargins minimumMargins() const { + return mMinimumMargins; + } + QCP::MarginSides autoMargins() const { + return mAutoMargins; + } + QSize minimumSize() const { + return mMinimumSize; + } + QSize maximumSize() const { + return mMaximumSize; + } + SizeConstraintRect sizeConstraintRect() const { + return mSizeConstraintRect; + } + QCPMarginGroup *marginGroup(QCP::MarginSide side) const { + return mMarginGroups.value(side, nullptr); + } + QHash marginGroups() const { + return mMarginGroups; + } + + // setters: + void setOuterRect(const QRect &rect); + void setMargins(const QMargins &margins); + void setMinimumMargins(const QMargins &margins); + void setAutoMargins(QCP::MarginSides sides); + void setMinimumSize(const QSize &size); + void setMinimumSize(int width, int height); + void setMaximumSize(const QSize &size); + void setMaximumSize(int width, int height); + void setSizeConstraintRect(SizeConstraintRect constraintRect); + void setMarginGroup(QCP::MarginSides sides, QCPMarginGroup *group); + + // introduced virtual methods: + virtual void update(UpdatePhase phase); + virtual QSize minimumOuterSizeHint() const; + virtual QSize maximumOuterSizeHint() const; + virtual QList elements(bool recursive) const; + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = nullptr) const Q_DECL_OVERRIDE; + protected: - // property members: - QCPLayout *mParentLayout; - QSize mMinimumSize, mMaximumSize; - SizeConstraintRect mSizeConstraintRect; - QRect mRect, mOuterRect; - QMargins mMargins, mMinimumMargins; - QCP::MarginSides mAutoMargins; - QHash mMarginGroups; - - // introduced virtual methods: - virtual int calculateAutoMargin(QCP::MarginSide side); - virtual void layoutChanged(); - - // reimplemented virtual methods: - 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; + // property members: + QCPLayout *mParentLayout; + QSize mMinimumSize, mMaximumSize; + SizeConstraintRect mSizeConstraintRect; + QRect mRect, mOuterRect; + QMargins mMargins, mMinimumMargins; + QCP::MarginSides mAutoMargins; + QHash mMarginGroups; + + // introduced virtual methods: + virtual int calculateAutoMargin(QCP::MarginSide side); + virtual void layoutChanged(); + + // reimplemented virtual methods: + 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) - - friend class QCustomPlot; - friend class QCPLayout; - friend class QCPMarginGroup; + Q_DISABLE_COPY(QCPLayoutElement) + + friend class QCustomPlot; + friend class QCPLayout; + friend class QCPMarginGroup; }; Q_DECLARE_METATYPE(QCPLayoutElement::UpdatePhase) class QCP_LIB_DECL QCPLayout : public QCPLayoutElement { - Q_OBJECT + Q_OBJECT public: - explicit QCPLayout(); - - // reimplemented virtual methods: - 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; - virtual QCPLayoutElement* elementAt(int index) const = 0; - virtual QCPLayoutElement* takeAt(int index) = 0; - virtual bool take(QCPLayoutElement* element) = 0; - virtual void simplify(); - - // non-virtual methods: - bool removeAt(int index); - bool remove(QCPLayoutElement* element); - void clear(); - + explicit QCPLayout(); + + // reimplemented virtual methods: + 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; + virtual QCPLayoutElement *elementAt(int index) const = 0; + virtual QCPLayoutElement *takeAt(int index) = 0; + virtual bool take(QCPLayoutElement *element) = 0; + virtual void simplify(); + + // non-virtual methods: + bool removeAt(int index); + bool remove(QCPLayoutElement *element); + void clear(); + protected: - // introduced virtual methods: - virtual void updateLayout(); - - // non-virtual methods: - void sizeConstraintsChanged() const; - void adoptElement(QCPLayoutElement *el); - void releaseElement(QCPLayoutElement *el); - QVector getSectionSizes(QVector maxSizes, QVector minSizes, QVector stretchFactors, int totalSize) const; - static QSize getFinalMinimumOuterSize(const QCPLayoutElement *el); - static QSize getFinalMaximumOuterSize(const QCPLayoutElement *el); - + // introduced virtual methods: + virtual void updateLayout(); + + // non-virtual methods: + void sizeConstraintsChanged() const; + void adoptElement(QCPLayoutElement *el); + void releaseElement(QCPLayoutElement *el); + QVector getSectionSizes(QVector maxSizes, QVector minSizes, QVector stretchFactors, int totalSize) const; + static QSize getFinalMinimumOuterSize(const QCPLayoutElement *el); + static QSize getFinalMaximumOuterSize(const QCPLayoutElement *el); + private: - Q_DISABLE_COPY(QCPLayout) - friend class QCPLayoutElement; + Q_DISABLE_COPY(QCPLayout) + friend class QCPLayoutElement; }; class QCP_LIB_DECL QCPLayoutGrid : public QCPLayout { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(int rowCount READ rowCount) - Q_PROPERTY(int columnCount READ columnCount) - Q_PROPERTY(QList columnStretchFactors READ columnStretchFactors WRITE setColumnStretchFactors) - 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 + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(int rowCount READ rowCount) + Q_PROPERTY(int columnCount READ columnCount) + Q_PROPERTY(QList columnStretchFactors READ columnStretchFactors WRITE setColumnStretchFactors) + 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() Q_DECL_OVERRIDE; - - // getters: - 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); - void setColumnStretchFactors(const QList &factors); - void setRowStretchFactor(int row, double factor); - 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() 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 minimumOuterSizeHint() const Q_DECL_OVERRIDE; - virtual QSize maximumOuterSizeHint() 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; - + */ + 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() Q_DECL_OVERRIDE; + + // getters: + 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); + void setColumnStretchFactors(const QList &factors); + void setRowStretchFactor(int row, double factor); + 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() 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 minimumOuterSizeHint() const Q_DECL_OVERRIDE; + virtual QSize maximumOuterSizeHint() 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: - QList > mElements; - QList mColumnStretchFactors; - QList mRowStretchFactors; - int mColumnSpacing, mRowSpacing; - int mWrap; - FillOrder mFillOrder; - - // non-virtual methods: - void getMinimumRowColSizes(QVector *minColWidths, QVector *minRowHeights) const; - void getMaximumRowColSizes(QVector *maxColWidths, QVector *maxRowHeights) const; - + // property members: + QList > mElements; + QList mColumnStretchFactors; + QList mRowStretchFactors; + int mColumnSpacing, mRowSpacing; + int mWrap; + FillOrder mFillOrder; + + // non-virtual methods: + void getMinimumRowColSizes(QVector *minColWidths, QVector *minRowHeights) const; + void getMaximumRowColSizes(QVector *maxColWidths, QVector *maxRowHeights) const; + private: - Q_DISABLE_COPY(QCPLayoutGrid) + Q_DISABLE_COPY(QCPLayoutGrid) }; Q_DECLARE_METATYPE(QCPLayoutGrid::FillOrder) class QCP_LIB_DECL QCPLayoutInset : public QCPLayout { - Q_OBJECT + Q_OBJECT public: - /*! + /*! Defines how the placement and sizing is handled for a certain element in a QCPLayoutInset. - */ - 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() Q_DECL_OVERRIDE; - - // getters: - InsetPlacement insetPlacement(int index) const; - Qt::Alignment insetAlignment(int index) const; - QRectF insetRect(int index) const; - - // setters: - void setInsetPlacement(int index, InsetPlacement placement); - void setInsetAlignment(int index, Qt::Alignment alignment); - void setInsetRect(int index, const QRectF &rect); - - // reimplemented virtual methods: - 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=nullptr) const Q_DECL_OVERRIDE; - - // non-virtual methods: - void addElement(QCPLayoutElement *element, Qt::Alignment alignment); - void addElement(QCPLayoutElement *element, const QRectF &rect); - + */ + 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() Q_DECL_OVERRIDE; + + // getters: + InsetPlacement insetPlacement(int index) const; + Qt::Alignment insetAlignment(int index) const; + QRectF insetRect(int index) const; + + // setters: + void setInsetPlacement(int index, InsetPlacement placement); + void setInsetAlignment(int index, Qt::Alignment alignment); + void setInsetRect(int index, const QRectF &rect); + + // reimplemented virtual methods: + 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 = nullptr) const Q_DECL_OVERRIDE; + + // non-virtual methods: + void addElement(QCPLayoutElement *element, Qt::Alignment alignment); + void addElement(QCPLayoutElement *element, const QRectF &rect); + protected: - // property members: - QList mElements; - QList mInsetPlacement; - QList mInsetAlignment; - QList mInsetRect; - + // property members: + QList mElements; + QList mInsetPlacement; + QList mInsetAlignment; + QList mInsetRect; + private: - Q_DISABLE_COPY(QCPLayoutInset) + Q_DISABLE_COPY(QCPLayoutInset) }; Q_DECLARE_METATYPE(QCPLayoutInset::InsetPlacement) @@ -1492,58 +1696,66 @@ Q_DECLARE_METATYPE(QCPLayoutInset::InsetPlacement) class QCP_LIB_DECL QCPLineEnding { - Q_GADGET + Q_GADGET public: - /*! + /*! Defines the type of ending decoration for line-like items, e.g. an arrow. - + \image html QCPLineEnding.png - + The width and length of these decorations can be controlled with the functions \ref setWidth and \ref setLength. Some decorations like \ref esDisc, \ref esSquare, \ref esDiamond and \ref esBar only support a width, the length property is ignored. - + \see QCPItemLine::setHead, QCPItemLine::setTail, QCPItemCurve::setHead, QCPItemCurve::setTail, QCPAxis::setLowerEnding, QCPAxis::setUpperEnding - */ - 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 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); - - // getters: - EndingStyle style() const { return mStyle; } - double width() const { return mWidth; } - double length() const { return mLength; } - bool inverted() const { return mInverted; } - - // setters: - void setStyle(EndingStyle style); - void setWidth(double width); - void setLength(double length); - void setInverted(bool inverted); - - // non-property methods: - double boundingDistance() const; - double realLength() const; - void draw(QCPPainter *painter, const QCPVector2D &pos, const QCPVector2D &dir) const; - void draw(QCPPainter *painter, const QCPVector2D &pos, double angle) const; - + */ + 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 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); + + // getters: + EndingStyle style() const { + return mStyle; + } + double width() const { + return mWidth; + } + double length() const { + return mLength; + } + bool inverted() const { + return mInverted; + } + + // setters: + void setStyle(EndingStyle style); + void setWidth(double width); + void setLength(double length); + void setInverted(bool inverted); + + // non-property methods: + double boundingDistance() const; + double realLength() 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: - EndingStyle mStyle; - double mWidth, mLength; - bool mInverted; + // property members: + EndingStyle mStyle; + double mWidth, mLength; + bool mInverted; }; Q_DECLARE_TYPEINFO(QCPLineEnding, Q_MOVABLE_TYPE); Q_DECLARE_METATYPE(QCPLineEnding::EndingStyle) @@ -1556,133 +1768,153 @@ Q_DECLARE_METATYPE(QCPLineEnding::EndingStyle) class QCPLabelPainterPrivate { - Q_GADGET + Q_GADGET public: - /*! + /*! TODO - */ - enum AnchorMode { amRectangular ///< - ,amSkewedUpright ///< - ,amSkewedRotated ///< - }; - Q_ENUMS(AnchorMode) - - /*! - TODO - */ - enum AnchorReferenceType { artNormal ///< - ,artTangent ///< - }; - Q_ENUMS(AnchorReferenceType) - - /*! - TODO - */ - enum AnchorSide { asLeft ///< - ,asRight ///< - ,asTop ///< - ,asBottom ///< - ,asTopLeft - ,asTopRight - ,asBottomRight - ,asBottomLeft - }; - Q_ENUMS(AnchorSide) - - explicit QCPLabelPainterPrivate(QCustomPlot *parentPlot); - virtual ~QCPLabelPainterPrivate(); - - // setters: - void setAnchorSide(AnchorSide side); - void setAnchorMode(AnchorMode mode); - void setAnchorReference(const QPointF &pixelPoint); - void setAnchorReferenceType(AnchorReferenceType type); - void setFont(const QFont &font); - void setColor(const QColor &color); - void setPadding(int padding); - void setRotation(double rotation); - void setSubstituteExponent(bool enabled); - void setMultiplicationSymbol(QChar symbol); - void setAbbreviateDecimalPowers(bool enabled); - void setCacheSize(int labelCount); - - // getters: - AnchorMode anchorMode() const { return mAnchorMode; } - AnchorSide anchorSide() const { return mAnchorSide; } - QPointF anchorReference() const { return mAnchorReference; } - AnchorReferenceType anchorReferenceType() const { return mAnchorReferenceType; } - QFont font() const { return mFont; } - QColor color() const { return mColor; } - int padding() const { return mPadding; } - double rotation() const { return mRotation; } - bool substituteExponent() const { return mSubstituteExponent; } - QChar multiplicationSymbol() const { return mMultiplicationSymbol; } - bool abbreviateDecimalPowers() const { return mAbbreviateDecimalPowers; } - int cacheSize() const; - - //virtual int size() const; - - // non-property methods: - void drawTickLabel(QCPPainter *painter, const QPointF &tickPos, const QString &text); - void clearCache(); - - // constants that may be used with setMultiplicationSymbol: - static const QChar SymbolDot; - static const QChar SymbolCross; - -protected: - struct CachedLabel - { - QPoint offset; - QPixmap pixmap; - }; - struct LabelData - { - AnchorSide side; - double rotation; // angle in degrees - QTransform transform; // the transform about the label anchor which is at (0, 0). Does not contain final absolute x/y positioning on the plot/axis - QString basePart, expPart, suffixPart; - QRect baseBounds, expBounds, suffixBounds; - QRect totalBounds; // is in a coordinate system where label top left is at (0, 0) - QRect rotatedTotalBounds; // is in a coordinate system where the label anchor is at (0, 0) - QFont baseFont, expFont; - QColor color; - }; - - // property members: - AnchorMode mAnchorMode; - AnchorSide mAnchorSide; - QPointF mAnchorReference; - AnchorReferenceType mAnchorReferenceType; - QFont mFont; - QColor mColor; - int mPadding; - double mRotation; // this is the rotation applied uniformly to all labels, not the heterogeneous rotation in amCircularRotated mode - bool mSubstituteExponent; - QChar mMultiplicationSymbol; - bool mAbbreviateDecimalPowers; - // non-property members: - QCustomPlot *mParentPlot; - QByteArray mLabelParameterHash; // to determine whether mLabelCache needs to be cleared due to changed parameters - QCache mLabelCache; - QRect mAxisSelectionBox, mTickLabelsSelectionBox, mLabelSelectionBox; - int mLetterCapHeight, mLetterDescent; - - // introduced virtual methods: - virtual void drawLabelMaybeCached(QCPPainter *painter, const QFont &font, const QColor &color, const QPointF &pos, AnchorSide side, double rotation, const QString &text); - virtual QByteArray generateLabelParameterHash() const; // TODO: get rid of this in favor of invalidation flag upon setters? + */ + enum AnchorMode { amRectangular ///< + , amSkewedUpright ///< + , amSkewedRotated ///< + }; + Q_ENUMS(AnchorMode) - // non-virtual methods: - QPointF getAnchorPos(const QPointF &tickPos); - void drawText(QCPPainter *painter, const QPointF &pos, const LabelData &labelData) const; - LabelData getTickLabelData(const QFont &font, const QColor &color, double rotation, AnchorSide side, const QString &text) const; - void applyAnchorTransform(LabelData &labelData) const; - //void getMaxTickLabelSize(const QFont &font, const QString &text, QSize *tickLabelsSize) const; - CachedLabel *createCachedLabel(const LabelData &labelData) const; - QByteArray cacheKey(const QString &text, const QColor &color, double rotation, AnchorSide side) const; - AnchorSide skewedAnchorSide(const QPointF &tickPos, double sideExpandHorz, double sideExpandVert) const; - AnchorSide rotationCorrectedSide(AnchorSide side, double rotation) const; - void analyzeFontMetrics(); + /*! + TODO + */ + enum AnchorReferenceType { artNormal ///< + , artTangent ///< + }; + Q_ENUMS(AnchorReferenceType) + + /*! + TODO + */ + enum AnchorSide { asLeft ///< + , asRight ///< + , asTop ///< + , asBottom ///< + , asTopLeft + , asTopRight + , asBottomRight + , asBottomLeft + }; + Q_ENUMS(AnchorSide) + + explicit QCPLabelPainterPrivate(QCustomPlot *parentPlot); + virtual ~QCPLabelPainterPrivate(); + + // setters: + void setAnchorSide(AnchorSide side); + void setAnchorMode(AnchorMode mode); + void setAnchorReference(const QPointF &pixelPoint); + void setAnchorReferenceType(AnchorReferenceType type); + void setFont(const QFont &font); + void setColor(const QColor &color); + void setPadding(int padding); + void setRotation(double rotation); + void setSubstituteExponent(bool enabled); + void setMultiplicationSymbol(QChar symbol); + void setAbbreviateDecimalPowers(bool enabled); + void setCacheSize(int labelCount); + + // getters: + AnchorMode anchorMode() const { + return mAnchorMode; + } + AnchorSide anchorSide() const { + return mAnchorSide; + } + QPointF anchorReference() const { + return mAnchorReference; + } + AnchorReferenceType anchorReferenceType() const { + return mAnchorReferenceType; + } + QFont font() const { + return mFont; + } + QColor color() const { + return mColor; + } + int padding() const { + return mPadding; + } + double rotation() const { + return mRotation; + } + bool substituteExponent() const { + return mSubstituteExponent; + } + QChar multiplicationSymbol() const { + return mMultiplicationSymbol; + } + bool abbreviateDecimalPowers() const { + return mAbbreviateDecimalPowers; + } + int cacheSize() const; + + //virtual int size() const; + + // non-property methods: + void drawTickLabel(QCPPainter *painter, const QPointF &tickPos, const QString &text); + void clearCache(); + + // constants that may be used with setMultiplicationSymbol: + static const QChar SymbolDot; + static const QChar SymbolCross; + +protected: + struct CachedLabel { + QPoint offset; + QPixmap pixmap; + }; + struct LabelData { + AnchorSide side; + double rotation; // angle in degrees + QTransform transform; // the transform about the label anchor which is at (0, 0). Does not contain final absolute x/y positioning on the plot/axis + QString basePart, expPart, suffixPart; + QRect baseBounds, expBounds, suffixBounds; + QRect totalBounds; // is in a coordinate system where label top left is at (0, 0) + QRect rotatedTotalBounds; // is in a coordinate system where the label anchor is at (0, 0) + QFont baseFont, expFont; + QColor color; + }; + + // property members: + AnchorMode mAnchorMode; + AnchorSide mAnchorSide; + QPointF mAnchorReference; + AnchorReferenceType mAnchorReferenceType; + QFont mFont; + QColor mColor; + int mPadding; + double mRotation; // this is the rotation applied uniformly to all labels, not the heterogeneous rotation in amCircularRotated mode + bool mSubstituteExponent; + QChar mMultiplicationSymbol; + bool mAbbreviateDecimalPowers; + // non-property members: + QCustomPlot *mParentPlot; + QByteArray mLabelParameterHash; // to determine whether mLabelCache needs to be cleared due to changed parameters + QCache mLabelCache; + QRect mAxisSelectionBox, mTickLabelsSelectionBox, mLabelSelectionBox; + int mLetterCapHeight, mLetterDescent; + + // introduced virtual methods: + virtual void drawLabelMaybeCached(QCPPainter *painter, const QFont &font, const QColor &color, const QPointF &pos, AnchorSide side, double rotation, const QString &text); + virtual QByteArray generateLabelParameterHash() const; // TODO: get rid of this in favor of invalidation flag upon setters? + + // non-virtual methods: + QPointF getAnchorPos(const QPointF &tickPos); + void drawText(QCPPainter *painter, const QPointF &pos, const LabelData &labelData) const; + LabelData getTickLabelData(const QFont &font, const QColor &color, double rotation, AnchorSide side, const QString &text) const; + void applyAnchorTransform(LabelData &labelData) const; + //void getMaxTickLabelSize(const QFont &font, const QString &text, QSize *tickLabelsSize) const; + CachedLabel *createCachedLabel(const LabelData &labelData) const; + QByteArray cacheKey(const QString &text, const QColor &color, double rotation, AnchorSide side) const; + AnchorSide skewedAnchorSide(const QPointF &tickPos, double sideExpandHorz, double sideExpandVert) const; + AnchorSide rotationCorrectedSide(AnchorSide side, double rotation) const; + void analyzeFontMetrics(); }; Q_DECLARE_METATYPE(QCPLabelPainterPrivate::AnchorMode) Q_DECLARE_METATYPE(QCPLabelPainterPrivate::AnchorSide) @@ -1696,59 +1928,64 @@ Q_DECLARE_METATYPE(QCPLabelPainterPrivate::AnchorSide) class QCP_LIB_DECL QCPAxisTicker { - Q_GADGET + 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); - + */ + 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=nullptr) const; - double cleanMantissa(double input) const; - + // 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 = nullptr) const; + double cleanMantissa(double input) const; + private: - Q_DISABLE_COPY(QCPAxisTicker) - + Q_DISABLE_COPY(QCPAxisTicker) + }; Q_DECLARE_METATYPE(QCPAxisTicker::TickStepStrategy) Q_DECLARE_METATYPE(QSharedPointer) @@ -1762,44 +1999,50 @@ Q_DECLARE_METATYPE(QSharedPointer) class QCP_LIB_DECL QCPAxisTickerDateTime : public QCPAxisTicker { public: - QCPAxisTickerDateTime(); - - // getters: - QString dateTimeFormat() const { return mDateTimeFormat; } - Qt::TimeSpec dateTimeSpec() const { return mDateTimeSpec; } + QCPAxisTickerDateTime(); + + // getters: + QString dateTimeFormat() const { + return mDateTimeFormat; + } + Qt::TimeSpec dateTimeSpec() const { + return mDateTimeSpec; + } # if QT_VERSION >= QT_VERSION_CHECK(5, 2, 0) - QTimeZone timeZone() const { return mTimeZone; } + QTimeZone timeZone() const { + return mTimeZone; + } #endif - - // setters: - void setDateTimeFormat(const QString &format); - void setDateTimeSpec(Qt::TimeSpec spec); + + // setters: + void setDateTimeFormat(const QString &format); + void setDateTimeSpec(Qt::TimeSpec spec); # if QT_VERSION >= QT_VERSION_CHECK(5, 2, 0) - void setTimeZone(const QTimeZone &zone); + void setTimeZone(const QTimeZone &zone); # endif - 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, Qt::TimeSpec timeSpec=Qt::LocalTime); - + 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, Qt::TimeSpec timeSpec = Qt::LocalTime); + protected: - // property members: - QString mDateTimeFormat; - Qt::TimeSpec mDateTimeSpec; + // property members: + QString mDateTimeFormat; + Qt::TimeSpec mDateTimeSpec; # if QT_VERSION >= QT_VERSION_CHECK(5, 2, 0) - QTimeZone mTimeZone; + QTimeZone mTimeZone; # endif - // 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; + // 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' */ @@ -1810,47 +2053,51 @@ protected: class QCP_LIB_DECL QCPAxisTickerTime : public QCPAxisTicker { - Q_GADGET + Q_GADGET public: - /*! + /*! Defines the logical units in which fractions of time spans can be expressed. - - \see setFieldWidth, setTimeFormat - */ - enum TimeUnit { tuMilliseconds ///< Milliseconds, one thousandth of a second (%%z in \ref setTimeFormat) - ,tuSeconds ///< Seconds (%%s in \ref setTimeFormat) - ,tuMinutes ///< Minutes (%%m in \ref setTimeFormat) - ,tuHours ///< Hours (%%h in \ref setTimeFormat) - ,tuDays ///< Days (%%d in \ref setTimeFormat) - }; - 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); - + \see setFieldWidth, setTimeFormat + */ + enum TimeUnit { tuMilliseconds ///< Milliseconds, one thousandth of a second (%%z in \ref setTimeFormat) + , tuSeconds ///< Seconds (%%s in \ref setTimeFormat) + , tuMinutes ///< Minutes (%%m in \ref setTimeFormat) + , tuHours ///< Hours (%%h in \ref setTimeFormat) + , tuDays ///< Days (%%d in \ref setTimeFormat) + }; + 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; + // 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) @@ -1862,37 +2109,41 @@ Q_DECLARE_METATYPE(QCPAxisTickerTime::TimeUnit) class QCP_LIB_DECL QCPAxisTickerFixed : public QCPAxisTicker { - Q_GADGET + 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); - + */ + 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; + // property members: + double mTickStep; + ScaleStrategy mScaleStrategy; + + // reimplemented virtual methods: + virtual double getTickStep(const QCPRange &range) Q_DECL_OVERRIDE; }; Q_DECLARE_METATYPE(QCPAxisTickerFixed::ScaleStrategy) @@ -1905,33 +2156,37 @@ Q_DECLARE_METATYPE(QCPAxisTickerFixed::ScaleStrategy) 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, const QString &label); - void addTicks(const QMap &ticks); - void addTicks(const QVector &positions, const QVector &labels); - + 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, const 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; + // 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' */ @@ -1942,54 +2197,62 @@ protected: class QCP_LIB_DECL QCPAxisTickerPi : public QCPAxisTicker { - Q_GADGET + 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); - + */ + 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; + // 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) @@ -2002,27 +2265,31 @@ Q_DECLARE_METATYPE(QCPAxisTickerPi::FractionStyle) 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); - + 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 int getSubTickCount(double tickStep) Q_DECL_OVERRIDE; - virtual QVector createTickVector(double tickStep, const QCPRange &range) Q_DECL_OVERRIDE; + // property members: + double mLogBase; + int mSubTickCount; + + // non-property members: + double mLogBaseLnInv; + + // reimplemented virtual methods: + 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' */ @@ -2031,353 +2298,432 @@ protected: /* including file 'src/axis/axis.h' */ /* modified 2021-03-29T02:30:44, size 20913 */ -class QCP_LIB_DECL QCPGrid :public QCPLayerable +class QCP_LIB_DECL QCPGrid : public QCPLayerable { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(bool subGridVisible READ subGridVisible WRITE setSubGridVisible) - Q_PROPERTY(bool antialiasedSubGrid READ antialiasedSubGrid WRITE setAntialiasedSubGrid) - Q_PROPERTY(bool antialiasedZeroLine READ antialiasedZeroLine WRITE setAntialiasedZeroLine) - Q_PROPERTY(QPen pen READ pen WRITE setPen) - Q_PROPERTY(QPen subGridPen READ subGridPen WRITE setSubGridPen) - Q_PROPERTY(QPen zeroLinePen READ zeroLinePen WRITE setZeroLinePen) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(bool subGridVisible READ subGridVisible WRITE setSubGridVisible) + Q_PROPERTY(bool antialiasedSubGrid READ antialiasedSubGrid WRITE setAntialiasedSubGrid) + Q_PROPERTY(bool antialiasedZeroLine READ antialiasedZeroLine WRITE setAntialiasedZeroLine) + Q_PROPERTY(QPen pen READ pen WRITE setPen) + Q_PROPERTY(QPen subGridPen READ subGridPen WRITE setSubGridPen) + Q_PROPERTY(QPen zeroLinePen READ zeroLinePen WRITE setZeroLinePen) + /// \endcond public: - explicit QCPGrid(QCPAxis *parentAxis); - - // getters: - bool subGridVisible() const { return mSubGridVisible; } - bool antialiasedSubGrid() const { return mAntialiasedSubGrid; } - bool antialiasedZeroLine() const { return mAntialiasedZeroLine; } - QPen pen() const { return mPen; } - QPen subGridPen() const { return mSubGridPen; } - QPen zeroLinePen() const { return mZeroLinePen; } - - // setters: - void setSubGridVisible(bool visible); - void setAntialiasedSubGrid(bool enabled); - void setAntialiasedZeroLine(bool enabled); - void setPen(const QPen &pen); - void setSubGridPen(const QPen &pen); - void setZeroLinePen(const QPen &pen); - + explicit QCPGrid(QCPAxis *parentAxis); + + // getters: + bool subGridVisible() const { + return mSubGridVisible; + } + bool antialiasedSubGrid() const { + return mAntialiasedSubGrid; + } + bool antialiasedZeroLine() const { + return mAntialiasedZeroLine; + } + QPen pen() const { + return mPen; + } + QPen subGridPen() const { + return mSubGridPen; + } + QPen zeroLinePen() const { + return mZeroLinePen; + } + + // setters: + void setSubGridVisible(bool visible); + void setAntialiasedSubGrid(bool enabled); + void setAntialiasedZeroLine(bool enabled); + void setPen(const QPen &pen); + void setSubGridPen(const QPen &pen); + void setZeroLinePen(const QPen &pen); + protected: - // property members: - bool mSubGridVisible; - bool mAntialiasedSubGrid, mAntialiasedZeroLine; - QPen mPen, mSubGridPen, mZeroLinePen; - - // non-property members: - QCPAxis *mParentAxis; - - // reimplemented virtual methods: - 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; - void drawSubGridLines(QCPPainter *painter) const; - - friend class QCPAxis; + // property members: + bool mSubGridVisible; + bool mAntialiasedSubGrid, mAntialiasedZeroLine; + QPen mPen, mSubGridPen, mZeroLinePen; + + // non-property members: + QCPAxis *mParentAxis; + + // reimplemented virtual methods: + 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; + void drawSubGridLines(QCPPainter *painter) const; + + friend class QCPAxis; }; class QCP_LIB_DECL QCPAxis : public QCPLayerable { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(AxisType axisType READ axisType) - Q_PROPERTY(QCPAxisRect* axisRect READ axisRect) - Q_PROPERTY(ScaleType scaleType READ scaleType WRITE setScaleType NOTIFY scaleTypeChanged) - Q_PROPERTY(QCPRange range READ range WRITE setRange NOTIFY rangeChanged) - Q_PROPERTY(bool rangeReversed READ rangeReversed WRITE setRangeReversed) - 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(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 numberFormat READ numberFormat WRITE setNumberFormat) - Q_PROPERTY(int numberPrecision READ numberPrecision WRITE setNumberPrecision) - 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(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) - Q_PROPERTY(QPen tickPen READ tickPen WRITE setTickPen) - Q_PROPERTY(QPen subTickPen READ subTickPen WRITE setSubTickPen) - Q_PROPERTY(QFont labelFont READ labelFont WRITE setLabelFont) - Q_PROPERTY(QColor labelColor READ labelColor WRITE setLabelColor) - Q_PROPERTY(QString label READ label WRITE setLabel) - Q_PROPERTY(int labelPadding READ labelPadding WRITE setLabelPadding) - Q_PROPERTY(int padding READ padding WRITE setPadding) - Q_PROPERTY(int offset READ offset WRITE setOffset) - Q_PROPERTY(SelectableParts selectedParts READ selectedParts WRITE setSelectedParts NOTIFY selectionChanged) - Q_PROPERTY(SelectableParts selectableParts READ selectableParts WRITE setSelectableParts NOTIFY selectableChanged) - Q_PROPERTY(QFont selectedTickLabelFont READ selectedTickLabelFont WRITE setSelectedTickLabelFont) - Q_PROPERTY(QFont selectedLabelFont READ selectedLabelFont WRITE setSelectedLabelFont) - Q_PROPERTY(QColor selectedTickLabelColor READ selectedTickLabelColor WRITE setSelectedTickLabelColor) - Q_PROPERTY(QColor selectedLabelColor READ selectedLabelColor WRITE setSelectedLabelColor) - Q_PROPERTY(QPen selectedBasePen READ selectedBasePen WRITE setSelectedBasePen) - Q_PROPERTY(QPen selectedTickPen READ selectedTickPen WRITE setSelectedTickPen) - Q_PROPERTY(QPen selectedSubTickPen READ selectedSubTickPen WRITE setSelectedSubTickPen) - Q_PROPERTY(QCPLineEnding lowerEnding READ lowerEnding WRITE setLowerEnding) - Q_PROPERTY(QCPLineEnding upperEnding READ upperEnding WRITE setUpperEnding) - Q_PROPERTY(QCPGrid* grid READ grid) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(AxisType axisType READ axisType) + Q_PROPERTY(QCPAxisRect *axisRect READ axisRect) + Q_PROPERTY(ScaleType scaleType READ scaleType WRITE setScaleType NOTIFY scaleTypeChanged) + Q_PROPERTY(QCPRange range READ range WRITE setRange NOTIFY rangeChanged) + Q_PROPERTY(bool rangeReversed READ rangeReversed WRITE setRangeReversed) + 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(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 numberFormat READ numberFormat WRITE setNumberFormat) + Q_PROPERTY(int numberPrecision READ numberPrecision WRITE setNumberPrecision) + 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(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) + Q_PROPERTY(QPen tickPen READ tickPen WRITE setTickPen) + Q_PROPERTY(QPen subTickPen READ subTickPen WRITE setSubTickPen) + Q_PROPERTY(QFont labelFont READ labelFont WRITE setLabelFont) + Q_PROPERTY(QColor labelColor READ labelColor WRITE setLabelColor) + Q_PROPERTY(QString label READ label WRITE setLabel) + Q_PROPERTY(int labelPadding READ labelPadding WRITE setLabelPadding) + Q_PROPERTY(int padding READ padding WRITE setPadding) + Q_PROPERTY(int offset READ offset WRITE setOffset) + Q_PROPERTY(SelectableParts selectedParts READ selectedParts WRITE setSelectedParts NOTIFY selectionChanged) + Q_PROPERTY(SelectableParts selectableParts READ selectableParts WRITE setSelectableParts NOTIFY selectableChanged) + Q_PROPERTY(QFont selectedTickLabelFont READ selectedTickLabelFont WRITE setSelectedTickLabelFont) + Q_PROPERTY(QFont selectedLabelFont READ selectedLabelFont WRITE setSelectedLabelFont) + Q_PROPERTY(QColor selectedTickLabelColor READ selectedTickLabelColor WRITE setSelectedTickLabelColor) + Q_PROPERTY(QColor selectedLabelColor READ selectedLabelColor WRITE setSelectedLabelColor) + Q_PROPERTY(QPen selectedBasePen READ selectedBasePen WRITE setSelectedBasePen) + Q_PROPERTY(QPen selectedTickPen READ selectedTickPen WRITE setSelectedTickPen) + Q_PROPERTY(QPen selectedSubTickPen READ selectedSubTickPen WRITE setSelectedSubTickPen) + Q_PROPERTY(QCPLineEnding lowerEnding READ lowerEnding WRITE setLowerEnding) + Q_PROPERTY(QCPLineEnding upperEnding READ upperEnding WRITE setUpperEnding) + Q_PROPERTY(QCPGrid *grid READ grid) + /// \endcond public: - /*! + /*! Defines at which side of the axis rect the axis will appear. This also affects how the tick marks are drawn, on which side the labels are placed etc. - */ - enum AxisType { atLeft = 0x01 ///< 0x01 Axis is vertical and on the left side of the axis rect - ,atRight = 0x02 ///< 0x02 Axis is vertical and on the right side of the axis rect - ,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_ENUMS(AxisType) - Q_FLAGS(AxisTypes) - Q_DECLARE_FLAGS(AxisTypes, AxisType) - /*! + */ + enum AxisType { atLeft = 0x01 ///< 0x01 Axis is vertical and on the left side of the axis rect + , atRight = 0x02 ///< 0x02 Axis is vertical and on the right side of the axis rect + , 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_ENUMS(AxisType) + Q_FLAGS(AxisTypes) + Q_DECLARE_FLAGS(AxisTypes, AxisType) + /*! Defines on which side of the axis the tick labels (numbers) shall appear. - + \see setTickLabelSide - */ - enum LabelSide { lsInside ///< Tick labels will be displayed inside the axis rect and clipped to the inner axis rect - ,lsOutside ///< Tick labels will be displayed outside the axis rect - }; - Q_ENUMS(LabelSide) - /*! + */ + enum LabelSide { lsInside ///< Tick labels will be displayed inside the axis rect and clipped to the inner axis rect + , lsOutside ///< Tick labels will be displayed outside the axis rect + }; + Q_ENUMS(LabelSide) + /*! Defines the scale of an axis. \see setScaleType - */ - enum ScaleType { stLinear ///< Linear scaling - ,stLogarithmic ///< Logarithmic scaling with correspondingly transformed axis coordinates (possibly also \ref setTicker to a \ref QCPAxisTickerLog instance). - }; - Q_ENUMS(ScaleType) - /*! + */ + enum ScaleType { stLinear ///< Linear scaling + , stLogarithmic ///< Logarithmic scaling with correspondingly transformed axis coordinates (possibly also \ref setTicker to a \ref QCPAxisTickerLog instance). + }; + Q_ENUMS(ScaleType) + /*! Defines the selectable parts of an axis. \see setSelectableParts, setSelectedParts - */ - enum SelectablePart { spNone = 0 ///< None of the selectable parts - ,spAxis = 0x001 ///< The axis backbone and tick marks - ,spTickLabels = 0x002 ///< Tick labels (numbers) of this axis (as a whole, not individually) - ,spAxisLabel = 0x004 ///< The axis label - }; - Q_ENUMS(SelectablePart) - Q_FLAGS(SelectableParts) - Q_DECLARE_FLAGS(SelectableParts, SelectablePart) - - explicit QCPAxis(QCPAxisRect *parent, AxisType type); - virtual ~QCPAxis() Q_DECL_OVERRIDE; - - // getters: - AxisType axisType() const { return mAxisType; } - QCPAxisRect *axisRect() const { return mAxisRect; } - ScaleType scaleType() const { return mScaleType; } - const QCPRange range() const { return mRange; } - bool rangeReversed() const { return mRangeReversed; } - QSharedPointer ticker() const { return mTicker; } - bool ticks() const { return mTicks; } - bool tickLabels() const { return mTickLabels; } - int tickLabelPadding() const; - QFont tickLabelFont() const { return mTickLabelFont; } - QColor tickLabelColor() const { return mTickLabelColor; } - double tickLabelRotation() const; - LabelSide tickLabelSide() const; - QString numberFormat() const; - int numberPrecision() const { return mNumberPrecision; } - QVector tickVector() const { return mTickVector; } - QVector tickVectorLabels() const { return mTickVectorLabels; } - int tickLengthIn() const; - int tickLengthOut() const; - bool subTicks() const { return mSubTicks; } - int subTickLengthIn() const; - int subTickLengthOut() const; - QPen basePen() const { return mBasePen; } - QPen tickPen() const { return mTickPen; } - QPen subTickPen() const { return mSubTickPen; } - QFont labelFont() const { return mLabelFont; } - QColor labelColor() const { return mLabelColor; } - QString label() const { return mLabel; } - int labelPadding() const; - int padding() const { return mPadding; } - int offset() const; - SelectableParts selectedParts() const { return mSelectedParts; } - SelectableParts selectableParts() const { return mSelectableParts; } - QFont selectedTickLabelFont() const { return mSelectedTickLabelFont; } - QFont selectedLabelFont() const { return mSelectedLabelFont; } - QColor selectedTickLabelColor() const { return mSelectedTickLabelColor; } - QColor selectedLabelColor() const { return mSelectedLabelColor; } - QPen selectedBasePen() const { return mSelectedBasePen; } - QPen selectedTickPen() const { return mSelectedTickPen; } - QPen selectedSubTickPen() const { return mSelectedSubTickPen; } - QCPLineEnding lowerEnding() const; - QCPLineEnding upperEnding() const; - QCPGrid *grid() const { return mGrid; } - - // setters: - Q_SLOT void setScaleType(QCPAxis::ScaleType type); - 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 setTicker(QSharedPointer ticker); - void setTicks(bool show); - void setTickLabels(bool show); - void setTickLabelPadding(int padding); - void setTickLabelFont(const QFont &font); - void setTickLabelColor(const QColor &color); - void setTickLabelRotation(double degrees); - void setTickLabelSide(LabelSide side); - void setNumberFormat(const QString &formatCode); - void setNumberPrecision(int precision); - void setTickLength(int inside, int outside=0); - void setTickLengthIn(int inside); - void setTickLengthOut(int outside); - void setSubTicks(bool show); - void setSubTickLength(int inside, int outside=0); - void setSubTickLengthIn(int inside); - void setSubTickLengthOut(int outside); - void setBasePen(const QPen &pen); - void setTickPen(const QPen &pen); - void setSubTickPen(const QPen &pen); - void setLabelFont(const QFont &font); - void setLabelColor(const QColor &color); - void setLabel(const QString &str); - void setLabelPadding(int padding); - void setPadding(int padding); - void setOffset(int offset); - void setSelectedTickLabelFont(const QFont &font); - void setSelectedLabelFont(const QFont &font); - void setSelectedTickLabelColor(const QColor &color); - void setSelectedLabelColor(const QColor &color); - void setSelectedBasePen(const QPen &pen); - void setSelectedTickPen(const QPen &pen); - void setSelectedSubTickPen(const QPen &pen); - Q_SLOT void setSelectableParts(const QCPAxis::SelectableParts &selectableParts); - Q_SLOT void setSelectedParts(const QCPAxis::SelectableParts &selectedParts); - void setLowerEnding(const QCPLineEnding &ending); - void setUpperEnding(const QCPLineEnding &ending); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) 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); - double pixelToCoord(double value) const; - double coordToPixel(double value) const; - SelectablePart getPartAt(const QPointF &pos) const; - QList plottables() const; - QList graphs() const; - QList items() const; - - static AxisType marginSideToAxisType(QCP::MarginSide side); - static Qt::Orientation orientation(AxisType type) { return type==atBottom || type==atTop ? Qt::Horizontal : Qt::Vertical; } - static AxisType opposite(AxisType type); - + */ + enum SelectablePart { spNone = 0 ///< None of the selectable parts + , spAxis = 0x001 ///< The axis backbone and tick marks + , spTickLabels = 0x002 ///< Tick labels (numbers) of this axis (as a whole, not individually) + , spAxisLabel = 0x004 ///< The axis label + }; + Q_ENUMS(SelectablePart) + Q_FLAGS(SelectableParts) + Q_DECLARE_FLAGS(SelectableParts, SelectablePart) + + explicit QCPAxis(QCPAxisRect *parent, AxisType type); + virtual ~QCPAxis() Q_DECL_OVERRIDE; + + // getters: + AxisType axisType() const { + return mAxisType; + } + QCPAxisRect *axisRect() const { + return mAxisRect; + } + ScaleType scaleType() const { + return mScaleType; + } + const QCPRange range() const { + return mRange; + } + bool rangeReversed() const { + return mRangeReversed; + } + QSharedPointer ticker() const { + return mTicker; + } + bool ticks() const { + return mTicks; + } + bool tickLabels() const { + return mTickLabels; + } + int tickLabelPadding() const; + QFont tickLabelFont() const { + return mTickLabelFont; + } + QColor tickLabelColor() const { + return mTickLabelColor; + } + double tickLabelRotation() const; + LabelSide tickLabelSide() const; + QString numberFormat() const; + int numberPrecision() const { + return mNumberPrecision; + } + QVector tickVector() const { + return mTickVector; + } + QVector tickVectorLabels() const { + return mTickVectorLabels; + } + int tickLengthIn() const; + int tickLengthOut() const; + bool subTicks() const { + return mSubTicks; + } + int subTickLengthIn() const; + int subTickLengthOut() const; + QPen basePen() const { + return mBasePen; + } + QPen tickPen() const { + return mTickPen; + } + QPen subTickPen() const { + return mSubTickPen; + } + QFont labelFont() const { + return mLabelFont; + } + QColor labelColor() const { + return mLabelColor; + } + QString label() const { + return mLabel; + } + int labelPadding() const; + int padding() const { + return mPadding; + } + int offset() const; + SelectableParts selectedParts() const { + return mSelectedParts; + } + SelectableParts selectableParts() const { + return mSelectableParts; + } + QFont selectedTickLabelFont() const { + return mSelectedTickLabelFont; + } + QFont selectedLabelFont() const { + return mSelectedLabelFont; + } + QColor selectedTickLabelColor() const { + return mSelectedTickLabelColor; + } + QColor selectedLabelColor() const { + return mSelectedLabelColor; + } + QPen selectedBasePen() const { + return mSelectedBasePen; + } + QPen selectedTickPen() const { + return mSelectedTickPen; + } + QPen selectedSubTickPen() const { + return mSelectedSubTickPen; + } + QCPLineEnding lowerEnding() const; + QCPLineEnding upperEnding() const; + QCPGrid *grid() const { + return mGrid; + } + + // setters: + Q_SLOT void setScaleType(QCPAxis::ScaleType type); + 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 setTicker(QSharedPointer ticker); + void setTicks(bool show); + void setTickLabels(bool show); + void setTickLabelPadding(int padding); + void setTickLabelFont(const QFont &font); + void setTickLabelColor(const QColor &color); + void setTickLabelRotation(double degrees); + void setTickLabelSide(LabelSide side); + void setNumberFormat(const QString &formatCode); + void setNumberPrecision(int precision); + void setTickLength(int inside, int outside = 0); + void setTickLengthIn(int inside); + void setTickLengthOut(int outside); + void setSubTicks(bool show); + void setSubTickLength(int inside, int outside = 0); + void setSubTickLengthIn(int inside); + void setSubTickLengthOut(int outside); + void setBasePen(const QPen &pen); + void setTickPen(const QPen &pen); + void setSubTickPen(const QPen &pen); + void setLabelFont(const QFont &font); + void setLabelColor(const QColor &color); + void setLabel(const QString &str); + void setLabelPadding(int padding); + void setPadding(int padding); + void setOffset(int offset); + void setSelectedTickLabelFont(const QFont &font); + void setSelectedLabelFont(const QFont &font); + void setSelectedTickLabelColor(const QColor &color); + void setSelectedLabelColor(const QColor &color); + void setSelectedBasePen(const QPen &pen); + void setSelectedTickPen(const QPen &pen); + void setSelectedSubTickPen(const QPen &pen); + Q_SLOT void setSelectableParts(const QCPAxis::SelectableParts &selectableParts); + Q_SLOT void setSelectedParts(const QCPAxis::SelectableParts &selectedParts); + void setLowerEnding(const QCPLineEnding &ending); + void setUpperEnding(const QCPLineEnding &ending); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = nullptr) 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); + double pixelToCoord(double value) const; + double coordToPixel(double value) const; + SelectablePart getPartAt(const QPointF &pos) const; + QList plottables() const; + QList graphs() const; + QList items() const; + + static AxisType marginSideToAxisType(QCP::MarginSide side); + static Qt::Orientation orientation(AxisType type) { + return type == atBottom || type == atTop ? Qt::Horizontal : Qt::Vertical; + } + static AxisType opposite(AxisType type); + signals: - void rangeChanged(const QCPRange &newRange); - void rangeChanged(const QCPRange &newRange, const QCPRange &oldRange); - void scaleTypeChanged(QCPAxis::ScaleType scaleType); - void selectionChanged(const QCPAxis::SelectableParts &parts); - void selectableChanged(const QCPAxis::SelectableParts &parts); + void rangeChanged(const QCPRange &newRange); + void rangeChanged(const QCPRange &newRange, const QCPRange &oldRange); + void scaleTypeChanged(QCPAxis::ScaleType scaleType); + void selectionChanged(const QCPAxis::SelectableParts &parts); + void selectableChanged(const QCPAxis::SelectableParts &parts); protected: - // property members: - // axis base: - AxisType mAxisType; - QCPAxisRect *mAxisRect; - //int mOffset; // in QCPAxisPainter - int mPadding; - Qt::Orientation mOrientation; - SelectableParts mSelectableParts, mSelectedParts; - QPen mBasePen, mSelectedBasePen; - //QCPLineEnding mLowerEnding, mUpperEnding; // in QCPAxisPainter - // axis label: - //int mLabelPadding; // in QCPAxisPainter - QString mLabel; - QFont mLabelFont, mSelectedLabelFont; - QColor mLabelColor, mSelectedLabelColor; - // tick labels: - //int mTickLabelPadding; // in QCPAxisPainter - bool mTickLabels; - //double mTickLabelRotation; // in QCPAxisPainter - QFont mTickLabelFont, mSelectedTickLabelFont; - QColor mTickLabelColor, mSelectedTickLabelColor; - int mNumberPrecision; - QLatin1Char mNumberFormatChar; - bool mNumberBeautifulPowers; - //bool mNumberMultiplyCross; // QCPAxisPainter - // ticks and subticks: - bool mTicks; - bool mSubTicks; - //int mTickLengthIn, mTickLengthOut, mSubTickLengthIn, mSubTickLengthOut; // QCPAxisPainter - QPen mTickPen, mSelectedTickPen; - QPen mSubTickPen, mSelectedSubTickPen; - // scale and range: - QCPRange mRange; - bool mRangeReversed; - ScaleType mScaleType; - - // non-property members: - QCPGrid *mGrid; - QCPAxisPainterPrivate *mAxisPainter; - QSharedPointer mTicker; - QVector mTickVector; - QVector mTickVectorLabels; - QVector mSubTickVector; - bool mCachedMarginValid; - int mCachedMargin; - bool mDragging; - QCPRange mDragStartRange; - QCP::AntialiasedElements mAADragBackup, mNotAADragBackup; - - // introduced virtual methods: - virtual int calculateMargin(); - - // reimplemented virtual methods: - 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) Q_DECL_OVERRIDE; - virtual void deselectEvent(bool *selectionStateChanged) Q_DECL_OVERRIDE; - // mouse events: - 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-virtual methods: - void setupTickVectors(); - QPen getBasePen() const; - QPen getTickPen() const; - QPen getSubTickPen() const; - QFont getTickLabelFont() const; - QFont getLabelFont() const; - QColor getTickLabelColor() const; - QColor getLabelColor() const; - + // property members: + // axis base: + AxisType mAxisType; + QCPAxisRect *mAxisRect; + //int mOffset; // in QCPAxisPainter + int mPadding; + Qt::Orientation mOrientation; + SelectableParts mSelectableParts, mSelectedParts; + QPen mBasePen, mSelectedBasePen; + //QCPLineEnding mLowerEnding, mUpperEnding; // in QCPAxisPainter + // axis label: + //int mLabelPadding; // in QCPAxisPainter + QString mLabel; + QFont mLabelFont, mSelectedLabelFont; + QColor mLabelColor, mSelectedLabelColor; + // tick labels: + //int mTickLabelPadding; // in QCPAxisPainter + bool mTickLabels; + //double mTickLabelRotation; // in QCPAxisPainter + QFont mTickLabelFont, mSelectedTickLabelFont; + QColor mTickLabelColor, mSelectedTickLabelColor; + int mNumberPrecision; + QLatin1Char mNumberFormatChar; + bool mNumberBeautifulPowers; + //bool mNumberMultiplyCross; // QCPAxisPainter + // ticks and subticks: + bool mTicks; + bool mSubTicks; + //int mTickLengthIn, mTickLengthOut, mSubTickLengthIn, mSubTickLengthOut; // QCPAxisPainter + QPen mTickPen, mSelectedTickPen; + QPen mSubTickPen, mSelectedSubTickPen; + // scale and range: + QCPRange mRange; + bool mRangeReversed; + ScaleType mScaleType; + + // non-property members: + QCPGrid *mGrid; + QCPAxisPainterPrivate *mAxisPainter; + QSharedPointer mTicker; + QVector mTickVector; + QVector mTickVectorLabels; + QVector mSubTickVector; + bool mCachedMarginValid; + int mCachedMargin; + bool mDragging; + QCPRange mDragStartRange; + QCP::AntialiasedElements mAADragBackup, mNotAADragBackup; + + // introduced virtual methods: + virtual int calculateMargin(); + + // reimplemented virtual methods: + 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) Q_DECL_OVERRIDE; + virtual void deselectEvent(bool *selectionStateChanged) Q_DECL_OVERRIDE; + // mouse events: + 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-virtual methods: + void setupTickVectors(); + QPen getBasePen() const; + QPen getTickPen() const; + QPen getSubTickPen() const; + QFont getTickLabelFont() const; + QFont getLabelFont() const; + QColor getTickLabelColor() const; + QColor getLabelColor() const; + private: - Q_DISABLE_COPY(QCPAxis) - - friend class QCustomPlot; - friend class QCPGrid; - friend class QCPAxisRect; + Q_DISABLE_COPY(QCPAxis) + + friend class QCustomPlot; + friend class QCPGrid; + friend class QCPAxisRect; }; Q_DECLARE_OPERATORS_FOR_FLAGS(QCPAxis::SelectableParts) Q_DECLARE_OPERATORS_FOR_FLAGS(QCPAxis::AxisTypes) @@ -2390,67 +2736,71 @@ Q_DECLARE_METATYPE(QCPAxis::SelectablePart) class QCPAxisPainterPrivate { public: - explicit QCPAxisPainterPrivate(QCustomPlot *parentPlot); - virtual ~QCPAxisPainterPrivate(); - - virtual void draw(QCPPainter *painter); - virtual int size(); - void clearCache(); - - QRect axisSelectionBox() const { return mAxisSelectionBox; } - QRect tickLabelsSelectionBox() const { return mTickLabelsSelectionBox; } - QRect labelSelectionBox() const { return mLabelSelectionBox; } - - // public property members: - QCPAxis::AxisType type; - QPen basePen; - QCPLineEnding lowerEnding, upperEnding; // directly accessed by QCPAxis setters/getters - int labelPadding; // directly accessed by QCPAxis setters/getters - QFont labelFont; - QColor labelColor; - QString label; - int tickLabelPadding; // directly accessed by QCPAxis setters/getters - double tickLabelRotation; // directly accessed by QCPAxis setters/getters - QCPAxis::LabelSide tickLabelSide; // directly accessed by QCPAxis setters/getters - bool substituteExponent; - bool numberMultiplyCross; // directly accessed by QCPAxis setters/getters - int tickLengthIn, tickLengthOut, subTickLengthIn, subTickLengthOut; // directly accessed by QCPAxis setters/getters - QPen tickPen, subTickPen; - QFont tickLabelFont; - QColor tickLabelColor; - QRect axisRect, viewportRect; - int offset; // directly accessed by QCPAxis setters/getters - bool abbreviateDecimalPowers; - bool reversedEndings; - - QVector subTickPositions; - QVector tickPositions; - QVector tickLabels; - + explicit QCPAxisPainterPrivate(QCustomPlot *parentPlot); + virtual ~QCPAxisPainterPrivate(); + + virtual void draw(QCPPainter *painter); + virtual int size(); + void clearCache(); + + QRect axisSelectionBox() const { + return mAxisSelectionBox; + } + QRect tickLabelsSelectionBox() const { + return mTickLabelsSelectionBox; + } + QRect labelSelectionBox() const { + return mLabelSelectionBox; + } + + // public property members: + QCPAxis::AxisType type; + QPen basePen; + QCPLineEnding lowerEnding, upperEnding; // directly accessed by QCPAxis setters/getters + int labelPadding; // directly accessed by QCPAxis setters/getters + QFont labelFont; + QColor labelColor; + QString label; + int tickLabelPadding; // directly accessed by QCPAxis setters/getters + double tickLabelRotation; // directly accessed by QCPAxis setters/getters + QCPAxis::LabelSide tickLabelSide; // directly accessed by QCPAxis setters/getters + bool substituteExponent; + bool numberMultiplyCross; // directly accessed by QCPAxis setters/getters + int tickLengthIn, tickLengthOut, subTickLengthIn, subTickLengthOut; // directly accessed by QCPAxis setters/getters + QPen tickPen, subTickPen; + QFont tickLabelFont; + QColor tickLabelColor; + QRect axisRect, viewportRect; + int offset; // directly accessed by QCPAxis setters/getters + bool abbreviateDecimalPowers; + bool reversedEndings; + + QVector subTickPositions; + QVector tickPositions; + QVector tickLabels; + protected: - struct CachedLabel - { - QPointF offset; - QPixmap pixmap; - }; - struct TickLabelData - { - QString basePart, expPart, suffixPart; - QRect baseBounds, expBounds, suffixBounds, totalBounds, rotatedTotalBounds; - QFont baseFont, expFont; - }; - QCustomPlot *mParentPlot; - QByteArray mLabelParameterHash; // to determine whether mLabelCache needs to be cleared due to changed parameters - QCache mLabelCache; - QRect mAxisSelectionBox, mTickLabelsSelectionBox, mLabelSelectionBox; - - virtual QByteArray generateLabelParameterHash() const; - - virtual void placeTickLabel(QCPPainter *painter, double position, int distanceToAxis, const QString &text, QSize *tickLabelsSize); - virtual void drawTickLabel(QCPPainter *painter, double x, double y, const TickLabelData &labelData) const; - virtual TickLabelData getTickLabelData(const QFont &font, const QString &text) const; - virtual QPointF getTickLabelDrawOffset(const TickLabelData &labelData) const; - virtual void getMaxTickLabelSize(const QFont &font, const QString &text, QSize *tickLabelsSize) const; + struct CachedLabel { + QPointF offset; + QPixmap pixmap; + }; + struct TickLabelData { + QString basePart, expPart, suffixPart; + QRect baseBounds, expBounds, suffixBounds, totalBounds, rotatedTotalBounds; + QFont baseFont, expFont; + }; + QCustomPlot *mParentPlot; + QByteArray mLabelParameterHash; // to determine whether mLabelCache needs to be cleared due to changed parameters + QCache mLabelCache; + QRect mAxisSelectionBox, mTickLabelsSelectionBox, mLabelSelectionBox; + + virtual QByteArray generateLabelParameterHash() const; + + virtual void placeTickLabel(QCPPainter *painter, double position, int distanceToAxis, const QString &text, QSize *tickLabelsSize); + virtual void drawTickLabel(QCPPainter *painter, double x, double y, const TickLabelData &labelData) const; + virtual TickLabelData getTickLabelData(const QFont &font, const QString &text) const; + virtual QPointF getTickLabelDrawOffset(const TickLabelData &labelData) const; + virtual void getMaxTickLabelSize(const QFont &font, const QString &text, QSize *tickLabelsSize) const; }; /* end of 'src/axis/axis.h' */ @@ -2461,99 +2811,115 @@ protected: class QCP_LIB_DECL QCPScatterStyle { - Q_GADGET + 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) + */ + 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) + */ + 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; } + 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); - // 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); + // 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; + } - // 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; + // 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; + // 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) @@ -2572,63 +2938,84 @@ Q_DECLARE_METATYPE(QCPScatterStyle::ScatterShape) \see QCPDataContainer::sort */ template -inline bool qcpLessThanSortKey(const DataType &a, const DataType &b) { return a.sortKey() < b.sortKey(); } +inline bool qcpLessThanSortKey(const DataType &a, const DataType &b) +{ + return a.sortKey() < b.sortKey(); +} template class QCPDataContainer // no QCP_LIB_DECL, template class ends up in header (cpp included below) { 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; - + 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(); + // property members: + bool mAutoSqueeze; + + // non-property memebers: + QVector mData; + int mPreallocSize; + int mPreallocIteration; + + // non-virtual methods: + void preallocateGrow(int minimumPreallocSize); + void performAutoSqueeze(); }; @@ -2708,27 +3095,27 @@ protected: /* 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 @@ -2737,9 +3124,9 @@ protected: */ /*! \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. @@ -2769,9 +3156,9 @@ protected: */ template QCPDataContainer::QCPDataContainer() : - mAutoSqueeze(true), - mPreallocSize(0), - mPreallocIteration(0) + mAutoSqueeze(true), + mPreallocSize(0), + mPreallocIteration(0) { } @@ -2779,160 +3166,162 @@ QCPDataContainer::QCPDataContainer() : 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(); - } + 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); + 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(); + 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); - } + 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); - } + 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); - } + 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 += int(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(); + QCPDataContainer::iterator it = begin(); + QCPDataContainer::iterator itEnd = std::lower_bound(begin(), end(), DataType::fromSortKey(sortKey), qcpLessThanSortKey); + mPreallocSize += int(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(); + } } /*! @@ -2943,68 +3332,72 @@ void QCPDataContainer::removeBefore(double sortKey) 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(); + 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(); + 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(); + 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; + mData.clear(); + mPreallocIteration = 0; + mPreallocSize = 0; } /*! @@ -3021,34 +3414,33 @@ void QCPDataContainer::clear() template void QCPDataContainer::sort() { - std::sort(begin(), end(), qcpLessThanSortKey); + 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; + if (preAllocation) { + if (mPreallocSize > 0) { + std::copy(begin(), end(), mData.begin()); + mData.resize(size()); + mPreallocSize = 0; + } + mPreallocIteration = 0; + } + if (postAllocation) { + mData.squeeze(); } - mPreallocIteration = 0; - } - if (postAllocation) - mData.squeeze(); } /*! @@ -3069,13 +3461,15 @@ void QCPDataContainer::squeeze(bool preAllocation, bool postAllocation 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; + 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; } /*! @@ -3096,13 +3490,15 @@ typename QCPDataContainer::const_iterator QCPDataContainer:: 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; + if (isEmpty()) { + return constEnd(); + } + + QCPDataContainer::const_iterator it = std::upper_bound(constBegin(), constEnd(), DataType::fromSortKey(sortKey), qcpLessThanSortKey); + if (expandedRange && it != constEnd()) { + ++it; + } + return it; } /*! @@ -3110,121 +3506,99 @@ typename QCPDataContainer::const_iterator QCPDataContainer:: 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; - } + if (isEmpty()) { + foundRange = false; + return QCPRange(); } - } 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; + 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; + } } - if ((current > range.upper || !haveUpper) && current < 0) - { - range.upper = current; - haveUpper = true; + } 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; } - } - ++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; + + foundRange = haveLower && haveUpper; + return range; } /*! @@ -3246,134 +3620,124 @@ QCPRange QCPDataContainer::keyRange(bool &foundRange, QCP::SignDomain 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, false); - itEnd = findEnd(inKeyRange.upper, false); - } - 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; - } + if (isEmpty()) { + foundRange = false; + return QCPRange(); } - } 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; - } + 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, false); + itEnd = findEnd(inKeyRange.upper, false); } - } 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; - } + 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; + + 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. The initial range described by the passed iterators \a begin and \a end is never expanded, only contracted if necessary. - + 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(int(begin-constBegin()), int(end-constBegin())); - iteratorRange = iteratorRange.bounded(dataRange.bounded(this->dataRange())); - begin = constBegin()+iteratorRange.begin(); - end = constBegin()+iteratorRange.end(); + QCPDataRange iteratorRange(int(begin - constBegin()), int(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<::preallocateGrow(int minimumPreallocSize) template 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); + 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); + } } @@ -3410,152 +3773,182 @@ void QCPDataContainer::performAutoSqueeze() 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); - + 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); - + // 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_DISABLE_COPY(QCPSelectionDecorator) + friend class QCPAbstractPlottable; }; -Q_DECLARE_METATYPE(QCPSelectionDecorator*) +Q_DECLARE_METATYPE(QCPSelectionDecorator *) class QCP_LIB_DECL QCPAbstractPlottable : public QCPLayerable { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - 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(QPen pen READ pen WRITE setPen) - Q_PROPERTY(QBrush brush READ brush WRITE setBrush) - Q_PROPERTY(QCPAxis* keyAxis READ keyAxis WRITE setKeyAxis) - Q_PROPERTY(QCPAxis* valueAxis READ valueAxis WRITE setValueAxis) - 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 + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES 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(QPen pen READ pen WRITE setPen) + Q_PROPERTY(QBrush brush READ brush WRITE setBrush) + Q_PROPERTY(QCPAxis *keyAxis READ keyAxis WRITE setKeyAxis) + Q_PROPERTY(QCPAxis *valueAxis READ valueAxis WRITE setValueAxis) + 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() Q_DECL_OVERRIDE; - - // getters: - QString name() const { return mName; } - bool antialiasedFill() const { return mAntialiasedFill; } - bool antialiasedScatters() const { return mAntialiasedScatters; } - QPen pen() const { return mPen; } - QBrush brush() const { return mBrush; } - QCPAxis *keyAxis() const { return mKeyAxis.data(); } - QCPAxis *valueAxis() const { return mValueAxis.data(); } - 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 setPen(const QPen &pen); - void setBrush(const QBrush &brush); - void setKeyAxis(QCPAxis *axis); - void setValueAxis(QCPAxis *axis); - Q_SLOT void setSelectable(QCP::SelectionType selectable); - Q_SLOT void setSelection(QCPDataSelection selection); - void setSelectionDecorator(QCPSelectionDecorator *decorator); + QCPAbstractPlottable(QCPAxis *keyAxis, QCPAxis *valueAxis); + virtual ~QCPAbstractPlottable() Q_DECL_OVERRIDE; + + // getters: + QString name() const { + return mName; + } + bool antialiasedFill() const { + return mAntialiasedFill; + } + bool antialiasedScatters() const { + return mAntialiasedScatters; + } + QPen pen() const { + return mPen; + } + QBrush brush() const { + return mBrush; + } + QCPAxis *keyAxis() const { + return mKeyAxis.data(); + } + QCPAxis *valueAxis() const { + return mValueAxis.data(); + } + 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 setPen(const QPen &pen); + void setBrush(const QBrush &brush); + void setKeyAxis(QCPAxis *axis); + void setValueAxis(QCPAxis *axis); + Q_SLOT void setSelectable(QCP::SelectionType selectable); + Q_SLOT void setSelection(QCPDataSelection selection); + void setSelectionDecorator(QCPSelectionDecorator *decorator); + + // introduced virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = nullptr) const Q_DECL_OVERRIDE = 0; // actually introduced in QCPLayerable as non-pure, but we want to force reimplementation for plottables + virtual QCPPlottableInterface1D *interface1D() { + return nullptr; + } + 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 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; + 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; - // introduced virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE = 0; // actually introduced in QCPLayerable as non-pure, but we want to force reimplementation for plottables - virtual QCPPlottableInterface1D *interface1D() { return nullptr; } - 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 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; - 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); - + 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; + // 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; private: - Q_DISABLE_COPY(QCPAbstractPlottable) - - friend class QCustomPlot; - friend class QCPAxis; - friend class QCPPlottableLegendItem; + Q_DISABLE_COPY(QCPAbstractPlottable) + + friend class QCustomPlot; + friend class QCPAxis; + friend class QCPPlottableLegendItem; }; @@ -3567,181 +3960,215 @@ private: class QCP_LIB_DECL QCPItemAnchor { - Q_GADGET -public: - QCPItemAnchor(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString &name, int anchorId=-1); - virtual ~QCPItemAnchor(); - - // getters: - QString name() const { return mName; } - virtual QPointF pixelPosition() const; - + Q_GADGET +public: QCPItemAnchor(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString &name, int anchorId = -1); + virtual ~QCPItemAnchor(); + + // getters: + QString name() const { + return mName; + } + virtual QPointF pixelPosition() const; + protected: - // property members: - QString mName; - - // non-property members: - QCustomPlot *mParentPlot; - QCPAbstractItem *mParentItem; - int mAnchorId; - QSet mChildrenX, mChildrenY; - - // introduced virtual methods: - virtual QCPItemPosition *toQCPItemPosition() { return nullptr; } - - // non-virtual methods: - void addChildX(QCPItemPosition* pos); // called from pos when this anchor is set as parent - void removeChildX(QCPItemPosition *pos); // called from pos when its parent anchor is reset or pos deleted - void addChildY(QCPItemPosition* pos); // called from pos when this anchor is set as parent - void removeChildY(QCPItemPosition *pos); // called from pos when its parent anchor is reset or pos deleted - + // property members: + QString mName; + + // non-property members: + QCustomPlot *mParentPlot; + QCPAbstractItem *mParentItem; + int mAnchorId; + QSet mChildrenX, mChildrenY; + + // introduced virtual methods: + virtual QCPItemPosition *toQCPItemPosition() { + return nullptr; + } + + // non-virtual methods: + void addChildX(QCPItemPosition *pos); // called from pos when this anchor is set as parent + void removeChildX(QCPItemPosition *pos); // called from pos when its parent anchor is reset or pos deleted + void addChildY(QCPItemPosition *pos); // called from pos when this anchor is set as parent + void removeChildY(QCPItemPosition *pos); // called from pos when its parent anchor is reset or pos deleted + private: - Q_DISABLE_COPY(QCPItemAnchor) - - friend class QCPItemPosition; + Q_DISABLE_COPY(QCPItemAnchor) + + friend class QCPItemPosition; }; class QCP_LIB_DECL QCPItemPosition : public QCPItemAnchor { - Q_GADGET + Q_GADGET public: - /*! + /*! Defines the ways an item position can be specified. Thus it defines what the numbers passed to \ref setCoords actually mean. - + \see setType - */ - enum PositionType { ptAbsolute ///< Static positioning in pixels, starting from the top left corner of the viewport/widget. - ,ptViewportRatio ///< Static positioning given by a fraction of the viewport size. For example, if you call setCoords(0, 0), the position will be at the top - ///< left corner of the viewport/widget. setCoords(1, 1) will be at the bottom right corner, setCoords(0.5, 0) will be horizontally centered and - ///< vertically at the top of the viewport/widget, etc. - ,ptAxisRectRatio ///< Static positioning given by a fraction of the axis rect size (see \ref setAxisRect). For example, if you call setCoords(0, 0), the position will be at the top - ///< left corner of the axis rect. setCoords(1, 1) will be at the bottom right corner, setCoords(0.5, 0) will be horizontally centered and - ///< 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); - virtual ~QCPItemPosition() Q_DECL_OVERRIDE; - - // getters: - PositionType type() const { return typeX(); } - PositionType typeX() const { return mPositionTypeX; } - PositionType typeY() const { return mPositionTypeY; } - QCPItemAnchor *parentAnchor() const { return parentAnchorX(); } - QCPItemAnchor *parentAnchorX() const { return mParentAnchorX; } - QCPItemAnchor *parentAnchorY() const { return mParentAnchorY; } - double key() const { return mKey; } - double value() const { return mValue; } - QPointF coords() const { return QPointF(mKey, mValue); } - QCPAxis *keyAxis() const { return mKeyAxis.data(); } - QCPAxis *valueAxis() const { return mValueAxis.data(); } - QCPAxisRect *axisRect() const; - virtual QPointF pixelPosition() const Q_DECL_OVERRIDE; - - // setters: - void setType(PositionType type); - void setTypeX(PositionType type); - void setTypeY(PositionType type); - bool setParentAnchor(QCPItemAnchor *parentAnchor, bool keepPixelPosition=false); - bool setParentAnchorX(QCPItemAnchor *parentAnchor, bool keepPixelPosition=false); - bool setParentAnchorY(QCPItemAnchor *parentAnchor, bool keepPixelPosition=false); - void setCoords(double key, double value); - void setCoords(const QPointF &pos); - void setAxes(QCPAxis* keyAxis, QCPAxis* valueAxis); - void setAxisRect(QCPAxisRect *axisRect); - void setPixelPosition(const QPointF &pixelPosition); - + */ + enum PositionType { ptAbsolute ///< Static positioning in pixels, starting from the top left corner of the viewport/widget. + , ptViewportRatio ///< Static positioning given by a fraction of the viewport size. For example, if you call setCoords(0, 0), the position will be at the top + ///< left corner of the viewport/widget. setCoords(1, 1) will be at the bottom right corner, setCoords(0.5, 0) will be horizontally centered and + ///< vertically at the top of the viewport/widget, etc. + , ptAxisRectRatio ///< Static positioning given by a fraction of the axis rect size (see \ref setAxisRect). For example, if you call setCoords(0, 0), the position will be at the top + ///< left corner of the axis rect. setCoords(1, 1) will be at the bottom right corner, setCoords(0.5, 0) will be horizontally centered and + ///< 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); + virtual ~QCPItemPosition() Q_DECL_OVERRIDE; + + // getters: + PositionType type() const { + return typeX(); + } + PositionType typeX() const { + return mPositionTypeX; + } + PositionType typeY() const { + return mPositionTypeY; + } + QCPItemAnchor *parentAnchor() const { + return parentAnchorX(); + } + QCPItemAnchor *parentAnchorX() const { + return mParentAnchorX; + } + QCPItemAnchor *parentAnchorY() const { + return mParentAnchorY; + } + double key() const { + return mKey; + } + double value() const { + return mValue; + } + QPointF coords() const { + return QPointF(mKey, mValue); + } + QCPAxis *keyAxis() const { + return mKeyAxis.data(); + } + QCPAxis *valueAxis() const { + return mValueAxis.data(); + } + QCPAxisRect *axisRect() const; + virtual QPointF pixelPosition() const Q_DECL_OVERRIDE; + + // setters: + void setType(PositionType type); + void setTypeX(PositionType type); + void setTypeY(PositionType type); + bool setParentAnchor(QCPItemAnchor *parentAnchor, bool keepPixelPosition = false); + bool setParentAnchorX(QCPItemAnchor *parentAnchor, bool keepPixelPosition = false); + bool setParentAnchorY(QCPItemAnchor *parentAnchor, bool keepPixelPosition = false); + void setCoords(double key, double value); + void setCoords(const QPointF &pos); + void setAxes(QCPAxis *keyAxis, QCPAxis *valueAxis); + void setAxisRect(QCPAxisRect *axisRect); + void setPixelPosition(const QPointF &pixelPosition); + protected: - // property members: - PositionType mPositionTypeX, mPositionTypeY; - QPointer mKeyAxis, mValueAxis; - QPointer mAxisRect; - double mKey, mValue; - QCPItemAnchor *mParentAnchorX, *mParentAnchorY; - - // reimplemented virtual methods: - virtual QCPItemPosition *toQCPItemPosition() Q_DECL_OVERRIDE { return this; } - + // property members: + PositionType mPositionTypeX, mPositionTypeY; + QPointer mKeyAxis, mValueAxis; + QPointer mAxisRect; + double mKey, mValue; + QCPItemAnchor *mParentAnchorX, *mParentAnchorY; + + // reimplemented virtual methods: + virtual QCPItemPosition *toQCPItemPosition() Q_DECL_OVERRIDE { return this; } + private: - Q_DISABLE_COPY(QCPItemPosition) - + Q_DISABLE_COPY(QCPItemPosition) + }; Q_DECLARE_METATYPE(QCPItemPosition::PositionType) class QCP_LIB_DECL QCPAbstractItem : public QCPLayerable { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(bool clipToAxisRect READ clipToAxisRect WRITE setClipToAxisRect) - Q_PROPERTY(QCPAxisRect* clipAxisRect READ clipAxisRect WRITE setClipAxisRect) - Q_PROPERTY(bool selectable READ selectable WRITE setSelectable NOTIFY selectableChanged) - Q_PROPERTY(bool selected READ selected WRITE setSelected NOTIFY selectionChanged) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(bool clipToAxisRect READ clipToAxisRect WRITE setClipToAxisRect) + Q_PROPERTY(QCPAxisRect *clipAxisRect READ clipAxisRect WRITE setClipAxisRect) + Q_PROPERTY(bool selectable READ selectable WRITE setSelectable NOTIFY selectableChanged) + Q_PROPERTY(bool selected READ selected WRITE setSelected NOTIFY selectionChanged) + /// \endcond public: - explicit QCPAbstractItem(QCustomPlot *parentPlot); - virtual ~QCPAbstractItem() Q_DECL_OVERRIDE; - - // getters: - bool clipToAxisRect() const { return mClipToAxisRect; } - QCPAxisRect *clipAxisRect() const; - bool selectable() const { return mSelectable; } - bool selected() const { return mSelected; } - - // setters: - void setClipToAxisRect(bool clip); - void setClipAxisRect(QCPAxisRect *rect); - Q_SLOT void setSelectable(bool selectable); - Q_SLOT void setSelected(bool selected); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE = 0; - - // non-virtual methods: - QList positions() const { return mPositions; } - QList anchors() const { return mAnchors; } - QCPItemPosition *position(const QString &name) const; - QCPItemAnchor *anchor(const QString &name) const; - bool hasAnchor(const QString &name) const; - + explicit QCPAbstractItem(QCustomPlot *parentPlot); + virtual ~QCPAbstractItem() Q_DECL_OVERRIDE; + + // getters: + bool clipToAxisRect() const { + return mClipToAxisRect; + } + QCPAxisRect *clipAxisRect() const; + bool selectable() const { + return mSelectable; + } + bool selected() const { + return mSelected; + } + + // setters: + void setClipToAxisRect(bool clip); + void setClipAxisRect(QCPAxisRect *rect); + Q_SLOT void setSelectable(bool selectable); + Q_SLOT void setSelected(bool selected); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = nullptr) const Q_DECL_OVERRIDE = 0; + + // non-virtual methods: + QList positions() const { + return mPositions; + } + QList anchors() const { + return mAnchors; + } + QCPItemPosition *position(const QString &name) const; + QCPItemAnchor *anchor(const QString &name) const; + bool hasAnchor(const QString &name) const; + signals: - void selectionChanged(bool selected); - void selectableChanged(bool selectable); - + void selectionChanged(bool selected); + void selectableChanged(bool selectable); + protected: - // property members: - bool mClipToAxisRect; - QPointer mClipAxisRect; - QList mPositions; - QList mAnchors; - bool mSelectable, mSelected; - - // reimplemented virtual methods: - 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) Q_DECL_OVERRIDE; - virtual void deselectEvent(bool *selectionStateChanged) Q_DECL_OVERRIDE; - - // introduced virtual methods: - virtual QPointF anchorPixelPosition(int anchorId) const; - - // non-virtual methods: - double rectDistance(const QRectF &rect, const QPointF &pos, bool filledRect) const; - QCPItemPosition *createPosition(const QString &name); - QCPItemAnchor *createAnchor(const QString &name, int anchorId); - + // property members: + bool mClipToAxisRect; + QPointer mClipAxisRect; + QList mPositions; + QList mAnchors; + bool mSelectable, mSelected; + + // reimplemented virtual methods: + 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) Q_DECL_OVERRIDE; + virtual void deselectEvent(bool *selectionStateChanged) Q_DECL_OVERRIDE; + + // introduced virtual methods: + virtual QPointF anchorPixelPosition(int anchorId) const; + + // non-virtual methods: + double rectDistance(const QRectF &rect, const QPointF &pos, bool filledRect) const; + QCPItemPosition *createPosition(const QString &name); + QCPItemAnchor *createAnchor(const QString &name, int anchorId); + private: - Q_DISABLE_COPY(QCPAbstractItem) - - friend class QCustomPlot; - friend class QCPItemAnchor; + Q_DISABLE_COPY(QCPAbstractItem) + + friend class QCustomPlot; + friend class QCPItemAnchor; }; /* end of 'src/item.h' */ @@ -3752,269 +4179,303 @@ private: class QCP_LIB_DECL QCustomPlot : public QWidget { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QRect viewport READ viewport WRITE setViewport) - Q_PROPERTY(QPixmap background READ background WRITE setBackground) - Q_PROPERTY(bool backgroundScaled READ backgroundScaled WRITE setBackgroundScaled) - Q_PROPERTY(Qt::AspectRatioMode backgroundScaledMode READ backgroundScaledMode WRITE setBackgroundScaledMode) - Q_PROPERTY(QCPLayoutGrid* plotLayout READ plotLayout) - Q_PROPERTY(bool autoAddPlottableToLegend READ autoAddPlottableToLegend WRITE setAutoAddPlottableToLegend) - 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 + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(QRect viewport READ viewport WRITE setViewport) + Q_PROPERTY(QPixmap background READ background WRITE setBackground) + Q_PROPERTY(bool backgroundScaled READ backgroundScaled WRITE setBackgroundScaled) + Q_PROPERTY(Qt::AspectRatioMode backgroundScaledMode READ backgroundScaledMode WRITE setBackgroundScaledMode) + Q_PROPERTY(QCPLayoutGrid *plotLayout READ plotLayout) + Q_PROPERTY(bool autoAddPlottableToLegend READ autoAddPlottableToLegend WRITE setAutoAddPlottableToLegend) + 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: - /*! + /*! Defines how a layer should be inserted relative to an other layer. \see addLayer, moveLayer - */ - enum LayerInsertMode { limBelow ///< Layer is inserted below other layer - ,limAbove ///< Layer is inserted above other layer - }; - Q_ENUMS(LayerInsertMode) - - /*! + */ + enum LayerInsertMode { limBelow ///< Layer is inserted below other layer + , limAbove ///< Layer is inserted above other layer + }; + Q_ENUMS(LayerInsertMode) + + /*! Defines with what timing the QCustomPlot surface is refreshed after a replot. \see replot - */ - 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 = nullptr); - virtual ~QCustomPlot() Q_DECL_OVERRIDE; - - // 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; } - QCPLayoutGrid *plotLayout() const { return mPlotLayout; } - QCP::AntialiasedElements antialiasedElements() const { return mAntialiasedElements; } - QCP::AntialiasedElements notAntialiasedElements() const { return mNotAntialiasedElements; } - bool autoAddPlottableToLegend() const { return mAutoAddPlottableToLegend; } - const QCP::Interactions interactions() const { return mInteractions; } - int selectionTolerance() const { return mSelectionTolerance; } - 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); - void setBackgroundScaled(bool scaled); - void setBackgroundScaledMode(Qt::AspectRatioMode mode); - void setAntialiasedElements(const QCP::AntialiasedElements &antialiasedElements); - void setAntialiasedElement(QCP::AntialiasedElement antialiasedElement, bool enabled=true); - void setNotAntialiasedElements(const QCP::AntialiasedElements ¬AntialiasedElements); - void setNotAntialiasedElement(QCP::AntialiasedElement notAntialiasedElement, bool enabled=true); - void setAutoAddPlottableToLegend(bool on); - void setInteractions(const QCP::Interactions &interactions); - void setInteraction(const QCP::Interaction &interaction, bool enabled=true); - void setSelectionTolerance(int pixels); - void setNoAntialiasingOnDrag(bool enabled); - 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 removePlottable(QCPAbstractPlottable *plottable); - bool removePlottable(int index); - int clearPlottables(); - int plottableCount() const; - QList selectedPlottables() const; - template - PlottableType *plottableAt(const QPointF &pos, bool onlySelectable=false, int *dataIndex=nullptr) const; - QCPAbstractPlottable *plottableAt(const QPointF &pos, bool onlySelectable=false, int *dataIndex=nullptr) const; - bool hasPlottable(QCPAbstractPlottable *plottable) const; - - // specialized interface for QCPGraph: - QCPGraph *graph(int index) const; - QCPGraph *graph() const; - QCPGraph *addGraph(QCPAxis *keyAxis=nullptr, QCPAxis *valueAxis=nullptr); - bool removeGraph(QCPGraph *graph); - bool removeGraph(int index); - int clearGraphs(); - int graphCount() const; - QList selectedGraphs() const; + */ + 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 = nullptr); + virtual ~QCustomPlot() Q_DECL_OVERRIDE; + + // 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; + } + QCPLayoutGrid *plotLayout() const { + return mPlotLayout; + } + QCP::AntialiasedElements antialiasedElements() const { + return mAntialiasedElements; + } + QCP::AntialiasedElements notAntialiasedElements() const { + return mNotAntialiasedElements; + } + bool autoAddPlottableToLegend() const { + return mAutoAddPlottableToLegend; + } + const QCP::Interactions interactions() const { + return mInteractions; + } + int selectionTolerance() const { + return mSelectionTolerance; + } + 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); + void setBackgroundScaled(bool scaled); + void setBackgroundScaledMode(Qt::AspectRatioMode mode); + void setAntialiasedElements(const QCP::AntialiasedElements &antialiasedElements); + void setAntialiasedElement(QCP::AntialiasedElement antialiasedElement, bool enabled = true); + void setNotAntialiasedElements(const QCP::AntialiasedElements ¬AntialiasedElements); + void setNotAntialiasedElement(QCP::AntialiasedElement notAntialiasedElement, bool enabled = true); + void setAutoAddPlottableToLegend(bool on); + void setInteractions(const QCP::Interactions &interactions); + void setInteraction(const QCP::Interaction &interaction, bool enabled = true); + void setSelectionTolerance(int pixels); + void setNoAntialiasingOnDrag(bool enabled); + 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 removePlottable(QCPAbstractPlottable *plottable); + bool removePlottable(int index); + int clearPlottables(); + int plottableCount() const; + QList selectedPlottables() const; + template + PlottableType *plottableAt(const QPointF &pos, bool onlySelectable = false, int *dataIndex = nullptr) const; + QCPAbstractPlottable *plottableAt(const QPointF &pos, bool onlySelectable = false, int *dataIndex = nullptr) const; + bool hasPlottable(QCPAbstractPlottable *plottable) const; + + // specialized interface for QCPGraph: + QCPGraph *graph(int index) const; + QCPGraph *graph() const; + QCPGraph *addGraph(QCPAxis *keyAxis = nullptr, QCPAxis *valueAxis = nullptr); + bool removeGraph(QCPGraph *graph); + bool removeGraph(int index); + int clearGraphs(); + int graphCount() const; + QList selectedGraphs() const; + + // item interface: + QCPAbstractItem *item(int index) const; + QCPAbstractItem *item() const; + bool removeItem(QCPAbstractItem *item); + bool removeItem(int index); + int clearItems(); + int itemCount() const; + QList selectedItems() const; + template + ItemType *itemAt(const QPointF &pos, bool onlySelectable = false) const; + QCPAbstractItem *itemAt(const QPointF &pos, bool onlySelectable = false) const; + bool hasItem(QCPAbstractItem *item) const; + + // layer interface: + QCPLayer *layer(const QString &name) const; + QCPLayer *layer(int index) const; + QCPLayer *currentLayer() const; + bool setCurrentLayer(const QString &name); + bool setCurrentLayer(QCPLayer *layer); + int layerCount() const; + bool addLayer(const QString &name, QCPLayer *otherLayer = nullptr, LayerInsertMode insertMode = limAbove); + bool removeLayer(QCPLayer *layer); + bool moveLayer(QCPLayer *layer, QCPLayer *otherLayer, LayerInsertMode insertMode = limAbove); + + // axis rect/layout interface: + int axisRectCount() const; + 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, 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::rpRefreshHint); + double replotTime(bool average = false) const; + + QCPAxis *xAxis, *yAxis, *xAxis2, *yAxis2; + QCPLegend *legend; - // item interface: - QCPAbstractItem *item(int index) const; - QCPAbstractItem *item() const; - bool removeItem(QCPAbstractItem *item); - bool removeItem(int index); - int clearItems(); - int itemCount() const; - QList selectedItems() const; - template - ItemType *itemAt(const QPointF &pos, bool onlySelectable=false) const; - QCPAbstractItem *itemAt(const QPointF &pos, bool onlySelectable=false) const; - bool hasItem(QCPAbstractItem *item) const; - - // layer interface: - QCPLayer *layer(const QString &name) const; - QCPLayer *layer(int index) const; - QCPLayer *currentLayer() const; - bool setCurrentLayer(const QString &name); - bool setCurrentLayer(QCPLayer *layer); - int layerCount() const; - bool addLayer(const QString &name, QCPLayer *otherLayer=nullptr, LayerInsertMode insertMode=limAbove); - bool removeLayer(QCPLayer *layer); - bool moveLayer(QCPLayer *layer, QCPLayer *otherLayer, LayerInsertMode insertMode=limAbove); - - // axis rect/layout interface: - int axisRectCount() const; - 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, 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::rpRefreshHint); - double replotTime(bool average=false) const; - - QCPAxis *xAxis, *yAxis, *xAxis2, *yAxis2; - QCPLegend *legend; - signals: - void mouseDoubleClick(QMouseEvent *event); - void mousePress(QMouseEvent *event); - void mouseMove(QMouseEvent *event); - void mouseRelease(QMouseEvent *event); - void mouseWheel(QWheelEvent *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 selectionChangedByUser(); - void beforeReplot(); - void afterLayout(); - void afterReplot(); - + void mouseDoubleClick(QMouseEvent *event); + void mousePress(QMouseEvent *event); + void mouseMove(QMouseEvent *event); + void mouseRelease(QMouseEvent *event); + void mouseWheel(QWheelEvent *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 selectionChangedByUser(); + void beforeReplot(); + void afterLayout(); + void afterReplot(); + protected: - // property members: - QRect mViewport; - double mBufferDevicePixelRatio; - QCPLayoutGrid *mPlotLayout; - bool mAutoAddPlottableToLegend; - QList mPlottables; - QList mGraphs; // extra list of plottables also in mPlottables that are of type QCPGraph - QList mItems; - QList mLayers; - QCP::AntialiasedElements mAntialiasedElements, mNotAntialiasedElements; - QCP::Interactions mInteractions; - int mSelectionTolerance; - bool mNoAntialiasingOnDrag; - QBrush mBackgroundBrush; - QPixmap mBackgroundPixmap; - QPixmap mScaledBackgroundPixmap; - bool mBackgroundScaled; - Qt::AspectRatioMode mBackgroundScaledMode; - QCPLayer *mCurrentLayer; - QCP::PlottingHints mPlottingHints; - Qt::KeyboardModifier mMultiSelectModifier; - QCP::SelectionRectMode mSelectionRectMode; - QCPSelectionRect *mSelectionRect; - bool mOpenGl; - - // non-property members: - QList > mPaintBuffers; - QPoint mMousePressPos; - bool mMouseHasMoved; - QPointer mMouseEventLayerable; - QPointer mMouseSignalLayerable; - QVariant mMouseEventLayerableDetails; - QVariant mMouseSignalLayerableDetails; - bool mReplotting; - bool mReplotQueued; - double mReplotTime, mReplotTimeAverage; - int mOpenGlMultisamples; - QCP::AntialiasedElements mOpenGlAntialiasedElementsBackup; - bool mOpenGlCacheLabelsBackup; + // property members: + QRect mViewport; + double mBufferDevicePixelRatio; + QCPLayoutGrid *mPlotLayout; + bool mAutoAddPlottableToLegend; + QList mPlottables; + QList mGraphs; // extra list of plottables also in mPlottables that are of type QCPGraph + QList mItems; + QList mLayers; + QCP::AntialiasedElements mAntialiasedElements, mNotAntialiasedElements; + QCP::Interactions mInteractions; + int mSelectionTolerance; + bool mNoAntialiasingOnDrag; + QBrush mBackgroundBrush; + QPixmap mBackgroundPixmap; + QPixmap mScaledBackgroundPixmap; + bool mBackgroundScaled; + Qt::AspectRatioMode mBackgroundScaledMode; + QCPLayer *mCurrentLayer; + QCP::PlottingHints mPlottingHints; + Qt::KeyboardModifier mMultiSelectModifier; + QCP::SelectionRectMode mSelectionRectMode; + QCPSelectionRect *mSelectionRect; + bool mOpenGl; + + // non-property members: + QList > mPaintBuffers; + QPoint mMousePressPos; + bool mMouseHasMoved; + QPointer mMouseEventLayerable; + QPointer mMouseSignalLayerable; + QVariant mMouseEventLayerableDetails; + QVariant mMouseSignalLayerableDetails; + bool mReplotting; + bool mReplotQueued; + double mReplotTime, mReplotTimeAverage; + int mOpenGlMultisamples; + QCP::AntialiasedElements mOpenGlAntialiasedElementsBackup; + bool mOpenGlCacheLabelsBackup; #ifdef QCP_OPENGL_FBO - QSharedPointer mGlContext; - QSharedPointer mGlSurface; - QSharedPointer mGlPaintDevice; + QSharedPointer mGlContext; + QSharedPointer mGlSurface; + QSharedPointer mGlPaintDevice; #endif - - // reimplemented virtual methods: - 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=nullptr) const; - QList layerableListAt(const QPointF &pos, bool onlySelectable, QList *selectionDetails=nullptr) 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; + + // reimplemented virtual methods: + 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 = nullptr) const; + QList layerableListAt(const QPointF &pos, bool onlySelectable, QList *selectionDetails = nullptr) 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) @@ -4029,49 +4490,47 @@ Q_DECLARE_METATYPE(QCustomPlot::RefreshPriority) Plottables that only consist of single lines (like graphs) have a tolerance band around them, see \ref setSelectionTolerance. If multiple plottables come into consideration, the one closest to \a pos is returned. - + If \a onlySelectable is true, only plottables that are selectable (QCPAbstractPlottable::setSelectable) are considered. - + if \a dataIndex is non-null, it is set to the index of the plottable's data point that is closest to \a pos. If there is no plottable of the specified type at \a pos, returns \c nullptr. - + \see itemAt, layoutElementAt */ template PlottableType *QCustomPlot::plottableAt(const QPointF &pos, bool onlySelectable, int *dataIndex) const { - PlottableType *resultPlottable = 0; - QVariant resultDetails; - double resultDistance = mSelectionTolerance; // only regard clicks with distances smaller than mSelectionTolerance as selections, so initialize with that value - - foreach (QCPAbstractPlottable *plottable, mPlottables) - { - PlottableType *currentPlottable = qobject_cast(plottable); - if (!currentPlottable || (onlySelectable && !currentPlottable->selectable())) // we could have also passed onlySelectable to the selectTest function, but checking here is faster, because we have access to QCPAbstractPlottable::selectable - continue; - if (currentPlottable->clipRect().contains(pos.toPoint())) // only consider clicks where the plottable is actually visible - { - QVariant details; - double currentDistance = currentPlottable->selectTest(pos, false, dataIndex ? &details : nullptr); - if (currentDistance >= 0 && currentDistance < resultDistance) - { - resultPlottable = currentPlottable; - resultDetails = details; - resultDistance = currentDistance; - } + PlottableType *resultPlottable = 0; + QVariant resultDetails; + double resultDistance = mSelectionTolerance; // only regard clicks with distances smaller than mSelectionTolerance as selections, so initialize with that value + + foreach (QCPAbstractPlottable *plottable, mPlottables) { + PlottableType *currentPlottable = qobject_cast(plottable); + if (!currentPlottable || (onlySelectable && !currentPlottable->selectable())) { // we could have also passed onlySelectable to the selectTest function, but checking here is faster, because we have access to QCPAbstractPlottable::selectable + continue; + } + if (currentPlottable->clipRect().contains(pos.toPoint())) { // only consider clicks where the plottable is actually visible + QVariant details; + double currentDistance = currentPlottable->selectTest(pos, false, dataIndex ? &details : nullptr); + if (currentDistance >= 0 && currentDistance < resultDistance) { + resultPlottable = currentPlottable; + resultDetails = details; + resultDistance = currentDistance; + } + } } - } - - if (resultPlottable && dataIndex) - { - QCPDataSelection sel = resultDetails.value(); - if (!sel.isEmpty()) - *dataIndex = sel.dataRange(0).begin(); - } - return resultPlottable; + + if (resultPlottable && dataIndex) { + QCPDataSelection sel = resultDetails.value(); + if (!sel.isEmpty()) { + *dataIndex = sel.dataRange(0).begin(); + } + } + return resultPlottable; } /*! @@ -4079,37 +4538,35 @@ PlottableType *QCustomPlot::plottableAt(const QPointF &pos, bool onlySelectable, taken into consideration can be specified via the template parameter. Items that only consist of single lines (e.g. \ref QCPItemLine or \ref QCPItemCurve) have a tolerance band around them, see \ref setSelectionTolerance. If multiple items come into consideration, the one closest to \a pos is returned. - + If \a onlySelectable is true, only items that are selectable (QCPAbstractItem::setSelectable) are considered. - + If there is no item at \a pos, returns \c nullptr. - + \see plottableAt, layoutElementAt */ template ItemType *QCustomPlot::itemAt(const QPointF &pos, bool onlySelectable) const { - ItemType *resultItem = 0; - double resultDistance = mSelectionTolerance; // only regard clicks with distances smaller than mSelectionTolerance as selections, so initialize with that value - - foreach (QCPAbstractItem *item, mItems) - { - ItemType *currentItem = qobject_cast(item); - if (!currentItem || (onlySelectable && !currentItem->selectable())) // we could have also passed onlySelectable to the selectTest function, but checking here is faster, because we have access to QCPAbstractItem::selectable - continue; - if (!currentItem->clipToAxisRect() || currentItem->clipRect().contains(pos.toPoint())) // only consider clicks inside axis cliprect of the item if actually clipped to it - { - double currentDistance = currentItem->selectTest(pos, false); - if (currentDistance >= 0 && currentDistance < resultDistance) - { - resultItem = currentItem; - resultDistance = currentDistance; - } + ItemType *resultItem = 0; + double resultDistance = mSelectionTolerance; // only regard clicks with distances smaller than mSelectionTolerance as selections, so initialize with that value + + foreach (QCPAbstractItem *item, mItems) { + ItemType *currentItem = qobject_cast(item); + if (!currentItem || (onlySelectable && !currentItem->selectable())) { // we could have also passed onlySelectable to the selectTest function, but checking here is faster, because we have access to QCPAbstractItem::selectable + continue; + } + if (!currentItem->clipToAxisRect() || currentItem->clipRect().contains(pos.toPoint())) { // only consider clicks inside axis cliprect of the item if actually clipped to it + double currentDistance = currentItem->selectTest(pos, false); + if (currentDistance >= 0 && currentDistance < resultDistance) { + resultItem = currentItem; + resultDistance = currentDistance; + } + } } - } - - return resultItem; + + return resultItem; } @@ -4123,56 +4580,56 @@ ItemType *QCustomPlot::itemAt(const QPointF &pos, bool onlySelectable) const class QCPPlottableInterface1D { public: - virtual ~QCPPlottableInterface1D() = default; - // 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; + virtual ~QCPPlottableInterface1D() = default; + // 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 QCPAbstractPlottable1D : public QCPAbstractPlottable, public QCPPlottableInterface1D // no QCP_LIB_DECL, template class ends up in header (cpp included below) { - // No Q_OBJECT macro due to template class - + // No Q_OBJECT macro due to template class + public: - QCPAbstractPlottable1D(QCPAxis *keyAxis, QCPAxis *valueAxis); - virtual ~QCPAbstractPlottable1D() Q_DECL_OVERRIDE; - - // virtual methods of 1d plottable interface: - virtual int dataCount() const Q_DECL_OVERRIDE; - virtual double dataMainKey(int index) const Q_DECL_OVERRIDE; - virtual double dataSortKey(int index) const Q_DECL_OVERRIDE; - virtual double dataMainValue(int index) const Q_DECL_OVERRIDE; - virtual QCPRange dataValueRange(int index) const Q_DECL_OVERRIDE; - virtual QPointF dataPixelPosition(int index) const Q_DECL_OVERRIDE; - virtual bool sortKeyIsMainKey() const Q_DECL_OVERRIDE; - virtual QCPDataSelection selectTestRect(const QRectF &rect, bool onlySelectable) const Q_DECL_OVERRIDE; - virtual int findBegin(double sortKey, bool expandedRange=true) const Q_DECL_OVERRIDE; - virtual int findEnd(double sortKey, bool expandedRange=true) const Q_DECL_OVERRIDE; - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE; - virtual QCPPlottableInterface1D *interface1D() Q_DECL_OVERRIDE { return this; } - + QCPAbstractPlottable1D(QCPAxis *keyAxis, QCPAxis *valueAxis); + virtual ~QCPAbstractPlottable1D() Q_DECL_OVERRIDE; + + // virtual methods of 1d plottable interface: + virtual int dataCount() const Q_DECL_OVERRIDE; + virtual double dataMainKey(int index) const Q_DECL_OVERRIDE; + virtual double dataSortKey(int index) const Q_DECL_OVERRIDE; + virtual double dataMainValue(int index) const Q_DECL_OVERRIDE; + virtual QCPRange dataValueRange(int index) const Q_DECL_OVERRIDE; + virtual QPointF dataPixelPosition(int index) const Q_DECL_OVERRIDE; + virtual bool sortKeyIsMainKey() const Q_DECL_OVERRIDE; + virtual QCPDataSelection selectTestRect(const QRectF &rect, bool onlySelectable) const Q_DECL_OVERRIDE; + virtual int findBegin(double sortKey, bool expandedRange = true) const Q_DECL_OVERRIDE; + virtual int findEnd(double sortKey, bool expandedRange = true) const Q_DECL_OVERRIDE; + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = nullptr) const Q_DECL_OVERRIDE; + virtual QCPPlottableInterface1D *interface1D() Q_DECL_OVERRIDE { 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; + // 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) - + Q_DISABLE_COPY(QCPAbstractPlottable1D) + }; @@ -4208,55 +4665,55 @@ private: /* 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. @@ -4350,10 +4807,10 @@ private: /* start documentation of inline functions */ /*! \fn QCPPlottableInterface1D *QCPAbstractPlottable1D::interface1D() - + Returns a \ref QCPPlottableInterface1D pointer to this plottable, providing access to its 1D interface. - + \seebaseclassmethod */ @@ -4365,8 +4822,8 @@ private: */ template QCPAbstractPlottable1D::QCPAbstractPlottable1D(QCPAxis *keyAxis, QCPAxis *valueAxis) : - QCPAbstractPlottable(keyAxis, valueAxis), - mDataContainer(new QCPDataContainer) + QCPAbstractPlottable(keyAxis, valueAxis), + mDataContainer(new QCPDataContainer) { } @@ -4381,7 +4838,7 @@ QCPAbstractPlottable1D::~QCPAbstractPlottable1D() template int QCPAbstractPlottable1D::dataCount() const { - return mDataContainer->size(); + return mDataContainer->size(); } /*! @@ -4390,14 +4847,12 @@ int QCPAbstractPlottable1D::dataCount() const 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; - } + if (index >= 0 && index < mDataContainer->size()) { + return (mDataContainer->constBegin() + index)->mainKey(); + } else { + qDebug() << Q_FUNC_INFO << "Index out of bounds" << index; + return 0; + } } /*! @@ -4406,14 +4861,12 @@ double QCPAbstractPlottable1D::dataMainKey(int index) const 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; - } + if (index >= 0 && index < mDataContainer->size()) { + return (mDataContainer->constBegin() + index)->sortKey(); + } else { + qDebug() << Q_FUNC_INFO << "Index out of bounds" << index; + return 0; + } } /*! @@ -4422,14 +4875,12 @@ double QCPAbstractPlottable1D::dataSortKey(int index) const 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; - } + if (index >= 0 && index < mDataContainer->size()) { + return (mDataContainer->constBegin() + index)->mainValue(); + } else { + qDebug() << Q_FUNC_INFO << "Index out of bounds" << index; + return 0; + } } /*! @@ -4438,14 +4889,12 @@ double QCPAbstractPlottable1D::dataMainValue(int index) const 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); - } + 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); + } } /*! @@ -4454,15 +4903,13 @@ QCPRange QCPAbstractPlottable1D::dataValueRange(int index) const 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(); - } + 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(); + } } /*! @@ -4471,7 +4918,7 @@ QPointF QCPAbstractPlottable1D::dataPixelPosition(int index) const template bool QCPAbstractPlottable1D::sortKeyIsMainKey() const { - return DataType::sortKeyIsMainKey(); + return DataType::sortKeyIsMainKey(); } /*! @@ -4484,47 +4931,48 @@ bool QCPAbstractPlottable1D::sortKeyIsMainKey() const 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 = int(it-mDataContainer->constBegin()); - } else if (!valueRange.contains(it->mainValue()) || !keyRange.contains(it->mainKey())) // segment just ended - { - result.addDataRange(QCPDataRange(currentSegmentBegin, int(it-mDataContainer->constBegin())), false); - currentSegmentBegin = -1; + QCPDataSelection result; + if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty()) { + return result; } - } - // process potential last segment: - if (currentSegmentBegin != -1) - result.addDataRange(QCPDataRange(currentSegmentBegin, int(end-mDataContainer->constBegin())), false); - - result.simplify(); - 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 = int(it - mDataContainer->constBegin()); + } + } else if (!valueRange.contains(it->mainValue()) || !keyRange.contains(it->mainKey())) { // segment just ended + result.addDataRange(QCPDataRange(currentSegmentBegin, int(it - mDataContainer->constBegin())), false); + currentSegmentBegin = -1; + } + } + // process potential last segment: + if (currentSegmentBegin != -1) { + result.addDataRange(QCPDataRange(currentSegmentBegin, int(end - mDataContainer->constBegin())), false); + } + + result.simplify(); + return result; } /*! @@ -4533,7 +4981,7 @@ QCPDataSelection QCPAbstractPlottable1D::selectTestRect(const QRectF & template int QCPAbstractPlottable1D::findBegin(double sortKey, bool expandedRange) const { - return int(mDataContainer->findBegin(sortKey, expandedRange)-mDataContainer->constBegin()); + return int(mDataContainer->findBegin(sortKey, expandedRange) - mDataContainer->constBegin()); } /*! @@ -4542,7 +4990,7 @@ int QCPAbstractPlottable1D::findBegin(double sortKey, bool expandedRan template int QCPAbstractPlottable1D::findEnd(double sortKey, bool expandedRange) const { - return int(mDataContainer->findEnd(sortKey, expandedRange)-mDataContainer->constBegin()); + return int(mDataContainer->findEnd(sortKey, expandedRange) - mDataContainer->constBegin()); } /*! @@ -4552,59 +5000,61 @@ int QCPAbstractPlottable1D::findEnd(double sortKey, bool expandedRange If \a details is not 0, it will be set to a \ref QCPDataSelection, describing the closest data point to \a pos. - + \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 = int(it-mDataContainer->constBegin()); - } + if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty()) { + return -1; } - } - if (minDistIndex != mDataContainer->size()) - selectionResult.addDataRange(QCPDataRange(minDistIndex, minDistIndex+1), false); - - selectionResult.simplify(); - if (details) - details->setValue(selectionResult); - return qSqrt(minDistSqr); + 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 = int(it - mDataContainer->constBegin()); + } + } + } + if (minDistIndex != mDataContainer->size()) { + selectionResult.addDataRange(QCPDataRange(minDistIndex, minDistIndex + 1), false); + } + + selectionResult.simplify(); + if (details) { + details->setValue(selectionResult); + } + return qSqrt(minDistSqr); } /*! @@ -4620,21 +5070,20 @@ double QCPAbstractPlottable1D::selectTest(const QPointF &pos, bool onl 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(); - } + 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(); + } } /*! @@ -4650,59 +5099,55 @@ void QCPAbstractPlottable1D::getDataSegments(QList &sele template void QCPAbstractPlottable1D::drawPolyline(QCPPainter *painter, const QVector &lineData) const { - // if drawing lines in plot (instead of PDF), reduce 1px lines to cosmetic, because at least in - // Qt6 drawing of "1px" width lines is much slower even though it has same appearance apart from - // High-DPI. In High-DPI cases people must set a pen width slightly larger than 1.0 to get - // correct DPI scaling of width, but of course with performance penalty. - if (!painter->modes().testFlag(QCPPainter::pmVectorized) && - qFuzzyCompare(painter->pen().widthF(), 1.0)) - { - QPen newPen = painter->pen(); - newPen.setWidth(0); - painter->setPen(newPen); - } + // if drawing lines in plot (instead of PDF), reduce 1px lines to cosmetic, because at least in + // Qt6 drawing of "1px" width lines is much slower even though it has same appearance apart from + // High-DPI. In High-DPI cases people must set a pen width slightly larger than 1.0 to get + // correct DPI scaling of width, but of course with performance penalty. + if (!painter->modes().testFlag(QCPPainter::pmVectorized) && + qFuzzyCompare(painter->pen().widthF(), 1.0)) { + QPen newPen = painter->pen(); + newPen.setWidth(0); + painter->setPen(newPen); + } - // 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; + // 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); } - } 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); - } } @@ -4714,96 +5159,110 @@ void QCPAbstractPlottable1D::drawPolyline(QCPPainter *painter, const Q class QCP_LIB_DECL QCPColorGradient { - Q_GADGET + Q_GADGET public: - /*! + /*! Defines the color spaces in which color interpolation between gradient stops can be performed. - + \see setColorInterpolation - */ - enum ColorInterpolation { ciRGB ///< Color channels red, green and blue are linearly interpolated - ,ciHSV ///< Color channels hue, saturation and value are linearly interpolated (The hue is interpolated over the shortest angle distance) - }; - Q_ENUMS(ColorInterpolation) - - /*! + */ + enum ColorInterpolation { ciRGB ///< Color channels red, green and blue are linearly interpolated + , ciHSV ///< Color channels hue, saturation and value are linearly interpolated (The hue is interpolated over the shortest angle distance) + }; + Q_ENUMS(ColorInterpolation) + + /*! Defines how NaN data points shall appear in the plot. - + \see setNanHandling, setNanColor - */ - enum NanHandling { nhNone ///< NaN data points are not explicitly handled and shouldn't occur in the data (this gives slight performance improvement) - ,nhLowestColor ///< NaN data points appear as the lowest color defined in this QCPColorGradient - ,nhHighestColor ///< NaN data points appear as the highest color defined in this QCPColorGradient - ,nhTransparent ///< NaN data points appear transparent - ,nhNanColor ///< NaN data points appear as the color defined with \ref setNanColor - }; - Q_ENUMS(NanHandling) - - /*! + */ + enum NanHandling { nhNone ///< NaN data points are not explicitly handled and shouldn't occur in the data (this gives slight performance improvement) + , nhLowestColor ///< NaN data points appear as the lowest color defined in this QCPColorGradient + , nhHighestColor ///< NaN data points appear as the highest color defined in this QCPColorGradient + , nhTransparent ///< NaN data points appear transparent + , nhNanColor ///< NaN data points appear as the color defined with \ref setNanColor + }; + Q_ENUMS(NanHandling) + + /*! Defines the available presets that can be loaded with \ref loadPreset. See the documentation there for an image of the presets. - */ - enum GradientPreset { gpGrayscale ///< Continuous lightness from black to white (suited for non-biased data representation) - ,gpHot ///< Continuous lightness from black over firey colors to white (suited for non-biased data representation) - ,gpCold ///< Continuous lightness from black over icey colors to white (suited for non-biased data representation) - ,gpNight ///< Continuous lightness from black over weak blueish colors to white (suited for non-biased data representation) - ,gpCandy ///< Blue over pink to white - ,gpGeography ///< Colors suitable to represent different elevations on geographical maps - ,gpIon ///< Half hue spectrum from black over purple to blue and finally green (creates banding illusion but allows more precise magnitude estimates) - ,gpThermal ///< Colors suitable for thermal imaging, ranging from dark blue over purple to orange, yellow and white - ,gpPolar ///< Colors suitable to emphasize polarity around the center, with blue for negative, black in the middle and red for positive values - ,gpSpectrum ///< An approximation of the visible light spectrum (creates banding illusion but allows more precise magnitude estimates) - ,gpJet ///< Hue variation similar to a spectrum, often used in numerical visualization (creates banding illusion but allows more precise magnitude estimates) - ,gpHues ///< Full hue cycle, with highest and lowest color red (suitable for periodic data, such as angles and phases, see \ref setPeriodic) - }; - Q_ENUMS(GradientPreset) - - QCPColorGradient(); - QCPColorGradient(GradientPreset preset); - bool operator==(const QCPColorGradient &other) const; - bool operator!=(const QCPColorGradient &other) const { return !(*this == other); } - - // getters: - int levelCount() const { return mLevelCount; } - QMap colorStops() const { return mColorStops; } - ColorInterpolation colorInterpolation() const { return mColorInterpolation; } - NanHandling nanHandling() const { return mNanHandling; } - QColor nanColor() const { return mNanColor; } - bool periodic() const { return mPeriodic; } - - // setters: - void setLevelCount(int n); - void setColorStops(const QMap &colorStops); - void setColorStopAt(double position, const QColor &color); - void setColorInterpolation(ColorInterpolation interpolation); - void setNanHandling(NanHandling handling); - void setNanColor(const QColor &color); - void setPeriodic(bool enabled); - - // 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; - + */ + enum GradientPreset { gpGrayscale ///< Continuous lightness from black to white (suited for non-biased data representation) + , gpHot ///< Continuous lightness from black over firey colors to white (suited for non-biased data representation) + , gpCold ///< Continuous lightness from black over icey colors to white (suited for non-biased data representation) + , gpNight ///< Continuous lightness from black over weak blueish colors to white (suited for non-biased data representation) + , gpCandy ///< Blue over pink to white + , gpGeography ///< Colors suitable to represent different elevations on geographical maps + , gpIon ///< Half hue spectrum from black over purple to blue and finally green (creates banding illusion but allows more precise magnitude estimates) + , gpThermal ///< Colors suitable for thermal imaging, ranging from dark blue over purple to orange, yellow and white + , gpPolar ///< Colors suitable to emphasize polarity around the center, with blue for negative, black in the middle and red for positive values + , gpSpectrum ///< An approximation of the visible light spectrum (creates banding illusion but allows more precise magnitude estimates) + , gpJet ///< Hue variation similar to a spectrum, often used in numerical visualization (creates banding illusion but allows more precise magnitude estimates) + , gpHues ///< Full hue cycle, with highest and lowest color red (suitable for periodic data, such as angles and phases, see \ref setPeriodic) + }; + Q_ENUMS(GradientPreset) + + QCPColorGradient(); + QCPColorGradient(GradientPreset preset); + bool operator==(const QCPColorGradient &other) const; + bool operator!=(const QCPColorGradient &other) const { + return !(*this == other); + } + + // getters: + int levelCount() const { + return mLevelCount; + } + QMap colorStops() const { + return mColorStops; + } + ColorInterpolation colorInterpolation() const { + return mColorInterpolation; + } + NanHandling nanHandling() const { + return mNanHandling; + } + QColor nanColor() const { + return mNanColor; + } + bool periodic() const { + return mPeriodic; + } + + // setters: + void setLevelCount(int n); + void setColorStops(const QMap &colorStops); + void setColorStopAt(double position, const QColor &color); + void setColorInterpolation(ColorInterpolation interpolation); + void setNanHandling(NanHandling handling); + void setNanColor(const QColor &color); + void setPeriodic(bool enabled); + + // 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: - // property members: - int mLevelCount; - QMap mColorStops; - ColorInterpolation mColorInterpolation; - NanHandling mNanHandling; - QColor mNanColor; - bool mPeriodic; - - // non-property members: - QVector mColorBuffer; // have colors premultiplied with alpha (for usage with QImage::Format_ARGB32_Premultiplied) - bool mColorBufferInvalidated; - - // non-virtual methods: - bool stopsUseAlpha() const; - void updateColorBuffer(); + // property members: + int mLevelCount; + QMap mColorStops; + ColorInterpolation mColorInterpolation; + NanHandling mNanHandling; + QColor mNanColor; + bool mPeriodic; + + // non-property members: + 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::NanHandling) @@ -4817,64 +5276,78 @@ Q_DECLARE_METATYPE(QCPColorGradient::GradientPreset) class QCP_LIB_DECL QCPSelectionDecoratorBracket : public QCPSelectionDecorator { - Q_GADGET + 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() Q_DECL_OVERRIDE; - - // 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) Q_DECL_OVERRIDE; - + */ + 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() Q_DECL_OVERRIDE; + + // 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) Q_DECL_OVERRIDE; + 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; - + // 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) @@ -4886,121 +5359,158 @@ Q_DECLARE_METATYPE(QCPSelectionDecoratorBracket::BracketStyle) class QCP_LIB_DECL QCPAxisRect : public QCPLayoutElement { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QPixmap background READ background WRITE setBackground) - Q_PROPERTY(bool backgroundScaled READ backgroundScaled WRITE setBackgroundScaled) - Q_PROPERTY(Qt::AspectRatioMode backgroundScaledMode READ backgroundScaledMode WRITE setBackgroundScaledMode) - Q_PROPERTY(Qt::Orientations rangeDrag READ rangeDrag WRITE setRangeDrag) - Q_PROPERTY(Qt::Orientations rangeZoom READ rangeZoom WRITE setRangeZoom) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QPixmap background READ background WRITE setBackground) + Q_PROPERTY(bool backgroundScaled READ backgroundScaled WRITE setBackgroundScaled) + Q_PROPERTY(Qt::AspectRatioMode backgroundScaledMode READ backgroundScaledMode WRITE setBackgroundScaledMode) + Q_PROPERTY(Qt::Orientations rangeDrag READ rangeDrag WRITE setRangeDrag) + Q_PROPERTY(Qt::Orientations rangeZoom READ rangeZoom WRITE setRangeZoom) + /// \endcond public: - explicit QCPAxisRect(QCustomPlot *parentPlot, bool setupDefaultAxes=true); - virtual ~QCPAxisRect() Q_DECL_OVERRIDE; - - // 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: - void setBackground(const QPixmap &pm); - void setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode=Qt::KeepAspectRatioByExpanding); - void setBackground(const QBrush &brush); - void setBackgroundScaled(bool scaled); - void setBackgroundScaledMode(Qt::AspectRatioMode mode); - 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); - - // non-property methods: - int axisCount(QCPAxis::AxisType type) const; - QCPAxis *axis(QCPAxis::AxisType type, int index=0) const; - QList axes(QCPAxis::AxisTypes types) const; - QList axes() const; - QCPAxis *addAxis(QCPAxis::AxisType type, QCPAxis *axis=nullptr); - QList addAxes(QCPAxis::AxisTypes types); - 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; - QList items() const; - - // read-only interface imitating a QRect: - int left() const { return mRect.left(); } - int right() const { return mRect.right(); } - int top() const { return mRect.top(); } - int bottom() const { return mRect.bottom(); } - int width() const { return mRect.width(); } - int height() const { return mRect.height(); } - QSize size() const { return mRect.size(); } - QPoint topLeft() const { return mRect.topLeft(); } - QPoint topRight() const { return mRect.topRight(); } - QPoint bottomLeft() const { return mRect.bottomLeft(); } - QPoint bottomRight() const { return mRect.bottomRight(); } - QPoint center() const { return mRect.center(); } - - // reimplemented virtual methods: - virtual void update(UpdatePhase phase) Q_DECL_OVERRIDE; - virtual QList elements(bool recursive) const Q_DECL_OVERRIDE; + explicit QCPAxisRect(QCustomPlot *parentPlot, bool setupDefaultAxes = true); + virtual ~QCPAxisRect() Q_DECL_OVERRIDE; + + // 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: + void setBackground(const QPixmap &pm); + void setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode = Qt::KeepAspectRatioByExpanding); + void setBackground(const QBrush &brush); + void setBackgroundScaled(bool scaled); + void setBackgroundScaledMode(Qt::AspectRatioMode mode); + 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); + + // non-property methods: + int axisCount(QCPAxis::AxisType type) const; + QCPAxis *axis(QCPAxis::AxisType type, int index = 0) const; + QList axes(QCPAxis::AxisTypes types) const; + QList axes() const; + QCPAxis *addAxis(QCPAxis::AxisType type, QCPAxis *axis = nullptr); + QList addAxes(QCPAxis::AxisTypes types); + 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; + QList items() const; + + // read-only interface imitating a QRect: + int left() const { + return mRect.left(); + } + int right() const { + return mRect.right(); + } + int top() const { + return mRect.top(); + } + int bottom() const { + return mRect.bottom(); + } + int width() const { + return mRect.width(); + } + int height() const { + return mRect.height(); + } + QSize size() const { + return mRect.size(); + } + QPoint topLeft() const { + return mRect.topLeft(); + } + QPoint topRight() const { + return mRect.topRight(); + } + QPoint bottomLeft() const { + return mRect.bottomLeft(); + } + QPoint bottomRight() const { + return mRect.bottomRight(); + } + QPoint center() const { + return mRect.center(); + } + + // reimplemented virtual methods: + virtual void update(UpdatePhase phase) Q_DECL_OVERRIDE; + virtual QList elements(bool recursive) const Q_DECL_OVERRIDE; protected: - // property members: - QBrush mBackgroundBrush; - QPixmap mBackgroundPixmap; - QPixmap mScaledBackgroundPixmap; - bool mBackgroundScaled; - Qt::AspectRatioMode mBackgroundScaledMode; - QCPLayoutInset *mInsetLayout; - Qt::Orientations mRangeDrag, mRangeZoom; - QList > mRangeDragHorzAxis, mRangeDragVertAxis; - QList > mRangeZoomHorzAxis, mRangeZoomVertAxis; - double mRangeZoomFactorHorz, mRangeZoomFactorVert; - - // non-property members: - QList mDragStartHorzRange, mDragStartVertRange; - QCP::AntialiasedElements mAADragBackup, mNotAADragBackup; - bool mDragging; - QHash > mAxes; - - // reimplemented virtual methods: - 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, 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); - void updateAxesOffset(QCPAxis::AxisType type); - + // property members: + QBrush mBackgroundBrush; + QPixmap mBackgroundPixmap; + QPixmap mScaledBackgroundPixmap; + bool mBackgroundScaled; + Qt::AspectRatioMode mBackgroundScaledMode; + QCPLayoutInset *mInsetLayout; + Qt::Orientations mRangeDrag, mRangeZoom; + QList > mRangeDragHorzAxis, mRangeDragVertAxis; + QList > mRangeZoomHorzAxis, mRangeZoomVertAxis; + double mRangeZoomFactorHorz, mRangeZoomFactorVert; + + // non-property members: + QList mDragStartHorzRange, mDragStartVertRange; + QCP::AntialiasedElements mAADragBackup, mNotAADragBackup; + bool mDragging; + QHash > mAxes; + + // reimplemented virtual methods: + 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, 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); + void updateAxesOffset(QCPAxis::AxisType type); + private: - Q_DISABLE_COPY(QCPAxisRect) - - friend class QCustomPlot; + Q_DISABLE_COPY(QCPAxisRect) + + friend class QCustomPlot; }; @@ -5012,212 +5522,252 @@ private: class QCP_LIB_DECL QCPAbstractLegendItem : public QCPLayoutElement { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QCPLegend* parentLegend READ parentLegend) - Q_PROPERTY(QFont font READ font WRITE setFont) - Q_PROPERTY(QColor textColor READ textColor WRITE setTextColor) - Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont) - Q_PROPERTY(QColor selectedTextColor READ selectedTextColor WRITE setSelectedTextColor) - Q_PROPERTY(bool selectable READ selectable WRITE setSelectable NOTIFY selectionChanged) - Q_PROPERTY(bool selected READ selected WRITE setSelected NOTIFY selectableChanged) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QCPLegend* parentLegend READ parentLegend) + Q_PROPERTY(QFont font READ font WRITE setFont) + Q_PROPERTY(QColor textColor READ textColor WRITE setTextColor) + Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont) + Q_PROPERTY(QColor selectedTextColor READ selectedTextColor WRITE setSelectedTextColor) + Q_PROPERTY(bool selectable READ selectable WRITE setSelectable NOTIFY selectionChanged) + Q_PROPERTY(bool selected READ selected WRITE setSelected NOTIFY selectableChanged) + /// \endcond public: - explicit QCPAbstractLegendItem(QCPLegend *parent); - - // getters: - QCPLegend *parentLegend() const { return mParentLegend; } - QFont font() const { return mFont; } - QColor textColor() const { return mTextColor; } - QFont selectedFont() const { return mSelectedFont; } - QColor selectedTextColor() const { return mSelectedTextColor; } - bool selectable() const { return mSelectable; } - bool selected() const { return mSelected; } - - // setters: - void setFont(const QFont &font); - void setTextColor(const QColor &color); - void setSelectedFont(const QFont &font); - void setSelectedTextColor(const QColor &color); - Q_SLOT void setSelectable(bool selectable); - Q_SLOT void setSelected(bool selected); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE; - + explicit QCPAbstractLegendItem(QCPLegend *parent); + + // getters: + QCPLegend *parentLegend() const { + return mParentLegend; + } + QFont font() const { + return mFont; + } + QColor textColor() const { + return mTextColor; + } + QFont selectedFont() const { + return mSelectedFont; + } + QColor selectedTextColor() const { + return mSelectedTextColor; + } + bool selectable() const { + return mSelectable; + } + bool selected() const { + return mSelected; + } + + // setters: + void setFont(const QFont &font); + void setTextColor(const QColor &color); + void setSelectedFont(const QFont &font); + void setSelectedTextColor(const QColor &color); + Q_SLOT void setSelectable(bool selectable); + Q_SLOT void setSelected(bool selected); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = nullptr) const Q_DECL_OVERRIDE; + signals: - void selectionChanged(bool selected); - void selectableChanged(bool selectable); - + void selectionChanged(bool selected); + void selectableChanged(bool selectable); + protected: - // property members: - QCPLegend *mParentLegend; - QFont mFont; - QColor mTextColor; - QFont mSelectedFont; - QColor mSelectedTextColor; - bool mSelectable, mSelected; - - // reimplemented virtual methods: - 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) Q_DECL_OVERRIDE; - virtual void deselectEvent(bool *selectionStateChanged) Q_DECL_OVERRIDE; - + // property members: + QCPLegend *mParentLegend; + QFont mFont; + QColor mTextColor; + QFont mSelectedFont; + QColor mSelectedTextColor; + bool mSelectable, mSelected; + + // reimplemented virtual methods: + 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) Q_DECL_OVERRIDE; + virtual void deselectEvent(bool *selectionStateChanged) Q_DECL_OVERRIDE; + private: - Q_DISABLE_COPY(QCPAbstractLegendItem) - - friend class QCPLegend; + Q_DISABLE_COPY(QCPAbstractLegendItem) + + friend class QCPLegend; }; class QCP_LIB_DECL QCPPlottableLegendItem : public QCPAbstractLegendItem { - Q_OBJECT -public: - QCPPlottableLegendItem(QCPLegend *parent, QCPAbstractPlottable *plottable); - - // getters: - QCPAbstractPlottable *plottable() { return mPlottable; } - + Q_OBJECT +public: QCPPlottableLegendItem(QCPLegend *parent, QCPAbstractPlottable *plottable); + + // getters: + QCPAbstractPlottable *plottable() { + return mPlottable; + } + protected: - // property members: - QCPAbstractPlottable *mPlottable; - - // reimplemented virtual methods: - virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; - virtual QSize minimumOuterSizeHint() const Q_DECL_OVERRIDE; - - // non-virtual methods: - QPen getIconBorderPen() const; - QColor getTextColor() const; - QFont getFont() const; + // property members: + QCPAbstractPlottable *mPlottable; + + // reimplemented virtual methods: + virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; + virtual QSize minimumOuterSizeHint() const Q_DECL_OVERRIDE; + + // non-virtual methods: + QPen getIconBorderPen() const; + QColor getTextColor() const; + QFont getFont() const; }; class QCP_LIB_DECL QCPLegend : public QCPLayoutGrid { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QPen borderPen READ borderPen WRITE setBorderPen) - Q_PROPERTY(QBrush brush READ brush WRITE setBrush) - Q_PROPERTY(QFont font READ font WRITE setFont) - Q_PROPERTY(QColor textColor READ textColor WRITE setTextColor) - Q_PROPERTY(QSize iconSize READ iconSize WRITE setIconSize) - Q_PROPERTY(int iconTextPadding READ iconTextPadding WRITE setIconTextPadding) - Q_PROPERTY(QPen iconBorderPen READ iconBorderPen WRITE setIconBorderPen) - Q_PROPERTY(SelectableParts selectableParts READ selectableParts WRITE setSelectableParts NOTIFY selectionChanged) - Q_PROPERTY(SelectableParts selectedParts READ selectedParts WRITE setSelectedParts NOTIFY selectableChanged) - Q_PROPERTY(QPen selectedBorderPen READ selectedBorderPen WRITE setSelectedBorderPen) - Q_PROPERTY(QPen selectedIconBorderPen READ selectedIconBorderPen WRITE setSelectedIconBorderPen) - Q_PROPERTY(QBrush selectedBrush READ selectedBrush WRITE setSelectedBrush) - Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont) - Q_PROPERTY(QColor selectedTextColor READ selectedTextColor WRITE setSelectedTextColor) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(QPen borderPen READ borderPen WRITE setBorderPen) + Q_PROPERTY(QBrush brush READ brush WRITE setBrush) + Q_PROPERTY(QFont font READ font WRITE setFont) + Q_PROPERTY(QColor textColor READ textColor WRITE setTextColor) + Q_PROPERTY(QSize iconSize READ iconSize WRITE setIconSize) + Q_PROPERTY(int iconTextPadding READ iconTextPadding WRITE setIconTextPadding) + Q_PROPERTY(QPen iconBorderPen READ iconBorderPen WRITE setIconBorderPen) + Q_PROPERTY(SelectableParts selectableParts READ selectableParts WRITE setSelectableParts NOTIFY selectionChanged) + Q_PROPERTY(SelectableParts selectedParts READ selectedParts WRITE setSelectedParts NOTIFY selectableChanged) + Q_PROPERTY(QPen selectedBorderPen READ selectedBorderPen WRITE setSelectedBorderPen) + Q_PROPERTY(QPen selectedIconBorderPen READ selectedIconBorderPen WRITE setSelectedIconBorderPen) + Q_PROPERTY(QBrush selectedBrush READ selectedBrush WRITE setSelectedBrush) + Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont) + Q_PROPERTY(QColor selectedTextColor READ selectedTextColor WRITE setSelectedTextColor) + /// \endcond public: - /*! + /*! Defines the selectable parts of a legend - + \see setSelectedParts, setSelectableParts - */ - enum SelectablePart { spNone = 0x000 ///< 0x000 None - ,spLegendBox = 0x001 ///< 0x001 The legend box (frame) - ,spItems = 0x002 ///< 0x002 Legend items individually (see \ref selectedItems) - }; - Q_ENUMS(SelectablePart) - Q_FLAGS(SelectableParts) - Q_DECLARE_FLAGS(SelectableParts, SelectablePart) - - explicit QCPLegend(); - virtual ~QCPLegend() Q_DECL_OVERRIDE; - - // getters: - QPen borderPen() const { return mBorderPen; } - QBrush brush() const { return mBrush; } - QFont font() const { return mFont; } - QColor textColor() const { return mTextColor; } - QSize iconSize() const { return mIconSize; } - int iconTextPadding() const { return mIconTextPadding; } - QPen iconBorderPen() const { return mIconBorderPen; } - SelectableParts selectableParts() const { return mSelectableParts; } - SelectableParts selectedParts() const; - QPen selectedBorderPen() const { return mSelectedBorderPen; } - QPen selectedIconBorderPen() const { return mSelectedIconBorderPen; } - QBrush selectedBrush() const { return mSelectedBrush; } - QFont selectedFont() const { return mSelectedFont; } - QColor selectedTextColor() const { return mSelectedTextColor; } - - // setters: - void setBorderPen(const QPen &pen); - void setBrush(const QBrush &brush); - void setFont(const QFont &font); - void setTextColor(const QColor &color); - void setIconSize(const QSize &size); - void setIconSize(int width, int height); - void setIconTextPadding(int padding); - void setIconBorderPen(const QPen &pen); - Q_SLOT void setSelectableParts(const SelectableParts &selectableParts); - Q_SLOT void setSelectedParts(const SelectableParts &selectedParts); - void setSelectedBorderPen(const QPen &pen); - void setSelectedIconBorderPen(const QPen &pen); - void setSelectedBrush(const QBrush &brush); - void setSelectedFont(const QFont &font); - void setSelectedTextColor(const QColor &color); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE; - - // non-virtual methods: - QCPAbstractLegendItem *item(int index) const; - QCPPlottableLegendItem *itemWithPlottable(const QCPAbstractPlottable *plottable) const; - int itemCount() const; - bool hasItem(QCPAbstractLegendItem *item) const; - bool hasItemWithPlottable(const QCPAbstractPlottable *plottable) const; - bool addItem(QCPAbstractLegendItem *item); - bool removeItem(int index); - bool removeItem(QCPAbstractLegendItem *item); - void clearItems(); - QList selectedItems() const; - + */ + enum SelectablePart { spNone = 0x000 ///< 0x000 None + , spLegendBox = 0x001 ///< 0x001 The legend box (frame) + , spItems = 0x002 ///< 0x002 Legend items individually (see \ref selectedItems) + }; + Q_ENUMS(SelectablePart) + Q_FLAGS(SelectableParts) + Q_DECLARE_FLAGS(SelectableParts, SelectablePart) + + explicit QCPLegend(); + virtual ~QCPLegend() Q_DECL_OVERRIDE; + + // getters: + QPen borderPen() const { + return mBorderPen; + } + QBrush brush() const { + return mBrush; + } + QFont font() const { + return mFont; + } + QColor textColor() const { + return mTextColor; + } + QSize iconSize() const { + return mIconSize; + } + int iconTextPadding() const { + return mIconTextPadding; + } + QPen iconBorderPen() const { + return mIconBorderPen; + } + SelectableParts selectableParts() const { + return mSelectableParts; + } + SelectableParts selectedParts() const; + QPen selectedBorderPen() const { + return mSelectedBorderPen; + } + QPen selectedIconBorderPen() const { + return mSelectedIconBorderPen; + } + QBrush selectedBrush() const { + return mSelectedBrush; + } + QFont selectedFont() const { + return mSelectedFont; + } + QColor selectedTextColor() const { + return mSelectedTextColor; + } + + // setters: + void setBorderPen(const QPen &pen); + void setBrush(const QBrush &brush); + void setFont(const QFont &font); + void setTextColor(const QColor &color); + void setIconSize(const QSize &size); + void setIconSize(int width, int height); + void setIconTextPadding(int padding); + void setIconBorderPen(const QPen &pen); + Q_SLOT void setSelectableParts(const SelectableParts &selectableParts); + Q_SLOT void setSelectedParts(const SelectableParts &selectedParts); + void setSelectedBorderPen(const QPen &pen); + void setSelectedIconBorderPen(const QPen &pen); + void setSelectedBrush(const QBrush &brush); + void setSelectedFont(const QFont &font); + void setSelectedTextColor(const QColor &color); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = nullptr) const Q_DECL_OVERRIDE; + + // non-virtual methods: + QCPAbstractLegendItem *item(int index) const; + QCPPlottableLegendItem *itemWithPlottable(const QCPAbstractPlottable *plottable) const; + int itemCount() const; + bool hasItem(QCPAbstractLegendItem *item) const; + bool hasItemWithPlottable(const QCPAbstractPlottable *plottable) const; + bool addItem(QCPAbstractLegendItem *item); + bool removeItem(int index); + bool removeItem(QCPAbstractLegendItem *item); + void clearItems(); + QList selectedItems() const; + signals: - void selectionChanged(QCPLegend::SelectableParts parts); - void selectableChanged(QCPLegend::SelectableParts parts); - + void selectionChanged(QCPLegend::SelectableParts parts); + void selectableChanged(QCPLegend::SelectableParts parts); + protected: - // property members: - QPen mBorderPen, mIconBorderPen; - QBrush mBrush; - QFont mFont; - QColor mTextColor; - QSize mIconSize; - int mIconTextPadding; - SelectableParts mSelectedParts, mSelectableParts; - QPen mSelectedBorderPen, mSelectedIconBorderPen; - QBrush mSelectedBrush; - QFont mSelectedFont; - QColor mSelectedTextColor; - - // reimplemented virtual methods: - 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) Q_DECL_OVERRIDE; - virtual void deselectEvent(bool *selectionStateChanged) Q_DECL_OVERRIDE; - - // non-virtual methods: - QPen getBorderPen() const; - QBrush getBrush() const; - + // property members: + QPen mBorderPen, mIconBorderPen; + QBrush mBrush; + QFont mFont; + QColor mTextColor; + QSize mIconSize; + int mIconTextPadding; + SelectableParts mSelectedParts, mSelectableParts; + QPen mSelectedBorderPen, mSelectedIconBorderPen; + QBrush mSelectedBrush; + QFont mSelectedFont; + QColor mSelectedTextColor; + + // reimplemented virtual methods: + 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) Q_DECL_OVERRIDE; + virtual void deselectEvent(bool *selectionStateChanged) Q_DECL_OVERRIDE; + + // non-virtual methods: + QPen getBorderPen() const; + QBrush getBrush() const; + private: - Q_DISABLE_COPY(QCPLegend) - - friend class QCustomPlot; - friend class QCPAbstractLegendItem; + Q_DISABLE_COPY(QCPLegend) + + friend class QCustomPlot; + friend class QCPAbstractLegendItem; }; Q_DECLARE_OPERATORS_FOR_FLAGS(QCPLegend::SelectableParts) Q_DECLARE_METATYPE(QCPLegend::SelectablePart) @@ -5230,81 +5780,96 @@ Q_DECLARE_METATYPE(QCPLegend::SelectablePart) class QCP_LIB_DECL QCPTextElement : public QCPLayoutElement { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QString text READ text WRITE setText) - Q_PROPERTY(QFont font READ font WRITE setFont) - Q_PROPERTY(QColor textColor READ textColor WRITE setTextColor) - Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont) - Q_PROPERTY(QColor selectedTextColor READ selectedTextColor WRITE setSelectedTextColor) - Q_PROPERTY(bool selectable READ selectable WRITE setSelectable NOTIFY selectableChanged) - Q_PROPERTY(bool selected READ selected WRITE setSelected NOTIFY selectionChanged) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QString text READ text WRITE setText) + Q_PROPERTY(QFont font READ font WRITE setFont) + Q_PROPERTY(QColor textColor READ textColor WRITE setTextColor) + Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont) + Q_PROPERTY(QColor selectedTextColor READ selectedTextColor WRITE setSelectedTextColor) + Q_PROPERTY(bool selectable READ selectable WRITE setSelectable NOTIFY selectableChanged) + Q_PROPERTY(bool selected READ selected WRITE setSelected NOTIFY selectionChanged) + /// \endcond public: - 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; } - QColor selectedTextColor() const { return mSelectedTextColor; } - bool selectable() const { return mSelectable; } - bool selected() const { return mSelected; } - - // 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); - void setSelectedTextColor(const QColor &color); - Q_SLOT void setSelectable(bool selectable); - Q_SLOT void setSelected(bool selected); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) 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; - + 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; + } + QColor selectedTextColor() const { + return mSelectedTextColor; + } + bool selectable() const { + return mSelectable; + } + bool selected() const { + return mSelected; + } + + // 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); + void setSelectedTextColor(const QColor &color); + Q_SLOT void setSelectable(bool selectable); + Q_SLOT void setSelected(bool selected); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = nullptr) 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); - + 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; - QColor mSelectedTextColor; - QRect mTextBoundingRect; - bool mSelectable, mSelected; - - // reimplemented virtual methods: - virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const Q_DECL_OVERRIDE; - virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; - virtual QSize minimumOuterSizeHint() const Q_DECL_OVERRIDE; - virtual QSize maximumOuterSizeHint() 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; - - // non-virtual methods: - QFont mainFont() const; - QColor mainTextColor() const; - + // property members: + QString mText; + int mTextFlags; + QFont mFont; + QColor mTextColor; + QFont mSelectedFont; + QColor mSelectedTextColor; + QRect mTextBoundingRect; + bool mSelectable, mSelected; + + // reimplemented virtual methods: + virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const Q_DECL_OVERRIDE; + virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; + virtual QSize minimumOuterSizeHint() const Q_DECL_OVERRIDE; + virtual QSize maximumOuterSizeHint() 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; + + // non-virtual methods: + QFont mainFont() const; + QColor mainTextColor() const; + private: - Q_DISABLE_COPY(QCPTextElement) + Q_DISABLE_COPY(QCPTextElement) }; @@ -5318,102 +5883,113 @@ private: class QCPColorScaleAxisRectPrivate : public QCPAxisRect { - Q_OBJECT + Q_OBJECT public: - explicit QCPColorScaleAxisRectPrivate(QCPColorScale *parentColorScale); + explicit QCPColorScaleAxisRectPrivate(QCPColorScale *parentColorScale); protected: - QCPColorScale *mParentColorScale; - QImage mGradientImage; - bool mGradientImageInvalidated; - // re-using some methods of QCPAxisRect to make them available to friend class QCPColorScale - using QCPAxisRect::calculateAutoMargin; - using QCPAxisRect::mousePressEvent; - using QCPAxisRect::mouseMoveEvent; - using QCPAxisRect::mouseReleaseEvent; - using QCPAxisRect::wheelEvent; - using QCPAxisRect::update; - virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; - void updateGradientImage(); - Q_SLOT void axisSelectionChanged(QCPAxis::SelectableParts selectedParts); - Q_SLOT void axisSelectableChanged(QCPAxis::SelectableParts selectableParts); - friend class QCPColorScale; + QCPColorScale *mParentColorScale; + QImage mGradientImage; + bool mGradientImageInvalidated; + // re-using some methods of QCPAxisRect to make them available to friend class QCPColorScale + using QCPAxisRect::calculateAutoMargin; + using QCPAxisRect::mousePressEvent; + using QCPAxisRect::mouseMoveEvent; + using QCPAxisRect::mouseReleaseEvent; + using QCPAxisRect::wheelEvent; + using QCPAxisRect::update; + virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; + void updateGradientImage(); + Q_SLOT void axisSelectionChanged(QCPAxis::SelectableParts selectedParts); + Q_SLOT void axisSelectableChanged(QCPAxis::SelectableParts selectableParts); + friend class QCPColorScale; }; class QCP_LIB_DECL QCPColorScale : public QCPLayoutElement { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QCPAxis::AxisType type READ type WRITE setType) - Q_PROPERTY(QCPRange dataRange READ dataRange WRITE setDataRange NOTIFY dataRangeChanged) - Q_PROPERTY(QCPAxis::ScaleType dataScaleType READ dataScaleType WRITE setDataScaleType NOTIFY dataScaleTypeChanged) - Q_PROPERTY(QCPColorGradient gradient READ gradient WRITE setGradient NOTIFY gradientChanged) - Q_PROPERTY(QString label READ label WRITE setLabel) - Q_PROPERTY(int barWidth READ barWidth WRITE setBarWidth) - Q_PROPERTY(bool rangeDrag READ rangeDrag WRITE setRangeDrag) - Q_PROPERTY(bool rangeZoom READ rangeZoom WRITE setRangeZoom) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QCPAxis::AxisType type READ type WRITE setType) + Q_PROPERTY(QCPRange dataRange READ dataRange WRITE setDataRange NOTIFY dataRangeChanged) + Q_PROPERTY(QCPAxis::ScaleType dataScaleType READ dataScaleType WRITE setDataScaleType NOTIFY dataScaleTypeChanged) + Q_PROPERTY(QCPColorGradient gradient READ gradient WRITE setGradient NOTIFY gradientChanged) + Q_PROPERTY(QString label READ label WRITE setLabel) + Q_PROPERTY(int barWidth READ barWidth WRITE setBarWidth) + Q_PROPERTY(bool rangeDrag READ rangeDrag WRITE setRangeDrag) + Q_PROPERTY(bool rangeZoom READ rangeZoom WRITE setRangeZoom) + /// \endcond public: - explicit QCPColorScale(QCustomPlot *parentPlot); - virtual ~QCPColorScale() Q_DECL_OVERRIDE; - - // getters: - QCPAxis *axis() const { return mColorAxis.data(); } - QCPAxis::AxisType type() const { return mType; } - QCPRange dataRange() const { return mDataRange; } - QCPAxis::ScaleType dataScaleType() const { return mDataScaleType; } - QCPColorGradient gradient() const { return mGradient; } - QString label() const; - int barWidth () const { return mBarWidth; } - bool rangeDrag() const; - bool rangeZoom() const; - - // setters: - void setType(QCPAxis::AxisType type); - Q_SLOT void setDataRange(const QCPRange &dataRange); - Q_SLOT void setDataScaleType(QCPAxis::ScaleType scaleType); - Q_SLOT void setGradient(const QCPColorGradient &gradient); - void setLabel(const QString &str); - void setBarWidth(int width); - void setRangeDrag(bool enabled); - void setRangeZoom(bool enabled); - - // non-property methods: - QList colorMaps() const; - void rescaleDataRange(bool onlyVisibleMaps); - - // reimplemented virtual methods: - virtual void update(UpdatePhase phase) Q_DECL_OVERRIDE; - + explicit QCPColorScale(QCustomPlot *parentPlot); + virtual ~QCPColorScale() Q_DECL_OVERRIDE; + + // getters: + QCPAxis *axis() const { + return mColorAxis.data(); + } + QCPAxis::AxisType type() const { + return mType; + } + QCPRange dataRange() const { + return mDataRange; + } + QCPAxis::ScaleType dataScaleType() const { + return mDataScaleType; + } + QCPColorGradient gradient() const { + return mGradient; + } + QString label() const; + int barWidth() const { + return mBarWidth; + } + bool rangeDrag() const; + bool rangeZoom() const; + + // setters: + void setType(QCPAxis::AxisType type); + Q_SLOT void setDataRange(const QCPRange &dataRange); + Q_SLOT void setDataScaleType(QCPAxis::ScaleType scaleType); + Q_SLOT void setGradient(const QCPColorGradient &gradient); + void setLabel(const QString &str); + void setBarWidth(int width); + void setRangeDrag(bool enabled); + void setRangeZoom(bool enabled); + + // non-property methods: + QList colorMaps() const; + void rescaleDataRange(bool onlyVisibleMaps); + + // reimplemented virtual methods: + virtual void update(UpdatePhase phase) Q_DECL_OVERRIDE; + signals: - void dataRangeChanged(const QCPRange &newRange); - void dataScaleTypeChanged(QCPAxis::ScaleType scaleType); - void gradientChanged(const QCPColorGradient &newGradient); + void dataRangeChanged(const QCPRange &newRange); + void dataScaleTypeChanged(QCPAxis::ScaleType scaleType); + void gradientChanged(const QCPColorGradient &newGradient); protected: - // property members: - QCPAxis::AxisType mType; - QCPRange mDataRange; - QCPAxis::ScaleType mDataScaleType; - QCPColorGradient mGradient; - int mBarWidth; - - // non-property members: - QPointer mAxisRect; - QPointer mColorAxis; - - // reimplemented virtual methods: - virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const Q_DECL_OVERRIDE; - // events: - 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; - + // property members: + QCPAxis::AxisType mType; + QCPRange mDataRange; + QCPAxis::ScaleType mDataScaleType; + QCPColorGradient mGradient; + int mBarWidth; + + // non-property members: + QPointer mAxisRect; + QPointer mColorAxis; + + // reimplemented virtual methods: + virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const Q_DECL_OVERRIDE; + // events: + 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) - - friend class QCPColorScaleAxisRectPrivate; + Q_DISABLE_COPY(QCPColorScale) + + friend class QCPColorScaleAxisRectPrivate; }; @@ -5426,133 +6002,166 @@ private: class QCP_LIB_DECL QCPGraphData { public: - QCPGraphData(); - QCPGraphData(double key, double value); - - 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; + QCPGraphData(); + QCPGraphData(double key, double value); + + 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 QCPDataContainer QCPGraphDataContainer; 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(int scatterSkip READ scatterSkip WRITE setScatterSkip) - Q_PROPERTY(QCPGraph* channelFillGraph READ channelFillGraph WRITE setChannelFillGraph) - Q_PROPERTY(bool adaptiveSampling READ adaptiveSampling WRITE setAdaptiveSampling) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(LineStyle lineStyle READ lineStyle WRITE setLineStyle) + Q_PROPERTY(QCPScatterStyle scatterStyle READ scatterStyle WRITE setScatterStyle) + 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 public: - /*! + /*! Defines how the graph's line is represented visually in the plot. The line is drawn with the current pen of the graph (\ref setPen). \see setLineStyle - */ - enum LineStyle { lsNone ///< data points are not connected with any lines (e.g. data only represented - ///< with symbols according to the scatter style, see \ref setScatterStyle) - ,lsLine ///< data points are connected by a straight line - ,lsStepLeft ///< line is drawn as steps where the step height is the value of the left data point - ,lsStepRight ///< line is drawn as steps where the step height is the value of the right data point - ,lsStepCenter ///< line is drawn as steps where the step is in between two data points - ,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) - - explicit QCPGraph(QCPAxis *keyAxis, QCPAxis *valueAxis); - virtual ~QCPGraph() Q_DECL_OVERRIDE; - - // getters: - QSharedPointer data() const { return mDataContainer; } - LineStyle lineStyle() const { return mLineStyle; } - QCPScatterStyle scatterStyle() const { return mScatterStyle; } - int scatterSkip() const { return mScatterSkip; } - QCPGraph *channelFillGraph() const { return mChannelFillGraph.data(); } - bool adaptiveSampling() const { return mAdaptiveSampling; } - - // setters: - 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 setScatterSkip(int skip); - void setChannelFillGraph(QCPGraph *targetGraph); - void setAdaptiveSampling(bool enabled); - - // non-property methods: - void addData(const QVector &keys, const QVector &values, bool alreadySorted=false); - void addData(double key, double value); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) 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; - + */ + enum LineStyle { lsNone ///< data points are not connected with any lines (e.g. data only represented + ///< with symbols according to the scatter style, see \ref setScatterStyle) + , lsLine ///< data points are connected by a straight line + , lsStepLeft ///< line is drawn as steps where the step height is the value of the left data point + , lsStepRight ///< line is drawn as steps where the step height is the value of the right data point + , lsStepCenter ///< line is drawn as steps where the step is in between two data points + , 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) + + explicit QCPGraph(QCPAxis *keyAxis, QCPAxis *valueAxis); + virtual ~QCPGraph() Q_DECL_OVERRIDE; + + // getters: + QSharedPointer data() const { + return mDataContainer; + } + LineStyle lineStyle() const { + return mLineStyle; + } + QCPScatterStyle scatterStyle() const { + return mScatterStyle; + } + int scatterSkip() const { + return mScatterSkip; + } + QCPGraph *channelFillGraph() const { + return mChannelFillGraph.data(); + } + bool adaptiveSampling() const { + return mAdaptiveSampling; + } + + // setters: + 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 setScatterSkip(int skip); + void setChannelFillGraph(QCPGraph *targetGraph); + void setAdaptiveSampling(bool enabled); + + // non-property methods: + void addData(const QVector &keys, const QVector &values, bool alreadySorted = false); + void addData(double key, double value); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = nullptr) 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: - LineStyle mLineStyle; - QCPScatterStyle mScatterStyle; - int mScatterSkip; - QPointer mChannelFillGraph; - bool mAdaptiveSampling; - - // reimplemented virtual methods: - 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 *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 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; - QVector getNonNanSegments(const QVector *lineData, Qt::Orientation keyOrientation) const; - QVector > getOverlappingSegments(QVector thisSegments, const QVector *thisData, QVector otherSegments, const QVector *otherData) const; - bool segmentsIntersect(double aLower, double aUpper, double bLower, double bUpper, int &bPrecedence) const; - QPointF getFillBasePoint(QPointF matchingDataPoint) const; - const QPolygonF getFillPolygon(const QVector *lineData, QCPDataRange segment) const; - const QPolygonF getChannelFillPolygon(const QVector *thisData, QCPDataRange thisSegment, const QVector *otherData, QCPDataRange otherSegment) 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, QCPGraphDataContainer::const_iterator &closestData) const; - - friend class QCustomPlot; - friend class QCPLegend; + // property members: + LineStyle mLineStyle; + QCPScatterStyle mScatterStyle; + int mScatterSkip; + QPointer mChannelFillGraph; + bool mAdaptiveSampling; + + // reimplemented virtual methods: + virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; + virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const Q_DECL_OVERRIDE; + + int smooth; +public: + void setSmooth(int smooth); + +protected: + // introduced virtual methods: + 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 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; + QVector getNonNanSegments(const QVector *lineData, Qt::Orientation keyOrientation) const; + QVector > getOverlappingSegments(QVector thisSegments, const QVector *thisData, QVector otherSegments, const QVector *otherData) const; + bool segmentsIntersect(double aLower, double aUpper, double bLower, double bUpper, int &bPrecedence) const; + QPointF getFillBasePoint(QPointF matchingDataPoint) const; + + const QPolygonF getFillPolygon(const QVector *lineData, QCPDataRange segment) const; + const QPainterPath getFillPath(const QVector *lineData, QCPDataRange segment) const; + const QPolygonF getChannelFillPolygon(const QVector *lineData, QCPDataRange thisSegment, const QVector *otherData, QCPDataRange otherSegment) const; + //const QPainterPath getChannelFillPath(const QVector *lineData, QCPDataRange thisSegment, const QVector *otherData, QCPDataRange otherSegment) 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, QCPGraphDataContainer::const_iterator &closestData) const; + + friend class QCustomPlot; + friend class QCPLegend; }; Q_DECLARE_METATYPE(QCPGraph::LineStyle) @@ -5565,109 +6174,129 @@ Q_DECLARE_METATYPE(QCPGraph::LineStyle) 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; + 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_PRIMITIVE_TYPE); /*! \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. - + \see QCPCurveData, QCPCurve::setData */ typedef QCPDataContainer QCPCurveDataContainer; 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 + 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: - /*! + /*! Defines how the curve's line is represented visually in the plot. The line is drawn with the current pen of the curve (\ref setPen). \see setLineStyle - */ - 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() Q_DECL_OVERRIDE; - - // getters: - QSharedPointer data() const { return mDataContainer; } - QCPScatterStyle scatterStyle() const { return mScatterStyle; } - int scatterSkip() const { return mScatterSkip; } - LineStyle lineStyle() const { return mLineStyle; } - - // setters: - 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 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); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) 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; - + */ + 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() Q_DECL_OVERRIDE; + + // getters: + QSharedPointer data() const { + return mDataContainer; + } + QCPScatterStyle scatterStyle() const { + return mScatterStyle; + } + int scatterSkip() const { + return mScatterSkip; + } + LineStyle lineStyle() const { + return mLineStyle; + } + + // setters: + 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 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); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = nullptr) 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: - QCPScatterStyle mScatterStyle; - int mScatterSkip; - LineStyle mLineStyle; - - // reimplemented virtual methods: - 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 drawCurveLine(QCPPainter *painter, const QVector &lines) const; - virtual void drawScatterPlot(QCPPainter *painter, const QVector &points, const QCPScatterStyle &style) const; - - // non-virtual methods: - 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 otherRegion, double otherKey, double otherValue, 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 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; + // property members: + QCPScatterStyle mScatterStyle; + int mScatterSkip; + LineStyle mLineStyle; + + // reimplemented virtual methods: + 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 drawCurveLine(QCPPainter *painter, const QVector &lines) const; + virtual void drawScatterPlot(QCPPainter *painter, const QVector &points, const QCPScatterStyle &style) const; + + // non-virtual methods: + 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 otherRegion, double otherKey, double otherValue, 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 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) @@ -5679,65 +6308,77 @@ Q_DECLARE_METATYPE(QCPCurve::LineStyle) class QCP_LIB_DECL QCPBarsGroup : public QObject { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(SpacingType spacingType READ spacingType WRITE setSpacingType) - Q_PROPERTY(double spacing READ spacing WRITE setSpacing) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(SpacingType spacingType READ spacingType WRITE setSpacingType) + Q_PROPERTY(double spacing READ spacing WRITE setSpacing) + /// \endcond public: - /*! + /*! Defines the ways the spacing between bars in the group can be specified. Thus it defines what the number passed to \ref setSpacing actually means. - + \see setSpacingType, setSpacing - */ - 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) - - explicit QCPBarsGroup(QCustomPlot *parentPlot); - virtual ~QCPBarsGroup(); - - // getters: - SpacingType spacingType() const { return mSpacingType; } - double spacing() const { return mSpacing; } - - // setters: - void setSpacingType(SpacingType spacingType); - void setSpacing(double spacing); - - // non-virtual methods: - QList bars() const { return mBars; } - QCPBars* bars(int index) const; - int size() const { return mBars.size(); } - bool isEmpty() const { return mBars.isEmpty(); } - void clear(); - bool contains(QCPBars *bars) const { return mBars.contains(bars); } - void append(QCPBars *bars); - void insert(int i, QCPBars *bars); - void remove(QCPBars *bars); - + */ + 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) + + explicit QCPBarsGroup(QCustomPlot *parentPlot); + virtual ~QCPBarsGroup(); + + // getters: + SpacingType spacingType() const { + return mSpacingType; + } + double spacing() const { + return mSpacing; + } + + // setters: + void setSpacingType(SpacingType spacingType); + void setSpacing(double spacing); + + // non-virtual methods: + QList bars() const { + return mBars; + } + QCPBars *bars(int index) const; + int size() const { + return mBars.size(); + } + bool isEmpty() const { + return mBars.isEmpty(); + } + void clear(); + bool contains(QCPBars *bars) const { + return mBars.contains(bars); + } + void append(QCPBars *bars); + void insert(int i, QCPBars *bars); + void remove(QCPBars *bars); + protected: - // non-property members: - QCustomPlot *mParentPlot; - SpacingType mSpacingType; - double mSpacing; - QList mBars; - - // non-virtual methods: - void registerBars(QCPBars *bars); - void unregisterBars(QCPBars *bars); - - // virtual methods: - double keyPixelOffset(const QCPBars *bars, double keyCoord); - double getPixelSpacing(const QCPBars *bars, double keyCoord); - + // non-property members: + QCustomPlot *mParentPlot; + SpacingType mSpacingType; + double mSpacing; + QList mBars; + + // non-virtual methods: + void registerBars(QCPBars *bars); + void unregisterBars(QCPBars *bars); + + // virtual methods: + double keyPixelOffset(const QCPBars *bars, double keyCoord); + double getPixelSpacing(const QCPBars *bars, double keyCoord); + private: - Q_DISABLE_COPY(QCPBarsGroup) - - friend class QCPBars; + Q_DISABLE_COPY(QCPBarsGroup) + + friend class QCPBars; }; Q_DECLARE_METATYPE(QCPBarsGroup::SpacingType) @@ -5745,117 +6386,145 @@ Q_DECLARE_METATYPE(QCPBarsGroup::SpacingType) class QCP_LIB_DECL QCPBarsData { public: - 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; + 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(QCPBarsData, Q_PRIMITIVE_TYPE); /*! \typedef QCPBarsDataContainer - + 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 QCPDataContainer QCPBarsDataContainer; class QCP_LIB_DECL QCPBars : public QCPAbstractPlottable1D { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(double width READ width WRITE setWidth) - 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 + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(double width READ width WRITE setWidth) + 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 public: - /*! + /*! Defines the ways the width of the bar can be specified. Thus it defines what the number passed to \ref setWidth actually means. - + \see setWidthType, setWidth - */ - enum WidthType { wtAbsolute ///< Bar width is in absolute pixels - ,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) - - explicit QCPBars(QCPAxis *keyAxis, QCPAxis *valueAxis); - virtual ~QCPBars() Q_DECL_OVERRIDE; - - // getters: - double width() const { return mWidth; } - 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(); } - 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 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); - - // 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=nullptr) 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; - + */ + enum WidthType { wtAbsolute ///< Bar width is in absolute pixels + , 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) + + explicit QCPBars(QCPAxis *keyAxis, QCPAxis *valueAxis); + virtual ~QCPBars() Q_DECL_OVERRIDE; + + // getters: + double width() const { + return mWidth; + } + 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(); + } + 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 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); + + // 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 = nullptr) 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: - double mWidth; - WidthType mWidthType; - QCPBarsGroup *mBarsGroup; - double mBaseValue; - double mStackingGap; - QPointer mBarBelow, mBarAbove; - - // reimplemented virtual methods: - 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(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); - - friend class QCustomPlot; - friend class QCPLegend; - friend class QCPBarsGroup; + // property members: + double mWidth; + WidthType mWidthType; + QCPBarsGroup *mBarsGroup; + double mBaseValue; + double mStackingGap; + QPointer mBarBelow, mBarAbove; + + // reimplemented virtual methods: + 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(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); + + friend class QCustomPlot; + friend class QCPLegend; + friend class QCPBarsGroup; }; Q_DECLARE_METATYPE(QCPBars::WidthType) @@ -5868,112 +6537,137 @@ Q_DECLARE_METATYPE(QCPBars::WidthType) 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; + 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 QCPAbstractPlottable1D { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - 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 + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES 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 public: - explicit QCPStatisticalBox(QCPAxis *keyAxis, QCPAxis *valueAxis); - - // getters: - 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; } + explicit QCPStatisticalBox(QCPAxis *keyAxis, QCPAxis *valueAxis); + + // getters: + 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 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: + 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 = nullptr) 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; - // setters: - 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: - 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=nullptr) 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: - double mWidth; - double mWhiskerWidth; - QPen mWhiskerPen, mWhiskerBarPen; - bool mWhiskerAntialiased; - QPen mMedianPen; - QCPScatterStyle mOutlierStyle; - - // reimplemented virtual methods: - 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 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; + // property members: + double mWidth; + double mWhiskerWidth; + QPen mWhiskerPen, mWhiskerBarPen; + bool mWhiskerAntialiased; + QPen mMedianPen; + QCPScatterStyle mOutlierStyle; + + // reimplemented virtual methods: + 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 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' */ @@ -5985,131 +6679,156 @@ protected: class QCP_LIB_DECL QCPColorMapData { public: - QCPColorMapData(int keySize, int valueSize, const QCPRange &keyRange, const QCPRange &valueRange); - ~QCPColorMapData(); - QCPColorMapData(const QCPColorMapData &other); - QCPColorMapData &operator=(const QCPColorMapData &other); - - // getters: - int keySize() const { return mKeySize; } - int valueSize() const { return mValueSize; } - QCPRange keyRange() const { return mKeyRange; } - QCPRange valueRange() const { return mValueRange; } - 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); - void setKeySize(int keySize); - void setValueSize(int valueSize); - void setRange(const QCPRange &keyRange, const QCPRange &valueRange); - void setKeyRange(const QCPRange &keyRange); - 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; - + QCPColorMapData(int keySize, int valueSize, const QCPRange &keyRange, const QCPRange &valueRange); + ~QCPColorMapData(); + QCPColorMapData(const QCPColorMapData &other); + QCPColorMapData &operator=(const QCPColorMapData &other); + + // getters: + int keySize() const { + return mKeySize; + } + int valueSize() const { + return mValueSize; + } + QCPRange keyRange() const { + return mKeyRange; + } + QCPRange valueRange() const { + return mValueRange; + } + 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); + void setKeySize(int keySize); + void setValueSize(int valueSize); + void setRange(const QCPRange &keyRange, const QCPRange &valueRange); + void setKeyRange(const QCPRange &keyRange); + 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; + protected: - // property members: - 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; + // property members: + 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; }; class QCP_LIB_DECL QCPColorMap : public QCPAbstractPlottable { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QCPRange dataRange READ dataRange WRITE setDataRange NOTIFY dataRangeChanged) - Q_PROPERTY(QCPAxis::ScaleType dataScaleType READ dataScaleType WRITE setDataScaleType NOTIFY dataScaleTypeChanged) - Q_PROPERTY(QCPColorGradient gradient READ gradient WRITE setGradient NOTIFY gradientChanged) - Q_PROPERTY(bool interpolate READ interpolate WRITE setInterpolate) - Q_PROPERTY(bool tightBoundary READ tightBoundary WRITE setTightBoundary) - Q_PROPERTY(QCPColorScale* colorScale READ colorScale WRITE setColorScale) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QCPRange dataRange READ dataRange WRITE setDataRange NOTIFY dataRangeChanged) + Q_PROPERTY(QCPAxis::ScaleType dataScaleType READ dataScaleType WRITE setDataScaleType NOTIFY dataScaleTypeChanged) + Q_PROPERTY(QCPColorGradient gradient READ gradient WRITE setGradient NOTIFY gradientChanged) + Q_PROPERTY(bool interpolate READ interpolate WRITE setInterpolate) + Q_PROPERTY(bool tightBoundary READ tightBoundary WRITE setTightBoundary) + Q_PROPERTY(QCPColorScale *colorScale READ colorScale WRITE setColorScale) + /// \endcond public: - explicit QCPColorMap(QCPAxis *keyAxis, QCPAxis *valueAxis); - virtual ~QCPColorMap() Q_DECL_OVERRIDE; - - // getters: - QCPColorMapData *data() const { return mMapData; } - QCPRange dataRange() const { return mDataRange; } - QCPAxis::ScaleType dataScaleType() const { return mDataScaleType; } - bool interpolate() const { return mInterpolate; } - bool tightBoundary() const { return mTightBoundary; } - QCPColorGradient gradient() const { return mGradient; } - QCPColorScale *colorScale() const { return mColorScale.data(); } - - // setters: - void setData(QCPColorMapData *data, bool copy=false); - Q_SLOT void setDataRange(const QCPRange &dataRange); - Q_SLOT void setDataScaleType(QCPAxis::ScaleType scaleType); - Q_SLOT void setGradient(const QCPColorGradient &gradient); - void setInterpolate(bool enabled); - void setTightBoundary(bool enabled); - void setColorScale(QCPColorScale *colorScale); - - // non-property methods: - void rescaleDataRange(bool recalculateDataBounds=false); - Q_SLOT void updateLegendIcon(Qt::TransformationMode transformMode=Qt::SmoothTransformation, const QSize &thumbSize=QSize(32, 18)); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) 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; - + explicit QCPColorMap(QCPAxis *keyAxis, QCPAxis *valueAxis); + virtual ~QCPColorMap() Q_DECL_OVERRIDE; + + // getters: + QCPColorMapData *data() const { + return mMapData; + } + QCPRange dataRange() const { + return mDataRange; + } + QCPAxis::ScaleType dataScaleType() const { + return mDataScaleType; + } + bool interpolate() const { + return mInterpolate; + } + bool tightBoundary() const { + return mTightBoundary; + } + QCPColorGradient gradient() const { + return mGradient; + } + QCPColorScale *colorScale() const { + return mColorScale.data(); + } + + // setters: + void setData(QCPColorMapData *data, bool copy = false); + Q_SLOT void setDataRange(const QCPRange &dataRange); + Q_SLOT void setDataScaleType(QCPAxis::ScaleType scaleType); + Q_SLOT void setGradient(const QCPColorGradient &gradient); + void setInterpolate(bool enabled); + void setTightBoundary(bool enabled); + void setColorScale(QCPColorScale *colorScale); + + // non-property methods: + void rescaleDataRange(bool recalculateDataBounds = false); + Q_SLOT void updateLegendIcon(Qt::TransformationMode transformMode = Qt::SmoothTransformation, const QSize &thumbSize = QSize(32, 18)); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = nullptr) 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(const QCPRange &newRange); - void dataScaleTypeChanged(QCPAxis::ScaleType scaleType); - void gradientChanged(const QCPColorGradient &newGradient); - + void dataRangeChanged(const QCPRange &newRange); + void dataScaleTypeChanged(QCPAxis::ScaleType scaleType); + void gradientChanged(const QCPColorGradient &newGradient); + protected: - // property members: - QCPRange mDataRange; - QCPAxis::ScaleType mDataScaleType; - QCPColorMapData *mMapData; - QCPColorGradient mGradient; - bool mInterpolate; - bool mTightBoundary; - QPointer mColorScale; - - // non-property members: - QImage mMapImage, mUndersampledMapImage; - QPixmap mLegendIcon; - bool mMapImageInvalidated; - - // introduced virtual methods: - virtual void updateMapImage(); - - // reimplemented virtual methods: - 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; + // property members: + QCPRange mDataRange; + QCPAxis::ScaleType mDataScaleType; + QCPColorMapData *mMapData; + QCPColorGradient mGradient; + bool mInterpolate; + bool mTightBoundary; + QPointer mColorScale; + + // non-property members: + QImage mMapImage, mUndersampledMapImage; + QPixmap mLegendIcon; + bool mMapImageInvalidated; + + // introduced virtual methods: + virtual void updateMapImage(); + + // reimplemented virtual methods: + 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; }; /* end of 'src/plottables/plottable-colormap.h' */ @@ -6121,133 +6840,163 @@ protected: 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; + 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_PRIMITIVE_TYPE); /*! \typedef QCPFinancialDataContainer - + 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 QCPDataContainer QCPFinancialDataContainer; 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) - Q_PROPERTY(QPen penPositive READ penPositive WRITE setPenPositive) - Q_PROPERTY(QPen penNegative READ penNegative WRITE setPenNegative) - /// \endcond + 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) + Q_PROPERTY(QPen penPositive READ penPositive WRITE setPenPositive) + 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) - - /*! + */ + 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. - + \see setChartStyle - */ - enum ChartStyle { csOhlc ///< Open-High-Low-Close bar representation - ,csCandlestick ///< Candlestick representation - }; - Q_ENUMS(ChartStyle) - - explicit QCPFinancial(QCPAxis *keyAxis, QCPAxis *valueAxis); - virtual ~QCPFinancial() Q_DECL_OVERRIDE; - - // getters: - 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(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); - void setPenPositive(const QPen &pen); - void setPenNegative(const QPen &pen); - - // non-property methods: - 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); - - // 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=nullptr) 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 QCPFinancialDataContainer timeSeriesToOhlc(const QVector &time, const QVector &value, double timeBinSize, double timeBinOffset = 0); - + */ + enum ChartStyle { csOhlc ///< Open-High-Low-Close bar representation + , csCandlestick ///< Candlestick representation + }; + Q_ENUMS(ChartStyle) + + explicit QCPFinancial(QCPAxis *keyAxis, QCPAxis *valueAxis); + virtual ~QCPFinancial() Q_DECL_OVERRIDE; + + // getters: + 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(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); + void setPenPositive(const QPen &pen); + void setPenNegative(const QPen &pen); + + // non-property methods: + 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); + + // 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 = nullptr) 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 QCPFinancialDataContainer timeSeriesToOhlc(const QVector &time, const QVector &value, double timeBinSize, double timeBinOffset = 0); + protected: - // property members: - ChartStyle mChartStyle; - double mWidth; - WidthType mWidthType; - bool mTwoColored; - QBrush mBrushPositive, mBrushNegative; - QPen mPenPositive, mPenNegative; - - // reimplemented virtual methods: - 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 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; + // property members: + ChartStyle mChartStyle; + double mWidth; + WidthType mWidthType; + bool mTwoColored; + QBrush mBrushPositive, mBrushNegative; + QPen mPenPositive, mPenNegative; + + // reimplemented virtual methods: + 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 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) @@ -6260,11 +7009,11 @@ Q_DECLARE_METATYPE(QCPFinancial::ChartStyle) class QCP_LIB_DECL QCPErrorBarsData { public: - QCPErrorBarsData(); - explicit QCPErrorBarsData(double error); - QCPErrorBarsData(double errorMinus, double errorPlus); - - double errorMinus, errorPlus; + QCPErrorBarsData(); + explicit QCPErrorBarsData(double error); + QCPErrorBarsData(double errorMinus, double errorPlus); + + double errorMinus, errorPlus; }; Q_DECLARE_TYPEINFO(QCPErrorBarsData, Q_PRIMITIVE_TYPE); @@ -6288,92 +7037,102 @@ 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 + 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() Q_DECL_OVERRIDE; - // 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 Q_DECL_OVERRIDE; - virtual double dataMainKey(int index) const Q_DECL_OVERRIDE; - virtual double dataSortKey(int index) const Q_DECL_OVERRIDE; - virtual double dataMainValue(int index) const Q_DECL_OVERRIDE; - virtual QCPRange dataValueRange(int index) const Q_DECL_OVERRIDE; - virtual QPointF dataPixelPosition(int index) const Q_DECL_OVERRIDE; - virtual bool sortKeyIsMainKey() const Q_DECL_OVERRIDE; - virtual QCPDataSelection selectTestRect(const QRectF &rect, bool onlySelectable) const Q_DECL_OVERRIDE; - virtual int findBegin(double sortKey, bool expandedRange=true) const Q_DECL_OVERRIDE; - virtual int findEnd(double sortKey, bool expandedRange=true) const Q_DECL_OVERRIDE; - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE; - virtual QCPPlottableInterface1D *interface1D() Q_DECL_OVERRIDE { return this; } - + */ + 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() Q_DECL_OVERRIDE; + // 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 Q_DECL_OVERRIDE; + virtual double dataMainKey(int index) const Q_DECL_OVERRIDE; + virtual double dataSortKey(int index) const Q_DECL_OVERRIDE; + virtual double dataMainValue(int index) const Q_DECL_OVERRIDE; + virtual QCPRange dataValueRange(int index) const Q_DECL_OVERRIDE; + virtual QPointF dataPixelPosition(int index) const Q_DECL_OVERRIDE; + virtual bool sortKeyIsMainKey() const Q_DECL_OVERRIDE; + virtual QCPDataSelection selectTestRect(const QRectF &rect, bool onlySelectable) const Q_DECL_OVERRIDE; + virtual int findBegin(double sortKey, bool expandedRange = true) const Q_DECL_OVERRIDE; + virtual int findEnd(double sortKey, bool expandedRange = true) const Q_DECL_OVERRIDE; + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = nullptr) 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; + // 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' */ @@ -6384,39 +7143,42 @@ protected: class QCP_LIB_DECL QCPItemStraightLine : public QCPAbstractItem { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QPen pen READ pen WRITE setPen) - Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QPen pen READ pen WRITE setPen) + Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) + /// \endcond public: - explicit QCPItemStraightLine(QCustomPlot *parentPlot); - virtual ~QCPItemStraightLine() Q_DECL_OVERRIDE; - - // getters: - QPen pen() const { return mPen; } - QPen selectedPen() const { return mSelectedPen; } - - // setters; - void setPen(const QPen &pen); - void setSelectedPen(const QPen &pen); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE; - - QCPItemPosition * const point1; - QCPItemPosition * const point2; - + explicit QCPItemStraightLine(QCustomPlot *parentPlot); + virtual ~QCPItemStraightLine() Q_DECL_OVERRIDE; + + // getters: + QPen pen() const { + return mPen; + } + QPen selectedPen() const { + return mSelectedPen; + } + + // setters; + void setPen(const QPen &pen); + void setSelectedPen(const QPen &pen); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = nullptr) const Q_DECL_OVERRIDE; + + QCPItemPosition *const point1; + QCPItemPosition *const point2; + protected: - // property members: - QPen mPen, mSelectedPen; - - // reimplemented virtual methods: - virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; - - // non-virtual methods: - QLineF getRectClippedStraightLine(const QCPVector2D &base, const QCPVector2D &vec, const QRect &rect) const; - QPen mainPen() const; + // property members: + QPen mPen, mSelectedPen; + + // reimplemented virtual methods: + virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; + + // non-virtual methods: + QLineF getRectClippedStraightLine(const QCPVector2D &base, const QCPVector2D &vec, const QRect &rect) const; + QPen mainPen() const; }; /* end of 'src/items/item-straightline.h' */ @@ -6427,46 +7189,53 @@ protected: class QCP_LIB_DECL QCPItemLine : public QCPAbstractItem { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QPen pen READ pen WRITE setPen) - Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) - Q_PROPERTY(QCPLineEnding head READ head WRITE setHead) - Q_PROPERTY(QCPLineEnding tail READ tail WRITE setTail) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QPen pen READ pen WRITE setPen) + Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) + Q_PROPERTY(QCPLineEnding head READ head WRITE setHead) + Q_PROPERTY(QCPLineEnding tail READ tail WRITE setTail) + /// \endcond public: - explicit QCPItemLine(QCustomPlot *parentPlot); - virtual ~QCPItemLine() Q_DECL_OVERRIDE; - - // getters: - QPen pen() const { return mPen; } - QPen selectedPen() const { return mSelectedPen; } - QCPLineEnding head() const { return mHead; } - QCPLineEnding tail() const { return mTail; } - - // setters; - void setPen(const QPen &pen); - void setSelectedPen(const QPen &pen); - void setHead(const QCPLineEnding &head); - void setTail(const QCPLineEnding &tail); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE; - - QCPItemPosition * const start; - QCPItemPosition * const end; - + explicit QCPItemLine(QCustomPlot *parentPlot); + virtual ~QCPItemLine() Q_DECL_OVERRIDE; + + // getters: + QPen pen() const { + return mPen; + } + QPen selectedPen() const { + return mSelectedPen; + } + QCPLineEnding head() const { + return mHead; + } + QCPLineEnding tail() const { + return mTail; + } + + // setters; + void setPen(const QPen &pen); + void setSelectedPen(const QPen &pen); + void setHead(const QCPLineEnding &head); + void setTail(const QCPLineEnding &tail); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = nullptr) const Q_DECL_OVERRIDE; + + QCPItemPosition *const start; + QCPItemPosition *const end; + protected: - // property members: - QPen mPen, mSelectedPen; - QCPLineEnding mHead, mTail; - - // reimplemented virtual methods: - virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; - - // non-virtual methods: - QLineF getRectClippedLine(const QCPVector2D &start, const QCPVector2D &end, const QRect &rect) const; - QPen mainPen() const; + // property members: + QPen mPen, mSelectedPen; + QCPLineEnding mHead, mTail; + + // reimplemented virtual methods: + virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; + + // non-virtual methods: + QLineF getRectClippedLine(const QCPVector2D &start, const QCPVector2D &end, const QRect &rect) const; + QPen mainPen() const; }; /* end of 'src/items/item-line.h' */ @@ -6477,47 +7246,54 @@ protected: class QCP_LIB_DECL QCPItemCurve : public QCPAbstractItem { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QPen pen READ pen WRITE setPen) - Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) - Q_PROPERTY(QCPLineEnding head READ head WRITE setHead) - Q_PROPERTY(QCPLineEnding tail READ tail WRITE setTail) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QPen pen READ pen WRITE setPen) + Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) + Q_PROPERTY(QCPLineEnding head READ head WRITE setHead) + Q_PROPERTY(QCPLineEnding tail READ tail WRITE setTail) + /// \endcond public: - explicit QCPItemCurve(QCustomPlot *parentPlot); - virtual ~QCPItemCurve() Q_DECL_OVERRIDE; - - // getters: - QPen pen() const { return mPen; } - QPen selectedPen() const { return mSelectedPen; } - QCPLineEnding head() const { return mHead; } - QCPLineEnding tail() const { return mTail; } - - // setters; - void setPen(const QPen &pen); - void setSelectedPen(const QPen &pen); - void setHead(const QCPLineEnding &head); - void setTail(const QCPLineEnding &tail); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE; - - QCPItemPosition * const start; - QCPItemPosition * const startDir; - QCPItemPosition * const endDir; - QCPItemPosition * const end; - + explicit QCPItemCurve(QCustomPlot *parentPlot); + virtual ~QCPItemCurve() Q_DECL_OVERRIDE; + + // getters: + QPen pen() const { + return mPen; + } + QPen selectedPen() const { + return mSelectedPen; + } + QCPLineEnding head() const { + return mHead; + } + QCPLineEnding tail() const { + return mTail; + } + + // setters; + void setPen(const QPen &pen); + void setSelectedPen(const QPen &pen); + void setHead(const QCPLineEnding &head); + void setTail(const QCPLineEnding &tail); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = nullptr) const Q_DECL_OVERRIDE; + + QCPItemPosition *const start; + QCPItemPosition *const startDir; + QCPItemPosition *const endDir; + QCPItemPosition *const end; + protected: - // property members: - QPen mPen, mSelectedPen; - QCPLineEnding mHead, mTail; - - // reimplemented virtual methods: - virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; - - // non-virtual methods: - QPen mainPen() const; + // property members: + QPen mPen, mSelectedPen; + QCPLineEnding mHead, mTail; + + // reimplemented virtual methods: + virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; + + // non-virtual methods: + QPen mainPen() const; }; /* end of 'src/items/item-curve.h' */ @@ -6528,55 +7304,62 @@ protected: class QCP_LIB_DECL QCPItemRect : public QCPAbstractItem { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - 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) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES 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) + /// \endcond public: - explicit QCPItemRect(QCustomPlot *parentPlot); - virtual ~QCPItemRect() Q_DECL_OVERRIDE; - - // getters: - QPen pen() const { return mPen; } - QPen selectedPen() const { return mSelectedPen; } - QBrush brush() const { return mBrush; } - QBrush selectedBrush() const { return mSelectedBrush; } - - // setters; - void setPen(const QPen &pen); - void setSelectedPen(const QPen &pen); - void setBrush(const QBrush &brush); - void setSelectedBrush(const QBrush &brush); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE; - - QCPItemPosition * const topLeft; - QCPItemPosition * const bottomRight; - QCPItemAnchor * const top; - QCPItemAnchor * const topRight; - QCPItemAnchor * const right; - QCPItemAnchor * const bottom; - QCPItemAnchor * const bottomLeft; - QCPItemAnchor * const left; - + explicit QCPItemRect(QCustomPlot *parentPlot); + virtual ~QCPItemRect() Q_DECL_OVERRIDE; + + // getters: + QPen pen() const { + return mPen; + } + QPen selectedPen() const { + return mSelectedPen; + } + QBrush brush() const { + return mBrush; + } + QBrush selectedBrush() const { + return mSelectedBrush; + } + + // setters; + void setPen(const QPen &pen); + void setSelectedPen(const QPen &pen); + void setBrush(const QBrush &brush); + void setSelectedBrush(const QBrush &brush); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = nullptr) const Q_DECL_OVERRIDE; + + QCPItemPosition *const topLeft; + QCPItemPosition *const bottomRight; + QCPItemAnchor *const top; + QCPItemAnchor *const topRight; + QCPItemAnchor *const right; + QCPItemAnchor *const bottom; + QCPItemAnchor *const bottomLeft; + QCPItemAnchor *const left; + protected: - enum AnchorIndex {aiTop, aiTopRight, aiRight, aiBottom, aiBottomLeft, aiLeft}; - - // property members: - QPen mPen, mSelectedPen; - QBrush mBrush, mSelectedBrush; - - // reimplemented virtual methods: - 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; + enum AnchorIndex {aiTop, aiTopRight, aiRight, aiBottom, aiBottomLeft, aiLeft}; + + // property members: + QPen mPen, mSelectedPen; + QBrush mBrush, mSelectedBrush; + + // reimplemented virtual methods: + 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' */ @@ -6587,93 +7370,118 @@ protected: class QCP_LIB_DECL QCPItemText : public QCPAbstractItem { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QColor color READ color WRITE setColor) - Q_PROPERTY(QColor selectedColor READ selectedColor WRITE setSelectedColor) - 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(QFont font READ font WRITE setFont) - Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont) - Q_PROPERTY(QString text READ text WRITE setText) - Q_PROPERTY(Qt::Alignment positionAlignment READ positionAlignment WRITE setPositionAlignment) - Q_PROPERTY(Qt::Alignment textAlignment READ textAlignment WRITE setTextAlignment) - Q_PROPERTY(double rotation READ rotation WRITE setRotation) - Q_PROPERTY(QMargins padding READ padding WRITE setPadding) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QColor color READ color WRITE setColor) + Q_PROPERTY(QColor selectedColor READ selectedColor WRITE setSelectedColor) + 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(QFont font READ font WRITE setFont) + Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont) + Q_PROPERTY(QString text READ text WRITE setText) + Q_PROPERTY(Qt::Alignment positionAlignment READ positionAlignment WRITE setPositionAlignment) + Q_PROPERTY(Qt::Alignment textAlignment READ textAlignment WRITE setTextAlignment) + Q_PROPERTY(double rotation READ rotation WRITE setRotation) + Q_PROPERTY(QMargins padding READ padding WRITE setPadding) + /// \endcond public: - explicit QCPItemText(QCustomPlot *parentPlot); - virtual ~QCPItemText() Q_DECL_OVERRIDE; - - // getters: - QColor color() const { return mColor; } - QColor selectedColor() const { return mSelectedColor; } - QPen pen() const { return mPen; } - QPen selectedPen() const { return mSelectedPen; } - QBrush brush() const { return mBrush; } - QBrush selectedBrush() const { return mSelectedBrush; } - QFont font() const { return mFont; } - QFont selectedFont() const { return mSelectedFont; } - QString text() const { return mText; } - Qt::Alignment positionAlignment() const { return mPositionAlignment; } - Qt::Alignment textAlignment() const { return mTextAlignment; } - double rotation() const { return mRotation; } - QMargins padding() const { return mPadding; } - - // setters; - void setColor(const QColor &color); - void setSelectedColor(const QColor &color); - void setPen(const QPen &pen); - void setSelectedPen(const QPen &pen); - void setBrush(const QBrush &brush); - void setSelectedBrush(const QBrush &brush); - void setFont(const QFont &font); - void setSelectedFont(const QFont &font); - void setText(const QString &text); - void setPositionAlignment(Qt::Alignment alignment); - void setTextAlignment(Qt::Alignment alignment); - void setRotation(double degrees); - void setPadding(const QMargins &padding); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE; - - QCPItemPosition * const position; - QCPItemAnchor * const topLeft; - QCPItemAnchor * const top; - QCPItemAnchor * const topRight; - QCPItemAnchor * const right; - QCPItemAnchor * const bottomRight; - QCPItemAnchor * const bottom; - QCPItemAnchor * const bottomLeft; - QCPItemAnchor * const left; - + explicit QCPItemText(QCustomPlot *parentPlot); + virtual ~QCPItemText() Q_DECL_OVERRIDE; + + // getters: + QColor color() const { + return mColor; + } + QColor selectedColor() const { + return mSelectedColor; + } + QPen pen() const { + return mPen; + } + QPen selectedPen() const { + return mSelectedPen; + } + QBrush brush() const { + return mBrush; + } + QBrush selectedBrush() const { + return mSelectedBrush; + } + QFont font() const { + return mFont; + } + QFont selectedFont() const { + return mSelectedFont; + } + QString text() const { + return mText; + } + Qt::Alignment positionAlignment() const { + return mPositionAlignment; + } + Qt::Alignment textAlignment() const { + return mTextAlignment; + } + double rotation() const { + return mRotation; + } + QMargins padding() const { + return mPadding; + } + + // setters; + void setColor(const QColor &color); + void setSelectedColor(const QColor &color); + void setPen(const QPen &pen); + void setSelectedPen(const QPen &pen); + void setBrush(const QBrush &brush); + void setSelectedBrush(const QBrush &brush); + void setFont(const QFont &font); + void setSelectedFont(const QFont &font); + void setText(const QString &text); + void setPositionAlignment(Qt::Alignment alignment); + void setTextAlignment(Qt::Alignment alignment); + void setRotation(double degrees); + void setPadding(const QMargins &padding); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = nullptr) const Q_DECL_OVERRIDE; + + QCPItemPosition *const position; + QCPItemAnchor *const topLeft; + QCPItemAnchor *const top; + QCPItemAnchor *const topRight; + QCPItemAnchor *const right; + QCPItemAnchor *const bottomRight; + QCPItemAnchor *const bottom; + QCPItemAnchor *const bottomLeft; + QCPItemAnchor *const left; + protected: - enum AnchorIndex {aiTopLeft, aiTop, aiTopRight, aiRight, aiBottomRight, aiBottom, aiBottomLeft, aiLeft}; - - // property members: - QColor mColor, mSelectedColor; - QPen mPen, mSelectedPen; - QBrush mBrush, mSelectedBrush; - QFont mFont, mSelectedFont; - QString mText; - Qt::Alignment mPositionAlignment; - Qt::Alignment mTextAlignment; - double mRotation; - QMargins mPadding; - - // reimplemented virtual methods: - 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; - QFont mainFont() const; - QColor mainColor() const; - QPen mainPen() const; - QBrush mainBrush() const; + enum AnchorIndex {aiTopLeft, aiTop, aiTopRight, aiRight, aiBottomRight, aiBottom, aiBottomLeft, aiLeft}; + + // property members: + QColor mColor, mSelectedColor; + QPen mPen, mSelectedPen; + QBrush mBrush, mSelectedBrush; + QFont mFont, mSelectedFont; + QString mText; + Qt::Alignment mPositionAlignment; + Qt::Alignment mTextAlignment; + double mRotation; + QMargins mPadding; + + // reimplemented virtual methods: + 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; + QFont mainFont() const; + QColor mainColor() const; + QPen mainPen() const; + QBrush mainBrush() const; }; /* end of 'src/items/item-text.h' */ @@ -6684,58 +7492,65 @@ protected: class QCP_LIB_DECL QCPItemEllipse : public QCPAbstractItem { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - 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) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES 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) + /// \endcond public: - explicit QCPItemEllipse(QCustomPlot *parentPlot); - virtual ~QCPItemEllipse() Q_DECL_OVERRIDE; - - // getters: - QPen pen() const { return mPen; } - QPen selectedPen() const { return mSelectedPen; } - QBrush brush() const { return mBrush; } - QBrush selectedBrush() const { return mSelectedBrush; } - - // setters; - void setPen(const QPen &pen); - void setSelectedPen(const QPen &pen); - void setBrush(const QBrush &brush); - void setSelectedBrush(const QBrush &brush); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE; - - QCPItemPosition * const topLeft; - QCPItemPosition * const bottomRight; - QCPItemAnchor * const topLeftRim; - QCPItemAnchor * const top; - QCPItemAnchor * const topRightRim; - QCPItemAnchor * const right; - QCPItemAnchor * const bottomRightRim; - QCPItemAnchor * const bottom; - QCPItemAnchor * const bottomLeftRim; - QCPItemAnchor * const left; - QCPItemAnchor * const center; - + explicit QCPItemEllipse(QCustomPlot *parentPlot); + virtual ~QCPItemEllipse() Q_DECL_OVERRIDE; + + // getters: + QPen pen() const { + return mPen; + } + QPen selectedPen() const { + return mSelectedPen; + } + QBrush brush() const { + return mBrush; + } + QBrush selectedBrush() const { + return mSelectedBrush; + } + + // setters; + void setPen(const QPen &pen); + void setSelectedPen(const QPen &pen); + void setBrush(const QBrush &brush); + void setSelectedBrush(const QBrush &brush); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = nullptr) const Q_DECL_OVERRIDE; + + QCPItemPosition *const topLeft; + QCPItemPosition *const bottomRight; + QCPItemAnchor *const topLeftRim; + QCPItemAnchor *const top; + QCPItemAnchor *const topRightRim; + QCPItemAnchor *const right; + QCPItemAnchor *const bottomRightRim; + QCPItemAnchor *const bottom; + QCPItemAnchor *const bottomLeftRim; + QCPItemAnchor *const left; + QCPItemAnchor *const center; + protected: - enum AnchorIndex {aiTopLeftRim, aiTop, aiTopRightRim, aiRight, aiBottomRightRim, aiBottom, aiBottomLeftRim, aiLeft, aiCenter}; - - // property members: - QPen mPen, mSelectedPen; - QBrush mBrush, mSelectedBrush; - - // reimplemented virtual methods: - 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; + enum AnchorIndex {aiTopLeftRim, aiTop, aiTopRightRim, aiRight, aiBottomRightRim, aiBottom, aiBottomLeftRim, aiLeft, aiCenter}; + + // property members: + QPen mPen, mSelectedPen; + QBrush mBrush, mSelectedBrush; + + // reimplemented virtual methods: + 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' */ @@ -6746,65 +7561,76 @@ protected: class QCP_LIB_DECL QCPItemPixmap : public QCPAbstractItem { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QPixmap pixmap READ pixmap WRITE setPixmap) - Q_PROPERTY(bool scaled READ scaled WRITE setScaled) - Q_PROPERTY(Qt::AspectRatioMode aspectRatioMode READ aspectRatioMode) - Q_PROPERTY(Qt::TransformationMode transformationMode READ transformationMode) - Q_PROPERTY(QPen pen READ pen WRITE setPen) - Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QPixmap pixmap READ pixmap WRITE setPixmap) + Q_PROPERTY(bool scaled READ scaled WRITE setScaled) + Q_PROPERTY(Qt::AspectRatioMode aspectRatioMode READ aspectRatioMode) + Q_PROPERTY(Qt::TransformationMode transformationMode READ transformationMode) + Q_PROPERTY(QPen pen READ pen WRITE setPen) + Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) + /// \endcond public: - explicit QCPItemPixmap(QCustomPlot *parentPlot); - virtual ~QCPItemPixmap() Q_DECL_OVERRIDE; - - // getters: - QPixmap pixmap() const { return mPixmap; } - bool scaled() const { return mScaled; } - Qt::AspectRatioMode aspectRatioMode() const { return mAspectRatioMode; } - Qt::TransformationMode transformationMode() const { return mTransformationMode; } - QPen pen() const { return mPen; } - QPen selectedPen() const { return mSelectedPen; } - - // setters; - void setPixmap(const QPixmap &pixmap); - void setScaled(bool scaled, Qt::AspectRatioMode aspectRatioMode=Qt::KeepAspectRatio, Qt::TransformationMode transformationMode=Qt::SmoothTransformation); - void setPen(const QPen &pen); - void setSelectedPen(const QPen &pen); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE; - - QCPItemPosition * const topLeft; - QCPItemPosition * const bottomRight; - QCPItemAnchor * const top; - QCPItemAnchor * const topRight; - QCPItemAnchor * const right; - QCPItemAnchor * const bottom; - QCPItemAnchor * const bottomLeft; - QCPItemAnchor * const left; - + explicit QCPItemPixmap(QCustomPlot *parentPlot); + virtual ~QCPItemPixmap() Q_DECL_OVERRIDE; + + // getters: + QPixmap pixmap() const { + return mPixmap; + } + bool scaled() const { + return mScaled; + } + Qt::AspectRatioMode aspectRatioMode() const { + return mAspectRatioMode; + } + Qt::TransformationMode transformationMode() const { + return mTransformationMode; + } + QPen pen() const { + return mPen; + } + QPen selectedPen() const { + return mSelectedPen; + } + + // setters; + void setPixmap(const QPixmap &pixmap); + void setScaled(bool scaled, Qt::AspectRatioMode aspectRatioMode = Qt::KeepAspectRatio, Qt::TransformationMode transformationMode = Qt::SmoothTransformation); + void setPen(const QPen &pen); + void setSelectedPen(const QPen &pen); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = nullptr) const Q_DECL_OVERRIDE; + + QCPItemPosition *const topLeft; + QCPItemPosition *const bottomRight; + QCPItemAnchor *const top; + QCPItemAnchor *const topRight; + QCPItemAnchor *const right; + QCPItemAnchor *const bottom; + QCPItemAnchor *const bottomLeft; + QCPItemAnchor *const left; + protected: - enum AnchorIndex {aiTop, aiTopRight, aiRight, aiBottom, aiBottomLeft, aiLeft}; - - // property members: - 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) 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); - QRect getFinalRect(bool *flippedHorz=nullptr, bool *flippedVert=nullptr) const; - QPen mainPen() const; + enum AnchorIndex {aiTop, aiTopRight, aiRight, aiBottom, aiBottomLeft, aiLeft}; + + // property members: + 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) 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); + QRect getFinalRect(bool *flippedHorz = nullptr, bool *flippedVert = nullptr) const; + QPen mainPen() const; }; /* end of 'src/items/item-pixmap.h' */ @@ -6815,81 +7641,99 @@ protected: class QCP_LIB_DECL QCPItemTracer : public QCPAbstractItem { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - 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(double size READ size WRITE setSize) - Q_PROPERTY(TracerStyle style READ style WRITE setStyle) - Q_PROPERTY(QCPGraph* graph READ graph WRITE setGraph) - Q_PROPERTY(double graphKey READ graphKey WRITE setGraphKey) - Q_PROPERTY(bool interpolating READ interpolating WRITE setInterpolating) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + 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(double size READ size WRITE setSize) + Q_PROPERTY(TracerStyle style READ style WRITE setStyle) + Q_PROPERTY(QCPGraph *graph READ graph WRITE setGraph) + Q_PROPERTY(double graphKey READ graphKey WRITE setGraphKey) + Q_PROPERTY(bool interpolating READ interpolating WRITE setInterpolating) + /// \endcond public: - /*! + /*! The different visual appearances a tracer item can have. Some styles size may be controlled with \ref setSize. - + \see setStyle - */ - enum TracerStyle { tsNone ///< The tracer is not visible - ,tsPlus ///< A plus shaped crosshair with limited size - ,tsCrosshair ///< A plus shaped crosshair which spans the complete axis rect - ,tsCircle ///< A circle - ,tsSquare ///< A square - }; - Q_ENUMS(TracerStyle) + */ + enum TracerStyle { tsNone ///< The tracer is not visible + , tsPlus ///< A plus shaped crosshair with limited size + , tsCrosshair ///< A plus shaped crosshair which spans the complete axis rect + , tsCircle ///< A circle + , tsSquare ///< A square + }; + Q_ENUMS(TracerStyle) - explicit QCPItemTracer(QCustomPlot *parentPlot); - virtual ~QCPItemTracer() Q_DECL_OVERRIDE; + explicit QCPItemTracer(QCustomPlot *parentPlot); + virtual ~QCPItemTracer() Q_DECL_OVERRIDE; - // getters: - QPen pen() const { return mPen; } - QPen selectedPen() const { return mSelectedPen; } - QBrush brush() const { return mBrush; } - QBrush selectedBrush() const { return mSelectedBrush; } - double size() const { return mSize; } - TracerStyle style() const { return mStyle; } - QCPGraph *graph() const { return mGraph; } - double graphKey() const { return mGraphKey; } - bool interpolating() const { return mInterpolating; } + // getters: + QPen pen() const { + return mPen; + } + QPen selectedPen() const { + return mSelectedPen; + } + QBrush brush() const { + return mBrush; + } + QBrush selectedBrush() const { + return mSelectedBrush; + } + double size() const { + return mSize; + } + TracerStyle style() const { + return mStyle; + } + QCPGraph *graph() const { + return mGraph; + } + double graphKey() const { + return mGraphKey; + } + bool interpolating() const { + return mInterpolating; + } - // setters; - void setPen(const QPen &pen); - void setSelectedPen(const QPen &pen); - void setBrush(const QBrush &brush); - void setSelectedBrush(const QBrush &brush); - void setSize(double size); - void setStyle(TracerStyle style); - void setGraph(QCPGraph *graph); - void setGraphKey(double key); - void setInterpolating(bool enabled); + // setters; + void setPen(const QPen &pen); + void setSelectedPen(const QPen &pen); + void setBrush(const QBrush &brush); + void setSelectedBrush(const QBrush &brush); + void setSize(double size); + void setStyle(TracerStyle style); + void setGraph(QCPGraph *graph); + void setGraphKey(double key); + void setInterpolating(bool enabled); - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE; - - // non-virtual methods: - void updatePosition(); + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = nullptr) const Q_DECL_OVERRIDE; - QCPItemPosition * const position; + // non-virtual methods: + void updatePosition(); + + QCPItemPosition *const position; protected: - // property members: - QPen mPen, mSelectedPen; - QBrush mBrush, mSelectedBrush; - double mSize; - TracerStyle mStyle; - QCPGraph *mGraph; - double mGraphKey; - bool mInterpolating; + // property members: + QPen mPen, mSelectedPen; + QBrush mBrush, mSelectedBrush; + double mSize; + TracerStyle mStyle; + QCPGraph *mGraph; + double mGraphKey; + bool mInterpolating; - // reimplemented virtual methods: - virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; + // reimplemented virtual methods: + virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; - // non-virtual methods: - QPen mainPen() const; - QBrush mainBrush() const; + // non-virtual methods: + QPen mainPen() const; + QBrush mainBrush() const; }; Q_DECLARE_METATYPE(QCPItemTracer::TracerStyle) @@ -6901,62 +7745,70 @@ Q_DECLARE_METATYPE(QCPItemTracer::TracerStyle) class QCP_LIB_DECL QCPItemBracket : public QCPAbstractItem { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QPen pen READ pen WRITE setPen) - Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) - Q_PROPERTY(double length READ length WRITE setLength) - Q_PROPERTY(BracketStyle style READ style WRITE setStyle) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(QPen pen READ pen WRITE setPen) + Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) + Q_PROPERTY(double length READ length WRITE setLength) + 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) - explicit QCPItemBracket(QCustomPlot *parentPlot); - virtual ~QCPItemBracket() Q_DECL_OVERRIDE; - - // getters: - QPen pen() const { return mPen; } - QPen selectedPen() const { return mSelectedPen; } - double length() const { return mLength; } - BracketStyle style() const { return mStyle; } - - // setters; - void setPen(const QPen &pen); - void setSelectedPen(const QPen &pen); - void setLength(double length); - void setStyle(BracketStyle style); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE; - - QCPItemPosition * const left; - QCPItemPosition * const right; - QCPItemAnchor * const center; - + \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) + + explicit QCPItemBracket(QCustomPlot *parentPlot); + virtual ~QCPItemBracket() Q_DECL_OVERRIDE; + + // getters: + QPen pen() const { + return mPen; + } + QPen selectedPen() const { + return mSelectedPen; + } + double length() const { + return mLength; + } + BracketStyle style() const { + return mStyle; + } + + // setters; + void setPen(const QPen &pen); + void setSelectedPen(const QPen &pen); + void setLength(double length); + void setStyle(BracketStyle style); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = nullptr) const Q_DECL_OVERRIDE; + + QCPItemPosition *const left; + QCPItemPosition *const right; + QCPItemAnchor *const center; + protected: - // property members: - enum AnchorIndex {aiCenter}; - QPen mPen, mSelectedPen; - double mLength; - BracketStyle mStyle; - - // reimplemented virtual methods: - virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; - virtual QPointF anchorPixelPosition(int anchorId) const Q_DECL_OVERRIDE; - - // non-virtual methods: - QPen mainPen() const; + // property members: + enum AnchorIndex {aiCenter}; + QPen mPen, mSelectedPen; + double mLength; + BracketStyle mStyle; + + // reimplemented virtual methods: + 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) @@ -6969,241 +7821,313 @@ Q_DECLARE_METATYPE(QCPItemBracket::BracketStyle) class QCP_LIB_DECL QCPPolarAxisRadial : public QCPLayerable { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + + /// \endcond public: - /*! + /*! Defines the reference of the angle at which a radial axis is tilted (\ref setAngle). - */ - enum AngleReference { arAbsolute ///< The axis tilt is given in absolute degrees. The zero is to the right and positive angles are measured counter-clockwise. - ,arAngularAxis ///< The axis tilt is measured in the angular coordinate system given by the parent angular axis. - }; - Q_ENUMS(AngleReference) - /*! + */ + enum AngleReference { arAbsolute ///< The axis tilt is given in absolute degrees. The zero is to the right and positive angles are measured counter-clockwise. + , arAngularAxis ///< The axis tilt is measured in the angular coordinate system given by the parent angular axis. + }; + Q_ENUMS(AngleReference) + /*! Defines the scale of an axis. \see setScaleType - */ - enum ScaleType { stLinear ///< Linear scaling - ,stLogarithmic ///< Logarithmic scaling with correspondingly transformed axis coordinates (possibly also \ref setTicker to a \ref QCPAxisTickerLog instance). - }; - Q_ENUMS(ScaleType) - /*! + */ + enum ScaleType { stLinear ///< Linear scaling + , stLogarithmic ///< Logarithmic scaling with correspondingly transformed axis coordinates (possibly also \ref setTicker to a \ref QCPAxisTickerLog instance). + }; + Q_ENUMS(ScaleType) + /*! Defines the selectable parts of an axis. \see setSelectableParts, setSelectedParts - */ - enum SelectablePart { spNone = 0 ///< None of the selectable parts - ,spAxis = 0x001 ///< The axis backbone and tick marks - ,spTickLabels = 0x002 ///< Tick labels (numbers) of this axis (as a whole, not individually) - ,spAxisLabel = 0x004 ///< The axis label - }; - Q_ENUMS(SelectablePart) - Q_FLAGS(SelectableParts) - Q_DECLARE_FLAGS(SelectableParts, SelectablePart) - - enum LabelMode { lmUpright ///< - ,lmRotated ///< - }; - Q_ENUMS(LabelMode) - - explicit QCPPolarAxisRadial(QCPPolarAxisAngular *parent); - virtual ~QCPPolarAxisRadial(); - - // getters: - bool rangeDrag() const { return mRangeDrag; } - bool rangeZoom() const { return mRangeZoom; } - double rangeZoomFactor() const { return mRangeZoomFactor; } - - QCPPolarAxisAngular *angularAxis() const { return mAngularAxis; } - ScaleType scaleType() const { return mScaleType; } - const QCPRange range() const { return mRange; } - bool rangeReversed() const { return mRangeReversed; } - double angle() const { return mAngle; } - AngleReference angleReference() const { return mAngleReference; } - QSharedPointer ticker() const { return mTicker; } - bool ticks() const { return mTicks; } - bool tickLabels() const { return mTickLabels; } - int tickLabelPadding() const { return mLabelPainter.padding(); } - QFont tickLabelFont() const { return mTickLabelFont; } - QColor tickLabelColor() const { return mTickLabelColor; } - double tickLabelRotation() const { return mLabelPainter.rotation(); } - LabelMode tickLabelMode() const; - QString numberFormat() const; - int numberPrecision() const { return mNumberPrecision; } - QVector tickVector() const { return mTickVector; } - QVector subTickVector() const { return mSubTickVector; } - QVector tickVectorLabels() const { return mTickVectorLabels; } - int tickLengthIn() const; - int tickLengthOut() const; - bool subTicks() const { return mSubTicks; } - int subTickLengthIn() const; - int subTickLengthOut() const; - QPen basePen() const { return mBasePen; } - QPen tickPen() const { return mTickPen; } - QPen subTickPen() const { return mSubTickPen; } - QFont labelFont() const { return mLabelFont; } - QColor labelColor() const { return mLabelColor; } - QString label() const { return mLabel; } - int labelPadding() const; - SelectableParts selectedParts() const { return mSelectedParts; } - SelectableParts selectableParts() const { return mSelectableParts; } - QFont selectedTickLabelFont() const { return mSelectedTickLabelFont; } - QFont selectedLabelFont() const { return mSelectedLabelFont; } - QColor selectedTickLabelColor() const { return mSelectedTickLabelColor; } - QColor selectedLabelColor() const { return mSelectedLabelColor; } - QPen selectedBasePen() const { return mSelectedBasePen; } - QPen selectedTickPen() const { return mSelectedTickPen; } - QPen selectedSubTickPen() const { return mSelectedSubTickPen; } - - // setters: - void setRangeDrag(bool enabled); - void setRangeZoom(bool enabled); - void setRangeZoomFactor(double factor); - - Q_SLOT void setScaleType(QCPPolarAxisRadial::ScaleType type); - 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 setAngle(double degrees); - void setAngleReference(AngleReference reference); - void setTicker(QSharedPointer ticker); - void setTicks(bool show); - void setTickLabels(bool show); - void setTickLabelPadding(int padding); - void setTickLabelFont(const QFont &font); - void setTickLabelColor(const QColor &color); - void setTickLabelRotation(double degrees); - void setTickLabelMode(LabelMode mode); - void setNumberFormat(const QString &formatCode); - void setNumberPrecision(int precision); - void setTickLength(int inside, int outside=0); - void setTickLengthIn(int inside); - void setTickLengthOut(int outside); - void setSubTicks(bool show); - void setSubTickLength(int inside, int outside=0); - void setSubTickLengthIn(int inside); - void setSubTickLengthOut(int outside); - void setBasePen(const QPen &pen); - void setTickPen(const QPen &pen); - void setSubTickPen(const QPen &pen); - void setLabelFont(const QFont &font); - void setLabelColor(const QColor &color); - void setLabel(const QString &str); - void setLabelPadding(int padding); - void setSelectedTickLabelFont(const QFont &font); - void setSelectedLabelFont(const QFont &font); - void setSelectedTickLabelColor(const QColor &color); - void setSelectedLabelColor(const QColor &color); - void setSelectedBasePen(const QPen &pen); - void setSelectedTickPen(const QPen &pen); - void setSelectedSubTickPen(const QPen &pen); - Q_SLOT void setSelectableParts(const QCPPolarAxisRadial::SelectableParts &selectableParts); - Q_SLOT void setSelectedParts(const QCPPolarAxisRadial::SelectableParts &selectedParts); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const Q_DECL_OVERRIDE; - - // non-property methods: - void moveRange(double diff); - void scaleRange(double factor); - void scaleRange(double factor, double center); - void rescale(bool onlyVisiblePlottables=false); - void pixelToCoord(QPointF pixelPos, double &angleCoord, double &radiusCoord) const; - QPointF coordToPixel(double angleCoord, double radiusCoord) const; - double coordToRadius(double coord) const; - double radiusToCoord(double radius) const; - SelectablePart getPartAt(const QPointF &pos) const; - + */ + enum SelectablePart { spNone = 0 ///< None of the selectable parts + , spAxis = 0x001 ///< The axis backbone and tick marks + , spTickLabels = 0x002 ///< Tick labels (numbers) of this axis (as a whole, not individually) + , spAxisLabel = 0x004 ///< The axis label + }; + Q_ENUMS(SelectablePart) + Q_FLAGS(SelectableParts) + Q_DECLARE_FLAGS(SelectableParts, SelectablePart) + + enum LabelMode { lmUpright ///< + , lmRotated ///< + }; + Q_ENUMS(LabelMode) + + explicit QCPPolarAxisRadial(QCPPolarAxisAngular *parent); + virtual ~QCPPolarAxisRadial(); + + // getters: + bool rangeDrag() const { + return mRangeDrag; + } + bool rangeZoom() const { + return mRangeZoom; + } + double rangeZoomFactor() const { + return mRangeZoomFactor; + } + + QCPPolarAxisAngular *angularAxis() const { + return mAngularAxis; + } + ScaleType scaleType() const { + return mScaleType; + } + const QCPRange range() const { + return mRange; + } + bool rangeReversed() const { + return mRangeReversed; + } + double angle() const { + return mAngle; + } + AngleReference angleReference() const { + return mAngleReference; + } + QSharedPointer ticker() const { + return mTicker; + } + bool ticks() const { + return mTicks; + } + bool tickLabels() const { + return mTickLabels; + } + int tickLabelPadding() const { + return mLabelPainter.padding(); + } + QFont tickLabelFont() const { + return mTickLabelFont; + } + QColor tickLabelColor() const { + return mTickLabelColor; + } + double tickLabelRotation() const { + return mLabelPainter.rotation(); + } + LabelMode tickLabelMode() const; + QString numberFormat() const; + int numberPrecision() const { + return mNumberPrecision; + } + QVector tickVector() const { + return mTickVector; + } + QVector subTickVector() const { + return mSubTickVector; + } + QVector tickVectorLabels() const { + return mTickVectorLabels; + } + int tickLengthIn() const; + int tickLengthOut() const; + bool subTicks() const { + return mSubTicks; + } + int subTickLengthIn() const; + int subTickLengthOut() const; + QPen basePen() const { + return mBasePen; + } + QPen tickPen() const { + return mTickPen; + } + QPen subTickPen() const { + return mSubTickPen; + } + QFont labelFont() const { + return mLabelFont; + } + QColor labelColor() const { + return mLabelColor; + } + QString label() const { + return mLabel; + } + int labelPadding() const; + SelectableParts selectedParts() const { + return mSelectedParts; + } + SelectableParts selectableParts() const { + return mSelectableParts; + } + QFont selectedTickLabelFont() const { + return mSelectedTickLabelFont; + } + QFont selectedLabelFont() const { + return mSelectedLabelFont; + } + QColor selectedTickLabelColor() const { + return mSelectedTickLabelColor; + } + QColor selectedLabelColor() const { + return mSelectedLabelColor; + } + QPen selectedBasePen() const { + return mSelectedBasePen; + } + QPen selectedTickPen() const { + return mSelectedTickPen; + } + QPen selectedSubTickPen() const { + return mSelectedSubTickPen; + } + + // setters: + void setRangeDrag(bool enabled); + void setRangeZoom(bool enabled); + void setRangeZoomFactor(double factor); + + Q_SLOT void setScaleType(QCPPolarAxisRadial::ScaleType type); + 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 setAngle(double degrees); + void setAngleReference(AngleReference reference); + void setTicker(QSharedPointer ticker); + void setTicks(bool show); + void setTickLabels(bool show); + void setTickLabelPadding(int padding); + void setTickLabelFont(const QFont &font); + void setTickLabelColor(const QColor &color); + void setTickLabelRotation(double degrees); + void setTickLabelMode(LabelMode mode); + void setNumberFormat(const QString &formatCode); + void setNumberPrecision(int precision); + void setTickLength(int inside, int outside = 0); + void setTickLengthIn(int inside); + void setTickLengthOut(int outside); + void setSubTicks(bool show); + void setSubTickLength(int inside, int outside = 0); + void setSubTickLengthIn(int inside); + void setSubTickLengthOut(int outside); + void setBasePen(const QPen &pen); + void setTickPen(const QPen &pen); + void setSubTickPen(const QPen &pen); + void setLabelFont(const QFont &font); + void setLabelColor(const QColor &color); + void setLabel(const QString &str); + void setLabelPadding(int padding); + void setSelectedTickLabelFont(const QFont &font); + void setSelectedLabelFont(const QFont &font); + void setSelectedTickLabelColor(const QColor &color); + void setSelectedLabelColor(const QColor &color); + void setSelectedBasePen(const QPen &pen); + void setSelectedTickPen(const QPen &pen); + void setSelectedSubTickPen(const QPen &pen); + Q_SLOT void setSelectableParts(const QCPPolarAxisRadial::SelectableParts &selectableParts); + Q_SLOT void setSelectedParts(const QCPPolarAxisRadial::SelectableParts &selectedParts); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = 0) const Q_DECL_OVERRIDE; + + // non-property methods: + void moveRange(double diff); + void scaleRange(double factor); + void scaleRange(double factor, double center); + void rescale(bool onlyVisiblePlottables = false); + void pixelToCoord(QPointF pixelPos, double &angleCoord, double &radiusCoord) const; + QPointF coordToPixel(double angleCoord, double radiusCoord) const; + double coordToRadius(double coord) const; + double radiusToCoord(double radius) const; + SelectablePart getPartAt(const QPointF &pos) const; + signals: - void rangeChanged(const QCPRange &newRange); - void rangeChanged(const QCPRange &newRange, const QCPRange &oldRange); - void scaleTypeChanged(QCPPolarAxisRadial::ScaleType scaleType); - void selectionChanged(const QCPPolarAxisRadial::SelectableParts &parts); - void selectableChanged(const QCPPolarAxisRadial::SelectableParts &parts); + void rangeChanged(const QCPRange &newRange); + void rangeChanged(const QCPRange &newRange, const QCPRange &oldRange); + void scaleTypeChanged(QCPPolarAxisRadial::ScaleType scaleType); + void selectionChanged(const QCPPolarAxisRadial::SelectableParts &parts); + void selectableChanged(const QCPPolarAxisRadial::SelectableParts &parts); protected: - // property members: - bool mRangeDrag; - bool mRangeZoom; - double mRangeZoomFactor; - - // axis base: - QCPPolarAxisAngular *mAngularAxis; - double mAngle; - AngleReference mAngleReference; - SelectableParts mSelectableParts, mSelectedParts; - QPen mBasePen, mSelectedBasePen; - // axis label: - int mLabelPadding; - QString mLabel; - QFont mLabelFont, mSelectedLabelFont; - QColor mLabelColor, mSelectedLabelColor; - // tick labels: - //int mTickLabelPadding; in label painter - bool mTickLabels; - //double mTickLabelRotation; in label painter - QFont mTickLabelFont, mSelectedTickLabelFont; - QColor mTickLabelColor, mSelectedTickLabelColor; - int mNumberPrecision; - QLatin1Char mNumberFormatChar; - bool mNumberBeautifulPowers; - bool mNumberMultiplyCross; - // ticks and subticks: - bool mTicks; - bool mSubTicks; - int mTickLengthIn, mTickLengthOut, mSubTickLengthIn, mSubTickLengthOut; - QPen mTickPen, mSelectedTickPen; - QPen mSubTickPen, mSelectedSubTickPen; - // scale and range: - QCPRange mRange; - bool mRangeReversed; - ScaleType mScaleType; - - // non-property members: - QPointF mCenter; - double mRadius; - QSharedPointer mTicker; - QVector mTickVector; - QVector mTickVectorLabels; - QVector mSubTickVector; - bool mDragging; - QCPRange mDragStartRange; - QCP::AntialiasedElements mAADragBackup, mNotAADragBackup; - QCPLabelPainterPrivate mLabelPainter; - - // reimplemented virtual methods: - 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) Q_DECL_OVERRIDE; - virtual void deselectEvent(bool *selectionStateChanged) Q_DECL_OVERRIDE; - // mouse events: - 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-virtual methods: - void updateGeometry(const QPointF ¢er, double radius); - void setupTickVectors(); - QPen getBasePen() const; - QPen getTickPen() const; - QPen getSubTickPen() const; - QFont getTickLabelFont() const; - QFont getLabelFont() const; - QColor getTickLabelColor() const; - QColor getLabelColor() const; - + // property members: + bool mRangeDrag; + bool mRangeZoom; + double mRangeZoomFactor; + + // axis base: + QCPPolarAxisAngular *mAngularAxis; + double mAngle; + AngleReference mAngleReference; + SelectableParts mSelectableParts, mSelectedParts; + QPen mBasePen, mSelectedBasePen; + // axis label: + int mLabelPadding; + QString mLabel; + QFont mLabelFont, mSelectedLabelFont; + QColor mLabelColor, mSelectedLabelColor; + // tick labels: + //int mTickLabelPadding; in label painter + bool mTickLabels; + //double mTickLabelRotation; in label painter + QFont mTickLabelFont, mSelectedTickLabelFont; + QColor mTickLabelColor, mSelectedTickLabelColor; + int mNumberPrecision; + QLatin1Char mNumberFormatChar; + bool mNumberBeautifulPowers; + bool mNumberMultiplyCross; + // ticks and subticks: + bool mTicks; + bool mSubTicks; + int mTickLengthIn, mTickLengthOut, mSubTickLengthIn, mSubTickLengthOut; + QPen mTickPen, mSelectedTickPen; + QPen mSubTickPen, mSelectedSubTickPen; + // scale and range: + QCPRange mRange; + bool mRangeReversed; + ScaleType mScaleType; + + // non-property members: + QPointF mCenter; + double mRadius; + QSharedPointer mTicker; + QVector mTickVector; + QVector mTickVectorLabels; + QVector mSubTickVector; + bool mDragging; + QCPRange mDragStartRange; + QCP::AntialiasedElements mAADragBackup, mNotAADragBackup; + QCPLabelPainterPrivate mLabelPainter; + + // reimplemented virtual methods: + 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) Q_DECL_OVERRIDE; + virtual void deselectEvent(bool *selectionStateChanged) Q_DECL_OVERRIDE; + // mouse events: + 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-virtual methods: + void updateGeometry(const QPointF ¢er, double radius); + void setupTickVectors(); + QPen getBasePen() const; + QPen getTickPen() const; + QPen getSubTickPen() const; + QFont getTickLabelFont() const; + QFont getLabelFont() const; + QColor getTickLabelColor() const; + QColor getLabelColor() const; + private: - Q_DISABLE_COPY(QCPPolarAxisRadial) - - friend class QCustomPlot; - friend class QCPPolarAxisAngular; + Q_DISABLE_COPY(QCPPolarAxisRadial) + + friend class QCustomPlot; + friend class QCPPolarAxisAngular; }; Q_DECLARE_OPERATORS_FOR_FLAGS(QCPPolarAxisRadial::SelectableParts) Q_DECLARE_METATYPE(QCPPolarAxisRadial::AngleReference) @@ -7220,267 +8144,383 @@ Q_DECLARE_METATYPE(QCPPolarAxisRadial::SelectablePart) class QCP_LIB_DECL QCPPolarAxisAngular : public QCPLayoutElement { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + + /// \endcond public: - /*! + /*! Defines the selectable parts of an axis. \see setSelectableParts, setSelectedParts - */ - enum SelectablePart { spNone = 0 ///< None of the selectable parts - ,spAxis = 0x001 ///< The axis backbone and tick marks - ,spTickLabels = 0x002 ///< Tick labels (numbers) of this axis (as a whole, not individually) - ,spAxisLabel = 0x004 ///< The axis label - }; - Q_ENUMS(SelectablePart) - Q_FLAGS(SelectableParts) - Q_DECLARE_FLAGS(SelectableParts, SelectablePart) - - /*! + */ + enum SelectablePart { spNone = 0 ///< None of the selectable parts + , spAxis = 0x001 ///< The axis backbone and tick marks + , spTickLabels = 0x002 ///< Tick labels (numbers) of this axis (as a whole, not individually) + , spAxisLabel = 0x004 ///< The axis label + }; + Q_ENUMS(SelectablePart) + Q_FLAGS(SelectableParts) + Q_DECLARE_FLAGS(SelectableParts, SelectablePart) + + /*! TODO - */ - enum LabelMode { lmUpright ///< - ,lmRotated ///< - }; - Q_ENUMS(LabelMode) - - explicit QCPPolarAxisAngular(QCustomPlot *parentPlot); - virtual ~QCPPolarAxisAngular(); - - // getters: - QPixmap background() const { return mBackgroundPixmap; } - QBrush backgroundBrush() const { return mBackgroundBrush; } - bool backgroundScaled() const { return mBackgroundScaled; } - Qt::AspectRatioMode backgroundScaledMode() const { return mBackgroundScaledMode; } - bool rangeDrag() const { return mRangeDrag; } - bool rangeZoom() const { return mRangeZoom; } - double rangeZoomFactor() const { return mRangeZoomFactor; } - - const QCPRange range() const { return mRange; } - bool rangeReversed() const { return mRangeReversed; } - double angle() const { return mAngle; } - QSharedPointer ticker() const { return mTicker; } - bool ticks() const { return mTicks; } - bool tickLabels() const { return mTickLabels; } - int tickLabelPadding() const { return mLabelPainter.padding(); } - QFont tickLabelFont() const { return mTickLabelFont; } - QColor tickLabelColor() const { return mTickLabelColor; } - double tickLabelRotation() const { return mLabelPainter.rotation(); } - LabelMode tickLabelMode() const; - QString numberFormat() const; - int numberPrecision() const { return mNumberPrecision; } - QVector tickVector() const { return mTickVector; } - QVector tickVectorLabels() const { return mTickVectorLabels; } - int tickLengthIn() const { return mTickLengthIn; } - int tickLengthOut() const { return mTickLengthOut; } - bool subTicks() const { return mSubTicks; } - int subTickLengthIn() const { return mSubTickLengthIn; } - int subTickLengthOut() const { return mSubTickLengthOut; } - QPen basePen() const { return mBasePen; } - QPen tickPen() const { return mTickPen; } - QPen subTickPen() const { return mSubTickPen; } - QFont labelFont() const { return mLabelFont; } - QColor labelColor() const { return mLabelColor; } - QString label() const { return mLabel; } - int labelPadding() const { return mLabelPadding; } - SelectableParts selectedParts() const { return mSelectedParts; } - SelectableParts selectableParts() const { return mSelectableParts; } - QFont selectedTickLabelFont() const { return mSelectedTickLabelFont; } - QFont selectedLabelFont() const { return mSelectedLabelFont; } - QColor selectedTickLabelColor() const { return mSelectedTickLabelColor; } - QColor selectedLabelColor() const { return mSelectedLabelColor; } - QPen selectedBasePen() const { return mSelectedBasePen; } - QPen selectedTickPen() const { return mSelectedTickPen; } - QPen selectedSubTickPen() const { return mSelectedSubTickPen; } - QCPPolarGrid *grid() const { return mGrid; } - - // setters: - void setBackground(const QPixmap &pm); - void setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode=Qt::KeepAspectRatioByExpanding); - void setBackground(const QBrush &brush); - void setBackgroundScaled(bool scaled); - void setBackgroundScaledMode(Qt::AspectRatioMode mode); - void setRangeDrag(bool enabled); - void setRangeZoom(bool enabled); - void setRangeZoomFactor(double factor); - - 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 setAngle(double degrees); - void setTicker(QSharedPointer ticker); - void setTicks(bool show); - void setTickLabels(bool show); - void setTickLabelPadding(int padding); - void setTickLabelFont(const QFont &font); - void setTickLabelColor(const QColor &color); - void setTickLabelRotation(double degrees); - void setTickLabelMode(LabelMode mode); - void setNumberFormat(const QString &formatCode); - void setNumberPrecision(int precision); - void setTickLength(int inside, int outside=0); - void setTickLengthIn(int inside); - void setTickLengthOut(int outside); - void setSubTicks(bool show); - void setSubTickLength(int inside, int outside=0); - void setSubTickLengthIn(int inside); - void setSubTickLengthOut(int outside); - void setBasePen(const QPen &pen); - void setTickPen(const QPen &pen); - void setSubTickPen(const QPen &pen); - void setLabelFont(const QFont &font); - void setLabelColor(const QColor &color); - void setLabel(const QString &str); - void setLabelPadding(int padding); - void setLabelPosition(Qt::AlignmentFlag position); - void setSelectedTickLabelFont(const QFont &font); - void setSelectedLabelFont(const QFont &font); - void setSelectedTickLabelColor(const QColor &color); - void setSelectedLabelColor(const QColor &color); - void setSelectedBasePen(const QPen &pen); - void setSelectedTickPen(const QPen &pen); - void setSelectedSubTickPen(const QPen &pen); - Q_SLOT void setSelectableParts(const QCPPolarAxisAngular::SelectableParts &selectableParts); - Q_SLOT void setSelectedParts(const QCPPolarAxisAngular::SelectableParts &selectedParts); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const Q_DECL_OVERRIDE; - virtual void update(UpdatePhase phase) Q_DECL_OVERRIDE; - virtual QList elements(bool recursive) const Q_DECL_OVERRIDE; - - // non-property methods: - bool removeGraph(QCPPolarGraph *graph); - int radialAxisCount() const; - QCPPolarAxisRadial *radialAxis(int index=0) const; - QList radialAxes() const; - QCPPolarAxisRadial *addRadialAxis(QCPPolarAxisRadial *axis=0); - bool removeRadialAxis(QCPPolarAxisRadial *axis); - QCPLayoutInset *insetLayout() const { return mInsetLayout; } - QRegion exactClipRegion() const; - - void moveRange(double diff); - void scaleRange(double factor); - void scaleRange(double factor, double center); - void rescale(bool onlyVisiblePlottables=false); - double coordToAngleRad(double coord) const { return mAngleRad+(coord-mRange.lower)/mRange.size()*(mRangeReversed ? -2.0*M_PI : 2.0*M_PI); } // mention in doc that return doesn't wrap - double angleRadToCoord(double angleRad) const { return mRange.lower+(angleRad-mAngleRad)/(mRangeReversed ? -2.0*M_PI : 2.0*M_PI)*mRange.size(); } - void pixelToCoord(QPointF pixelPos, double &angleCoord, double &radiusCoord) const; - QPointF coordToPixel(double angleCoord, double radiusCoord) const; - SelectablePart getPartAt(const QPointF &pos) const; - - // read-only interface imitating a QRect: - int left() const { return mRect.left(); } - int right() const { return mRect.right(); } - int top() const { return mRect.top(); } - int bottom() const { return mRect.bottom(); } - int width() const { return mRect.width(); } - int height() const { return mRect.height(); } - QSize size() const { return mRect.size(); } - QPoint topLeft() const { return mRect.topLeft(); } - QPoint topRight() const { return mRect.topRight(); } - QPoint bottomLeft() const { return mRect.bottomLeft(); } - QPoint bottomRight() const { return mRect.bottomRight(); } - QPointF center() const { return mCenter; } - double radius() const { return mRadius; } - + */ + enum LabelMode { lmUpright ///< + , lmRotated ///< + }; + Q_ENUMS(LabelMode) + + explicit QCPPolarAxisAngular(QCustomPlot *parentPlot); + virtual ~QCPPolarAxisAngular(); + + // getters: + QPixmap background() const { + return mBackgroundPixmap; + } + QBrush backgroundBrush() const { + return mBackgroundBrush; + } + bool backgroundScaled() const { + return mBackgroundScaled; + } + Qt::AspectRatioMode backgroundScaledMode() const { + return mBackgroundScaledMode; + } + bool rangeDrag() const { + return mRangeDrag; + } + bool rangeZoom() const { + return mRangeZoom; + } + double rangeZoomFactor() const { + return mRangeZoomFactor; + } + + const QCPRange range() const { + return mRange; + } + bool rangeReversed() const { + return mRangeReversed; + } + double angle() const { + return mAngle; + } + QSharedPointer ticker() const { + return mTicker; + } + bool ticks() const { + return mTicks; + } + bool tickLabels() const { + return mTickLabels; + } + int tickLabelPadding() const { + return mLabelPainter.padding(); + } + QFont tickLabelFont() const { + return mTickLabelFont; + } + QColor tickLabelColor() const { + return mTickLabelColor; + } + double tickLabelRotation() const { + return mLabelPainter.rotation(); + } + LabelMode tickLabelMode() const; + QString numberFormat() const; + int numberPrecision() const { + return mNumberPrecision; + } + QVector tickVector() const { + return mTickVector; + } + QVector tickVectorLabels() const { + return mTickVectorLabels; + } + int tickLengthIn() const { + return mTickLengthIn; + } + int tickLengthOut() const { + return mTickLengthOut; + } + bool subTicks() const { + return mSubTicks; + } + int subTickLengthIn() const { + return mSubTickLengthIn; + } + int subTickLengthOut() const { + return mSubTickLengthOut; + } + QPen basePen() const { + return mBasePen; + } + QPen tickPen() const { + return mTickPen; + } + QPen subTickPen() const { + return mSubTickPen; + } + QFont labelFont() const { + return mLabelFont; + } + QColor labelColor() const { + return mLabelColor; + } + QString label() const { + return mLabel; + } + int labelPadding() const { + return mLabelPadding; + } + SelectableParts selectedParts() const { + return mSelectedParts; + } + SelectableParts selectableParts() const { + return mSelectableParts; + } + QFont selectedTickLabelFont() const { + return mSelectedTickLabelFont; + } + QFont selectedLabelFont() const { + return mSelectedLabelFont; + } + QColor selectedTickLabelColor() const { + return mSelectedTickLabelColor; + } + QColor selectedLabelColor() const { + return mSelectedLabelColor; + } + QPen selectedBasePen() const { + return mSelectedBasePen; + } + QPen selectedTickPen() const { + return mSelectedTickPen; + } + QPen selectedSubTickPen() const { + return mSelectedSubTickPen; + } + QCPPolarGrid *grid() const { + return mGrid; + } + + // setters: + void setBackground(const QPixmap &pm); + void setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode = Qt::KeepAspectRatioByExpanding); + void setBackground(const QBrush &brush); + void setBackgroundScaled(bool scaled); + void setBackgroundScaledMode(Qt::AspectRatioMode mode); + void setRangeDrag(bool enabled); + void setRangeZoom(bool enabled); + void setRangeZoomFactor(double factor); + + 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 setAngle(double degrees); + void setTicker(QSharedPointer ticker); + void setTicks(bool show); + void setTickLabels(bool show); + void setTickLabelPadding(int padding); + void setTickLabelFont(const QFont &font); + void setTickLabelColor(const QColor &color); + void setTickLabelRotation(double degrees); + void setTickLabelMode(LabelMode mode); + void setNumberFormat(const QString &formatCode); + void setNumberPrecision(int precision); + void setTickLength(int inside, int outside = 0); + void setTickLengthIn(int inside); + void setTickLengthOut(int outside); + void setSubTicks(bool show); + void setSubTickLength(int inside, int outside = 0); + void setSubTickLengthIn(int inside); + void setSubTickLengthOut(int outside); + void setBasePen(const QPen &pen); + void setTickPen(const QPen &pen); + void setSubTickPen(const QPen &pen); + void setLabelFont(const QFont &font); + void setLabelColor(const QColor &color); + void setLabel(const QString &str); + void setLabelPadding(int padding); + void setLabelPosition(Qt::AlignmentFlag position); + void setSelectedTickLabelFont(const QFont &font); + void setSelectedLabelFont(const QFont &font); + void setSelectedTickLabelColor(const QColor &color); + void setSelectedLabelColor(const QColor &color); + void setSelectedBasePen(const QPen &pen); + void setSelectedTickPen(const QPen &pen); + void setSelectedSubTickPen(const QPen &pen); + Q_SLOT void setSelectableParts(const QCPPolarAxisAngular::SelectableParts &selectableParts); + Q_SLOT void setSelectedParts(const QCPPolarAxisAngular::SelectableParts &selectedParts); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = 0) const Q_DECL_OVERRIDE; + virtual void update(UpdatePhase phase) Q_DECL_OVERRIDE; + virtual QList elements(bool recursive) const Q_DECL_OVERRIDE; + + // non-property methods: + bool removeGraph(QCPPolarGraph *graph); + int radialAxisCount() const; + QCPPolarAxisRadial *radialAxis(int index = 0) const; + QList radialAxes() const; + QCPPolarAxisRadial *addRadialAxis(QCPPolarAxisRadial *axis = 0); + bool removeRadialAxis(QCPPolarAxisRadial *axis); + QCPLayoutInset *insetLayout() const { + return mInsetLayout; + } + QRegion exactClipRegion() const; + + void moveRange(double diff); + void scaleRange(double factor); + void scaleRange(double factor, double center); + void rescale(bool onlyVisiblePlottables = false); + double coordToAngleRad(double coord) const { + return mAngleRad + (coord - mRange.lower) / mRange.size() * (mRangeReversed ? -2.0 * M_PI : 2.0 * M_PI); // mention in doc that return doesn't wrap + } + double angleRadToCoord(double angleRad) const { + return mRange.lower + (angleRad - mAngleRad) / (mRangeReversed ? -2.0 * M_PI : 2.0 * M_PI) * mRange.size(); + } + void pixelToCoord(QPointF pixelPos, double &angleCoord, double &radiusCoord) const; + QPointF coordToPixel(double angleCoord, double radiusCoord) const; + SelectablePart getPartAt(const QPointF &pos) const; + + // read-only interface imitating a QRect: + int left() const { + return mRect.left(); + } + int right() const { + return mRect.right(); + } + int top() const { + return mRect.top(); + } + int bottom() const { + return mRect.bottom(); + } + int width() const { + return mRect.width(); + } + int height() const { + return mRect.height(); + } + QSize size() const { + return mRect.size(); + } + QPoint topLeft() const { + return mRect.topLeft(); + } + QPoint topRight() const { + return mRect.topRight(); + } + QPoint bottomLeft() const { + return mRect.bottomLeft(); + } + QPoint bottomRight() const { + return mRect.bottomRight(); + } + QPointF center() const { + return mCenter; + } + double radius() const { + return mRadius; + } + signals: - void rangeChanged(const QCPRange &newRange); - void rangeChanged(const QCPRange &newRange, const QCPRange &oldRange); - void selectionChanged(const QCPPolarAxisAngular::SelectableParts &parts); - void selectableChanged(const QCPPolarAxisAngular::SelectableParts &parts); - + void rangeChanged(const QCPRange &newRange); + void rangeChanged(const QCPRange &newRange, const QCPRange &oldRange); + void selectionChanged(const QCPPolarAxisAngular::SelectableParts &parts); + void selectableChanged(const QCPPolarAxisAngular::SelectableParts &parts); + protected: - // property members: - QBrush mBackgroundBrush; - QPixmap mBackgroundPixmap; - QPixmap mScaledBackgroundPixmap; - bool mBackgroundScaled; - Qt::AspectRatioMode mBackgroundScaledMode; - QCPLayoutInset *mInsetLayout; - bool mRangeDrag; - bool mRangeZoom; - double mRangeZoomFactor; - - // axis base: - double mAngle, mAngleRad; - SelectableParts mSelectableParts, mSelectedParts; - QPen mBasePen, mSelectedBasePen; - // axis label: - int mLabelPadding; - QString mLabel; - QFont mLabelFont, mSelectedLabelFont; - QColor mLabelColor, mSelectedLabelColor; - // tick labels: - //int mTickLabelPadding; in label painter - bool mTickLabels; - //double mTickLabelRotation; in label painter - QFont mTickLabelFont, mSelectedTickLabelFont; - QColor mTickLabelColor, mSelectedTickLabelColor; - int mNumberPrecision; - QLatin1Char mNumberFormatChar; - bool mNumberBeautifulPowers; - bool mNumberMultiplyCross; - // ticks and subticks: - bool mTicks; - bool mSubTicks; - int mTickLengthIn, mTickLengthOut, mSubTickLengthIn, mSubTickLengthOut; - QPen mTickPen, mSelectedTickPen; - QPen mSubTickPen, mSelectedSubTickPen; - // scale and range: - QCPRange mRange; - bool mRangeReversed; - - // non-property members: - QPointF mCenter; - double mRadius; - QList mRadialAxes; - QCPPolarGrid *mGrid; - QList mGraphs; - QSharedPointer mTicker; - QVector mTickVector; - QVector mTickVectorLabels; - QVector mTickVectorCosSin; - QVector mSubTickVector; - QVector mSubTickVectorCosSin; - bool mDragging; - QCPRange mDragAngularStart; - QList mDragRadialStart; - QCP::AntialiasedElements mAADragBackup, mNotAADragBackup; - QCPLabelPainterPrivate mLabelPainter; - - // reimplemented virtual methods: - 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 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-virtual methods: - bool registerPolarGraph(QCPPolarGraph *graph); - void drawBackground(QCPPainter *painter, const QPointF ¢er, double radius); - void setupTickVectors(); - QPen getBasePen() const; - QPen getTickPen() const; - QPen getSubTickPen() const; - QFont getTickLabelFont() const; - QFont getLabelFont() const; - QColor getTickLabelColor() const; - QColor getLabelColor() const; - + // property members: + QBrush mBackgroundBrush; + QPixmap mBackgroundPixmap; + QPixmap mScaledBackgroundPixmap; + bool mBackgroundScaled; + Qt::AspectRatioMode mBackgroundScaledMode; + QCPLayoutInset *mInsetLayout; + bool mRangeDrag; + bool mRangeZoom; + double mRangeZoomFactor; + + // axis base: + double mAngle, mAngleRad; + SelectableParts mSelectableParts, mSelectedParts; + QPen mBasePen, mSelectedBasePen; + // axis label: + int mLabelPadding; + QString mLabel; + QFont mLabelFont, mSelectedLabelFont; + QColor mLabelColor, mSelectedLabelColor; + // tick labels: + //int mTickLabelPadding; in label painter + bool mTickLabels; + //double mTickLabelRotation; in label painter + QFont mTickLabelFont, mSelectedTickLabelFont; + QColor mTickLabelColor, mSelectedTickLabelColor; + int mNumberPrecision; + QLatin1Char mNumberFormatChar; + bool mNumberBeautifulPowers; + bool mNumberMultiplyCross; + // ticks and subticks: + bool mTicks; + bool mSubTicks; + int mTickLengthIn, mTickLengthOut, mSubTickLengthIn, mSubTickLengthOut; + QPen mTickPen, mSelectedTickPen; + QPen mSubTickPen, mSelectedSubTickPen; + // scale and range: + QCPRange mRange; + bool mRangeReversed; + + // non-property members: + QPointF mCenter; + double mRadius; + QList mRadialAxes; + QCPPolarGrid *mGrid; + QList mGraphs; + QSharedPointer mTicker; + QVector mTickVector; + QVector mTickVectorLabels; + QVector mTickVectorCosSin; + QVector mSubTickVector; + QVector mSubTickVectorCosSin; + bool mDragging; + QCPRange mDragAngularStart; + QList mDragRadialStart; + QCP::AntialiasedElements mAADragBackup, mNotAADragBackup; + QCPLabelPainterPrivate mLabelPainter; + + // reimplemented virtual methods: + 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 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-virtual methods: + bool registerPolarGraph(QCPPolarGraph *graph); + void drawBackground(QCPPainter *painter, const QPointF ¢er, double radius); + void setupTickVectors(); + QPen getBasePen() const; + QPen getTickPen() const; + QPen getSubTickPen() const; + QFont getTickLabelFont() const; + QFont getLabelFont() const; + QColor getTickLabelColor() const; + QColor getLabelColor() const; + private: - Q_DISABLE_COPY(QCPPolarAxisAngular) - - friend class QCustomPlot; - friend class QCPPolarGrid; - friend class QCPPolarGraph; + Q_DISABLE_COPY(QCPPolarAxisAngular) + + friend class QCustomPlot; + friend class QCPPolarGrid; + friend class QCPPolarGraph; }; Q_DECLARE_OPERATORS_FOR_FLAGS(QCPPolarAxisAngular::SelectableParts) Q_DECLARE_METATYPE(QCPPolarAxisAngular::SelectablePart) @@ -7491,74 +8531,94 @@ Q_DECLARE_METATYPE(QCPPolarAxisAngular::SelectablePart) /* including file 'src/polar/polargrid.h' */ /* modified 2021-03-29T02:30:44, size 4506 */ -class QCP_LIB_DECL QCPPolarGrid :public QCPLayerable +class QCP_LIB_DECL QCPPolarGrid : public QCPLayerable { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + + /// \endcond public: - /*! + /*! TODO - */ - enum GridType { gtAngular = 0x01 ///< - ,gtRadial = 0x02 ///< - ,gtAll = 0xFF ///< - ,gtNone = 0x00 ///< - }; - Q_ENUMS(GridType) - Q_FLAGS(GridTypes) - Q_DECLARE_FLAGS(GridTypes, GridType) - - explicit QCPPolarGrid(QCPPolarAxisAngular *parentAxis); - - // getters: - QCPPolarAxisRadial *radialAxis() const { return mRadialAxis.data(); } - GridTypes type() const { return mType; } - GridTypes subGridType() const { return mSubGridType; } - bool antialiasedSubGrid() const { return mAntialiasedSubGrid; } - bool antialiasedZeroLine() const { return mAntialiasedZeroLine; } - QPen angularPen() const { return mAngularPen; } - QPen angularSubGridPen() const { return mAngularSubGridPen; } - QPen radialPen() const { return mRadialPen; } - QPen radialSubGridPen() const { return mRadialSubGridPen; } - QPen radialZeroLinePen() const { return mRadialZeroLinePen; } - - // setters: - void setRadialAxis(QCPPolarAxisRadial *axis); - void setType(GridTypes type); - void setSubGridType(GridTypes type); - void setAntialiasedSubGrid(bool enabled); - void setAntialiasedZeroLine(bool enabled); - void setAngularPen(const QPen &pen); - void setAngularSubGridPen(const QPen &pen); - void setRadialPen(const QPen &pen); - void setRadialSubGridPen(const QPen &pen); - void setRadialZeroLinePen(const QPen &pen); - + */ + enum GridType { gtAngular = 0x01 ///< + , gtRadial = 0x02 ///< + , gtAll = 0xFF ///< + , gtNone = 0x00 ///< + }; + Q_ENUMS(GridType) + Q_FLAGS(GridTypes) + Q_DECLARE_FLAGS(GridTypes, GridType) + + explicit QCPPolarGrid(QCPPolarAxisAngular *parentAxis); + + // getters: + QCPPolarAxisRadial *radialAxis() const { + return mRadialAxis.data(); + } + GridTypes type() const { + return mType; + } + GridTypes subGridType() const { + return mSubGridType; + } + bool antialiasedSubGrid() const { + return mAntialiasedSubGrid; + } + bool antialiasedZeroLine() const { + return mAntialiasedZeroLine; + } + QPen angularPen() const { + return mAngularPen; + } + QPen angularSubGridPen() const { + return mAngularSubGridPen; + } + QPen radialPen() const { + return mRadialPen; + } + QPen radialSubGridPen() const { + return mRadialSubGridPen; + } + QPen radialZeroLinePen() const { + return mRadialZeroLinePen; + } + + // setters: + void setRadialAxis(QCPPolarAxisRadial *axis); + void setType(GridTypes type); + void setSubGridType(GridTypes type); + void setAntialiasedSubGrid(bool enabled); + void setAntialiasedZeroLine(bool enabled); + void setAngularPen(const QPen &pen); + void setAngularSubGridPen(const QPen &pen); + void setRadialPen(const QPen &pen); + void setRadialSubGridPen(const QPen &pen); + void setRadialZeroLinePen(const QPen &pen); + protected: - // property members: - GridTypes mType; - GridTypes mSubGridType; - bool mAntialiasedSubGrid, mAntialiasedZeroLine; - QPen mAngularPen, mAngularSubGridPen; - QPen mRadialPen, mRadialSubGridPen, mRadialZeroLinePen; - - // non-property members: - QCPPolarAxisAngular *mParentAxis; - QPointer mRadialAxis; - - // reimplemented virtual methods: - virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const Q_DECL_OVERRIDE; - virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; - - // non-virtual methods: - void drawRadialGrid(QCPPainter *painter, const QPointF ¢er, const QVector &coords, const QPen &pen, const QPen &zeroPen=Qt::NoPen); - void drawAngularGrid(QCPPainter *painter, const QPointF ¢er, double radius, const QVector &ticksCosSin, const QPen &pen); - + // property members: + GridTypes mType; + GridTypes mSubGridType; + bool mAntialiasedSubGrid, mAntialiasedZeroLine; + QPen mAngularPen, mAngularSubGridPen; + QPen mRadialPen, mRadialSubGridPen, mRadialZeroLinePen; + + // non-property members: + QCPPolarAxisAngular *mParentAxis; + QPointer mRadialAxis; + + // reimplemented virtual methods: + virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const Q_DECL_OVERRIDE; + virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; + + // non-virtual methods: + void drawRadialGrid(QCPPainter *painter, const QPointF ¢er, const QVector &coords, const QPen &pen, const QPen &zeroPen = Qt::NoPen); + void drawAngularGrid(QCPPainter *painter, const QPointF ¢er, double radius, const QVector &ticksCosSin, const QPen &pen); + private: - Q_DISABLE_COPY(QCPPolarGrid) - + Q_DISABLE_COPY(QCPPolarGrid) + }; Q_DECLARE_OPERATORS_FOR_FLAGS(QCPPolarGrid::GridTypes) @@ -7574,160 +8634,191 @@ Q_DECLARE_METATYPE(QCPPolarGrid::GridType) class QCP_LIB_DECL QCPPolarLegendItem : public QCPAbstractLegendItem { - Q_OBJECT -public: - QCPPolarLegendItem(QCPLegend *parent, QCPPolarGraph *graph); - - // getters: - QCPPolarGraph *polarGraph() { return mPolarGraph; } - + Q_OBJECT +public: QCPPolarLegendItem(QCPLegend *parent, QCPPolarGraph *graph); + + // getters: + QCPPolarGraph *polarGraph() { + return mPolarGraph; + } + protected: - // property members: - QCPPolarGraph *mPolarGraph; - - // reimplemented virtual methods: - virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; - virtual QSize minimumOuterSizeHint() const Q_DECL_OVERRIDE; - - // non-virtual methods: - QPen getIconBorderPen() const; - QColor getTextColor() const; - QFont getFont() const; + // property members: + QCPPolarGraph *mPolarGraph; + + // reimplemented virtual methods: + virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; + virtual QSize minimumOuterSizeHint() const Q_DECL_OVERRIDE; + + // non-virtual methods: + QPen getIconBorderPen() const; + QColor getTextColor() const; + QFont getFont() const; }; class QCP_LIB_DECL QCPPolarGraph : public QCPLayerable { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + + /// \endcond public: - /*! + /*! Defines how the graph's line is represented visually in the plot. The line is drawn with the current pen of the graph (\ref setPen). \see setLineStyle - */ - enum LineStyle { lsNone ///< data points are not connected with any lines (e.g. data only represented - ///< with symbols according to the scatter style, see \ref setScatterStyle) - ,lsLine ///< data points are connected by a straight line - }; - Q_ENUMS(LineStyle) - - QCPPolarGraph(QCPPolarAxisAngular *keyAxis, QCPPolarAxisRadial *valueAxis); - virtual ~QCPPolarGraph(); - - // getters: - QString name() const { return mName; } - bool antialiasedFill() const { return mAntialiasedFill; } - bool antialiasedScatters() const { return mAntialiasedScatters; } - QPen pen() const { return mPen; } - QBrush brush() const { return mBrush; } - bool periodic() const { return mPeriodic; } - QCPPolarAxisAngular *keyAxis() const { return mKeyAxis.data(); } - QCPPolarAxisRadial *valueAxis() const { return mValueAxis.data(); } - QCP::SelectionType selectable() const { return mSelectable; } - bool selected() const { return !mSelection.isEmpty(); } - QCPDataSelection selection() const { return mSelection; } - //QCPSelectionDecorator *selectionDecorator() const { return mSelectionDecorator; } - QSharedPointer data() const { return mDataContainer; } - LineStyle lineStyle() const { return mLineStyle; } - QCPScatterStyle scatterStyle() const { return mScatterStyle; } - - // setters: - void setName(const QString &name); - void setAntialiasedFill(bool enabled); - void setAntialiasedScatters(bool enabled); - void setPen(const QPen &pen); - void setBrush(const QBrush &brush); - void setPeriodic(bool enabled); - void setKeyAxis(QCPPolarAxisAngular *axis); - void setValueAxis(QCPPolarAxisRadial *axis); - Q_SLOT void setSelectable(QCP::SelectionType selectable); - Q_SLOT void setSelection(QCPDataSelection selection); - //void setSelectionDecorator(QCPSelectionDecorator *decorator); - void setData(QSharedPointer data); - void setData(const QVector &keys, const QVector &values, bool alreadySorted=false); - void setLineStyle(LineStyle ls); - void setScatterStyle(const QCPScatterStyle &style); + */ + enum LineStyle { lsNone ///< data points are not connected with any lines (e.g. data only represented + ///< with symbols according to the scatter style, see \ref setScatterStyle) + , lsLine ///< data points are connected by a straight line + }; + Q_ENUMS(LineStyle) + + QCPPolarGraph(QCPPolarAxisAngular *keyAxis, QCPPolarAxisRadial *valueAxis); + virtual ~QCPPolarGraph(); + + // getters: + QString name() const { + return mName; + } + bool antialiasedFill() const { + return mAntialiasedFill; + } + bool antialiasedScatters() const { + return mAntialiasedScatters; + } + QPen pen() const { + return mPen; + } + QBrush brush() const { + return mBrush; + } + bool periodic() const { + return mPeriodic; + } + QCPPolarAxisAngular *keyAxis() const { + return mKeyAxis.data(); + } + QCPPolarAxisRadial *valueAxis() const { + return mValueAxis.data(); + } + QCP::SelectionType selectable() const { + return mSelectable; + } + bool selected() const { + return !mSelection.isEmpty(); + } + QCPDataSelection selection() const { + return mSelection; + } + //QCPSelectionDecorator *selectionDecorator() const { return mSelectionDecorator; } + QSharedPointer data() const { + return mDataContainer; + } + LineStyle lineStyle() const { + return mLineStyle; + } + QCPScatterStyle scatterStyle() const { + return mScatterStyle; + } + + // setters: + void setName(const QString &name); + void setAntialiasedFill(bool enabled); + void setAntialiasedScatters(bool enabled); + void setPen(const QPen &pen); + void setBrush(const QBrush &brush); + void setPeriodic(bool enabled); + void setKeyAxis(QCPPolarAxisAngular *axis); + void setValueAxis(QCPPolarAxisRadial *axis); + Q_SLOT void setSelectable(QCP::SelectionType selectable); + Q_SLOT void setSelection(QCPDataSelection selection); + //void setSelectionDecorator(QCPSelectionDecorator *decorator); + void setData(QSharedPointer data); + void setData(const QVector &keys, const QVector &values, bool alreadySorted = false); + void setLineStyle(LineStyle ls); + void setScatterStyle(const QCPScatterStyle &style); + + // non-property methods: + void addData(const QVector &keys, const QVector &values, bool alreadySorted = false); + void addData(double key, double value); + 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; + 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; + + // introduced virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = 0) const; // actually introduced in QCPLayerable as non-pure, but we want to force reimplementation for plottables + virtual QCPPlottableInterface1D *interface1D() { + return 0; // TODO: return this later, when QCPAbstractPolarPlottable is created + } + virtual QCPRange getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain = QCP::sdBoth) const; + virtual QCPRange getValueRange(bool &foundRange, QCP::SignDomain inSignDomain = QCP::sdBoth, const QCPRange &inKeyRange = QCPRange()) const; - // non-property methods: - void addData(const QVector &keys, const QVector &values, bool alreadySorted=false); - void addData(double key, double value); - 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; - 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; - - // introduced virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; // actually introduced in QCPLayerable as non-pure, but we want to force reimplementation for plottables - virtual QCPPlottableInterface1D *interface1D() { return 0; } // TODO: return this later, when QCPAbstractPolarPlottable is created - virtual QCPRange getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain=QCP::sdBoth) const; - virtual QCPRange getValueRange(bool &foundRange, QCP::SignDomain inSignDomain=QCP::sdBoth, const QCPRange &inKeyRange=QCPRange()) const; - signals: - void selectionChanged(bool selected); - void selectionChanged(const QCPDataSelection &selection); - void selectableChanged(QCP::SelectionType selectable); - + void selectionChanged(bool selected); + void selectionChanged(const QCPDataSelection &selection); + void selectableChanged(QCP::SelectionType selectable); + protected: - // property members: - QSharedPointer mDataContainer; - LineStyle mLineStyle; - QCPScatterStyle mScatterStyle; - QString mName; - bool mAntialiasedFill, mAntialiasedScatters; - QPen mPen; - QBrush mBrush; - bool mPeriodic; - QPointer mKeyAxis; - QPointer mValueAxis; - QCP::SelectionType mSelectable; - QCPDataSelection mSelection; - //QCPSelectionDecorator *mSelectionDecorator; - - // introduced virtual methods (later reimplemented TODO from QCPAbstractPolarPlottable): - virtual QRect clipRect() const; - virtual void draw(QCPPainter *painter); - 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); - // virtual drawing helpers: - virtual void drawLinePlot(QCPPainter *painter, const QVector &lines) const; - virtual void drawFill(QCPPainter *painter, QVector *lines) const; - virtual void drawScatterPlot(QCPPainter *painter, const QVector &scatters, const QCPScatterStyle &style) const; - - // introduced virtual methods: - virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const; - - // non-virtual methods: - void applyFillAntialiasingHint(QCPPainter *painter) const; - void applyScattersAntialiasingHint(QCPPainter *painter) const; - double pointDistance(const QPointF &pixelPoint, QCPGraphDataContainer::const_iterator &closestData) const; - // drawing helpers: - virtual int dataCount() const; - void getDataSegments(QList &selectedSegments, QList &unselectedSegments) const; - void drawPolyline(QCPPainter *painter, const 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; - void getOptimizedLineData(QVector *lineData, const QCPGraphDataContainer::const_iterator &begin, const QCPGraphDataContainer::const_iterator &end) const; - void getOptimizedScatterData(QVector *scatterData, QCPGraphDataContainer::const_iterator begin, QCPGraphDataContainer::const_iterator end) const; - QVector dataToLines(const QVector &data) const; + // property members: + QSharedPointer mDataContainer; + LineStyle mLineStyle; + QCPScatterStyle mScatterStyle; + QString mName; + bool mAntialiasedFill, mAntialiasedScatters; + QPen mPen; + QBrush mBrush; + bool mPeriodic; + QPointer mKeyAxis; + QPointer mValueAxis; + QCP::SelectionType mSelectable; + QCPDataSelection mSelection; + //QCPSelectionDecorator *mSelectionDecorator; + + // introduced virtual methods (later reimplemented TODO from QCPAbstractPolarPlottable): + virtual QRect clipRect() const; + virtual void draw(QCPPainter *painter); + 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); + // virtual drawing helpers: + virtual void drawLinePlot(QCPPainter *painter, const QVector &lines) const; + virtual void drawFill(QCPPainter *painter, QVector *lines) const; + virtual void drawScatterPlot(QCPPainter *painter, const QVector &scatters, const QCPScatterStyle &style) const; + + // introduced virtual methods: + virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const; + + // non-virtual methods: + void applyFillAntialiasingHint(QCPPainter *painter) const; + void applyScattersAntialiasingHint(QCPPainter *painter) const; + double pointDistance(const QPointF &pixelPoint, QCPGraphDataContainer::const_iterator &closestData) const; + // drawing helpers: + virtual int dataCount() const; + void getDataSegments(QList &selectedSegments, QList &unselectedSegments) const; + void drawPolyline(QCPPainter *painter, const 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; + void getOptimizedLineData(QVector *lineData, const QCPGraphDataContainer::const_iterator &begin, const QCPGraphDataContainer::const_iterator &end) const; + void getOptimizedScatterData(QVector *scatterData, QCPGraphDataContainer::const_iterator begin, QCPGraphDataContainer::const_iterator end) const; + QVector dataToLines(const QVector &data) const; private: - Q_DISABLE_COPY(QCPPolarGraph) - - friend class QCPPolarLegendItem; + Q_DISABLE_COPY(QCPPolarGraph) + + friend class QCPPolarLegendItem; }; /* end of 'src/polar/polargraph.h' */ diff --git a/third/3rd_qcustomplot/v2_1_6/qcustomplot.h b/third/3rd_qcustomplot/v2_1_6/qcustomplot.h index 8990c4f..0c96bf8 100644 --- a/third/3rd_qcustomplot/v2_1_6/qcustomplot.h +++ b/third/3rd_qcustomplot/v2_1_6/qcustomplot.h @@ -1,4 +1,4 @@ -/*************************************************************************** +/*************************************************************************** ** ** ** QCustomPlot, an easy to use, modern plotting widget for Qt ** ** Copyright (C) 2011-2021 Emanuel Eichhammer ** @@ -157,7 +157,7 @@ class QCPPolarGraph; It provides QMetaObject-based reflection of its enums and flags via \a QCP::staticMetaObject. */ namespace QCP { - Q_NAMESPACE +Q_NAMESPACE /*! Defines the different units in which the image resolution can be specified in the export @@ -166,8 +166,8 @@ namespace QCP { \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) +, ruDotsPerCentimeter ///< Resolution is given in dots per centimeter (dpcm) +, ruDotsPerInch ///< Resolution is given in dots per inch (DPI/PPI) }; /*! @@ -176,32 +176,32 @@ enum ResolutionUnit { ruDotsPerMeter ///< Resolution is given in dots per \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) +, 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 +, 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. - + \see QCPLayoutElement::setAutoMargins, QCPAxisRect::setAutoMargins */ enum MarginSide { msLeft = 0x01 ///< 0x01 left margin - ,msRight = 0x02 ///< 0x02 right margin - ,msTop = 0x04 ///< 0x04 top margin - ,msBottom = 0x08 ///< 0x08 bottom margin - ,msAll = 0xFF ///< 0xFF all margins - ,msNone = 0x00 ///< 0x00 no margin +, msRight = 0x02 ///< 0x02 right margin +, msTop = 0x04 ///< 0x04 top margin +, msBottom = 0x08 ///< 0x08 bottom margin +, msAll = 0xFF ///< 0xFF all margins +, msNone = 0x00 ///< 0x00 no margin }; Q_DECLARE_FLAGS(MarginSides, MarginSide) @@ -209,76 +209,76 @@ Q_DECLARE_FLAGS(MarginSides, MarginSide) Defines what objects of a plot can be forcibly drawn antialiased/not antialiased. If an object is neither forcibly drawn antialiased nor forcibly drawn not antialiased, it is up to the respective element how it is drawn. Typically it provides a \a setAntialiased function for this. - + \c AntialiasedElements is a flag of or-combined elements of this enum type. - + \see QCustomPlot::setAntialiasedElements, QCustomPlot::setNotAntialiasedElements */ enum AntialiasedElement { aeAxes = 0x0001 ///< 0x0001 Axis base line and tick marks - ,aeGrid = 0x0002 ///< 0x0002 Grid lines - ,aeSubGrid = 0x0004 ///< 0x0004 Sub grid lines - ,aeLegend = 0x0008 ///< 0x0008 Legend box - ,aeLegendItems = 0x0010 ///< 0x0010 Legend items - ,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) - ,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 +, aeGrid = 0x0002 ///< 0x0002 Grid lines +, aeSubGrid = 0x0004 ///< 0x0004 Sub grid lines +, aeLegend = 0x0008 ///< 0x0008 Legend box +, aeLegendItems = 0x0010 ///< 0x0010 Legend items +, 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) +, 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 }; Q_DECLARE_FLAGS(AntialiasedElements, AntialiasedElement) /*! Defines plotting hints that control various aspects of the quality and speed of plotting. - + \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, 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. +, 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) /*! Defines the mouse interactions possible with QCustomPlot. - + \c Interactions is a flag of or-combined elements of this enum type. - + \see QCustomPlot::setInteractions */ enum Interaction { iNone = 0x000 ///< 0x000 None of the interactions are possible - ,iRangeDrag = 0x001 ///< 0x001 Axis ranges are draggable (see \ref QCPAxisRect::setRangeDrag, \ref QCPAxisRect::setRangeDragAxes) - ,iRangeZoom = 0x002 ///< 0x002 Axis ranges are zoomable with the mouse wheel (see \ref QCPAxisRect::setRangeZoom, \ref QCPAxisRect::setRangeZoomAxes) - ,iMultiSelect = 0x004 ///< 0x004 The user can select multiple objects by holding the modifier set by \ref QCustomPlot::setMultiSelectModifier while clicking - ,iSelectPlottables = 0x008 ///< 0x008 Plottables are selectable (e.g. graphs, curves, bars,... see QCPAbstractPlottable) - ,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, other layout elements,...) - ,iSelectPlottablesBeyondAxisRect = 0x100 ///< 0x100 When performing plottable selection/hit tests, this flag extends the sensitive area beyond the axis rect +, iRangeDrag = 0x001 ///< 0x001 Axis ranges are draggable (see \ref QCPAxisRect::setRangeDrag, \ref QCPAxisRect::setRangeDragAxes) +, iRangeZoom = 0x002 ///< 0x002 Axis ranges are zoomable with the mouse wheel (see \ref QCPAxisRect::setRangeZoom, \ref QCPAxisRect::setRangeZoomAxes) +, iMultiSelect = 0x004 ///< 0x004 The user can select multiple objects by holding the modifier set by \ref QCustomPlot::setMultiSelectModifier while clicking +, iSelectPlottables = 0x008 ///< 0x008 Plottables are selectable (e.g. graphs, curves, bars,... see QCPAbstractPlottable) +, 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, other layout elements,...) +, iSelectPlottablesBeyondAxisRect = 0x100 ///< 0x100 When performing plottable selection/hit tests, this flag extends the sensitive area beyond the axis rect }; 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. +, 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: - +
@@ -290,88 +290,102 @@ enum SelectionRectMode { srmNone ///< The selection rect is disabled, and all
- + \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 - }; +, 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 + }; - Q_ENUM_NS(ExportPen) - Q_ENUM_NS(ResolutionUnit) - Q_ENUM_NS(SignDomain) - Q_ENUM_NS(MarginSide) - Q_FLAG_NS(MarginSides) - Q_ENUM_NS(AntialiasedElement) - Q_FLAG_NS(AntialiasedElements) - Q_ENUM_NS(PlottingHint) - Q_FLAG_NS(PlottingHints) - Q_ENUM_NS(Interaction) - Q_FLAG_NS(Interactions) - Q_ENUM_NS(SelectionRectMode) - Q_ENUM_NS(SelectionType) +Q_ENUM_NS(ExportPen) +Q_ENUM_NS(ResolutionUnit) +Q_ENUM_NS(SignDomain) +Q_ENUM_NS(MarginSide) +Q_FLAG_NS(MarginSides) +Q_ENUM_NS(AntialiasedElement) +Q_FLAG_NS(AntialiasedElements) +Q_ENUM_NS(PlottingHint) +Q_FLAG_NS(PlottingHints) +Q_ENUM_NS(Interaction) +Q_FLAG_NS(Interactions) +Q_ENUM_NS(SelectionRectMode) +Q_ENUM_NS(SelectionType) /*! \internal - + Returns whether the specified \a value is considered an invalid data value for plottables (i.e. is \e nan or \e +/-inf). This function is used to check data validity upon replots, when the compiler flag \c QCUSTOMPLOT_CHECK_DATA is set. */ inline bool isInvalidData(double value) { - return qIsNaN(value) || qIsInf(value); + return qIsNaN(value) || qIsInf(value); } /*! \internal \overload - + Checks two arguments instead of one. */ inline bool isInvalidData(double value1, double value2) { - return isInvalidData(value1) || isInvalidData(value2); + return isInvalidData(value1) || isInvalidData(value2); } /*! \internal - + Sets the specified \a side of \a margins to \a value - + \see getMarginValue */ inline void setMarginValue(QMargins &margins, QCP::MarginSide side, int value) { - switch (side) - { - case QCP::msLeft: margins.setLeft(value); break; - case QCP::msRight: margins.setRight(value); break; - case QCP::msTop: margins.setTop(value); break; - case QCP::msBottom: margins.setBottom(value); break; - case QCP::msAll: margins = QMargins(value, value, value, value); break; - default: break; - } + switch (side) { + case QCP::msLeft: + margins.setLeft(value); + break; + case QCP::msRight: + margins.setRight(value); + break; + case QCP::msTop: + margins.setTop(value); + break; + case QCP::msBottom: + margins.setBottom(value); + break; + case QCP::msAll: + margins = QMargins(value, value, value, value); + break; + default: + break; + } } /*! \internal - + Returns the value of the specified \a side of \a margins. If \a side is \ref QCP::msNone or \ref QCP::msAll, returns 0. - + \see setMarginValue */ inline int getMarginValue(const QMargins &margins, QCP::MarginSide side) { - switch (side) - { - case QCP::msLeft: return margins.left(); - case QCP::msRight: return margins.right(); - case QCP::msTop: return margins.top(); - case QCP::msBottom: return margins.bottom(); - default: break; - } - return 0; + switch (side) { + case QCP::msLeft: + return margins.left(); + case QCP::msRight: + return margins.right(); + case QCP::msTop: + return margins.top(); + case QCP::msBottom: + return margins.bottom(); + default: + break; + } + return 0; } } // end of namespace QCP @@ -390,61 +404,107 @@ Q_DECLARE_OPERATORS_FOR_FLAGS(QCP::Interactions) class QCP_LIB_DECL QCPVector2D { public: - QCPVector2D(); - QCPVector2D(double x, double y); - QCPVector2D(const QPoint &point); - QCPVector2D(const QPointF &point); - - // getters: - double x() const { return mX; } - double y() const { return mY; } - double &rx() { return mX; } - double &ry() { return mY; } - - // 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; } - double angle() const { return qAtan2(mY, mX); } - QPoint toPoint() const { return QPoint(int(mX), int(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); - + QCPVector2D(); + QCPVector2D(double x, double y); + QCPVector2D(const QPoint &point); + QCPVector2D(const QPointF &point); + + // getters: + double x() const { + return mX; + } + double y() const { + return mY; + } + double &rx() { + return mX; + } + double &ry() { + return mY; + } + + // 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; + } + double angle() const { + return qAtan2(mY, mX); + } + QPoint toPoint() const { + return QPoint(int(mX), int(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); + // 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(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); } +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 @@ -464,53 +524,59 @@ inline QDebug operator<< (QDebug d, const QCPVector2D &vec) class QCP_LIB_DECL QCPPainter : public QPainter { - Q_GADGET + Q_GADGET public: - /*! - Defines special modes the painter can operate in. They disable or enable certain subsets of features/fixes/workarounds, - depending on whether they are wanted on the respective output device. - */ - enum PainterMode { pmDefault = 0x00 ///< 0x00 Default mode for painting on screen devices - ,pmVectorized = 0x01 ///< 0x01 Mode for vectorized painting (e.g. PDF export). For example, this prevents some antialiasing fixes. - ,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_ENUMS(PainterMode) - Q_FLAGS(PainterModes) - Q_DECLARE_FLAGS(PainterModes, PainterMode) - - QCPPainter(); - explicit QCPPainter(QPaintDevice *device); - - // getters: - bool antialiasing() const { return testRenderHint(QPainter::Antialiasing); } - PainterModes modes() const { return mModes; } + /*! + Defines special modes the painter can operate in. They disable or enable certain subsets of features/fixes/workarounds, + depending on whether they are wanted on the respective output device. + */ + enum PainterMode { pmDefault = 0x00 ///< 0x00 Default mode for painting on screen devices + , pmVectorized = 0x01 ///< 0x01 Mode for vectorized painting (e.g. PDF export). For example, this prevents some antialiasing fixes. + , 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_ENUMS(PainterMode) + Q_FLAGS(PainterModes) + Q_DECLARE_FLAGS(PainterModes, PainterMode) - // setters: - void setAntialiasing(bool enabled); - void setMode(PainterMode mode, bool enabled=true); - void setModes(PainterModes modes); + QCPPainter(); + explicit QCPPainter(QPaintDevice *device); + + // getters: + bool antialiasing() const { + return testRenderHint(QPainter::Antialiasing); + } + PainterModes modes() const { + return mModes; + } + + // setters: + void setAntialiasing(bool enabled); + void setMode(PainterMode mode, bool enabled = true); + void setModes(PainterModes modes); + + // methods hiding non-virtual base class functions (QPainter bug workarounds): + bool begin(QPaintDevice *device); + void setPen(const QPen &pen); + void setPen(const QColor &color); + void setPen(Qt::PenStyle penStyle); + void drawLine(const QLineF &line); + void drawLine(const QPointF &p1, const QPointF &p2) { + drawLine(QLineF(p1, p2)); + } + void save(); + void restore(); + + // non-virtual methods: + void makeNonCosmetic(); - // methods hiding non-virtual base class functions (QPainter bug workarounds): - bool begin(QPaintDevice *device); - void setPen(const QPen &pen); - void setPen(const QColor &color); - void setPen(Qt::PenStyle penStyle); - void drawLine(const QLineF &line); - void drawLine(const QPointF &p1, const QPointF &p2) {drawLine(QLineF(p1, p2));} - void save(); - void restore(); - - // non-virtual methods: - void makeNonCosmetic(); - protected: - // property members: - PainterModes mModes; - bool mIsAntialiasing; - - // non-property members: - QStack mAntialiasingStack; + // property members: + PainterModes mModes; + bool mIsAntialiasing; + + // non-property members: + QStack mAntialiasingStack; }; Q_DECLARE_OPERATORS_FOR_FLAGS(QCPPainter::PainterModes) Q_DECLARE_METATYPE(QCPPainter::PainterMode) @@ -524,55 +590,61 @@ Q_DECLARE_METATYPE(QCPPainter::PainterMode) 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; - + 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; + // 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() Q_DECL_OVERRIDE; - - // 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; - + explicit QCPPaintBufferPixmap(const QSize &size, double devicePixelRatio); + virtual ~QCPPaintBufferPixmap() Q_DECL_OVERRIDE; + + // 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; + // non-property members: + QPixmap mBuffer; + + // reimplemented virtual methods: + virtual void reallocateBuffer() Q_DECL_OVERRIDE; }; @@ -580,21 +652,21 @@ protected: class QCP_LIB_DECL QCPPaintBufferGlPbuffer : public QCPAbstractPaintBuffer { public: - explicit QCPPaintBufferGlPbuffer(const QSize &size, double devicePixelRatio, int multisamples); - virtual ~QCPPaintBufferGlPbuffer() Q_DECL_OVERRIDE; - - // 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; - + explicit QCPPaintBufferGlPbuffer(const QSize &size, double devicePixelRatio, int multisamples); + virtual ~QCPPaintBufferGlPbuffer() Q_DECL_OVERRIDE; + + // 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; + // non-property members: + QGLPixelBuffer *mGlPBuffer; + int mMultisamples; + + // reimplemented virtual methods: + virtual void reallocateBuffer() Q_DECL_OVERRIDE; }; #endif // QCP_OPENGL_PBUFFER @@ -603,23 +675,23 @@ protected: class QCP_LIB_DECL QCPPaintBufferGlFbo : public QCPAbstractPaintBuffer { public: - explicit QCPPaintBufferGlFbo(const QSize &size, double devicePixelRatio, QWeakPointer glContext, QWeakPointer glPaintDevice); - virtual ~QCPPaintBufferGlFbo() Q_DECL_OVERRIDE; - - // 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; - + explicit QCPPaintBufferGlFbo(const QSize &size, double devicePixelRatio, QWeakPointer glContext, QWeakPointer glPaintDevice); + virtual ~QCPPaintBufferGlFbo() Q_DECL_OVERRIDE; + + // 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; + // non-property members: + QWeakPointer mGlContext; + QWeakPointer mGlPaintDevice; + QOpenGLFramebufferObject *mGlFrameBuffer; + + // reimplemented virtual methods: + virtual void reallocateBuffer() Q_DECL_OVERRIDE; }; #endif // QCP_OPENGL_FBO @@ -631,145 +703,166 @@ protected: class QCP_LIB_DECL QCPLayer : public QObject { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QCustomPlot* parentPlot READ parentPlot) - Q_PROPERTY(QString name READ name) - 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 + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(QCustomPlot *parentPlot READ parentPlot) + Q_PROPERTY(QString name READ name) + 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); - virtual ~QCPLayer(); - - // getters: - QCustomPlot *parentPlot() const { return mParentPlot; } - QString name() const { return mName; } - 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(); - + /*! + 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); + virtual ~QCPLayer(); + + // getters: + QCustomPlot *parentPlot() const { + return mParentPlot; + } + QString name() const { + return mName; + } + 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: - QCustomPlot *mParentPlot; - QString mName; - 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); - + // property members: + QCustomPlot *mParentPlot; + QString mName; + 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); + private: - Q_DISABLE_COPY(QCPLayer) - - friend class QCustomPlot; - friend class QCPLayerable; + Q_DISABLE_COPY(QCPLayer) + + friend class QCustomPlot; + friend class QCPLayerable; }; Q_DECLARE_METATYPE(QCPLayer::LayerMode) class QCP_LIB_DECL QCPLayerable : public QObject { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(bool visible READ visible WRITE setVisible) - Q_PROPERTY(QCustomPlot* parentPlot READ parentPlot) - Q_PROPERTY(QCPLayerable* parentLayerable READ parentLayerable) - Q_PROPERTY(QCPLayer* layer READ layer WRITE setLayer NOTIFY layerChanged) - Q_PROPERTY(bool antialiased READ antialiased WRITE setAntialiased) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(bool visible READ visible WRITE setVisible) + Q_PROPERTY(QCustomPlot *parentPlot READ parentPlot) + Q_PROPERTY(QCPLayerable *parentLayerable READ parentLayerable) + Q_PROPERTY(QCPLayer *layer READ layer WRITE setLayer NOTIFY layerChanged) + Q_PROPERTY(bool antialiased READ antialiased WRITE setAntialiased) + /// \endcond public: - QCPLayerable(QCustomPlot *plot, QString targetLayer=QString(), QCPLayerable *parentLayerable=nullptr); - virtual ~QCPLayerable(); - - // getters: - bool visible() const { return mVisible; } - QCustomPlot *parentPlot() const { return mParentPlot; } - QCPLayerable *parentLayerable() const { return mParentLayerable.data(); } - QCPLayer *layer() const { return mLayer; } - bool antialiased() const { return mAntialiased; } - - // setters: - void setVisible(bool on); - Q_SLOT bool setLayer(QCPLayer *layer); - bool setLayer(const QString &layerName); - void setAntialiased(bool enabled); - - // introduced virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const; + QCPLayerable(QCustomPlot *plot, QString targetLayer = QString(), QCPLayerable *parentLayerable = nullptr); + virtual ~QCPLayerable(); + + // getters: + bool visible() const { + return mVisible; + } + QCustomPlot *parentPlot() const { + return mParentPlot; + } + QCPLayerable *parentLayerable() const { + return mParentLayerable.data(); + } + QCPLayer *layer() const { + return mLayer; + } + bool antialiased() const { + return mAntialiased; + } + + // setters: + void setVisible(bool on); + Q_SLOT bool setLayer(QCPLayer *layer); + bool setLayer(const QString &layerName); + void setAntialiased(bool enabled); + + // introduced virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = nullptr) const; + + // non-property methods: + bool realVisibility() const; - // non-property methods: - bool realVisibility() const; - signals: - void layerChanged(QCPLayer *newLayer); - + void layerChanged(QCPLayer *newLayer); + protected: - // property members: - bool mVisible; - QCustomPlot *mParentPlot; - QPointer mParentLayerable; - QCPLayer *mLayer; - bool mAntialiased; - - // introduced virtual methods: - virtual void parentPlotInitialized(QCustomPlot *parentPlot); - virtual QCP::Interaction selectionCategory() const; - virtual QRect clipRect() const; - virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const = 0; - virtual void draw(QCPPainter *painter) = 0; - // 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); - void setParentLayerable(QCPLayerable* parentLayerable); - bool moveToLayer(QCPLayer *layer, bool prepend); - void applyAntialiasingHint(QCPPainter *painter, bool localAntialiased, QCP::AntialiasedElement overrideElement) const; - + // property members: + bool mVisible; + QCustomPlot *mParentPlot; + QPointer mParentLayerable; + QCPLayer *mLayer; + bool mAntialiased; + + // introduced virtual methods: + virtual void parentPlotInitialized(QCustomPlot *parentPlot); + virtual QCP::Interaction selectionCategory() const; + virtual QRect clipRect() const; + virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const = 0; + virtual void draw(QCPPainter *painter) = 0; + // 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); + void setParentLayerable(QCPLayerable *parentLayerable); + bool moveToLayer(QCPLayer *layer, bool prepend); + void applyAntialiasingHint(QCPPainter *painter, bool localAntialiased, QCP::AntialiasedElement overrideElement) const; + private: - Q_DISABLE_COPY(QCPLayerable) - - friend class QCustomPlot; - friend class QCPLayer; - friend class QCPAxisRect; + Q_DISABLE_COPY(QCPLayerable) + + friend class QCustomPlot; + friend class QCPLayer; + friend class QCPAxisRect; }; /* end of 'src/layer.h' */ @@ -781,42 +874,72 @@ private: class QCP_LIB_DECL QCPRange { public: - double lower, upper; - - QCPRange(); - QCPRange(double lower, double upper); - - bool operator==(const QCPRange& other) const { return lower == other.lower && upper == other.upper; } - bool operator!=(const QCPRange& other) const { return !(*this == other); } - - QCPRange &operator+=(const double& value) { lower+=value; upper+=value; return *this; } - QCPRange &operator-=(const double& value) { lower-=value; upper-=value; return *this; } - QCPRange &operator*=(const double& value) { lower*=value; upper*=value; return *this; } - QCPRange &operator/=(const double& value) { lower/=value; upper/=value; return *this; } - friend inline const QCPRange operator+(const QCPRange&, double); - friend inline const QCPRange operator+(double, const QCPRange&); - friend inline const QCPRange operator-(const QCPRange& range, double value); - friend inline const QCPRange operator*(const QCPRange& range, double value); - friend inline const QCPRange operator*(double value, const QCPRange& range); - friend inline const QCPRange operator/(const QCPRange& range, double value); - - 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 { return value >= lower && value <= upper; } - - static bool validRange(double lower, double upper); - static bool validRange(const QCPRange &range); - static const double minRange; - static const double maxRange; - + double lower, upper; + + QCPRange(); + QCPRange(double lower, double upper); + + bool operator==(const QCPRange &other) const { + return lower == other.lower && upper == other.upper; + } + bool operator!=(const QCPRange &other) const { + return !(*this == other); + } + + QCPRange &operator+=(const double &value) { + lower += value; + upper += value; + return *this; + } + QCPRange &operator-=(const double &value) { + lower -= value; + upper -= value; + return *this; + } + QCPRange &operator*=(const double &value) { + lower *= value; + upper *= value; + return *this; + } + QCPRange &operator/=(const double &value) { + lower /= value; + upper /= value; + return *this; + } + friend inline const QCPRange operator+(const QCPRange &, double); + friend inline const QCPRange operator+(double, const QCPRange &); + friend inline const QCPRange operator-(const QCPRange &range, double value); + friend inline const QCPRange operator*(const QCPRange &range, double value); + friend inline const QCPRange operator*(double value, const QCPRange &range); + friend inline const QCPRange operator/(const QCPRange &range, double value); + + 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 { + return value >= lower && value <= upper; + } + + static bool validRange(double lower, double upper); + static bool validRange(const QCPRange &range); + static const double minRange; + static const double maxRange; + }; Q_DECLARE_TYPEINFO(QCPRange, Q_MOVABLE_TYPE); @@ -833,61 +956,61 @@ inline QDebug operator<< (QDebug d, const QCPRange &range) /*! Adds \a value to both boundaries of the range. */ -inline const QCPRange operator+(const QCPRange& range, double value) +inline const QCPRange operator+(const QCPRange &range, double value) { - QCPRange result(range); - result += value; - return result; + QCPRange result(range); + result += value; + return result; } /*! Adds \a value to both boundaries of the range. */ -inline const QCPRange operator+(double value, const QCPRange& range) +inline const QCPRange operator+(double value, const QCPRange &range) { - QCPRange result(range); - result += value; - return result; + QCPRange result(range); + result += value; + return result; } /*! Subtracts \a value from both boundaries of the range. */ -inline const QCPRange operator-(const QCPRange& range, double value) +inline const QCPRange operator-(const QCPRange &range, double value) { - QCPRange result(range); - result -= value; - return result; + QCPRange result(range); + result -= value; + return result; } /*! Multiplies both boundaries of the range by \a value. */ -inline const QCPRange operator*(const QCPRange& range, double value) +inline const QCPRange operator*(const QCPRange &range, double value) { - QCPRange result(range); - result *= value; - return result; + QCPRange result(range); + result *= value; + return result; } /*! Multiplies both boundaries of the range by \a value. */ -inline const QCPRange operator*(double value, const QCPRange& range) +inline const QCPRange operator*(double value, const QCPRange &range) { - QCPRange result(range); - result *= value; - return result; + QCPRange result(range); + result *= value; + return result; } /*! Divides both boundaries of the range by \a value. */ -inline const QCPRange operator/(const QCPRange& range, double value) +inline const QCPRange operator/(const QCPRange &range, double value) { - QCPRange result(range); - result /= value; - return result; + QCPRange result(range); + result /= value; + return result; } /* end of 'src/axis/range.h' */ @@ -899,35 +1022,57 @@ inline const QCPRange operator/(const QCPRange& range, double value) 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; - + 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; + // property members: + int mBegin, mEnd; }; Q_DECLARE_TYPEINFO(QCPDataRange, Q_MOVABLE_TYPE); @@ -936,47 +1081,57 @@ 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; - + 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(); } + // property members: + QList mDataRanges; + + inline static bool lessThanDataRangeBegin(const QCPDataRange &a, const QCPDataRange &b) { + return a.begin() < b.begin(); + } }; Q_DECLARE_METATYPE(QCPDataSelection) @@ -985,84 +1140,84 @@ 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) +inline const QCPDataSelection operator+(const QCPDataSelection &a, const QCPDataSelection &b) { - QCPDataSelection result(a); - result += b; - return result; + 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) +inline const QCPDataSelection operator+(const QCPDataRange &a, const QCPDataSelection &b) { - QCPDataSelection result(a); - result += b; - return result; + 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) +inline const QCPDataSelection operator+(const QCPDataSelection &a, const QCPDataRange &b) { - QCPDataSelection result(a); - result += b; - return result; + 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) +inline const QCPDataSelection operator+(const QCPDataRange &a, const QCPDataRange &b) { - QCPDataSelection result(a); - result += b; - return result; + 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) +inline const QCPDataSelection operator-(const QCPDataSelection &a, const QCPDataSelection &b) { - QCPDataSelection result(a); - result -= b; - return result; + 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) +inline const QCPDataSelection operator-(const QCPDataRange &a, const QCPDataSelection &b) { - QCPDataSelection result(a); - result -= b; - return result; + 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) +inline const QCPDataSelection operator-(const QCPDataSelection &a, const QCPDataRange &b) { - QCPDataSelection result(a); - result -= b; - return result; + 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) +inline const QCPDataSelection operator-(const QCPDataRange &a, const QCPDataRange &b) { - QCPDataSelection result(a); - result -= b; - return result; + QCPDataSelection result(a); + result -= b; + return result; } /*! \relates QCPDataRange @@ -1071,8 +1226,8 @@ inline const QCPDataSelection operator-(const QCPDataRange& a, const QCPDataRang */ inline QDebug operator<< (QDebug d, const QCPDataRange &dataRange) { - d.nospace() << "QCPDataRange(" << dataRange.begin() << ", " << dataRange.end() << ")"; - return d; + d.nospace() << "QCPDataRange(" << dataRange.begin() << ", " << dataRange.end() << ")"; + return d; } /*! \relates QCPDataSelection @@ -1082,11 +1237,11 @@ inline QDebug operator<< (QDebug d, const QCPDataRange &dataRange) 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); } - bool isEmpty() const; - void clear(); - + explicit QCPMarginGroup(QCustomPlot *parentPlot); + virtual ~QCPMarginGroup(); + + // non-virtual methods: + QList elements(QCP::MarginSide side) const { + return mChildren.value(side); + } + bool isEmpty() const; + void clear(); + protected: - // non-property members: - QCustomPlot *mParentPlot; - QHash > mChildren; - - // introduced virtual methods: - virtual int commonMargin(QCP::MarginSide side) const; - - // non-virtual methods: - void addChild(QCP::MarginSide side, QCPLayoutElement *element); - void removeChild(QCP::MarginSide side, QCPLayoutElement *element); - + // non-property members: + QCustomPlot *mParentPlot; + QHash > mChildren; + + // introduced virtual methods: + virtual int commonMargin(QCP::MarginSide side) const; + + // non-virtual methods: + void addChild(QCP::MarginSide side, QCPLayoutElement *element); + void removeChild(QCP::MarginSide side, QCPLayoutElement *element); + private: - Q_DISABLE_COPY(QCPMarginGroup) - - friend class QCPLayoutElement; + Q_DISABLE_COPY(QCPMarginGroup) + + friend class QCPLayoutElement; }; class QCP_LIB_DECL QCPLayoutElement : public QCPLayerable { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QCPLayout* layout READ layout) - Q_PROPERTY(QRect rect READ rect) - Q_PROPERTY(QRect outerRect READ outerRect WRITE setOuterRect) - Q_PROPERTY(QMargins margins READ margins WRITE setMargins) - Q_PROPERTY(QMargins minimumMargins READ minimumMargins WRITE setMinimumMargins) - Q_PROPERTY(QSize minimumSize READ minimumSize WRITE setMinimumSize) - Q_PROPERTY(QSize maximumSize READ maximumSize WRITE setMaximumSize) - Q_PROPERTY(SizeConstraintRect sizeConstraintRect READ sizeConstraintRect WRITE setSizeConstraintRect) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(QCPLayout *layout READ layout) + Q_PROPERTY(QRect rect READ rect) + Q_PROPERTY(QRect outerRect READ outerRect WRITE setOuterRect) + Q_PROPERTY(QMargins margins READ margins WRITE setMargins) + Q_PROPERTY(QMargins minimumMargins READ minimumMargins WRITE setMinimumMargins) + Q_PROPERTY(QSize minimumSize READ minimumSize WRITE setMinimumSize) + Q_PROPERTY(QSize maximumSize READ maximumSize WRITE setMaximumSize) + Q_PROPERTY(SizeConstraintRect sizeConstraintRect READ sizeConstraintRect WRITE setSizeConstraintRect) + /// \endcond public: - /*! - Defines the phases of the update process, that happens just before a replot. At each phase, - \ref update is called with the according UpdatePhase value. - */ - enum UpdatePhase { upPreparation ///< Phase used for any type of preparation that needs to be done before margin calculation and layout - ,upMargins ///< Phase in which the margins are calculated and set - ,upLayout ///< Final phase in which the layout system places the rects of the elements - }; - Q_ENUMS(UpdatePhase) - - /*! - Defines to which rect of a layout element the size constraints that can be set via \ref - setMinimumSize and \ref setMaximumSize apply. The outer rect (\ref outerRect) includes the - margins (e.g. in the case of a QCPAxisRect the axis labels), whereas the inner rect (\ref rect) - does not. - - \see setSizeConstraintRect - */ - enum SizeConstraintRect { scrInnerRect ///< Minimum/Maximum size constraints apply to inner rect - , scrOuterRect ///< Minimum/Maximum size constraints apply to outer rect, thus include layout element margins - }; - Q_ENUMS(SizeConstraintRect) + /*! + Defines the phases of the update process, that happens just before a replot. At each phase, + \ref update is called with the according UpdatePhase value. + */ + enum UpdatePhase { upPreparation ///< Phase used for any type of preparation that needs to be done before margin calculation and layout + , upMargins ///< Phase in which the margins are calculated and set + , upLayout ///< Final phase in which the layout system places the rects of the elements + }; + Q_ENUMS(UpdatePhase) + + /*! + Defines to which rect of a layout element the size constraints that can be set via \ref + setMinimumSize and \ref setMaximumSize apply. The outer rect (\ref outerRect) includes the + margins (e.g. in the case of a QCPAxisRect the axis labels), whereas the inner rect (\ref rect) + does not. + + \see setSizeConstraintRect + */ + enum SizeConstraintRect { scrInnerRect ///< Minimum/Maximum size constraints apply to inner rect + , scrOuterRect ///< Minimum/Maximum size constraints apply to outer rect, thus include layout element margins + }; + Q_ENUMS(SizeConstraintRect) + + explicit QCPLayoutElement(QCustomPlot *parentPlot = nullptr); + virtual ~QCPLayoutElement() Q_DECL_OVERRIDE; + + // getters: + QCPLayout *layout() const { + return mParentLayout; + } + QRect rect() const { + return mRect; + } + QRect outerRect() const { + return mOuterRect; + } + QMargins margins() const { + return mMargins; + } + QMargins minimumMargins() const { + return mMinimumMargins; + } + QCP::MarginSides autoMargins() const { + return mAutoMargins; + } + QSize minimumSize() const { + return mMinimumSize; + } + QSize maximumSize() const { + return mMaximumSize; + } + SizeConstraintRect sizeConstraintRect() const { + return mSizeConstraintRect; + } + QCPMarginGroup *marginGroup(QCP::MarginSide side) const { + return mMarginGroups.value(side, nullptr); + } + QHash marginGroups() const { + return mMarginGroups; + } + + // setters: + void setOuterRect(const QRect &rect); + void setMargins(const QMargins &margins); + void setMinimumMargins(const QMargins &margins); + void setAutoMargins(QCP::MarginSides sides); + void setMinimumSize(const QSize &size); + void setMinimumSize(int width, int height); + void setMaximumSize(const QSize &size); + void setMaximumSize(int width, int height); + void setSizeConstraintRect(SizeConstraintRect constraintRect); + void setMarginGroup(QCP::MarginSides sides, QCPMarginGroup *group); + + // introduced virtual methods: + virtual void update(UpdatePhase phase); + virtual QSize minimumOuterSizeHint() const; + virtual QSize maximumOuterSizeHint() const; + virtual QList elements(bool recursive) const; + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = nullptr) const Q_DECL_OVERRIDE; - explicit QCPLayoutElement(QCustomPlot *parentPlot=nullptr); - virtual ~QCPLayoutElement() Q_DECL_OVERRIDE; - - // getters: - QCPLayout *layout() const { return mParentLayout; } - QRect rect() const { return mRect; } - QRect outerRect() const { return mOuterRect; } - QMargins margins() const { return mMargins; } - QMargins minimumMargins() const { return mMinimumMargins; } - QCP::MarginSides autoMargins() const { return mAutoMargins; } - QSize minimumSize() const { return mMinimumSize; } - QSize maximumSize() const { return mMaximumSize; } - SizeConstraintRect sizeConstraintRect() const { return mSizeConstraintRect; } - QCPMarginGroup *marginGroup(QCP::MarginSide side) const { return mMarginGroups.value(side, nullptr); } - QHash marginGroups() const { return mMarginGroups; } - - // setters: - void setOuterRect(const QRect &rect); - void setMargins(const QMargins &margins); - void setMinimumMargins(const QMargins &margins); - void setAutoMargins(QCP::MarginSides sides); - void setMinimumSize(const QSize &size); - void setMinimumSize(int width, int height); - void setMaximumSize(const QSize &size); - void setMaximumSize(int width, int height); - void setSizeConstraintRect(SizeConstraintRect constraintRect); - void setMarginGroup(QCP::MarginSides sides, QCPMarginGroup *group); - - // introduced virtual methods: - virtual void update(UpdatePhase phase); - virtual QSize minimumOuterSizeHint() const; - virtual QSize maximumOuterSizeHint() const; - virtual QList elements(bool recursive) const; - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE; - protected: - // property members: - QCPLayout *mParentLayout; - QSize mMinimumSize, mMaximumSize; - SizeConstraintRect mSizeConstraintRect; - QRect mRect, mOuterRect; - QMargins mMargins, mMinimumMargins; - QCP::MarginSides mAutoMargins; - QHash mMarginGroups; - - // introduced virtual methods: - virtual int calculateAutoMargin(QCP::MarginSide side); - virtual void layoutChanged(); - - // reimplemented virtual methods: - 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; + // property members: + QCPLayout *mParentLayout; + QSize mMinimumSize, mMaximumSize; + SizeConstraintRect mSizeConstraintRect; + QRect mRect, mOuterRect; + QMargins mMargins, mMinimumMargins; + QCP::MarginSides mAutoMargins; + QHash mMarginGroups; + + // introduced virtual methods: + virtual int calculateAutoMargin(QCP::MarginSide side); + virtual void layoutChanged(); + + // reimplemented virtual methods: + 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) - - friend class QCustomPlot; - friend class QCPLayout; - friend class QCPMarginGroup; + Q_DISABLE_COPY(QCPLayoutElement) + + friend class QCustomPlot; + friend class QCPLayout; + friend class QCPMarginGroup; }; Q_DECLARE_METATYPE(QCPLayoutElement::UpdatePhase) class QCP_LIB_DECL QCPLayout : public QCPLayoutElement { - Q_OBJECT + Q_OBJECT public: - explicit QCPLayout(); - - // reimplemented virtual methods: - 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; - virtual QCPLayoutElement* elementAt(int index) const = 0; - virtual QCPLayoutElement* takeAt(int index) = 0; - virtual bool take(QCPLayoutElement* element) = 0; - virtual void simplify(); - - // non-virtual methods: - bool removeAt(int index); - bool remove(QCPLayoutElement* element); - void clear(); - + explicit QCPLayout(); + + // reimplemented virtual methods: + 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; + virtual QCPLayoutElement *elementAt(int index) const = 0; + virtual QCPLayoutElement *takeAt(int index) = 0; + virtual bool take(QCPLayoutElement *element) = 0; + virtual void simplify(); + + // non-virtual methods: + bool removeAt(int index); + bool remove(QCPLayoutElement *element); + void clear(); + protected: - // introduced virtual methods: - virtual void updateLayout(); - - // non-virtual methods: - void sizeConstraintsChanged() const; - void adoptElement(QCPLayoutElement *el); - void releaseElement(QCPLayoutElement *el); - QVector getSectionSizes(QVector maxSizes, QVector minSizes, QVector stretchFactors, int totalSize) const; - static QSize getFinalMinimumOuterSize(const QCPLayoutElement *el); - static QSize getFinalMaximumOuterSize(const QCPLayoutElement *el); - + // introduced virtual methods: + virtual void updateLayout(); + + // non-virtual methods: + void sizeConstraintsChanged() const; + void adoptElement(QCPLayoutElement *el); + void releaseElement(QCPLayoutElement *el); + QVector getSectionSizes(QVector maxSizes, QVector minSizes, QVector stretchFactors, int totalSize) const; + static QSize getFinalMinimumOuterSize(const QCPLayoutElement *el); + static QSize getFinalMaximumOuterSize(const QCPLayoutElement *el); + private: - Q_DISABLE_COPY(QCPLayout) - friend class QCPLayoutElement; + Q_DISABLE_COPY(QCPLayout) + friend class QCPLayoutElement; }; class QCP_LIB_DECL QCPLayoutGrid : public QCPLayout { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(int rowCount READ rowCount) - Q_PROPERTY(int columnCount READ columnCount) - Q_PROPERTY(QList columnStretchFactors READ columnStretchFactors WRITE setColumnStretchFactors) - 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 + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(int rowCount READ rowCount) + Q_PROPERTY(int columnCount READ columnCount) + Q_PROPERTY(QList columnStretchFactors READ columnStretchFactors WRITE setColumnStretchFactors) + 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() Q_DECL_OVERRIDE; - - // getters: - 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); - void setColumnStretchFactors(const QList &factors); - void setRowStretchFactor(int row, double factor); - 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() 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 minimumOuterSizeHint() const Q_DECL_OVERRIDE; - virtual QSize maximumOuterSizeHint() 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; - + /*! + 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() Q_DECL_OVERRIDE; + + // getters: + 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); + void setColumnStretchFactors(const QList &factors); + void setRowStretchFactor(int row, double factor); + 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() 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 minimumOuterSizeHint() const Q_DECL_OVERRIDE; + virtual QSize maximumOuterSizeHint() 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: - QList > mElements; - QList mColumnStretchFactors; - QList mRowStretchFactors; - int mColumnSpacing, mRowSpacing; - int mWrap; - FillOrder mFillOrder; - - // non-virtual methods: - void getMinimumRowColSizes(QVector *minColWidths, QVector *minRowHeights) const; - void getMaximumRowColSizes(QVector *maxColWidths, QVector *maxRowHeights) const; - + // property members: + QList > mElements; + QList mColumnStretchFactors; + QList mRowStretchFactors; + int mColumnSpacing, mRowSpacing; + int mWrap; + FillOrder mFillOrder; + + // non-virtual methods: + void getMinimumRowColSizes(QVector *minColWidths, QVector *minRowHeights) const; + void getMaximumRowColSizes(QVector *maxColWidths, QVector *maxRowHeights) const; + private: - Q_DISABLE_COPY(QCPLayoutGrid) + Q_DISABLE_COPY(QCPLayoutGrid) }; Q_DECLARE_METATYPE(QCPLayoutGrid::FillOrder) class QCP_LIB_DECL QCPLayoutInset : public QCPLayout { - Q_OBJECT + Q_OBJECT public: - /*! - Defines how the placement and sizing is handled for a certain element in a QCPLayoutInset. - */ - 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() Q_DECL_OVERRIDE; - - // getters: - InsetPlacement insetPlacement(int index) const; - Qt::Alignment insetAlignment(int index) const; - QRectF insetRect(int index) const; - - // setters: - void setInsetPlacement(int index, InsetPlacement placement); - void setInsetAlignment(int index, Qt::Alignment alignment); - void setInsetRect(int index, const QRectF &rect); - - // reimplemented virtual methods: - 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=nullptr) const Q_DECL_OVERRIDE; - - // non-virtual methods: - void addElement(QCPLayoutElement *element, Qt::Alignment alignment); - void addElement(QCPLayoutElement *element, const QRectF &rect); - + /*! + Defines how the placement and sizing is handled for a certain element in a QCPLayoutInset. + */ + 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() Q_DECL_OVERRIDE; + + // getters: + InsetPlacement insetPlacement(int index) const; + Qt::Alignment insetAlignment(int index) const; + QRectF insetRect(int index) const; + + // setters: + void setInsetPlacement(int index, InsetPlacement placement); + void setInsetAlignment(int index, Qt::Alignment alignment); + void setInsetRect(int index, const QRectF &rect); + + // reimplemented virtual methods: + 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 = nullptr) const Q_DECL_OVERRIDE; + + // non-virtual methods: + void addElement(QCPLayoutElement *element, Qt::Alignment alignment); + void addElement(QCPLayoutElement *element, const QRectF &rect); + protected: - // property members: - QList mElements; - QList mInsetPlacement; - QList mInsetAlignment; - QList mInsetRect; - + // property members: + QList mElements; + QList mInsetPlacement; + QList mInsetAlignment; + QList mInsetRect; + private: - Q_DISABLE_COPY(QCPLayoutInset) + Q_DISABLE_COPY(QCPLayoutInset) }; Q_DECLARE_METATYPE(QCPLayoutInset::InsetPlacement) @@ -1477,58 +1684,66 @@ Q_DECLARE_METATYPE(QCPLayoutInset::InsetPlacement) class QCP_LIB_DECL QCPLineEnding { - Q_GADGET + Q_GADGET public: - /*! - Defines the type of ending decoration for line-like items, e.g. an arrow. - - \image html QCPLineEnding.png - - The width and length of these decorations can be controlled with the functions \ref setWidth - and \ref setLength. Some decorations like \ref esDisc, \ref esSquare, \ref esDiamond and \ref esBar only - support a width, the length property is ignored. - - \see QCPItemLine::setHead, QCPItemLine::setTail, QCPItemCurve::setHead, QCPItemCurve::setTail, QCPAxis::setLowerEnding, QCPAxis::setUpperEnding - */ - 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 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); - - // getters: - EndingStyle style() const { return mStyle; } - double width() const { return mWidth; } - double length() const { return mLength; } - bool inverted() const { return mInverted; } - - // setters: - void setStyle(EndingStyle style); - void setWidth(double width); - void setLength(double length); - void setInverted(bool inverted); - - // non-property methods: - double boundingDistance() const; - double realLength() const; - void draw(QCPPainter *painter, const QCPVector2D &pos, const QCPVector2D &dir) const; - void draw(QCPPainter *painter, const QCPVector2D &pos, double angle) const; - + /*! + Defines the type of ending decoration for line-like items, e.g. an arrow. + + \image html QCPLineEnding.png + + The width and length of these decorations can be controlled with the functions \ref setWidth + and \ref setLength. Some decorations like \ref esDisc, \ref esSquare, \ref esDiamond and \ref esBar only + support a width, the length property is ignored. + + \see QCPItemLine::setHead, QCPItemLine::setTail, QCPItemCurve::setHead, QCPItemCurve::setTail, QCPAxis::setLowerEnding, QCPAxis::setUpperEnding + */ + 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 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); + + // getters: + EndingStyle style() const { + return mStyle; + } + double width() const { + return mWidth; + } + double length() const { + return mLength; + } + bool inverted() const { + return mInverted; + } + + // setters: + void setStyle(EndingStyle style); + void setWidth(double width); + void setLength(double length); + void setInverted(bool inverted); + + // non-property methods: + double boundingDistance() const; + double realLength() 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: - EndingStyle mStyle; - double mWidth, mLength; - bool mInverted; + // property members: + EndingStyle mStyle; + double mWidth, mLength; + bool mInverted; }; Q_DECLARE_TYPEINFO(QCPLineEnding, Q_MOVABLE_TYPE); Q_DECLARE_METATYPE(QCPLineEnding::EndingStyle) @@ -1541,133 +1756,153 @@ Q_DECLARE_METATYPE(QCPLineEnding::EndingStyle) class QCPLabelPainterPrivate { - Q_GADGET + Q_GADGET public: - /*! - TODO - */ - enum AnchorMode { amRectangular ///< - ,amSkewedUpright ///< - ,amSkewedRotated ///< - }; - Q_ENUMS(AnchorMode) - - /*! - TODO - */ - enum AnchorReferenceType { artNormal ///< - ,artTangent ///< - }; - Q_ENUMS(AnchorReferenceType) - - /*! - TODO - */ - enum AnchorSide { asLeft ///< - ,asRight ///< - ,asTop ///< - ,asBottom ///< - ,asTopLeft - ,asTopRight - ,asBottomRight - ,asBottomLeft - }; - Q_ENUMS(AnchorSide) - - explicit QCPLabelPainterPrivate(QCustomPlot *parentPlot); - virtual ~QCPLabelPainterPrivate(); - - // setters: - void setAnchorSide(AnchorSide side); - void setAnchorMode(AnchorMode mode); - void setAnchorReference(const QPointF &pixelPoint); - void setAnchorReferenceType(AnchorReferenceType type); - void setFont(const QFont &font); - void setColor(const QColor &color); - void setPadding(int padding); - void setRotation(double rotation); - void setSubstituteExponent(bool enabled); - void setMultiplicationSymbol(QChar symbol); - void setAbbreviateDecimalPowers(bool enabled); - void setCacheSize(int labelCount); - - // getters: - AnchorMode anchorMode() const { return mAnchorMode; } - AnchorSide anchorSide() const { return mAnchorSide; } - QPointF anchorReference() const { return mAnchorReference; } - AnchorReferenceType anchorReferenceType() const { return mAnchorReferenceType; } - QFont font() const { return mFont; } - QColor color() const { return mColor; } - int padding() const { return mPadding; } - double rotation() const { return mRotation; } - bool substituteExponent() const { return mSubstituteExponent; } - QChar multiplicationSymbol() const { return mMultiplicationSymbol; } - bool abbreviateDecimalPowers() const { return mAbbreviateDecimalPowers; } - int cacheSize() const; - - //virtual int size() const; - - // non-property methods: - void drawTickLabel(QCPPainter *painter, const QPointF &tickPos, const QString &text); - void clearCache(); - - // constants that may be used with setMultiplicationSymbol: - static const QChar SymbolDot; - static const QChar SymbolCross; - -protected: - struct CachedLabel - { - QPoint offset; - QPixmap pixmap; - }; - struct LabelData - { - AnchorSide side; - double rotation; // angle in degrees - QTransform transform; // the transform about the label anchor which is at (0, 0). Does not contain final absolute x/y positioning on the plot/axis - QString basePart, expPart, suffixPart; - QRect baseBounds, expBounds, suffixBounds; - QRect totalBounds; // is in a coordinate system where label top left is at (0, 0) - QRect rotatedTotalBounds; // is in a coordinate system where the label anchor is at (0, 0) - QFont baseFont, expFont; - QColor color; - }; - - // property members: - AnchorMode mAnchorMode; - AnchorSide mAnchorSide; - QPointF mAnchorReference; - AnchorReferenceType mAnchorReferenceType; - QFont mFont; - QColor mColor; - int mPadding; - double mRotation; // this is the rotation applied uniformly to all labels, not the heterogeneous rotation in amCircularRotated mode - bool mSubstituteExponent; - QChar mMultiplicationSymbol; - bool mAbbreviateDecimalPowers; - // non-property members: - QCustomPlot *mParentPlot; - QByteArray mLabelParameterHash; // to determine whether mLabelCache needs to be cleared due to changed parameters - QCache mLabelCache; - QRect mAxisSelectionBox, mTickLabelsSelectionBox, mLabelSelectionBox; - int mLetterCapHeight, mLetterDescent; - - // introduced virtual methods: - virtual void drawLabelMaybeCached(QCPPainter *painter, const QFont &font, const QColor &color, const QPointF &pos, AnchorSide side, double rotation, const QString &text); - virtual QByteArray generateLabelParameterHash() const; // TODO: get rid of this in favor of invalidation flag upon setters? + /*! + TODO + */ + enum AnchorMode { amRectangular ///< + , amSkewedUpright ///< + , amSkewedRotated ///< + }; + Q_ENUMS(AnchorMode) - // non-virtual methods: - QPointF getAnchorPos(const QPointF &tickPos); - void drawText(QCPPainter *painter, const QPointF &pos, const LabelData &labelData) const; - LabelData getTickLabelData(const QFont &font, const QColor &color, double rotation, AnchorSide side, const QString &text) const; - void applyAnchorTransform(LabelData &labelData) const; - //void getMaxTickLabelSize(const QFont &font, const QString &text, QSize *tickLabelsSize) const; - CachedLabel *createCachedLabel(const LabelData &labelData) const; - QByteArray cacheKey(const QString &text, const QColor &color, double rotation, AnchorSide side) const; - AnchorSide skewedAnchorSide(const QPointF &tickPos, double sideExpandHorz, double sideExpandVert) const; - AnchorSide rotationCorrectedSide(AnchorSide side, double rotation) const; - void analyzeFontMetrics(); + /*! + TODO + */ + enum AnchorReferenceType { artNormal ///< + , artTangent ///< + }; + Q_ENUMS(AnchorReferenceType) + + /*! + TODO + */ + enum AnchorSide { asLeft ///< + , asRight ///< + , asTop ///< + , asBottom ///< + , asTopLeft + , asTopRight + , asBottomRight + , asBottomLeft + }; + Q_ENUMS(AnchorSide) + + explicit QCPLabelPainterPrivate(QCustomPlot *parentPlot); + virtual ~QCPLabelPainterPrivate(); + + // setters: + void setAnchorSide(AnchorSide side); + void setAnchorMode(AnchorMode mode); + void setAnchorReference(const QPointF &pixelPoint); + void setAnchorReferenceType(AnchorReferenceType type); + void setFont(const QFont &font); + void setColor(const QColor &color); + void setPadding(int padding); + void setRotation(double rotation); + void setSubstituteExponent(bool enabled); + void setMultiplicationSymbol(QChar symbol); + void setAbbreviateDecimalPowers(bool enabled); + void setCacheSize(int labelCount); + + // getters: + AnchorMode anchorMode() const { + return mAnchorMode; + } + AnchorSide anchorSide() const { + return mAnchorSide; + } + QPointF anchorReference() const { + return mAnchorReference; + } + AnchorReferenceType anchorReferenceType() const { + return mAnchorReferenceType; + } + QFont font() const { + return mFont; + } + QColor color() const { + return mColor; + } + int padding() const { + return mPadding; + } + double rotation() const { + return mRotation; + } + bool substituteExponent() const { + return mSubstituteExponent; + } + QChar multiplicationSymbol() const { + return mMultiplicationSymbol; + } + bool abbreviateDecimalPowers() const { + return mAbbreviateDecimalPowers; + } + int cacheSize() const; + + //virtual int size() const; + + // non-property methods: + void drawTickLabel(QCPPainter *painter, const QPointF &tickPos, const QString &text); + void clearCache(); + + // constants that may be used with setMultiplicationSymbol: + static const QChar SymbolDot; + static const QChar SymbolCross; + +protected: + struct CachedLabel { + QPoint offset; + QPixmap pixmap; + }; + struct LabelData { + AnchorSide side; + double rotation; // angle in degrees + QTransform transform; // the transform about the label anchor which is at (0, 0). Does not contain final absolute x/y positioning on the plot/axis + QString basePart, expPart, suffixPart; + QRect baseBounds, expBounds, suffixBounds; + QRect totalBounds; // is in a coordinate system where label top left is at (0, 0) + QRect rotatedTotalBounds; // is in a coordinate system where the label anchor is at (0, 0) + QFont baseFont, expFont; + QColor color; + }; + + // property members: + AnchorMode mAnchorMode; + AnchorSide mAnchorSide; + QPointF mAnchorReference; + AnchorReferenceType mAnchorReferenceType; + QFont mFont; + QColor mColor; + int mPadding; + double mRotation; // this is the rotation applied uniformly to all labels, not the heterogeneous rotation in amCircularRotated mode + bool mSubstituteExponent; + QChar mMultiplicationSymbol; + bool mAbbreviateDecimalPowers; + // non-property members: + QCustomPlot *mParentPlot; + QByteArray mLabelParameterHash; // to determine whether mLabelCache needs to be cleared due to changed parameters + QCache mLabelCache; + QRect mAxisSelectionBox, mTickLabelsSelectionBox, mLabelSelectionBox; + int mLetterCapHeight, mLetterDescent; + + // introduced virtual methods: + virtual void drawLabelMaybeCached(QCPPainter *painter, const QFont &font, const QColor &color, const QPointF &pos, AnchorSide side, double rotation, const QString &text); + virtual QByteArray generateLabelParameterHash() const; // TODO: get rid of this in favor of invalidation flag upon setters? + + // non-virtual methods: + QPointF getAnchorPos(const QPointF &tickPos); + void drawText(QCPPainter *painter, const QPointF &pos, const LabelData &labelData) const; + LabelData getTickLabelData(const QFont &font, const QColor &color, double rotation, AnchorSide side, const QString &text) const; + void applyAnchorTransform(LabelData &labelData) const; + //void getMaxTickLabelSize(const QFont &font, const QString &text, QSize *tickLabelsSize) const; + CachedLabel *createCachedLabel(const LabelData &labelData) const; + QByteArray cacheKey(const QString &text, const QColor &color, double rotation, AnchorSide side) const; + AnchorSide skewedAnchorSide(const QPointF &tickPos, double sideExpandHorz, double sideExpandVert) const; + AnchorSide rotationCorrectedSide(AnchorSide side, double rotation) const; + void analyzeFontMetrics(); }; Q_DECLARE_METATYPE(QCPLabelPainterPrivate::AnchorMode) Q_DECLARE_METATYPE(QCPLabelPainterPrivate::AnchorSide) @@ -1681,59 +1916,64 @@ Q_DECLARE_METATYPE(QCPLabelPainterPrivate::AnchorSide) class QCP_LIB_DECL QCPAxisTicker { - Q_GADGET + 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); - + /*! + 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=nullptr) const; - double cleanMantissa(double input) const; - + // 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 = nullptr) const; + double cleanMantissa(double input) const; + private: - Q_DISABLE_COPY(QCPAxisTicker) - + Q_DISABLE_COPY(QCPAxisTicker) + }; Q_DECLARE_METATYPE(QCPAxisTicker::TickStepStrategy) Q_DECLARE_METATYPE(QSharedPointer) @@ -1747,44 +1987,50 @@ Q_DECLARE_METATYPE(QSharedPointer) class QCP_LIB_DECL QCPAxisTickerDateTime : public QCPAxisTicker { public: - QCPAxisTickerDateTime(); - - // getters: - QString dateTimeFormat() const { return mDateTimeFormat; } - Qt::TimeSpec dateTimeSpec() const { return mDateTimeSpec; } + QCPAxisTickerDateTime(); + + // getters: + QString dateTimeFormat() const { + return mDateTimeFormat; + } + Qt::TimeSpec dateTimeSpec() const { + return mDateTimeSpec; + } # if QT_VERSION >= QT_VERSION_CHECK(5, 2, 0) - QTimeZone timeZone() const { return mTimeZone; } + QTimeZone timeZone() const { + return mTimeZone; + } #endif - - // setters: - void setDateTimeFormat(const QString &format); - void setDateTimeSpec(Qt::TimeSpec spec); + + // setters: + void setDateTimeFormat(const QString &format); + void setDateTimeSpec(Qt::TimeSpec spec); # if QT_VERSION >= QT_VERSION_CHECK(5, 2, 0) - void setTimeZone(const QTimeZone &zone); + void setTimeZone(const QTimeZone &zone); # endif - 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, Qt::TimeSpec timeSpec=Qt::LocalTime); - + 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, Qt::TimeSpec timeSpec = Qt::LocalTime); + protected: - // property members: - QString mDateTimeFormat; - Qt::TimeSpec mDateTimeSpec; + // property members: + QString mDateTimeFormat; + Qt::TimeSpec mDateTimeSpec; # if QT_VERSION >= QT_VERSION_CHECK(5, 2, 0) - QTimeZone mTimeZone; + QTimeZone mTimeZone; # endif - // 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; + // 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' */ @@ -1795,47 +2041,51 @@ protected: class QCP_LIB_DECL QCPAxisTickerTime : public QCPAxisTicker { - Q_GADGET + Q_GADGET public: - /*! - Defines the logical units in which fractions of time spans can be expressed. - - \see setFieldWidth, setTimeFormat - */ - enum TimeUnit { tuMilliseconds ///< Milliseconds, one thousandth of a second (%%z in \ref setTimeFormat) - ,tuSeconds ///< Seconds (%%s in \ref setTimeFormat) - ,tuMinutes ///< Minutes (%%m in \ref setTimeFormat) - ,tuHours ///< Hours (%%h in \ref setTimeFormat) - ,tuDays ///< Days (%%d in \ref setTimeFormat) - }; - Q_ENUMS(TimeUnit) - - QCPAxisTickerTime(); + /*! + Defines the logical units in which fractions of time spans can be expressed. + + \see setFieldWidth, setTimeFormat + */ + enum TimeUnit { tuMilliseconds ///< Milliseconds, one thousandth of a second (%%z in \ref setTimeFormat) + , tuSeconds ///< Seconds (%%s in \ref setTimeFormat) + , tuMinutes ///< Minutes (%%m in \ref setTimeFormat) + , tuHours ///< Hours (%%h in \ref setTimeFormat) + , tuDays ///< Days (%%d in \ref setTimeFormat) + }; + 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); - // 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; + // 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) @@ -1847,37 +2097,41 @@ Q_DECLARE_METATYPE(QCPAxisTickerTime::TimeUnit) class QCP_LIB_DECL QCPAxisTickerFixed : public QCPAxisTicker { - Q_GADGET + 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); - + /*! + 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; + // property members: + double mTickStep; + ScaleStrategy mScaleStrategy; + + // reimplemented virtual methods: + virtual double getTickStep(const QCPRange &range) Q_DECL_OVERRIDE; }; Q_DECLARE_METATYPE(QCPAxisTickerFixed::ScaleStrategy) @@ -1890,33 +2144,37 @@ Q_DECLARE_METATYPE(QCPAxisTickerFixed::ScaleStrategy) 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, const QString &label); - void addTicks(const QMap &ticks); - void addTicks(const QVector &positions, const QVector &labels); - + 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, const 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; + // 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' */ @@ -1927,54 +2185,62 @@ protected: class QCP_LIB_DECL QCPAxisTickerPi : public QCPAxisTicker { - Q_GADGET + 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); - + /*! + 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; + // 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) @@ -1987,27 +2253,31 @@ Q_DECLARE_METATYPE(QCPAxisTickerPi::FractionStyle) 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); - + 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 int getSubTickCount(double tickStep) Q_DECL_OVERRIDE; - virtual QVector createTickVector(double tickStep, const QCPRange &range) Q_DECL_OVERRIDE; + // property members: + double mLogBase; + int mSubTickCount; + + // non-property members: + double mLogBaseLnInv; + + // reimplemented virtual methods: + 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' */ @@ -2016,353 +2286,432 @@ protected: /* including file 'src/axis/axis.h' */ /* modified 2021-03-29T02:30:44, size 20913 */ -class QCP_LIB_DECL QCPGrid :public QCPLayerable +class QCP_LIB_DECL QCPGrid : public QCPLayerable { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(bool subGridVisible READ subGridVisible WRITE setSubGridVisible) - Q_PROPERTY(bool antialiasedSubGrid READ antialiasedSubGrid WRITE setAntialiasedSubGrid) - Q_PROPERTY(bool antialiasedZeroLine READ antialiasedZeroLine WRITE setAntialiasedZeroLine) - Q_PROPERTY(QPen pen READ pen WRITE setPen) - Q_PROPERTY(QPen subGridPen READ subGridPen WRITE setSubGridPen) - Q_PROPERTY(QPen zeroLinePen READ zeroLinePen WRITE setZeroLinePen) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(bool subGridVisible READ subGridVisible WRITE setSubGridVisible) + Q_PROPERTY(bool antialiasedSubGrid READ antialiasedSubGrid WRITE setAntialiasedSubGrid) + Q_PROPERTY(bool antialiasedZeroLine READ antialiasedZeroLine WRITE setAntialiasedZeroLine) + Q_PROPERTY(QPen pen READ pen WRITE setPen) + Q_PROPERTY(QPen subGridPen READ subGridPen WRITE setSubGridPen) + Q_PROPERTY(QPen zeroLinePen READ zeroLinePen WRITE setZeroLinePen) + /// \endcond public: - explicit QCPGrid(QCPAxis *parentAxis); - - // getters: - bool subGridVisible() const { return mSubGridVisible; } - bool antialiasedSubGrid() const { return mAntialiasedSubGrid; } - bool antialiasedZeroLine() const { return mAntialiasedZeroLine; } - QPen pen() const { return mPen; } - QPen subGridPen() const { return mSubGridPen; } - QPen zeroLinePen() const { return mZeroLinePen; } - - // setters: - void setSubGridVisible(bool visible); - void setAntialiasedSubGrid(bool enabled); - void setAntialiasedZeroLine(bool enabled); - void setPen(const QPen &pen); - void setSubGridPen(const QPen &pen); - void setZeroLinePen(const QPen &pen); - + explicit QCPGrid(QCPAxis *parentAxis); + + // getters: + bool subGridVisible() const { + return mSubGridVisible; + } + bool antialiasedSubGrid() const { + return mAntialiasedSubGrid; + } + bool antialiasedZeroLine() const { + return mAntialiasedZeroLine; + } + QPen pen() const { + return mPen; + } + QPen subGridPen() const { + return mSubGridPen; + } + QPen zeroLinePen() const { + return mZeroLinePen; + } + + // setters: + void setSubGridVisible(bool visible); + void setAntialiasedSubGrid(bool enabled); + void setAntialiasedZeroLine(bool enabled); + void setPen(const QPen &pen); + void setSubGridPen(const QPen &pen); + void setZeroLinePen(const QPen &pen); + protected: - // property members: - bool mSubGridVisible; - bool mAntialiasedSubGrid, mAntialiasedZeroLine; - QPen mPen, mSubGridPen, mZeroLinePen; - - // non-property members: - QCPAxis *mParentAxis; - - // reimplemented virtual methods: - 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; - void drawSubGridLines(QCPPainter *painter) const; - - friend class QCPAxis; + // property members: + bool mSubGridVisible; + bool mAntialiasedSubGrid, mAntialiasedZeroLine; + QPen mPen, mSubGridPen, mZeroLinePen; + + // non-property members: + QCPAxis *mParentAxis; + + // reimplemented virtual methods: + 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; + void drawSubGridLines(QCPPainter *painter) const; + + friend class QCPAxis; }; class QCP_LIB_DECL QCPAxis : public QCPLayerable { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(AxisType axisType READ axisType) - Q_PROPERTY(QCPAxisRect* axisRect READ axisRect) - Q_PROPERTY(ScaleType scaleType READ scaleType WRITE setScaleType NOTIFY scaleTypeChanged) - Q_PROPERTY(QCPRange range READ range WRITE setRange NOTIFY rangeChanged) - Q_PROPERTY(bool rangeReversed READ rangeReversed WRITE setRangeReversed) - 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(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 numberFormat READ numberFormat WRITE setNumberFormat) - Q_PROPERTY(int numberPrecision READ numberPrecision WRITE setNumberPrecision) - 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(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) - Q_PROPERTY(QPen tickPen READ tickPen WRITE setTickPen) - Q_PROPERTY(QPen subTickPen READ subTickPen WRITE setSubTickPen) - Q_PROPERTY(QFont labelFont READ labelFont WRITE setLabelFont) - Q_PROPERTY(QColor labelColor READ labelColor WRITE setLabelColor) - Q_PROPERTY(QString label READ label WRITE setLabel) - Q_PROPERTY(int labelPadding READ labelPadding WRITE setLabelPadding) - Q_PROPERTY(int padding READ padding WRITE setPadding) - Q_PROPERTY(int offset READ offset WRITE setOffset) - Q_PROPERTY(SelectableParts selectedParts READ selectedParts WRITE setSelectedParts NOTIFY selectionChanged) - Q_PROPERTY(SelectableParts selectableParts READ selectableParts WRITE setSelectableParts NOTIFY selectableChanged) - Q_PROPERTY(QFont selectedTickLabelFont READ selectedTickLabelFont WRITE setSelectedTickLabelFont) - Q_PROPERTY(QFont selectedLabelFont READ selectedLabelFont WRITE setSelectedLabelFont) - Q_PROPERTY(QColor selectedTickLabelColor READ selectedTickLabelColor WRITE setSelectedTickLabelColor) - Q_PROPERTY(QColor selectedLabelColor READ selectedLabelColor WRITE setSelectedLabelColor) - Q_PROPERTY(QPen selectedBasePen READ selectedBasePen WRITE setSelectedBasePen) - Q_PROPERTY(QPen selectedTickPen READ selectedTickPen WRITE setSelectedTickPen) - Q_PROPERTY(QPen selectedSubTickPen READ selectedSubTickPen WRITE setSelectedSubTickPen) - Q_PROPERTY(QCPLineEnding lowerEnding READ lowerEnding WRITE setLowerEnding) - Q_PROPERTY(QCPLineEnding upperEnding READ upperEnding WRITE setUpperEnding) - Q_PROPERTY(QCPGrid* grid READ grid) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(AxisType axisType READ axisType) + Q_PROPERTY(QCPAxisRect *axisRect READ axisRect) + Q_PROPERTY(ScaleType scaleType READ scaleType WRITE setScaleType NOTIFY scaleTypeChanged) + Q_PROPERTY(QCPRange range READ range WRITE setRange NOTIFY rangeChanged) + Q_PROPERTY(bool rangeReversed READ rangeReversed WRITE setRangeReversed) + 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(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 numberFormat READ numberFormat WRITE setNumberFormat) + Q_PROPERTY(int numberPrecision READ numberPrecision WRITE setNumberPrecision) + 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(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) + Q_PROPERTY(QPen tickPen READ tickPen WRITE setTickPen) + Q_PROPERTY(QPen subTickPen READ subTickPen WRITE setSubTickPen) + Q_PROPERTY(QFont labelFont READ labelFont WRITE setLabelFont) + Q_PROPERTY(QColor labelColor READ labelColor WRITE setLabelColor) + Q_PROPERTY(QString label READ label WRITE setLabel) + Q_PROPERTY(int labelPadding READ labelPadding WRITE setLabelPadding) + Q_PROPERTY(int padding READ padding WRITE setPadding) + Q_PROPERTY(int offset READ offset WRITE setOffset) + Q_PROPERTY(SelectableParts selectedParts READ selectedParts WRITE setSelectedParts NOTIFY selectionChanged) + Q_PROPERTY(SelectableParts selectableParts READ selectableParts WRITE setSelectableParts NOTIFY selectableChanged) + Q_PROPERTY(QFont selectedTickLabelFont READ selectedTickLabelFont WRITE setSelectedTickLabelFont) + Q_PROPERTY(QFont selectedLabelFont READ selectedLabelFont WRITE setSelectedLabelFont) + Q_PROPERTY(QColor selectedTickLabelColor READ selectedTickLabelColor WRITE setSelectedTickLabelColor) + Q_PROPERTY(QColor selectedLabelColor READ selectedLabelColor WRITE setSelectedLabelColor) + Q_PROPERTY(QPen selectedBasePen READ selectedBasePen WRITE setSelectedBasePen) + Q_PROPERTY(QPen selectedTickPen READ selectedTickPen WRITE setSelectedTickPen) + Q_PROPERTY(QPen selectedSubTickPen READ selectedSubTickPen WRITE setSelectedSubTickPen) + Q_PROPERTY(QCPLineEnding lowerEnding READ lowerEnding WRITE setLowerEnding) + Q_PROPERTY(QCPLineEnding upperEnding READ upperEnding WRITE setUpperEnding) + Q_PROPERTY(QCPGrid *grid READ grid) + /// \endcond public: - /*! - Defines at which side of the axis rect the axis will appear. This also affects how the tick - marks are drawn, on which side the labels are placed etc. - */ - enum AxisType { atLeft = 0x01 ///< 0x01 Axis is vertical and on the left side of the axis rect - ,atRight = 0x02 ///< 0x02 Axis is vertical and on the right side of the axis rect - ,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_ENUMS(AxisType) - Q_FLAGS(AxisTypes) - Q_DECLARE_FLAGS(AxisTypes, AxisType) - /*! - Defines on which side of the axis the tick labels (numbers) shall appear. - - \see setTickLabelSide - */ - enum LabelSide { lsInside ///< Tick labels will be displayed inside the axis rect and clipped to the inner axis rect - ,lsOutside ///< Tick labels will be displayed outside the axis rect - }; - Q_ENUMS(LabelSide) - /*! - Defines the scale of an axis. - \see setScaleType - */ - enum ScaleType { stLinear ///< Linear scaling - ,stLogarithmic ///< Logarithmic scaling with correspondingly transformed axis coordinates (possibly also \ref setTicker to a \ref QCPAxisTickerLog instance). - }; - Q_ENUMS(ScaleType) - /*! - Defines the selectable parts of an axis. - \see setSelectableParts, setSelectedParts - */ - enum SelectablePart { spNone = 0 ///< None of the selectable parts - ,spAxis = 0x001 ///< The axis backbone and tick marks - ,spTickLabels = 0x002 ///< Tick labels (numbers) of this axis (as a whole, not individually) - ,spAxisLabel = 0x004 ///< The axis label - }; - Q_ENUMS(SelectablePart) - Q_FLAGS(SelectableParts) - Q_DECLARE_FLAGS(SelectableParts, SelectablePart) - - explicit QCPAxis(QCPAxisRect *parent, AxisType type); - virtual ~QCPAxis() Q_DECL_OVERRIDE; - - // getters: - AxisType axisType() const { return mAxisType; } - QCPAxisRect *axisRect() const { return mAxisRect; } - ScaleType scaleType() const { return mScaleType; } - const QCPRange range() const { return mRange; } - bool rangeReversed() const { return mRangeReversed; } - QSharedPointer ticker() const { return mTicker; } - bool ticks() const { return mTicks; } - bool tickLabels() const { return mTickLabels; } - int tickLabelPadding() const; - QFont tickLabelFont() const { return mTickLabelFont; } - QColor tickLabelColor() const { return mTickLabelColor; } - double tickLabelRotation() const; - LabelSide tickLabelSide() const; - QString numberFormat() const; - int numberPrecision() const { return mNumberPrecision; } - QVector tickVector() const { return mTickVector; } - QVector tickVectorLabels() const { return mTickVectorLabels; } - int tickLengthIn() const; - int tickLengthOut() const; - bool subTicks() const { return mSubTicks; } - int subTickLengthIn() const; - int subTickLengthOut() const; - QPen basePen() const { return mBasePen; } - QPen tickPen() const { return mTickPen; } - QPen subTickPen() const { return mSubTickPen; } - QFont labelFont() const { return mLabelFont; } - QColor labelColor() const { return mLabelColor; } - QString label() const { return mLabel; } - int labelPadding() const; - int padding() const { return mPadding; } - int offset() const; - SelectableParts selectedParts() const { return mSelectedParts; } - SelectableParts selectableParts() const { return mSelectableParts; } - QFont selectedTickLabelFont() const { return mSelectedTickLabelFont; } - QFont selectedLabelFont() const { return mSelectedLabelFont; } - QColor selectedTickLabelColor() const { return mSelectedTickLabelColor; } - QColor selectedLabelColor() const { return mSelectedLabelColor; } - QPen selectedBasePen() const { return mSelectedBasePen; } - QPen selectedTickPen() const { return mSelectedTickPen; } - QPen selectedSubTickPen() const { return mSelectedSubTickPen; } - QCPLineEnding lowerEnding() const; - QCPLineEnding upperEnding() const; - QCPGrid *grid() const { return mGrid; } - - // setters: - Q_SLOT void setScaleType(QCPAxis::ScaleType type); - 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 setTicker(QSharedPointer ticker); - void setTicks(bool show); - void setTickLabels(bool show); - void setTickLabelPadding(int padding); - void setTickLabelFont(const QFont &font); - void setTickLabelColor(const QColor &color); - void setTickLabelRotation(double degrees); - void setTickLabelSide(LabelSide side); - void setNumberFormat(const QString &formatCode); - void setNumberPrecision(int precision); - void setTickLength(int inside, int outside=0); - void setTickLengthIn(int inside); - void setTickLengthOut(int outside); - void setSubTicks(bool show); - void setSubTickLength(int inside, int outside=0); - void setSubTickLengthIn(int inside); - void setSubTickLengthOut(int outside); - void setBasePen(const QPen &pen); - void setTickPen(const QPen &pen); - void setSubTickPen(const QPen &pen); - void setLabelFont(const QFont &font); - void setLabelColor(const QColor &color); - void setLabel(const QString &str); - void setLabelPadding(int padding); - void setPadding(int padding); - void setOffset(int offset); - void setSelectedTickLabelFont(const QFont &font); - void setSelectedLabelFont(const QFont &font); - void setSelectedTickLabelColor(const QColor &color); - void setSelectedLabelColor(const QColor &color); - void setSelectedBasePen(const QPen &pen); - void setSelectedTickPen(const QPen &pen); - void setSelectedSubTickPen(const QPen &pen); - Q_SLOT void setSelectableParts(const QCPAxis::SelectableParts &selectableParts); - Q_SLOT void setSelectedParts(const QCPAxis::SelectableParts &selectedParts); - void setLowerEnding(const QCPLineEnding &ending); - void setUpperEnding(const QCPLineEnding &ending); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) 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); - double pixelToCoord(double value) const; - double coordToPixel(double value) const; - SelectablePart getPartAt(const QPointF &pos) const; - QList plottables() const; - QList graphs() const; - QList items() const; - - static AxisType marginSideToAxisType(QCP::MarginSide side); - static Qt::Orientation orientation(AxisType type) { return type==atBottom || type==atTop ? Qt::Horizontal : Qt::Vertical; } - static AxisType opposite(AxisType type); - + /*! + Defines at which side of the axis rect the axis will appear. This also affects how the tick + marks are drawn, on which side the labels are placed etc. + */ + enum AxisType { atLeft = 0x01 ///< 0x01 Axis is vertical and on the left side of the axis rect + , atRight = 0x02 ///< 0x02 Axis is vertical and on the right side of the axis rect + , 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_ENUMS(AxisType) + Q_FLAGS(AxisTypes) + Q_DECLARE_FLAGS(AxisTypes, AxisType) + /*! + Defines on which side of the axis the tick labels (numbers) shall appear. + + \see setTickLabelSide + */ + enum LabelSide { lsInside ///< Tick labels will be displayed inside the axis rect and clipped to the inner axis rect + , lsOutside ///< Tick labels will be displayed outside the axis rect + }; + Q_ENUMS(LabelSide) + /*! + Defines the scale of an axis. + \see setScaleType + */ + enum ScaleType { stLinear ///< Linear scaling + , stLogarithmic ///< Logarithmic scaling with correspondingly transformed axis coordinates (possibly also \ref setTicker to a \ref QCPAxisTickerLog instance). + }; + Q_ENUMS(ScaleType) + /*! + Defines the selectable parts of an axis. + \see setSelectableParts, setSelectedParts + */ + enum SelectablePart { spNone = 0 ///< None of the selectable parts + , spAxis = 0x001 ///< The axis backbone and tick marks + , spTickLabels = 0x002 ///< Tick labels (numbers) of this axis (as a whole, not individually) + , spAxisLabel = 0x004 ///< The axis label + }; + Q_ENUMS(SelectablePart) + Q_FLAGS(SelectableParts) + Q_DECLARE_FLAGS(SelectableParts, SelectablePart) + + explicit QCPAxis(QCPAxisRect *parent, AxisType type); + virtual ~QCPAxis() Q_DECL_OVERRIDE; + + // getters: + AxisType axisType() const { + return mAxisType; + } + QCPAxisRect *axisRect() const { + return mAxisRect; + } + ScaleType scaleType() const { + return mScaleType; + } + const QCPRange range() const { + return mRange; + } + bool rangeReversed() const { + return mRangeReversed; + } + QSharedPointer ticker() const { + return mTicker; + } + bool ticks() const { + return mTicks; + } + bool tickLabels() const { + return mTickLabels; + } + int tickLabelPadding() const; + QFont tickLabelFont() const { + return mTickLabelFont; + } + QColor tickLabelColor() const { + return mTickLabelColor; + } + double tickLabelRotation() const; + LabelSide tickLabelSide() const; + QString numberFormat() const; + int numberPrecision() const { + return mNumberPrecision; + } + QVector tickVector() const { + return mTickVector; + } + QVector tickVectorLabels() const { + return mTickVectorLabels; + } + int tickLengthIn() const; + int tickLengthOut() const; + bool subTicks() const { + return mSubTicks; + } + int subTickLengthIn() const; + int subTickLengthOut() const; + QPen basePen() const { + return mBasePen; + } + QPen tickPen() const { + return mTickPen; + } + QPen subTickPen() const { + return mSubTickPen; + } + QFont labelFont() const { + return mLabelFont; + } + QColor labelColor() const { + return mLabelColor; + } + QString label() const { + return mLabel; + } + int labelPadding() const; + int padding() const { + return mPadding; + } + int offset() const; + SelectableParts selectedParts() const { + return mSelectedParts; + } + SelectableParts selectableParts() const { + return mSelectableParts; + } + QFont selectedTickLabelFont() const { + return mSelectedTickLabelFont; + } + QFont selectedLabelFont() const { + return mSelectedLabelFont; + } + QColor selectedTickLabelColor() const { + return mSelectedTickLabelColor; + } + QColor selectedLabelColor() const { + return mSelectedLabelColor; + } + QPen selectedBasePen() const { + return mSelectedBasePen; + } + QPen selectedTickPen() const { + return mSelectedTickPen; + } + QPen selectedSubTickPen() const { + return mSelectedSubTickPen; + } + QCPLineEnding lowerEnding() const; + QCPLineEnding upperEnding() const; + QCPGrid *grid() const { + return mGrid; + } + + // setters: + Q_SLOT void setScaleType(QCPAxis::ScaleType type); + 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 setTicker(QSharedPointer ticker); + void setTicks(bool show); + void setTickLabels(bool show); + void setTickLabelPadding(int padding); + void setTickLabelFont(const QFont &font); + void setTickLabelColor(const QColor &color); + void setTickLabelRotation(double degrees); + void setTickLabelSide(LabelSide side); + void setNumberFormat(const QString &formatCode); + void setNumberPrecision(int precision); + void setTickLength(int inside, int outside = 0); + void setTickLengthIn(int inside); + void setTickLengthOut(int outside); + void setSubTicks(bool show); + void setSubTickLength(int inside, int outside = 0); + void setSubTickLengthIn(int inside); + void setSubTickLengthOut(int outside); + void setBasePen(const QPen &pen); + void setTickPen(const QPen &pen); + void setSubTickPen(const QPen &pen); + void setLabelFont(const QFont &font); + void setLabelColor(const QColor &color); + void setLabel(const QString &str); + void setLabelPadding(int padding); + void setPadding(int padding); + void setOffset(int offset); + void setSelectedTickLabelFont(const QFont &font); + void setSelectedLabelFont(const QFont &font); + void setSelectedTickLabelColor(const QColor &color); + void setSelectedLabelColor(const QColor &color); + void setSelectedBasePen(const QPen &pen); + void setSelectedTickPen(const QPen &pen); + void setSelectedSubTickPen(const QPen &pen); + Q_SLOT void setSelectableParts(const QCPAxis::SelectableParts &selectableParts); + Q_SLOT void setSelectedParts(const QCPAxis::SelectableParts &selectedParts); + void setLowerEnding(const QCPLineEnding &ending); + void setUpperEnding(const QCPLineEnding &ending); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = nullptr) 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); + double pixelToCoord(double value) const; + double coordToPixel(double value) const; + SelectablePart getPartAt(const QPointF &pos) const; + QList plottables() const; + QList graphs() const; + QList items() const; + + static AxisType marginSideToAxisType(QCP::MarginSide side); + static Qt::Orientation orientation(AxisType type) { + return type == atBottom || type == atTop ? Qt::Horizontal : Qt::Vertical; + } + static AxisType opposite(AxisType type); + signals: - void rangeChanged(const QCPRange &newRange); - void rangeChanged(const QCPRange &newRange, const QCPRange &oldRange); - void scaleTypeChanged(QCPAxis::ScaleType scaleType); - void selectionChanged(const QCPAxis::SelectableParts &parts); - void selectableChanged(const QCPAxis::SelectableParts &parts); + void rangeChanged(const QCPRange &newRange); + void rangeChanged(const QCPRange &newRange, const QCPRange &oldRange); + void scaleTypeChanged(QCPAxis::ScaleType scaleType); + void selectionChanged(const QCPAxis::SelectableParts &parts); + void selectableChanged(const QCPAxis::SelectableParts &parts); protected: - // property members: - // axis base: - AxisType mAxisType; - QCPAxisRect *mAxisRect; - //int mOffset; // in QCPAxisPainter - int mPadding; - Qt::Orientation mOrientation; - SelectableParts mSelectableParts, mSelectedParts; - QPen mBasePen, mSelectedBasePen; - //QCPLineEnding mLowerEnding, mUpperEnding; // in QCPAxisPainter - // axis label: - //int mLabelPadding; // in QCPAxisPainter - QString mLabel; - QFont mLabelFont, mSelectedLabelFont; - QColor mLabelColor, mSelectedLabelColor; - // tick labels: - //int mTickLabelPadding; // in QCPAxisPainter - bool mTickLabels; - //double mTickLabelRotation; // in QCPAxisPainter - QFont mTickLabelFont, mSelectedTickLabelFont; - QColor mTickLabelColor, mSelectedTickLabelColor; - int mNumberPrecision; - QLatin1Char mNumberFormatChar; - bool mNumberBeautifulPowers; - //bool mNumberMultiplyCross; // QCPAxisPainter - // ticks and subticks: - bool mTicks; - bool mSubTicks; - //int mTickLengthIn, mTickLengthOut, mSubTickLengthIn, mSubTickLengthOut; // QCPAxisPainter - QPen mTickPen, mSelectedTickPen; - QPen mSubTickPen, mSelectedSubTickPen; - // scale and range: - QCPRange mRange; - bool mRangeReversed; - ScaleType mScaleType; - - // non-property members: - QCPGrid *mGrid; - QCPAxisPainterPrivate *mAxisPainter; - QSharedPointer mTicker; - QVector mTickVector; - QVector mTickVectorLabels; - QVector mSubTickVector; - bool mCachedMarginValid; - int mCachedMargin; - bool mDragging; - QCPRange mDragStartRange; - QCP::AntialiasedElements mAADragBackup, mNotAADragBackup; - - // introduced virtual methods: - virtual int calculateMargin(); - - // reimplemented virtual methods: - 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) Q_DECL_OVERRIDE; - virtual void deselectEvent(bool *selectionStateChanged) Q_DECL_OVERRIDE; - // mouse events: - 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-virtual methods: - void setupTickVectors(); - QPen getBasePen() const; - QPen getTickPen() const; - QPen getSubTickPen() const; - QFont getTickLabelFont() const; - QFont getLabelFont() const; - QColor getTickLabelColor() const; - QColor getLabelColor() const; - + // property members: + // axis base: + AxisType mAxisType; + QCPAxisRect *mAxisRect; + //int mOffset; // in QCPAxisPainter + int mPadding; + Qt::Orientation mOrientation; + SelectableParts mSelectableParts, mSelectedParts; + QPen mBasePen, mSelectedBasePen; + //QCPLineEnding mLowerEnding, mUpperEnding; // in QCPAxisPainter + // axis label: + //int mLabelPadding; // in QCPAxisPainter + QString mLabel; + QFont mLabelFont, mSelectedLabelFont; + QColor mLabelColor, mSelectedLabelColor; + // tick labels: + //int mTickLabelPadding; // in QCPAxisPainter + bool mTickLabels; + //double mTickLabelRotation; // in QCPAxisPainter + QFont mTickLabelFont, mSelectedTickLabelFont; + QColor mTickLabelColor, mSelectedTickLabelColor; + int mNumberPrecision; + QLatin1Char mNumberFormatChar; + bool mNumberBeautifulPowers; + //bool mNumberMultiplyCross; // QCPAxisPainter + // ticks and subticks: + bool mTicks; + bool mSubTicks; + //int mTickLengthIn, mTickLengthOut, mSubTickLengthIn, mSubTickLengthOut; // QCPAxisPainter + QPen mTickPen, mSelectedTickPen; + QPen mSubTickPen, mSelectedSubTickPen; + // scale and range: + QCPRange mRange; + bool mRangeReversed; + ScaleType mScaleType; + + // non-property members: + QCPGrid *mGrid; + QCPAxisPainterPrivate *mAxisPainter; + QSharedPointer mTicker; + QVector mTickVector; + QVector mTickVectorLabels; + QVector mSubTickVector; + bool mCachedMarginValid; + int mCachedMargin; + bool mDragging; + QCPRange mDragStartRange; + QCP::AntialiasedElements mAADragBackup, mNotAADragBackup; + + // introduced virtual methods: + virtual int calculateMargin(); + + // reimplemented virtual methods: + 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) Q_DECL_OVERRIDE; + virtual void deselectEvent(bool *selectionStateChanged) Q_DECL_OVERRIDE; + // mouse events: + 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-virtual methods: + void setupTickVectors(); + QPen getBasePen() const; + QPen getTickPen() const; + QPen getSubTickPen() const; + QFont getTickLabelFont() const; + QFont getLabelFont() const; + QColor getTickLabelColor() const; + QColor getLabelColor() const; + private: - Q_DISABLE_COPY(QCPAxis) - - friend class QCustomPlot; - friend class QCPGrid; - friend class QCPAxisRect; + Q_DISABLE_COPY(QCPAxis) + + friend class QCustomPlot; + friend class QCPGrid; + friend class QCPAxisRect; }; Q_DECLARE_OPERATORS_FOR_FLAGS(QCPAxis::SelectableParts) Q_DECLARE_OPERATORS_FOR_FLAGS(QCPAxis::AxisTypes) @@ -2375,67 +2724,71 @@ Q_DECLARE_METATYPE(QCPAxis::SelectablePart) class QCPAxisPainterPrivate { public: - explicit QCPAxisPainterPrivate(QCustomPlot *parentPlot); - virtual ~QCPAxisPainterPrivate(); - - virtual void draw(QCPPainter *painter); - virtual int size(); - void clearCache(); - - QRect axisSelectionBox() const { return mAxisSelectionBox; } - QRect tickLabelsSelectionBox() const { return mTickLabelsSelectionBox; } - QRect labelSelectionBox() const { return mLabelSelectionBox; } - - // public property members: - QCPAxis::AxisType type; - QPen basePen; - QCPLineEnding lowerEnding, upperEnding; // directly accessed by QCPAxis setters/getters - int labelPadding; // directly accessed by QCPAxis setters/getters - QFont labelFont; - QColor labelColor; - QString label; - int tickLabelPadding; // directly accessed by QCPAxis setters/getters - double tickLabelRotation; // directly accessed by QCPAxis setters/getters - QCPAxis::LabelSide tickLabelSide; // directly accessed by QCPAxis setters/getters - bool substituteExponent; - bool numberMultiplyCross; // directly accessed by QCPAxis setters/getters - int tickLengthIn, tickLengthOut, subTickLengthIn, subTickLengthOut; // directly accessed by QCPAxis setters/getters - QPen tickPen, subTickPen; - QFont tickLabelFont; - QColor tickLabelColor; - QRect axisRect, viewportRect; - int offset; // directly accessed by QCPAxis setters/getters - bool abbreviateDecimalPowers; - bool reversedEndings; - - QVector subTickPositions; - QVector tickPositions; - QVector tickLabels; - + explicit QCPAxisPainterPrivate(QCustomPlot *parentPlot); + virtual ~QCPAxisPainterPrivate(); + + virtual void draw(QCPPainter *painter); + virtual int size(); + void clearCache(); + + QRect axisSelectionBox() const { + return mAxisSelectionBox; + } + QRect tickLabelsSelectionBox() const { + return mTickLabelsSelectionBox; + } + QRect labelSelectionBox() const { + return mLabelSelectionBox; + } + + // public property members: + QCPAxis::AxisType type; + QPen basePen; + QCPLineEnding lowerEnding, upperEnding; // directly accessed by QCPAxis setters/getters + int labelPadding; // directly accessed by QCPAxis setters/getters + QFont labelFont; + QColor labelColor; + QString label; + int tickLabelPadding; // directly accessed by QCPAxis setters/getters + double tickLabelRotation; // directly accessed by QCPAxis setters/getters + QCPAxis::LabelSide tickLabelSide; // directly accessed by QCPAxis setters/getters + bool substituteExponent; + bool numberMultiplyCross; // directly accessed by QCPAxis setters/getters + int tickLengthIn, tickLengthOut, subTickLengthIn, subTickLengthOut; // directly accessed by QCPAxis setters/getters + QPen tickPen, subTickPen; + QFont tickLabelFont; + QColor tickLabelColor; + QRect axisRect, viewportRect; + int offset; // directly accessed by QCPAxis setters/getters + bool abbreviateDecimalPowers; + bool reversedEndings; + + QVector subTickPositions; + QVector tickPositions; + QVector tickLabels; + protected: - struct CachedLabel - { - QPointF offset; - QPixmap pixmap; - }; - struct TickLabelData - { - QString basePart, expPart, suffixPart; - QRect baseBounds, expBounds, suffixBounds, totalBounds, rotatedTotalBounds; - QFont baseFont, expFont; - }; - QCustomPlot *mParentPlot; - QByteArray mLabelParameterHash; // to determine whether mLabelCache needs to be cleared due to changed parameters - QCache mLabelCache; - QRect mAxisSelectionBox, mTickLabelsSelectionBox, mLabelSelectionBox; - - virtual QByteArray generateLabelParameterHash() const; - - virtual void placeTickLabel(QCPPainter *painter, double position, int distanceToAxis, const QString &text, QSize *tickLabelsSize); - virtual void drawTickLabel(QCPPainter *painter, double x, double y, const TickLabelData &labelData) const; - virtual TickLabelData getTickLabelData(const QFont &font, const QString &text) const; - virtual QPointF getTickLabelDrawOffset(const TickLabelData &labelData) const; - virtual void getMaxTickLabelSize(const QFont &font, const QString &text, QSize *tickLabelsSize) const; + struct CachedLabel { + QPointF offset; + QPixmap pixmap; + }; + struct TickLabelData { + QString basePart, expPart, suffixPart; + QRect baseBounds, expBounds, suffixBounds, totalBounds, rotatedTotalBounds; + QFont baseFont, expFont; + }; + QCustomPlot *mParentPlot; + QByteArray mLabelParameterHash; // to determine whether mLabelCache needs to be cleared due to changed parameters + QCache mLabelCache; + QRect mAxisSelectionBox, mTickLabelsSelectionBox, mLabelSelectionBox; + + virtual QByteArray generateLabelParameterHash() const; + + virtual void placeTickLabel(QCPPainter *painter, double position, int distanceToAxis, const QString &text, QSize *tickLabelsSize); + virtual void drawTickLabel(QCPPainter *painter, double x, double y, const TickLabelData &labelData) const; + virtual TickLabelData getTickLabelData(const QFont &font, const QString &text) const; + virtual QPointF getTickLabelDrawOffset(const TickLabelData &labelData) const; + virtual void getMaxTickLabelSize(const QFont &font, const QString &text, QSize *tickLabelsSize) const; }; /* end of 'src/axis/axis.h' */ @@ -2446,99 +2799,115 @@ protected: class QCP_LIB_DECL QCPScatterStyle { - Q_GADGET + 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. + /*! + 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) + 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. + /*! + 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) + 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; } + 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); - // 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); + // 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; + } - // 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; + // 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; + // 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) @@ -2557,63 +2926,84 @@ Q_DECLARE_METATYPE(QCPScatterStyle::ScatterShape) \see QCPDataContainer::sort */ template -inline bool qcpLessThanSortKey(const DataType &a, const DataType &b) { return a.sortKey() < b.sortKey(); } +inline bool qcpLessThanSortKey(const DataType &a, const DataType &b) +{ + return a.sortKey() < b.sortKey(); +} template class QCPDataContainer // no QCP_LIB_DECL, template class ends up in header (cpp included below) { 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; - + 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(); + // property members: + bool mAutoSqueeze; + + // non-property memebers: + QVector mData; + int mPreallocSize; + int mPreallocIteration; + + // non-virtual methods: + void preallocateGrow(int minimumPreallocSize); + void performAutoSqueeze(); }; @@ -2693,27 +3083,27 @@ protected: /* 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 @@ -2722,9 +3112,9 @@ protected: */ /*! \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. @@ -2754,9 +3144,9 @@ protected: */ template QCPDataContainer::QCPDataContainer() : - mAutoSqueeze(true), - mPreallocSize(0), - mPreallocIteration(0) + mAutoSqueeze(true), + mPreallocSize(0), + mPreallocIteration(0) { } @@ -2764,160 +3154,162 @@ QCPDataContainer::QCPDataContainer() : 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(); - } + 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); + 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(); + 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); - } + 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); - } + 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); - } + 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 += int(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(); + QCPDataContainer::iterator it = begin(); + QCPDataContainer::iterator itEnd = std::lower_bound(begin(), end(), DataType::fromSortKey(sortKey), qcpLessThanSortKey); + mPreallocSize += int(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(); + } } /*! @@ -2928,68 +3320,72 @@ void QCPDataContainer::removeBefore(double sortKey) 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(); + 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(); + 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(); + 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; + mData.clear(); + mPreallocIteration = 0; + mPreallocSize = 0; } /*! @@ -3006,34 +3402,33 @@ void QCPDataContainer::clear() template void QCPDataContainer::sort() { - std::sort(begin(), end(), qcpLessThanSortKey); + 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; + if (preAllocation) { + if (mPreallocSize > 0) { + std::copy(begin(), end(), mData.begin()); + mData.resize(size()); + mPreallocSize = 0; + } + mPreallocIteration = 0; + } + if (postAllocation) { + mData.squeeze(); } - mPreallocIteration = 0; - } - if (postAllocation) - mData.squeeze(); } /*! @@ -3054,13 +3449,15 @@ void QCPDataContainer::squeeze(bool preAllocation, bool postAllocation 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; + 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; } /*! @@ -3081,13 +3478,15 @@ typename QCPDataContainer::const_iterator QCPDataContainer:: 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; + if (isEmpty()) { + return constEnd(); + } + + QCPDataContainer::const_iterator it = std::upper_bound(constBegin(), constEnd(), DataType::fromSortKey(sortKey), qcpLessThanSortKey); + if (expandedRange && it != constEnd()) { + ++it; + } + return it; } /*! @@ -3095,121 +3494,99 @@ typename QCPDataContainer::const_iterator QCPDataContainer:: 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; - } + if (isEmpty()) { + foundRange = false; + return QCPRange(); } - } 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; + 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; + } } - if ((current > range.upper || !haveUpper) && current < 0) - { - range.upper = current; - haveUpper = true; + } 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; } - } - ++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; + + foundRange = haveLower && haveUpper; + return range; } /*! @@ -3231,134 +3608,124 @@ QCPRange QCPDataContainer::keyRange(bool &foundRange, QCP::SignDomain 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, false); - itEnd = findEnd(inKeyRange.upper, false); - } - 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; - } + if (isEmpty()) { + foundRange = false; + return QCPRange(); } - } 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; - } + 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, false); + itEnd = findEnd(inKeyRange.upper, false); } - } 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; - } + 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; + + 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. The initial range described by the passed iterators \a begin and \a end is never expanded, only contracted if necessary. - + 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(int(begin-constBegin()), int(end-constBegin())); - iteratorRange = iteratorRange.bounded(dataRange.bounded(this->dataRange())); - begin = constBegin()+iteratorRange.begin(); - end = constBegin()+iteratorRange.end(); + QCPDataRange iteratorRange(int(begin - constBegin()), int(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<::preallocateGrow(int minimumPreallocSize) template 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); + 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); + } } @@ -3395,152 +3761,182 @@ void QCPDataContainer::performAutoSqueeze() 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); - + 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); - + // 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_DISABLE_COPY(QCPSelectionDecorator) + friend class QCPAbstractPlottable; }; -Q_DECLARE_METATYPE(QCPSelectionDecorator*) +Q_DECLARE_METATYPE(QCPSelectionDecorator *) class QCP_LIB_DECL QCPAbstractPlottable : public QCPLayerable { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - 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(QPen pen READ pen WRITE setPen) - Q_PROPERTY(QBrush brush READ brush WRITE setBrush) - Q_PROPERTY(QCPAxis* keyAxis READ keyAxis WRITE setKeyAxis) - Q_PROPERTY(QCPAxis* valueAxis READ valueAxis WRITE setValueAxis) - 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 + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES 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(QPen pen READ pen WRITE setPen) + Q_PROPERTY(QBrush brush READ brush WRITE setBrush) + Q_PROPERTY(QCPAxis *keyAxis READ keyAxis WRITE setKeyAxis) + Q_PROPERTY(QCPAxis *valueAxis READ valueAxis WRITE setValueAxis) + 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() Q_DECL_OVERRIDE; - - // getters: - QString name() const { return mName; } - bool antialiasedFill() const { return mAntialiasedFill; } - bool antialiasedScatters() const { return mAntialiasedScatters; } - QPen pen() const { return mPen; } - QBrush brush() const { return mBrush; } - QCPAxis *keyAxis() const { return mKeyAxis.data(); } - QCPAxis *valueAxis() const { return mValueAxis.data(); } - 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 setPen(const QPen &pen); - void setBrush(const QBrush &brush); - void setKeyAxis(QCPAxis *axis); - void setValueAxis(QCPAxis *axis); - Q_SLOT void setSelectable(QCP::SelectionType selectable); - Q_SLOT void setSelection(QCPDataSelection selection); - void setSelectionDecorator(QCPSelectionDecorator *decorator); + QCPAbstractPlottable(QCPAxis *keyAxis, QCPAxis *valueAxis); + virtual ~QCPAbstractPlottable() Q_DECL_OVERRIDE; + + // getters: + QString name() const { + return mName; + } + bool antialiasedFill() const { + return mAntialiasedFill; + } + bool antialiasedScatters() const { + return mAntialiasedScatters; + } + QPen pen() const { + return mPen; + } + QBrush brush() const { + return mBrush; + } + QCPAxis *keyAxis() const { + return mKeyAxis.data(); + } + QCPAxis *valueAxis() const { + return mValueAxis.data(); + } + 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 setPen(const QPen &pen); + void setBrush(const QBrush &brush); + void setKeyAxis(QCPAxis *axis); + void setValueAxis(QCPAxis *axis); + Q_SLOT void setSelectable(QCP::SelectionType selectable); + Q_SLOT void setSelection(QCPDataSelection selection); + void setSelectionDecorator(QCPSelectionDecorator *decorator); + + // introduced virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = nullptr) const Q_DECL_OVERRIDE = 0; // actually introduced in QCPLayerable as non-pure, but we want to force reimplementation for plottables + virtual QCPPlottableInterface1D *interface1D() { + return nullptr; + } + 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 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; + 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; - // introduced virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE = 0; // actually introduced in QCPLayerable as non-pure, but we want to force reimplementation for plottables - virtual QCPPlottableInterface1D *interface1D() { return nullptr; } - 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 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; - 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); - + 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; + // 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; private: - Q_DISABLE_COPY(QCPAbstractPlottable) - - friend class QCustomPlot; - friend class QCPAxis; - friend class QCPPlottableLegendItem; + Q_DISABLE_COPY(QCPAbstractPlottable) + + friend class QCustomPlot; + friend class QCPAxis; + friend class QCPPlottableLegendItem; }; @@ -3552,181 +3948,215 @@ private: class QCP_LIB_DECL QCPItemAnchor { - Q_GADGET -public: - QCPItemAnchor(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString &name, int anchorId=-1); - virtual ~QCPItemAnchor(); - - // getters: - QString name() const { return mName; } - virtual QPointF pixelPosition() const; - + Q_GADGET +public: QCPItemAnchor(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString &name, int anchorId = -1); + virtual ~QCPItemAnchor(); + + // getters: + QString name() const { + return mName; + } + virtual QPointF pixelPosition() const; + protected: - // property members: - QString mName; - - // non-property members: - QCustomPlot *mParentPlot; - QCPAbstractItem *mParentItem; - int mAnchorId; - QSet mChildrenX, mChildrenY; - - // introduced virtual methods: - virtual QCPItemPosition *toQCPItemPosition() { return nullptr; } - - // non-virtual methods: - void addChildX(QCPItemPosition* pos); // called from pos when this anchor is set as parent - void removeChildX(QCPItemPosition *pos); // called from pos when its parent anchor is reset or pos deleted - void addChildY(QCPItemPosition* pos); // called from pos when this anchor is set as parent - void removeChildY(QCPItemPosition *pos); // called from pos when its parent anchor is reset or pos deleted - + // property members: + QString mName; + + // non-property members: + QCustomPlot *mParentPlot; + QCPAbstractItem *mParentItem; + int mAnchorId; + QSet mChildrenX, mChildrenY; + + // introduced virtual methods: + virtual QCPItemPosition *toQCPItemPosition() { + return nullptr; + } + + // non-virtual methods: + void addChildX(QCPItemPosition *pos); // called from pos when this anchor is set as parent + void removeChildX(QCPItemPosition *pos); // called from pos when its parent anchor is reset or pos deleted + void addChildY(QCPItemPosition *pos); // called from pos when this anchor is set as parent + void removeChildY(QCPItemPosition *pos); // called from pos when its parent anchor is reset or pos deleted + private: - Q_DISABLE_COPY(QCPItemAnchor) - - friend class QCPItemPosition; + Q_DISABLE_COPY(QCPItemAnchor) + + friend class QCPItemPosition; }; class QCP_LIB_DECL QCPItemPosition : public QCPItemAnchor { - Q_GADGET + Q_GADGET public: - /*! - Defines the ways an item position can be specified. Thus it defines what the numbers passed to - \ref setCoords actually mean. - - \see setType - */ - enum PositionType { ptAbsolute ///< Static positioning in pixels, starting from the top left corner of the viewport/widget. - ,ptViewportRatio ///< Static positioning given by a fraction of the viewport size. For example, if you call setCoords(0, 0), the position will be at the top - ///< left corner of the viewport/widget. setCoords(1, 1) will be at the bottom right corner, setCoords(0.5, 0) will be horizontally centered and - ///< vertically at the top of the viewport/widget, etc. - ,ptAxisRectRatio ///< Static positioning given by a fraction of the axis rect size (see \ref setAxisRect). For example, if you call setCoords(0, 0), the position will be at the top - ///< left corner of the axis rect. setCoords(1, 1) will be at the bottom right corner, setCoords(0.5, 0) will be horizontally centered and - ///< 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); - virtual ~QCPItemPosition() Q_DECL_OVERRIDE; - - // getters: - PositionType type() const { return typeX(); } - PositionType typeX() const { return mPositionTypeX; } - PositionType typeY() const { return mPositionTypeY; } - QCPItemAnchor *parentAnchor() const { return parentAnchorX(); } - QCPItemAnchor *parentAnchorX() const { return mParentAnchorX; } - QCPItemAnchor *parentAnchorY() const { return mParentAnchorY; } - double key() const { return mKey; } - double value() const { return mValue; } - QPointF coords() const { return QPointF(mKey, mValue); } - QCPAxis *keyAxis() const { return mKeyAxis.data(); } - QCPAxis *valueAxis() const { return mValueAxis.data(); } - QCPAxisRect *axisRect() const; - virtual QPointF pixelPosition() const Q_DECL_OVERRIDE; - - // setters: - void setType(PositionType type); - void setTypeX(PositionType type); - void setTypeY(PositionType type); - bool setParentAnchor(QCPItemAnchor *parentAnchor, bool keepPixelPosition=false); - bool setParentAnchorX(QCPItemAnchor *parentAnchor, bool keepPixelPosition=false); - bool setParentAnchorY(QCPItemAnchor *parentAnchor, bool keepPixelPosition=false); - void setCoords(double key, double value); - void setCoords(const QPointF &pos); - void setAxes(QCPAxis* keyAxis, QCPAxis* valueAxis); - void setAxisRect(QCPAxisRect *axisRect); - void setPixelPosition(const QPointF &pixelPosition); - + /*! + Defines the ways an item position can be specified. Thus it defines what the numbers passed to + \ref setCoords actually mean. + + \see setType + */ + enum PositionType { ptAbsolute ///< Static positioning in pixels, starting from the top left corner of the viewport/widget. + , ptViewportRatio ///< Static positioning given by a fraction of the viewport size. For example, if you call setCoords(0, 0), the position will be at the top + ///< left corner of the viewport/widget. setCoords(1, 1) will be at the bottom right corner, setCoords(0.5, 0) will be horizontally centered and + ///< vertically at the top of the viewport/widget, etc. + , ptAxisRectRatio ///< Static positioning given by a fraction of the axis rect size (see \ref setAxisRect). For example, if you call setCoords(0, 0), the position will be at the top + ///< left corner of the axis rect. setCoords(1, 1) will be at the bottom right corner, setCoords(0.5, 0) will be horizontally centered and + ///< 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); + virtual ~QCPItemPosition() Q_DECL_OVERRIDE; + + // getters: + PositionType type() const { + return typeX(); + } + PositionType typeX() const { + return mPositionTypeX; + } + PositionType typeY() const { + return mPositionTypeY; + } + QCPItemAnchor *parentAnchor() const { + return parentAnchorX(); + } + QCPItemAnchor *parentAnchorX() const { + return mParentAnchorX; + } + QCPItemAnchor *parentAnchorY() const { + return mParentAnchorY; + } + double key() const { + return mKey; + } + double value() const { + return mValue; + } + QPointF coords() const { + return QPointF(mKey, mValue); + } + QCPAxis *keyAxis() const { + return mKeyAxis.data(); + } + QCPAxis *valueAxis() const { + return mValueAxis.data(); + } + QCPAxisRect *axisRect() const; + virtual QPointF pixelPosition() const Q_DECL_OVERRIDE; + + // setters: + void setType(PositionType type); + void setTypeX(PositionType type); + void setTypeY(PositionType type); + bool setParentAnchor(QCPItemAnchor *parentAnchor, bool keepPixelPosition = false); + bool setParentAnchorX(QCPItemAnchor *parentAnchor, bool keepPixelPosition = false); + bool setParentAnchorY(QCPItemAnchor *parentAnchor, bool keepPixelPosition = false); + void setCoords(double key, double value); + void setCoords(const QPointF &pos); + void setAxes(QCPAxis *keyAxis, QCPAxis *valueAxis); + void setAxisRect(QCPAxisRect *axisRect); + void setPixelPosition(const QPointF &pixelPosition); + protected: - // property members: - PositionType mPositionTypeX, mPositionTypeY; - QPointer mKeyAxis, mValueAxis; - QPointer mAxisRect; - double mKey, mValue; - QCPItemAnchor *mParentAnchorX, *mParentAnchorY; - - // reimplemented virtual methods: - virtual QCPItemPosition *toQCPItemPosition() Q_DECL_OVERRIDE { return this; } - + // property members: + PositionType mPositionTypeX, mPositionTypeY; + QPointer mKeyAxis, mValueAxis; + QPointer mAxisRect; + double mKey, mValue; + QCPItemAnchor *mParentAnchorX, *mParentAnchorY; + + // reimplemented virtual methods: + virtual QCPItemPosition *toQCPItemPosition() Q_DECL_OVERRIDE { return this; } + private: - Q_DISABLE_COPY(QCPItemPosition) - + Q_DISABLE_COPY(QCPItemPosition) + }; Q_DECLARE_METATYPE(QCPItemPosition::PositionType) class QCP_LIB_DECL QCPAbstractItem : public QCPLayerable { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(bool clipToAxisRect READ clipToAxisRect WRITE setClipToAxisRect) - Q_PROPERTY(QCPAxisRect* clipAxisRect READ clipAxisRect WRITE setClipAxisRect) - Q_PROPERTY(bool selectable READ selectable WRITE setSelectable NOTIFY selectableChanged) - Q_PROPERTY(bool selected READ selected WRITE setSelected NOTIFY selectionChanged) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(bool clipToAxisRect READ clipToAxisRect WRITE setClipToAxisRect) + Q_PROPERTY(QCPAxisRect *clipAxisRect READ clipAxisRect WRITE setClipAxisRect) + Q_PROPERTY(bool selectable READ selectable WRITE setSelectable NOTIFY selectableChanged) + Q_PROPERTY(bool selected READ selected WRITE setSelected NOTIFY selectionChanged) + /// \endcond public: - explicit QCPAbstractItem(QCustomPlot *parentPlot); - virtual ~QCPAbstractItem() Q_DECL_OVERRIDE; - - // getters: - bool clipToAxisRect() const { return mClipToAxisRect; } - QCPAxisRect *clipAxisRect() const; - bool selectable() const { return mSelectable; } - bool selected() const { return mSelected; } - - // setters: - void setClipToAxisRect(bool clip); - void setClipAxisRect(QCPAxisRect *rect); - Q_SLOT void setSelectable(bool selectable); - Q_SLOT void setSelected(bool selected); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE = 0; - - // non-virtual methods: - QList positions() const { return mPositions; } - QList anchors() const { return mAnchors; } - QCPItemPosition *position(const QString &name) const; - QCPItemAnchor *anchor(const QString &name) const; - bool hasAnchor(const QString &name) const; - + explicit QCPAbstractItem(QCustomPlot *parentPlot); + virtual ~QCPAbstractItem() Q_DECL_OVERRIDE; + + // getters: + bool clipToAxisRect() const { + return mClipToAxisRect; + } + QCPAxisRect *clipAxisRect() const; + bool selectable() const { + return mSelectable; + } + bool selected() const { + return mSelected; + } + + // setters: + void setClipToAxisRect(bool clip); + void setClipAxisRect(QCPAxisRect *rect); + Q_SLOT void setSelectable(bool selectable); + Q_SLOT void setSelected(bool selected); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = nullptr) const Q_DECL_OVERRIDE = 0; + + // non-virtual methods: + QList positions() const { + return mPositions; + } + QList anchors() const { + return mAnchors; + } + QCPItemPosition *position(const QString &name) const; + QCPItemAnchor *anchor(const QString &name) const; + bool hasAnchor(const QString &name) const; + signals: - void selectionChanged(bool selected); - void selectableChanged(bool selectable); - + void selectionChanged(bool selected); + void selectableChanged(bool selectable); + protected: - // property members: - bool mClipToAxisRect; - QPointer mClipAxisRect; - QList mPositions; - QList mAnchors; - bool mSelectable, mSelected; - - // reimplemented virtual methods: - 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) Q_DECL_OVERRIDE; - virtual void deselectEvent(bool *selectionStateChanged) Q_DECL_OVERRIDE; - - // introduced virtual methods: - virtual QPointF anchorPixelPosition(int anchorId) const; - - // non-virtual methods: - double rectDistance(const QRectF &rect, const QPointF &pos, bool filledRect) const; - QCPItemPosition *createPosition(const QString &name); - QCPItemAnchor *createAnchor(const QString &name, int anchorId); - + // property members: + bool mClipToAxisRect; + QPointer mClipAxisRect; + QList mPositions; + QList mAnchors; + bool mSelectable, mSelected; + + // reimplemented virtual methods: + 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) Q_DECL_OVERRIDE; + virtual void deselectEvent(bool *selectionStateChanged) Q_DECL_OVERRIDE; + + // introduced virtual methods: + virtual QPointF anchorPixelPosition(int anchorId) const; + + // non-virtual methods: + double rectDistance(const QRectF &rect, const QPointF &pos, bool filledRect) const; + QCPItemPosition *createPosition(const QString &name); + QCPItemAnchor *createAnchor(const QString &name, int anchorId); + private: - Q_DISABLE_COPY(QCPAbstractItem) - - friend class QCustomPlot; - friend class QCPItemAnchor; + Q_DISABLE_COPY(QCPAbstractItem) + + friend class QCustomPlot; + friend class QCPItemAnchor; }; /* end of 'src/item.h' */ @@ -3737,269 +4167,303 @@ private: class QCP_LIB_DECL QCustomPlot : public QWidget { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QRect viewport READ viewport WRITE setViewport) - Q_PROPERTY(QPixmap background READ background WRITE setBackground) - Q_PROPERTY(bool backgroundScaled READ backgroundScaled WRITE setBackgroundScaled) - Q_PROPERTY(Qt::AspectRatioMode backgroundScaledMode READ backgroundScaledMode WRITE setBackgroundScaledMode) - Q_PROPERTY(QCPLayoutGrid* plotLayout READ plotLayout) - Q_PROPERTY(bool autoAddPlottableToLegend READ autoAddPlottableToLegend WRITE setAutoAddPlottableToLegend) - 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 + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(QRect viewport READ viewport WRITE setViewport) + Q_PROPERTY(QPixmap background READ background WRITE setBackground) + Q_PROPERTY(bool backgroundScaled READ backgroundScaled WRITE setBackgroundScaled) + Q_PROPERTY(Qt::AspectRatioMode backgroundScaledMode READ backgroundScaledMode WRITE setBackgroundScaledMode) + Q_PROPERTY(QCPLayoutGrid *plotLayout READ plotLayout) + Q_PROPERTY(bool autoAddPlottableToLegend READ autoAddPlottableToLegend WRITE setAutoAddPlottableToLegend) + 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: - /*! - Defines how a layer should be inserted relative to an other layer. + /*! + Defines how a layer should be inserted relative to an other layer. - \see addLayer, moveLayer - */ - enum LayerInsertMode { limBelow ///< Layer is inserted below other layer - ,limAbove ///< Layer is inserted above other layer - }; - Q_ENUMS(LayerInsertMode) - - /*! - Defines with what timing the QCustomPlot surface is refreshed after a replot. + \see addLayer, moveLayer + */ + enum LayerInsertMode { limBelow ///< Layer is inserted below other layer + , limAbove ///< Layer is inserted above other layer + }; + Q_ENUMS(LayerInsertMode) - \see replot - */ - 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 = nullptr); - virtual ~QCustomPlot() Q_DECL_OVERRIDE; - - // 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; } - QCPLayoutGrid *plotLayout() const { return mPlotLayout; } - QCP::AntialiasedElements antialiasedElements() const { return mAntialiasedElements; } - QCP::AntialiasedElements notAntialiasedElements() const { return mNotAntialiasedElements; } - bool autoAddPlottableToLegend() const { return mAutoAddPlottableToLegend; } - const QCP::Interactions interactions() const { return mInteractions; } - int selectionTolerance() const { return mSelectionTolerance; } - 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); - void setBackgroundScaled(bool scaled); - void setBackgroundScaledMode(Qt::AspectRatioMode mode); - void setAntialiasedElements(const QCP::AntialiasedElements &antialiasedElements); - void setAntialiasedElement(QCP::AntialiasedElement antialiasedElement, bool enabled=true); - void setNotAntialiasedElements(const QCP::AntialiasedElements ¬AntialiasedElements); - void setNotAntialiasedElement(QCP::AntialiasedElement notAntialiasedElement, bool enabled=true); - void setAutoAddPlottableToLegend(bool on); - void setInteractions(const QCP::Interactions &interactions); - void setInteraction(const QCP::Interaction &interaction, bool enabled=true); - void setSelectionTolerance(int pixels); - void setNoAntialiasingOnDrag(bool enabled); - 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 removePlottable(QCPAbstractPlottable *plottable); - bool removePlottable(int index); - int clearPlottables(); - int plottableCount() const; - QList selectedPlottables() const; - template - PlottableType *plottableAt(const QPointF &pos, bool onlySelectable=false, int *dataIndex=nullptr) const; - QCPAbstractPlottable *plottableAt(const QPointF &pos, bool onlySelectable=false, int *dataIndex=nullptr) const; - bool hasPlottable(QCPAbstractPlottable *plottable) const; - - // specialized interface for QCPGraph: - QCPGraph *graph(int index) const; - QCPGraph *graph() const; - QCPGraph *addGraph(QCPAxis *keyAxis=nullptr, QCPAxis *valueAxis=nullptr); - bool removeGraph(QCPGraph *graph); - bool removeGraph(int index); - int clearGraphs(); - int graphCount() const; - QList selectedGraphs() const; + /*! + Defines with what timing the QCustomPlot surface is refreshed after a replot. + + \see replot + */ + 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 = nullptr); + virtual ~QCustomPlot() Q_DECL_OVERRIDE; + + // 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; + } + QCPLayoutGrid *plotLayout() const { + return mPlotLayout; + } + QCP::AntialiasedElements antialiasedElements() const { + return mAntialiasedElements; + } + QCP::AntialiasedElements notAntialiasedElements() const { + return mNotAntialiasedElements; + } + bool autoAddPlottableToLegend() const { + return mAutoAddPlottableToLegend; + } + const QCP::Interactions interactions() const { + return mInteractions; + } + int selectionTolerance() const { + return mSelectionTolerance; + } + 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); + void setBackgroundScaled(bool scaled); + void setBackgroundScaledMode(Qt::AspectRatioMode mode); + void setAntialiasedElements(const QCP::AntialiasedElements &antialiasedElements); + void setAntialiasedElement(QCP::AntialiasedElement antialiasedElement, bool enabled = true); + void setNotAntialiasedElements(const QCP::AntialiasedElements ¬AntialiasedElements); + void setNotAntialiasedElement(QCP::AntialiasedElement notAntialiasedElement, bool enabled = true); + void setAutoAddPlottableToLegend(bool on); + void setInteractions(const QCP::Interactions &interactions); + void setInteraction(const QCP::Interaction &interaction, bool enabled = true); + void setSelectionTolerance(int pixels); + void setNoAntialiasingOnDrag(bool enabled); + 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 removePlottable(QCPAbstractPlottable *plottable); + bool removePlottable(int index); + int clearPlottables(); + int plottableCount() const; + QList selectedPlottables() const; + template + PlottableType *plottableAt(const QPointF &pos, bool onlySelectable = false, int *dataIndex = nullptr) const; + QCPAbstractPlottable *plottableAt(const QPointF &pos, bool onlySelectable = false, int *dataIndex = nullptr) const; + bool hasPlottable(QCPAbstractPlottable *plottable) const; + + // specialized interface for QCPGraph: + QCPGraph *graph(int index) const; + QCPGraph *graph() const; + QCPGraph *addGraph(QCPAxis *keyAxis = nullptr, QCPAxis *valueAxis = nullptr); + bool removeGraph(QCPGraph *graph); + bool removeGraph(int index); + int clearGraphs(); + int graphCount() const; + QList selectedGraphs() const; + + // item interface: + QCPAbstractItem *item(int index) const; + QCPAbstractItem *item() const; + bool removeItem(QCPAbstractItem *item); + bool removeItem(int index); + int clearItems(); + int itemCount() const; + QList selectedItems() const; + template + ItemType *itemAt(const QPointF &pos, bool onlySelectable = false) const; + QCPAbstractItem *itemAt(const QPointF &pos, bool onlySelectable = false) const; + bool hasItem(QCPAbstractItem *item) const; + + // layer interface: + QCPLayer *layer(const QString &name) const; + QCPLayer *layer(int index) const; + QCPLayer *currentLayer() const; + bool setCurrentLayer(const QString &name); + bool setCurrentLayer(QCPLayer *layer); + int layerCount() const; + bool addLayer(const QString &name, QCPLayer *otherLayer = nullptr, LayerInsertMode insertMode = limAbove); + bool removeLayer(QCPLayer *layer); + bool moveLayer(QCPLayer *layer, QCPLayer *otherLayer, LayerInsertMode insertMode = limAbove); + + // axis rect/layout interface: + int axisRectCount() const; + 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, 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::rpRefreshHint); + double replotTime(bool average = false) const; + + QCPAxis *xAxis, *yAxis, *xAxis2, *yAxis2; + QCPLegend *legend; - // item interface: - QCPAbstractItem *item(int index) const; - QCPAbstractItem *item() const; - bool removeItem(QCPAbstractItem *item); - bool removeItem(int index); - int clearItems(); - int itemCount() const; - QList selectedItems() const; - template - ItemType *itemAt(const QPointF &pos, bool onlySelectable=false) const; - QCPAbstractItem *itemAt(const QPointF &pos, bool onlySelectable=false) const; - bool hasItem(QCPAbstractItem *item) const; - - // layer interface: - QCPLayer *layer(const QString &name) const; - QCPLayer *layer(int index) const; - QCPLayer *currentLayer() const; - bool setCurrentLayer(const QString &name); - bool setCurrentLayer(QCPLayer *layer); - int layerCount() const; - bool addLayer(const QString &name, QCPLayer *otherLayer=nullptr, LayerInsertMode insertMode=limAbove); - bool removeLayer(QCPLayer *layer); - bool moveLayer(QCPLayer *layer, QCPLayer *otherLayer, LayerInsertMode insertMode=limAbove); - - // axis rect/layout interface: - int axisRectCount() const; - 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, 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::rpRefreshHint); - double replotTime(bool average=false) const; - - QCPAxis *xAxis, *yAxis, *xAxis2, *yAxis2; - QCPLegend *legend; - signals: - void mouseDoubleClick(QMouseEvent *event); - void mousePress(QMouseEvent *event); - void mouseMove(QMouseEvent *event); - void mouseRelease(QMouseEvent *event); - void mouseWheel(QWheelEvent *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 selectionChangedByUser(); - void beforeReplot(); - void afterLayout(); - void afterReplot(); - + void mouseDoubleClick(QMouseEvent *event); + void mousePress(QMouseEvent *event); + void mouseMove(QMouseEvent *event); + void mouseRelease(QMouseEvent *event); + void mouseWheel(QWheelEvent *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 selectionChangedByUser(); + void beforeReplot(); + void afterLayout(); + void afterReplot(); + protected: - // property members: - QRect mViewport; - double mBufferDevicePixelRatio; - QCPLayoutGrid *mPlotLayout; - bool mAutoAddPlottableToLegend; - QList mPlottables; - QList mGraphs; // extra list of plottables also in mPlottables that are of type QCPGraph - QList mItems; - QList mLayers; - QCP::AntialiasedElements mAntialiasedElements, mNotAntialiasedElements; - QCP::Interactions mInteractions; - int mSelectionTolerance; - bool mNoAntialiasingOnDrag; - QBrush mBackgroundBrush; - QPixmap mBackgroundPixmap; - QPixmap mScaledBackgroundPixmap; - bool mBackgroundScaled; - Qt::AspectRatioMode mBackgroundScaledMode; - QCPLayer *mCurrentLayer; - QCP::PlottingHints mPlottingHints; - Qt::KeyboardModifier mMultiSelectModifier; - QCP::SelectionRectMode mSelectionRectMode; - QCPSelectionRect *mSelectionRect; - bool mOpenGl; - - // non-property members: - QList > mPaintBuffers; - QPoint mMousePressPos; - bool mMouseHasMoved; - QPointer mMouseEventLayerable; - QPointer mMouseSignalLayerable; - QVariant mMouseEventLayerableDetails; - QVariant mMouseSignalLayerableDetails; - bool mReplotting; - bool mReplotQueued; - double mReplotTime, mReplotTimeAverage; - int mOpenGlMultisamples; - QCP::AntialiasedElements mOpenGlAntialiasedElementsBackup; - bool mOpenGlCacheLabelsBackup; + // property members: + QRect mViewport; + double mBufferDevicePixelRatio; + QCPLayoutGrid *mPlotLayout; + bool mAutoAddPlottableToLegend; + QList mPlottables; + QList mGraphs; // extra list of plottables also in mPlottables that are of type QCPGraph + QList mItems; + QList mLayers; + QCP::AntialiasedElements mAntialiasedElements, mNotAntialiasedElements; + QCP::Interactions mInteractions; + int mSelectionTolerance; + bool mNoAntialiasingOnDrag; + QBrush mBackgroundBrush; + QPixmap mBackgroundPixmap; + QPixmap mScaledBackgroundPixmap; + bool mBackgroundScaled; + Qt::AspectRatioMode mBackgroundScaledMode; + QCPLayer *mCurrentLayer; + QCP::PlottingHints mPlottingHints; + Qt::KeyboardModifier mMultiSelectModifier; + QCP::SelectionRectMode mSelectionRectMode; + QCPSelectionRect *mSelectionRect; + bool mOpenGl; + + // non-property members: + QList > mPaintBuffers; + QPoint mMousePressPos; + bool mMouseHasMoved; + QPointer mMouseEventLayerable; + QPointer mMouseSignalLayerable; + QVariant mMouseEventLayerableDetails; + QVariant mMouseSignalLayerableDetails; + bool mReplotting; + bool mReplotQueued; + double mReplotTime, mReplotTimeAverage; + int mOpenGlMultisamples; + QCP::AntialiasedElements mOpenGlAntialiasedElementsBackup; + bool mOpenGlCacheLabelsBackup; #ifdef QCP_OPENGL_FBO - QSharedPointer mGlContext; - QSharedPointer mGlSurface; - QSharedPointer mGlPaintDevice; + QSharedPointer mGlContext; + QSharedPointer mGlSurface; + QSharedPointer mGlPaintDevice; #endif - - // reimplemented virtual methods: - 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=nullptr) const; - QList layerableListAt(const QPointF &pos, bool onlySelectable, QList *selectionDetails=nullptr) 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; + + // reimplemented virtual methods: + 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 = nullptr) const; + QList layerableListAt(const QPointF &pos, bool onlySelectable, QList *selectionDetails = nullptr) 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) @@ -4014,49 +4478,47 @@ Q_DECLARE_METATYPE(QCustomPlot::RefreshPriority) Plottables that only consist of single lines (like graphs) have a tolerance band around them, see \ref setSelectionTolerance. If multiple plottables come into consideration, the one closest to \a pos is returned. - + If \a onlySelectable is true, only plottables that are selectable (QCPAbstractPlottable::setSelectable) are considered. - + if \a dataIndex is non-null, it is set to the index of the plottable's data point that is closest to \a pos. If there is no plottable of the specified type at \a pos, returns \c nullptr. - + \see itemAt, layoutElementAt */ template PlottableType *QCustomPlot::plottableAt(const QPointF &pos, bool onlySelectable, int *dataIndex) const { - PlottableType *resultPlottable = 0; - QVariant resultDetails; - double resultDistance = mSelectionTolerance; // only regard clicks with distances smaller than mSelectionTolerance as selections, so initialize with that value - - foreach (QCPAbstractPlottable *plottable, mPlottables) - { - PlottableType *currentPlottable = qobject_cast(plottable); - if (!currentPlottable || (onlySelectable && !currentPlottable->selectable())) // we could have also passed onlySelectable to the selectTest function, but checking here is faster, because we have access to QCPAbstractPlottable::selectable - continue; - if (currentPlottable->clipRect().contains(pos.toPoint())) // only consider clicks where the plottable is actually visible - { - QVariant details; - double currentDistance = currentPlottable->selectTest(pos, false, dataIndex ? &details : nullptr); - if (currentDistance >= 0 && currentDistance < resultDistance) - { - resultPlottable = currentPlottable; - resultDetails = details; - resultDistance = currentDistance; - } + PlottableType *resultPlottable = 0; + QVariant resultDetails; + double resultDistance = mSelectionTolerance; // only regard clicks with distances smaller than mSelectionTolerance as selections, so initialize with that value + + foreach (QCPAbstractPlottable *plottable, mPlottables) { + PlottableType *currentPlottable = qobject_cast(plottable); + if (!currentPlottable || (onlySelectable && !currentPlottable->selectable())) { // we could have also passed onlySelectable to the selectTest function, but checking here is faster, because we have access to QCPAbstractPlottable::selectable + continue; + } + if (currentPlottable->clipRect().contains(pos.toPoint())) { // only consider clicks where the plottable is actually visible + QVariant details; + double currentDistance = currentPlottable->selectTest(pos, false, dataIndex ? &details : nullptr); + if (currentDistance >= 0 && currentDistance < resultDistance) { + resultPlottable = currentPlottable; + resultDetails = details; + resultDistance = currentDistance; + } + } } - } - - if (resultPlottable && dataIndex) - { - QCPDataSelection sel = resultDetails.value(); - if (!sel.isEmpty()) - *dataIndex = sel.dataRange(0).begin(); - } - return resultPlottable; + + if (resultPlottable && dataIndex) { + QCPDataSelection sel = resultDetails.value(); + if (!sel.isEmpty()) { + *dataIndex = sel.dataRange(0).begin(); + } + } + return resultPlottable; } /*! @@ -4064,37 +4526,35 @@ PlottableType *QCustomPlot::plottableAt(const QPointF &pos, bool onlySelectable, taken into consideration can be specified via the template parameter. Items that only consist of single lines (e.g. \ref QCPItemLine or \ref QCPItemCurve) have a tolerance band around them, see \ref setSelectionTolerance. If multiple items come into consideration, the one closest to \a pos is returned. - + If \a onlySelectable is true, only items that are selectable (QCPAbstractItem::setSelectable) are considered. - + If there is no item at \a pos, returns \c nullptr. - + \see plottableAt, layoutElementAt */ template ItemType *QCustomPlot::itemAt(const QPointF &pos, bool onlySelectable) const { - ItemType *resultItem = 0; - double resultDistance = mSelectionTolerance; // only regard clicks with distances smaller than mSelectionTolerance as selections, so initialize with that value - - foreach (QCPAbstractItem *item, mItems) - { - ItemType *currentItem = qobject_cast(item); - if (!currentItem || (onlySelectable && !currentItem->selectable())) // we could have also passed onlySelectable to the selectTest function, but checking here is faster, because we have access to QCPAbstractItem::selectable - continue; - if (!currentItem->clipToAxisRect() || currentItem->clipRect().contains(pos.toPoint())) // only consider clicks inside axis cliprect of the item if actually clipped to it - { - double currentDistance = currentItem->selectTest(pos, false); - if (currentDistance >= 0 && currentDistance < resultDistance) - { - resultItem = currentItem; - resultDistance = currentDistance; - } + ItemType *resultItem = 0; + double resultDistance = mSelectionTolerance; // only regard clicks with distances smaller than mSelectionTolerance as selections, so initialize with that value + + foreach (QCPAbstractItem *item, mItems) { + ItemType *currentItem = qobject_cast(item); + if (!currentItem || (onlySelectable && !currentItem->selectable())) { // we could have also passed onlySelectable to the selectTest function, but checking here is faster, because we have access to QCPAbstractItem::selectable + continue; + } + if (!currentItem->clipToAxisRect() || currentItem->clipRect().contains(pos.toPoint())) { // only consider clicks inside axis cliprect of the item if actually clipped to it + double currentDistance = currentItem->selectTest(pos, false); + if (currentDistance >= 0 && currentDistance < resultDistance) { + resultItem = currentItem; + resultDistance = currentDistance; + } + } } - } - - return resultItem; + + return resultItem; } @@ -4108,56 +4568,56 @@ ItemType *QCustomPlot::itemAt(const QPointF &pos, bool onlySelectable) const class QCPPlottableInterface1D { public: - virtual ~QCPPlottableInterface1D() = default; - // 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; + virtual ~QCPPlottableInterface1D() = default; + // 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 QCPAbstractPlottable1D : public QCPAbstractPlottable, public QCPPlottableInterface1D // no QCP_LIB_DECL, template class ends up in header (cpp included below) { - // No Q_OBJECT macro due to template class - + // No Q_OBJECT macro due to template class + public: - QCPAbstractPlottable1D(QCPAxis *keyAxis, QCPAxis *valueAxis); - virtual ~QCPAbstractPlottable1D() Q_DECL_OVERRIDE; - - // virtual methods of 1d plottable interface: - virtual int dataCount() const Q_DECL_OVERRIDE; - virtual double dataMainKey(int index) const Q_DECL_OVERRIDE; - virtual double dataSortKey(int index) const Q_DECL_OVERRIDE; - virtual double dataMainValue(int index) const Q_DECL_OVERRIDE; - virtual QCPRange dataValueRange(int index) const Q_DECL_OVERRIDE; - virtual QPointF dataPixelPosition(int index) const Q_DECL_OVERRIDE; - virtual bool sortKeyIsMainKey() const Q_DECL_OVERRIDE; - virtual QCPDataSelection selectTestRect(const QRectF &rect, bool onlySelectable) const Q_DECL_OVERRIDE; - virtual int findBegin(double sortKey, bool expandedRange=true) const Q_DECL_OVERRIDE; - virtual int findEnd(double sortKey, bool expandedRange=true) const Q_DECL_OVERRIDE; - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE; - virtual QCPPlottableInterface1D *interface1D() Q_DECL_OVERRIDE { return this; } - + QCPAbstractPlottable1D(QCPAxis *keyAxis, QCPAxis *valueAxis); + virtual ~QCPAbstractPlottable1D() Q_DECL_OVERRIDE; + + // virtual methods of 1d plottable interface: + virtual int dataCount() const Q_DECL_OVERRIDE; + virtual double dataMainKey(int index) const Q_DECL_OVERRIDE; + virtual double dataSortKey(int index) const Q_DECL_OVERRIDE; + virtual double dataMainValue(int index) const Q_DECL_OVERRIDE; + virtual QCPRange dataValueRange(int index) const Q_DECL_OVERRIDE; + virtual QPointF dataPixelPosition(int index) const Q_DECL_OVERRIDE; + virtual bool sortKeyIsMainKey() const Q_DECL_OVERRIDE; + virtual QCPDataSelection selectTestRect(const QRectF &rect, bool onlySelectable) const Q_DECL_OVERRIDE; + virtual int findBegin(double sortKey, bool expandedRange = true) const Q_DECL_OVERRIDE; + virtual int findEnd(double sortKey, bool expandedRange = true) const Q_DECL_OVERRIDE; + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = nullptr) const Q_DECL_OVERRIDE; + virtual QCPPlottableInterface1D *interface1D() Q_DECL_OVERRIDE { 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; + // 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) - + Q_DISABLE_COPY(QCPAbstractPlottable1D) + }; @@ -4193,55 +4653,55 @@ private: /* 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. @@ -4335,10 +4795,10 @@ private: /* start documentation of inline functions */ /*! \fn QCPPlottableInterface1D *QCPAbstractPlottable1D::interface1D() - + Returns a \ref QCPPlottableInterface1D pointer to this plottable, providing access to its 1D interface. - + \seebaseclassmethod */ @@ -4350,8 +4810,8 @@ private: */ template QCPAbstractPlottable1D::QCPAbstractPlottable1D(QCPAxis *keyAxis, QCPAxis *valueAxis) : - QCPAbstractPlottable(keyAxis, valueAxis), - mDataContainer(new QCPDataContainer) + QCPAbstractPlottable(keyAxis, valueAxis), + mDataContainer(new QCPDataContainer) { } @@ -4366,7 +4826,7 @@ QCPAbstractPlottable1D::~QCPAbstractPlottable1D() template int QCPAbstractPlottable1D::dataCount() const { - return mDataContainer->size(); + return mDataContainer->size(); } /*! @@ -4375,14 +4835,12 @@ int QCPAbstractPlottable1D::dataCount() const 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; - } + if (index >= 0 && index < mDataContainer->size()) { + return (mDataContainer->constBegin() + index)->mainKey(); + } else { + qDebug() << Q_FUNC_INFO << "Index out of bounds" << index; + return 0; + } } /*! @@ -4391,14 +4849,12 @@ double QCPAbstractPlottable1D::dataMainKey(int index) const 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; - } + if (index >= 0 && index < mDataContainer->size()) { + return (mDataContainer->constBegin() + index)->sortKey(); + } else { + qDebug() << Q_FUNC_INFO << "Index out of bounds" << index; + return 0; + } } /*! @@ -4407,14 +4863,12 @@ double QCPAbstractPlottable1D::dataSortKey(int index) const 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; - } + if (index >= 0 && index < mDataContainer->size()) { + return (mDataContainer->constBegin() + index)->mainValue(); + } else { + qDebug() << Q_FUNC_INFO << "Index out of bounds" << index; + return 0; + } } /*! @@ -4423,14 +4877,12 @@ double QCPAbstractPlottable1D::dataMainValue(int index) const 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); - } + 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); + } } /*! @@ -4439,15 +4891,13 @@ QCPRange QCPAbstractPlottable1D::dataValueRange(int index) const 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(); - } + 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(); + } } /*! @@ -4456,7 +4906,7 @@ QPointF QCPAbstractPlottable1D::dataPixelPosition(int index) const template bool QCPAbstractPlottable1D::sortKeyIsMainKey() const { - return DataType::sortKeyIsMainKey(); + return DataType::sortKeyIsMainKey(); } /*! @@ -4469,47 +4919,48 @@ bool QCPAbstractPlottable1D::sortKeyIsMainKey() const 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 = int(it-mDataContainer->constBegin()); - } else if (!valueRange.contains(it->mainValue()) || !keyRange.contains(it->mainKey())) // segment just ended - { - result.addDataRange(QCPDataRange(currentSegmentBegin, int(it-mDataContainer->constBegin())), false); - currentSegmentBegin = -1; + QCPDataSelection result; + if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty()) { + return result; } - } - // process potential last segment: - if (currentSegmentBegin != -1) - result.addDataRange(QCPDataRange(currentSegmentBegin, int(end-mDataContainer->constBegin())), false); - - result.simplify(); - 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 = int(it - mDataContainer->constBegin()); + } + } else if (!valueRange.contains(it->mainValue()) || !keyRange.contains(it->mainKey())) { // segment just ended + result.addDataRange(QCPDataRange(currentSegmentBegin, int(it - mDataContainer->constBegin())), false); + currentSegmentBegin = -1; + } + } + // process potential last segment: + if (currentSegmentBegin != -1) { + result.addDataRange(QCPDataRange(currentSegmentBegin, int(end - mDataContainer->constBegin())), false); + } + + result.simplify(); + return result; } /*! @@ -4518,7 +4969,7 @@ QCPDataSelection QCPAbstractPlottable1D::selectTestRect(const QRectF & template int QCPAbstractPlottable1D::findBegin(double sortKey, bool expandedRange) const { - return int(mDataContainer->findBegin(sortKey, expandedRange)-mDataContainer->constBegin()); + return int(mDataContainer->findBegin(sortKey, expandedRange) - mDataContainer->constBegin()); } /*! @@ -4527,7 +4978,7 @@ int QCPAbstractPlottable1D::findBegin(double sortKey, bool expandedRan template int QCPAbstractPlottable1D::findEnd(double sortKey, bool expandedRange) const { - return int(mDataContainer->findEnd(sortKey, expandedRange)-mDataContainer->constBegin()); + return int(mDataContainer->findEnd(sortKey, expandedRange) - mDataContainer->constBegin()); } /*! @@ -4537,59 +4988,61 @@ int QCPAbstractPlottable1D::findEnd(double sortKey, bool expandedRange If \a details is not 0, it will be set to a \ref QCPDataSelection, describing the closest data point to \a pos. - + \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 = int(it-mDataContainer->constBegin()); - } + if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty()) { + return -1; } - } - if (minDistIndex != mDataContainer->size()) - selectionResult.addDataRange(QCPDataRange(minDistIndex, minDistIndex+1), false); - - selectionResult.simplify(); - if (details) - details->setValue(selectionResult); - return qSqrt(minDistSqr); + 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 = int(it - mDataContainer->constBegin()); + } + } + } + if (minDistIndex != mDataContainer->size()) { + selectionResult.addDataRange(QCPDataRange(minDistIndex, minDistIndex + 1), false); + } + + selectionResult.simplify(); + if (details) { + details->setValue(selectionResult); + } + return qSqrt(minDistSqr); } /*! @@ -4605,21 +5058,20 @@ double QCPAbstractPlottable1D::selectTest(const QPointF &pos, bool onl 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(); - } + 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(); + } } /*! @@ -4635,59 +5087,55 @@ void QCPAbstractPlottable1D::getDataSegments(QList &sele template void QCPAbstractPlottable1D::drawPolyline(QCPPainter *painter, const QVector &lineData) const { - // if drawing lines in plot (instead of PDF), reduce 1px lines to cosmetic, because at least in - // Qt6 drawing of "1px" width lines is much slower even though it has same appearance apart from - // High-DPI. In High-DPI cases people must set a pen width slightly larger than 1.0 to get - // correct DPI scaling of width, but of course with performance penalty. - if (!painter->modes().testFlag(QCPPainter::pmVectorized) && - qFuzzyCompare(painter->pen().widthF(), 1.0)) - { - QPen newPen = painter->pen(); - newPen.setWidth(0); - painter->setPen(newPen); - } + // if drawing lines in plot (instead of PDF), reduce 1px lines to cosmetic, because at least in + // Qt6 drawing of "1px" width lines is much slower even though it has same appearance apart from + // High-DPI. In High-DPI cases people must set a pen width slightly larger than 1.0 to get + // correct DPI scaling of width, but of course with performance penalty. + if (!painter->modes().testFlag(QCPPainter::pmVectorized) && + qFuzzyCompare(painter->pen().widthF(), 1.0)) { + QPen newPen = painter->pen(); + newPen.setWidth(0); + painter->setPen(newPen); + } - // 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; + // 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); } - } 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); - } } @@ -4699,96 +5147,110 @@ void QCPAbstractPlottable1D::drawPolyline(QCPPainter *painter, const Q class QCP_LIB_DECL QCPColorGradient { - Q_GADGET + Q_GADGET public: - /*! - Defines the color spaces in which color interpolation between gradient stops can be performed. - - \see setColorInterpolation - */ - enum ColorInterpolation { ciRGB ///< Color channels red, green and blue are linearly interpolated - ,ciHSV ///< Color channels hue, saturation and value are linearly interpolated (The hue is interpolated over the shortest angle distance) - }; - Q_ENUMS(ColorInterpolation) - - /*! - Defines how NaN data points shall appear in the plot. - - \see setNanHandling, setNanColor - */ - enum NanHandling { nhNone ///< NaN data points are not explicitly handled and shouldn't occur in the data (this gives slight performance improvement) - ,nhLowestColor ///< NaN data points appear as the lowest color defined in this QCPColorGradient - ,nhHighestColor ///< NaN data points appear as the highest color defined in this QCPColorGradient - ,nhTransparent ///< NaN data points appear transparent - ,nhNanColor ///< NaN data points appear as the color defined with \ref setNanColor - }; - Q_ENUMS(NanHandling) - - /*! - Defines the available presets that can be loaded with \ref loadPreset. See the documentation - there for an image of the presets. - */ - enum GradientPreset { gpGrayscale ///< Continuous lightness from black to white (suited for non-biased data representation) - ,gpHot ///< Continuous lightness from black over firey colors to white (suited for non-biased data representation) - ,gpCold ///< Continuous lightness from black over icey colors to white (suited for non-biased data representation) - ,gpNight ///< Continuous lightness from black over weak blueish colors to white (suited for non-biased data representation) - ,gpCandy ///< Blue over pink to white - ,gpGeography ///< Colors suitable to represent different elevations on geographical maps - ,gpIon ///< Half hue spectrum from black over purple to blue and finally green (creates banding illusion but allows more precise magnitude estimates) - ,gpThermal ///< Colors suitable for thermal imaging, ranging from dark blue over purple to orange, yellow and white - ,gpPolar ///< Colors suitable to emphasize polarity around the center, with blue for negative, black in the middle and red for positive values - ,gpSpectrum ///< An approximation of the visible light spectrum (creates banding illusion but allows more precise magnitude estimates) - ,gpJet ///< Hue variation similar to a spectrum, often used in numerical visualization (creates banding illusion but allows more precise magnitude estimates) - ,gpHues ///< Full hue cycle, with highest and lowest color red (suitable for periodic data, such as angles and phases, see \ref setPeriodic) - }; - Q_ENUMS(GradientPreset) - - QCPColorGradient(); - QCPColorGradient(GradientPreset preset); - bool operator==(const QCPColorGradient &other) const; - bool operator!=(const QCPColorGradient &other) const { return !(*this == other); } - - // getters: - int levelCount() const { return mLevelCount; } - QMap colorStops() const { return mColorStops; } - ColorInterpolation colorInterpolation() const { return mColorInterpolation; } - NanHandling nanHandling() const { return mNanHandling; } - QColor nanColor() const { return mNanColor; } - bool periodic() const { return mPeriodic; } - - // setters: - void setLevelCount(int n); - void setColorStops(const QMap &colorStops); - void setColorStopAt(double position, const QColor &color); - void setColorInterpolation(ColorInterpolation interpolation); - void setNanHandling(NanHandling handling); - void setNanColor(const QColor &color); - void setPeriodic(bool enabled); - - // 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; - + /*! + Defines the color spaces in which color interpolation between gradient stops can be performed. + + \see setColorInterpolation + */ + enum ColorInterpolation { ciRGB ///< Color channels red, green and blue are linearly interpolated + , ciHSV ///< Color channels hue, saturation and value are linearly interpolated (The hue is interpolated over the shortest angle distance) + }; + Q_ENUMS(ColorInterpolation) + + /*! + Defines how NaN data points shall appear in the plot. + + \see setNanHandling, setNanColor + */ + enum NanHandling { nhNone ///< NaN data points are not explicitly handled and shouldn't occur in the data (this gives slight performance improvement) + , nhLowestColor ///< NaN data points appear as the lowest color defined in this QCPColorGradient + , nhHighestColor ///< NaN data points appear as the highest color defined in this QCPColorGradient + , nhTransparent ///< NaN data points appear transparent + , nhNanColor ///< NaN data points appear as the color defined with \ref setNanColor + }; + Q_ENUMS(NanHandling) + + /*! + Defines the available presets that can be loaded with \ref loadPreset. See the documentation + there for an image of the presets. + */ + enum GradientPreset { gpGrayscale ///< Continuous lightness from black to white (suited for non-biased data representation) + , gpHot ///< Continuous lightness from black over firey colors to white (suited for non-biased data representation) + , gpCold ///< Continuous lightness from black over icey colors to white (suited for non-biased data representation) + , gpNight ///< Continuous lightness from black over weak blueish colors to white (suited for non-biased data representation) + , gpCandy ///< Blue over pink to white + , gpGeography ///< Colors suitable to represent different elevations on geographical maps + , gpIon ///< Half hue spectrum from black over purple to blue and finally green (creates banding illusion but allows more precise magnitude estimates) + , gpThermal ///< Colors suitable for thermal imaging, ranging from dark blue over purple to orange, yellow and white + , gpPolar ///< Colors suitable to emphasize polarity around the center, with blue for negative, black in the middle and red for positive values + , gpSpectrum ///< An approximation of the visible light spectrum (creates banding illusion but allows more precise magnitude estimates) + , gpJet ///< Hue variation similar to a spectrum, often used in numerical visualization (creates banding illusion but allows more precise magnitude estimates) + , gpHues ///< Full hue cycle, with highest and lowest color red (suitable for periodic data, such as angles and phases, see \ref setPeriodic) + }; + Q_ENUMS(GradientPreset) + + QCPColorGradient(); + QCPColorGradient(GradientPreset preset); + bool operator==(const QCPColorGradient &other) const; + bool operator!=(const QCPColorGradient &other) const { + return !(*this == other); + } + + // getters: + int levelCount() const { + return mLevelCount; + } + QMap colorStops() const { + return mColorStops; + } + ColorInterpolation colorInterpolation() const { + return mColorInterpolation; + } + NanHandling nanHandling() const { + return mNanHandling; + } + QColor nanColor() const { + return mNanColor; + } + bool periodic() const { + return mPeriodic; + } + + // setters: + void setLevelCount(int n); + void setColorStops(const QMap &colorStops); + void setColorStopAt(double position, const QColor &color); + void setColorInterpolation(ColorInterpolation interpolation); + void setNanHandling(NanHandling handling); + void setNanColor(const QColor &color); + void setPeriodic(bool enabled); + + // 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: - // property members: - int mLevelCount; - QMap mColorStops; - ColorInterpolation mColorInterpolation; - NanHandling mNanHandling; - QColor mNanColor; - bool mPeriodic; - - // non-property members: - QVector mColorBuffer; // have colors premultiplied with alpha (for usage with QImage::Format_ARGB32_Premultiplied) - bool mColorBufferInvalidated; - - // non-virtual methods: - bool stopsUseAlpha() const; - void updateColorBuffer(); + // property members: + int mLevelCount; + QMap mColorStops; + ColorInterpolation mColorInterpolation; + NanHandling mNanHandling; + QColor mNanColor; + bool mPeriodic; + + // non-property members: + 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::NanHandling) @@ -4802,64 +5264,78 @@ Q_DECLARE_METATYPE(QCPColorGradient::GradientPreset) class QCP_LIB_DECL QCPSelectionDecoratorBracket : public QCPSelectionDecorator { - Q_GADGET + 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() Q_DECL_OVERRIDE; - - // 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) Q_DECL_OVERRIDE; - + + /*! + 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() Q_DECL_OVERRIDE; + + // 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) Q_DECL_OVERRIDE; + 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; - + // 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) @@ -4871,121 +5347,158 @@ Q_DECLARE_METATYPE(QCPSelectionDecoratorBracket::BracketStyle) class QCP_LIB_DECL QCPAxisRect : public QCPLayoutElement { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QPixmap background READ background WRITE setBackground) - Q_PROPERTY(bool backgroundScaled READ backgroundScaled WRITE setBackgroundScaled) - Q_PROPERTY(Qt::AspectRatioMode backgroundScaledMode READ backgroundScaledMode WRITE setBackgroundScaledMode) - Q_PROPERTY(Qt::Orientations rangeDrag READ rangeDrag WRITE setRangeDrag) - Q_PROPERTY(Qt::Orientations rangeZoom READ rangeZoom WRITE setRangeZoom) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QPixmap background READ background WRITE setBackground) + Q_PROPERTY(bool backgroundScaled READ backgroundScaled WRITE setBackgroundScaled) + Q_PROPERTY(Qt::AspectRatioMode backgroundScaledMode READ backgroundScaledMode WRITE setBackgroundScaledMode) + Q_PROPERTY(Qt::Orientations rangeDrag READ rangeDrag WRITE setRangeDrag) + Q_PROPERTY(Qt::Orientations rangeZoom READ rangeZoom WRITE setRangeZoom) + /// \endcond public: - explicit QCPAxisRect(QCustomPlot *parentPlot, bool setupDefaultAxes=true); - virtual ~QCPAxisRect() Q_DECL_OVERRIDE; - - // 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: - void setBackground(const QPixmap &pm); - void setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode=Qt::KeepAspectRatioByExpanding); - void setBackground(const QBrush &brush); - void setBackgroundScaled(bool scaled); - void setBackgroundScaledMode(Qt::AspectRatioMode mode); - 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); - - // non-property methods: - int axisCount(QCPAxis::AxisType type) const; - QCPAxis *axis(QCPAxis::AxisType type, int index=0) const; - QList axes(QCPAxis::AxisTypes types) const; - QList axes() const; - QCPAxis *addAxis(QCPAxis::AxisType type, QCPAxis *axis=nullptr); - QList addAxes(QCPAxis::AxisTypes types); - 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; - QList items() const; - - // read-only interface imitating a QRect: - int left() const { return mRect.left(); } - int right() const { return mRect.right(); } - int top() const { return mRect.top(); } - int bottom() const { return mRect.bottom(); } - int width() const { return mRect.width(); } - int height() const { return mRect.height(); } - QSize size() const { return mRect.size(); } - QPoint topLeft() const { return mRect.topLeft(); } - QPoint topRight() const { return mRect.topRight(); } - QPoint bottomLeft() const { return mRect.bottomLeft(); } - QPoint bottomRight() const { return mRect.bottomRight(); } - QPoint center() const { return mRect.center(); } - - // reimplemented virtual methods: - virtual void update(UpdatePhase phase) Q_DECL_OVERRIDE; - virtual QList elements(bool recursive) const Q_DECL_OVERRIDE; + explicit QCPAxisRect(QCustomPlot *parentPlot, bool setupDefaultAxes = true); + virtual ~QCPAxisRect() Q_DECL_OVERRIDE; + + // 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: + void setBackground(const QPixmap &pm); + void setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode = Qt::KeepAspectRatioByExpanding); + void setBackground(const QBrush &brush); + void setBackgroundScaled(bool scaled); + void setBackgroundScaledMode(Qt::AspectRatioMode mode); + 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); + + // non-property methods: + int axisCount(QCPAxis::AxisType type) const; + QCPAxis *axis(QCPAxis::AxisType type, int index = 0) const; + QList axes(QCPAxis::AxisTypes types) const; + QList axes() const; + QCPAxis *addAxis(QCPAxis::AxisType type, QCPAxis *axis = nullptr); + QList addAxes(QCPAxis::AxisTypes types); + 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; + QList items() const; + + // read-only interface imitating a QRect: + int left() const { + return mRect.left(); + } + int right() const { + return mRect.right(); + } + int top() const { + return mRect.top(); + } + int bottom() const { + return mRect.bottom(); + } + int width() const { + return mRect.width(); + } + int height() const { + return mRect.height(); + } + QSize size() const { + return mRect.size(); + } + QPoint topLeft() const { + return mRect.topLeft(); + } + QPoint topRight() const { + return mRect.topRight(); + } + QPoint bottomLeft() const { + return mRect.bottomLeft(); + } + QPoint bottomRight() const { + return mRect.bottomRight(); + } + QPoint center() const { + return mRect.center(); + } + + // reimplemented virtual methods: + virtual void update(UpdatePhase phase) Q_DECL_OVERRIDE; + virtual QList elements(bool recursive) const Q_DECL_OVERRIDE; protected: - // property members: - QBrush mBackgroundBrush; - QPixmap mBackgroundPixmap; - QPixmap mScaledBackgroundPixmap; - bool mBackgroundScaled; - Qt::AspectRatioMode mBackgroundScaledMode; - QCPLayoutInset *mInsetLayout; - Qt::Orientations mRangeDrag, mRangeZoom; - QList > mRangeDragHorzAxis, mRangeDragVertAxis; - QList > mRangeZoomHorzAxis, mRangeZoomVertAxis; - double mRangeZoomFactorHorz, mRangeZoomFactorVert; - - // non-property members: - QList mDragStartHorzRange, mDragStartVertRange; - QCP::AntialiasedElements mAADragBackup, mNotAADragBackup; - bool mDragging; - QHash > mAxes; - - // reimplemented virtual methods: - 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, 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); - void updateAxesOffset(QCPAxis::AxisType type); - + // property members: + QBrush mBackgroundBrush; + QPixmap mBackgroundPixmap; + QPixmap mScaledBackgroundPixmap; + bool mBackgroundScaled; + Qt::AspectRatioMode mBackgroundScaledMode; + QCPLayoutInset *mInsetLayout; + Qt::Orientations mRangeDrag, mRangeZoom; + QList > mRangeDragHorzAxis, mRangeDragVertAxis; + QList > mRangeZoomHorzAxis, mRangeZoomVertAxis; + double mRangeZoomFactorHorz, mRangeZoomFactorVert; + + // non-property members: + QList mDragStartHorzRange, mDragStartVertRange; + QCP::AntialiasedElements mAADragBackup, mNotAADragBackup; + bool mDragging; + QHash > mAxes; + + // reimplemented virtual methods: + 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, 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); + void updateAxesOffset(QCPAxis::AxisType type); + private: - Q_DISABLE_COPY(QCPAxisRect) - - friend class QCustomPlot; + Q_DISABLE_COPY(QCPAxisRect) + + friend class QCustomPlot; }; @@ -4997,212 +5510,252 @@ private: class QCP_LIB_DECL QCPAbstractLegendItem : public QCPLayoutElement { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QCPLegend* parentLegend READ parentLegend) - Q_PROPERTY(QFont font READ font WRITE setFont) - Q_PROPERTY(QColor textColor READ textColor WRITE setTextColor) - Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont) - Q_PROPERTY(QColor selectedTextColor READ selectedTextColor WRITE setSelectedTextColor) - Q_PROPERTY(bool selectable READ selectable WRITE setSelectable NOTIFY selectionChanged) - Q_PROPERTY(bool selected READ selected WRITE setSelected NOTIFY selectableChanged) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QCPLegend* parentLegend READ parentLegend) + Q_PROPERTY(QFont font READ font WRITE setFont) + Q_PROPERTY(QColor textColor READ textColor WRITE setTextColor) + Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont) + Q_PROPERTY(QColor selectedTextColor READ selectedTextColor WRITE setSelectedTextColor) + Q_PROPERTY(bool selectable READ selectable WRITE setSelectable NOTIFY selectionChanged) + Q_PROPERTY(bool selected READ selected WRITE setSelected NOTIFY selectableChanged) + /// \endcond public: - explicit QCPAbstractLegendItem(QCPLegend *parent); - - // getters: - QCPLegend *parentLegend() const { return mParentLegend; } - QFont font() const { return mFont; } - QColor textColor() const { return mTextColor; } - QFont selectedFont() const { return mSelectedFont; } - QColor selectedTextColor() const { return mSelectedTextColor; } - bool selectable() const { return mSelectable; } - bool selected() const { return mSelected; } - - // setters: - void setFont(const QFont &font); - void setTextColor(const QColor &color); - void setSelectedFont(const QFont &font); - void setSelectedTextColor(const QColor &color); - Q_SLOT void setSelectable(bool selectable); - Q_SLOT void setSelected(bool selected); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE; - + explicit QCPAbstractLegendItem(QCPLegend *parent); + + // getters: + QCPLegend *parentLegend() const { + return mParentLegend; + } + QFont font() const { + return mFont; + } + QColor textColor() const { + return mTextColor; + } + QFont selectedFont() const { + return mSelectedFont; + } + QColor selectedTextColor() const { + return mSelectedTextColor; + } + bool selectable() const { + return mSelectable; + } + bool selected() const { + return mSelected; + } + + // setters: + void setFont(const QFont &font); + void setTextColor(const QColor &color); + void setSelectedFont(const QFont &font); + void setSelectedTextColor(const QColor &color); + Q_SLOT void setSelectable(bool selectable); + Q_SLOT void setSelected(bool selected); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = nullptr) const Q_DECL_OVERRIDE; + signals: - void selectionChanged(bool selected); - void selectableChanged(bool selectable); - + void selectionChanged(bool selected); + void selectableChanged(bool selectable); + protected: - // property members: - QCPLegend *mParentLegend; - QFont mFont; - QColor mTextColor; - QFont mSelectedFont; - QColor mSelectedTextColor; - bool mSelectable, mSelected; - - // reimplemented virtual methods: - 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) Q_DECL_OVERRIDE; - virtual void deselectEvent(bool *selectionStateChanged) Q_DECL_OVERRIDE; - + // property members: + QCPLegend *mParentLegend; + QFont mFont; + QColor mTextColor; + QFont mSelectedFont; + QColor mSelectedTextColor; + bool mSelectable, mSelected; + + // reimplemented virtual methods: + 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) Q_DECL_OVERRIDE; + virtual void deselectEvent(bool *selectionStateChanged) Q_DECL_OVERRIDE; + private: - Q_DISABLE_COPY(QCPAbstractLegendItem) - - friend class QCPLegend; + Q_DISABLE_COPY(QCPAbstractLegendItem) + + friend class QCPLegend; }; class QCP_LIB_DECL QCPPlottableLegendItem : public QCPAbstractLegendItem { - Q_OBJECT -public: - QCPPlottableLegendItem(QCPLegend *parent, QCPAbstractPlottable *plottable); - - // getters: - QCPAbstractPlottable *plottable() { return mPlottable; } - + Q_OBJECT +public: QCPPlottableLegendItem(QCPLegend *parent, QCPAbstractPlottable *plottable); + + // getters: + QCPAbstractPlottable *plottable() { + return mPlottable; + } + protected: - // property members: - QCPAbstractPlottable *mPlottable; - - // reimplemented virtual methods: - virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; - virtual QSize minimumOuterSizeHint() const Q_DECL_OVERRIDE; - - // non-virtual methods: - QPen getIconBorderPen() const; - QColor getTextColor() const; - QFont getFont() const; + // property members: + QCPAbstractPlottable *mPlottable; + + // reimplemented virtual methods: + virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; + virtual QSize minimumOuterSizeHint() const Q_DECL_OVERRIDE; + + // non-virtual methods: + QPen getIconBorderPen() const; + QColor getTextColor() const; + QFont getFont() const; }; class QCP_LIB_DECL QCPLegend : public QCPLayoutGrid { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QPen borderPen READ borderPen WRITE setBorderPen) - Q_PROPERTY(QBrush brush READ brush WRITE setBrush) - Q_PROPERTY(QFont font READ font WRITE setFont) - Q_PROPERTY(QColor textColor READ textColor WRITE setTextColor) - Q_PROPERTY(QSize iconSize READ iconSize WRITE setIconSize) - Q_PROPERTY(int iconTextPadding READ iconTextPadding WRITE setIconTextPadding) - Q_PROPERTY(QPen iconBorderPen READ iconBorderPen WRITE setIconBorderPen) - Q_PROPERTY(SelectableParts selectableParts READ selectableParts WRITE setSelectableParts NOTIFY selectionChanged) - Q_PROPERTY(SelectableParts selectedParts READ selectedParts WRITE setSelectedParts NOTIFY selectableChanged) - Q_PROPERTY(QPen selectedBorderPen READ selectedBorderPen WRITE setSelectedBorderPen) - Q_PROPERTY(QPen selectedIconBorderPen READ selectedIconBorderPen WRITE setSelectedIconBorderPen) - Q_PROPERTY(QBrush selectedBrush READ selectedBrush WRITE setSelectedBrush) - Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont) - Q_PROPERTY(QColor selectedTextColor READ selectedTextColor WRITE setSelectedTextColor) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(QPen borderPen READ borderPen WRITE setBorderPen) + Q_PROPERTY(QBrush brush READ brush WRITE setBrush) + Q_PROPERTY(QFont font READ font WRITE setFont) + Q_PROPERTY(QColor textColor READ textColor WRITE setTextColor) + Q_PROPERTY(QSize iconSize READ iconSize WRITE setIconSize) + Q_PROPERTY(int iconTextPadding READ iconTextPadding WRITE setIconTextPadding) + Q_PROPERTY(QPen iconBorderPen READ iconBorderPen WRITE setIconBorderPen) + Q_PROPERTY(SelectableParts selectableParts READ selectableParts WRITE setSelectableParts NOTIFY selectionChanged) + Q_PROPERTY(SelectableParts selectedParts READ selectedParts WRITE setSelectedParts NOTIFY selectableChanged) + Q_PROPERTY(QPen selectedBorderPen READ selectedBorderPen WRITE setSelectedBorderPen) + Q_PROPERTY(QPen selectedIconBorderPen READ selectedIconBorderPen WRITE setSelectedIconBorderPen) + Q_PROPERTY(QBrush selectedBrush READ selectedBrush WRITE setSelectedBrush) + Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont) + Q_PROPERTY(QColor selectedTextColor READ selectedTextColor WRITE setSelectedTextColor) + /// \endcond public: - /*! - Defines the selectable parts of a legend - - \see setSelectedParts, setSelectableParts - */ - enum SelectablePart { spNone = 0x000 ///< 0x000 None - ,spLegendBox = 0x001 ///< 0x001 The legend box (frame) - ,spItems = 0x002 ///< 0x002 Legend items individually (see \ref selectedItems) - }; - Q_ENUMS(SelectablePart) - Q_FLAGS(SelectableParts) - Q_DECLARE_FLAGS(SelectableParts, SelectablePart) - - explicit QCPLegend(); - virtual ~QCPLegend() Q_DECL_OVERRIDE; - - // getters: - QPen borderPen() const { return mBorderPen; } - QBrush brush() const { return mBrush; } - QFont font() const { return mFont; } - QColor textColor() const { return mTextColor; } - QSize iconSize() const { return mIconSize; } - int iconTextPadding() const { return mIconTextPadding; } - QPen iconBorderPen() const { return mIconBorderPen; } - SelectableParts selectableParts() const { return mSelectableParts; } - SelectableParts selectedParts() const; - QPen selectedBorderPen() const { return mSelectedBorderPen; } - QPen selectedIconBorderPen() const { return mSelectedIconBorderPen; } - QBrush selectedBrush() const { return mSelectedBrush; } - QFont selectedFont() const { return mSelectedFont; } - QColor selectedTextColor() const { return mSelectedTextColor; } - - // setters: - void setBorderPen(const QPen &pen); - void setBrush(const QBrush &brush); - void setFont(const QFont &font); - void setTextColor(const QColor &color); - void setIconSize(const QSize &size); - void setIconSize(int width, int height); - void setIconTextPadding(int padding); - void setIconBorderPen(const QPen &pen); - Q_SLOT void setSelectableParts(const SelectableParts &selectableParts); - Q_SLOT void setSelectedParts(const SelectableParts &selectedParts); - void setSelectedBorderPen(const QPen &pen); - void setSelectedIconBorderPen(const QPen &pen); - void setSelectedBrush(const QBrush &brush); - void setSelectedFont(const QFont &font); - void setSelectedTextColor(const QColor &color); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE; - - // non-virtual methods: - QCPAbstractLegendItem *item(int index) const; - QCPPlottableLegendItem *itemWithPlottable(const QCPAbstractPlottable *plottable) const; - int itemCount() const; - bool hasItem(QCPAbstractLegendItem *item) const; - bool hasItemWithPlottable(const QCPAbstractPlottable *plottable) const; - bool addItem(QCPAbstractLegendItem *item); - bool removeItem(int index); - bool removeItem(QCPAbstractLegendItem *item); - void clearItems(); - QList selectedItems() const; - + /*! + Defines the selectable parts of a legend + + \see setSelectedParts, setSelectableParts + */ + enum SelectablePart { spNone = 0x000 ///< 0x000 None + , spLegendBox = 0x001 ///< 0x001 The legend box (frame) + , spItems = 0x002 ///< 0x002 Legend items individually (see \ref selectedItems) + }; + Q_ENUMS(SelectablePart) + Q_FLAGS(SelectableParts) + Q_DECLARE_FLAGS(SelectableParts, SelectablePart) + + explicit QCPLegend(); + virtual ~QCPLegend() Q_DECL_OVERRIDE; + + // getters: + QPen borderPen() const { + return mBorderPen; + } + QBrush brush() const { + return mBrush; + } + QFont font() const { + return mFont; + } + QColor textColor() const { + return mTextColor; + } + QSize iconSize() const { + return mIconSize; + } + int iconTextPadding() const { + return mIconTextPadding; + } + QPen iconBorderPen() const { + return mIconBorderPen; + } + SelectableParts selectableParts() const { + return mSelectableParts; + } + SelectableParts selectedParts() const; + QPen selectedBorderPen() const { + return mSelectedBorderPen; + } + QPen selectedIconBorderPen() const { + return mSelectedIconBorderPen; + } + QBrush selectedBrush() const { + return mSelectedBrush; + } + QFont selectedFont() const { + return mSelectedFont; + } + QColor selectedTextColor() const { + return mSelectedTextColor; + } + + // setters: + void setBorderPen(const QPen &pen); + void setBrush(const QBrush &brush); + void setFont(const QFont &font); + void setTextColor(const QColor &color); + void setIconSize(const QSize &size); + void setIconSize(int width, int height); + void setIconTextPadding(int padding); + void setIconBorderPen(const QPen &pen); + Q_SLOT void setSelectableParts(const SelectableParts &selectableParts); + Q_SLOT void setSelectedParts(const SelectableParts &selectedParts); + void setSelectedBorderPen(const QPen &pen); + void setSelectedIconBorderPen(const QPen &pen); + void setSelectedBrush(const QBrush &brush); + void setSelectedFont(const QFont &font); + void setSelectedTextColor(const QColor &color); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = nullptr) const Q_DECL_OVERRIDE; + + // non-virtual methods: + QCPAbstractLegendItem *item(int index) const; + QCPPlottableLegendItem *itemWithPlottable(const QCPAbstractPlottable *plottable) const; + int itemCount() const; + bool hasItem(QCPAbstractLegendItem *item) const; + bool hasItemWithPlottable(const QCPAbstractPlottable *plottable) const; + bool addItem(QCPAbstractLegendItem *item); + bool removeItem(int index); + bool removeItem(QCPAbstractLegendItem *item); + void clearItems(); + QList selectedItems() const; + signals: - void selectionChanged(QCPLegend::SelectableParts parts); - void selectableChanged(QCPLegend::SelectableParts parts); - + void selectionChanged(QCPLegend::SelectableParts parts); + void selectableChanged(QCPLegend::SelectableParts parts); + protected: - // property members: - QPen mBorderPen, mIconBorderPen; - QBrush mBrush; - QFont mFont; - QColor mTextColor; - QSize mIconSize; - int mIconTextPadding; - SelectableParts mSelectedParts, mSelectableParts; - QPen mSelectedBorderPen, mSelectedIconBorderPen; - QBrush mSelectedBrush; - QFont mSelectedFont; - QColor mSelectedTextColor; - - // reimplemented virtual methods: - 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) Q_DECL_OVERRIDE; - virtual void deselectEvent(bool *selectionStateChanged) Q_DECL_OVERRIDE; - - // non-virtual methods: - QPen getBorderPen() const; - QBrush getBrush() const; - + // property members: + QPen mBorderPen, mIconBorderPen; + QBrush mBrush; + QFont mFont; + QColor mTextColor; + QSize mIconSize; + int mIconTextPadding; + SelectableParts mSelectedParts, mSelectableParts; + QPen mSelectedBorderPen, mSelectedIconBorderPen; + QBrush mSelectedBrush; + QFont mSelectedFont; + QColor mSelectedTextColor; + + // reimplemented virtual methods: + 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) Q_DECL_OVERRIDE; + virtual void deselectEvent(bool *selectionStateChanged) Q_DECL_OVERRIDE; + + // non-virtual methods: + QPen getBorderPen() const; + QBrush getBrush() const; + private: - Q_DISABLE_COPY(QCPLegend) - - friend class QCustomPlot; - friend class QCPAbstractLegendItem; + Q_DISABLE_COPY(QCPLegend) + + friend class QCustomPlot; + friend class QCPAbstractLegendItem; }; Q_DECLARE_OPERATORS_FOR_FLAGS(QCPLegend::SelectableParts) Q_DECLARE_METATYPE(QCPLegend::SelectablePart) @@ -5215,81 +5768,96 @@ Q_DECLARE_METATYPE(QCPLegend::SelectablePart) class QCP_LIB_DECL QCPTextElement : public QCPLayoutElement { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QString text READ text WRITE setText) - Q_PROPERTY(QFont font READ font WRITE setFont) - Q_PROPERTY(QColor textColor READ textColor WRITE setTextColor) - Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont) - Q_PROPERTY(QColor selectedTextColor READ selectedTextColor WRITE setSelectedTextColor) - Q_PROPERTY(bool selectable READ selectable WRITE setSelectable NOTIFY selectableChanged) - Q_PROPERTY(bool selected READ selected WRITE setSelected NOTIFY selectionChanged) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QString text READ text WRITE setText) + Q_PROPERTY(QFont font READ font WRITE setFont) + Q_PROPERTY(QColor textColor READ textColor WRITE setTextColor) + Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont) + Q_PROPERTY(QColor selectedTextColor READ selectedTextColor WRITE setSelectedTextColor) + Q_PROPERTY(bool selectable READ selectable WRITE setSelectable NOTIFY selectableChanged) + Q_PROPERTY(bool selected READ selected WRITE setSelected NOTIFY selectionChanged) + /// \endcond public: - 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; } - QColor selectedTextColor() const { return mSelectedTextColor; } - bool selectable() const { return mSelectable; } - bool selected() const { return mSelected; } - - // 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); - void setSelectedTextColor(const QColor &color); - Q_SLOT void setSelectable(bool selectable); - Q_SLOT void setSelected(bool selected); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) 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; - + 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; + } + QColor selectedTextColor() const { + return mSelectedTextColor; + } + bool selectable() const { + return mSelectable; + } + bool selected() const { + return mSelected; + } + + // 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); + void setSelectedTextColor(const QColor &color); + Q_SLOT void setSelectable(bool selectable); + Q_SLOT void setSelected(bool selected); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = nullptr) 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); - + 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; - QColor mSelectedTextColor; - QRect mTextBoundingRect; - bool mSelectable, mSelected; - - // reimplemented virtual methods: - virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const Q_DECL_OVERRIDE; - virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; - virtual QSize minimumOuterSizeHint() const Q_DECL_OVERRIDE; - virtual QSize maximumOuterSizeHint() 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; - - // non-virtual methods: - QFont mainFont() const; - QColor mainTextColor() const; - + // property members: + QString mText; + int mTextFlags; + QFont mFont; + QColor mTextColor; + QFont mSelectedFont; + QColor mSelectedTextColor; + QRect mTextBoundingRect; + bool mSelectable, mSelected; + + // reimplemented virtual methods: + virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const Q_DECL_OVERRIDE; + virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; + virtual QSize minimumOuterSizeHint() const Q_DECL_OVERRIDE; + virtual QSize maximumOuterSizeHint() 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; + + // non-virtual methods: + QFont mainFont() const; + QColor mainTextColor() const; + private: - Q_DISABLE_COPY(QCPTextElement) + Q_DISABLE_COPY(QCPTextElement) }; @@ -5303,102 +5871,113 @@ private: class QCPColorScaleAxisRectPrivate : public QCPAxisRect { - Q_OBJECT + Q_OBJECT public: - explicit QCPColorScaleAxisRectPrivate(QCPColorScale *parentColorScale); + explicit QCPColorScaleAxisRectPrivate(QCPColorScale *parentColorScale); protected: - QCPColorScale *mParentColorScale; - QImage mGradientImage; - bool mGradientImageInvalidated; - // re-using some methods of QCPAxisRect to make them available to friend class QCPColorScale - using QCPAxisRect::calculateAutoMargin; - using QCPAxisRect::mousePressEvent; - using QCPAxisRect::mouseMoveEvent; - using QCPAxisRect::mouseReleaseEvent; - using QCPAxisRect::wheelEvent; - using QCPAxisRect::update; - virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; - void updateGradientImage(); - Q_SLOT void axisSelectionChanged(QCPAxis::SelectableParts selectedParts); - Q_SLOT void axisSelectableChanged(QCPAxis::SelectableParts selectableParts); - friend class QCPColorScale; + QCPColorScale *mParentColorScale; + QImage mGradientImage; + bool mGradientImageInvalidated; + // re-using some methods of QCPAxisRect to make them available to friend class QCPColorScale + using QCPAxisRect::calculateAutoMargin; + using QCPAxisRect::mousePressEvent; + using QCPAxisRect::mouseMoveEvent; + using QCPAxisRect::mouseReleaseEvent; + using QCPAxisRect::wheelEvent; + using QCPAxisRect::update; + virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; + void updateGradientImage(); + Q_SLOT void axisSelectionChanged(QCPAxis::SelectableParts selectedParts); + Q_SLOT void axisSelectableChanged(QCPAxis::SelectableParts selectableParts); + friend class QCPColorScale; }; class QCP_LIB_DECL QCPColorScale : public QCPLayoutElement { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QCPAxis::AxisType type READ type WRITE setType) - Q_PROPERTY(QCPRange dataRange READ dataRange WRITE setDataRange NOTIFY dataRangeChanged) - Q_PROPERTY(QCPAxis::ScaleType dataScaleType READ dataScaleType WRITE setDataScaleType NOTIFY dataScaleTypeChanged) - Q_PROPERTY(QCPColorGradient gradient READ gradient WRITE setGradient NOTIFY gradientChanged) - Q_PROPERTY(QString label READ label WRITE setLabel) - Q_PROPERTY(int barWidth READ barWidth WRITE setBarWidth) - Q_PROPERTY(bool rangeDrag READ rangeDrag WRITE setRangeDrag) - Q_PROPERTY(bool rangeZoom READ rangeZoom WRITE setRangeZoom) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QCPAxis::AxisType type READ type WRITE setType) + Q_PROPERTY(QCPRange dataRange READ dataRange WRITE setDataRange NOTIFY dataRangeChanged) + Q_PROPERTY(QCPAxis::ScaleType dataScaleType READ dataScaleType WRITE setDataScaleType NOTIFY dataScaleTypeChanged) + Q_PROPERTY(QCPColorGradient gradient READ gradient WRITE setGradient NOTIFY gradientChanged) + Q_PROPERTY(QString label READ label WRITE setLabel) + Q_PROPERTY(int barWidth READ barWidth WRITE setBarWidth) + Q_PROPERTY(bool rangeDrag READ rangeDrag WRITE setRangeDrag) + Q_PROPERTY(bool rangeZoom READ rangeZoom WRITE setRangeZoom) + /// \endcond public: - explicit QCPColorScale(QCustomPlot *parentPlot); - virtual ~QCPColorScale() Q_DECL_OVERRIDE; - - // getters: - QCPAxis *axis() const { return mColorAxis.data(); } - QCPAxis::AxisType type() const { return mType; } - QCPRange dataRange() const { return mDataRange; } - QCPAxis::ScaleType dataScaleType() const { return mDataScaleType; } - QCPColorGradient gradient() const { return mGradient; } - QString label() const; - int barWidth () const { return mBarWidth; } - bool rangeDrag() const; - bool rangeZoom() const; - - // setters: - void setType(QCPAxis::AxisType type); - Q_SLOT void setDataRange(const QCPRange &dataRange); - Q_SLOT void setDataScaleType(QCPAxis::ScaleType scaleType); - Q_SLOT void setGradient(const QCPColorGradient &gradient); - void setLabel(const QString &str); - void setBarWidth(int width); - void setRangeDrag(bool enabled); - void setRangeZoom(bool enabled); - - // non-property methods: - QList colorMaps() const; - void rescaleDataRange(bool onlyVisibleMaps); - - // reimplemented virtual methods: - virtual void update(UpdatePhase phase) Q_DECL_OVERRIDE; - + explicit QCPColorScale(QCustomPlot *parentPlot); + virtual ~QCPColorScale() Q_DECL_OVERRIDE; + + // getters: + QCPAxis *axis() const { + return mColorAxis.data(); + } + QCPAxis::AxisType type() const { + return mType; + } + QCPRange dataRange() const { + return mDataRange; + } + QCPAxis::ScaleType dataScaleType() const { + return mDataScaleType; + } + QCPColorGradient gradient() const { + return mGradient; + } + QString label() const; + int barWidth() const { + return mBarWidth; + } + bool rangeDrag() const; + bool rangeZoom() const; + + // setters: + void setType(QCPAxis::AxisType type); + Q_SLOT void setDataRange(const QCPRange &dataRange); + Q_SLOT void setDataScaleType(QCPAxis::ScaleType scaleType); + Q_SLOT void setGradient(const QCPColorGradient &gradient); + void setLabel(const QString &str); + void setBarWidth(int width); + void setRangeDrag(bool enabled); + void setRangeZoom(bool enabled); + + // non-property methods: + QList colorMaps() const; + void rescaleDataRange(bool onlyVisibleMaps); + + // reimplemented virtual methods: + virtual void update(UpdatePhase phase) Q_DECL_OVERRIDE; + signals: - void dataRangeChanged(const QCPRange &newRange); - void dataScaleTypeChanged(QCPAxis::ScaleType scaleType); - void gradientChanged(const QCPColorGradient &newGradient); + void dataRangeChanged(const QCPRange &newRange); + void dataScaleTypeChanged(QCPAxis::ScaleType scaleType); + void gradientChanged(const QCPColorGradient &newGradient); protected: - // property members: - QCPAxis::AxisType mType; - QCPRange mDataRange; - QCPAxis::ScaleType mDataScaleType; - QCPColorGradient mGradient; - int mBarWidth; - - // non-property members: - QPointer mAxisRect; - QPointer mColorAxis; - - // reimplemented virtual methods: - virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const Q_DECL_OVERRIDE; - // events: - 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; - + // property members: + QCPAxis::AxisType mType; + QCPRange mDataRange; + QCPAxis::ScaleType mDataScaleType; + QCPColorGradient mGradient; + int mBarWidth; + + // non-property members: + QPointer mAxisRect; + QPointer mColorAxis; + + // reimplemented virtual methods: + virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const Q_DECL_OVERRIDE; + // events: + 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) - - friend class QCPColorScaleAxisRectPrivate; + Q_DISABLE_COPY(QCPColorScale) + + friend class QCPColorScaleAxisRectPrivate; }; @@ -5411,133 +5990,166 @@ private: class QCP_LIB_DECL QCPGraphData { public: - QCPGraphData(); - QCPGraphData(double key, double value); - - 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; + QCPGraphData(); + QCPGraphData(double key, double value); + + 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 QCPDataContainer QCPGraphDataContainer; 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(int scatterSkip READ scatterSkip WRITE setScatterSkip) - Q_PROPERTY(QCPGraph* channelFillGraph READ channelFillGraph WRITE setChannelFillGraph) - Q_PROPERTY(bool adaptiveSampling READ adaptiveSampling WRITE setAdaptiveSampling) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(LineStyle lineStyle READ lineStyle WRITE setLineStyle) + Q_PROPERTY(QCPScatterStyle scatterStyle READ scatterStyle WRITE setScatterStyle) + 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 public: - /*! - Defines how the graph's line is represented visually in the plot. The line is drawn with the - current pen of the graph (\ref setPen). - \see setLineStyle - */ - enum LineStyle { lsNone ///< data points are not connected with any lines (e.g. data only represented - ///< with symbols according to the scatter style, see \ref setScatterStyle) - ,lsLine ///< data points are connected by a straight line - ,lsStepLeft ///< line is drawn as steps where the step height is the value of the left data point - ,lsStepRight ///< line is drawn as steps where the step height is the value of the right data point - ,lsStepCenter ///< line is drawn as steps where the step is in between two data points - ,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) - - explicit QCPGraph(QCPAxis *keyAxis, QCPAxis *valueAxis); - virtual ~QCPGraph() Q_DECL_OVERRIDE; - - // getters: - QSharedPointer data() const { return mDataContainer; } - LineStyle lineStyle() const { return mLineStyle; } - QCPScatterStyle scatterStyle() const { return mScatterStyle; } - int scatterSkip() const { return mScatterSkip; } - QCPGraph *channelFillGraph() const { return mChannelFillGraph.data(); } - bool adaptiveSampling() const { return mAdaptiveSampling; } - - // setters: - 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 setScatterSkip(int skip); - void setChannelFillGraph(QCPGraph *targetGraph); - void setAdaptiveSampling(bool enabled); - - // non-property methods: - void addData(const QVector &keys, const QVector &values, bool alreadySorted=false); - void addData(double key, double value); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) 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; - + /*! + Defines how the graph's line is represented visually in the plot. The line is drawn with the + current pen of the graph (\ref setPen). + \see setLineStyle + */ + enum LineStyle { lsNone ///< data points are not connected with any lines (e.g. data only represented + ///< with symbols according to the scatter style, see \ref setScatterStyle) + , lsLine ///< data points are connected by a straight line + , lsStepLeft ///< line is drawn as steps where the step height is the value of the left data point + , lsStepRight ///< line is drawn as steps where the step height is the value of the right data point + , lsStepCenter ///< line is drawn as steps where the step is in between two data points + , 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) + + explicit QCPGraph(QCPAxis *keyAxis, QCPAxis *valueAxis); + virtual ~QCPGraph() Q_DECL_OVERRIDE; + + // getters: + QSharedPointer data() const { + return mDataContainer; + } + LineStyle lineStyle() const { + return mLineStyle; + } + QCPScatterStyle scatterStyle() const { + return mScatterStyle; + } + int scatterSkip() const { + return mScatterSkip; + } + QCPGraph *channelFillGraph() const { + return mChannelFillGraph.data(); + } + bool adaptiveSampling() const { + return mAdaptiveSampling; + } + + // setters: + 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 setScatterSkip(int skip); + void setChannelFillGraph(QCPGraph *targetGraph); + void setAdaptiveSampling(bool enabled); + + // non-property methods: + void addData(const QVector &keys, const QVector &values, bool alreadySorted = false); + void addData(double key, double value); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = nullptr) 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: - LineStyle mLineStyle; - QCPScatterStyle mScatterStyle; - int mScatterSkip; - QPointer mChannelFillGraph; - bool mAdaptiveSampling; - - // reimplemented virtual methods: - 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 *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 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; - QVector getNonNanSegments(const QVector *lineData, Qt::Orientation keyOrientation) const; - QVector > getOverlappingSegments(QVector thisSegments, const QVector *thisData, QVector otherSegments, const QVector *otherData) const; - bool segmentsIntersect(double aLower, double aUpper, double bLower, double bUpper, int &bPrecedence) const; - QPointF getFillBasePoint(QPointF matchingDataPoint) const; - const QPolygonF getFillPolygon(const QVector *lineData, QCPDataRange segment) const; - const QPolygonF getChannelFillPolygon(const QVector *thisData, QCPDataRange thisSegment, const QVector *otherData, QCPDataRange otherSegment) 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, QCPGraphDataContainer::const_iterator &closestData) const; - - friend class QCustomPlot; - friend class QCPLegend; + // property members: + LineStyle mLineStyle; + QCPScatterStyle mScatterStyle; + int mScatterSkip; + QPointer mChannelFillGraph; + bool mAdaptiveSampling; + + // reimplemented virtual methods: + virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; + virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const Q_DECL_OVERRIDE; + + int smooth; +public: + void setSmooth(int smooth); + +protected: + // introduced virtual methods: + 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 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; + QVector getNonNanSegments(const QVector *lineData, Qt::Orientation keyOrientation) const; + QVector > getOverlappingSegments(QVector thisSegments, const QVector *thisData, QVector otherSegments, const QVector *otherData) const; + bool segmentsIntersect(double aLower, double aUpper, double bLower, double bUpper, int &bPrecedence) const; + QPointF getFillBasePoint(QPointF matchingDataPoint) const; + + const QPolygonF getFillPolygon(const QVector *lineData, QCPDataRange segment) const; + const QPainterPath getFillPath(const QVector *lineData, QCPDataRange segment) const; + const QPolygonF getChannelFillPolygon(const QVector *lineData, QCPDataRange thisSegment, const QVector *otherData, QCPDataRange otherSegment) const; + //const QPainterPath getChannelFillPath(const QVector *lineData, QCPDataRange thisSegment, const QVector *otherData, QCPDataRange otherSegment) 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, QCPGraphDataContainer::const_iterator &closestData) const; + + friend class QCustomPlot; + friend class QCPLegend; }; Q_DECLARE_METATYPE(QCPGraph::LineStyle) @@ -5550,109 +6162,129 @@ Q_DECLARE_METATYPE(QCPGraph::LineStyle) 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; + 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_PRIMITIVE_TYPE); /*! \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. - + \see QCPCurveData, QCPCurve::setData */ typedef QCPDataContainer QCPCurveDataContainer; 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 + 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: - /*! - Defines how the curve's line is represented visually in the plot. The line is drawn with the - current pen of the curve (\ref setPen). - \see setLineStyle - */ - 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() Q_DECL_OVERRIDE; - - // getters: - QSharedPointer data() const { return mDataContainer; } - QCPScatterStyle scatterStyle() const { return mScatterStyle; } - int scatterSkip() const { return mScatterSkip; } - LineStyle lineStyle() const { return mLineStyle; } - - // setters: - 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 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); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) 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; - + /*! + Defines how the curve's line is represented visually in the plot. The line is drawn with the + current pen of the curve (\ref setPen). + \see setLineStyle + */ + 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() Q_DECL_OVERRIDE; + + // getters: + QSharedPointer data() const { + return mDataContainer; + } + QCPScatterStyle scatterStyle() const { + return mScatterStyle; + } + int scatterSkip() const { + return mScatterSkip; + } + LineStyle lineStyle() const { + return mLineStyle; + } + + // setters: + 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 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); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = nullptr) 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: - QCPScatterStyle mScatterStyle; - int mScatterSkip; - LineStyle mLineStyle; - - // reimplemented virtual methods: - 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 drawCurveLine(QCPPainter *painter, const QVector &lines) const; - virtual void drawScatterPlot(QCPPainter *painter, const QVector &points, const QCPScatterStyle &style) const; - - // non-virtual methods: - 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 otherRegion, double otherKey, double otherValue, 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 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; + // property members: + QCPScatterStyle mScatterStyle; + int mScatterSkip; + LineStyle mLineStyle; + + // reimplemented virtual methods: + 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 drawCurveLine(QCPPainter *painter, const QVector &lines) const; + virtual void drawScatterPlot(QCPPainter *painter, const QVector &points, const QCPScatterStyle &style) const; + + // non-virtual methods: + 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 otherRegion, double otherKey, double otherValue, 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 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) @@ -5664,65 +6296,77 @@ Q_DECLARE_METATYPE(QCPCurve::LineStyle) class QCP_LIB_DECL QCPBarsGroup : public QObject { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(SpacingType spacingType READ spacingType WRITE setSpacingType) - Q_PROPERTY(double spacing READ spacing WRITE setSpacing) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(SpacingType spacingType READ spacingType WRITE setSpacingType) + Q_PROPERTY(double spacing READ spacing WRITE setSpacing) + /// \endcond public: - /*! - Defines the ways the spacing between bars in the group can be specified. Thus it defines what - the number passed to \ref setSpacing actually means. - - \see setSpacingType, setSpacing - */ - 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) - - explicit QCPBarsGroup(QCustomPlot *parentPlot); - virtual ~QCPBarsGroup(); - - // getters: - SpacingType spacingType() const { return mSpacingType; } - double spacing() const { return mSpacing; } - - // setters: - void setSpacingType(SpacingType spacingType); - void setSpacing(double spacing); - - // non-virtual methods: - QList bars() const { return mBars; } - QCPBars* bars(int index) const; - int size() const { return mBars.size(); } - bool isEmpty() const { return mBars.isEmpty(); } - void clear(); - bool contains(QCPBars *bars) const { return mBars.contains(bars); } - void append(QCPBars *bars); - void insert(int i, QCPBars *bars); - void remove(QCPBars *bars); - + /*! + Defines the ways the spacing between bars in the group can be specified. Thus it defines what + the number passed to \ref setSpacing actually means. + + \see setSpacingType, setSpacing + */ + 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) + + explicit QCPBarsGroup(QCustomPlot *parentPlot); + virtual ~QCPBarsGroup(); + + // getters: + SpacingType spacingType() const { + return mSpacingType; + } + double spacing() const { + return mSpacing; + } + + // setters: + void setSpacingType(SpacingType spacingType); + void setSpacing(double spacing); + + // non-virtual methods: + QList bars() const { + return mBars; + } + QCPBars *bars(int index) const; + int size() const { + return mBars.size(); + } + bool isEmpty() const { + return mBars.isEmpty(); + } + void clear(); + bool contains(QCPBars *bars) const { + return mBars.contains(bars); + } + void append(QCPBars *bars); + void insert(int i, QCPBars *bars); + void remove(QCPBars *bars); + protected: - // non-property members: - QCustomPlot *mParentPlot; - SpacingType mSpacingType; - double mSpacing; - QList mBars; - - // non-virtual methods: - void registerBars(QCPBars *bars); - void unregisterBars(QCPBars *bars); - - // virtual methods: - double keyPixelOffset(const QCPBars *bars, double keyCoord); - double getPixelSpacing(const QCPBars *bars, double keyCoord); - + // non-property members: + QCustomPlot *mParentPlot; + SpacingType mSpacingType; + double mSpacing; + QList mBars; + + // non-virtual methods: + void registerBars(QCPBars *bars); + void unregisterBars(QCPBars *bars); + + // virtual methods: + double keyPixelOffset(const QCPBars *bars, double keyCoord); + double getPixelSpacing(const QCPBars *bars, double keyCoord); + private: - Q_DISABLE_COPY(QCPBarsGroup) - - friend class QCPBars; + Q_DISABLE_COPY(QCPBarsGroup) + + friend class QCPBars; }; Q_DECLARE_METATYPE(QCPBarsGroup::SpacingType) @@ -5730,117 +6374,145 @@ Q_DECLARE_METATYPE(QCPBarsGroup::SpacingType) class QCP_LIB_DECL QCPBarsData { public: - 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; + 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(QCPBarsData, Q_PRIMITIVE_TYPE); /*! \typedef QCPBarsDataContainer - + 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 QCPDataContainer QCPBarsDataContainer; class QCP_LIB_DECL QCPBars : public QCPAbstractPlottable1D { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(double width READ width WRITE setWidth) - 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 + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(double width READ width WRITE setWidth) + 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 public: - /*! - Defines the ways the width of the bar can be specified. Thus it defines what the number passed - to \ref setWidth actually means. - - \see setWidthType, setWidth - */ - enum WidthType { wtAbsolute ///< Bar width is in absolute pixels - ,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) - - explicit QCPBars(QCPAxis *keyAxis, QCPAxis *valueAxis); - virtual ~QCPBars() Q_DECL_OVERRIDE; - - // getters: - double width() const { return mWidth; } - 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(); } - 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 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); - - // 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=nullptr) 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; - + /*! + Defines the ways the width of the bar can be specified. Thus it defines what the number passed + to \ref setWidth actually means. + + \see setWidthType, setWidth + */ + enum WidthType { wtAbsolute ///< Bar width is in absolute pixels + , 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) + + explicit QCPBars(QCPAxis *keyAxis, QCPAxis *valueAxis); + virtual ~QCPBars() Q_DECL_OVERRIDE; + + // getters: + double width() const { + return mWidth; + } + 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(); + } + 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 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); + + // 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 = nullptr) 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: - double mWidth; - WidthType mWidthType; - QCPBarsGroup *mBarsGroup; - double mBaseValue; - double mStackingGap; - QPointer mBarBelow, mBarAbove; - - // reimplemented virtual methods: - 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(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); - - friend class QCustomPlot; - friend class QCPLegend; - friend class QCPBarsGroup; + // property members: + double mWidth; + WidthType mWidthType; + QCPBarsGroup *mBarsGroup; + double mBaseValue; + double mStackingGap; + QPointer mBarBelow, mBarAbove; + + // reimplemented virtual methods: + 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(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); + + friend class QCustomPlot; + friend class QCPLegend; + friend class QCPBarsGroup; }; Q_DECLARE_METATYPE(QCPBars::WidthType) @@ -5853,112 +6525,137 @@ Q_DECLARE_METATYPE(QCPBars::WidthType) 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; + 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 QCPAbstractPlottable1D { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - 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 + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES 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 public: - explicit QCPStatisticalBox(QCPAxis *keyAxis, QCPAxis *valueAxis); - - // getters: - 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; } + explicit QCPStatisticalBox(QCPAxis *keyAxis, QCPAxis *valueAxis); + + // getters: + 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 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: + 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 = nullptr) 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; - // setters: - 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: - 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=nullptr) 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: - double mWidth; - double mWhiskerWidth; - QPen mWhiskerPen, mWhiskerBarPen; - bool mWhiskerAntialiased; - QPen mMedianPen; - QCPScatterStyle mOutlierStyle; - - // reimplemented virtual methods: - 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 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; + // property members: + double mWidth; + double mWhiskerWidth; + QPen mWhiskerPen, mWhiskerBarPen; + bool mWhiskerAntialiased; + QPen mMedianPen; + QCPScatterStyle mOutlierStyle; + + // reimplemented virtual methods: + 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 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' */ @@ -5970,131 +6667,156 @@ protected: class QCP_LIB_DECL QCPColorMapData { public: - QCPColorMapData(int keySize, int valueSize, const QCPRange &keyRange, const QCPRange &valueRange); - ~QCPColorMapData(); - QCPColorMapData(const QCPColorMapData &other); - QCPColorMapData &operator=(const QCPColorMapData &other); - - // getters: - int keySize() const { return mKeySize; } - int valueSize() const { return mValueSize; } - QCPRange keyRange() const { return mKeyRange; } - QCPRange valueRange() const { return mValueRange; } - 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); - void setKeySize(int keySize); - void setValueSize(int valueSize); - void setRange(const QCPRange &keyRange, const QCPRange &valueRange); - void setKeyRange(const QCPRange &keyRange); - 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; - + QCPColorMapData(int keySize, int valueSize, const QCPRange &keyRange, const QCPRange &valueRange); + ~QCPColorMapData(); + QCPColorMapData(const QCPColorMapData &other); + QCPColorMapData &operator=(const QCPColorMapData &other); + + // getters: + int keySize() const { + return mKeySize; + } + int valueSize() const { + return mValueSize; + } + QCPRange keyRange() const { + return mKeyRange; + } + QCPRange valueRange() const { + return mValueRange; + } + 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); + void setKeySize(int keySize); + void setValueSize(int valueSize); + void setRange(const QCPRange &keyRange, const QCPRange &valueRange); + void setKeyRange(const QCPRange &keyRange); + 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; + protected: - // property members: - 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; + // property members: + 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; }; class QCP_LIB_DECL QCPColorMap : public QCPAbstractPlottable { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QCPRange dataRange READ dataRange WRITE setDataRange NOTIFY dataRangeChanged) - Q_PROPERTY(QCPAxis::ScaleType dataScaleType READ dataScaleType WRITE setDataScaleType NOTIFY dataScaleTypeChanged) - Q_PROPERTY(QCPColorGradient gradient READ gradient WRITE setGradient NOTIFY gradientChanged) - Q_PROPERTY(bool interpolate READ interpolate WRITE setInterpolate) - Q_PROPERTY(bool tightBoundary READ tightBoundary WRITE setTightBoundary) - Q_PROPERTY(QCPColorScale* colorScale READ colorScale WRITE setColorScale) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QCPRange dataRange READ dataRange WRITE setDataRange NOTIFY dataRangeChanged) + Q_PROPERTY(QCPAxis::ScaleType dataScaleType READ dataScaleType WRITE setDataScaleType NOTIFY dataScaleTypeChanged) + Q_PROPERTY(QCPColorGradient gradient READ gradient WRITE setGradient NOTIFY gradientChanged) + Q_PROPERTY(bool interpolate READ interpolate WRITE setInterpolate) + Q_PROPERTY(bool tightBoundary READ tightBoundary WRITE setTightBoundary) + Q_PROPERTY(QCPColorScale *colorScale READ colorScale WRITE setColorScale) + /// \endcond public: - explicit QCPColorMap(QCPAxis *keyAxis, QCPAxis *valueAxis); - virtual ~QCPColorMap() Q_DECL_OVERRIDE; - - // getters: - QCPColorMapData *data() const { return mMapData; } - QCPRange dataRange() const { return mDataRange; } - QCPAxis::ScaleType dataScaleType() const { return mDataScaleType; } - bool interpolate() const { return mInterpolate; } - bool tightBoundary() const { return mTightBoundary; } - QCPColorGradient gradient() const { return mGradient; } - QCPColorScale *colorScale() const { return mColorScale.data(); } - - // setters: - void setData(QCPColorMapData *data, bool copy=false); - Q_SLOT void setDataRange(const QCPRange &dataRange); - Q_SLOT void setDataScaleType(QCPAxis::ScaleType scaleType); - Q_SLOT void setGradient(const QCPColorGradient &gradient); - void setInterpolate(bool enabled); - void setTightBoundary(bool enabled); - void setColorScale(QCPColorScale *colorScale); - - // non-property methods: - void rescaleDataRange(bool recalculateDataBounds=false); - Q_SLOT void updateLegendIcon(Qt::TransformationMode transformMode=Qt::SmoothTransformation, const QSize &thumbSize=QSize(32, 18)); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) 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; - + explicit QCPColorMap(QCPAxis *keyAxis, QCPAxis *valueAxis); + virtual ~QCPColorMap() Q_DECL_OVERRIDE; + + // getters: + QCPColorMapData *data() const { + return mMapData; + } + QCPRange dataRange() const { + return mDataRange; + } + QCPAxis::ScaleType dataScaleType() const { + return mDataScaleType; + } + bool interpolate() const { + return mInterpolate; + } + bool tightBoundary() const { + return mTightBoundary; + } + QCPColorGradient gradient() const { + return mGradient; + } + QCPColorScale *colorScale() const { + return mColorScale.data(); + } + + // setters: + void setData(QCPColorMapData *data, bool copy = false); + Q_SLOT void setDataRange(const QCPRange &dataRange); + Q_SLOT void setDataScaleType(QCPAxis::ScaleType scaleType); + Q_SLOT void setGradient(const QCPColorGradient &gradient); + void setInterpolate(bool enabled); + void setTightBoundary(bool enabled); + void setColorScale(QCPColorScale *colorScale); + + // non-property methods: + void rescaleDataRange(bool recalculateDataBounds = false); + Q_SLOT void updateLegendIcon(Qt::TransformationMode transformMode = Qt::SmoothTransformation, const QSize &thumbSize = QSize(32, 18)); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = nullptr) 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(const QCPRange &newRange); - void dataScaleTypeChanged(QCPAxis::ScaleType scaleType); - void gradientChanged(const QCPColorGradient &newGradient); - + void dataRangeChanged(const QCPRange &newRange); + void dataScaleTypeChanged(QCPAxis::ScaleType scaleType); + void gradientChanged(const QCPColorGradient &newGradient); + protected: - // property members: - QCPRange mDataRange; - QCPAxis::ScaleType mDataScaleType; - QCPColorMapData *mMapData; - QCPColorGradient mGradient; - bool mInterpolate; - bool mTightBoundary; - QPointer mColorScale; - - // non-property members: - QImage mMapImage, mUndersampledMapImage; - QPixmap mLegendIcon; - bool mMapImageInvalidated; - - // introduced virtual methods: - virtual void updateMapImage(); - - // reimplemented virtual methods: - 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; + // property members: + QCPRange mDataRange; + QCPAxis::ScaleType mDataScaleType; + QCPColorMapData *mMapData; + QCPColorGradient mGradient; + bool mInterpolate; + bool mTightBoundary; + QPointer mColorScale; + + // non-property members: + QImage mMapImage, mUndersampledMapImage; + QPixmap mLegendIcon; + bool mMapImageInvalidated; + + // introduced virtual methods: + virtual void updateMapImage(); + + // reimplemented virtual methods: + 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; }; /* end of 'src/plottables/plottable-colormap.h' */ @@ -6106,133 +6828,163 @@ protected: 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; + 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_PRIMITIVE_TYPE); /*! \typedef QCPFinancialDataContainer - + 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 QCPDataContainer QCPFinancialDataContainer; 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) - Q_PROPERTY(QPen penPositive READ penPositive WRITE setPenPositive) - Q_PROPERTY(QPen penNegative READ penNegative WRITE setPenNegative) - /// \endcond + 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) + Q_PROPERTY(QPen penPositive READ penPositive WRITE setPenPositive) + 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. + /*! + 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. + + \see setChartStyle + */ + enum ChartStyle { csOhlc ///< Open-High-Low-Close bar representation + , csCandlestick ///< Candlestick representation + }; + Q_ENUMS(ChartStyle) + + explicit QCPFinancial(QCPAxis *keyAxis, QCPAxis *valueAxis); + virtual ~QCPFinancial() Q_DECL_OVERRIDE; + + // getters: + 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(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); + void setPenPositive(const QPen &pen); + void setPenNegative(const QPen &pen); + + // non-property methods: + 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); + + // 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 = nullptr) 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 QCPFinancialDataContainer timeSeriesToOhlc(const QVector &time, const QVector &value, double timeBinSize, double timeBinOffset = 0); - \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. - - \see setChartStyle - */ - enum ChartStyle { csOhlc ///< Open-High-Low-Close bar representation - ,csCandlestick ///< Candlestick representation - }; - Q_ENUMS(ChartStyle) - - explicit QCPFinancial(QCPAxis *keyAxis, QCPAxis *valueAxis); - virtual ~QCPFinancial() Q_DECL_OVERRIDE; - - // getters: - 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(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); - void setPenPositive(const QPen &pen); - void setPenNegative(const QPen &pen); - - // non-property methods: - 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); - - // 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=nullptr) 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 QCPFinancialDataContainer timeSeriesToOhlc(const QVector &time, const QVector &value, double timeBinSize, double timeBinOffset = 0); - protected: - // property members: - ChartStyle mChartStyle; - double mWidth; - WidthType mWidthType; - bool mTwoColored; - QBrush mBrushPositive, mBrushNegative; - QPen mPenPositive, mPenNegative; - - // reimplemented virtual methods: - 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 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; + // property members: + ChartStyle mChartStyle; + double mWidth; + WidthType mWidthType; + bool mTwoColored; + QBrush mBrushPositive, mBrushNegative; + QPen mPenPositive, mPenNegative; + + // reimplemented virtual methods: + 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 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) @@ -6245,11 +6997,11 @@ Q_DECLARE_METATYPE(QCPFinancial::ChartStyle) class QCP_LIB_DECL QCPErrorBarsData { public: - QCPErrorBarsData(); - explicit QCPErrorBarsData(double error); - QCPErrorBarsData(double errorMinus, double errorPlus); - - double errorMinus, errorPlus; + QCPErrorBarsData(); + explicit QCPErrorBarsData(double error); + QCPErrorBarsData(double errorMinus, double errorPlus); + + double errorMinus, errorPlus; }; Q_DECLARE_TYPEINFO(QCPErrorBarsData, Q_PRIMITIVE_TYPE); @@ -6273,92 +7025,102 @@ 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 + 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() Q_DECL_OVERRIDE; - // 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 Q_DECL_OVERRIDE; - virtual double dataMainKey(int index) const Q_DECL_OVERRIDE; - virtual double dataSortKey(int index) const Q_DECL_OVERRIDE; - virtual double dataMainValue(int index) const Q_DECL_OVERRIDE; - virtual QCPRange dataValueRange(int index) const Q_DECL_OVERRIDE; - virtual QPointF dataPixelPosition(int index) const Q_DECL_OVERRIDE; - virtual bool sortKeyIsMainKey() const Q_DECL_OVERRIDE; - virtual QCPDataSelection selectTestRect(const QRectF &rect, bool onlySelectable) const Q_DECL_OVERRIDE; - virtual int findBegin(double sortKey, bool expandedRange=true) const Q_DECL_OVERRIDE; - virtual int findEnd(double sortKey, bool expandedRange=true) const Q_DECL_OVERRIDE; - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE; - virtual QCPPlottableInterface1D *interface1D() Q_DECL_OVERRIDE { return this; } - + /*! + 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() Q_DECL_OVERRIDE; + // 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 Q_DECL_OVERRIDE; + virtual double dataMainKey(int index) const Q_DECL_OVERRIDE; + virtual double dataSortKey(int index) const Q_DECL_OVERRIDE; + virtual double dataMainValue(int index) const Q_DECL_OVERRIDE; + virtual QCPRange dataValueRange(int index) const Q_DECL_OVERRIDE; + virtual QPointF dataPixelPosition(int index) const Q_DECL_OVERRIDE; + virtual bool sortKeyIsMainKey() const Q_DECL_OVERRIDE; + virtual QCPDataSelection selectTestRect(const QRectF &rect, bool onlySelectable) const Q_DECL_OVERRIDE; + virtual int findBegin(double sortKey, bool expandedRange = true) const Q_DECL_OVERRIDE; + virtual int findEnd(double sortKey, bool expandedRange = true) const Q_DECL_OVERRIDE; + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = nullptr) 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; + // 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' */ @@ -6369,39 +7131,42 @@ protected: class QCP_LIB_DECL QCPItemStraightLine : public QCPAbstractItem { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QPen pen READ pen WRITE setPen) - Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QPen pen READ pen WRITE setPen) + Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) + /// \endcond public: - explicit QCPItemStraightLine(QCustomPlot *parentPlot); - virtual ~QCPItemStraightLine() Q_DECL_OVERRIDE; - - // getters: - QPen pen() const { return mPen; } - QPen selectedPen() const { return mSelectedPen; } - - // setters; - void setPen(const QPen &pen); - void setSelectedPen(const QPen &pen); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE; - - QCPItemPosition * const point1; - QCPItemPosition * const point2; - + explicit QCPItemStraightLine(QCustomPlot *parentPlot); + virtual ~QCPItemStraightLine() Q_DECL_OVERRIDE; + + // getters: + QPen pen() const { + return mPen; + } + QPen selectedPen() const { + return mSelectedPen; + } + + // setters; + void setPen(const QPen &pen); + void setSelectedPen(const QPen &pen); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = nullptr) const Q_DECL_OVERRIDE; + + QCPItemPosition *const point1; + QCPItemPosition *const point2; + protected: - // property members: - QPen mPen, mSelectedPen; - - // reimplemented virtual methods: - virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; - - // non-virtual methods: - QLineF getRectClippedStraightLine(const QCPVector2D &base, const QCPVector2D &vec, const QRect &rect) const; - QPen mainPen() const; + // property members: + QPen mPen, mSelectedPen; + + // reimplemented virtual methods: + virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; + + // non-virtual methods: + QLineF getRectClippedStraightLine(const QCPVector2D &base, const QCPVector2D &vec, const QRect &rect) const; + QPen mainPen() const; }; /* end of 'src/items/item-straightline.h' */ @@ -6412,46 +7177,53 @@ protected: class QCP_LIB_DECL QCPItemLine : public QCPAbstractItem { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QPen pen READ pen WRITE setPen) - Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) - Q_PROPERTY(QCPLineEnding head READ head WRITE setHead) - Q_PROPERTY(QCPLineEnding tail READ tail WRITE setTail) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QPen pen READ pen WRITE setPen) + Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) + Q_PROPERTY(QCPLineEnding head READ head WRITE setHead) + Q_PROPERTY(QCPLineEnding tail READ tail WRITE setTail) + /// \endcond public: - explicit QCPItemLine(QCustomPlot *parentPlot); - virtual ~QCPItemLine() Q_DECL_OVERRIDE; - - // getters: - QPen pen() const { return mPen; } - QPen selectedPen() const { return mSelectedPen; } - QCPLineEnding head() const { return mHead; } - QCPLineEnding tail() const { return mTail; } - - // setters; - void setPen(const QPen &pen); - void setSelectedPen(const QPen &pen); - void setHead(const QCPLineEnding &head); - void setTail(const QCPLineEnding &tail); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE; - - QCPItemPosition * const start; - QCPItemPosition * const end; - + explicit QCPItemLine(QCustomPlot *parentPlot); + virtual ~QCPItemLine() Q_DECL_OVERRIDE; + + // getters: + QPen pen() const { + return mPen; + } + QPen selectedPen() const { + return mSelectedPen; + } + QCPLineEnding head() const { + return mHead; + } + QCPLineEnding tail() const { + return mTail; + } + + // setters; + void setPen(const QPen &pen); + void setSelectedPen(const QPen &pen); + void setHead(const QCPLineEnding &head); + void setTail(const QCPLineEnding &tail); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = nullptr) const Q_DECL_OVERRIDE; + + QCPItemPosition *const start; + QCPItemPosition *const end; + protected: - // property members: - QPen mPen, mSelectedPen; - QCPLineEnding mHead, mTail; - - // reimplemented virtual methods: - virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; - - // non-virtual methods: - QLineF getRectClippedLine(const QCPVector2D &start, const QCPVector2D &end, const QRect &rect) const; - QPen mainPen() const; + // property members: + QPen mPen, mSelectedPen; + QCPLineEnding mHead, mTail; + + // reimplemented virtual methods: + virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; + + // non-virtual methods: + QLineF getRectClippedLine(const QCPVector2D &start, const QCPVector2D &end, const QRect &rect) const; + QPen mainPen() const; }; /* end of 'src/items/item-line.h' */ @@ -6462,47 +7234,54 @@ protected: class QCP_LIB_DECL QCPItemCurve : public QCPAbstractItem { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QPen pen READ pen WRITE setPen) - Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) - Q_PROPERTY(QCPLineEnding head READ head WRITE setHead) - Q_PROPERTY(QCPLineEnding tail READ tail WRITE setTail) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QPen pen READ pen WRITE setPen) + Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) + Q_PROPERTY(QCPLineEnding head READ head WRITE setHead) + Q_PROPERTY(QCPLineEnding tail READ tail WRITE setTail) + /// \endcond public: - explicit QCPItemCurve(QCustomPlot *parentPlot); - virtual ~QCPItemCurve() Q_DECL_OVERRIDE; - - // getters: - QPen pen() const { return mPen; } - QPen selectedPen() const { return mSelectedPen; } - QCPLineEnding head() const { return mHead; } - QCPLineEnding tail() const { return mTail; } - - // setters; - void setPen(const QPen &pen); - void setSelectedPen(const QPen &pen); - void setHead(const QCPLineEnding &head); - void setTail(const QCPLineEnding &tail); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE; - - QCPItemPosition * const start; - QCPItemPosition * const startDir; - QCPItemPosition * const endDir; - QCPItemPosition * const end; - + explicit QCPItemCurve(QCustomPlot *parentPlot); + virtual ~QCPItemCurve() Q_DECL_OVERRIDE; + + // getters: + QPen pen() const { + return mPen; + } + QPen selectedPen() const { + return mSelectedPen; + } + QCPLineEnding head() const { + return mHead; + } + QCPLineEnding tail() const { + return mTail; + } + + // setters; + void setPen(const QPen &pen); + void setSelectedPen(const QPen &pen); + void setHead(const QCPLineEnding &head); + void setTail(const QCPLineEnding &tail); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = nullptr) const Q_DECL_OVERRIDE; + + QCPItemPosition *const start; + QCPItemPosition *const startDir; + QCPItemPosition *const endDir; + QCPItemPosition *const end; + protected: - // property members: - QPen mPen, mSelectedPen; - QCPLineEnding mHead, mTail; - - // reimplemented virtual methods: - virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; - - // non-virtual methods: - QPen mainPen() const; + // property members: + QPen mPen, mSelectedPen; + QCPLineEnding mHead, mTail; + + // reimplemented virtual methods: + virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; + + // non-virtual methods: + QPen mainPen() const; }; /* end of 'src/items/item-curve.h' */ @@ -6513,55 +7292,62 @@ protected: class QCP_LIB_DECL QCPItemRect : public QCPAbstractItem { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - 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) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES 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) + /// \endcond public: - explicit QCPItemRect(QCustomPlot *parentPlot); - virtual ~QCPItemRect() Q_DECL_OVERRIDE; - - // getters: - QPen pen() const { return mPen; } - QPen selectedPen() const { return mSelectedPen; } - QBrush brush() const { return mBrush; } - QBrush selectedBrush() const { return mSelectedBrush; } - - // setters; - void setPen(const QPen &pen); - void setSelectedPen(const QPen &pen); - void setBrush(const QBrush &brush); - void setSelectedBrush(const QBrush &brush); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE; - - QCPItemPosition * const topLeft; - QCPItemPosition * const bottomRight; - QCPItemAnchor * const top; - QCPItemAnchor * const topRight; - QCPItemAnchor * const right; - QCPItemAnchor * const bottom; - QCPItemAnchor * const bottomLeft; - QCPItemAnchor * const left; - + explicit QCPItemRect(QCustomPlot *parentPlot); + virtual ~QCPItemRect() Q_DECL_OVERRIDE; + + // getters: + QPen pen() const { + return mPen; + } + QPen selectedPen() const { + return mSelectedPen; + } + QBrush brush() const { + return mBrush; + } + QBrush selectedBrush() const { + return mSelectedBrush; + } + + // setters; + void setPen(const QPen &pen); + void setSelectedPen(const QPen &pen); + void setBrush(const QBrush &brush); + void setSelectedBrush(const QBrush &brush); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = nullptr) const Q_DECL_OVERRIDE; + + QCPItemPosition *const topLeft; + QCPItemPosition *const bottomRight; + QCPItemAnchor *const top; + QCPItemAnchor *const topRight; + QCPItemAnchor *const right; + QCPItemAnchor *const bottom; + QCPItemAnchor *const bottomLeft; + QCPItemAnchor *const left; + protected: - enum AnchorIndex {aiTop, aiTopRight, aiRight, aiBottom, aiBottomLeft, aiLeft}; - - // property members: - QPen mPen, mSelectedPen; - QBrush mBrush, mSelectedBrush; - - // reimplemented virtual methods: - 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; + enum AnchorIndex {aiTop, aiTopRight, aiRight, aiBottom, aiBottomLeft, aiLeft}; + + // property members: + QPen mPen, mSelectedPen; + QBrush mBrush, mSelectedBrush; + + // reimplemented virtual methods: + 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' */ @@ -6572,93 +7358,118 @@ protected: class QCP_LIB_DECL QCPItemText : public QCPAbstractItem { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QColor color READ color WRITE setColor) - Q_PROPERTY(QColor selectedColor READ selectedColor WRITE setSelectedColor) - 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(QFont font READ font WRITE setFont) - Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont) - Q_PROPERTY(QString text READ text WRITE setText) - Q_PROPERTY(Qt::Alignment positionAlignment READ positionAlignment WRITE setPositionAlignment) - Q_PROPERTY(Qt::Alignment textAlignment READ textAlignment WRITE setTextAlignment) - Q_PROPERTY(double rotation READ rotation WRITE setRotation) - Q_PROPERTY(QMargins padding READ padding WRITE setPadding) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QColor color READ color WRITE setColor) + Q_PROPERTY(QColor selectedColor READ selectedColor WRITE setSelectedColor) + 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(QFont font READ font WRITE setFont) + Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont) + Q_PROPERTY(QString text READ text WRITE setText) + Q_PROPERTY(Qt::Alignment positionAlignment READ positionAlignment WRITE setPositionAlignment) + Q_PROPERTY(Qt::Alignment textAlignment READ textAlignment WRITE setTextAlignment) + Q_PROPERTY(double rotation READ rotation WRITE setRotation) + Q_PROPERTY(QMargins padding READ padding WRITE setPadding) + /// \endcond public: - explicit QCPItemText(QCustomPlot *parentPlot); - virtual ~QCPItemText() Q_DECL_OVERRIDE; - - // getters: - QColor color() const { return mColor; } - QColor selectedColor() const { return mSelectedColor; } - QPen pen() const { return mPen; } - QPen selectedPen() const { return mSelectedPen; } - QBrush brush() const { return mBrush; } - QBrush selectedBrush() const { return mSelectedBrush; } - QFont font() const { return mFont; } - QFont selectedFont() const { return mSelectedFont; } - QString text() const { return mText; } - Qt::Alignment positionAlignment() const { return mPositionAlignment; } - Qt::Alignment textAlignment() const { return mTextAlignment; } - double rotation() const { return mRotation; } - QMargins padding() const { return mPadding; } - - // setters; - void setColor(const QColor &color); - void setSelectedColor(const QColor &color); - void setPen(const QPen &pen); - void setSelectedPen(const QPen &pen); - void setBrush(const QBrush &brush); - void setSelectedBrush(const QBrush &brush); - void setFont(const QFont &font); - void setSelectedFont(const QFont &font); - void setText(const QString &text); - void setPositionAlignment(Qt::Alignment alignment); - void setTextAlignment(Qt::Alignment alignment); - void setRotation(double degrees); - void setPadding(const QMargins &padding); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE; - - QCPItemPosition * const position; - QCPItemAnchor * const topLeft; - QCPItemAnchor * const top; - QCPItemAnchor * const topRight; - QCPItemAnchor * const right; - QCPItemAnchor * const bottomRight; - QCPItemAnchor * const bottom; - QCPItemAnchor * const bottomLeft; - QCPItemAnchor * const left; - + explicit QCPItemText(QCustomPlot *parentPlot); + virtual ~QCPItemText() Q_DECL_OVERRIDE; + + // getters: + QColor color() const { + return mColor; + } + QColor selectedColor() const { + return mSelectedColor; + } + QPen pen() const { + return mPen; + } + QPen selectedPen() const { + return mSelectedPen; + } + QBrush brush() const { + return mBrush; + } + QBrush selectedBrush() const { + return mSelectedBrush; + } + QFont font() const { + return mFont; + } + QFont selectedFont() const { + return mSelectedFont; + } + QString text() const { + return mText; + } + Qt::Alignment positionAlignment() const { + return mPositionAlignment; + } + Qt::Alignment textAlignment() const { + return mTextAlignment; + } + double rotation() const { + return mRotation; + } + QMargins padding() const { + return mPadding; + } + + // setters; + void setColor(const QColor &color); + void setSelectedColor(const QColor &color); + void setPen(const QPen &pen); + void setSelectedPen(const QPen &pen); + void setBrush(const QBrush &brush); + void setSelectedBrush(const QBrush &brush); + void setFont(const QFont &font); + void setSelectedFont(const QFont &font); + void setText(const QString &text); + void setPositionAlignment(Qt::Alignment alignment); + void setTextAlignment(Qt::Alignment alignment); + void setRotation(double degrees); + void setPadding(const QMargins &padding); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = nullptr) const Q_DECL_OVERRIDE; + + QCPItemPosition *const position; + QCPItemAnchor *const topLeft; + QCPItemAnchor *const top; + QCPItemAnchor *const topRight; + QCPItemAnchor *const right; + QCPItemAnchor *const bottomRight; + QCPItemAnchor *const bottom; + QCPItemAnchor *const bottomLeft; + QCPItemAnchor *const left; + protected: - enum AnchorIndex {aiTopLeft, aiTop, aiTopRight, aiRight, aiBottomRight, aiBottom, aiBottomLeft, aiLeft}; - - // property members: - QColor mColor, mSelectedColor; - QPen mPen, mSelectedPen; - QBrush mBrush, mSelectedBrush; - QFont mFont, mSelectedFont; - QString mText; - Qt::Alignment mPositionAlignment; - Qt::Alignment mTextAlignment; - double mRotation; - QMargins mPadding; - - // reimplemented virtual methods: - 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; - QFont mainFont() const; - QColor mainColor() const; - QPen mainPen() const; - QBrush mainBrush() const; + enum AnchorIndex {aiTopLeft, aiTop, aiTopRight, aiRight, aiBottomRight, aiBottom, aiBottomLeft, aiLeft}; + + // property members: + QColor mColor, mSelectedColor; + QPen mPen, mSelectedPen; + QBrush mBrush, mSelectedBrush; + QFont mFont, mSelectedFont; + QString mText; + Qt::Alignment mPositionAlignment; + Qt::Alignment mTextAlignment; + double mRotation; + QMargins mPadding; + + // reimplemented virtual methods: + 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; + QFont mainFont() const; + QColor mainColor() const; + QPen mainPen() const; + QBrush mainBrush() const; }; /* end of 'src/items/item-text.h' */ @@ -6669,58 +7480,65 @@ protected: class QCP_LIB_DECL QCPItemEllipse : public QCPAbstractItem { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - 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) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES 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) + /// \endcond public: - explicit QCPItemEllipse(QCustomPlot *parentPlot); - virtual ~QCPItemEllipse() Q_DECL_OVERRIDE; - - // getters: - QPen pen() const { return mPen; } - QPen selectedPen() const { return mSelectedPen; } - QBrush brush() const { return mBrush; } - QBrush selectedBrush() const { return mSelectedBrush; } - - // setters; - void setPen(const QPen &pen); - void setSelectedPen(const QPen &pen); - void setBrush(const QBrush &brush); - void setSelectedBrush(const QBrush &brush); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE; - - QCPItemPosition * const topLeft; - QCPItemPosition * const bottomRight; - QCPItemAnchor * const topLeftRim; - QCPItemAnchor * const top; - QCPItemAnchor * const topRightRim; - QCPItemAnchor * const right; - QCPItemAnchor * const bottomRightRim; - QCPItemAnchor * const bottom; - QCPItemAnchor * const bottomLeftRim; - QCPItemAnchor * const left; - QCPItemAnchor * const center; - + explicit QCPItemEllipse(QCustomPlot *parentPlot); + virtual ~QCPItemEllipse() Q_DECL_OVERRIDE; + + // getters: + QPen pen() const { + return mPen; + } + QPen selectedPen() const { + return mSelectedPen; + } + QBrush brush() const { + return mBrush; + } + QBrush selectedBrush() const { + return mSelectedBrush; + } + + // setters; + void setPen(const QPen &pen); + void setSelectedPen(const QPen &pen); + void setBrush(const QBrush &brush); + void setSelectedBrush(const QBrush &brush); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = nullptr) const Q_DECL_OVERRIDE; + + QCPItemPosition *const topLeft; + QCPItemPosition *const bottomRight; + QCPItemAnchor *const topLeftRim; + QCPItemAnchor *const top; + QCPItemAnchor *const topRightRim; + QCPItemAnchor *const right; + QCPItemAnchor *const bottomRightRim; + QCPItemAnchor *const bottom; + QCPItemAnchor *const bottomLeftRim; + QCPItemAnchor *const left; + QCPItemAnchor *const center; + protected: - enum AnchorIndex {aiTopLeftRim, aiTop, aiTopRightRim, aiRight, aiBottomRightRim, aiBottom, aiBottomLeftRim, aiLeft, aiCenter}; - - // property members: - QPen mPen, mSelectedPen; - QBrush mBrush, mSelectedBrush; - - // reimplemented virtual methods: - 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; + enum AnchorIndex {aiTopLeftRim, aiTop, aiTopRightRim, aiRight, aiBottomRightRim, aiBottom, aiBottomLeftRim, aiLeft, aiCenter}; + + // property members: + QPen mPen, mSelectedPen; + QBrush mBrush, mSelectedBrush; + + // reimplemented virtual methods: + 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' */ @@ -6731,65 +7549,76 @@ protected: class QCP_LIB_DECL QCPItemPixmap : public QCPAbstractItem { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QPixmap pixmap READ pixmap WRITE setPixmap) - Q_PROPERTY(bool scaled READ scaled WRITE setScaled) - Q_PROPERTY(Qt::AspectRatioMode aspectRatioMode READ aspectRatioMode) - Q_PROPERTY(Qt::TransformationMode transformationMode READ transformationMode) - Q_PROPERTY(QPen pen READ pen WRITE setPen) - Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QPixmap pixmap READ pixmap WRITE setPixmap) + Q_PROPERTY(bool scaled READ scaled WRITE setScaled) + Q_PROPERTY(Qt::AspectRatioMode aspectRatioMode READ aspectRatioMode) + Q_PROPERTY(Qt::TransformationMode transformationMode READ transformationMode) + Q_PROPERTY(QPen pen READ pen WRITE setPen) + Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) + /// \endcond public: - explicit QCPItemPixmap(QCustomPlot *parentPlot); - virtual ~QCPItemPixmap() Q_DECL_OVERRIDE; - - // getters: - QPixmap pixmap() const { return mPixmap; } - bool scaled() const { return mScaled; } - Qt::AspectRatioMode aspectRatioMode() const { return mAspectRatioMode; } - Qt::TransformationMode transformationMode() const { return mTransformationMode; } - QPen pen() const { return mPen; } - QPen selectedPen() const { return mSelectedPen; } - - // setters; - void setPixmap(const QPixmap &pixmap); - void setScaled(bool scaled, Qt::AspectRatioMode aspectRatioMode=Qt::KeepAspectRatio, Qt::TransformationMode transformationMode=Qt::SmoothTransformation); - void setPen(const QPen &pen); - void setSelectedPen(const QPen &pen); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE; - - QCPItemPosition * const topLeft; - QCPItemPosition * const bottomRight; - QCPItemAnchor * const top; - QCPItemAnchor * const topRight; - QCPItemAnchor * const right; - QCPItemAnchor * const bottom; - QCPItemAnchor * const bottomLeft; - QCPItemAnchor * const left; - + explicit QCPItemPixmap(QCustomPlot *parentPlot); + virtual ~QCPItemPixmap() Q_DECL_OVERRIDE; + + // getters: + QPixmap pixmap() const { + return mPixmap; + } + bool scaled() const { + return mScaled; + } + Qt::AspectRatioMode aspectRatioMode() const { + return mAspectRatioMode; + } + Qt::TransformationMode transformationMode() const { + return mTransformationMode; + } + QPen pen() const { + return mPen; + } + QPen selectedPen() const { + return mSelectedPen; + } + + // setters; + void setPixmap(const QPixmap &pixmap); + void setScaled(bool scaled, Qt::AspectRatioMode aspectRatioMode = Qt::KeepAspectRatio, Qt::TransformationMode transformationMode = Qt::SmoothTransformation); + void setPen(const QPen &pen); + void setSelectedPen(const QPen &pen); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = nullptr) const Q_DECL_OVERRIDE; + + QCPItemPosition *const topLeft; + QCPItemPosition *const bottomRight; + QCPItemAnchor *const top; + QCPItemAnchor *const topRight; + QCPItemAnchor *const right; + QCPItemAnchor *const bottom; + QCPItemAnchor *const bottomLeft; + QCPItemAnchor *const left; + protected: - enum AnchorIndex {aiTop, aiTopRight, aiRight, aiBottom, aiBottomLeft, aiLeft}; - - // property members: - 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) 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); - QRect getFinalRect(bool *flippedHorz=nullptr, bool *flippedVert=nullptr) const; - QPen mainPen() const; + enum AnchorIndex {aiTop, aiTopRight, aiRight, aiBottom, aiBottomLeft, aiLeft}; + + // property members: + 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) 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); + QRect getFinalRect(bool *flippedHorz = nullptr, bool *flippedVert = nullptr) const; + QPen mainPen() const; }; /* end of 'src/items/item-pixmap.h' */ @@ -6800,81 +7629,99 @@ protected: class QCP_LIB_DECL QCPItemTracer : public QCPAbstractItem { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - 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(double size READ size WRITE setSize) - Q_PROPERTY(TracerStyle style READ style WRITE setStyle) - Q_PROPERTY(QCPGraph* graph READ graph WRITE setGraph) - Q_PROPERTY(double graphKey READ graphKey WRITE setGraphKey) - Q_PROPERTY(bool interpolating READ interpolating WRITE setInterpolating) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + 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(double size READ size WRITE setSize) + Q_PROPERTY(TracerStyle style READ style WRITE setStyle) + Q_PROPERTY(QCPGraph *graph READ graph WRITE setGraph) + Q_PROPERTY(double graphKey READ graphKey WRITE setGraphKey) + Q_PROPERTY(bool interpolating READ interpolating WRITE setInterpolating) + /// \endcond public: - /*! - The different visual appearances a tracer item can have. Some styles size may be controlled with \ref setSize. - - \see setStyle - */ - enum TracerStyle { tsNone ///< The tracer is not visible - ,tsPlus ///< A plus shaped crosshair with limited size - ,tsCrosshair ///< A plus shaped crosshair which spans the complete axis rect - ,tsCircle ///< A circle - ,tsSquare ///< A square - }; - Q_ENUMS(TracerStyle) + /*! + The different visual appearances a tracer item can have. Some styles size may be controlled with \ref setSize. - explicit QCPItemTracer(QCustomPlot *parentPlot); - virtual ~QCPItemTracer() Q_DECL_OVERRIDE; + \see setStyle + */ + enum TracerStyle { tsNone ///< The tracer is not visible + , tsPlus ///< A plus shaped crosshair with limited size + , tsCrosshair ///< A plus shaped crosshair which spans the complete axis rect + , tsCircle ///< A circle + , tsSquare ///< A square + }; + Q_ENUMS(TracerStyle) - // getters: - QPen pen() const { return mPen; } - QPen selectedPen() const { return mSelectedPen; } - QBrush brush() const { return mBrush; } - QBrush selectedBrush() const { return mSelectedBrush; } - double size() const { return mSize; } - TracerStyle style() const { return mStyle; } - QCPGraph *graph() const { return mGraph; } - double graphKey() const { return mGraphKey; } - bool interpolating() const { return mInterpolating; } + explicit QCPItemTracer(QCustomPlot *parentPlot); + virtual ~QCPItemTracer() Q_DECL_OVERRIDE; - // setters; - void setPen(const QPen &pen); - void setSelectedPen(const QPen &pen); - void setBrush(const QBrush &brush); - void setSelectedBrush(const QBrush &brush); - void setSize(double size); - void setStyle(TracerStyle style); - void setGraph(QCPGraph *graph); - void setGraphKey(double key); - void setInterpolating(bool enabled); + // getters: + QPen pen() const { + return mPen; + } + QPen selectedPen() const { + return mSelectedPen; + } + QBrush brush() const { + return mBrush; + } + QBrush selectedBrush() const { + return mSelectedBrush; + } + double size() const { + return mSize; + } + TracerStyle style() const { + return mStyle; + } + QCPGraph *graph() const { + return mGraph; + } + double graphKey() const { + return mGraphKey; + } + bool interpolating() const { + return mInterpolating; + } - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE; - - // non-virtual methods: - void updatePosition(); + // setters; + void setPen(const QPen &pen); + void setSelectedPen(const QPen &pen); + void setBrush(const QBrush &brush); + void setSelectedBrush(const QBrush &brush); + void setSize(double size); + void setStyle(TracerStyle style); + void setGraph(QCPGraph *graph); + void setGraphKey(double key); + void setInterpolating(bool enabled); - QCPItemPosition * const position; + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = nullptr) const Q_DECL_OVERRIDE; + + // non-virtual methods: + void updatePosition(); + + QCPItemPosition *const position; protected: - // property members: - QPen mPen, mSelectedPen; - QBrush mBrush, mSelectedBrush; - double mSize; - TracerStyle mStyle; - QCPGraph *mGraph; - double mGraphKey; - bool mInterpolating; + // property members: + QPen mPen, mSelectedPen; + QBrush mBrush, mSelectedBrush; + double mSize; + TracerStyle mStyle; + QCPGraph *mGraph; + double mGraphKey; + bool mInterpolating; - // reimplemented virtual methods: - virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; + // reimplemented virtual methods: + virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; - // non-virtual methods: - QPen mainPen() const; - QBrush mainBrush() const; + // non-virtual methods: + QPen mainPen() const; + QBrush mainBrush() const; }; Q_DECLARE_METATYPE(QCPItemTracer::TracerStyle) @@ -6886,62 +7733,70 @@ Q_DECLARE_METATYPE(QCPItemTracer::TracerStyle) class QCP_LIB_DECL QCPItemBracket : public QCPAbstractItem { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - Q_PROPERTY(QPen pen READ pen WRITE setPen) - Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) - Q_PROPERTY(double length READ length WRITE setLength) - Q_PROPERTY(BracketStyle style READ style WRITE setStyle) - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(QPen pen READ pen WRITE setPen) + Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) + Q_PROPERTY(double length READ length WRITE setLength) + 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) + /*! + 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) + + explicit QCPItemBracket(QCustomPlot *parentPlot); + virtual ~QCPItemBracket() Q_DECL_OVERRIDE; + + // getters: + QPen pen() const { + return mPen; + } + QPen selectedPen() const { + return mSelectedPen; + } + double length() const { + return mLength; + } + BracketStyle style() const { + return mStyle; + } + + // setters; + void setPen(const QPen &pen); + void setSelectedPen(const QPen &pen); + void setLength(double length); + void setStyle(BracketStyle style); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = nullptr) const Q_DECL_OVERRIDE; + + QCPItemPosition *const left; + QCPItemPosition *const right; + QCPItemAnchor *const center; - explicit QCPItemBracket(QCustomPlot *parentPlot); - virtual ~QCPItemBracket() Q_DECL_OVERRIDE; - - // getters: - QPen pen() const { return mPen; } - QPen selectedPen() const { return mSelectedPen; } - double length() const { return mLength; } - BracketStyle style() const { return mStyle; } - - // setters; - void setPen(const QPen &pen); - void setSelectedPen(const QPen &pen); - void setLength(double length); - void setStyle(BracketStyle style); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=nullptr) const Q_DECL_OVERRIDE; - - QCPItemPosition * const left; - QCPItemPosition * const right; - QCPItemAnchor * const center; - protected: - // property members: - enum AnchorIndex {aiCenter}; - QPen mPen, mSelectedPen; - double mLength; - BracketStyle mStyle; - - // reimplemented virtual methods: - virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; - virtual QPointF anchorPixelPosition(int anchorId) const Q_DECL_OVERRIDE; - - // non-virtual methods: - QPen mainPen() const; + // property members: + enum AnchorIndex {aiCenter}; + QPen mPen, mSelectedPen; + double mLength; + BracketStyle mStyle; + + // reimplemented virtual methods: + 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) @@ -6954,241 +7809,313 @@ Q_DECLARE_METATYPE(QCPItemBracket::BracketStyle) class QCP_LIB_DECL QCPPolarAxisRadial : public QCPLayerable { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + + /// \endcond public: - /*! - Defines the reference of the angle at which a radial axis is tilted (\ref setAngle). - */ - enum AngleReference { arAbsolute ///< The axis tilt is given in absolute degrees. The zero is to the right and positive angles are measured counter-clockwise. - ,arAngularAxis ///< The axis tilt is measured in the angular coordinate system given by the parent angular axis. - }; - Q_ENUMS(AngleReference) - /*! - Defines the scale of an axis. - \see setScaleType - */ - enum ScaleType { stLinear ///< Linear scaling - ,stLogarithmic ///< Logarithmic scaling with correspondingly transformed axis coordinates (possibly also \ref setTicker to a \ref QCPAxisTickerLog instance). - }; - Q_ENUMS(ScaleType) - /*! - Defines the selectable parts of an axis. - \see setSelectableParts, setSelectedParts - */ - enum SelectablePart { spNone = 0 ///< None of the selectable parts - ,spAxis = 0x001 ///< The axis backbone and tick marks - ,spTickLabels = 0x002 ///< Tick labels (numbers) of this axis (as a whole, not individually) - ,spAxisLabel = 0x004 ///< The axis label - }; - Q_ENUMS(SelectablePart) - Q_FLAGS(SelectableParts) - Q_DECLARE_FLAGS(SelectableParts, SelectablePart) - - enum LabelMode { lmUpright ///< - ,lmRotated ///< - }; - Q_ENUMS(LabelMode) - - explicit QCPPolarAxisRadial(QCPPolarAxisAngular *parent); - virtual ~QCPPolarAxisRadial(); - - // getters: - bool rangeDrag() const { return mRangeDrag; } - bool rangeZoom() const { return mRangeZoom; } - double rangeZoomFactor() const { return mRangeZoomFactor; } - - QCPPolarAxisAngular *angularAxis() const { return mAngularAxis; } - ScaleType scaleType() const { return mScaleType; } - const QCPRange range() const { return mRange; } - bool rangeReversed() const { return mRangeReversed; } - double angle() const { return mAngle; } - AngleReference angleReference() const { return mAngleReference; } - QSharedPointer ticker() const { return mTicker; } - bool ticks() const { return mTicks; } - bool tickLabels() const { return mTickLabels; } - int tickLabelPadding() const { return mLabelPainter.padding(); } - QFont tickLabelFont() const { return mTickLabelFont; } - QColor tickLabelColor() const { return mTickLabelColor; } - double tickLabelRotation() const { return mLabelPainter.rotation(); } - LabelMode tickLabelMode() const; - QString numberFormat() const; - int numberPrecision() const { return mNumberPrecision; } - QVector tickVector() const { return mTickVector; } - QVector subTickVector() const { return mSubTickVector; } - QVector tickVectorLabels() const { return mTickVectorLabels; } - int tickLengthIn() const; - int tickLengthOut() const; - bool subTicks() const { return mSubTicks; } - int subTickLengthIn() const; - int subTickLengthOut() const; - QPen basePen() const { return mBasePen; } - QPen tickPen() const { return mTickPen; } - QPen subTickPen() const { return mSubTickPen; } - QFont labelFont() const { return mLabelFont; } - QColor labelColor() const { return mLabelColor; } - QString label() const { return mLabel; } - int labelPadding() const; - SelectableParts selectedParts() const { return mSelectedParts; } - SelectableParts selectableParts() const { return mSelectableParts; } - QFont selectedTickLabelFont() const { return mSelectedTickLabelFont; } - QFont selectedLabelFont() const { return mSelectedLabelFont; } - QColor selectedTickLabelColor() const { return mSelectedTickLabelColor; } - QColor selectedLabelColor() const { return mSelectedLabelColor; } - QPen selectedBasePen() const { return mSelectedBasePen; } - QPen selectedTickPen() const { return mSelectedTickPen; } - QPen selectedSubTickPen() const { return mSelectedSubTickPen; } - - // setters: - void setRangeDrag(bool enabled); - void setRangeZoom(bool enabled); - void setRangeZoomFactor(double factor); - - Q_SLOT void setScaleType(QCPPolarAxisRadial::ScaleType type); - 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 setAngle(double degrees); - void setAngleReference(AngleReference reference); - void setTicker(QSharedPointer ticker); - void setTicks(bool show); - void setTickLabels(bool show); - void setTickLabelPadding(int padding); - void setTickLabelFont(const QFont &font); - void setTickLabelColor(const QColor &color); - void setTickLabelRotation(double degrees); - void setTickLabelMode(LabelMode mode); - void setNumberFormat(const QString &formatCode); - void setNumberPrecision(int precision); - void setTickLength(int inside, int outside=0); - void setTickLengthIn(int inside); - void setTickLengthOut(int outside); - void setSubTicks(bool show); - void setSubTickLength(int inside, int outside=0); - void setSubTickLengthIn(int inside); - void setSubTickLengthOut(int outside); - void setBasePen(const QPen &pen); - void setTickPen(const QPen &pen); - void setSubTickPen(const QPen &pen); - void setLabelFont(const QFont &font); - void setLabelColor(const QColor &color); - void setLabel(const QString &str); - void setLabelPadding(int padding); - void setSelectedTickLabelFont(const QFont &font); - void setSelectedLabelFont(const QFont &font); - void setSelectedTickLabelColor(const QColor &color); - void setSelectedLabelColor(const QColor &color); - void setSelectedBasePen(const QPen &pen); - void setSelectedTickPen(const QPen &pen); - void setSelectedSubTickPen(const QPen &pen); - Q_SLOT void setSelectableParts(const QCPPolarAxisRadial::SelectableParts &selectableParts); - Q_SLOT void setSelectedParts(const QCPPolarAxisRadial::SelectableParts &selectedParts); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const Q_DECL_OVERRIDE; - - // non-property methods: - void moveRange(double diff); - void scaleRange(double factor); - void scaleRange(double factor, double center); - void rescale(bool onlyVisiblePlottables=false); - void pixelToCoord(QPointF pixelPos, double &angleCoord, double &radiusCoord) const; - QPointF coordToPixel(double angleCoord, double radiusCoord) const; - double coordToRadius(double coord) const; - double radiusToCoord(double radius) const; - SelectablePart getPartAt(const QPointF &pos) const; - + /*! + Defines the reference of the angle at which a radial axis is tilted (\ref setAngle). + */ + enum AngleReference { arAbsolute ///< The axis tilt is given in absolute degrees. The zero is to the right and positive angles are measured counter-clockwise. + , arAngularAxis ///< The axis tilt is measured in the angular coordinate system given by the parent angular axis. + }; + Q_ENUMS(AngleReference) + /*! + Defines the scale of an axis. + \see setScaleType + */ + enum ScaleType { stLinear ///< Linear scaling + , stLogarithmic ///< Logarithmic scaling with correspondingly transformed axis coordinates (possibly also \ref setTicker to a \ref QCPAxisTickerLog instance). + }; + Q_ENUMS(ScaleType) + /*! + Defines the selectable parts of an axis. + \see setSelectableParts, setSelectedParts + */ + enum SelectablePart { spNone = 0 ///< None of the selectable parts + , spAxis = 0x001 ///< The axis backbone and tick marks + , spTickLabels = 0x002 ///< Tick labels (numbers) of this axis (as a whole, not individually) + , spAxisLabel = 0x004 ///< The axis label + }; + Q_ENUMS(SelectablePart) + Q_FLAGS(SelectableParts) + Q_DECLARE_FLAGS(SelectableParts, SelectablePart) + + enum LabelMode { lmUpright ///< + , lmRotated ///< + }; + Q_ENUMS(LabelMode) + + explicit QCPPolarAxisRadial(QCPPolarAxisAngular *parent); + virtual ~QCPPolarAxisRadial(); + + // getters: + bool rangeDrag() const { + return mRangeDrag; + } + bool rangeZoom() const { + return mRangeZoom; + } + double rangeZoomFactor() const { + return mRangeZoomFactor; + } + + QCPPolarAxisAngular *angularAxis() const { + return mAngularAxis; + } + ScaleType scaleType() const { + return mScaleType; + } + const QCPRange range() const { + return mRange; + } + bool rangeReversed() const { + return mRangeReversed; + } + double angle() const { + return mAngle; + } + AngleReference angleReference() const { + return mAngleReference; + } + QSharedPointer ticker() const { + return mTicker; + } + bool ticks() const { + return mTicks; + } + bool tickLabels() const { + return mTickLabels; + } + int tickLabelPadding() const { + return mLabelPainter.padding(); + } + QFont tickLabelFont() const { + return mTickLabelFont; + } + QColor tickLabelColor() const { + return mTickLabelColor; + } + double tickLabelRotation() const { + return mLabelPainter.rotation(); + } + LabelMode tickLabelMode() const; + QString numberFormat() const; + int numberPrecision() const { + return mNumberPrecision; + } + QVector tickVector() const { + return mTickVector; + } + QVector subTickVector() const { + return mSubTickVector; + } + QVector tickVectorLabels() const { + return mTickVectorLabels; + } + int tickLengthIn() const; + int tickLengthOut() const; + bool subTicks() const { + return mSubTicks; + } + int subTickLengthIn() const; + int subTickLengthOut() const; + QPen basePen() const { + return mBasePen; + } + QPen tickPen() const { + return mTickPen; + } + QPen subTickPen() const { + return mSubTickPen; + } + QFont labelFont() const { + return mLabelFont; + } + QColor labelColor() const { + return mLabelColor; + } + QString label() const { + return mLabel; + } + int labelPadding() const; + SelectableParts selectedParts() const { + return mSelectedParts; + } + SelectableParts selectableParts() const { + return mSelectableParts; + } + QFont selectedTickLabelFont() const { + return mSelectedTickLabelFont; + } + QFont selectedLabelFont() const { + return mSelectedLabelFont; + } + QColor selectedTickLabelColor() const { + return mSelectedTickLabelColor; + } + QColor selectedLabelColor() const { + return mSelectedLabelColor; + } + QPen selectedBasePen() const { + return mSelectedBasePen; + } + QPen selectedTickPen() const { + return mSelectedTickPen; + } + QPen selectedSubTickPen() const { + return mSelectedSubTickPen; + } + + // setters: + void setRangeDrag(bool enabled); + void setRangeZoom(bool enabled); + void setRangeZoomFactor(double factor); + + Q_SLOT void setScaleType(QCPPolarAxisRadial::ScaleType type); + 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 setAngle(double degrees); + void setAngleReference(AngleReference reference); + void setTicker(QSharedPointer ticker); + void setTicks(bool show); + void setTickLabels(bool show); + void setTickLabelPadding(int padding); + void setTickLabelFont(const QFont &font); + void setTickLabelColor(const QColor &color); + void setTickLabelRotation(double degrees); + void setTickLabelMode(LabelMode mode); + void setNumberFormat(const QString &formatCode); + void setNumberPrecision(int precision); + void setTickLength(int inside, int outside = 0); + void setTickLengthIn(int inside); + void setTickLengthOut(int outside); + void setSubTicks(bool show); + void setSubTickLength(int inside, int outside = 0); + void setSubTickLengthIn(int inside); + void setSubTickLengthOut(int outside); + void setBasePen(const QPen &pen); + void setTickPen(const QPen &pen); + void setSubTickPen(const QPen &pen); + void setLabelFont(const QFont &font); + void setLabelColor(const QColor &color); + void setLabel(const QString &str); + void setLabelPadding(int padding); + void setSelectedTickLabelFont(const QFont &font); + void setSelectedLabelFont(const QFont &font); + void setSelectedTickLabelColor(const QColor &color); + void setSelectedLabelColor(const QColor &color); + void setSelectedBasePen(const QPen &pen); + void setSelectedTickPen(const QPen &pen); + void setSelectedSubTickPen(const QPen &pen); + Q_SLOT void setSelectableParts(const QCPPolarAxisRadial::SelectableParts &selectableParts); + Q_SLOT void setSelectedParts(const QCPPolarAxisRadial::SelectableParts &selectedParts); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = 0) const Q_DECL_OVERRIDE; + + // non-property methods: + void moveRange(double diff); + void scaleRange(double factor); + void scaleRange(double factor, double center); + void rescale(bool onlyVisiblePlottables = false); + void pixelToCoord(QPointF pixelPos, double &angleCoord, double &radiusCoord) const; + QPointF coordToPixel(double angleCoord, double radiusCoord) const; + double coordToRadius(double coord) const; + double radiusToCoord(double radius) const; + SelectablePart getPartAt(const QPointF &pos) const; + signals: - void rangeChanged(const QCPRange &newRange); - void rangeChanged(const QCPRange &newRange, const QCPRange &oldRange); - void scaleTypeChanged(QCPPolarAxisRadial::ScaleType scaleType); - void selectionChanged(const QCPPolarAxisRadial::SelectableParts &parts); - void selectableChanged(const QCPPolarAxisRadial::SelectableParts &parts); + void rangeChanged(const QCPRange &newRange); + void rangeChanged(const QCPRange &newRange, const QCPRange &oldRange); + void scaleTypeChanged(QCPPolarAxisRadial::ScaleType scaleType); + void selectionChanged(const QCPPolarAxisRadial::SelectableParts &parts); + void selectableChanged(const QCPPolarAxisRadial::SelectableParts &parts); protected: - // property members: - bool mRangeDrag; - bool mRangeZoom; - double mRangeZoomFactor; - - // axis base: - QCPPolarAxisAngular *mAngularAxis; - double mAngle; - AngleReference mAngleReference; - SelectableParts mSelectableParts, mSelectedParts; - QPen mBasePen, mSelectedBasePen; - // axis label: - int mLabelPadding; - QString mLabel; - QFont mLabelFont, mSelectedLabelFont; - QColor mLabelColor, mSelectedLabelColor; - // tick labels: - //int mTickLabelPadding; in label painter - bool mTickLabels; - //double mTickLabelRotation; in label painter - QFont mTickLabelFont, mSelectedTickLabelFont; - QColor mTickLabelColor, mSelectedTickLabelColor; - int mNumberPrecision; - QLatin1Char mNumberFormatChar; - bool mNumberBeautifulPowers; - bool mNumberMultiplyCross; - // ticks and subticks: - bool mTicks; - bool mSubTicks; - int mTickLengthIn, mTickLengthOut, mSubTickLengthIn, mSubTickLengthOut; - QPen mTickPen, mSelectedTickPen; - QPen mSubTickPen, mSelectedSubTickPen; - // scale and range: - QCPRange mRange; - bool mRangeReversed; - ScaleType mScaleType; - - // non-property members: - QPointF mCenter; - double mRadius; - QSharedPointer mTicker; - QVector mTickVector; - QVector mTickVectorLabels; - QVector mSubTickVector; - bool mDragging; - QCPRange mDragStartRange; - QCP::AntialiasedElements mAADragBackup, mNotAADragBackup; - QCPLabelPainterPrivate mLabelPainter; - - // reimplemented virtual methods: - 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) Q_DECL_OVERRIDE; - virtual void deselectEvent(bool *selectionStateChanged) Q_DECL_OVERRIDE; - // mouse events: - 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-virtual methods: - void updateGeometry(const QPointF ¢er, double radius); - void setupTickVectors(); - QPen getBasePen() const; - QPen getTickPen() const; - QPen getSubTickPen() const; - QFont getTickLabelFont() const; - QFont getLabelFont() const; - QColor getTickLabelColor() const; - QColor getLabelColor() const; - + // property members: + bool mRangeDrag; + bool mRangeZoom; + double mRangeZoomFactor; + + // axis base: + QCPPolarAxisAngular *mAngularAxis; + double mAngle; + AngleReference mAngleReference; + SelectableParts mSelectableParts, mSelectedParts; + QPen mBasePen, mSelectedBasePen; + // axis label: + int mLabelPadding; + QString mLabel; + QFont mLabelFont, mSelectedLabelFont; + QColor mLabelColor, mSelectedLabelColor; + // tick labels: + //int mTickLabelPadding; in label painter + bool mTickLabels; + //double mTickLabelRotation; in label painter + QFont mTickLabelFont, mSelectedTickLabelFont; + QColor mTickLabelColor, mSelectedTickLabelColor; + int mNumberPrecision; + QLatin1Char mNumberFormatChar; + bool mNumberBeautifulPowers; + bool mNumberMultiplyCross; + // ticks and subticks: + bool mTicks; + bool mSubTicks; + int mTickLengthIn, mTickLengthOut, mSubTickLengthIn, mSubTickLengthOut; + QPen mTickPen, mSelectedTickPen; + QPen mSubTickPen, mSelectedSubTickPen; + // scale and range: + QCPRange mRange; + bool mRangeReversed; + ScaleType mScaleType; + + // non-property members: + QPointF mCenter; + double mRadius; + QSharedPointer mTicker; + QVector mTickVector; + QVector mTickVectorLabels; + QVector mSubTickVector; + bool mDragging; + QCPRange mDragStartRange; + QCP::AntialiasedElements mAADragBackup, mNotAADragBackup; + QCPLabelPainterPrivate mLabelPainter; + + // reimplemented virtual methods: + 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) Q_DECL_OVERRIDE; + virtual void deselectEvent(bool *selectionStateChanged) Q_DECL_OVERRIDE; + // mouse events: + 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-virtual methods: + void updateGeometry(const QPointF ¢er, double radius); + void setupTickVectors(); + QPen getBasePen() const; + QPen getTickPen() const; + QPen getSubTickPen() const; + QFont getTickLabelFont() const; + QFont getLabelFont() const; + QColor getTickLabelColor() const; + QColor getLabelColor() const; + private: - Q_DISABLE_COPY(QCPPolarAxisRadial) - - friend class QCustomPlot; - friend class QCPPolarAxisAngular; + Q_DISABLE_COPY(QCPPolarAxisRadial) + + friend class QCustomPlot; + friend class QCPPolarAxisAngular; }; Q_DECLARE_OPERATORS_FOR_FLAGS(QCPPolarAxisRadial::SelectableParts) Q_DECLARE_METATYPE(QCPPolarAxisRadial::AngleReference) @@ -7205,267 +8132,383 @@ Q_DECLARE_METATYPE(QCPPolarAxisRadial::SelectablePart) class QCP_LIB_DECL QCPPolarAxisAngular : public QCPLayoutElement { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + + /// \endcond public: - /*! - Defines the selectable parts of an axis. - \see setSelectableParts, setSelectedParts - */ - enum SelectablePart { spNone = 0 ///< None of the selectable parts - ,spAxis = 0x001 ///< The axis backbone and tick marks - ,spTickLabels = 0x002 ///< Tick labels (numbers) of this axis (as a whole, not individually) - ,spAxisLabel = 0x004 ///< The axis label - }; - Q_ENUMS(SelectablePart) - Q_FLAGS(SelectableParts) - Q_DECLARE_FLAGS(SelectableParts, SelectablePart) - - /*! - TODO - */ - enum LabelMode { lmUpright ///< - ,lmRotated ///< - }; - Q_ENUMS(LabelMode) - - explicit QCPPolarAxisAngular(QCustomPlot *parentPlot); - virtual ~QCPPolarAxisAngular(); - - // getters: - QPixmap background() const { return mBackgroundPixmap; } - QBrush backgroundBrush() const { return mBackgroundBrush; } - bool backgroundScaled() const { return mBackgroundScaled; } - Qt::AspectRatioMode backgroundScaledMode() const { return mBackgroundScaledMode; } - bool rangeDrag() const { return mRangeDrag; } - bool rangeZoom() const { return mRangeZoom; } - double rangeZoomFactor() const { return mRangeZoomFactor; } - - const QCPRange range() const { return mRange; } - bool rangeReversed() const { return mRangeReversed; } - double angle() const { return mAngle; } - QSharedPointer ticker() const { return mTicker; } - bool ticks() const { return mTicks; } - bool tickLabels() const { return mTickLabels; } - int tickLabelPadding() const { return mLabelPainter.padding(); } - QFont tickLabelFont() const { return mTickLabelFont; } - QColor tickLabelColor() const { return mTickLabelColor; } - double tickLabelRotation() const { return mLabelPainter.rotation(); } - LabelMode tickLabelMode() const; - QString numberFormat() const; - int numberPrecision() const { return mNumberPrecision; } - QVector tickVector() const { return mTickVector; } - QVector tickVectorLabels() const { return mTickVectorLabels; } - int tickLengthIn() const { return mTickLengthIn; } - int tickLengthOut() const { return mTickLengthOut; } - bool subTicks() const { return mSubTicks; } - int subTickLengthIn() const { return mSubTickLengthIn; } - int subTickLengthOut() const { return mSubTickLengthOut; } - QPen basePen() const { return mBasePen; } - QPen tickPen() const { return mTickPen; } - QPen subTickPen() const { return mSubTickPen; } - QFont labelFont() const { return mLabelFont; } - QColor labelColor() const { return mLabelColor; } - QString label() const { return mLabel; } - int labelPadding() const { return mLabelPadding; } - SelectableParts selectedParts() const { return mSelectedParts; } - SelectableParts selectableParts() const { return mSelectableParts; } - QFont selectedTickLabelFont() const { return mSelectedTickLabelFont; } - QFont selectedLabelFont() const { return mSelectedLabelFont; } - QColor selectedTickLabelColor() const { return mSelectedTickLabelColor; } - QColor selectedLabelColor() const { return mSelectedLabelColor; } - QPen selectedBasePen() const { return mSelectedBasePen; } - QPen selectedTickPen() const { return mSelectedTickPen; } - QPen selectedSubTickPen() const { return mSelectedSubTickPen; } - QCPPolarGrid *grid() const { return mGrid; } - - // setters: - void setBackground(const QPixmap &pm); - void setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode=Qt::KeepAspectRatioByExpanding); - void setBackground(const QBrush &brush); - void setBackgroundScaled(bool scaled); - void setBackgroundScaledMode(Qt::AspectRatioMode mode); - void setRangeDrag(bool enabled); - void setRangeZoom(bool enabled); - void setRangeZoomFactor(double factor); - - 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 setAngle(double degrees); - void setTicker(QSharedPointer ticker); - void setTicks(bool show); - void setTickLabels(bool show); - void setTickLabelPadding(int padding); - void setTickLabelFont(const QFont &font); - void setTickLabelColor(const QColor &color); - void setTickLabelRotation(double degrees); - void setTickLabelMode(LabelMode mode); - void setNumberFormat(const QString &formatCode); - void setNumberPrecision(int precision); - void setTickLength(int inside, int outside=0); - void setTickLengthIn(int inside); - void setTickLengthOut(int outside); - void setSubTicks(bool show); - void setSubTickLength(int inside, int outside=0); - void setSubTickLengthIn(int inside); - void setSubTickLengthOut(int outside); - void setBasePen(const QPen &pen); - void setTickPen(const QPen &pen); - void setSubTickPen(const QPen &pen); - void setLabelFont(const QFont &font); - void setLabelColor(const QColor &color); - void setLabel(const QString &str); - void setLabelPadding(int padding); - void setLabelPosition(Qt::AlignmentFlag position); - void setSelectedTickLabelFont(const QFont &font); - void setSelectedLabelFont(const QFont &font); - void setSelectedTickLabelColor(const QColor &color); - void setSelectedLabelColor(const QColor &color); - void setSelectedBasePen(const QPen &pen); - void setSelectedTickPen(const QPen &pen); - void setSelectedSubTickPen(const QPen &pen); - Q_SLOT void setSelectableParts(const QCPPolarAxisAngular::SelectableParts &selectableParts); - Q_SLOT void setSelectedParts(const QCPPolarAxisAngular::SelectableParts &selectedParts); - - // reimplemented virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const Q_DECL_OVERRIDE; - virtual void update(UpdatePhase phase) Q_DECL_OVERRIDE; - virtual QList elements(bool recursive) const Q_DECL_OVERRIDE; - - // non-property methods: - bool removeGraph(QCPPolarGraph *graph); - int radialAxisCount() const; - QCPPolarAxisRadial *radialAxis(int index=0) const; - QList radialAxes() const; - QCPPolarAxisRadial *addRadialAxis(QCPPolarAxisRadial *axis=0); - bool removeRadialAxis(QCPPolarAxisRadial *axis); - QCPLayoutInset *insetLayout() const { return mInsetLayout; } - QRegion exactClipRegion() const; - - void moveRange(double diff); - void scaleRange(double factor); - void scaleRange(double factor, double center); - void rescale(bool onlyVisiblePlottables=false); - double coordToAngleRad(double coord) const { return mAngleRad+(coord-mRange.lower)/mRange.size()*(mRangeReversed ? -2.0*M_PI : 2.0*M_PI); } // mention in doc that return doesn't wrap - double angleRadToCoord(double angleRad) const { return mRange.lower+(angleRad-mAngleRad)/(mRangeReversed ? -2.0*M_PI : 2.0*M_PI)*mRange.size(); } - void pixelToCoord(QPointF pixelPos, double &angleCoord, double &radiusCoord) const; - QPointF coordToPixel(double angleCoord, double radiusCoord) const; - SelectablePart getPartAt(const QPointF &pos) const; - - // read-only interface imitating a QRect: - int left() const { return mRect.left(); } - int right() const { return mRect.right(); } - int top() const { return mRect.top(); } - int bottom() const { return mRect.bottom(); } - int width() const { return mRect.width(); } - int height() const { return mRect.height(); } - QSize size() const { return mRect.size(); } - QPoint topLeft() const { return mRect.topLeft(); } - QPoint topRight() const { return mRect.topRight(); } - QPoint bottomLeft() const { return mRect.bottomLeft(); } - QPoint bottomRight() const { return mRect.bottomRight(); } - QPointF center() const { return mCenter; } - double radius() const { return mRadius; } - + /*! + Defines the selectable parts of an axis. + \see setSelectableParts, setSelectedParts + */ + enum SelectablePart { spNone = 0 ///< None of the selectable parts + , spAxis = 0x001 ///< The axis backbone and tick marks + , spTickLabels = 0x002 ///< Tick labels (numbers) of this axis (as a whole, not individually) + , spAxisLabel = 0x004 ///< The axis label + }; + Q_ENUMS(SelectablePart) + Q_FLAGS(SelectableParts) + Q_DECLARE_FLAGS(SelectableParts, SelectablePart) + + /*! + TODO + */ + enum LabelMode { lmUpright ///< + , lmRotated ///< + }; + Q_ENUMS(LabelMode) + + explicit QCPPolarAxisAngular(QCustomPlot *parentPlot); + virtual ~QCPPolarAxisAngular(); + + // getters: + QPixmap background() const { + return mBackgroundPixmap; + } + QBrush backgroundBrush() const { + return mBackgroundBrush; + } + bool backgroundScaled() const { + return mBackgroundScaled; + } + Qt::AspectRatioMode backgroundScaledMode() const { + return mBackgroundScaledMode; + } + bool rangeDrag() const { + return mRangeDrag; + } + bool rangeZoom() const { + return mRangeZoom; + } + double rangeZoomFactor() const { + return mRangeZoomFactor; + } + + const QCPRange range() const { + return mRange; + } + bool rangeReversed() const { + return mRangeReversed; + } + double angle() const { + return mAngle; + } + QSharedPointer ticker() const { + return mTicker; + } + bool ticks() const { + return mTicks; + } + bool tickLabels() const { + return mTickLabels; + } + int tickLabelPadding() const { + return mLabelPainter.padding(); + } + QFont tickLabelFont() const { + return mTickLabelFont; + } + QColor tickLabelColor() const { + return mTickLabelColor; + } + double tickLabelRotation() const { + return mLabelPainter.rotation(); + } + LabelMode tickLabelMode() const; + QString numberFormat() const; + int numberPrecision() const { + return mNumberPrecision; + } + QVector tickVector() const { + return mTickVector; + } + QVector tickVectorLabels() const { + return mTickVectorLabels; + } + int tickLengthIn() const { + return mTickLengthIn; + } + int tickLengthOut() const { + return mTickLengthOut; + } + bool subTicks() const { + return mSubTicks; + } + int subTickLengthIn() const { + return mSubTickLengthIn; + } + int subTickLengthOut() const { + return mSubTickLengthOut; + } + QPen basePen() const { + return mBasePen; + } + QPen tickPen() const { + return mTickPen; + } + QPen subTickPen() const { + return mSubTickPen; + } + QFont labelFont() const { + return mLabelFont; + } + QColor labelColor() const { + return mLabelColor; + } + QString label() const { + return mLabel; + } + int labelPadding() const { + return mLabelPadding; + } + SelectableParts selectedParts() const { + return mSelectedParts; + } + SelectableParts selectableParts() const { + return mSelectableParts; + } + QFont selectedTickLabelFont() const { + return mSelectedTickLabelFont; + } + QFont selectedLabelFont() const { + return mSelectedLabelFont; + } + QColor selectedTickLabelColor() const { + return mSelectedTickLabelColor; + } + QColor selectedLabelColor() const { + return mSelectedLabelColor; + } + QPen selectedBasePen() const { + return mSelectedBasePen; + } + QPen selectedTickPen() const { + return mSelectedTickPen; + } + QPen selectedSubTickPen() const { + return mSelectedSubTickPen; + } + QCPPolarGrid *grid() const { + return mGrid; + } + + // setters: + void setBackground(const QPixmap &pm); + void setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode = Qt::KeepAspectRatioByExpanding); + void setBackground(const QBrush &brush); + void setBackgroundScaled(bool scaled); + void setBackgroundScaledMode(Qt::AspectRatioMode mode); + void setRangeDrag(bool enabled); + void setRangeZoom(bool enabled); + void setRangeZoomFactor(double factor); + + 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 setAngle(double degrees); + void setTicker(QSharedPointer ticker); + void setTicks(bool show); + void setTickLabels(bool show); + void setTickLabelPadding(int padding); + void setTickLabelFont(const QFont &font); + void setTickLabelColor(const QColor &color); + void setTickLabelRotation(double degrees); + void setTickLabelMode(LabelMode mode); + void setNumberFormat(const QString &formatCode); + void setNumberPrecision(int precision); + void setTickLength(int inside, int outside = 0); + void setTickLengthIn(int inside); + void setTickLengthOut(int outside); + void setSubTicks(bool show); + void setSubTickLength(int inside, int outside = 0); + void setSubTickLengthIn(int inside); + void setSubTickLengthOut(int outside); + void setBasePen(const QPen &pen); + void setTickPen(const QPen &pen); + void setSubTickPen(const QPen &pen); + void setLabelFont(const QFont &font); + void setLabelColor(const QColor &color); + void setLabel(const QString &str); + void setLabelPadding(int padding); + void setLabelPosition(Qt::AlignmentFlag position); + void setSelectedTickLabelFont(const QFont &font); + void setSelectedLabelFont(const QFont &font); + void setSelectedTickLabelColor(const QColor &color); + void setSelectedLabelColor(const QColor &color); + void setSelectedBasePen(const QPen &pen); + void setSelectedTickPen(const QPen &pen); + void setSelectedSubTickPen(const QPen &pen); + Q_SLOT void setSelectableParts(const QCPPolarAxisAngular::SelectableParts &selectableParts); + Q_SLOT void setSelectedParts(const QCPPolarAxisAngular::SelectableParts &selectedParts); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = 0) const Q_DECL_OVERRIDE; + virtual void update(UpdatePhase phase) Q_DECL_OVERRIDE; + virtual QList elements(bool recursive) const Q_DECL_OVERRIDE; + + // non-property methods: + bool removeGraph(QCPPolarGraph *graph); + int radialAxisCount() const; + QCPPolarAxisRadial *radialAxis(int index = 0) const; + QList radialAxes() const; + QCPPolarAxisRadial *addRadialAxis(QCPPolarAxisRadial *axis = 0); + bool removeRadialAxis(QCPPolarAxisRadial *axis); + QCPLayoutInset *insetLayout() const { + return mInsetLayout; + } + QRegion exactClipRegion() const; + + void moveRange(double diff); + void scaleRange(double factor); + void scaleRange(double factor, double center); + void rescale(bool onlyVisiblePlottables = false); + double coordToAngleRad(double coord) const { + return mAngleRad + (coord - mRange.lower) / mRange.size() * (mRangeReversed ? -2.0 * M_PI : 2.0 * M_PI); // mention in doc that return doesn't wrap + } + double angleRadToCoord(double angleRad) const { + return mRange.lower + (angleRad - mAngleRad) / (mRangeReversed ? -2.0 * M_PI : 2.0 * M_PI) * mRange.size(); + } + void pixelToCoord(QPointF pixelPos, double &angleCoord, double &radiusCoord) const; + QPointF coordToPixel(double angleCoord, double radiusCoord) const; + SelectablePart getPartAt(const QPointF &pos) const; + + // read-only interface imitating a QRect: + int left() const { + return mRect.left(); + } + int right() const { + return mRect.right(); + } + int top() const { + return mRect.top(); + } + int bottom() const { + return mRect.bottom(); + } + int width() const { + return mRect.width(); + } + int height() const { + return mRect.height(); + } + QSize size() const { + return mRect.size(); + } + QPoint topLeft() const { + return mRect.topLeft(); + } + QPoint topRight() const { + return mRect.topRight(); + } + QPoint bottomLeft() const { + return mRect.bottomLeft(); + } + QPoint bottomRight() const { + return mRect.bottomRight(); + } + QPointF center() const { + return mCenter; + } + double radius() const { + return mRadius; + } + signals: - void rangeChanged(const QCPRange &newRange); - void rangeChanged(const QCPRange &newRange, const QCPRange &oldRange); - void selectionChanged(const QCPPolarAxisAngular::SelectableParts &parts); - void selectableChanged(const QCPPolarAxisAngular::SelectableParts &parts); - + void rangeChanged(const QCPRange &newRange); + void rangeChanged(const QCPRange &newRange, const QCPRange &oldRange); + void selectionChanged(const QCPPolarAxisAngular::SelectableParts &parts); + void selectableChanged(const QCPPolarAxisAngular::SelectableParts &parts); + protected: - // property members: - QBrush mBackgroundBrush; - QPixmap mBackgroundPixmap; - QPixmap mScaledBackgroundPixmap; - bool mBackgroundScaled; - Qt::AspectRatioMode mBackgroundScaledMode; - QCPLayoutInset *mInsetLayout; - bool mRangeDrag; - bool mRangeZoom; - double mRangeZoomFactor; - - // axis base: - double mAngle, mAngleRad; - SelectableParts mSelectableParts, mSelectedParts; - QPen mBasePen, mSelectedBasePen; - // axis label: - int mLabelPadding; - QString mLabel; - QFont mLabelFont, mSelectedLabelFont; - QColor mLabelColor, mSelectedLabelColor; - // tick labels: - //int mTickLabelPadding; in label painter - bool mTickLabels; - //double mTickLabelRotation; in label painter - QFont mTickLabelFont, mSelectedTickLabelFont; - QColor mTickLabelColor, mSelectedTickLabelColor; - int mNumberPrecision; - QLatin1Char mNumberFormatChar; - bool mNumberBeautifulPowers; - bool mNumberMultiplyCross; - // ticks and subticks: - bool mTicks; - bool mSubTicks; - int mTickLengthIn, mTickLengthOut, mSubTickLengthIn, mSubTickLengthOut; - QPen mTickPen, mSelectedTickPen; - QPen mSubTickPen, mSelectedSubTickPen; - // scale and range: - QCPRange mRange; - bool mRangeReversed; - - // non-property members: - QPointF mCenter; - double mRadius; - QList mRadialAxes; - QCPPolarGrid *mGrid; - QList mGraphs; - QSharedPointer mTicker; - QVector mTickVector; - QVector mTickVectorLabels; - QVector mTickVectorCosSin; - QVector mSubTickVector; - QVector mSubTickVectorCosSin; - bool mDragging; - QCPRange mDragAngularStart; - QList mDragRadialStart; - QCP::AntialiasedElements mAADragBackup, mNotAADragBackup; - QCPLabelPainterPrivate mLabelPainter; - - // reimplemented virtual methods: - 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 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-virtual methods: - bool registerPolarGraph(QCPPolarGraph *graph); - void drawBackground(QCPPainter *painter, const QPointF ¢er, double radius); - void setupTickVectors(); - QPen getBasePen() const; - QPen getTickPen() const; - QPen getSubTickPen() const; - QFont getTickLabelFont() const; - QFont getLabelFont() const; - QColor getTickLabelColor() const; - QColor getLabelColor() const; - + // property members: + QBrush mBackgroundBrush; + QPixmap mBackgroundPixmap; + QPixmap mScaledBackgroundPixmap; + bool mBackgroundScaled; + Qt::AspectRatioMode mBackgroundScaledMode; + QCPLayoutInset *mInsetLayout; + bool mRangeDrag; + bool mRangeZoom; + double mRangeZoomFactor; + + // axis base: + double mAngle, mAngleRad; + SelectableParts mSelectableParts, mSelectedParts; + QPen mBasePen, mSelectedBasePen; + // axis label: + int mLabelPadding; + QString mLabel; + QFont mLabelFont, mSelectedLabelFont; + QColor mLabelColor, mSelectedLabelColor; + // tick labels: + //int mTickLabelPadding; in label painter + bool mTickLabels; + //double mTickLabelRotation; in label painter + QFont mTickLabelFont, mSelectedTickLabelFont; + QColor mTickLabelColor, mSelectedTickLabelColor; + int mNumberPrecision; + QLatin1Char mNumberFormatChar; + bool mNumberBeautifulPowers; + bool mNumberMultiplyCross; + // ticks and subticks: + bool mTicks; + bool mSubTicks; + int mTickLengthIn, mTickLengthOut, mSubTickLengthIn, mSubTickLengthOut; + QPen mTickPen, mSelectedTickPen; + QPen mSubTickPen, mSelectedSubTickPen; + // scale and range: + QCPRange mRange; + bool mRangeReversed; + + // non-property members: + QPointF mCenter; + double mRadius; + QList mRadialAxes; + QCPPolarGrid *mGrid; + QList mGraphs; + QSharedPointer mTicker; + QVector mTickVector; + QVector mTickVectorLabels; + QVector mTickVectorCosSin; + QVector mSubTickVector; + QVector mSubTickVectorCosSin; + bool mDragging; + QCPRange mDragAngularStart; + QList mDragRadialStart; + QCP::AntialiasedElements mAADragBackup, mNotAADragBackup; + QCPLabelPainterPrivate mLabelPainter; + + // reimplemented virtual methods: + 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 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-virtual methods: + bool registerPolarGraph(QCPPolarGraph *graph); + void drawBackground(QCPPainter *painter, const QPointF ¢er, double radius); + void setupTickVectors(); + QPen getBasePen() const; + QPen getTickPen() const; + QPen getSubTickPen() const; + QFont getTickLabelFont() const; + QFont getLabelFont() const; + QColor getTickLabelColor() const; + QColor getLabelColor() const; + private: - Q_DISABLE_COPY(QCPPolarAxisAngular) - - friend class QCustomPlot; - friend class QCPPolarGrid; - friend class QCPPolarGraph; + Q_DISABLE_COPY(QCPPolarAxisAngular) + + friend class QCustomPlot; + friend class QCPPolarGrid; + friend class QCPPolarGraph; }; Q_DECLARE_OPERATORS_FOR_FLAGS(QCPPolarAxisAngular::SelectableParts) Q_DECLARE_METATYPE(QCPPolarAxisAngular::SelectablePart) @@ -7476,74 +8519,94 @@ Q_DECLARE_METATYPE(QCPPolarAxisAngular::SelectablePart) /* including file 'src/polar/polargrid.h' */ /* modified 2021-03-29T02:30:44, size 4506 */ -class QCP_LIB_DECL QCPPolarGrid :public QCPLayerable +class QCP_LIB_DECL QCPPolarGrid : public QCPLayerable { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - - /// \endcond + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + + /// \endcond public: - /*! - TODO - */ - enum GridType { gtAngular = 0x01 ///< - ,gtRadial = 0x02 ///< - ,gtAll = 0xFF ///< - ,gtNone = 0x00 ///< - }; - Q_ENUMS(GridType) - Q_FLAGS(GridTypes) - Q_DECLARE_FLAGS(GridTypes, GridType) - - explicit QCPPolarGrid(QCPPolarAxisAngular *parentAxis); - - // getters: - QCPPolarAxisRadial *radialAxis() const { return mRadialAxis.data(); } - GridTypes type() const { return mType; } - GridTypes subGridType() const { return mSubGridType; } - bool antialiasedSubGrid() const { return mAntialiasedSubGrid; } - bool antialiasedZeroLine() const { return mAntialiasedZeroLine; } - QPen angularPen() const { return mAngularPen; } - QPen angularSubGridPen() const { return mAngularSubGridPen; } - QPen radialPen() const { return mRadialPen; } - QPen radialSubGridPen() const { return mRadialSubGridPen; } - QPen radialZeroLinePen() const { return mRadialZeroLinePen; } - - // setters: - void setRadialAxis(QCPPolarAxisRadial *axis); - void setType(GridTypes type); - void setSubGridType(GridTypes type); - void setAntialiasedSubGrid(bool enabled); - void setAntialiasedZeroLine(bool enabled); - void setAngularPen(const QPen &pen); - void setAngularSubGridPen(const QPen &pen); - void setRadialPen(const QPen &pen); - void setRadialSubGridPen(const QPen &pen); - void setRadialZeroLinePen(const QPen &pen); - + /*! + TODO + */ + enum GridType { gtAngular = 0x01 ///< + , gtRadial = 0x02 ///< + , gtAll = 0xFF ///< + , gtNone = 0x00 ///< + }; + Q_ENUMS(GridType) + Q_FLAGS(GridTypes) + Q_DECLARE_FLAGS(GridTypes, GridType) + + explicit QCPPolarGrid(QCPPolarAxisAngular *parentAxis); + + // getters: + QCPPolarAxisRadial *radialAxis() const { + return mRadialAxis.data(); + } + GridTypes type() const { + return mType; + } + GridTypes subGridType() const { + return mSubGridType; + } + bool antialiasedSubGrid() const { + return mAntialiasedSubGrid; + } + bool antialiasedZeroLine() const { + return mAntialiasedZeroLine; + } + QPen angularPen() const { + return mAngularPen; + } + QPen angularSubGridPen() const { + return mAngularSubGridPen; + } + QPen radialPen() const { + return mRadialPen; + } + QPen radialSubGridPen() const { + return mRadialSubGridPen; + } + QPen radialZeroLinePen() const { + return mRadialZeroLinePen; + } + + // setters: + void setRadialAxis(QCPPolarAxisRadial *axis); + void setType(GridTypes type); + void setSubGridType(GridTypes type); + void setAntialiasedSubGrid(bool enabled); + void setAntialiasedZeroLine(bool enabled); + void setAngularPen(const QPen &pen); + void setAngularSubGridPen(const QPen &pen); + void setRadialPen(const QPen &pen); + void setRadialSubGridPen(const QPen &pen); + void setRadialZeroLinePen(const QPen &pen); + protected: - // property members: - GridTypes mType; - GridTypes mSubGridType; - bool mAntialiasedSubGrid, mAntialiasedZeroLine; - QPen mAngularPen, mAngularSubGridPen; - QPen mRadialPen, mRadialSubGridPen, mRadialZeroLinePen; - - // non-property members: - QCPPolarAxisAngular *mParentAxis; - QPointer mRadialAxis; - - // reimplemented virtual methods: - virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const Q_DECL_OVERRIDE; - virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; - - // non-virtual methods: - void drawRadialGrid(QCPPainter *painter, const QPointF ¢er, const QVector &coords, const QPen &pen, const QPen &zeroPen=Qt::NoPen); - void drawAngularGrid(QCPPainter *painter, const QPointF ¢er, double radius, const QVector &ticksCosSin, const QPen &pen); - + // property members: + GridTypes mType; + GridTypes mSubGridType; + bool mAntialiasedSubGrid, mAntialiasedZeroLine; + QPen mAngularPen, mAngularSubGridPen; + QPen mRadialPen, mRadialSubGridPen, mRadialZeroLinePen; + + // non-property members: + QCPPolarAxisAngular *mParentAxis; + QPointer mRadialAxis; + + // reimplemented virtual methods: + virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const Q_DECL_OVERRIDE; + virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; + + // non-virtual methods: + void drawRadialGrid(QCPPainter *painter, const QPointF ¢er, const QVector &coords, const QPen &pen, const QPen &zeroPen = Qt::NoPen); + void drawAngularGrid(QCPPainter *painter, const QPointF ¢er, double radius, const QVector &ticksCosSin, const QPen &pen); + private: - Q_DISABLE_COPY(QCPPolarGrid) - + Q_DISABLE_COPY(QCPPolarGrid) + }; Q_DECLARE_OPERATORS_FOR_FLAGS(QCPPolarGrid::GridTypes) @@ -7559,160 +8622,191 @@ Q_DECLARE_METATYPE(QCPPolarGrid::GridType) class QCP_LIB_DECL QCPPolarLegendItem : public QCPAbstractLegendItem { - Q_OBJECT -public: - QCPPolarLegendItem(QCPLegend *parent, QCPPolarGraph *graph); - - // getters: - QCPPolarGraph *polarGraph() { return mPolarGraph; } - + Q_OBJECT +public: QCPPolarLegendItem(QCPLegend *parent, QCPPolarGraph *graph); + + // getters: + QCPPolarGraph *polarGraph() { + return mPolarGraph; + } + protected: - // property members: - QCPPolarGraph *mPolarGraph; - - // reimplemented virtual methods: - virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; - virtual QSize minimumOuterSizeHint() const Q_DECL_OVERRIDE; - - // non-virtual methods: - QPen getIconBorderPen() const; - QColor getTextColor() const; - QFont getFont() const; + // property members: + QCPPolarGraph *mPolarGraph; + + // reimplemented virtual methods: + virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE; + virtual QSize minimumOuterSizeHint() const Q_DECL_OVERRIDE; + + // non-virtual methods: + QPen getIconBorderPen() const; + QColor getTextColor() const; + QFont getFont() const; }; class QCP_LIB_DECL QCPPolarGraph : public QCPLayerable { - Q_OBJECT - /// \cond INCLUDE_QPROPERTIES - - /// \endcond -public: - /*! - Defines how the graph's line is represented visually in the plot. The line is drawn with the - current pen of the graph (\ref setPen). - \see setLineStyle - */ - enum LineStyle { lsNone ///< data points are not connected with any lines (e.g. data only represented - ///< with symbols according to the scatter style, see \ref setScatterStyle) - ,lsLine ///< data points are connected by a straight line - }; - Q_ENUMS(LineStyle) - - QCPPolarGraph(QCPPolarAxisAngular *keyAxis, QCPPolarAxisRadial *valueAxis); - virtual ~QCPPolarGraph(); - - // getters: - QString name() const { return mName; } - bool antialiasedFill() const { return mAntialiasedFill; } - bool antialiasedScatters() const { return mAntialiasedScatters; } - QPen pen() const { return mPen; } - QBrush brush() const { return mBrush; } - bool periodic() const { return mPeriodic; } - QCPPolarAxisAngular *keyAxis() const { return mKeyAxis.data(); } - QCPPolarAxisRadial *valueAxis() const { return mValueAxis.data(); } - QCP::SelectionType selectable() const { return mSelectable; } - bool selected() const { return !mSelection.isEmpty(); } - QCPDataSelection selection() const { return mSelection; } - //QCPSelectionDecorator *selectionDecorator() const { return mSelectionDecorator; } - QSharedPointer data() const { return mDataContainer; } - LineStyle lineStyle() const { return mLineStyle; } - QCPScatterStyle scatterStyle() const { return mScatterStyle; } - - // setters: - void setName(const QString &name); - void setAntialiasedFill(bool enabled); - void setAntialiasedScatters(bool enabled); - void setPen(const QPen &pen); - void setBrush(const QBrush &brush); - void setPeriodic(bool enabled); - void setKeyAxis(QCPPolarAxisAngular *axis); - void setValueAxis(QCPPolarAxisRadial *axis); - Q_SLOT void setSelectable(QCP::SelectionType selectable); - Q_SLOT void setSelection(QCPDataSelection selection); - //void setSelectionDecorator(QCPSelectionDecorator *decorator); - void setData(QSharedPointer data); - void setData(const QVector &keys, const QVector &values, bool alreadySorted=false); - void setLineStyle(LineStyle ls); - void setScatterStyle(const QCPScatterStyle &style); + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + + /// \endcond +public: + /*! + Defines how the graph's line is represented visually in the plot. The line is drawn with the + current pen of the graph (\ref setPen). + \see setLineStyle + */ + enum LineStyle { lsNone ///< data points are not connected with any lines (e.g. data only represented + ///< with symbols according to the scatter style, see \ref setScatterStyle) + , lsLine ///< data points are connected by a straight line + }; + Q_ENUMS(LineStyle) + + QCPPolarGraph(QCPPolarAxisAngular *keyAxis, QCPPolarAxisRadial *valueAxis); + virtual ~QCPPolarGraph(); + + // getters: + QString name() const { + return mName; + } + bool antialiasedFill() const { + return mAntialiasedFill; + } + bool antialiasedScatters() const { + return mAntialiasedScatters; + } + QPen pen() const { + return mPen; + } + QBrush brush() const { + return mBrush; + } + bool periodic() const { + return mPeriodic; + } + QCPPolarAxisAngular *keyAxis() const { + return mKeyAxis.data(); + } + QCPPolarAxisRadial *valueAxis() const { + return mValueAxis.data(); + } + QCP::SelectionType selectable() const { + return mSelectable; + } + bool selected() const { + return !mSelection.isEmpty(); + } + QCPDataSelection selection() const { + return mSelection; + } + //QCPSelectionDecorator *selectionDecorator() const { return mSelectionDecorator; } + QSharedPointer data() const { + return mDataContainer; + } + LineStyle lineStyle() const { + return mLineStyle; + } + QCPScatterStyle scatterStyle() const { + return mScatterStyle; + } + + // setters: + void setName(const QString &name); + void setAntialiasedFill(bool enabled); + void setAntialiasedScatters(bool enabled); + void setPen(const QPen &pen); + void setBrush(const QBrush &brush); + void setPeriodic(bool enabled); + void setKeyAxis(QCPPolarAxisAngular *axis); + void setValueAxis(QCPPolarAxisRadial *axis); + Q_SLOT void setSelectable(QCP::SelectionType selectable); + Q_SLOT void setSelection(QCPDataSelection selection); + //void setSelectionDecorator(QCPSelectionDecorator *decorator); + void setData(QSharedPointer data); + void setData(const QVector &keys, const QVector &values, bool alreadySorted = false); + void setLineStyle(LineStyle ls); + void setScatterStyle(const QCPScatterStyle &style); + + // non-property methods: + void addData(const QVector &keys, const QVector &values, bool alreadySorted = false); + void addData(double key, double value); + 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; + 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; + + // introduced virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details = 0) const; // actually introduced in QCPLayerable as non-pure, but we want to force reimplementation for plottables + virtual QCPPlottableInterface1D *interface1D() { + return 0; // TODO: return this later, when QCPAbstractPolarPlottable is created + } + virtual QCPRange getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain = QCP::sdBoth) const; + virtual QCPRange getValueRange(bool &foundRange, QCP::SignDomain inSignDomain = QCP::sdBoth, const QCPRange &inKeyRange = QCPRange()) const; - // non-property methods: - void addData(const QVector &keys, const QVector &values, bool alreadySorted=false); - void addData(double key, double value); - 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; - 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; - - // introduced virtual methods: - virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; // actually introduced in QCPLayerable as non-pure, but we want to force reimplementation for plottables - virtual QCPPlottableInterface1D *interface1D() { return 0; } // TODO: return this later, when QCPAbstractPolarPlottable is created - virtual QCPRange getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain=QCP::sdBoth) const; - virtual QCPRange getValueRange(bool &foundRange, QCP::SignDomain inSignDomain=QCP::sdBoth, const QCPRange &inKeyRange=QCPRange()) const; - signals: - void selectionChanged(bool selected); - void selectionChanged(const QCPDataSelection &selection); - void selectableChanged(QCP::SelectionType selectable); - + void selectionChanged(bool selected); + void selectionChanged(const QCPDataSelection &selection); + void selectableChanged(QCP::SelectionType selectable); + protected: - // property members: - QSharedPointer mDataContainer; - LineStyle mLineStyle; - QCPScatterStyle mScatterStyle; - QString mName; - bool mAntialiasedFill, mAntialiasedScatters; - QPen mPen; - QBrush mBrush; - bool mPeriodic; - QPointer mKeyAxis; - QPointer mValueAxis; - QCP::SelectionType mSelectable; - QCPDataSelection mSelection; - //QCPSelectionDecorator *mSelectionDecorator; - - // introduced virtual methods (later reimplemented TODO from QCPAbstractPolarPlottable): - virtual QRect clipRect() const; - virtual void draw(QCPPainter *painter); - 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); - // virtual drawing helpers: - virtual void drawLinePlot(QCPPainter *painter, const QVector &lines) const; - virtual void drawFill(QCPPainter *painter, QVector *lines) const; - virtual void drawScatterPlot(QCPPainter *painter, const QVector &scatters, const QCPScatterStyle &style) const; - - // introduced virtual methods: - virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const; - - // non-virtual methods: - void applyFillAntialiasingHint(QCPPainter *painter) const; - void applyScattersAntialiasingHint(QCPPainter *painter) const; - double pointDistance(const QPointF &pixelPoint, QCPGraphDataContainer::const_iterator &closestData) const; - // drawing helpers: - virtual int dataCount() const; - void getDataSegments(QList &selectedSegments, QList &unselectedSegments) const; - void drawPolyline(QCPPainter *painter, const 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; - void getOptimizedLineData(QVector *lineData, const QCPGraphDataContainer::const_iterator &begin, const QCPGraphDataContainer::const_iterator &end) const; - void getOptimizedScatterData(QVector *scatterData, QCPGraphDataContainer::const_iterator begin, QCPGraphDataContainer::const_iterator end) const; - QVector dataToLines(const QVector &data) const; + // property members: + QSharedPointer mDataContainer; + LineStyle mLineStyle; + QCPScatterStyle mScatterStyle; + QString mName; + bool mAntialiasedFill, mAntialiasedScatters; + QPen mPen; + QBrush mBrush; + bool mPeriodic; + QPointer mKeyAxis; + QPointer mValueAxis; + QCP::SelectionType mSelectable; + QCPDataSelection mSelection; + //QCPSelectionDecorator *mSelectionDecorator; + + // introduced virtual methods (later reimplemented TODO from QCPAbstractPolarPlottable): + virtual QRect clipRect() const; + virtual void draw(QCPPainter *painter); + 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); + // virtual drawing helpers: + virtual void drawLinePlot(QCPPainter *painter, const QVector &lines) const; + virtual void drawFill(QCPPainter *painter, QVector *lines) const; + virtual void drawScatterPlot(QCPPainter *painter, const QVector &scatters, const QCPScatterStyle &style) const; + + // introduced virtual methods: + virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const; + + // non-virtual methods: + void applyFillAntialiasingHint(QCPPainter *painter) const; + void applyScattersAntialiasingHint(QCPPainter *painter) const; + double pointDistance(const QPointF &pixelPoint, QCPGraphDataContainer::const_iterator &closestData) const; + // drawing helpers: + virtual int dataCount() const; + void getDataSegments(QList &selectedSegments, QList &unselectedSegments) const; + void drawPolyline(QCPPainter *painter, const 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; + void getOptimizedLineData(QVector *lineData, const QCPGraphDataContainer::const_iterator &begin, const QCPGraphDataContainer::const_iterator &end) const; + void getOptimizedScatterData(QVector *scatterData, QCPGraphDataContainer::const_iterator begin, QCPGraphDataContainer::const_iterator end) const; + QVector dataToLines(const QVector &data) const; private: - Q_DISABLE_COPY(QCPPolarGraph) - - friend class QCPPolarLegendItem; + Q_DISABLE_COPY(QCPPolarGraph) + + friend class QCPPolarLegendItem; }; /* end of 'src/polar/polargraph.h' */