Example #1
0
void QgsPaperGrid::paint( QPainter* painter, const QStyleOptionGraphicsItem* itemStyle, QWidget* pWidget )
{
    Q_UNUSED( itemStyle );
    Q_UNUSED( pWidget );

    //draw grid
    if ( mComposition )
    {
        if ( mComposition->gridVisible() && mComposition->plotStyle() ==  QgsComposition::Preview
                && mComposition->snapGridResolution() > 0 )
        {
            int gridMultiplyX = static_cast< int >( mComposition->snapGridOffsetX() / mComposition->snapGridResolution() );
            int gridMultiplyY = static_cast< int >( mComposition->snapGridOffsetY() / mComposition->snapGridResolution() );
            double currentXCoord = mComposition->snapGridOffsetX() - gridMultiplyX * mComposition->snapGridResolution();
            double currentYCoord;
            double minYCoord = mComposition->snapGridOffsetY() - gridMultiplyY * mComposition->snapGridResolution();

            painter->save();
            //turn of antialiasing so grid is nice and sharp
            painter->setRenderHint( QPainter::Antialiasing, false );

            if ( mComposition->gridStyle() == QgsComposition::Solid )
            {
                painter->setPen( mComposition->gridPen() );

                //draw vertical lines
                for ( ; currentXCoord <= rect().width(); currentXCoord += mComposition->snapGridResolution() )
                {
                    painter->drawLine( QPointF( currentXCoord, 0 ), QPointF( currentXCoord, rect().height() ) );
                }

                //draw horizontal lines
                currentYCoord = minYCoord;
                for ( ; currentYCoord <= rect().height(); currentYCoord += mComposition->snapGridResolution() )
                {
                    painter->drawLine( QPointF( 0, currentYCoord ), QPointF( rect().width(), currentYCoord ) );
                }
            }
            else //'Dots' or 'Crosses'
            {
                QPen gridPen = mComposition->gridPen();
                painter->setPen( gridPen );
                painter->setBrush( QBrush( gridPen.color() ) );
                double halfCrossLength = 1;
                if ( mComposition->gridStyle() == QgsComposition::Dots )
                {
                    //dots are actually drawn as tiny crosses a few pixels across
                    //check QGraphicsView to get current transform
                    if ( scene() )
                    {
                        QList<QGraphicsView*> viewList = scene()->views();
                        if ( !viewList.isEmpty() )
                        {
                            QGraphicsView* currentView = viewList.at( 0 );
                            if ( currentView->isVisible() )
                            {
                                //set halfCrossLength to equivalent of 1 pixel
                                halfCrossLength = 1 / currentView->transform().m11();
                            }
                        }
                    }
                }
                else if ( mComposition->gridStyle() == QgsComposition::Crosses )
                {
                    halfCrossLength = mComposition->snapGridResolution() / 6;
                }

                for ( ; currentXCoord <= rect().width(); currentXCoord += mComposition->snapGridResolution() )
                {
                    currentYCoord = minYCoord;
                    for ( ; currentYCoord <= rect().height(); currentYCoord += mComposition->snapGridResolution() )
                    {
                        painter->drawLine( QPointF( currentXCoord - halfCrossLength, currentYCoord ), QPointF( currentXCoord + halfCrossLength, currentYCoord ) );
                        painter->drawLine( QPointF( currentXCoord, currentYCoord - halfCrossLength ), QPointF( currentXCoord, currentYCoord + halfCrossLength ) );
                    }
                }
            }
            painter->restore();
        }
    }
}
Example #2
0
void AudioNoiseWidget::paintEvent(QPaintEvent *) {
	QPainter paint(this);
	QPalette pal;

	paint.fillRect(rect(), pal.color(QPalette::Background));

	AudioInputPtr ai = g.ai;
	if (ai.get() == NULL || ! ai->sppPreprocess)
		return;

	QPolygonF poly;

	ai->qmSpeex.lock();

	spx_int32_t ps_size = 0;
	speex_preprocess_ctl(ai->sppPreprocess, SPEEX_PREPROCESS_GET_PSD_SIZE, &ps_size);

	STACKVAR(spx_int32_t, noise, ps_size);
	STACKVAR(spx_int32_t, ps, ps_size);

	speex_preprocess_ctl(ai->sppPreprocess, SPEEX_PREPROCESS_GET_PSD, ps);
	speex_preprocess_ctl(ai->sppPreprocess, SPEEX_PREPROCESS_GET_NOISE_PSD, noise);

	ai->qmSpeex.unlock();

	qreal sx, sy;

	sx = (static_cast<float>(width()) - 1.0f) / static_cast<float>(ps_size);
	sy = static_cast<float>(height()) - 1.0f;

	poly << QPointF(0.0f, height() - 1);
	float fftmul = 1.0 / (32768.0);
	for (int i=0; i < ps_size; i++) {
		qreal xp, yp;
		xp = i * sx;
		yp = sqrtf(sqrtf(static_cast<float>(noise[i]))) - 1.0f;
		yp = yp * fftmul;
		yp = qMin<qreal>(yp * 3000.0f, 1.0f);
		yp = (1 - yp) * sy;
		poly << QPointF(xp, yp);
	}

	poly << QPointF(width() - 1, height() - 1);
	poly << QPointF(0.0f, height() - 1);

	paint.setPen(Qt::blue);
	paint.setBrush(Qt::blue);
	paint.drawPolygon(poly);

	poly.clear();

	for (int i=0;i < ps_size; i++) {
		qreal xp, yp;
		xp = i * sx;
		yp = sqrtf(sqrtf(static_cast<float>(ps[i]))) - 1.0f;
		yp = yp * fftmul;
		yp = qMin(yp * 3000.0, 1.0);
		yp = (1 - yp) * sy;
		poly << QPointF(xp, yp);
	}

	paint.setPen(Qt::red);
	paint.drawPolyline(poly);
}
Example #3
0
void QgsDecorationGrid::drawCoordinateAnnotation( QPainter* p, QPointF pos, const QString& annotationString )
{
  Border frameBorder = borderForLineCoord( pos, p );
  double textWidth = textWidthMillimeters( mGridAnnotationFont, annotationString );
  //relevant for annotations is the height of digits
  double textHeight = fontHeightCharacterMM( mGridAnnotationFont, QChar( '0' ) );
  double xpos = pos.x();
  double ypos = pos.y();
  int rotation = 0;

  if ( frameBorder == Left )
  {

    if ( mGridAnnotationPosition == InsideMapFrame )
    {
      if ( mGridAnnotationDirection == Vertical || mGridAnnotationDirection == BoundaryDirection )
      {
        xpos += textHeight + mAnnotationFrameDistance;
        ypos += textWidth / 2.0;
        rotation = 270;
      }
      else
      {
        xpos += mAnnotationFrameDistance;
        ypos += textHeight / 2.0;
      }
    }
    else //Outside map frame
    {
      if ( mGridAnnotationDirection == Vertical || mGridAnnotationDirection == BoundaryDirection )
      {
        xpos -= mAnnotationFrameDistance;
        ypos += textWidth / 2.0;
        rotation = 270;
      }
      else
      {
        xpos -= textWidth + mAnnotationFrameDistance;
        ypos += textHeight / 2.0;
      }
    }

  }
  else if ( frameBorder == Right )
  {
    if ( mGridAnnotationPosition == InsideMapFrame )
    {
      if ( mGridAnnotationDirection == Vertical || mGridAnnotationDirection == BoundaryDirection )
      {
        xpos -= mAnnotationFrameDistance;
        ypos += textWidth / 2.0;
        rotation = 270;
      }
      else //Horizontal
      {
        xpos -= textWidth + mAnnotationFrameDistance;
        ypos += textHeight / 2.0;
      }
    }
    else //OutsideMapFrame
    {
      if ( mGridAnnotationDirection == Vertical || mGridAnnotationDirection == BoundaryDirection )
      {
        xpos += textHeight + mAnnotationFrameDistance;
        ypos += textWidth / 2.0;
        rotation = 270;
      }
      else //Horizontal
      {
        xpos += mAnnotationFrameDistance;
        ypos += textHeight / 2.0;
      }
    }
  }
  else if ( frameBorder == Bottom )
  {
    if ( mGridAnnotationPosition == InsideMapFrame )
    {
      if ( mGridAnnotationDirection == Horizontal || mGridAnnotationDirection == BoundaryDirection )
      {
        ypos -= mAnnotationFrameDistance;
        xpos -= textWidth / 2.0;
      }
      else //Vertical
      {
        xpos += textHeight / 2.0;
        ypos -= mAnnotationFrameDistance;
        rotation = 270;
      }
    }
    else //OutsideMapFrame
    {
      if ( mGridAnnotationDirection == Horizontal || mGridAnnotationDirection == BoundaryDirection )
      {
        ypos += mAnnotationFrameDistance + textHeight;
        xpos -= textWidth / 2.0;
      }
      else //Vertical
      {
        xpos += textHeight / 2.0;
        ypos += textWidth + mAnnotationFrameDistance;
        rotation = 270;
      }
    }
  }
  else //Top
  {
    if ( mGridAnnotationPosition == InsideMapFrame )
    {
      if ( mGridAnnotationDirection == Horizontal || mGridAnnotationDirection == BoundaryDirection )
      {
        xpos -= textWidth / 2.0;
        ypos += textHeight + mAnnotationFrameDistance;
      }
      else //Vertical
      {
        xpos += textHeight / 2.0;
        ypos += textWidth + mAnnotationFrameDistance;
        rotation = 270;
      }
    }
    else //OutsideMapFrame
    {
      if ( mGridAnnotationDirection == Horizontal || mGridAnnotationDirection == BoundaryDirection )
      {
        xpos -= textWidth / 2.0;
        ypos -= mAnnotationFrameDistance;
      }
      else //Vertical
      {
        xpos += textHeight / 2.0;
        ypos -= mAnnotationFrameDistance;
        rotation = 270;
      }
    }
  }

  drawAnnotation( p, QPointF( xpos, ypos ), rotation, annotationString );
}
Example #4
0
int main()
{
    {
        // STREAM
//! [0]
        QPolygon polygon;
        polygon << QPoint(10, 20) << QPoint(20, 30);
//! [0]
    }

    {
        // STREAMF
//! [1]
        QPolygonF polygon;
        polygon << QPointF(10.4, 20.5) << QPointF(20.2, 30.2);
//! [1]
    }

    {
        // SETPOINTS
//! [2]
        static const int points[] = { 10, 20, 30, 40 };
        QPolygon polygon;
        polygon.setPoints(2, points);
//! [2]
    }

    {
        // SETPOINTS2
//! [3]
        QPolygon polygon;
        polygon.setPoints(2, 10, 20, 30, 40);
//! [3]
    }

    {
        // PUTPOINTS
//! [4]
        QPolygon polygon(1);
        polygon[0] = QPoint(4, 5);
        polygon.putPoints(1, 2, 6,7, 8,9);
//! [4]
    }

    {
        // PUTPOINTS2
//! [5]
        QPolygon polygon(3);
        polygon.putPoints(0, 3, 4,5, 0,0, 8,9);
        polygon.putPoints(1, 1, 6,7);
//! [5]
    }

    {
        // PUTPOINTS3
//! [6]
        QPolygon polygon1;
        polygon1.putPoints(0, 3, 1,2, 0,0, 5,6);
        // polygon1 is now the three-point polygon(1,2, 0,0, 5,6);

        QPolygon polygon2;
        polygon2.putPoints(0, 3, 4,4, 5,5, 6,6);
        // polygon2 is now (4,4, 5,5, 6,6);

        polygon1.putPoints(2, 3, polygon2);
        // polygon1 is now the five-point polygon(1,2, 0,0, 4,4, 5,5, 6,6);
//! [6]
    }
    return 0;
}
static void fillRectVec(QVector<QPointF> &v)
{
    int numRects = v.size() / 5;

    int first = 0;
    v[first++] = QPointF(0, 0);
    v[first++] = QPointF(10, 0);
    v[first++] = QPointF(10, 10);
    v[first++] = QPointF(0, 10);
    v[first++] = QPointF(0, 0);

    v[first++] = QPointF(0, 0);
    v[first++] = QPointF(2, 2);
    v[first++] = QPointF(4, 0);
    v[first++] = QPointF(2, -2);
    v[first++] = QPointF(0, 0);

    v[first++] = QPointF(0, 0);
    v[first++] = QPointF(4, 4);
    v[first++] = QPointF(6, 2);
    v[first++] = QPointF(2, -2);
    v[first++] = QPointF(0, 0);

    for (int i = first / 5; i < numRects; ++i) {
        QPointF a = creatPoint();
        QPointF b = creatPoint();

        QPointF delta = a - b;
        QPointF perp(delta.y(), -delta.x());

        perp *= ((int)(20.0 * rand() / (RAND_MAX + 1.0))) / 20.0;

        int j = 5 * i;
        v[j++] = a + perp;
        v[j++] = a - perp;
        v[j++] = b - perp;
        v[j++] = b + perp;
        v[j++] = a + perp;
    }
}
Example #6
0
QRectF Window::boundingRect() const{
    return QRectF(QPointF(), size);
}
Example #7
0
QRectF QPageLayoutPrivate::fullRect(QPageLayout::Unit units) const
{
    return units == m_units ? fullRect() : QRectF(QPointF(0, 0), fullSizeUnits(units));
}
Example #8
0
void ChessBoard::renderBoard( QPainter &p, const QRectF &rc, bool flip,
    const std::vector<cheng4::Square> *excludeSquares )
{
    qreal maxh = std::max( rc.width(), rc.height() )/14;
    maxh = 18;
	qreal bordersz = maxh;
	if ( !border )
		bordersz = 0;
	qreal sw = (rc.width() - 2*bordersz) / 8;
	qreal sh = (rc.height() - 2*bordersz) / 8;
    sh = sw = std::min(sw, sh);

    QColor wb[2] = { QColor(255, 255, 255, 255), QColor(0, 0, 0, 255) };

	QColor bord = borderColor;

	QBrush lightb(lightColor);
	QBrush darkb(darkColor);
    p.setPen(Qt::transparent);
    // render border...
    p.setBrush( QBrush(bord) );
	p.drawRect(QRectF(rc.left(), rc.top(), 8*sw + 2*bordersz+1, 8*sh + 2*bordersz+1));

    QPen bpen( QColor(0, 0, 0, 128) );
    bpen.setWidth(1);
    p.setPen( bpen );
    p.setBrush( Qt::transparent );
    QRectF brect;
	brect.setTopLeft( QPoint(bordersz-1, bordersz-1) );
    brect.setSize( QSizeF(8*sw+2, 8*sh+2) );
    p.drawRect( brect );

    brect.setTopLeft( QPoint(0, 0) );
	brect.setSize( QSizeF(8*sw+2*bordersz, 8*sh+2*bordersz) );
    p.drawRect( brect );

    p.setPen( Qt::transparent );

    for (cheng4::Square s = 0; s < 64; s++)
    {
        cheng4::File f = cheng4::SquarePack::file(s);
        cheng4::Rank r = cheng4::SquarePack::rank(s);
		QRectF sub(rc.left() + sw*f + bordersz, rc.top() + sh*r + bordersz, sw, sh);
        cheng4::Square sq = flip ? cheng4::SquarePack::flipH(cheng4::SquarePack::flipV(s)) : s;


        p.setBrush( ((f+r) & 1) ? darkb : lightb );
        p.drawRect( sub );
        if ( excludeSquares && std::find(excludeSquares->begin(), excludeSquares->end(), sq)
             != excludeSquares->end() )
            continue;

        cheng4::Piece pc = board.piece(sq);
        cheng4::Piece pt = cheng4::PiecePack::type(pc);
        if ( pt == cheng4::ptNone )
            continue;
        cheng4::Color c = cheng4::PiecePack::color(pc);
		if ( !pieceSet || !pieceSet->pieces[c][pt-1] )
			continue;
        pieceSet->pieces[c][pt-1]->renderer()->render(&p, sub);
	}

	// FIXME: better!!!
	for (cheng4::Square s = 0; s < 64; s++)
	{
		cheng4::File f = cheng4::SquarePack::file(s);
		cheng4::Rank r = cheng4::SquarePack::rank(s);
		QRectF sub(rc.left() + sw*f + bordersz, rc.top() + sh*r + bordersz, sw, sh);
		cheng4::Square sq = flip ? cheng4::SquarePack::flipH(cheng4::SquarePack::flipV(s)) : s;
		// now highlight!!!
		if ( highlight == cheng4::mcNone || highlight == cheng4::mcNull )
			continue;
		cheng4::Square from, to;
		from = cheng4::MovePack::from(highlight);
		to = cheng4::MovePack::to(highlight);
		if ( sq != from && sq != to )
			continue;

		QPen hpen( highlightColor );
		hpen.setWidth(2);
		p.setPen( hpen );
		p.setBrush( Qt::transparent );
		p.drawRect( sub );
		p.setPen( Qt::transparent );
	}

	if ( !border )
		return;

    // draw board letters
	p.setPen( letterColor );
    QTextOption opt;
    opt.setAlignment(Qt::AlignCenter);
    QFont font;
    font.setBold(0);
    font.setPixelSize(12);
    p.setFont(font);
    for (uint i=0; i<8; i++)
    {
        // rows:
		QPointF pt( 0, bordersz + sh*i );
        QRectF rct;
        rct.setTopLeft( pt );
		rct.setSize( QSizeF( bordersz, sh ) );
        QString text;
        int irow = 7-(int)i;
        if ( flip )
            irow = 8-1-irow;
        text.sprintf("%d", irow+1);
        p.drawText(rct, text, opt);
		pt.setX( bordersz+sw*8 );
        rct.setTopLeft( pt );
		rct.setSize( QSizeF( bordersz, sh ) );
        p.drawText(rct, text, opt);
        // cols:
        int icol = (int)i;
        if ( flip )
            icol = 8-1-i;
        text.sprintf("%c", 'a' + icol);
		pt.setX( bordersz + sw*i );
        pt.setY( 0 );
        rct.setTopLeft(pt);
		rct.setSize( QSizeF( sw, bordersz ) );
        p.drawText(rct, text, opt);
		pt.setY( bordersz+sh*8 );
        rct.setTopLeft( pt );
		rct.setSize( QSizeF( sw, bordersz ) );
        p.drawText(rct, text, opt);
    }
    // draw stm
    QRectF upr;
	upr.setTopLeft( QPointF( bordersz + sw*8 + bordersz/8, bordersz/8 ) );
	upr.setSize( QSizeF( bordersz - 2*bordersz/8, bordersz - 2*bordersz/8 ) );

    bool upper = board.turn() == (flip ? cheng4::ctWhite : cheng4::ctBlack);

    p.setPen( wb[ cheng4::flip(board.turn()) ] );
    p.setBrush( wb[ board.turn() ] );

    if ( upper )
        p.drawRect( upr );

    QRectF lwr;
	lwr.setTopLeft( QPointF( bordersz + sw*8 + bordersz/8, bordersz + sh*8 + bordersz/8 ) );
	lwr.setSize( QSizeF( bordersz - 2*bordersz/8, bordersz - 2*bordersz/8 ) );

    if ( !upper )
        p.drawRect( lwr );
}
Example #9
0
/**
 * Evento chamado quando o mouse é clicado
 */
