Qwt之Plot

来源:互联网 发布:再见老婆啥软件 编辑:程序博客网 时间:2024/05/19 20:42

Qwt之Plot

确实有一些朋友需要使用Qwt,其实Qwt用起来还算简单,Plot的使用算是入门级别,官方也提供了很好的示例代码,但是一些朋友往往忽略了官方示例或者不知道在哪里能得到示例代码,因此给出我的一小段程序以便网友查阅,也算为《Qwt之QwtPlotPicker及其扩展》中的plotpickerbytime类的使用给出一个示例。
程序很简单,不做过多注释了,只是做了一个Graph类,使用Plot和绑定PlotPicker方法如下:

/** * @file graph.h */#ifndef GRAPH_H#define GRAPH_H#include <qwt_plot.h>#include <qwt_plot_grid.h>#include <qwt_plot_zoomer.h>#include <qwt_plot_magnifier.h>#include <qwt_date_scale_draw.h>#include <QObject>#include "graphcurve.h"#include "plotpickerbytime.h"   // 该类具体实现见博文《Qwt之QwtPlotPicker及其扩展》http://blog.csdn.net/desert187/article/details/12848305class Graph : public QObject{    Q_OBJECTpublic:    Graph();    ~Graph();private:    QwtPlot *plot;    QwtPlotGrid *grid;    GraphCurve *curve;    QwtPlotZoomer* zoomer;    QwtPlotMagnifier *magnifier;    QwtDateScaleDraw *timeScale;    PlotPickerByTime *picker;signals:    void addPoint(QPointF point);private slots:    void on_add_point(QPointF point);};#endif // GRAPH_H
/** * @file graph.cpp */#include "graph.h"#include <qwt_plot_panner.h>#include <qwt_plot_canvas.h>#include <qwt_legend.h>#include <qwt_scale_engine.h>#include "plotpickerbytime.h"   Graph::Graph(){    plot = new QwtPlot();    plot->setTitle( "Info" );    plot->setCanvasBackground( Qt::white );    plot->setAxisScale( QwtPlot::yLeft, 0.0, 10.0 );    plot->setAxisScale( QwtPlot::xBottom, 0.0, 60.0, 60.0 );    plot->setAxisAutoScale(QwtPlot::yLeft, true);    plot->setAxisAutoScale(QwtPlot::xBottom, true);    timeScale = new QwtDateScaleDraw(Qt::LocalTime);    QString *scaleFormat;    scaleFormat = new QString("Sec ss:zzz");    timeScale->setDateFormat(QwtDate::Millisecond, *scaleFormat);    delete scaleFormat;    scaleFormat = new QString("hh:mm:ss\nyy-MM-dd");    timeScale->setDateFormat(QwtDate::Second, *scaleFormat);    delete scaleFormat;    scaleFormat = new QString("hh:mm\nyy-MM-dd");    timeScale->setDateFormat(QwtDate::Minute, *scaleFormat);    delete scaleFormat;    scaleFormat = new QString("hh:mm\nyy-MM-dd");    timeScale->setDateFormat(QwtDate::Hour, *scaleFormat);    delete scaleFormat;    scaleFormat = new QString("hh:mm\nyy-MM-dd");    timeScale->setDateFormat(QwtDate::Day, *scaleFormat);    delete scaleFormat;    scaleFormat = new QString("yyyy-MM-dd");    timeScale->setDateFormat(QwtDate::Month, *scaleFormat);    delete scaleFormat;    scaleFormat = new QString("yyyy-MM");    timeScale->setDateFormat(QwtDate::Year, *scaleFormat);    delete scaleFormat;    plot->setAxisScaleDraw(QwtPlot::xBottom, timeScale);    plot->insertLegend( new QwtLegend() );    plot->setAutoReplot(false);    grid = new QwtPlotGrid();    grid->attach( plot );    curve = new GraphCurve();    AddCurve(curve);    picker = new PlotPickerByTime(plot->canvas());    picker->setTrackerMode(PlotPickerByTime::AlwaysOn);    picker->setTrackerPen(QColor( Qt::magenta ));    // LeftButton for the zooming    // MidButton for the panning    // RightButton: zoom out by 1    // Ctrl+RighButton: zoom out to full size    zoomer = new QwtPlotZoomer( plot->canvas() );    zoomer->setRubberBandPen( QColor( Qt::darkCyan ) );    zoomer->setMousePattern( QwtEventPattern::MouseSelect2, Qt::RightButton, Qt::ControlModifier );    zoomer->setMousePattern( QwtEventPattern::MouseSelect1, Qt::RightButton );    zoomer->setTrackerMode(QwtPlotPicker::AlwaysOff);    plot->resize( 800, 600 );    // panning with the left mouse button    ( void ) new QwtPlotPanner( plot->canvas() );    // zoom in/out with the wheel    magnifier = new QwtPlotMagnifier( plot->canvas() );    magnifier->setMouseButton(Qt::LeftButton, Qt::ControlModifier);    connect(this, SIGNAL(addPoint(QPointF)), this, SLOT(on_add_point(QPointF)));    plot->show();}Graph::~Graph(){    delete magnifier;    delete zoomer;    delete picker;    delete curve;    delete grid;    delete plot;}void Graph::on_add_point(QPointF point){    curve->AddPoint(point);    plot->replot();}void Graph::AddCurvePoint(QPointF point){    curve->AddPoint(point);    plot->replot();}
/** * @file plotpickerbytime.h */#ifndef PLOTPICKERBYTIME_H#define PLOTPICKERBYTIME_H#include <qwt_global.h>#include <qwt_picker.h>#include <qvector.h>#include <qwt_date.h>class QwtPlot;/*!  \brief QwtPlotPicker provides selections on a plot canvas  QwtPlotPicker is a QwtPicker tailored for selections on  a plot canvas. It is set to a x-Axis and y-Axis and  translates all pixel coordinates into this coordinate system.*/class QWT_EXPORT PlotPickerByTime: public QwtPicker{    Q_OBJECTpublic:    explicit PlotPickerByTime(QWidget *canvas);    virtual ~PlotPickerByTime();    explicit PlotPickerByTime( int xAxis, int yAxis, QWidget * );    explicit PlotPickerByTime( int xAxis, int yAxis,        RubberBand rubberBand, DisplayMode trackerMode, QWidget * );    virtual void setAxis( int xAxis, int yAxis );    int xAxis() const;    int yAxis() const;    QwtPlot *plot();    const QwtPlot *plot() const;    QWidget *canvas();    const QWidget *canvas() const;Q_SIGNALS:    /*!      A signal emitted in case of QwtPickerMachine::PointSelection.      \param pos Selected point    */    void selected( const QPointF &pos );    /*!      A signal emitted in case of QwtPickerMachine::RectSelection.      \param rect Selected rectangle    */    void selected( const QRectF &rect );    /*!      A signal emitting the selected points,      at the end of a selection.      \param pa Selected points    */    void selected( const QVector<QPointF> &pa );    /*!      A signal emitted when a point has been appended to the selection      \param pos Position of the appended point.      \sa append(). moved()    */    void appended( const QPointF &pos );    /*!      A signal emitted whenever the last appended point of the      selection has been moved.      \param pos Position of the moved last point of the selection.      \sa move(), appended()    */    void moved( const QPointF &pos );protected:    QRectF scaleRect() const;    QRectF invTransform( const QRect & ) const;    QRect transform( const QRectF & ) const;    QPointF invTransform( const QPoint & ) const;    QPoint transform( const QPointF & ) const;    virtual QwtText trackerText( const QPoint & ) const;    virtual QwtText trackerTextF( const QPointF & ) const;    QDateTime toDateTime( double ) const;    virtual void move( const QPoint & );    virtual void append( const QPoint & );    virtual bool end( bool ok = true );private:    int d_xAxis;    int d_yAxis;};#endif // PLOTPICKERBYTIME_H
/** * @file plotpickerbytime.cpp */#include "plotpickerbytime.h"#include <qwt_plot.h>#include <qwt_scale_div.h>#include <qwt_painter.h>#include <qwt_scale_map.h>#include <qwt_picker_machine.h>/*!  \brief Create a plot picker  The picker is set to those x- and y-axis of the plot  that are enabled. If both or no x-axis are enabled, the picker  is set to QwtPlot::xBottom. If both or no y-axis are  enabled, it is set to QwtPlot::yLeft.  \param canvas Plot canvas to observe, also the parent object  \sa QwtPlot::autoReplot(), QwtPlot::replot(), scaleRect()*/PlotPickerByTime::PlotPickerByTime(QWidget *canvas)    :      QwtPicker( canvas ),      d_xAxis( -1 ),      d_yAxis( -1 ){    if ( !canvas )        return;    int xAxis = QwtPlot::xBottom;    const QwtPlot *plot = PlotPickerByTime::plot();    if ( !plot->axisEnabled( QwtPlot::xBottom ) &&         plot->axisEnabled( QwtPlot::xTop ) )    {        xAxis = QwtPlot::xTop;    }    int yAxis = QwtPlot::yLeft;    if ( !plot->axisEnabled( QwtPlot::yLeft ) &&         plot->axisEnabled( QwtPlot::yRight ) )    {        yAxis = QwtPlot::yRight;    }    setAxis( xAxis, yAxis );}/*!  Create a plot picker  \param xAxis Set the x axis of the picker  \param yAxis Set the y axis of the picker  \param canvas Plot canvas to observe, also the parent object  \sa QwtPlot::autoReplot(), QwtPlot::replot(), scaleRect()*/PlotPickerByTime::PlotPickerByTime( int xAxis, int yAxis, QWidget *canvas ):    QwtPicker( canvas ),    d_xAxis( xAxis ),    d_yAxis( yAxis ){}/*!  Create a plot picker  \param xAxis X axis of the picker  \param yAxis Y axis of the picker  \param rubberBand Rubber band style  \param trackerMode Tracker mode  \param canvas Plot canvas to observe, also the parent object  \sa QwtPicker, QwtPicker::setSelectionFlags(), QwtPicker::setRubberBand(),      QwtPicker::setTrackerMode  \sa QwtPlot::autoReplot(), QwtPlot::replot(), scaleRect()*/PlotPickerByTime::PlotPickerByTime( int xAxis, int yAxis,                                    RubberBand rubberBand, DisplayMode trackerMode,                                    QWidget *canvas ):    QwtPicker( rubberBand, trackerMode, canvas ),    d_xAxis( xAxis ),    d_yAxis( yAxis ){}//! DestructorPlotPickerByTime::~PlotPickerByTime(){}//! \return Observed plot canvasQWidget *PlotPickerByTime::canvas(){    return parentWidget();}//! \return Observed plot canvasconst QWidget *PlotPickerByTime::canvas() const{    return parentWidget();}//! \return Plot widget, containing the observed plot canvasQwtPlot *PlotPickerByTime::plot(){    QWidget *w = canvas();    if ( w )        w = w->parentWidget();    return qobject_cast<QwtPlot *>( w );}//! \return Plot widget, containing the observed plot canvasconst QwtPlot *PlotPickerByTime::plot() const{    const QWidget *w = canvas();    if ( w )        w = w->parentWidget();    return qobject_cast<const QwtPlot *>( w );}/*!  \return Normalized bounding rectangle of the axes  \sa QwtPlot::autoReplot(), QwtPlot::replot().*/QRectF PlotPickerByTime::scaleRect() const{    QRectF rect;    if ( plot() )    {        const QwtScaleDiv &xs = plot()->axisScaleDiv( xAxis() );        const QwtScaleDiv &ys = plot()->axisScaleDiv( yAxis() );        rect = QRectF( xs.lowerBound(), ys.lowerBound(),                       xs.range(), ys.range() );        rect = rect.normalized();    }    return rect;}/*!  Set the x and y axes of the picker  \param xAxis X axis  \param yAxis Y axis*/void PlotPickerByTime::setAxis( int xAxis, int yAxis ){    const QwtPlot *plt = plot();    if ( !plt )        return;    if ( xAxis != d_xAxis || yAxis != d_yAxis )    {        d_xAxis = xAxis;        d_yAxis = yAxis;    }}//! Return x axisint PlotPickerByTime::xAxis() const{    return d_xAxis;}//! Return y axisint PlotPickerByTime::yAxis() const{    return d_yAxis;}/*!  Translate a pixel position into a position string  \param pos Position in pixel coordinates  \return Position string*/QwtText PlotPickerByTime::trackerText( const QPoint &pos ) const{    return trackerTextF( invTransform( pos ) );}/*!  \brief Translate a position into a position string  In case of HLineRubberBand the label is the value of the  y position, in case of VLineRubberBand the value of the x position.  Otherwise the label contains x and y position separated by a ',' .  The format for the double to string conversion is "%.4f".  \param pos Position  \return Position string*/QwtText PlotPickerByTime::trackerTextF( const QPointF &pos ) const{    QString text;    QDateTime time = toDateTime(double(pos.x()));    switch ( rubberBand() )    {    case HLineRubberBand:        text.sprintf( "%.4f", pos.y() );        break;    case VLineRubberBand:        text.sprintf( "%.4f", pos.x() );        break;    default:        text.append(QString::number(pos.y(),'f',2));        text.append('('+time.toString("yyyy-MM-dd HH:mm:ss:zzz")+')');    }    return QwtText( text );}QDateTime PlotPickerByTime::toDateTime( double value ) const{    QDateTime dt = QwtDate::toDateTime( value, Qt::LocalTime );    if ( !dt.isValid() )    {        const QDate date = ( value <= 0.0 )                ? QwtDate::minDate() : QwtDate::maxDate();        dt = QDateTime( date, QTime( 0, 0 ), Qt::LocalTime );    }    return dt;}/*!  Append a point to the selection and update rubber band and tracker.  \param pos Additional point  \sa isActive, begin(), end(), move(), appended()  \note The appended(const QPoint &), appended(const QDoublePoint &)        signals are emitted.*/void PlotPickerByTime::append( const QPoint &pos ){    QwtPicker::append( pos );    Q_EMIT appended( invTransform( pos ) );}/*!  Move the last point of the selection  \param pos New position  \sa isActive, begin(), end(), append()  \note The moved(const QPoint &), moved(const QDoublePoint &)        signals are emitted.*/void PlotPickerByTime::move( const QPoint &pos ){    QwtPicker::move( pos );    Q_EMIT moved( invTransform( pos ) );}/*!  Close a selection setting the state to inactive.  \param ok If true, complete the selection and emit selected signals            otherwise discard the selection.  \return True if the selection has been accepted, false otherwise*/bool PlotPickerByTime::end( bool ok ){    ok = QwtPicker::end( ok );    if ( !ok )        return false;    QwtPlot *plot = PlotPickerByTime::plot();    if ( !plot )        return false;    const QPolygon points = selection();    if ( points.count() == 0 )        return false;    QwtPickerMachine::SelectionType selectionType =            QwtPickerMachine::NoSelection;    if ( stateMachine() )        selectionType = stateMachine()->selectionType();    switch ( selectionType )    {    case QwtPickerMachine::PointSelection:    {        const QPointF pos = invTransform( points.first() );         Q_EMIT selected( pos );        break;    }    case QwtPickerMachine::RectSelection:    {        if ( points.count() >= 2 )        {            const QPoint p1 = points.first();            const QPoint p2 = points.last();            const QRect rect = QRect( p1, p2 ).normalized();            Q_EMIT selected( invTransform( rect ) );        }        break;    }    case QwtPickerMachine::PolygonSelection:    {        QVector<QPointF> dpa( points.count() );        for ( int i = 0; i < points.count(); i++ )            dpa[i] = invTransform( points[i] );        Q_EMIT selected( dpa );    }    default:        break;    }    return true;}/*!    Translate a rectangle from pixel into plot coordinates    \return Rectangle in plot coordinates    \sa transform()*/QRectF PlotPickerByTime::invTransform( const QRect &rect ) const{    const QwtScaleMap xMap = plot()->canvasMap( d_xAxis );    const QwtScaleMap yMap = plot()->canvasMap( d_yAxis );    return QwtScaleMap::invTransform( xMap, yMap, rect );}/*!    Translate a rectangle from plot into pixel coordinates    \return Rectangle in pixel coordinates    \sa invTransform()*/QRect PlotPickerByTime::transform( const QRectF &rect ) const{    const QwtScaleMap xMap = plot()->canvasMap( d_xAxis );    const QwtScaleMap yMap = plot()->canvasMap( d_yAxis );    return QwtScaleMap::transform( xMap, yMap, rect ).toRect();}/*!    Translate a point from pixel into plot coordinates    \return Point in plot coordinates    \sa transform()*/QPointF PlotPickerByTime::invTransform( const QPoint &pos ) const{    QwtScaleMap xMap = plot()->canvasMap( d_xAxis );    QwtScaleMap yMap = plot()->canvasMap( d_yAxis );    return QPointF(                xMap.invTransform( pos.x() ),                yMap.invTransform( pos.y() )                );}/*!    Translate a point from plot into pixel coordinates    \return Point in pixel coordinates    \sa invTransform()*/QPoint PlotPickerByTime::transform( const QPointF &pos ) const{    QwtScaleMap xMap = plot()->canvasMap( d_xAxis );    QwtScaleMap yMap = plot()->canvasMap( d_yAxis );    const QPointF p( xMap.transform( pos.x() ),                     yMap.transform( pos.y() ) );    return p.toPoint();}
/** * @file graphcurve.h */#ifndef GRAPHCURVE_H#define GRAPHCURVE_H#include <qwt_plot_curve.h>#include <qwt_symbol.h>class GraphCurve : public QwtPlotCurve{public:    GraphCurve();    ~GraphCurve();    void AddPoint(QPointF point);private:    QPolygonF points;};#endif // GRAPHCURVE_H
/** * @file graphcurve.cpp */ #include "graphcurve.h"GraphCurve::GraphCurve(){    this->setTitle( "Some Points" );    this->setPen( Qt::blue, 2 );    this->setRenderHint( QwtPlotItem::RenderAntialiased, true );}GraphCurve::~GraphCurve(){    ;}void GraphCurve::AddPoint(QPointF point){    points << point;    setSamples( points );}
0 0
原创粉丝点击