Esempio n. 1
0
void LineDialog::apply()
{
    if (tw->currentPage()==dynamic_cast<QWidget *>(options)){
        lm->setStyle(Graph::getPenStyle(styleBox->currentItem()));
        lm->setColor(colorBox->color());
        lm->setWidth(widthBox->value());
        lm->drawEndArrow(endBox->isChecked());
        lm->drawStartArrow(startBox->isChecked());
  } else if (tw->currentPage()==dynamic_cast<QWidget *>(head)){
        if (lm->headLength() != boxHeadLength->value())
            lm->setHeadLength( boxHeadLength->value() );

        if (lm->headAngle() != boxHeadAngle->value())
            lm->setHeadAngle( boxHeadAngle->value() );

        if (lm->filledArrowHead() != filledBox->isChecked())
            lm->fillArrowHead( filledBox->isChecked() );
  } else if (tw->currentPage()==dynamic_cast<QWidget *>(geometry))
        setCoordinates(unitBox->currentItem());

	QwtPlot *plot = lm->plot();
  Graph *g = dynamic_cast<Graph *>(plot->parent());
	plot->replot();
	g->notifyChanges();

	enableHeadTab();
}
/*! 
   Zoom in/out the axes scales
   \param factor A value < 1.0 zooms in, a value > 1.0 zooms out.
*/
void QwtPlotMagnifier::rescale(double factor)
{
    factor = qwtAbs(factor);
    if ( factor == 1.0 || factor == 0.0 )
        return;

    bool doReplot = false;
    QwtPlot* plt = plot();

    const bool autoReplot = plt->autoReplot();
    plt->setAutoReplot(false);

    for ( int axisId = 0; axisId < QwtPlot::axisCnt; axisId++ )
    {
        const QwtScaleDiv *scaleDiv = plt->axisScaleDiv(axisId);
        if ( isAxisEnabled(axisId) && scaleDiv->isValid() )
        {
            const double center =
                scaleDiv->lowerBound() + scaleDiv->range() / 2;
            const double width_2 = scaleDiv->range() / 2 * factor;

            plt->setAxisScale(axisId, center - width_2, center + width_2);
            doReplot = true;
        }
    }

    plt->setAutoReplot(autoReplot);

    if ( doReplot )
        plt->replot();
}
Esempio n. 3
0
void MultiLayer::setFonts(const QFont &titleFnt, const QFont &scaleFnt,
                          const QFont &numbersFnt, const QFont &legendFnt) {
  for (int i = 0; i < (int)graphsList.count(); i++) {
    Graph *gr = (Graph *)graphsList.at(i);
    QwtPlot *plot = gr->plotWidget();

    QwtText text = plot->title();
    text.setFont(titleFnt);
    plot->setTitle(text);
    for (int j = 0; j < QwtPlot::axisCnt; j++) {
      plot->setAxisFont(j, numbersFnt);

      text = plot->axisTitle(j);
      text.setFont(scaleFnt);
      plot->setAxisTitle(j, text);
    }

    QVector<int> keys = gr->textMarkerKeys();
    for (int k = 0; k < (int)keys.size(); k++) {
      Legend *mrk = (Legend *)gr->textMarker(keys[k]);
      if (mrk) mrk->setFont(legendFnt);
    }
    plot->replot();
  }
  emit modifiedPlot();
}
Esempio n. 4
0
MyForm::MyForm(QWidget *parent) : QWidget(parent)
{
  setupUi(this);

  QwtPlot *myPlot = new QwtPlot(this);
  
  QwtPlotCurve *curve1 = new QwtPlotCurve("Curve 1");

  
  QwtPointSeriesData myData;
  QVector<QPointF> samples;
  samples.push_back(QPointF(1.0,1.0));
  samples.push_back(QPointF(2.0,2.0));
  samples.push_back(QPointF(3.0,3.0));
  samples.push_back(QPointF(4.0,5.0));
  myData.setSamples(samples);
  curve1->setData(&myData);
  
  
//   double x[4];
//   double y[4];
//   x[0] = 0; y[0] = 0;
//   x[1] = 1; y[1] = 1;
//   x[2] = 2; y[2] = 2;
//   x[3] = 3; y[3] = 4;
//   curve1->setRawSamples(x, y, 4);
  
  curve1->attach(myPlot);
  
  myPlot->replot();
}
void QwtPlotZoomer::rescale()
{
    QwtPlot *plt = plot();
    if ( !plt )
        return;

    const QRectF &rect = d_data->zoomStack[d_data->zoomRectIndex];
    if ( rect != scaleRect() )
    {
        const bool doReplot = plt->autoReplot();
        plt->setAutoReplot( false );

        double x1 = rect.left();
        double x2 = rect.right();
        if ( !plt->axisScaleDiv( xAxis() ).isIncreasing() )
            qSwap( x1, x2 );

        plt->setAxisScale( xAxis(), x1, x2 );

        double y1 = rect.top();
        double y2 = rect.bottom();
        if ( !plt->axisScaleDiv( yAxis() ).isIncreasing() )
            qSwap( y1, y2 );

        plt->setAxisScale( yAxis(), y1, y2 );

        plt->setAutoReplot( doReplot );

        plt->replot();
    }
}
Esempio n. 6
0
void Widget::refreshPlot()
{
    if(initializing)
        return;

    model->fill_data();  
    findChild<QLineEdit*>("fermiLevelLineEdit")->setText(QString::number(model->get_fermi_level_eV(), 'f', 6));
    update_plot_data();
    mainCurve->setSamples(plotData.xs, plotData.ys);

    double Ev = 0;
    double Ec = Ev + model->get_Eg_eV();

    double xmin = mainCurve->minXValue();
    double xmax = mainCurve->maxXValue();
    set_level(EvCurve, Ev, xmin, xmax);
    set_level(EcCurve, Ec, xmin, xmax);
    set_level(EaCurve, Ev + model->get_Ea_eV(), xmin, xmax);
    set_level(EdCurve, Ec - model->get_Ed_eV(), xmin, xmax);
    set_level(fermiLevelCurve, Ev + model->get_fermi_level_eV(), xmin, xmax);

    QwtPlot* plotArea = findChild<QwtPlot*>("plotArea");
    plotArea->setAxisTitle(QwtPlot::xBottom, xAxisTitle);
    plotArea->setAxisTitle(QwtPlot::yLeft, yAxisTitle);
    plotArea->replot();
}
Esempio n. 7
0
// Применение изменений по вращении колеса мыши
void QWheelZoomSvc::applyWheel(QEvent *event,bool ax,bool ay)
{
    // приводим тип QEvent к QWheelEvent
    QWheelEvent *wEvent = static_cast<QWheelEvent *>(event);
    // если вращается вертикальное колесо мыши
    if (wEvent->orientation() == Qt::Vertical)
    {
        // определяем угол поворота колеса мыши
        // (значение 120 соответствует углу поворота 15°)
        int wd = wEvent->delta();
        // вычисляем масштабирующий множитель
        // (во сколько раз будет увеличен/уменьшен график)
        double kw = sfact*wd/120;
        if (wd != 0)    // если колесо вращалось, то
        {
            // фиксируем исходные границы графика (если этого еще не было сделано)
            zoom->fixBounds();
            // получаем указатель на график
            QwtPlot *plt = zoom->plot();
            if (ax) // если задано масштабирование по горизонтали
            {
                // получаем карту основной горизонтальной шкалы
                QwtScaleMap sm = plt->canvasMap(zoom->masterH());
                // определяем центр отображаемого на шкале x интервала
                double mx = (sm.s1()+sm.s2())/2;
                // и полуширину интервала
                double dx = (sm.s2()-sm.s1())/2;
                // в зависимости от знака угла поворота колеса мыши
                // уменьшаем полуширину отображаемых интервалов в kw раз
                if (wd > 0) dx /= kw;
                // или увеличиваем полуширину отображаемых интервалов в -kw раз
                else dx *= -kw;
                // устанавливаем новые левую и правую границы шкалы для оси x
                // (центр изображаемой части графика остается на месте,
                // а границы удаляются от центра, т.о. изображение графика уменьшается)
                zoom->isb_x->set(mx-dx,mx+dx);
            }
            if (ay) // если задано масштабирование по вертикали
            {
                // получаем карту основной вертикальной шкалы
                QwtScaleMap sm = plt->canvasMap(zoom->masterV());
                // определяем центр отображаемого на шкале y интервала
                double my = (sm.s1()+sm.s2())/2;
                // и полуширину интервала
                double dy = (sm.s2()-sm.s1())/2;
                // в зависимости от знака угла поворота колеса мыши
                // уменьшаем полуширину отображаемых интервалов в kw раз
                if (wd > 0) dy /= kw;
                // увеличиваем полуширину отображаемых интервалов в -kw раз
                else dy *= -kw;
                // устанавливаем новые нижнюю и верхнюю границы вертикальной шкалы
                // (центр изображаемой части графика остается на месте,
                // а границы удаляются от центра, т.о. изображение графика уменьшается)
                zoom->isb_y->set(my-dy,my+dy);
            }
            // перестраиваем график (синхронно с остальными)
            plt->replot();
        }
    }
}
/*!
   Update the axes scales

   \param intervals Scale intervals
*/
void QwtPlotRescaler::updateScales(
    QwtInterval intervals[QwtPlot::axisCnt] ) const
{
    if ( d_data->inReplot >= 5 )
    {
        return;
    }

    QwtPlot *plt = const_cast<QwtPlot *>( plot() );

    const bool doReplot = plt->autoReplot();
    plt->setAutoReplot( false );

    for ( int axis = 0; axis < QwtPlot::axisCnt; axis++ )
    {
        if ( axis == referenceAxis() || aspectRatio( axis ) > 0.0 )
        {
            double v1 = intervals[axis].minValue();
            double v2 = intervals[axis].maxValue();

            if ( plt->axisScaleDiv( axis )->lowerBound() >
                plt->axisScaleDiv( axis )->upperBound() )
            {
                qSwap( v1, v2 );
            }

            if ( d_data->inReplot >= 1 )
            {
                d_data->axisData[axis].scaleDiv = *plt->axisScaleDiv( axis );
            }

            if ( d_data->inReplot >= 2 )
            {
                QList<double> ticks[QwtScaleDiv::NTickTypes];
                for ( int i = 0; i < QwtScaleDiv::NTickTypes; i++ )
                    ticks[i] = d_data->axisData[axis].scaleDiv.ticks( i );

                plt->setAxisScaleDiv( axis, QwtScaleDiv( v1, v2, ticks ) );
            }
            else
            {
                plt->setAxisScale( axis, v1, v2 );
            }
        }
    }

    const bool immediatePaint = 
        plt->canvas()->testPaintAttribute( QwtPlotCanvas::ImmediatePaint );
    plt->canvas()->setPaintAttribute( QwtPlotCanvas::ImmediatePaint, false );

    plt->setAutoReplot( doReplot );

    d_data->inReplot++;
    plt->replot();
    d_data->inReplot--;

    plt->canvas()->setPaintAttribute( 
        QwtPlotCanvas::ImmediatePaint, immediatePaint );
}
Esempio n. 9
0
void PlotMatrix::updateLayout()
{
    for ( int row = 0; row < numRows(); row++ )
    {
        for ( int col = 0; col < numColumns(); col++ )
        {
            QwtPlot *p = plot( row, col );
            if ( p )
            {
                bool showAxis[QwtPlot::axisCnt];
                showAxis[QwtPlot::xBottom] =
                    axisEnabled( QwtPlot::xBottom ) && row == numRows() - 1;
                showAxis[QwtPlot::xTop] =
                    axisEnabled( QwtPlot::xTop ) && row == 0;
                showAxis[QwtPlot::yLeft] =
                    axisEnabled( QwtPlot::yLeft ) && col == 0;
                showAxis[QwtPlot::yRight] =
                    axisEnabled( QwtPlot::yRight ) && col == numColumns() - 1;

                for ( int axis = 0; axis < QwtPlot::axisCnt; axis++ )
                {
                    if ( axis == QwtPlot::xBottom || axis == QwtPlot::xTop )
                        p->enableAxis( axis, showAxis[axis] );
                    else
                    {
                        p->enableAxis( axis, true );

                        QwtScaleDraw *sd = p->axisScaleDraw( axis );
                        sd->enableComponent(
                            QwtScaleDraw::Backbone, showAxis[axis] );
                        sd->enableComponent(
                            QwtScaleDraw::Ticks, showAxis[axis] );
                        sd->enableComponent(
                            QwtScaleDraw::Labels, showAxis[axis] );
                    }
                }
            }
        }
    }

    for ( int col = 0; col < numColumns(); col++ )
    {
        alignVAxes( col, QwtPlot::yLeft );
        alignVAxes( col, QwtPlot::yRight );
    }

    for ( int row = 0; row < numRows(); row++ )
    {
        for ( int col = 0; col < numColumns(); col++ )
        {
            QwtPlot *p = plot( row, col );
            if ( p )
                p->replot();
        }
    }
}
Esempio n. 10
0
void PlotMatrix::updateLayout()
{
    for ( int row = 0; row < numRows(); row++ )
    {
        for ( int col = 0; col < numColumns(); col++ )
        {
            QwtPlot *p = plotAt( row, col );
            if ( p )
            {
                bool showAxis[QwtPlot::axisCnt];
                showAxis[QwtPlot::xBottom] =
                    axisEnabled( QwtPlot::xBottom ) && row == numRows() - 1;
                showAxis[QwtPlot::xTop] =
                    axisEnabled( QwtPlot::xTop ) && row == 0;
                showAxis[QwtPlot::yLeft] =
                    axisEnabled( QwtPlot::yLeft ) && col == 0;
                showAxis[QwtPlot::yRight] =
                    axisEnabled( QwtPlot::yRight ) && col == numColumns() - 1;

                for ( int axis = 0; axis < QwtPlot::axisCnt; axis++ )
                {
                    enablePlotAxis( p, axis, showAxis[axis] );
                }
            }
        }
    }

    for ( int row = 0; row < numRows(); row++ )
    {
        alignAxes( row, QwtPlot::xTop );
        alignAxes( row, QwtPlot::xBottom );

        alignScaleBorder( row, QwtPlot::yLeft );
        alignScaleBorder( row, QwtPlot::yRight );
    }

    for ( int col = 0; col < numColumns(); col++ )
    {
        alignAxes( col, QwtPlot::yLeft );
        alignAxes( col, QwtPlot::yRight );

        alignScaleBorder( col, QwtPlot::xBottom );
        alignScaleBorder( col, QwtPlot::xTop );
    }

    for ( int row = 0; row < numRows(); row++ )
    {
        for ( int col = 0; col < numColumns(); col++ )
        {
            QwtPlot *p = plotAt( row, col );
            if ( p )
                p->replot();
        }
    }
}
/*!
   Update the axes scales 

   \param intervals Scale intervals
*/
void QwtPlotRescaler::updateScales(
    QwtDoubleInterval intervals[QwtPlot::axisCnt]) const
{
    if ( d_data->inReplot >= 5 )
    {
        return;
    }

    QwtPlot *plt = (QwtPlot *)plot();

    const bool doReplot = plt->autoReplot();
    plt->setAutoReplot(false);

    for ( int axis = 0; axis < QwtPlot::axisCnt; axis++ )
    {
        if ( axis == referenceAxis() || aspectRatio(axis) > 0.0 )
        {
            double v1 = intervals[axis].minValue();
            double v2 = intervals[axis].maxValue();

            if ( plt->axisScaleDiv(axis)->lowerBound() >
                plt->axisScaleDiv(axis)->upperBound() )
            {
                qSwap(v1, v2);
            }

            if ( d_data->inReplot >= 1 )
            {
                d_data->axisData[axis].scaleDiv = *plt->axisScaleDiv(axis);
            }

            if ( d_data->inReplot >= 2 )
            {
                QwtValueList ticks[QwtScaleDiv::NTickTypes];
                for ( int i = 0; i < QwtScaleDiv::NTickTypes; i++ )
                    ticks[i] = d_data->axisData[axis].scaleDiv.ticks(i);

                plt->setAxisScaleDiv(axis, QwtScaleDiv(v1, v2, ticks));
            }
            else
            {
                plt->setAxisScale(axis, v1, v2);
            }
        }
    }

    plt->setAutoReplot(doReplot);

    d_data->inReplot++;
    plt->replot();
    d_data->inReplot--;
}
Esempio n. 12
0
int main(int argc, char **argv)
{
    QApplication a(argc, argv);

    QwtPlot plot;
    plot.setCanvasBackground(QColor(Qt::white));
    plot.setTitle("Histogram");

    QwtPlotGrid *grid = new QwtPlotGrid;
    grid->enableXMin(true);
    grid->enableYMin(true);
    grid->setMajPen(QPen(Qt::black, 0, Qt::DotLine));
    grid->setMinPen(QPen(Qt::gray, 0 , Qt::DotLine));
    grid->attach(&plot);

    HistogramItem *histogram = new HistogramItem();
    histogram->setColor(Qt::darkCyan);

    const int numValues = 20;

    QwtArray<QwtDoubleInterval> intervals(numValues);
    QwtArray<double> values(numValues);

    double pos = 0.0;
    for ( int i = 0; i < (int)intervals.size(); i++ )
    {
        const int width = 5 + rand() % 15;
        const int value = rand() % 100;

        intervals[i] = QwtDoubleInterval(pos, pos + double(width));
        values[i] = value; 

        pos += width;
    }

    histogram->setData(QwtIntervalData(intervals, values));
    histogram->attach(&plot);

    plot.setAxisScale(QwtPlot::yLeft, 0.0, 100.0);
    plot.setAxisScale(QwtPlot::xBottom, 0.0, pos);
    plot.replot();

#if QT_VERSION < 0x040000
    a.setMainWidget(&plot);
#endif

    plot.resize(600,400);
    plot.show();

    return a.exec(); 
}
/*!
  Reinitialized the zoom stack with scaleRect() as base.

  \param doReplot Call QwtPlot::replot() for the attached plot before initializing
                  the zoomer with its scales. This might be necessary,
                  when the plot is in a state with pending scale changes.

  \sa zoomBase(), scaleRect() QwtPlot::autoReplot(), QwtPlot::replot().
*/
void QwtPlotZoomer::setZoomBase( bool doReplot )
{
    QwtPlot *plt = plot();
    if ( plt == NULL )
        return;

    if ( doReplot )
        plt->replot();

    d_data->zoomStack.clear();
    d_data->zoomStack.push( scaleRect() );
    d_data->zoomRectIndex = 0;

    rescale();
}
Esempio n. 14
0
int main( int argc, char **argv )
{
  //using HistogramItem = QwtPlotItem;
  using HistogramItem = QwtPlotHistogram;
  //using QwtIntervalData = QwtSeriesData<QwtIntervalSample>;

  QApplication a(argc, argv);
  QwtPlot plot;
  plot.setCanvasBackground(QColor(Qt::white));
  plot.setTitle("Histogram");
  QwtPlotGrid *grid = new QwtPlotGrid;
  grid->enableXMin(true);
  grid->enableYMin(true);

  grid->setMajorPen(QPen(Qt::black, 0, Qt::DotLine));
  grid->setMinorPen(QPen(Qt::gray, 0 , Qt::DotLine));
  grid->attach(&plot);
  HistogramItem *histogram = new HistogramItem;
  //histogram->setColor(Qt::darkCyan);
  const int numValues = 20;
  //QwtArray<QwtDoubleInterval> intervals(numValues);
  QwtArray<QwtIntervalSample> intervals(numValues);
  QwtArray<double> values(numValues);
  double pos = 0.0;
  for ( int i = 0; i < (int)intervals.size(); i++ )
  {
    //const int width = 5 + rand() % 15;
    const int value = rand() % 100;
    //intervals[i] = QwtDoubleInterval(pos, pos + double(width));
    intervals[i] = QwtIntervalSample(value, pos, pos + double(width));
    //values[i] = value;
    pos += width;
  }

  //histogram->setData(QwtIntervalData(intervals, values));
  histogram->setSamples(intervals);
  //histogram->setSamples(QwtIntervalData(intervals, values));
  //QwtIntervalData d;
  //histogram->setData(d);
  histogram->attach(&plot);
  plot.setAxisScale(QwtPlot::yLeft, 0.0, 100.0);
  plot.setAxisScale(QwtPlot::xBottom, 0.0, pos);
  plot.replot();
  plot.resize(600,400);
  plot.show();
  return a.exec();
}
Esempio n. 15
0
/*!
   Adjust the enabled axes according to dx/dy

   \param dx Pixel offset in x direction
   \param dy Pixel offset in y direction

   \sa QwtPanner::panned()
*/
void QwtPlotPanner::moveCanvas( int dx, int dy )
{
    if ( dx == 0 && dy == 0 )
        return;

    QwtPlot *plot = this->plot();
    if ( plot == NULL )
        return;

    const bool doAutoReplot = plot->autoReplot();
    plot->setAutoReplot( false );

    for ( int axisPos = 0; axisPos < QwtAxis::PosCount; axisPos++ )
    {
        const int axesCount = plot->axesCount( axisPos );
        for ( int i = 0; i < axesCount; i++ )
        {
            const QwtAxisId axisId( axisPos, i );

            if ( !isAxisEnabled( axisId ) )
                continue;

            const QwtScaleMap map = plot->canvasMap( axisId );

            const double p1 = map.transform( plot->axisScaleDiv( axisId ).lowerBound() );
            const double p2 = map.transform( plot->axisScaleDiv( axisId ).upperBound() );

            double d1, d2;
            if ( QwtAxis::isXAxis( axisPos ) )
            {
                d1 = map.invTransform( p1 - dx );
                d2 = map.invTransform( p2 - dx );
            }
            else
            {
                d1 = map.invTransform( p1 - dy );
                d2 = map.invTransform( p2 - dy );
            }

            plot->setAxisScale( axisId, d1, d2 );
        }
    }

    plot->setAutoReplot( doAutoReplot );
    plot->replot();
}
Esempio n. 16
0
void Spectrogram::updateData(Matrix *m)
{
if (!m)
	return;

QwtPlot *plot = this->plot();
if (!plot)
	return;

setData(MatrixData(m));
setLevelsNumber(levels());

QwtScaleWidget *colorAxis = plot->axisWidget(color_axis);
if (colorAxis)
	colorAxis->setColorMap(data().range(), colorMap());

plot->setAxisScale(color_axis, data().range().minValue(), data().range().maxValue());
plot->replot();
}
Esempio n. 17
0
/*!
   Adjust the enabled axes according to dx/dy

   \param dx Pixel offset in x direction
   \param dy Pixel offset in y direction

   \sa QwtPanner::panned()
*/
void QwtPlotPanner::moveCanvas(int dx, int dy)
{
    if ( dx == 0 && dy == 0 )
        return;

    QwtPlot *plot = QwtPlotPanner::plot();
    if ( plot == NULL )
        return;
    
    const bool doAutoReplot = plot->autoReplot();
    plot->setAutoReplot(false);

    for ( int axis = 0; axis < QwtPlot::axisCnt; axis++ )
    {
        if ( !d_data->isAxisEnabled[axis] )
            continue;

        const QwtScaleMap map = plot->canvasMap(axis);

        const int i1 = map.transform(plot->axisScaleDiv(axis)->lowerBound());
        const int i2 = map.transform(plot->axisScaleDiv(axis)->upperBound());

        double d1, d2;
        if ( axis == QwtPlot::xBottom || axis == QwtPlot::xTop )
        {
            d1 = map.invTransform(i1 - dx);
            d2 = map.invTransform(i2 - dx);
        }
        else
        {
            d1 = map.invTransform(i1 - dy);
            d2 = map.invTransform(i2 - dy);
        }

        plot->setAxisScale(axis, d1, d2);
    }

    plot->setAutoReplot(doAutoReplot);
    plot->replot();
}
void DataWidget::setValue(double value)
{
    switch (_dataDescription->widget)
    {
    case DATA_WIDGET_PLOT:
	{
            QwtPlot *widget = qobject_cast<QwtPlot*> (_internalWidget);
            if (widget != 0)
            {
                _curveData->xData->append(_mainWindow->effectiveRunningTime());
                _curveData->yData->append(value);
#if QWT_VERSION >= 0x060000
                _curve->setRawSamples(_curveData->xData->data(),
                                      _curveData->yData->data(), _curveData->xData->size());
#else
#  warning Old version of qwt being used, data aggregator will not work.
#endif
                widget->replot();
            }
            else
            {
                qDebug() << "Bad data widget cast (DataWidget::setValue()) !";
            }
            break;
	}

    case DATA_WIDGET_LCD:
	{
            QLCDNumber *widget = qobject_cast<QLCDNumber*> (_internalWidget);
            if (widget != 0)
            {
                widget->display(value);
            }
            else
            {
                qDebug() << "Bad data widget cast (DataWidget::setValue()) !";
            }
            break;
	}

    case DATA_WIDGET_LEVEL:
	{
            QwtThermo *widget = qobject_cast<QwtThermo*> (_internalWidget);
            if (widget != 0)
            {
                widget->setValue(value);
            }
            else
            {
                qDebug() << "Bad data widget cast (DataWidget::setValue()) !";
            }
            break;
	}

    case DATA_WIDGET_DIAL:
	{
            QwtDial *widget = qobject_cast<QwtDial*> (_internalWidget);
            if (widget != 0)
            {
                widget->setValue(value);
            }
            else
            {
                qDebug() << "Bad data widget cast (DataWidget::setValue()) !";
            }
            break;
	}

    default:
        ;
    }

    emit valueChanged(value, _dataDescription->id);
}
Esempio n. 19
0
//--------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------
void MainWindow:: drawDistPlots(bool dummy)
{
    double *x, *prob;
    x = new double[nDistPts];
    prob = new double[nDistPts];
    QString median_qstr, shape_qstr;
    double median, shape;
    double expMean[3];
    double expTbase;
    bool use_lognormal = cbox_USE_LOGNORMAL_DIST->isChecked();

    groupBox_divisiondistributions->setEnabled(use_lognormal);
    for (int j=0; j<ndistplots; j++) {
        QwtPlot *qp = distplot_list[j];
        if (j == 0) {
            qp->setTitle("Type 1 division time (hrs)");
            if (use_lognormal) {
                median_qstr = line_DIVIDE_TIME_1_MEDIAN->text();
                shape_qstr = line_DIVIDE_TIME_1_SHAPE->text();
            } else {
                expTbase = line_T_G1_1->text().toDouble() + line_T_S_1->text().toDouble() + line_T_G2_1->text().toDouble();
                expMean[0] = line_G1_MEAN_DELAY_1->text().toDouble();
                expMean[1] = line_S_MEAN_DELAY_1->text().toDouble();
                expMean[2] = line_G2_MEAN_DELAY_1->text().toDouble();
            }
        } else if (j == 1) {
            qp->setTitle("Type 2 division time (hrs)");
            if (use_lognormal) {
                median_qstr = line_DIVIDE_TIME_2_MEDIAN->text();
                shape_qstr = line_DIVIDE_TIME_2_SHAPE->text();
            } else {
                expTbase = line_T_G1_2->text().toDouble() + line_T_S_2->text().toDouble() + line_T_G2_2->text().toDouble();
                expMean[0] = line_G1_MEAN_DELAY_2->text().toDouble();
                expMean[1] = line_S_MEAN_DELAY_2->text().toDouble();
                expMean[2] = line_G2_MEAN_DELAY_2->text().toDouble();
            }
        }
        if (use_lognormal) {
            median = median_qstr.toDouble();
            shape = shape_qstr.toDouble();
            create_lognorm_dist(median, shape, nDistPts, x, prob);
        } else {
            create_expon_dist(expTbase, expMean, nDistPts, x, prob);
        }

        int n = dist_limit(prob,nDistPts);
        double xmax = x[n];
        qp->setAxisScale(QwtPlot::xBottom, 0.0, xmax, 0.0);

        if (first_plot) {
            curve_list[j] = new QwtPlotCurve("title");
            curve_list[j]->setSamples(x, prob, n);
            curve_list[j]->attach(qp);
        } else {
            curve_list[j]->setSamples(x, prob, n);
        }
        qp->replot();
    }
    delete [] x;
    x = NULL;
    delete [] prob;
    prob = NULL;
    first_plot = false;
}
Esempio n. 20
0
void PlotExporter::exportPlot(QwtPlot *plot, const QRectF &zoom)
{
  QSizeF guessedDimensions;
  ExportPlotToImageDialog::Parameters p = m_exportDlg->parameters();

  m_exportDlg->setAspectRatio(plot->size().width() / plot->size().height());

  while (m_exportDlg->exec() == QDialog::Accepted) {
    p = m_exportDlg->parameters();

    QString path;

    if (p.path.length() < 0) {
      QMessageBox::warning(nullptr, QObject::tr("Invalid input"), QObject::tr("Invalid path"));
      continue;
    }
    if (!m_supportedFormats.contains(p.format)) {
      QMessageBox::warning(nullptr, QObject::tr("Invalid input"), QObject::tr("Invalid output format"));
      continue;
    }

    if (p.path.endsWith("." + p.format))
      path = p.path;
    else
      path = p.path + "." + p.format;

    /* Create a temporary QwtPlot to use to write the chart to file */
    QwtPlot exPlot;
    QwtPlotZoomer exPlorZoomer(exPlot.canvas());
    exPlorZoomer.zoom(zoom);

    exPlot.setCanvasBackground(QBrush(Qt::white));
    exPlot.setTitle(p.title);
    exPlot.setAxisTitle(QwtPlot::xBottom, plot->axisTitle(QwtPlot::xBottom));
    exPlot.setAxisTitle(QwtPlot::xTop, plot->axisTitle(QwtPlot::xTop));
    exPlot.setAxisTitle(QwtPlot::yLeft, plot->axisTitle(QwtPlot::yLeft));
    exPlot.setAxisTitle(QwtPlot::yRight, plot->axisTitle(QwtPlot::yRight));
    QwtPlotItemList curves = plot->itemList();

    /* Attach all plots from the GUI plot to the temporary plot
     * Note that this will detach the plots from the GUI plot! */
    QList<qreal> curvePenWidths;
    for (QwtPlotItem *i : curves) {
      QwtPlotCurve *c = dynamic_cast<QwtPlotCurve *>(i);

      if (c != nullptr) {
        QPen p = c->pen();
        qreal w = p.widthF();
        qreal nw;

        curvePenWidths.push_back(w);

        nw = w - 1.0;
        if (nw < 0.0)
          nw = 0.0;

        p.setWidthF(nw);
        c->setPen(p);
      }

      i->attach(&exPlot);
    }

    /* Scale up from millimeters to centimeters*/
    QSizeF dimensionsMM(p.dimensions.width() * 10.0, p.dimensions.height() * 10.0);

    /* Store current properties of the plot as we need to change them for rendering */
    QFont xBottomFont = plot->axisWidget(QwtPlot::xBottom)->font();
    QFont xTopFont = plot->axisWidget(QwtPlot::xTop)->font();
    QFont yLeftFont = plot->axisWidget(QwtPlot::yLeft)->font();
    QFont yRightFont = plot->axisWidget(QwtPlot::yRight)->font();
    QFont xBottomTitleFont = plot->axisTitle(QwtPlot::xBottom).font();
    QFont xTopTitleFont = plot->axisTitle(QwtPlot::xTop).font();
    QFont yLeftTitleFont = plot->axisTitle(QwtPlot::yLeft).font();
    QFont yRightTitleFont = plot->axisTitle(QwtPlot::yRight).font();
    QFont titleFont = plot->title().font();
    const qreal xBottomPenWidth = plot->axisWidget(QwtPlot::xBottom)->scaleDraw()->penWidth() > 0 ? plot->axisWidget(QwtPlot::xBottom)->scaleDraw()->penWidth() : 1.0;
    const qreal xTopPenWidth = plot->axisWidget(QwtPlot::xTop)->scaleDraw()->penWidth() > 0 ? plot->axisWidget(QwtPlot::xTop)->scaleDraw()->penWidth() : 1.0;
    const qreal yLeftPenWidth = plot->axisWidget(QwtPlot::yLeft)->scaleDraw()->penWidth() > 0 ? plot->axisWidget(QwtPlot::yLeft)->scaleDraw()->penWidth() : 1.0;
    const qreal yRightPenWidth = plot->axisWidget(QwtPlot::yRight)->scaleDraw()->penWidth() > 0 ? plot->axisWidget(QwtPlot::yRight)->scaleDraw()->penWidth() : 1.0;

    /* Recalculate sizes by the DPI for every element that needs it */
    const qreal outputInPixels = (static_cast<qreal>(p.dimensions.width()) / 2.54) * p.dpi;
    const qreal scalingRatio = (static_cast<qreal>(qApp->desktop()->logicalDpiX()) / p.dpi) * (outputInPixels / plot->geometry().width());

    const qreal _xBottomPenWidth = floor((xBottomPenWidth * scalingRatio) + 0.45);
    const qreal _xTopPenWidth = floor((xTopPenWidth * scalingRatio) + 0.45);
    const qreal _yLeftPenWidth = floor((yLeftPenWidth * scalingRatio) + 0.45);
    const qreal _yRightPenWidth = floor((yRightPenWidth * scalingRatio) + 0.45);
    xBottomFont.setPointSizeF(p.axisNumbersFontSize * scalingRatio);
    xTopFont.setPointSizeF(p.axisNumbersFontSize * scalingRatio);
    yLeftFont.setPointSizeF(p.axisNumbersFontSize * scalingRatio);
    yRightFont.setPointSizeF(p.axisNumbersFontSize * scalingRatio);
    xBottomTitleFont.setPointSizeF(p.axisTitlesFontSize * scalingRatio);
    xTopTitleFont.setPointSizeF(p.axisTitlesFontSize * scalingRatio);
    yLeftTitleFont.setPointSizeF(p.axisTitlesFontSize * scalingRatio);
    yRightTitleFont.setPointSizeF(p.axisTitlesFontSize * scalingRatio);
    titleFont.setPointSizeF(p.chartTitleFontSize * scalingRatio);
    exPlot.axisWidget(QwtPlot::xBottom)->scaleDraw()->setPenWidth(_xBottomPenWidth);
    exPlot.axisWidget(QwtPlot::xTop)->scaleDraw()->setPenWidth(_xTopPenWidth);
    exPlot.axisWidget(QwtPlot::yLeft)->scaleDraw()->setPenWidth(_yLeftPenWidth);
    exPlot.axisWidget(QwtPlot::yRight)->scaleDraw()->setPenWidth(_yRightPenWidth);

    exPlot.setPalette(m_plotPalette);
    exPlot.axisWidget(QwtPlot::xBottom)->setPalette(m_plotPalette);
    exPlot.axisWidget(QwtPlot::xTop)->setPalette(m_plotPalette);
    exPlot.axisWidget(QwtPlot::yLeft)->setPalette(m_plotPalette);
    exPlot.axisWidget(QwtPlot::yRight)->setPalette(m_plotPalette);
    exPlot.axisWidget(QwtPlot::xBottom)->setFont(xBottomFont);
    exPlot.axisWidget(QwtPlot::xTop)->setFont(xTopFont);
    exPlot.axisWidget(QwtPlot::yLeft)->setFont(yLeftFont);
    exPlot.axisWidget(QwtPlot::yRight)->setFont(yRightFont);
    setAxisTitleFont(&exPlot, QwtPlot::xBottom, xBottomTitleFont);
    setAxisTitleFont(&exPlot, QwtPlot::xTop, xTopTitleFont);
    setAxisTitleFont(&exPlot, QwtPlot::yLeft, yLeftTitleFont);
    setAxisTitleFont(&exPlot, QwtPlot::yRight, yRightTitleFont);
    setTitleFont(&exPlot, titleFont);

    exPlot.replot();

    renderPlotToFile(&exPlot, path, p.format, dimensionsMM, p.dpi);

    /* Reattach the plots back to the GUI plot */
    for (QwtPlotItem *i : curves) {
      QwtPlotCurve *c = dynamic_cast<QwtPlotCurve *>(i);

      if (c != nullptr) {
        QPen p = c->pen();

        if (curvePenWidths.isEmpty())
          break;

        p.setWidthF(curvePenWidths.front());
        curvePenWidths.pop_front();

        c->setPen(p);
      }

      i->attach(plot);
    }

    break; /* Exit the while loop */
  }
}
Esempio n. 21
0
/**
 * Odświeża bieżący wykres.
 */