void GraphicsScene::mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent)
{
  if(!running)
  {
    QPointF pos = mouseEvent->scenePos(); //posição do mouse na hora do clique
    //qDebug() << "x: " << pos.x() << " y: " << pos.y();
    bool colidiu = false;
    QList<QGraphicsItem *> cidades = this->items(); //lista de cidades na tela

    if(mouseEvent->button() == Qt::LeftButton) //adicionar uma cidade
    {
        QRectF bboxCidade(pos.x(),pos.y(), cidadeWidth, cidadeHeigth); //bouding box da elipse da cidade

        //gradiente de cores de cada cidade
        QRadialGradient gradient(10, 10, 10, 10, 10);
        gradient.setColorAt(0, QColor::fromRgbF(0.5, 0.8, 0.7, 1));
        gradient.setColorAt(1, QColor::fromRgbF(0, 0, 0, 0));
        gradient.setSpread(QGradient::ReflectSpread);
        QBrush brush(gradient);

        QGraphicsEllipseItem *cidade = new QGraphicsEllipseItem(bboxCidade);
        cidade->setPen(QPen(Qt::black, 1, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
        cidade->setBrush(brush);
        cidade->setZValue(1.0);

        for(int i = 0; i < cidades.size(); i++) //percorrendo a lista de cidades
        {
            if(cidades.at(i)->collidesWithItem(cidade) && cidades.at(i)->data(1).toBool())
            {
                colidiu = true;
                break;
            }
        }

        if(!colidiu) //se não houve colisão
        {
           cidade->setData(0, Cidade::getLastId() + 1);
           cidade->setData(1, 1);
           cidade->setData(4, pos);
           this->addItem(cidade);

           if(lastPos.x() != -10.0 && lastPos.y() != -10.0)
           {
               QPoint cids(Cidade::getLastId(),Cidade::getLastId() + 1);
               //this->drawEdge(lastPos, pos, cids);
           }

           lastPos = pos;
           emit cidadeCriada(pos); //sinal emitido quando uma cidade é criada
        }
    }
    else if(mouseEvent->button() == Qt::RightButton) //remover uma cidade
    {
        for(int i = 0; i < cidades.size(); i++) //percorrendo a lista de cidades
        {
            if(cidades.at(i)->contains(pos) && cidades.at(i)->data(1).toInt() == 1) //o mouse foi clicado em cima de uma cidade
            {
                int chave = cidades.at(i)->data(0).toInt();
                this->removeItem(cidades.at(i));
                //this->removeEdge(chave);

                if(items().size() == 0) lastPos = QPointF(-10,-10);
                emit cidadeRemovida(chave); //sinal emitido quando uma cidade removida
            }
        }
    }
  }
}
void QgsMarkerSymbolLayerV2::drawPreviewIcon( QgsSymbolV2RenderContext& context, QSize size )
{
  startRender( context );
  renderPoint( QPointF( size.width() / 2, size.height() / 2 ), context );
  stopRender( context );
}
QPointF QgsMarkerSymbolLayerV2::_rotatedOffset( const QPointF& offset, double angle )
{
  angle = DEG2RAD( angle );
  double c = cos( angle ), s = sin( angle );
  return QPointF( offset.x() * c - offset.y() * s, offset.x() * s + offset.y() * c );
}
Example #12
0
void FGWCondition::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);

    QFontMetrics fm = painter.fontMetrics();
    if (fm.ascent() + fm.descent() != m_fontHeight)
    {
        m_fontHeight = fm.ascent() + fm.descent();
        updateTransforms();
    }

    // Y-Axis label
    QTransform transform;
    transform.rotate(270);
    transform.translate(-(height() + fm.width(m_yAxisLabel)) / 2, fm.ascent());
    painter.setTransform(transform);
    painter.drawText(QPointF(0, 0), m_yAxisLabel);

    // X-Axis label
    transform.reset();
    painter.setTransform(transform);
    painter.drawText(QPointF((width() - fm.width(m_xAxisLabel)) / 2, height() - fm.descent()), m_xAxisLabel);

    // The actual graph
    if (m_forceCondition)
    {
        QPointF startPos(-1.0, 0.0);
        QPointF startViewPos = m_model2View.map(startPos);

        QPointF endPos(1.0, 0.0);
        QPointF endViewPos = m_model2View.map(endPos);

        double negativeSaturation = m_forceCondition->negativeSaturation();
        if (m_forceCondition->negativeCoefficient() < 0.0)
        {
            negativeSaturation = -negativeSaturation;
        }

        double positiveSaturation = m_forceCondition->positiveSaturation();
        if (m_forceCondition->positiveCoefficient() < 0.0)
        {
            positiveSaturation = -positiveSaturation;
        }

        double negativeDeadBandValue = CLIP11(m_forceCondition->offset() - m_forceCondition->deadBand());
        double positiveDeadBandValue = CLIP11(m_forceCondition->offset() + m_forceCondition->deadBand());

        double negCoeff = m_forceCondition->negativeCoefficient();
        double negCoeffValue = 1000.0;
        if (0.001 < fabs(negCoeff))
        {
            negCoeffValue = (1.0 / fabs(negCoeff)) - 1.0;
        }
        negCoeffValue *= m_forceCondition->negativeSaturation();
        double negativeSaturationValue = negativeDeadBandValue - negCoeffValue;
        if (negativeSaturationValue < -1.0)
        {
            double negCoeffVisible = negativeDeadBandValue + 1.0;
            double ratio = negCoeffVisible / negCoeffValue;
            negativeSaturation *= ratio;
            negativeSaturationValue = -1.0;
        }

        double posCoeff = m_forceCondition->positiveCoefficient();
        double posCoeffValue = 1000.0;
        if (0.001 < fabs(posCoeff))
        {
            posCoeffValue = (1.0 / fabs(posCoeff)) - 1.0;
        }
        posCoeffValue *= m_forceCondition->positiveSaturation();
        double positiveSaturationValue = positiveDeadBandValue + posCoeffValue;
        if (1.0 < positiveSaturationValue)
        {
            double posCoeffVisible = 1.0 - positiveDeadBandValue;
            double ratio = posCoeffVisible / posCoeffValue;
            positiveSaturation *= ratio;
            positiveSaturationValue = 1.0;
        }

        QPointF offsetPos(m_forceCondition->offset(), 0.0);
        QPointF offsetViewPos = m_model2View.map(offsetPos);

        QPointF negativeSaturationPos(-1.0, negativeSaturation);
        QPointF negativeSaturationViewPos = m_model2View.map(negativeSaturationPos);

        QPointF negativeCoefficientPos(negativeSaturationValue, negativeSaturation);
        QPointF negativeCoefficientViewPos = m_model2View.map(negativeCoefficientPos);

        QPointF negativeDeadBandPos(negativeDeadBandValue, 0.0);
        QPointF negativeDeadBandViewPos = m_model2View.map(negativeDeadBandPos);

        QPointF positiveDeadBandPos(positiveDeadBandValue, 0.0);
        QPointF positiveDeadBandViewPos = m_model2View.map(positiveDeadBandPos);

        QPointF positiveCoefficientPos(positiveSaturationValue, positiveSaturation);
        QPointF positiveCoefficientViewPos = m_model2View.map(positiveCoefficientPos);

        QPointF positiveSaturationPos(1.0, positiveSaturation);
        QPointF positiveSaturationViewPos = m_model2View.map(positiveSaturationPos);

        painter.setPen(Qt::black);
        painter.setBrush(Qt::green);
        QPolygon envelope;
        envelope << startViewPos.toPoint()
                 << negativeSaturationViewPos.toPoint()
                 << negativeCoefficientViewPos.toPoint()
                 << negativeDeadBandViewPos.toPoint()
                 << positiveDeadBandViewPos.toPoint()
                 << positiveCoefficientViewPos.toPoint()
                 << positiveSaturationViewPos.toPoint()
                 << endViewPos.toPoint();
        painter.drawPolygon(envelope);

        painter.setBrush(QBrush(Qt::red));
        painter.drawEllipse(negativeCoefficientViewPos, m_handleRadius, m_handleRadius);
        painter.drawEllipse(negativeDeadBandViewPos, m_handleRadius, m_handleRadius);
        painter.drawEllipse(positiveDeadBandViewPos, m_handleRadius, m_handleRadius);
        painter.drawEllipse(positiveCoefficientViewPos, m_handleRadius, m_handleRadius);

        if (!m_dragHandler->isDragging())
        {
            double negSatHalfWidth = (negativeCoefficientViewPos.x() - startViewPos.x()) / 2.0;
            m_dragHandler->setHitAreaView(NegativeSaturation,
                                          QPointF(startViewPos.x() + negSatHalfWidth, negativeSaturationViewPos.y()),
                                          negSatHalfWidth, m_handleRadius);
            m_dragHandler->setHitAreaView(NegativeCoefficient, negativeCoefficientViewPos);
            m_dragHandler->setHitAreaView(NegativeDeadBand, negativeDeadBandViewPos);
            double offsetHalfWidth = (positiveDeadBandViewPos.x() - negativeDeadBandViewPos.x()) / 2.0;
            m_dragHandler->setHitAreaView(Offset, offsetViewPos, offsetHalfWidth, m_handleRadius);
            m_dragHandler->setHitAreaView(PositiveDeadBand, positiveDeadBandViewPos);
            m_dragHandler->setHitAreaView(PositiveCoefficient, positiveCoefficientViewPos);
            double posSatHalfWidth = (endViewPos.x() - positiveCoefficientViewPos.x()) / 2.0;
            m_dragHandler->setHitAreaView(PositiveSaturation,
                                          QPointF(endViewPos.x() - posSatHalfWidth, positiveSaturationViewPos.y()),
                                          posSatHalfWidth, m_handleRadius);
        }
    }
}
Example #13
0
void Playground::SetEnvironment()
{
    ClearEnvironment();

    countingTimeText = scene.addSimpleText(QString("0"));
    countingTimeText->setPos(-100, 100);

    srand(numberAgents * numberObstacles);

    Obstacle * tempObstacle;
    QPolygonF polygon;
    int centerX, centerY;
    qreal koef = 0.5;
    for(int loop1 = 0; loop1 < numberObstacles; loop1++)
    {
        tempObstacle = new Obstacle();
        polygon.clear();
        centerX = rand() % 10 * 100 - 25 + rand() % 50;
        centerY = rand() % 10 * 100 - 25 + rand() % 50;

        int size = 30;
        switch(rand() % 3)
        {
        case 0:
            polygon.push_back(QPointF(koef * (centerX - size), koef * (centerY - size)));
            polygon.push_back(QPointF(koef * (centerX + size), koef * (centerY - size)));
            polygon.push_back(QPointF(koef * (centerX), koef * (centerY + size)));
            break;
        case 1:
            polygon.push_back(QPointF(koef * (centerX - size), koef * (centerY - size)));
            polygon.push_back(QPointF(koef * (centerX + size), koef * (centerY)));
            polygon.push_back(QPointF(koef * (centerX - size), koef * (centerY + size)));
            break;
        case 2:
            polygon.push_back(QPointF(koef * (centerX - size), koef * (centerY - size)));
            polygon.push_back(QPointF(koef * (centerX + size), koef * (centerY - size)));
            polygon.push_back(QPointF(koef * (centerX - size), koef * (centerY + size)));
            break;
        }
        tempObstacle->setPolygon(polygon);
        obstacle.push_back(tempObstacle);
        scene.addItem(tempObstacle);
    }

    Agent * tempAgent;
    PotentialField * tempField;
    GoalPoint * tempGoal;

    int agentX, agentY;
    int agentWidth = 5;
    for(int loop1 = 0; loop1 < numberAgents; loop1++)
    {
        switch(loop1 % 4)
        {
        case 0 :
            agentX = -40;
            agentY = rand() % 100 * 5;
            break;
        case 1 :
            agentX = 510;
            agentY = rand() % 100 * 5;
            break;

        case 2 :
            agentY = -40;
            agentX = rand() % 100 * 5;
            break;
        case 3 :
            agentY = 510;
            agentX = rand() % 100 * 5;
            break;
        }

        tempAgent = new Agent(agentX, agentY, agentWidth, agentWidth, 0);
        tempAgent->SetGoal(470 - agentX, 470 - agentY);
        tempGoal = new GoalPoint(470 - agentX - 5, 470 - agentY - 5, 10, 10, 0);
        tempField = new PotentialField(tempAgent, agentX, agentY, 0);
        tempAgent->SetField(tempField);

        agent.push_back(tempAgent);
        scene.addItem(tempAgent);
        field.push_back(tempField);
        scene.addItem(tempField);
        goalPoint.push_back(tempGoal);
        scene.addItem(tempGoal);
    }

}
Example #14
0
void SkyQPainter::drawDeepSkySymbol(const QPointF &pos, int type, float size, float e, float positionAngle)
{
    float x = pos.x();
    float y = pos.y();
    float zoom = Options::zoomFactor();

    int isize = int(size);

    float dx1 = -0.5*size;
    float dx2 =  0.5*size;
    float dy1 = -1.0*e*size/2.;
    float dy2 = e*size/2.;
    float x1 = x + dx1;
    float x2 = x + dx2;
    float y1 = y + dy1;
    float y2 = y + dy2;

    float dxa = -size/4.;
    float dxb =  size/4.;
    float dya = -1.0*e*size/4.;
    float dyb = e*size/4.;
    float xa = x + dxa;
    float xb = x + dxb;
    float ya = y + dya;
    float yb = y + dyb;

    QString color;

    float psize;

    QBrush tempBrush;

    std::function<void( float, float, float, float )> lambdaDrawEllipse;
    std::function<void( float, float, float, float )> lambdaDrawLine;
    std::function<void( float, float, float, float )> lambdaDrawCross;

    if ( Options::useAntialias() ) {
        lambdaDrawEllipse = [this]( float x, float y, float width, float height ) {
            drawEllipse( QRectF( x, y, width, height ) );
        };
        lambdaDrawLine = [this]( float x1, float y1, float x2, float y2 ) {
            drawLine( QLineF( x1, y1, x2, y2 ) );
        };
        lambdaDrawCross = [this]( float centerX, float centerY, float sizeX, float sizeY ) {
            drawLine( QLineF( centerX - sizeX/2., centerY, centerX + sizeX/2., centerY ) );
            drawLine( QLineF( centerX, centerY - sizeY/2., centerX, centerY + sizeY/2. ) );
        };
    }
    else {
        lambdaDrawEllipse = [this]( float x, float y, float width, float height ) {
            drawEllipse( QRect( x, y, width, height ) );
        };
        lambdaDrawLine = [this]( float x1, float y1, float x2, float y2 ) {
            drawLine( QLine( x1, y1, x2, y2 ) );
        };
        lambdaDrawCross = [this]( float centerX, float centerY, float sizeX, float sizeY ) {
            drawLine( QLine( centerX - sizeX/2., centerY, centerX + sizeX/2., centerY ) );
            drawLine( QLine( centerX, centerY - sizeY/2., centerX, centerY + sizeY/2. ) );
        };
    }

    switch ( type ) {
    case 0:
    case 1: //catalog star
        //Some NGC/IC objects are stars...changed their type to 1 (was double star)
        if (size<2.) size = 2.;
        lambdaDrawEllipse( x1, y1, size/2., size/2. );
        break;
    case 2: //Planet
        break;
    case 3: //Open cluster; draw circle of points
    case 13: { // Asterism
        tempBrush = brush();
        color = pen().color().name();
        setBrush( pen().color() );
        psize = 2.;
        if ( size > 50. )  psize *= 2.;
        if ( size > 100. ) psize *= 2.;
        auto putDot = [this, psize, &lambdaDrawEllipse]( float x, float y ) {
            lambdaDrawEllipse( x, y, psize, psize );
        };
        putDot( xa, y1 );
        putDot( xb, y1 );
        putDot( xa, y2 );
        putDot( xb, y2 );
        putDot( x1, ya );
        putDot( x1, yb );
        putDot( x2, ya );
        putDot( x2, yb );
        setBrush( tempBrush );
        break;
    }
    case 4: //Globular Cluster
        if (size<2.) size = 2.;
        save();
        translate( x, y );
        color = pen().color().name();
        rotate( positionAngle );  //rotate the coordinate system
        lambdaDrawEllipse( dx1, dy1, size, e*size );
        lambdaDrawCross( 0, 0, size, e*size );
        restore(); //reset coordinate system
        break;

    case 5: //Gaseous Nebula
    case 15: // Dark Nebula
        if (size <2.) size = 2.;
        save();
        translate( x, y );
        rotate( positionAngle );  //rotate the coordinate system
        color = pen().color().name();
        lambdaDrawLine( dx1, dy1, dx2, dy1 );
        lambdaDrawLine( dx2, dy1, dx2, dy2 );
        lambdaDrawLine( dx2, dy2, dx1, dy2 );
        lambdaDrawLine( dx1, dy2, dx1, dy1 );
        restore(); //reset coordinate system
        break;
    case 6: //Planetary Nebula
        if (size<2.) size = 2.;
        save();
        translate( x, y );
        rotate( positionAngle );  //rotate the coordinate system
        color = pen().color().name();
        lambdaDrawEllipse( dx1, dy1, size, e*size );
        lambdaDrawLine( 0., dy1, 0., dy1 - e*size/2. );
        lambdaDrawLine( 0., dy2, 0., dy2 + e*size/2. );
        lambdaDrawLine( dx1, 0., dx1 - size/2., 0. );
        lambdaDrawLine( dx2, 0., dx2 + size/2., 0. );
        restore(); //reset coordinate system
        break;
    case 7: //Supernova remnant // FIXME: Why is SNR drawn different from a gaseous nebula?
        if (size<2) size = 2;
        save();
        translate( x, y );
        rotate( positionAngle );  //rotate the coordinate system
        color = pen().color().name();
        lambdaDrawLine( 0., dy1, dx2, 0. );
        lambdaDrawLine( dx2, 0., 0., dy2 );
        lambdaDrawLine( 0., dy2, dx1, 0. );
        lambdaDrawLine( dx1, 0., 0., dy1 );
        restore(); //reset coordinate system
        break;
    case 8: //Galaxy
    case 16: // Quasar
        color = pen().color().name();
        if ( size <1. && zoom > 20*MINZOOM ) size = 3.; //force ellipse above zoomFactor 20
        if ( size <1. && zoom > 5*MINZOOM ) size = 1.; //force points above zoomFactor 5
        if ( size>2. ) {
            save();
            translate( x, y );
            rotate( positionAngle );  //rotate the coordinate system
            lambdaDrawEllipse( dx1, dy1, size, e*size );
            restore(); //reset coordinate system

        } else if ( size>0. ) {
            drawPoint( QPointF(x, y) );
        }
        break;
    case 14: { // Galaxy cluster - draw a dashed circle
        tempBrush = brush();
        setBrush( QBrush() );
        psize = 1.;
        if ( size > 50. )  psize *= 2.;
        color = pen().color().name();
        save();
        translate( x, y );
        rotate( positionAngle );  //rotate the coordinate system
        QPen newPen = pen();
        newPen.setStyle( Qt::DashLine );
        setPen( newPen );
        lambdaDrawEllipse( dx1, dy1, size, e*size );
        restore();
        setBrush( tempBrush );
        break;
    }
    default: // Unknown object or something we don't know how to draw. Just draw an ellipse with a ?-mark
        color = pen().color().name();
        if ( size <1. && zoom > 20*MINZOOM ) size = 3.; //force ellipse above zoomFactor 20
        if ( size <1. && zoom > 5*MINZOOM ) size = 1.; //force points above zoomFactor 5
        if ( size>2. ) {
            save();
            QFont f = font();
            const QString qMark = " ? ";
            double scaleFactor = 0.8 * size / fontMetrics().width( qMark );
            f.setPointSizeF( f.pointSizeF() * scaleFactor );
            setFont( f );
            translate( x, y );
            rotate( positionAngle );  //rotate the coordinate system
            lambdaDrawEllipse( dx1, dy1, size, e*size );
            if ( Options::useAntialias() )
                drawText( QRectF(dx1, dy1, size, e*size), Qt::AlignCenter, qMark );
            else {
                int idx1 = int(dx1); int idy1 = int(dy1);
                drawText( QRect(idx1, idy1, isize, int(e*size)), Qt::AlignCenter, qMark );
            }
            restore(); //reset coordinate system (and font?)
        }
        else if ( size>0. ) {
            if ( Options::useAntialias() )
                drawPoint( QPointF(x, y) );
            else
                drawPoint( QPoint( x, y ) );
        }
    }

}
Example #15
0
void Draw_Triangle::updateEdgeRects()
{


  handles[0]->setRect(QRectF(QPointF(item->boundingRect().topLeft().x()-5.0,item->boundingRect().topLeft().y()-5.0),QPointF(item->boundingRect().topLeft().x()+5.0,item->boundingRect().topLeft().y()+5.0)));
  handles[1]->setRect(QRectF(QPointF(item->boundingRect().topLeft().x()-5.0,((item->boundingRect().topLeft().y()+StrtPnt.y())/2)-5.0),QPointF(item->boundingRect().topLeft().x()+5.0,((item->boundingRect().topLeft().y()+StrtPnt.y())/2)+5.0)));
  handles[2]->setRect(QRectF(QPointF(item->boundingRect().topRight().x()-5.0,item->boundingRect().topRight().y()-5.0),QPointF(item->boundingRect().topRight().x()+5.0,item->boundingRect().topRight().y()+5.0)));
  handles[3]->setRect(QRectF(QPointF(item->boundingRect().topRight().x()-5.0,((item->boundingRect().topRight().y()+EndPnt.y())/2)-5.0),QPointF(item->boundingRect().topRight().x()+5.0,((item->boundingRect().topRight().y()+EndPnt.y())/2)+5.0)));
  handles[4]->setRect(QRectF(QPointF(StrtPnt.x()-5.0,StrtPnt.y()-5.0),QPointF(StrtPnt.x()+5.0,StrtPnt.y()+5.0)));
  handles[6]->setRect(QRectF(QPointF(EndPnt.x()-5.0,EndPnt.y()-5.0),QPointF(EndPnt.x()+5.0,EndPnt.y()+5.0)));
  handles[5]->setRect(QRectF(QPointF(((StrtPnt.x()+EndPnt.x())/2)-5.0,StrtPnt.y()-5.0),QPointF((StrtPnt.x()+EndPnt.x())/2+5.0,StrtPnt.y()+5.0)));
  handles[7]->setRect(QRectF(QPointF(HeightPnt.x()-5.0,HeightPnt.y()-5.0),QPointF(HeightPnt.x()+5.0,HeightPnt.y()+5.0)));



  Bounding_Rect->setRect(QRectF(item->boundingRect().topLeft(),item->boundingRect().bottomRight()));

    QPointF pnt1,pnt2;

    pnt1.setX(((item->boundingRect().topLeft().x()+item->boundingRect().bottomRight().x())/2)-5);
    pnt1.setY(item->boundingRect().topLeft().y()-20);

    pnt2.setX(((item->boundingRect().topLeft().x()+item->boundingRect().bottomRight().x())/2)+5);
    pnt2.setY(item->boundingRect().topLeft().y()-10);

    Rot_Rect->setRect(QRectF(pnt1,pnt2));

}
Example #16
0
void ezTimeWidget::UpdateStats()
{
  if (!isVisible())
    return;

  if (!ezTelemetry::IsConnectedToServer())
  {
    ListClocks->setEnabled(false);
    return;
  }

  ListClocks->setEnabled(true);

  if (m_bClocksChanged)
  {
    m_bClocksChanged = false;

    ListClocks->blockSignals(true);
    ListClocks->clear();

    for (ezMap<ezString, ezTimeWidget::ClockData>::Iterator it = m_ClockData.GetIterator(); it.IsValid(); ++it)
    {
      ListClocks->addItem(it.Key().GetData());

      QListWidgetItem* pItem = ListClocks->item(ListClocks->count() - 1);
      pItem->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsUserCheckable);
      pItem->setCheckState (it.Value().m_bDisplay ? Qt::Checked : Qt::Unchecked);
      pItem->setData(Qt::UserRole, QString(it.Key().GetData()));

      pItem->setTextColor(s_Colors[it.Value().m_iColor % s_uiMaxColors]);

      it.Value().m_pListItem = pItem;
    }

    ListClocks->blockSignals(false);
  }

  QPainterPath pp[s_uiMaxColors];

  ezTime tMin = ezTime::Seconds(100.0);
  ezTime tMax = ezTime::Seconds(0.0);

  for (ezMap<ezString, ClockData>::Iterator it = s_pWidget->m_ClockData.GetIterator(); it.IsValid(); ++it)
  {
    if (it.Value().m_TimeSamples.IsEmpty() || !it.Value().m_bDisplay)
      continue;

    const ezUInt32 uiColorPath = it.Value().m_iColor % s_uiMaxColors;
    ClockData& Clock = it.Value();
    const ezDeque<TimeSample>& Samples = Clock.m_TimeSamples;

    ezUInt32 uiFirstSample = 0;

    while ((uiFirstSample < Samples.GetCount()) && (m_MaxGlobalTime - Samples[uiFirstSample].m_AtGlobalTime > m_DisplayInterval))
      ++uiFirstSample;

    if (uiFirstSample < Samples.GetCount())
    {
      pp[uiColorPath].moveTo (QPointF((Samples[uiFirstSample].m_AtGlobalTime - m_MaxGlobalTime).GetSeconds(), Samples[uiFirstSample].m_Timestep.GetSeconds()));

      for (ezUInt32 i = uiFirstSample + 1; i < Samples.GetCount(); ++i)
      {
        pp[uiColorPath].lineTo (QPointF ((Samples[i].m_AtGlobalTime - m_MaxGlobalTime).GetSeconds(), Samples[i].m_Timestep.GetSeconds()));

        tMin = ezMath::Min(tMin, Samples[i].m_Timestep);
        tMax = ezMath::Max(tMax, Samples[i].m_Timestep);
      }
    }
  }

  for (ezUInt32 i = 0; i < s_uiMaxColors; ++i)
    m_pPath[i]->setPath(pp[i]);

  // render the helper lines for time values
  {
    QPainterPath pMax;

    for (ezUInt32 i = 1; i < 10; ++i)
    {
      pMax.moveTo(QPointF (-m_DisplayInterval.GetSeconds(), ezTime::Milliseconds(10.0 * i).GetSeconds()));
      pMax.lineTo(QPointF (0, ezTime::Milliseconds(10.0 * i).GetSeconds()));
    }

    m_pPathMax->setPath(pMax);
  }

  ezTime tShowMax = ezTime::Seconds(1.0 / 10.0);

  for (ezUInt32 t = 25; t < 100; t += 25)
  {
    tShowMax = ezTime::Milliseconds(1) * t;

    if (tMax < tShowMax)
      break;
  }

  {
    TimeView->setSceneRect (QRectF (-m_DisplayInterval.GetSeconds(), 0, m_DisplayInterval.GetSeconds(), tShowMax.GetSeconds()));
    TimeView->fitInView    (QRectF (-m_DisplayInterval.GetSeconds(), 0, m_DisplayInterval.GetSeconds(), tShowMax.GetSeconds()));
  }

  // once a second update the display of the clocks in the list
  if (ezTime::Now() - m_LastUpdatedClockList > ezTime::Seconds(1))
  {
    m_LastUpdatedClockList = ezTime::Now();

    ezStringBuilder s;
    s.Format("Max: %.0fms", tShowMax.GetMilliseconds());
    LabelMaxTime->setText(s.GetData());

    for (ezMap<ezString, ezTimeWidget::ClockData>::Iterator it = m_ClockData.GetIterator(); it.IsValid(); ++it)
    {
      const ezTimeWidget::ClockData& Clock = it.Value();

      if (!Clock.m_pListItem || Clock.m_TimeSamples.IsEmpty())
        continue;

      ezStringBuilder sTooltip;
      sTooltip.Format("<p>Clock: %s<br>Max Time Step: <b>%.2fms</b><br>Min Time Step: <b>%.2fms</b><br></p>",
        it.Key().GetData(), Clock.m_MaxTimestep.GetMilliseconds(), Clock.m_MinTimestep.GetMilliseconds());

      Clock.m_pListItem->setToolTip(sTooltip.GetData());
    }
  }
}
Example #17
0
void Draw_Triangle::setEdgeRects()
{
    QBrush rectbrush;
    rectbrush.setColor(QColor(0,175,225));
    rectbrush.setStyle(Qt::SolidPattern);
    qDebug()<<"strt pnt "<<StrtPnt<<" "<<"end pnt "<<EndPnt<<"\n";

  QGraphicsRectItem *rect = new QGraphicsRectItem(QRectF(QPointF(item->boundingRect().topLeft().x()-5.0,item->boundingRect().topLeft().y()-5.0),QPointF(item->boundingRect().topLeft().x()+5.0,item->boundingRect().topLeft().y()+5.0)));
    rect->setBrush(rectbrush);

  handles.push_back(rect);

  rect = new QGraphicsRectItem(QRectF(QPointF(item->boundingRect().topLeft().x()-5.0,(item->boundingRect().topLeft().y()+25)-5.0),QPointF(item->boundingRect().topLeft().x()+5.0,(item->boundingRect().topLeft().y()+25)+5.0)));
    rect->setBrush(rectbrush);

  handles.push_back(rect);

  rect = new QGraphicsRectItem(QRectF(QPointF(item->boundingRect().topRight().x()-5.0,item->boundingRect().topRight().y()-5.0),QPointF(item->boundingRect().topRight().x()+5.0,item->boundingRect().topRight().y()+5.0)));
    rect->setBrush(rectbrush);

  handles.push_back(rect);

  rect = new QGraphicsRectItem(QRectF(QPointF(item->boundingRect().topRight().x()-5.0,(item->boundingRect().topRight().y()+25)-5.0),QPointF(item->boundingRect().topRight().x()+5.0,(item->boundingRect().topRight().y()+25)+5.0)));
    rect->setBrush(rectbrush);

  handles.push_back(rect);

    rect = new QGraphicsRectItem(QRectF(QPointF(StrtPnt.x()-5.0,StrtPnt.y()-5.0),QPointF(StrtPnt.x()+5.0,StrtPnt.y()+5.0)));
    rect->setBrush(rectbrush);

  handles.push_back(rect);

  rect = new QGraphicsRectItem(QRectF(QPointF((StrtPnt.x()+50)-5.0,StrtPnt.y()-5.0),QPointF((StrtPnt.x()+50)+5.0,StrtPnt.y()+5.0)));
    rect->setBrush(rectbrush);

  handles.push_back(rect);

    rect = new QGraphicsRectItem(QRectF(QPointF(EndPnt.x()-5.0,EndPnt.y()-5.0),QPointF(EndPnt.x()+5.0,EndPnt.y()+5.0)));
    rect->setBrush(rectbrush);

  handles.push_back(rect);

    rect = new QGraphicsRectItem(QRectF(QPointF(HeightPnt.x()-5.0,HeightPnt.y()-5.0),QPointF(HeightPnt.x()+5.0,HeightPnt.y()+5.0)));
    rect->setBrush(rectbrush);

  handles.push_back(rect);

    QPen bound_rect;
    bound_rect.setStyle(Qt::DashLine);
    Bounding_Rect = new QGraphicsRectItem(QRectF(item->boundingRect().topLeft(),item->boundingRect().bottomRight()));
    Bounding_Rect->setPen(bound_rect);

    QPointF pnt1,pnt2;

    pnt1.setX(((item->boundingRect().topLeft().x()+item->boundingRect().bottomRight().x())/2)-5);
    pnt1.setY(item->boundingRect().topLeft().y()-20);

    pnt2.setX(((item->boundingRect().topLeft().x()+item->boundingRect().bottomRight().x())/2)+5);
    pnt2.setY(item->boundingRect().topLeft().y()-10);

    Rot_Rect = new QGraphicsEllipseItem(QRectF(pnt1,pnt2));
    Rot_Rect->setBrush(rectbrush);


}
Example #18
0
	void GlanceShower::Start ()
	{
		if (!TabWidget_)
		{
			qWarning () << Q_FUNC_INFO
				<< "no tab widget set";
			return;
		}

		int count = TabWidget_->count ();
		if (count < 2)
			return;

		QSequentialAnimationGroup *animGroup = new QSequentialAnimationGroup;

		int sqr = std::sqrt ((double)count);
		int rows = sqr;
		int cols = sqr;
		if (rows * cols < count)
			++cols;
		if (rows * cols < count)
			++rows;

		QRect screenGeom = QApplication::desktop ()->
				screenGeometry (Core::Instance ().GetReallyMainWindow ());
		int width = screenGeom.width ();
		int height = screenGeom.height ();

		int singleW = width / cols;
		int singleH = height / rows;

		int wW = singleW * 4 / 5;
		int wH = singleH * 4 / 5;

		qreal scaleFactor = 0;
		QSize sSize;

		int animLength = 500 / (sqr);

		QProgressDialog pg;
		pg.setMinimumDuration (1000);
		pg.setRange (0, count);

		for (int row = 0; row < rows; ++row)
			for (int column = 0;
					column < cols && column + row * cols < count;
					++column)
			{
				int idx = column + row * cols;
				pg.setValue (idx);
				QWidget *w = TabWidget_->widget (idx);

				if (!sSize.isValid ())
					sSize = w->size () / 2;
				if (sSize != w->size ())
					w->resize (sSize * 2);

				if (!scaleFactor)
					scaleFactor = std::min (static_cast<qreal> (wW) / sSize.width (),
							static_cast<qreal> (wH) / sSize.height ());

				QPixmap pixmap (sSize * 2);
				w->render (&pixmap);
				pixmap = pixmap.scaled (sSize,
						Qt::IgnoreAspectRatio, Qt::SmoothTransformation);

				{
					QPainter p (&pixmap);
					QPen pen (Qt::black);
					pen.setWidth (2 / scaleFactor + 1);
					p.setPen (pen);
					p.drawRect (QRect (QPoint (0, 0), sSize));
				}

				GlanceItem *item = new GlanceItem (pixmap);
				item->SetIndex (idx);
				connect (item,
						SIGNAL (clicked (int)),
						this,
						SLOT (handleClicked (int)));

				Scene_->addItem (item);
				item->setTransformOriginPoint (sSize.width () / 2, sSize.height () / 2);
				item->setScale (scaleFactor);
				item->SetIdealScale (scaleFactor);
				item->setOpacity (0);
				item->moveBy (column * singleW, row * singleH);

				QParallelAnimationGroup *pair = new QParallelAnimationGroup;

				QPropertyAnimation *posAnim = new QPropertyAnimation (item, "Pos");
				posAnim->setDuration (animLength);
				posAnim->setStartValue (QPointF (0, 0));
				posAnim->setEndValue (QPointF (column * singleW, row * singleH));
				posAnim->setEasingCurve (QEasingCurve::OutSine);
				pair->addAnimation (posAnim);

				QPropertyAnimation *opacityAnim = new QPropertyAnimation (item, "Opacity");
				opacityAnim->setDuration (animLength);
				opacityAnim->setStartValue (0.);
				opacityAnim->setEndValue (1.);
				pair->addAnimation (opacityAnim);

				animGroup->addAnimation (pair);
			}

		setScene (Scene_);

		setGeometry (screenGeom);
		animGroup->start ();
		show ();
	}