void ChartsWidget::refresh()
{
    QwtPlot* plot = static_cast<QwtPlot*>(ui->tabCharts->currentWidget());
    plot->replot();
    emit sendMessage(tr("Chart refreshed"));
}
Esempio n. 22
0
	void PlotItem::paint (QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget*)
	{
		const auto& rect = option->rect;
#else
	void PlotItem::paint (QPainter *painter)
	{
		const auto& rect = contentsBoundingRect ().toRect ();
#endif

		QwtPlot plot;
		plot.setFrameShape (QFrame::NoFrame);
		plot.enableAxis (QwtPlot::yLeft, LeftAxisEnabled_);
		plot.enableAxis (QwtPlot::xBottom, BottomAxisEnabled_);
		plot.setAxisTitle (QwtPlot::yLeft, LeftAxisTitle_);
		plot.setAxisTitle (QwtPlot::xBottom, BottomAxisTitle_);
		plot.resize (rect.size ());

		auto setPaletteColor = [&plot] (const QColor& color, QPalette::ColorRole role) -> void
		{
			if (!color.isValid ())
				return;

			auto pal = plot.palette ();
			pal.setColor (role, { color });
			plot.setPalette (pal);
		};

		setPaletteColor (BackgroundColor_, QPalette::Window);
		setPaletteColor (TextColor_, QPalette::WindowText);
		setPaletteColor (TextColor_, QPalette::Text);

		if (!PlotTitle_.isEmpty ())
			plot.setTitle (QwtText { PlotTitle_ });

		if (MinYValue_ < MaxYValue_)
		{
			plot.setAxisAutoScale (QwtPlot::yLeft, false);
			plot.setAxisScale (QwtPlot::yLeft, MinYValue_, MaxYValue_);
		}
		plot.setAutoFillBackground (false);
		plot.setCanvasBackground (Qt::transparent);

		if (YGridEnabled_)
		{
			auto grid = new QwtPlotGrid;
			grid->enableYMin (YMinorGridEnabled_);
			grid->enableX (false);
#if QWT_VERSION >= 0x060100
			grid->setMajorPen (QPen (GridLinesColor_, 1, Qt::SolidLine));
			grid->setMinorPen (QPen (GridLinesColor_, 1, Qt::DashLine));
#else
			grid->setMajPen (QPen (GridLinesColor_, 1, Qt::SolidLine));
			grid->setMinPen (QPen (GridLinesColor_, 1, Qt::DashLine));
#endif
			grid->attach (&plot);
		}

		auto items = Multipoints_;
		if (items.isEmpty ())
			items.push_back ({ Color_, Points_ });

		if (MinXValue_ < MaxXValue_)
			plot.setAxisScale (QwtPlot::xBottom, MinXValue_, MaxXValue_);
		else if (const auto ptsCount = items.first ().Points_.size ())
			plot.setAxisScale (QwtPlot::xBottom, 0, ptsCount - 1);

		std::vector<std::unique_ptr<QwtPlotCurve>> curves;
		for (const auto& item : items)
		{
			curves.emplace_back (new QwtPlotCurve);
			const auto curve = curves.back ().get ();

			curve->setPen (QPen (item.Color_));
			auto transpColor = item.Color_;
			transpColor.setAlphaF (Alpha_);
			curve->setBrush (transpColor);

			curve->setRenderHint (QwtPlotItem::RenderAntialiased);
			curve->attach (&plot);

			curve->setSamples (item.Points_.toVector ());
		}

		plot.replot ();

		QwtPlotRenderer {}.render (&plot, painter, rect);

		const auto xExtent = CalcXExtent (plot);
		const auto yExtent = CalcYExtent (plot);
		if (xExtent != XExtent_ || yExtent != YExtent_)
		{
			XExtent_ = xExtent;
			YExtent_ = yExtent;
			emit extentsChanged ();
		}
	}
Esempio n. 23
0
// Применение результатов перемещения границы шкалы
void QAxisZoomSvc::axisApplyMove(QPoint evpos,int ax)
{
    // получаем указатель на график
    QwtPlot *plt = zoom->plot();
    // определяем (для удобства) геометрию
    QRect gc = plt->canvas()->geometry();       // канвы графика
    QRect gw = plt->axisWidget(ax)->geometry(); // и виджета шкалы
    // определяем текущее положение курсора относительно канвы
    // (за вычетом смещений графика)
    int x = evpos.x() + gw.x() - gc.x() - scb_pxl;
    int y = evpos.y() + gw.y() - gc.y() - scb_pyt;
    bool bndCh = false; // пока ничего не изменилось
    // читаем режим масштабирования
    QwtChartZoom::QConvType ct = zoom->regim();
    // в зависимости от включенного режима выполняем некоторые действия
    switch (ct)
    {
        // режим изменения левой границы
    case QwtChartZoom::ctAxisHL:
    {
        // ограничение на положение курсора справа
        if (x >= scb_pw) x = scb_pw-1;
        // вычисляем новую ширину шкалы
        double wx = scb_wx * (scb_pw - scp_x) / (scb_pw - x);
        // применяем ограничения
        wx = limitScale(wx,scb_wx);
        // вычисляем новую левую границу
        double xl = scb_xr - wx;
        // устанавливаем ее для горизонтальной шкалы
        zoom->isb_x->set(xl,scb_xr);
        bndCh = true;   // изменилась граница
        break;
    }
        // режим изменения правой границы
    case QwtChartZoom::ctAxisHR:
    {
        // ограничение на положение курсора слева
        if (x <= 0) x = 1;
        // вычисляем новую ширину шкалы
        double wx = scb_wx * scp_x / x;
        // применяем ограничения
        wx = limitScale(wx,scb_wx);
        // вычисляем новую правую границу
        double xr = scb_xl + wx;
        // устанавливаем ее для горизонтальной шкалы
        zoom->isb_x->set(scb_xl,xr);
        bndCh = true;   // изменилась граница
        break;
    }
        // режим изменения нижней границы
    case QwtChartZoom::ctAxisVB:
    {
        // ограничение на положение курсора сверху
        if (y <= 0) y = 1;
        // вычисляем новую высоту шкалы
        double hy = scb_hy * scp_y / y;
        // применяем ограничения
        hy = limitScale(hy,scb_hy);
        // вычисляем новую нижнюю границу
        double yb = scb_yt - hy;
        // устанавливаем ее для вертикальной шкалы
        zoom->isb_y->set(yb,scb_yt);
        bndCh = true;   // изменилась граница
        break;
    }
        // режим изменения верхней границы
    case QwtChartZoom::ctAxisVT:
    {
        // ограничение на положение курсора снизу
        if (y >= scb_ph) y = scb_ph-1;
        // вычисляем новую высоту шкалы
        double hy = scb_hy * (scb_ph - scp_y) / (scb_ph - y);
        // применяем ограничения
        hy = limitScale(hy,scb_hy);
        // вычисляем новую верхнюю границу
        double yt = scb_yb + hy;
        // устанавливаем ее для вертикальной шкалы
        zoom->isb_y->set(scb_yb,yt);
        bndCh = true;   // изменилась граница
        break;
    }
        // для прочих режимов ничего не делаем
    default: ;
    }
    // если какя-либо граница изменилась, то перестраиваем график
    if (bndCh) plt->replot();
}