Example #19
0
QRectF QPageLayoutPrivate::fullRect() const
{
    return QRectF(QPointF(0, 0), m_fullSize);
}
void PaneWidget::mouseDoubleClickEvent(QMouseEvent *)
{
    // using setValue directly breaks animations
    pressing(screenMap(QPointF(0, 0)));
}
KisPropertiesConfigurationTest::KisPropertiesConfigurationTest() :
        v1(10), v2("hello"), v3(1242.0), v4(true)
{
    QList<QPointF> pts; pts.push_back(QPointF(0.2, 0.3)); pts.push_back(QPointF(0.5, 0.7));
    v5.setPoints(pts);
}
//-----------------------------------------------------------------------------
void ctkTransferFunctionRepresentation::computeCurve()
{
  Q_D(ctkTransferFunctionRepresentation);

  int count = d->TransferFunction ? d->TransferFunction->count() : 0;
  if (count <= 0)
    {
    return;
    }

  d->TransferFunction->range(d->WorldRangeX[0], d->WorldRangeX[1]);
  d->WorldRangeY[0] = this->posY(d->TransferFunction->minValue());
  d->WorldRangeY[1] = this->posY(d->TransferFunction->maxValue());

  d->RangeXDiff   = this->computeRangeXDiff(d->rect(), d->WorldRangeX);
  d->RangeXOffSet = this->computeRangeXOffset(d->WorldRangeX);

  d->RangeYDiff   = this->computeRangeYDiff(d->rect(), d->WorldRangeY);
  d->RangeYOffSet = this->computeRangeYOffset(d->WorldRangeY);

  ctkControlPoint* startCP = d->TransferFunction->controlPoint(0);
  ctkControlPoint* nextCP = 0;

  QPointF startPos = this->mapPointToScene(startCP);

  d->Points.clear();
  d->Points << startPos;

  d->Path = QPainterPath();
  d->Path.moveTo(startPos);
  for(int i = 1; i < count; ++i)
    {
    nextCP = d->TransferFunction->controlPoint(i);
    if (this->transferFunction()->isDiscrete())
      {
      QPointF nextPos = this->mapPointToScene(nextCP);
      qreal midPosX = (startPos.x() + nextPos.x()) / 2.;

      d->Path.lineTo(QPointF(midPosX, startPos.y()));
      d->Path.lineTo(QPointF(midPosX, nextPos.y()));

      d->Points << nextPos;
      startPos = nextPos;
      if (i == count -1)
        {
        d->Path.lineTo(nextPos);
        }
      }
    else if (dynamic_cast<ctkNonLinearControlPoint*>(startCP))
      {
      QList<ctkPoint> points = this->nonLinearPoints(startCP, nextCP);
      int j;
      for (j = 1; j < points.count(); ++j)
        {
        d->Path.lineTo(this->mapPointToScene(points[j]));
        }
      j = points.count() - 1;
      d->Points << this->mapPointToScene(points[j]);
      }
    else //dynamic_cast<ctkBezierControlPoint*>(startCP))
      {
      QList<ctkPoint> points = this->bezierParams(startCP, nextCP);
      QList<ctkPoint>::iterator it = points.begin();
      QList<QPointF> bezierPoints;
      foreach(const ctkPoint& p, points)
        {
        bezierPoints << this->mapPointToScene(p);
        }
      d->Path.cubicTo(bezierPoints[1], bezierPoints[2], bezierPoints[3]);
      d->Points << bezierPoints[3];
      }
    //qDebug() << i << points[0] << points[1] << points[2] << points[3];
    delete startCP;
    startCP = nextCP;
    }
 //------------------------------------------------------------------------------------------------------
 QPointF EqnSideItem::expressionPosition() const
 {
   return m_EqnItem != NULL ? m_EqnItem->position() : QPointF();
 }
Example #24
0
void HoldLine::paintEvent(QPaintEvent *event){
  QPainter painter(this);

  painter.setBackgroundMode (Qt::TransparentMode);
  painter.drawPixmap(QPointF(0,0),QPixmap("grass.png"));

  painter.drawLine(QPoint(0,600),QPoint(400,600));

  if(gameOver && enemyCount < MAXENEMIES){
    QFont font("Courier",15,QFont::DemiBold);
    QFontMetrics fm(font);
    int textWidth = fm.width("Game Over");

    painter.setFont(font);
    int h = height();
    int w = width();

    painter.translate(QPoint(w/2,h/2));
    painter.drawText(-textWidth/2,0,"GameOver");
    painter.drawText(-textWidth/2-50,30,"Press S to Restart");
    deleteEnemies();
    enemyList.resize(0);
    MAXENEMIES = 10;
    points = 0;
    level = 0;
  }
  else if(gameOver && enemyCount == MAXENEMIES && level < 3){
      QFont font("Courier",15,QFont::DemiBold);
      QFontMetrics fm(font);
      int textWidth = fm.width("Level Complete");

      painter.setFont(font);
      int h = height();
      int w = width();

      painter.translate(QPoint(w/2,h/2));
      painter.drawText(-textWidth/2,0,"Level Complete");
      painter.drawText(-textWidth/2-90,30,"Press S to go to Next Level");

  }

  else if(gameOver && enemyCount == MAXENEMIES && level == 3){
      QFont font("Courier",15,QFont::DemiBold);
      QFontMetrics fm(font);
      int textWidth = fm.width("You Held the Line");
      QString Score = "Score: ";
      Score.append(QString("%1").arg(points));

      painter.setFont(font);
      int h = height();
      int w = width();

      painter.translate(QPoint(w/2,h/2));
      painter.drawText(-textWidth/2-30,0,"You Held the Line");
      painter.drawText(-textWidth/2,30, Score);
      painter.drawText(-textWidth/2-20,60,"Press S to Restart");
      deleteEnemies();
      enemyList.resize(0);
      MAXENEMIES = 10;
      level = 0;
      points = 0;
  }

  else if(!gameStarted){
      QFont font("Courier",15,QFont::DemiBold);
      QFontMetrics fm(font);
      int textWidth = fm.width("Hold The Line");

      painter.setFont(font);
      int h = height();
      int w = width();

      painter.translate(QPoint(w/2,h/2));
      painter.drawText(-textWidth/2,0,"Hold The Line");
      painter.drawText(-textWidth/2-35,30,"Press S to Start");
  }
  else{
   painter.drawImage(prot->getRect(), prot->getImage());

   if(!protect->isDestroyed())
      painter.drawImage(protect->getRect(),protect->getImage());

   if(!protectItem->isDestroyed())
      painter.drawPixmap(protectItem->getRect(),protectItem->getImage());

   painter.drawPixmap(quiver->getRect(),quiver->getImage());
   painter.drawPixmap(trapBag->getRect(),trapBag->getImage());
	
   for(int i = 0; i < enemyList.size(); i++){
       if(!(enemyList[i]->isDestroyed()) && enemyList[i]->getRect().top() < 700)
       painter.drawPixmap(enemyList[i]->getRect(), enemyList[i]->getImage());
   }

   for(int i = 0; i < bulletList.size(); i++){
     if(!(bulletList[i]->isDestroyed()))
       painter.drawImage(bulletList[i]->getRect(), bulletList[i]->getImage());
   }

   for(int i = 0; i < arrowList.size(); i++){
     if(!(arrowList[i]->isDestroyed()))
       painter.drawImage(arrowList[i]->getRect(), arrowList[i]->getImage());
   }

   for(int i = 0; i < trapList.size(); i++){
     if(!(trapList[i]->isDestroyed()))
       painter.drawPixmap(trapList[i]->getRect(), trapList[i]->getImage());
   }

   for(int i = 0; i < treeList.size(); i++)
       painter.drawPixmap(treeList[i]->getRect(), treeList[i]->getImage());


   QString UI = "Arrow: ";
   UI.append(QString("%1").arg(remainingArrows));
   UI += "  Lives: ";
   UI.append(QString("%1").arg(prot->getLives()));
   UI += "  Traps: ";
   UI.append(QString("%1").arg(remainingTraps));
   QFont font("Courier",15,QFont::DemiBold);
   painter.setFont(font);
   painter.drawText(QPoint(10,12), UI);
   QString bla = "Score: ";
   bla.append(QString("%1").arg(enemyCount));
   painter.drawText(QPoint(10,42), bla);
  }//end else


}
QPointF creatPoint()
{
    qreal x = int(20.0 * (rand() / (RAND_MAX + 1.0)));
    qreal y = int(20.0 * (rand() / (RAND_MAX + 1.0)));
    return QPointF(x, y);
}
Example #26
0
QRectF UBGraphicsTextItem::boundingRect() const
{
    qreal width = textWidth();
    qreal height = textHeight();
    return QRectF(QPointF(), QSizeF(width, height));
}
 ControlPoint()
 {
     currentIndex = 0;
     points << QPointF(10,50) << QPointF(60,50);
 }
void QModernProgressWidget::paintEvent(QPaintEvent *event) {
    QWidget::paintEvent(event);
    QPixmap m_pix(width(), height());

    //if (m_doRepaint) {
        m_doRepaint=false;
        QPen pen;
        pen.setWidthF(1.0);

        double wid=qMin(height(), width());
        double displayFrac=(double)(m_value-m_rangeMin)/(double)(m_rangeMax-m_rangeMin);
        int currentItem=qMax(0, qMin(m_items, (int)round(displayFrac*(double)m_items)));
        int lastItem=round(m_nonBackgroundRange*(double)m_items);
        if (m_spin) currentItem=m_spinItem;
        if (!m_spin) lastItem=currentItem;
        //if (!m_spin) std::cout<<"m_value="<<m_value<<"   currentItem="<<currentItem<<std::endl;
        QPointF center=QPointF(width()/2.0, height()/2.0);

        double rIn=wid/2.0*m_innerRadius;
        double rOut=wid/2.0*m_outerRadius;
        if (rIn>rOut) qSwap(rIn, rOut);

        //                           2*M_PI
        double strokeWidth=qMax(1.0, 6.283 * rIn/(1.75*(double)m_items));
        double dAngle=360.0/(double)m_items;

        //m_pix.fill(this, 0, 0);
        m_pix.fill(Qt::transparent);

        QPainter painter(&m_pix);

        if (m_mode==QModernProgressWidget::Strokes) {
            QPen strokePen=pen;
            strokePen.setWidthF(strokeWidth);
            strokePen.setCapStyle(Qt::RoundCap);
            strokePen.setJoinStyle(Qt::RoundJoin);
            painter.save();
                painter.setRenderHint(QPainter::Antialiasing, true);
                painter.translate(center);
                if (m_spin) painter.rotate(-dAngle*(double)currentItem);
                else painter.rotate(-180);
                for (int i=0; i<m_items; i++) {
                    strokePen.setColor(m_backgroundColor);
                    //double frac=(double)i/(double)(m_items-1.0);

                    if (i<lastItem) {
                        const double r=m_startColor.redF();
                        const double g=m_startColor.greenF();
                        const double b=m_startColor.blueF();
                        const double re=m_stopColor.redF();
                        const double ge=m_stopColor.greenF();
                        const double be=m_stopColor.blueF();
                        double f=(double)i/(m_nonBackgroundRange*(double)m_items);
                        if (f>1) f=1.0;
                        if (f<0) f=0;
                        f=1.0-f;
                        QColor col;
                        col.setRgbF(r+f*(re-r), g+f*(ge-g), b+f*(be-b));
                        strokePen.setColor(col);
                    }
                    //if (fabs(frac-displayFrac)<=1.0/(double)m_items) strokePen.setColor(m_indicatorColor);
                    if (i==0) strokePen.setColor(m_indicatorColor);
                    painter.setPen(strokePen);
                    painter.drawLine(QLineF(0, rIn, 0, rOut));
                    painter.rotate(dAngle);
                }
            painter.restore();
        } else if (m_mode==QModernProgressWidget::Circles) {
            painter.save();
                painter.setRenderHint(QPainter::Antialiasing, true);
                painter.translate(center);
                if (m_spin) painter.rotate(-dAngle*(double)currentItem);
                else painter.rotate(-180);
                for (int i=0; i<m_items; i++) {
                    //double frac=(double)i/(double)(m_items-1.0);

                    QColor col=m_backgroundColor;

                    if (i<lastItem) {
                        const double r=m_startColor.redF();
                        const double g=m_startColor.greenF();
                        const double b=m_startColor.blueF();
                        const double re=m_stopColor.redF();
                        const double ge=m_stopColor.greenF();
                        const double be=m_stopColor.blueF();
                        double f=(double)i/(m_nonBackgroundRange*(double)m_items);
                        if (f>1) f=1.0;
                        if (f<0) f=0;
                        f=1.0-f;
                        col.setRgbF(r+f*(re-r), g+f*(ge-g), b+f*(be-b));
                    }
                    //if (fabs(frac-displayFrac)<=1.0/(double)m_items) strokePen.setColor(m_indicatorColor);
                    if (i==0) col=m_indicatorColor;
                    QBrush circleBrush(col);
                    QPen circlePen=QPen(col.darker(150));
                    painter.setBrush(circleBrush);
                    if (m_darkCircleBorder) {
                        painter.setPen(circlePen);
                    } else {
                        painter.setPen(QColor(Qt::transparent));
                    }
                    double d=(rOut-rIn)/2.0;
                    painter.drawEllipse(0, (rIn+rOut)/2.0, d, d);
                    painter.rotate(dAngle);
                }
            painter.restore();
        } else if (m_mode==QModernProgressWidget::GradientRing) {
            painter.save();
                QPainterPath path;
                path.setFillRule( Qt::OddEvenFill );
                path.addEllipse( QPointF(0,0), rOut, rOut );
                path.addEllipse( QPointF(0,0), rIn, rIn );

                painter.translate(center);
                if (m_spin) painter.rotate(-dAngle*(double)currentItem);
                else painter.rotate(-90);

                // Draw the ring background
                painter.setPen( Qt::NoPen );
                painter.setBrush( m_backgroundColor );
                painter.setRenderHint( QPainter::Antialiasing );
                painter.drawPath( path );

                // Draw the ring foreground
                QConicalGradient gradient( QPointF(0,0), 0.0 );
                if (m_spin) {
                    gradient.setColorAt( 0.0, m_backgroundColor );
                    gradient.setColorAt( qMax(0.0,(double)lastItem/(double)m_items-0.05), m_indicatorColor );
                    gradient.setColorAt( (double)lastItem/(double)m_items, m_backgroundColor );
                    painter.setBrush( gradient );
                } else {
                    double gfrac=qMax(0.0, qMin(1.0, 1.0-displayFrac));
                    //std::cout<<gfrac<<std::endl;
                    if ((fabs(gfrac)<=0.02)) {
                        painter.setBrush(QBrush(m_indicatorColor));
                    } else if (fabs(gfrac)>0.85) {
                        /*QColor cColor=m_indicatorColor;
                        cColor.setRedF(cColor.redF()+fabs(gfrac)/0.85*(m_backgroundColor.redF()-cColor.redF()));
                        cColor.setGreenF(cColor.greenF()+fabs(gfrac)/0.85*(m_backgroundColor.greenF()-cColor.greenF()));
                        cColor.setBlueF(cColor.blueF()+fabs(gfrac)/0.85*(m_backgroundColor.blueF()-cColor.blueF()));*/
                        QColor cColor=linColor(m_indicatorColor, m_backgroundColor, (gfrac-0.85)/0.15);
                        gradient.setColorAt( 0.05, m_backgroundColor );
                        gradient.setColorAt( 0.0, cColor );
                        gradient.setColorAt( 0.8, m_backgroundColor );
                        gradient.setColorAt( gfrac, cColor );
                        painter.setBrush( gradient );
                    } else if (fabs(gfrac)<0.15) {
                        /*QColor cColor=m_backgroundColor;
                        cColor.setRedF(m_indicatorColor.redF()-fabs(gfrac)/0.15*(m_indicatorColor.redF()-cColor.redF()));
                        cColor.setGreenF(m_indicatorColor.greenF()-fabs(gfrac)/0.15*(m_indicatorColor.greenF()-cColor.greenF()));
                        cColor.setBlueF(m_indicatorColor.blueF()-fabs(gfrac)/0.15*(m_indicatorColor.blueF()-cColor.blueF()));*/
                        QColor cColor=linColor(m_indicatorColor, m_backgroundColor, gfrac/0.15);
                        gradient.setColorAt( 0.0, m_indicatorColor );
                        gradient.setColorAt( gfrac/2.0, cColor );
                        gradient.setColorAt( gfrac, m_indicatorColor );
                        painter.setBrush( gradient );
                    } else {
                        gradient.setColorAt( 0.0, m_indicatorColor );
                        gradient.setColorAt( 0.05, m_backgroundColor );
                        gradient.setColorAt( qMax(0.0, gfrac-0.05), m_backgroundColor );
                        gradient.setColorAt( qMin(1.0, gfrac), m_indicatorColor );
                        painter.setBrush( gradient );
                    }
                }
                painter.drawPath( path );
            painter.restore();
        }

        if (m_displayPercent && ( (m_mode==QModernProgressWidget::Circles) || (m_mode==QModernProgressWidget::Strokes) || (m_mode==QModernProgressWidget::GradientRing) ) ) {
            painter.save();
            QFont f=font();
            QString s="";
            if (m_percentageMode==QModernProgressWidget::Percent) {
                s=QString::number(100.0*(double)(m_value-m_rangeMin)/(double)(m_rangeMax-m_rangeMin), 'f', m_precision)+"%";
            } else {
                s=QString::number(m_value, 'f', m_precision)+m_suffix;
            }
            QRect bound=QFontMetrics(f).boundingRect("100%");
            double r=sqrt( (bound.width()/2.0)*(bound.width()/2.0) + (bound.height()/2.0)*(bound.height()/2.0) );
            while ((f.pointSize()>5)&&(r>rIn)) {
                f.setPointSizeF(f.pointSizeF()-0.5);
                bound=QFontMetrics(f).boundingRect("100%");
                r=sqrt( (bound.width()/2.0)*(bound.width()/2.0) + (bound.height()/2.0)*(bound.height()/2.0) );
            }
            bound=QFontMetrics(f).boundingRect(s);
            painter.setFont(f);
            painter.setPen(m_textColor);
            painter.drawText(width()/2-bound.width()/2, height()/2+QFontMetrics(f).ascent()/2, s);
            painter.restore();
        }
    //}
    QPainter p(this);
    p.drawPixmap(QPoint(0,0), m_pix);
}
Example #29
0
void QStaticTextPrivate::paintText(const QPointF &topLeftPosition, QPainter *p)
{
    bool preferRichText = textFormat == Qt::RichText
                          || (textFormat == Qt::AutoText && Qt::mightBeRichText(text));

    if (!preferRichText) {
        QTextLayout textLayout;
        textLayout.setText(text);
        textLayout.setFont(font);
        textLayout.setTextOption(textOption);
        textLayout.setCacheEnabled(true);

        qreal leading = QFontMetricsF(font).leading();
        qreal height = -leading;

        textLayout.beginLayout();
        while (1) {
            QTextLine line = textLayout.createLine();
            if (!line.isValid())
                break;

            if (textWidth >= 0.0)
                line.setLineWidth(textWidth);
            height += leading;
            line.setPosition(QPointF(0.0, height));
            height += line.height();
        }
        textLayout.endLayout();

        actualSize = textLayout.boundingRect().size();
        textLayout.draw(p, topLeftPosition);
    } else {
        QTextDocument document;
#ifndef QT_NO_CSSPARSER
        QColor color = p->pen().color();
        document.setDefaultStyleSheet(QString::fromLatin1("body { color: #%1%2%3 }")
                                      .arg(QString::number(color.red(), 16), 2, QLatin1Char('0'))
                                      .arg(QString::number(color.green(), 16), 2, QLatin1Char('0'))
                                      .arg(QString::number(color.blue(), 16), 2, QLatin1Char('0')));
#endif
        document.setDefaultFont(font);
        document.setDocumentMargin(0.0);        
#ifndef QT_NO_TEXTHTMLPARSER
        document.setHtml(text);
#else
        document.setPlainText(text);
#endif
        if (textWidth >= 0.0)
            document.setTextWidth(textWidth);
        else
            document.adjustSize();
        document.setDefaultTextOption(textOption);

        p->save();
        p->translate(topLeftPosition);
        QAbstractTextDocumentLayout::PaintContext ctx;
        ctx.palette.setColor(QPalette::Text, p->pen().color());
        document.documentLayout()->draw(p, ctx);
        p->restore();

        if (textWidth >= 0.0)
            document.adjustSize(); // Find optimal size

        actualSize = document.size();
    }
}
  void TOPPASEdge::paint(QPainter * painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/)
  {
    painter->setBrush(Qt::white);

    QPen pen(color_);
    if (isSelected())
    {
      pen.setWidth(3);
    }
    else
    {
      pen.setWidth(2);
    }

    TOPPASToolVertex* ttv_source = qobject_cast<TOPPASToolVertex*>(this->getSourceVertex());
    // when copying parameters (using CTRL); only for incomplete edges drawn from tool nodes
    if (QApplication::keyboardModifiers() && Qt::ControlModifier && !this->to_ && ttv_source)
    {
      pen.setColor(Qt::darkMagenta);
      pen.setWidth(1);
    }

    painter->setPen(pen);

    // angle of line
    qreal angle = -QLineF(endPos(), startPos()).angle() + 180; // negate since angle() reports counter-clockwise; +180 since painter.rotate() is more intuivite then

    // draw the actual line
    QPainterPath path_line(startPos());
    path_line.lineTo(endPos());
    painter->drawPath(path_line);

    // print names
    qreal text_angle = angle;
    bool invert_text_direction = endPos().x() < startPos().x();
    if (invert_text_direction)
    {
      text_angle += 180;
    }
    QPainterPath path_line_short(borderPoint_(false));
    path_line_short.lineTo(endPos());

    // y offset for printing text; we add -1 to make "_" in param names visible (e.g. in "out_annotation")
    //                             otherwise they are too close to the edge itself
    int y_text = -pen.width() - 1;

    // source name
    QString str = getSourceOutParamName();
    if (!str.isEmpty())
    {
      painter->save();     // hard to avoid multiple calls to save() and restore() since we first translate and then rotate
      QPointF point = path_line_short.pointAtPercent(0.05);
      painter->translate(point);
      painter->rotate(text_angle);
      if (invert_text_direction)
      {
        QFontMetrics fm(painter->fontMetrics());
        int text_width=fm.width(str);
        painter->drawText(QPoint(-text_width, y_text), str);
      }
      else
      {
        painter->drawText(QPoint(0, y_text), str);
      }
      painter->restore();
    }
    // target name
    const qreal arrow_width = 10; // required multiple times, so defined here to avoid inconsistencies
    str = getTargetInParamName();
    if (!str.isEmpty())
    {
      painter->save();
      // qreal pc = path_line_short.percentAtLength(10);
      QPointF point = path_line_short.pointAtPercent(0.95);
      painter->translate(point);
      painter->rotate(text_angle);
      QFontMetrics fm(painter->fontMetrics());
      int text_width = fm.width(str);
      int text_height = fm.height();   // shift text below the edge by its own height
      if (invert_text_direction)
      {
        painter->drawText(QPoint(arrow_width, text_height + y_text), str);
      }
      else
      {
        painter->drawText(QPoint(-text_width - arrow_width, text_height + y_text), str);
      }
      painter->restore();
    }

    // draw arrow head
    painter->save();
    painter->translate(endPos());
    painter->rotate(angle);
    QPainterPath path;
    path.moveTo(QPointF(0, 0));
    path.lineTo(QPointF(-arrow_width, 4));
    path.lineTo(QPointF(-arrow_width, -4));
    path.closeSubpath();
    painter->drawPath(path);
    painter->restore();
  }