コード例 #1
0
ファイル: KoRuler.cpp プロジェクト: IGLOU-EU/krita
void VerticalPaintingStrategy::drawMeasurements(const KoRulerPrivate *d, QPainter &painter, const QRectF &rectangle)
{
    qreal numberStep = d->numberStepForUnit(); // number step in unit
    int numberStepPixel = qRound(d->viewConverter->documentToViewY( d->unit.fromUserValue(numberStep)));
    if (numberStepPixel <= 0)
        return;

    const QFont font = QFontDatabase::systemFont(QFontDatabase::SmallestReadableFont);
    const QFontMetrics fontMetrics(font);
    painter.setFont(font);

    // Calc the longest text length
    int textLength = 0;

    for(int i = 0; i < lengthInPixel; i += numberStepPixel) {
        int number = qRound((i / numberStepPixel) * numberStep);
        textLength = qMax(textLength, fontMetrics.width(QString::number(number)));
    }
    textLength += 4;  // Add some padding

    if (numberStepPixel == 0 || numberStep == 0)
        return;
    // Change number step so all digits will fit
    while(textLength > numberStepPixel) {
        numberStepPixel += numberStepPixel;
        numberStep += numberStep;
    }

    // Calc the first number step
    const int start = d->offset < 0 ? qAbs(d->offset) : 0;

    // make a little hack so rulers shows correctly inversed number aligned
    int stepCount = (start / numberStepPixel) + 1;
    int halfStepCount = (start / qRound(numberStepPixel * 0.5)) + 1;
    int quarterStepCount = (start / qRound(numberStepPixel * 0.25)) + 1;

    const QPen numberPen(d->ruler->palette().color(QPalette::Text));
    const QPen markerPen(d->ruler->palette().color(QPalette::Inactive, QPalette::Text));
    painter.setPen(markerPen);

    if(d->offset > 0)
        painter.translate(0, d->offset);

    const int len = qRound(rectangle.height()) + start;
    int nextStep = qRound(d->viewConverter->documentToViewY(
        d->unit.fromUserValue(numberStep * stepCount)));
    int nextHalfStep = qRound(d->viewConverter->documentToViewY(d->unit.fromUserValue(
        numberStep * 0.5 * halfStepCount)));
    int nextQuarterStep = qRound(d->viewConverter->documentToViewY(d->unit.fromUserValue(
        numberStep * 0.25 * quarterStepCount)));

    int pos = 0;
    for(int i = start; i < len; ++i) {
        pos = i - start;

        if(i == nextStep) {
            painter.save();
            painter.translate(rectangle.right()-fullStepMarkerLength, pos);
            if(pos != 0)
                painter.drawLine(QPointF(0, 0), QPointF(fullStepMarkerLength-1, 0));

            painter.rotate(-90);
            int number = qRound(stepCount * numberStep);
            QString numberText = QString::number(number);
            painter.setPen(numberPen);
            painter.drawText(QPointF(-fontMetrics.width(numberText) / 2.0, -measurementTextAboveBelowMargin), numberText);
            painter.restore();

            ++stepCount;
            nextStep = qRound(d->viewConverter->documentToViewY(
                d->unit.fromUserValue(numberStep * stepCount)));
            ++halfStepCount;
            nextHalfStep = qRound(d->viewConverter->documentToViewY(d->unit.fromUserValue(
                numberStep * 0.5 * halfStepCount)));
            ++quarterStepCount;
            nextQuarterStep = qRound(d->viewConverter->documentToViewY(d->unit.fromUserValue(
                numberStep * 0.25 * quarterStepCount)));
        } else if(i == nextHalfStep) {
            if(pos != 0)
                painter.drawLine(QPointF(rectangle.right() - halfStepMarkerLength, pos),
                                 QPointF(rectangle.right() - 1, pos));

            ++halfStepCount;
            nextHalfStep = qRound(d->viewConverter->documentToViewY(d->unit.fromUserValue(
                numberStep * 0.5 * halfStepCount)));
            ++quarterStepCount;
            nextQuarterStep = qRound(d->viewConverter->documentToViewY(d->unit.fromUserValue(
                numberStep * 0.25 * quarterStepCount)));
        } else if(i == nextQuarterStep) {
            if(pos != 0)
                painter.drawLine(QPointF(rectangle.right() - quarterStepMarkerLength, pos),
                                 QPointF(rectangle.right() - 1, pos));

            ++quarterStepCount;
            nextQuarterStep = qRound(d->viewConverter->documentToViewY(d->unit.fromUserValue(
                numberStep * 0.25 * quarterStepCount)));
        }
    }

    // Draw the mouse indicator
    const int mouseCoord = d->mouseCoordinate - start;
    if (d->selected == KoRulerPrivate::None || d->selected == KoRulerPrivate::HotSpot) {
        const qreal left = rectangle.left() + 1;
        const qreal right = rectangle.right() -1;
        if (d->selected == KoRulerPrivate::None && d->showMousePosition && mouseCoord > 0 && mouseCoord < rectangle.height() )
            painter.drawLine(QPointF(left, mouseCoord), QPointF(right, mouseCoord));
        foreach (const KoRulerPrivate::HotSpotData & hp, d->hotspots) {
            const qreal y = d->viewConverter->documentToViewY(hp.position) + d->offset;
            painter.drawLine(QPointF(left, y), QPointF(right, y));
        }
    }
}
コード例 #2
0
GRect GAppHelper::QRectF2GRect(const QRectF &other)
{
    return GRect(other.left(), other.top(),
                 other.right(), other.bottom());
}
コード例 #3
0
static QPainterPath qwtCombinePathList( const QRectF &rect, 
    const QList<QPainterPath> &pathList )
{
    if ( pathList.isEmpty() )
        return QPainterPath();

    QPainterPath ordered[8]; // starting top left

    for ( int i = 0; i < pathList.size(); i++ )
    {
        int index = -1;
        QPainterPath subPath = pathList[i];

        const QRectF br = pathList[i].controlPointRect();
        if ( br.center().x() < rect.center().x() )
        {
            if ( br.center().y() < rect.center().y() )
            {
                if ( qAbs( br.top() - rect.top() ) < 
                    qAbs( br.left() - rect.left() ) )
                {
                    index = 1;
                }
                else
                {
                    index = 0;
                }
            }
            else
            {
                if ( qAbs( br.bottom() - rect.bottom() ) < 
                    qAbs( br.left() - rect.left() ) )
                {
                    index = 6;
                }
                else
                {
                    index = 7;
                }
            }

            if ( subPath.currentPosition().y() > br.center().y() )
                qwtRevertPath( subPath );
        }
        else
        {
            if ( br.center().y() < rect.center().y() )
            {
                if ( qAbs( br.top() - rect.top() ) < 
                    qAbs( br.right() - rect.right() ) )
                {
                    index = 2;
                }
                else
                {
                    index = 3;
                }
            }
            else
            {
                if ( qAbs( br.bottom() - rect.bottom() ) < 
                    qAbs( br.right() - rect.right() ) )
                {
                    index = 5;
                }
                else
                {
                    index = 4;
                }
            }
            if ( subPath.currentPosition().y() < br.center().y() )
                qwtRevertPath( subPath );
        }   
        ordered[index] = subPath;
    }

    for ( int i = 0; i < 4; i++ )
    {
        if ( ordered[ 2 * i].isEmpty() != ordered[2 * i + 1].isEmpty() )
        {
            // we don't accept incomplete rounded borders
            return QPainterPath();
        }
    }


    const QPolygonF corners( rect );

    QPainterPath path;
    //path.moveTo( rect.topLeft() );

    for ( int i = 0; i < 4; i++ )
    {
        if ( ordered[2 * i].isEmpty() )
        {
            path.lineTo( corners[i] );
        }
        else
        {
            path.connectPath( ordered[2 * i] );
            path.connectPath( ordered[2 * i + 1] );
        }
    }

    path.closeSubpath();

#if 0
    return path.simplified();
#else
    return path;
#endif
}
コード例 #4
0
static QImage qwtExpandImage(const QImage &image,
    const QwtScaleMap &xMap, const QwtScaleMap &yMap,
    const QRectF &area, const QRectF &area2, const QRectF &paintRect,
    const QwtInterval &xInterval, const QwtInterval &yInterval )
{
    const QRectF strippedRect = qwtStripRect(paintRect, area2,
        xMap, yMap, xInterval, yInterval);
    const QSize sz = strippedRect.toRect().size();

    const int w = image.width();
    const int h = image.height();

    const QRectF r = QwtScaleMap::transform(xMap, yMap, area).normalized();
    const double pw = ( r.width() - 1) / w;
    const double ph = ( r.height() - 1) / h;

    double px0, py0;
    if ( !xMap.isInverting() )
    {
        px0 = xMap.transform( area2.left() );
        px0 = qRound( px0 );
        px0 = px0 - xMap.transform( area.left() );
    }
    else
    {
        px0 = xMap.transform( area2.right() );
        px0 = qRound( px0 );
        px0 -= xMap.transform( area.right() );

        px0 -= 1.0;
    }
    px0 += strippedRect.left() - paintRect.left();

    if ( !yMap.isInverting() )
    {
        py0 = yMap.transform( area2.top() );
        py0 = qRound( py0 );
        py0 -= yMap.transform( area.top() );
    }
    else
    {
        py0 = yMap.transform( area2.bottom() );
        py0 = qRound( py0 );
        py0 -= yMap.transform( area.bottom() );

        py0 -= 1.0;
    }
    py0 += strippedRect.top() - paintRect.top();

    QImage expanded(sz, image.format());

    switch( image.depth() )
    {
        case 32:
        {
            for ( int y1 = 0; y1 < h; y1++ )
            {
                int yy1;
                if ( y1 == 0 )
                {
                    yy1 = 0;
                }
                else
                {
                    yy1 = qRound( y1 * ph - py0 );
                    if ( yy1 < 0 )
                        yy1 = 0;
                }

                int yy2;
                if ( y1 == h - 1 )
                {
                    yy2 = sz.height();
                }
                else
                {
                    yy2 = qRound( ( y1 + 1 ) * ph - py0 );
                    if ( yy2 > sz.height() )
                        yy2 = sz.height();
                }

                const quint32 *line1 = 
                    reinterpret_cast<const quint32 *>( image.scanLine( y1 ) );

                for ( int x1 = 0; x1 < w; x1++ )
                {
                    int xx1;
                    if ( x1 == 0 )
                    {
                        xx1 = 0;
                    }
                    else
                    {
                        xx1 = qRound( x1 * pw - px0 );
                        if ( xx1 < 0 )
                            xx1 = 0;
                    }

                    int xx2;
                    if ( x1 == w - 1 )
                    {
                        xx2 = sz.width();
                    }
                    else
                    {
                        xx2 = qRound( ( x1 + 1 ) * pw - px0 );
                        if ( xx2 > sz.width() )
                            xx2 = sz.width();
                    }

                    const quint32 rgb( line1[x1] );
                    for ( int y2 = yy1; y2 < yy2; y2++ )
                    {
                        quint32 *line2 = reinterpret_cast<quint32 *>( 
                            expanded.scanLine( y2 ) );

                        for ( int x2 = xx1; x2 < xx2; x2++ ) 
                            line2[x2] = rgb;
                    }       
                }   
            }   
            break;
        }
        case 8:
        {
            for ( int y1 = 0; y1 < h; y1++ )
            {
                int yy1;
                if ( y1 == 0 )
                {
                    yy1 = 0;
                }   
                else
                {
                    yy1 = qRound( y1 * ph - py0 );
                    if ( yy1 < 0 )
                        yy1 = 0; 
                }       
                
                int yy2;
                if ( y1 == h - 1 )
                {
                    yy2 = sz.height();
                }   
                else
                {
                    yy2 = qRound( ( y1 + 1 ) * ph - py0 );
                    if ( yy2 > sz.height() )
                        yy2 = sz.height();
                }
    
                const uchar *line1 = image.scanLine( y1 );

                for ( int x1 = 0; x1 < w; x1++ )
                {
                    int xx1;
                    if ( x1 == 0 )
                    {
                        xx1 = 0;
                    }
                    else
                    {
                        xx1 = qRound( x1 * pw - px0 );
                        if ( xx1 < 0 )
                            xx1 = 0;
                    }

                    int xx2;
                    if ( x1 == w - 1 )
                    {
                        xx2 = sz.width();
                    }
                    else
                    {
                        xx2 = qRound( ( x1 + 1 ) * pw - px0 );
                        if ( xx2 > sz.width() )
                            xx2 = sz.width();
                    }

                    for ( int y2 = yy1; y2 < yy2; y2++ )
                    {
                        uchar *line2 = expanded.scanLine( y2 );
                        memset( line2 + xx1, line1[x1], xx2 - xx1 );
                    }       
                }   
            }
            break;
        }
        default:
            expanded = image;
    }
    
    return expanded;
}   
コード例 #5
0
	QRectF closeButtonRect(const QRectF& rect) const {
		return QRectF(rect.right()-closeButtonRectSize, rect.top(), closeButtonRectSize, closeButtonRectSize);
	}
コード例 #6
0
ファイル: qtloops.cpp プロジェクト: amcdawes/veusz
void plotPathsToPainter(QPainter& painter, QPainterPath& path,
			const Numpy1DObj& x, const Numpy1DObj& y,
			const Numpy1DObj* scaling,
			const QRectF* clip,
			const QImage* colorimg,
			bool scaleline)
{
  QRectF cliprect( QPointF(-32767,-32767), QPointF(32767,32767) );
  if( clip != 0 )
    {
      qreal x1, y1, x2, y2;
      clip->getCoords(&x1, &y1, &x2, &y2);
      cliprect.setCoords(x1, y1, x2, y2);
    }
  QRectF pathbox = path.boundingRect();
  cliprect.adjust(pathbox.left(), pathbox.top(),
		  pathbox.bottom(), pathbox.right());

  // keep track of duplicate points
  QPointF lastpt(-1e6, -1e6);
  // keep original transformation for restoration after each iteration
  QTransform origtrans(painter.worldTransform());

  // number of iterations
  int size = min(x.dim, y.dim);

  // if few color points, trim down number of paths
  if( colorimg != 0 )
    size = min(size, colorimg->width());
  // too few scaling points
  if( scaling != 0 )
    size = min(size, scaling->dim);

  // draw each path
  for(int i = 0; i < size; ++i)
    {
      const QPointF pt(x(i), y(i));
      if( cliprect.contains(pt) && ! smallDelta(lastpt, pt) )
	{
	  painter.translate(pt);

	  if( colorimg != 0 )
	    {
	      // get color from pixel and create a new brush
	      QBrush b( QColor::fromRgba(colorimg->pixel(i, 0)) );
	      painter.setBrush(b);
	    }

	  if( scaling == 0 )
	    {
	      painter.drawPath(path);
	    }
	  else
	    {
	      // scale point if requested
	      const qreal s = (*scaling)(i);
	      if( scaleline )
		{
		  painter.scale(s, s);
		  painter.drawPath(path);
		}
	      else
		{
		  QPainterPath scaled;
		  scalePath(path, s, scaled);
		  painter.drawPath(scaled);
		}
	    }

	  painter.setWorldTransform(origtrans);
	  lastpt = pt;
	}
    }
}
コード例 #7
0
//!
//! Updates the path end points according to the positions of start and end
//! nodes.
//!
void ConnectionGraphicsItem::updatePath ()
{
    prepareGeometryChange();

    // calculate positions of the end points
    QPointF startPoint = m_startPoint;
    QPointF endPoint = m_endPoint;
    if (m_startNodeItem)
        startPoint += m_startNodeItem->pos();
    if (m_endNodeItem)
        endPoint += m_endNodeItem->pos();

    // calculate the rectangles to help calculating the positions of the node's anchor points
    const qreal offset = 10;
    QRectF baseAnchorRect = QRectF(-offset, -offset, 2 * offset, 2 * offset);
    QRectF startAnchorRect = baseAnchorRect.translated(startPoint);
    QRectF endAnchorRect = baseAnchorRect.translated(endPoint);
    if (m_startNodeItem)
        startAnchorRect = m_startNodeItem->rect().adjusted(-offset, -offset, offset, offset).translated(m_startNodeItem->pos());
    if (m_endNodeItem)
        endAnchorRect = m_endNodeItem->rect().adjusted(-offset, -offset, offset, offset).translated(m_endNodeItem->pos());

    //
    // Diagram of anchor points for start and end nodes:
    //
    //    x        x      sU2, sU1     eU1, eU2      x        x
    //      ,----,                                     ,----,
    //      |    |                                     |    |
    //      |    |                                     |    |
    //      |   x| x      sP, sO         eO, eP      x |x   |
    //      '----'                                     '----'
    //    x        x      sL2, sL1     eL1, eL2      x        x
    //

    QPointF sP = startPoint;
    QPointF sO = QPointF(startAnchorRect.right(), startPoint.y());
    QPointF sU1 = startAnchorRect.topRight();
    QPointF sU2 = startAnchorRect.topLeft();
    QPointF sL1 = startAnchorRect.bottomRight();
    QPointF sL2 = startAnchorRect.bottomLeft();

    QPointF eP = endPoint;
    QPointF eO = QPointF(endAnchorRect.left(), endPoint.y());
    QPointF eU1 = endAnchorRect.topLeft();
    QPointF eU2 = endAnchorRect.topRight();
    QPointF eL1 = endAnchorRect.bottomLeft();
    QPointF eL2 = endAnchorRect.bottomRight();

    // declare path segments
    QList<QPointF> startPoints;
    QPainterPath cubicPath;
    QList<QPointF> endPoints;

    // construct the path segments
    if (eO.x() < sO.x() && eU2.x() > sL2.x() && eU2.y() < sL2.y() && eL2.y() > sU2.y()) {
        //> case 1V: elements very close to each other
        startPoints << sP << sO;

        QPointF offsetVector = QPointF(0, 0.75 * (eO.y() - sO.y()));
        cubicPath.moveTo(sO);
        cubicPath.cubicTo(sO + offsetVector, eO - offsetVector, eO);

        endPoints << eO << eP;
    } else if (eO.x() >= sO.x()) {
        //> case 1H: end node is right of start node
        startPoints << sP << sO;

        QPointF offsetVector = QPointF(0.75 * (eO.x() - sO.x()), 0);
        cubicPath.moveTo(sO);
        cubicPath.cubicTo(sO + offsetVector, eO - offsetVector, eO);

        endPoints << eO << eP;
    } else if (eU1.y() >= sL1.y()) {
        //> case 2LV
        startPoints << sP << sO << sL1;

        QPointF offsetVector = QPointF(0, 0.75 * (eU1.y() - sL1.y()));
        cubicPath.moveTo(sL1);
        cubicPath.cubicTo(sL1 + offsetVector, eU1 - offsetVector, eU1);

        endPoints << eU1 << eO << eP;
    } else if (eL1.y() <= sU1.y()) {
        //> case 2UV
        startPoints << sP << sO << sU1;

        QPointF offsetVector = QPointF(0, 0.75 * (eL1.y() - sU1.y()));
        cubicPath.moveTo(sU1);
        cubicPath.cubicTo(sU1 + offsetVector, eL1 - offsetVector, eL1);

        endPoints << eL1 << eO << eP;
    } else if (eP.y() >= sP.y()) {
        //> case 3L
        startPoints << sP << sO << sL1 << sL2;

        QPointF offsetVector = QPointF(0.75 * (eU2.x() - sL2.x()), 0);
        cubicPath.moveTo(sL2);
        cubicPath.cubicTo(sL2 + offsetVector, eU2 - offsetVector, eU2);

        endPoints << eU2 << eU1 << eO << eP;
    } else {
        //> case 3U
        startPoints << sP << sO << sU1 << sU2;

        QPointF offsetVector = QPointF(0.75 * (eL2.x() - sU2.x()), 0);
        cubicPath.moveTo(sU2);
        cubicPath.cubicTo(sU2 + offsetVector, eL2 - offsetVector, eL2);

        endPoints << eL2 << eL1 << eO << eP;
    }

    // build the main path from the path segments
    m_mainPath = QPainterPath();
    for (int i = 0; i < startPoints.size(); ++i)
        if (i == 0)
            m_mainPath.moveTo(startPoints[0]);
        else
            m_mainPath.lineTo(startPoints[i]);
    m_mainPath.addPath(cubicPath);
    for (int i = 0; i < endPoints.size(); ++i)
        if (i == 0)
            m_mainPath.moveTo(endPoints[0]);
        else
            m_mainPath.lineTo(endPoints[i]);

    // create the shadow path as a copy of the main path
    m_shadowPath = QPainterPath(m_mainPath);
    // move the path elements of the shadow path one pixel down and to the right
    for (int i = 1; i < m_shadowPath.elementCount(); ++i) {
        QPainterPath::Element element = m_shadowPath.elementAt(i);
        m_shadowPath.setElementPositionAt(i, element.x + 1, element.y + 1);
    }

    // get the center point for the arrow and the angle at that point
    static const qreal t = 0.5;
    QPointF arrowPoint = cubicPath.pointAtPercent(t);
    qreal angle = cubicPath.angleAtPercent(t) * Pi / 180;

    // calculate the polygon for the arrow head
    qreal pathLengthFraction = m_mainPath.length() / 10;
    static const qreal maxArrowSize = 10;
    qreal arrowSize = pathLengthFraction < maxArrowSize ? pathLengthFraction : maxArrowSize;
    QPointF arrowPoint1 = arrowPoint - QPointF(arrowSize * sin(angle - Pi / 2), arrowSize * cos(angle - Pi / 2));
    QPointF arrowPoint2 = arrowPoint - QPointF(arrowSize * sin(angle + Pi / 3), arrowSize * cos(angle + Pi / 3));
    QPointF arrowPoint3 = arrowPoint - QPointF(arrowSize * sin(angle + Pi - Pi / 3), arrowSize * cos(angle + Pi - Pi / 3));
    m_arrowHeadPolygon.clear();
    m_arrowHeadPolygon << arrowPoint1 << arrowPoint2 << arrowPoint3;

    // repaint the graphics item
    update();
}
コード例 #8
0
void UBGraphicsTriangle::calculatePoints(const QRectF& r)
{
    switch(mOrientation)
    {

    case BottomLeft:
        A1.setX(r.left()); A1.setY(r.top());
        B1.setX(r.left()); B1.setY(r.bottom());
        C1.setX(r.right()); C1.setY(r.bottom());
        break;
    case TopLeft:
        A1.setX(r.left()); A1.setY(r.bottom());
        B1.setX(r.left()); B1.setY(r.top());
        C1.setX(r.right()); C1.setY(r.top());
        break;
    case TopRight:
        A1.setX(r.right()); A1.setY(r.bottom());
        B1.setX(r.right()); B1.setY(r.top());
        C1.setX(r.left()); C1.setY(r.top());
        break;
    case BottomRight:
        A1.setX(r.right()); A1.setY(r.top());
        B1.setX(r.right()); B1.setY(r.bottom());
        C1.setX(r.left()); C1.setY(r.bottom());
        break;
    }

    C = sqrt(rect().width() * rect().width() + rect().height() * rect().height());
    qreal L = (C * d + rect().width() * d)/ rect().height();
    qreal K = (C * d + rect().height() * d)/ rect().width();

    switch(mOrientation)
    {
        case BottomLeft:
            A2.setX(r.left() + d); A2.setY(r.top() + K);
            B2.setX(r.left() + d); B2.setY(r.bottom() - d);
            C2.setX(r.right() - L); C2.setY(r.bottom() - d);
            break;
        case TopLeft:
            A2.setX(r.left() + d); A2.setY(r.bottom() - K);
            B2.setX(r.left() + d); B2.setY(r.top() + d);
            C2.setX(r.right() - L); C2.setY(r.top() + d);
            break;
        case TopRight:
            A2.setX(r.right() - d); A2.setY(r.bottom() - K);
            B2.setX(r.right() - d); B2.setY(r.top() + d);
            C2.setX(r.left() + L); C2.setY(r.top() + d);
            break;
        case BottomRight:
            A2.setX(r.right() - d); A2.setY(r.top() + K);
            B2.setX(r.right() - d); B2.setY(r.bottom() - d);
            C2.setX(r.left() + L); C2.setY(r.bottom() - d);
            break;
    }
    W1 = rect().height() * d / C;
    H1 = rect().width() * d / C;

    switch(mOrientation)
    {
        case BottomLeft:
            CC.setX(r.right() - L + W1); CC.setY(r.bottom() - d - H1);
            break;
        case TopLeft:
            CC.setX(r.right() - L + W1); CC.setY(r.top() + d + H1);
            break;
        case TopRight:
            CC.setX(r.left() + L - W1); CC.setY(r.top() + d + H1);
            break;
        case BottomRight:
            CC.setX(r.left() + L - W1); CC.setY(r.top() - d - H1);
            break;
    }
}
コード例 #9
0
ファイル: textdocumentgenerator.cpp プロジェクト: KDE/okular
/**
 * Generic Generator Implementation
 */
Okular::TextPage* TextDocumentGeneratorPrivate::createTextPage( int pageNumber ) const
{
#ifdef OKULAR_TEXTDOCUMENT_THREADED_RENDERING
    Q_Q( const TextDocumentGenerator );
#endif

    Okular::TextPage *textPage = new Okular::TextPage;

    int start, end;

#ifdef OKULAR_TEXTDOCUMENT_THREADED_RENDERING
    q->userMutex()->lock();
#endif
    TextDocumentUtils::calculatePositions( mDocument, pageNumber, start, end );

    {
    QTextCursor cursor( mDocument );
    for ( int i = start; i < end - 1; ++i ) {
        cursor.setPosition( i );
        cursor.setPosition( i + 1, QTextCursor::KeepAnchor );

        QString text = cursor.selectedText();
        if ( text.length() == 1 ) {
            QRectF rect;
            TextDocumentUtils::calculateBoundingRect( mDocument, i, i + 1, rect, pageNumber );
            if ( pageNumber == -1 )
                text = QStringLiteral("\n");

            textPage->append( text, new Okular::NormalizedRect( rect.left(), rect.top(), rect.right(), rect.bottom() ) );
        }
    }
    }
#ifdef OKULAR_TEXTDOCUMENT_THREADED_RENDERING
    q->userMutex()->unlock();
#endif

    return textPage;
}
コード例 #10
0
ファイル: shadereffect.cpp プロジェクト: sicily/qt4.8.4
void ShaderEffect::updateRenderTargets()
{
    if (!m_changed)
        return;

    m_changed = false;

    int count = m_renderTargets.count();
    for (int i = 0; i < count; i++) {
        if (m_renderTargets[i]->isLive() || m_renderTargets[i]->isDirtyTexture()) {
            m_renderTargets[i]->updateBackbuffer();
            ShaderEffectBuffer* target = m_renderTargets[i]->fbo();
            if (target && target->isValid() && target->width() > 0 && target->height() > 0) {
                QPainter p(target);
                p.setCompositionMode(QPainter::CompositionMode_Clear);
                p.fillRect(QRect(QPoint(0, 0), target->size()), Qt::transparent);
                p.setCompositionMode(QPainter::CompositionMode_SourceOver);

                QRectF sourceRect = m_renderTargets[i]->sourceRect();
                QSize textureSize = m_renderTargets[i]->textureSize();

                qreal yflip = m_renderTargets[i]->isMirrored() ? -1.0 : 1.0; // flip y to match scenegraph, it also flips texturecoordinates
                qreal xscale = 1.0;
                qreal yscale = 1.0 * yflip;

                qreal leftMargin = 0.0;
                qreal rightMargin = 0.0;
                qreal topMargin = 0.0;
                qreal bottomMargin = 0.0;

                qreal width = m_renderTargets[i]->sourceItem()->width();
                qreal height = m_renderTargets[i]->sourceItem()->height();

                if (!sourceRect.isEmpty()) {
                    leftMargin = -sourceRect.left();
                    rightMargin = sourceRect.right() - width;
                    topMargin = -sourceRect.top();
                    bottomMargin = sourceRect.bottom() - height;
                }

                if ((width + leftMargin + rightMargin) > 0 && (height + topMargin + bottomMargin) > 0) {
                    if (!textureSize.isEmpty()) {
                        qreal textureWidth = textureSize.width();
                        qreal textureHeight = textureSize.height();

                        xscale = width / (width + leftMargin + rightMargin);
                        yscale = height / (height + topMargin + bottomMargin);

                        p.translate(textureWidth / 2, textureHeight / 2);
                        p.scale(xscale, yscale * yflip);
                        p.translate(-textureWidth / 2, -textureHeight / 2);
                        p.scale(textureWidth / width, textureHeight / height);
                    } else {
                        xscale = width / (width + leftMargin + rightMargin);
                        yscale = height / (height + topMargin + bottomMargin);

                        p.translate(width / 2, height / 2);
                        p.scale(xscale, yscale * yflip);
                        p.translate(-width / 2, -height / 2);
                    }
                }

                drawSource(&p);
                p.end();
                m_renderTargets[i]->markSceneGraphDirty();
            }
        }
    }
}
コード例 #11
0
static QPointF rightCenter(const QRectF &rect)
{
    return QPointF(rect.right(), rect.center().y());
}
コード例 #12
0
/*! Paints the gantt item \a idx using \a painter and \a opt
 */
void ItemDelegate::paintGanttItem( QPainter* painter,
                                   const StyleOptionGanttItem& opt,
                                   const QModelIndex& idx )
{
    if ( !idx.isValid() ) return;
    const ItemType typ = static_cast<ItemType>( idx.model()->data( idx, ItemTypeRole ).toInt() );
    const QString& txt = opt.text;
    QRectF itemRect = opt.itemRect;
    QRectF boundingRect = opt.boundingRect;
    boundingRect.setY( itemRect.y() );
    boundingRect.setHeight( itemRect.height() );
    //qDebug() << "itemRect="<<itemRect<<", boundingRect="<<boundingRect;

    painter->save();

    QPen pen = defaultPen( typ );
    if ( opt.state & QStyle::State_Selected ) pen.setWidth( 2*pen.width() );
    painter->setPen( pen );
    painter->setBrush( defaultBrush( typ ) );

    qreal pw = painter->pen().width()/2.;
    switch( typ ) {
    case TypeTask:
        if ( itemRect.isValid() ) {
            // TODO
            qreal pw = painter->pen().width()/2.;
            pw-=1;
            QRectF r = itemRect;
            r.translate( 0., r.height()/6. );
            r.setHeight( 2.*r.height()/3. );
            painter->setBrushOrigin( itemRect.topLeft() );
            painter->save();
            painter->translate( 0.5, 0.5 );
            painter->drawRect( r );
            bool ok;
            qreal completion = idx.model()->data( idx, KDGantt::TaskCompletionRole ).toDouble( &ok );
            if ( ok ) {
                qreal h = r.height();
                QRectF cr( r.x(), r.y()+h/4. + 1,
                           r.width()*completion/100., h/2. - 2 );
                painter->fillRect( cr, painter->pen().brush() );
            }
            painter->restore();
            Qt::Alignment ta;
            switch( opt.displayPosition ) {
            case StyleOptionGanttItem::Left: ta = Qt::AlignLeft; break;
            case StyleOptionGanttItem::Right: ta = Qt::AlignRight; break;
            case StyleOptionGanttItem::Center: ta = Qt::AlignCenter; break;
            }
            painter->drawText( boundingRect, ta, txt );
        }
        break;
    case TypeSummary:
        if ( opt.itemRect.isValid() ) {
            // TODO
            pw-=1;
            const QRectF r = QRectF( opt.itemRect ).adjusted( -pw, -pw, pw, pw );
            QPainterPath path;
            const qreal deltaY = r.height()/2.;
            const qreal deltaX = qMin( r.width()/qreal(2), deltaY );
            path.moveTo( r.topLeft() );
            path.lineTo( r.topRight() );
            path.lineTo( QPointF( r.right(), r.top() + 2.*deltaY ) );
            //path.lineTo( QPointF( r.right()-3./2.*delta, r.top() + delta ) );
            path.quadTo( QPointF( r.right()-.5*deltaX, r.top() + deltaY ), QPointF( r.right()-2.*deltaX, r.top() + deltaY ) );
            //path.lineTo( QPointF( r.left()+3./2.*delta, r.top() + delta ) );
            path.lineTo( QPointF( r.left() + 2.*deltaX, r.top() + deltaY ) );
            path.quadTo( QPointF( r.left()+.5*deltaX, r.top() + deltaY ), QPointF( r.left(), r.top() + 2.*deltaY ) );
            path.closeSubpath();
            painter->setBrushOrigin( itemRect.topLeft() );
            painter->save();
            painter->translate( 0.5, 0.5 );
            painter->drawPath( path );
            painter->restore();
            Qt::Alignment ta;
            switch( opt.displayPosition ) {
            case StyleOptionGanttItem::Left: ta = Qt::AlignLeft; break;
            case StyleOptionGanttItem::Right: ta = Qt::AlignRight; break;
            case StyleOptionGanttItem::Center: ta = Qt::AlignCenter; break;
            }
            painter->drawText( boundingRect, ta | Qt::AlignVCenter, txt );
        }
        break;
    case TypeEvent: /* TODO */
        //qDebug() << opt.boundingRect << opt.itemRect;
        if ( opt.boundingRect.isValid() ) {
            const qreal pw = painter->pen().width() / 2. - 1;
            const QRectF r = QRectF( opt.rect ).adjusted( -pw, -pw, pw, pw );
            QPainterPath path;
            const qreal delta = static_cast< int >( r.height() / 2 );
            path.moveTo( delta, 0. );
            path.lineTo( 2.*delta, delta );
            path.lineTo( delta, 2.*delta );
            path.lineTo( 0., delta );
            path.closeSubpath();
            painter->save();
            painter->translate( r.topLeft() );
            painter->translate( 0.5, 0.5 );
            painter->drawPath( path );
            painter->restore();
            Qt::Alignment ta;
            switch( opt.displayPosition ) {
            case StyleOptionGanttItem::Left: ta = Qt::AlignLeft; break;
            case StyleOptionGanttItem::Right: ta = Qt::AlignRight; break;
            case StyleOptionGanttItem::Center: ta = Qt::AlignCenter; break;
            }
            painter->drawText( boundingRect, ta | Qt::AlignVCenter, txt );
        }
        break;
    default:
        break;
    }
    painter->restore();
}
コード例 #13
0
ファイル: qgraphicswidget_p.cpp プロジェクト: husninazer/qt
static void _q_boundGeometryToSizeConstraints(const QRectF &startGeometry,
                                              QRectF *rect, Qt::WindowFrameSection section,
                                              const QSizeF &min, const QSizeF &max,
                                              const QGraphicsWidget *widget)
{
    const QRectF proposedRect = *rect;
    qreal width = qBound(min.width(), proposedRect.width(), max.width());
    qreal height = qBound(min.height(), proposedRect.height(), max.height());

    QSizePolicy sp = widget->sizePolicy();
    if (const QGraphicsLayout *l = widget->layout()) {
        sp = l->sizePolicy();
    }
    const bool hasHFW = sp.hasHeightForWidth(); // || sp.hasWidthForHeight();

    const bool widthChanged = proposedRect.width() < widget->size().width();
    const bool heightChanged = proposedRect.height() < widget->size().height();

    if (hasHFW) {
        if (widthChanged || heightChanged) {
            const qreal minh = min.height();
            const qreal maxh = max.height();
            const qreal proposedHFW = minimumHeightForWidth(width, minh, maxh, widget);
            if (proposedHFW > proposedRect.height()) {
                QSizeF effectiveSize = closestAcceptableSize(QSizeF(width, height), widget);
                width = effectiveSize.width();
                height = effectiveSize.height();
            }
        }
    }

    switch (section) {
    case Qt::LeftSection:
        rect->setRect(startGeometry.right() - qRound(width), startGeometry.top(),
                      qRound(width), startGeometry.height());
        break;
    case Qt::TopLeftSection:
        rect->setRect(startGeometry.right() - qRound(width), startGeometry.bottom() - qRound(height),
                      qRound(width), qRound(height));
        break;
    case Qt::TopSection:
        rect->setRect(startGeometry.left(), startGeometry.bottom() - qRound(height),
                      startGeometry.width(), qRound(height));
        break;
    case Qt::TopRightSection:
        rect->setTop(rect->bottom() - qRound(height));
        rect->setWidth(qRound(width));
        break;
    case Qt::RightSection:
        rect->setWidth(qRound(width));
        break;
    case Qt::BottomRightSection:
        rect->setWidth(qRound(width));
        rect->setHeight(qRound(height));
        break;
    case Qt::BottomSection:
        rect->setHeight(qRound(height));
        break;
    case Qt::BottomLeftSection:
        rect->setRect(startGeometry.right() - qRound(width), startGeometry.top(),
                      qRound(width), qRound(height));
        break;
    default:
        break;
    }
}
コード例 #14
0
ファイル: cachedsvgitem.cpp プロジェクト: CheBuzz/TauLabs
void CachedSvgItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
#if defined(Q_OS_WIN)
    // Disable this on windows because the default Qt5 doesn't ship with full OpenGL support
    // https://bugreports.qt-project.org/browse/QTBUG-28715
    // since this is only used for the PFD and the QML PFD is accelerated this is probably
    // a non issue
    QGraphicsSvgItem::paint(painter, option, widget);
#else
    if (painter->paintEngine()->type() != QPaintEngine::OpenGL &&
            painter->paintEngine()->type() != QPaintEngine::OpenGL2) {
        //Fallback to direct painting
        QGraphicsSvgItem::paint(painter, option, widget);
        return;
    }

    QRectF br = boundingRect();
    QTransform transform = painter->worldTransform();
    qreal sceneScale = transform.map(QLineF(0,0,1,0)).length();

    bool stencilTestEnabled = glIsEnabled(GL_STENCIL_TEST);
    bool scissorTestEnabled = glIsEnabled(GL_SCISSOR_TEST);

    painter->beginNativePainting();

    if (stencilTestEnabled)
        glEnable(GL_STENCIL_TEST);
    if (scissorTestEnabled)
        glEnable(GL_SCISSOR_TEST);

    bool dirty = false;
    if (!m_texture) {
        glGenTextures(1, &m_texture);
        m_context = const_cast<QGLContext*>(QGLContext::currentContext());

        dirty = true;
    }

    if (!qFuzzyCompare(sceneScale, m_scale)) {
        m_scale = sceneScale;
        dirty = true;
    }

    int textureWidth = (int(br.width()*m_scale) + 3) & ~3;
    int textureHeight = (int(br.height()*m_scale) + 3) & ~3;

    if (dirty) {
        //qDebug() << "re-render image";

        QImage img(textureWidth, textureHeight, QImage::Format_ARGB32);
        {
            img.fill(Qt::transparent);
            QPainter p;
            p.begin(&img);
            p.setRenderHints(painter->renderHints());
            p.translate(br.topLeft());
            p.scale(m_scale, m_scale);
            QGraphicsSvgItem::paint(&p, option, 0);
            p.end();

            img = img.rgbSwapped();
        }

        glEnable(GL_TEXTURE_2D);

        glBindTexture(GL_TEXTURE_2D, m_texture);
        glTexImage2D(
                GL_TEXTURE_2D,
                0,
                GL_RGBA,
                textureWidth,
                textureHeight,
                0,
                GL_RGBA,
                GL_UNSIGNED_BYTE,
                img.bits());

        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

        glDisable(GL_TEXTURE_2D);

        dirty = false;
    }

    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glEnable(GL_TEXTURE_2D);

    glBindTexture(GL_TEXTURE_2D, m_texture);

    //texture may be slightly large than svn image, ensure only used area is rendered
    qreal tw = br.width()*m_scale/textureWidth;
    qreal th = br.height()*m_scale/textureHeight;

    glBegin(GL_QUADS);
    glTexCoord2d(0,  0 ); glVertex3d(br.left(), br.top(), -1);
    glTexCoord2d(tw, 0 ); glVertex3d(br.right(), br.top(), -1);
    glTexCoord2d(tw, th); glVertex3d(br.right(), br.bottom(), -1);
    glTexCoord2d(0,  th); glVertex3d(br.left(), br.bottom(), -1);
    glEnd();
    glDisable(GL_TEXTURE_2D);

    painter->endNativePainting();
#endif
}
コード例 #15
0
ファイル: qwt_point_data.cpp プロジェクト: Au-Zone/qwt
/*!
   Set a the "rectangle of interest"

   QwtPlotSeriesItem defines the current area of the plot canvas
   as "rect of interest" ( QwtPlotSeriesItem::updateScaleDiv() ).

   If interval().isValid() == false the x values are calculated
   in the interval rect.left() -> rect.right().

   \sa rectOfInterest()
*/
void QwtSyntheticPointData::setRectOfInterest( const QRectF &rect )
{
    d_rectOfInterest = rect;
    d_intervalOfInterest = QwtInterval(
        rect.left(), rect.right() ).normalized();
}
コード例 #16
0
/*!
  \brief Draw the identifier representing the curve on the legend

  \param painter Painter
  \param rect Bounding rectangle for the identifier

  \sa setLegendAttribute(), QwtPlotItem::Legend
*/
void QwtPlotCurve::drawLegendIdentifier(
    QPainter *painter, const QRectF &rect ) const
{
    if ( rect.isEmpty() )
        return;

    const double dim = qMin( rect.width(), rect.height() );

    QSizeF size( dim, dim );

    QRectF r( 0, 0, size.width(), size.height() );
    r.moveCenter( rect.center() );

    if ( d_data->legendAttributes == 0 )
    {
        QBrush brush = d_data->brush;
        if ( brush.style() == Qt::NoBrush )
        {
            if ( style() != QwtPlotCurve::NoCurve )
                brush = QBrush( pen().color() );
            else if ( d_data->symbol &&
                ( d_data->symbol->style() != QwtSymbol::NoSymbol ) )
            {
                brush = QBrush( d_data->symbol->pen().color() );
            }
        }
        if ( brush.style() != Qt::NoBrush )
            painter->fillRect( r, brush );
    }
    if ( d_data->legendAttributes & QwtPlotCurve::LegendShowBrush )
    {
        if ( d_data->brush.style() != Qt::NoBrush )
            painter->fillRect( r, d_data->brush );
    }
    if ( d_data->legendAttributes & QwtPlotCurve::LegendShowLine )
    {
        if ( pen() != Qt::NoPen )
        {
            painter->setPen( pen() );
            QwtPainter::drawLine( painter, rect.left(), rect.center().y(),
                                  rect.right() - 1.0, rect.center().y() );
        }
    }
    if ( d_data->legendAttributes & QwtPlotCurve::LegendShowSymbol )
    {
        if ( d_data->symbol &&
            ( d_data->symbol->style() != QwtSymbol::NoSymbol ) )
        {
            QSize symbolSize = d_data->symbol->boundingSize();
            symbolSize -= QSize( 2, 2 );

            // scale the symbol size down if it doesn't fit into rect.

            double xRatio = 1.0;
            if ( rect.width() < symbolSize.width() )
                xRatio = rect.width() / symbolSize.width();
            double yRatio = 1.0;
            if ( rect.height() < symbolSize.height() )
                yRatio = rect.height() / symbolSize.height();

            const double ratio = qMin( xRatio, yRatio );

            painter->save();
            painter->scale( ratio, ratio );

            d_data->symbol->drawSymbol( painter, rect.center() / ratio );

            painter->restore();
        }
    }
}
コード例 #17
0
void QColorTabBar::paintEvent(QPaintEvent *)
{
    //QTabBar::paintEvent(evt);

    QPainter painter;
    painter.begin( this );

    int nDiameter = 3 << 1;
    for( int i=0 ;i<count(); i++ )
    {
        QRect rectTab( tabRect(i).adjusted( 0, 0, -1, 0 ) );

        bool bActive = (m_nActiveIndex == i);
        if( bActive ) rectTab.adjust( 0, 0, 0, 1 );
        bool bHover = (m_nHoverIndex == i);
        bool bNotify = (m_nNotifyIndex == i);

        QPainterPath tabPath;
        QPainterPath tabS;

        QRectF arcRect( 0, 0, nDiameter, nDiameter );

        if (m_bHorz)
        {
            // Horz-Tab
            tabPath.moveTo( rectTab.bottomLeft() );
            tabPath.lineTo( rectTab.left(), rectTab.top()+nDiameter/2);
            tabS.moveTo( rectTab.left(), rectTab.top()+nDiameter/2 );
            arcRect.moveTo( rectTab.topLeft() );
            tabPath.arcTo( arcRect, 180, -90 );
            tabS.arcTo( arcRect, 180, -90 );
            tabPath.lineTo( rectTab.right()-nDiameter/2, rectTab.top() );
            tabS.lineTo( rectTab.right()-nDiameter/2, rectTab.top() );
            arcRect.moveTo( rectTab.right()-nDiameter, rectTab.top() );
            tabPath.arcTo( arcRect, 90, -90 );
            tabS.arcTo( arcRect, 90, -90 );
            tabPath.lineTo( rectTab.bottomRight() );
            //tabS.closeSubpath();
        }
        else
        {
            // Vert-Tab
            tabPath.moveTo( rectTab.right(), rectTab.y() );
            tabPath.lineTo( rectTab.x()+nDiameter, rectTab.y() );
            tabS.moveTo( rectTab.x()+nDiameter, rectTab.y() );
            arcRect.moveTo(rectTab.topLeft());
            tabPath.arcTo( arcRect, -270, 90 );
            tabS.arcTo( arcRect, -270, 90 );
            arcRect.moveTo(rectTab.x(), rectTab.bottom()-nDiameter);
            tabPath.arcTo( arcRect, -180, 90 );
            tabS.arcTo( arcRect, -180, 90 );
            tabPath.moveTo( rectTab.left()+nDiameter, rectTab.bottom() );
            tabPath.lineTo( rectTab.right(), rectTab.bottom() );
            //tabS.closeSubpath();
        }


        QColor colorBody;

        if (bNotify && (m_nBlinkCount % 2 == 0))
        {
            colorBody = QColor(252, 209, 211);
        }
        else
        {
            if (bActive)
                colorBody = QColor(255, 255, 255);
            else
                colorBody = QColor(0xF5, 0xF5, 0xF5);
        }

        painter.fillPath( tabPath, QBrush(colorBody) );

        QColor colorStart = bActive ? g_TabDefaultColor[i] : (bHover ? QColor(255, 190, 60, 200) : QColor(255, 255, 255, 200));
        QColor colorEnd(255, 255, 255, 200);
        QRectF rectTabTip;
        rectTabTip = tabS.boundingRect();
        QLinearGradient gradTip;
        if (m_bHorz)
        {
            gradTip.setStart(rectTabTip.center().x(), rectTabTip.top());
            gradTip.setFinalStop(rectTabTip.center().x(), rectTabTip.bottom());
        }
        else
        {
            gradTip.setStart(rectTabTip.left(), rectTabTip.center().y());
            gradTip.setFinalStop(rectTabTip.right(), rectTabTip.center().y());
        }
        gradTip.setColorAt( 0, colorStart );
        gradTip.setColorAt( 1.f, colorEnd );

        painter.setBrush(Qt::NoBrush);
        painter.setPen( QPen(QColor(160,160,160,100), 2.f) );
        painter.drawPath( tabPath );
        painter.setPen( QPen(QColor(160,160,160)) );
        painter.drawPath( tabPath );
        painter.setPen( Qt::white );
        if( bActive )
            painter.drawLine( rectTab.bottomLeft(), rectTab.bottomRight() );

        painter.fillPath( tabS, QBrush(gradTip) );
        if (bActive || bHover)
        {
            painter.setPen( colorStart );
            painter.drawPath( tabS );
        }

        QRectF rectText;

        float fTextOffset = 0.f;

        if (m_bHorz)
        {
            rectText.setX((float)rectTab.x() + fTextOffset);
            rectText.setY((float)rectTab.y() + nDiameter/2);
            rectText.setWidth((float)rectTab.width() - fTextOffset);
            rectText.setHeight((float)rectTab.height() - nDiameter/2);
        }
        else
        {
            rectText.setX((float)rectTab.x() + nDiameter/2 + fTextOffset);
            rectText.setY((float)rectTab.y());
            rectText.setWidth((float)rectTab.width() - nDiameter/2 - fTextOffset);
            rectText.setHeight((float)rectTab.height());
        }

        QFont fnt( font() );

        fnt.setBold(bActive);

        painter.setFont( fnt );

        int flags = Qt::AlignCenter|Qt::AlignVCenter|Qt::TextSingleLine;
        painter.setPen( QColor(80,80,80) );
        painter.drawText( rectText, flags, tabText(i) );

        if( m_nBlinkIndex == i && m_bBlinkFalg )
        {
            painter.fillPath( tabPath, QColor(240,240,0,128) );
        }
    }

    painter.end();
}
コード例 #18
0
static void _q_boundGeometryToSizeConstraints(const QRectF &startGeometry,
                                              QRectF *rect, Qt::WindowFrameSection section,
                                              const QSizeF &min, const QSizeF &max,
                                              const QGraphicsWidget *widget)
{
    const QRectF proposedRect = *rect;
    qreal width = qBound(min.width(), proposedRect.width(), max.width());
    qreal height = qBound(min.height(), proposedRect.height(), max.height());

    const bool hasHFW = QGraphicsLayoutItemPrivate::get(widget)->hasHeightForWidth();
    const bool hasWFH = QGraphicsLayoutItemPrivate::get(widget)->hasWidthForHeight();

    const bool widthChanged = proposedRect.width() != widget->size().width();
    const bool heightChanged = proposedRect.height() != widget->size().height();

    if (hasHFW || hasWFH) {
        if (widthChanged || heightChanged) {
            qreal minExtent;
            qreal maxExtent;
            qreal constraint;
            qreal proposed;
            if (hasHFW) {
                minExtent = min.height();
                maxExtent = max.height();
                constraint = width;
                proposed = proposedRect.height();
            } else {
                // width for height
                minExtent = min.width();
                maxExtent = max.width();
                constraint = height;
                proposed = proposedRect.width();
            }
            if (minimumHeightForWidth(constraint, minExtent, maxExtent, widget, hasHFW) > proposed) {
                QSizeF effectiveSize = closestAcceptableSize(QSizeF(width, height), widget);
                width = effectiveSize.width();
                height = effectiveSize.height();
            }
        }
    }

    switch (section) {
    case Qt::LeftSection:
        rect->setRect(startGeometry.right() - qRound(width), startGeometry.top(),
                      qRound(width), startGeometry.height());
        break;
    case Qt::TopLeftSection:
        rect->setRect(startGeometry.right() - qRound(width), startGeometry.bottom() - qRound(height),
                      qRound(width), qRound(height));
        break;
    case Qt::TopSection:
        rect->setRect(startGeometry.left(), startGeometry.bottom() - qRound(height),
                      startGeometry.width(), qRound(height));
        break;
    case Qt::TopRightSection:
        rect->setTop(rect->bottom() - qRound(height));
        rect->setWidth(qRound(width));
        break;
    case Qt::RightSection:
        rect->setWidth(qRound(width));
        break;
    case Qt::BottomRightSection:
        rect->setWidth(qRound(width));
        rect->setHeight(qRound(height));
        break;
    case Qt::BottomSection:
        rect->setHeight(qRound(height));
        break;
    case Qt::BottomLeftSection:
        rect->setRect(startGeometry.right() - qRound(width), startGeometry.top(),
                      qRound(width), qRound(height));
        break;
    default:
        break;
    }
}
コード例 #19
0
ファイル: qwt_text.cpp プロジェクト: 27sparks/GoldenCheetah
/*!
   Draw a text into a rectangle

   \param painter Painter
   \param rect Rectangle
*/
void QwtText::draw( QPainter *painter, const QRectF &rect ) const
{
    if ( d_data->paintAttributes & PaintBackground )
    {
        if ( d_data->borderPen != Qt::NoPen ||
            d_data->backgroundBrush != Qt::NoBrush )
        {
            painter->save();

            painter->setPen( d_data->borderPen );
            painter->setBrush( d_data->backgroundBrush );

            if ( d_data->borderRadius == 0 )
            {
                QwtPainter::drawRect( painter, rect );
            }
            else
            {
                painter->setRenderHint( QPainter::Antialiasing, true );
                painter->drawRoundedRect( rect,
                    d_data->borderRadius, d_data->borderRadius );
            }

            painter->restore();
        }
    }

    painter->save();

    if ( d_data->paintAttributes & PaintUsingTextFont )
    {
        painter->setFont( d_data->font );
    }

    if ( d_data->paintAttributes & PaintUsingTextColor )
    {
        if ( d_data->color.isValid() )
            painter->setPen( d_data->color );
    }

    QRectF expandedRect = rect;
    if ( d_data->layoutAttributes & MinimumLayout )
    {
        // We want to calculate in screen metrics. So
        // we need a font that uses screen metrics

        const QFont font( painter->font(), QApplication::desktop() );

        double left, right, top, bottom;
        d_data->textEngine->textMargins(
            font, d_data->text, left, right, top, bottom );

        expandedRect.setTop( rect.top() - top );
        expandedRect.setBottom( rect.bottom() + bottom );
        expandedRect.setLeft( rect.left() - left );
        expandedRect.setRight( rect.right() + right );
    }

    d_data->textEngine->draw( painter, expandedRect,
        d_data->renderFlags, d_data->text );

    painter->restore();
}
コード例 #20
0
ファイル: scgalphabet.cpp プロジェクト: AlexKlybik/kbe
void SCgAlphabet::paintStruct(QPainter *painter, const QColor &color,
                              const QRectF &boundRect, const SCgNodeStructType &type)
{
    QPen pen = QPen(QBrush(color, Qt::SolidPattern), 2, Qt::SolidLine, Qt::FlatCap, Qt::MiterJoin);
    painter->setPen(pen);

    // structure types
    QPointF c, d;
    switch (type)
    {
    case StructType_Struct:
        float w, h;
        w = boundRect.width() / 10.f;
        h = boundRect.height() / 10.f;
        painter->setBrush(QBrush(color, Qt::SolidPattern));
        painter->drawEllipse(-w, -h, w * 2 - 1, h * 2 - 1);
        painter->setBrush(QBrush(Qt::NoBrush));
        break;

    case StructType_Abstract:
    {
        QPen p = painter->pen();
        p.setWidthF(0);
        painter->setPen(p);
        qreal x1, x2, top, bottom;
        top = boundRect.top();
        bottom = boundRect.bottom();
        x1 = boundRect.left();
        x2 = boundRect.right();

        for (qreal y = top; y < bottom; y += 3)
            painter->drawLine(QLineF(x1, y, x2, y));

        break;
    }

    case StructType_Material:
    {
        QPen p = painter->pen();
        p.setWidthF(0);
        painter->setPen(p);
        qreal y1, y2, left, right;
        left = boundRect.left();
        right = boundRect.right();


        qreal dist = right - left;

        y1 = boundRect.top();
        y2 = boundRect.bottom();

        for (qreal d = 0; d <= dist; d += 4.2)
        {
            painter->drawLine(QLineF(left + d, y1, left, y1 + d));
            painter->drawLine(QLineF(right - d, y2, right, y2 - d));
        }

        break;
    }

    case StructType_Tuple:
        c = boundRect.center();
        d = QPointF(boundRect.width() / 2.0, 0.f);
        painter->drawLine(c - d, c + d);
        break;

    case StructType_Role:
        c = boundRect.center();
        d = QPointF(boundRect.width() / 2.0, 0.f);
        painter->drawLine(c - d, c + d);
        d = QPointF(0.f, boundRect.height() / 2.0);
        painter->drawLine(c - d, c + d);
        break;

    case StructType_Relation:
        painter->drawLine(boundRect.topLeft(), boundRect.bottomRight());
        painter->drawLine(boundRect.topRight(), boundRect.bottomLeft());
        break;

    case StructType_Group:
        painter->drawLine(boundRect.topLeft(), boundRect.bottomRight());
        painter->drawLine(boundRect.topRight(), boundRect.bottomLeft());
        painter->drawLine(boundRect.left(), boundRect.center().y(), boundRect.right(), boundRect.center().y());
        break;

    default:
        break;
    }
}
コード例 #21
0
ファイル: griditem.cpp プロジェクト: unix8net/MoniterV2
void GridItem::draw( QPainter *painter,
    const QwtScaleMap &xMap, const QwtScaleMap &yMap,
    const QRectF &canvasRect ) const
{
    const bool doAlign = QwtPainter::roundingAlignment( painter );

    const QRectF area = QwtScaleMap::invTransform( xMap, yMap, canvasRect );

    QList<double> xValues;
    if ( m_orientations & Qt::Horizontal )
    {
        xValues = m_xScaleDiv.ticks( QwtScaleDiv::MajorTick );

        if ( m_isXMinEnabled )
        {
            xValues += m_xScaleDiv.ticks( QwtScaleDiv::MediumTick );
            xValues += m_xScaleDiv.ticks( QwtScaleDiv::MinorTick );
        }

        if ( m_gridAttributes & FillCanvas )
        {
            xValues += area.left();
            xValues += area.right();
        }

        qSort( xValues );
    }

    QList<double> yValues;
    if ( m_orientations & Qt::Vertical )
    {
        yValues = m_yScaleDiv.ticks( QwtScaleDiv::MajorTick );

        if ( m_isYMinEnabled )
        {
            yValues += m_yScaleDiv.ticks( QwtScaleDiv::MediumTick );
            yValues += m_yScaleDiv.ticks( QwtScaleDiv::MinorTick );
        }

        if ( m_gridAttributes & FillCanvas )
        {
            yValues += area.top();
            yValues += area.bottom();
        }

        qSort( yValues );
    }

    painter->setPen( Qt::NoPen );

    if ( ( m_orientations & Qt::Horizontal ) &&
        ( m_orientations & Qt::Vertical ) )
    {
        for ( int i = 1; i < xValues.size(); i++ )
        {
            double x1 = xMap.transform( xValues[i - 1] );
            double x2 = xMap.transform( xValues[i] );

            if ( doAlign )
            {
                x1 = qRound( x1 );
                x2 = qRound( x2 );
            }

            for ( int j = 1; j < yValues.size(); j++ )
            {
                const QRectF rect( xValues[i - 1], yValues[j - 1],
                    xValues[i] - xValues[i - 1], yValues[j] - yValues[j - 1] );

                painter->setBrush( brush( i - 1, j - 1, rect ) );

                double y1 = yMap.transform( yValues[j - 1] );
                double y2 = yMap.transform( yValues[j] );

                if ( doAlign )
                {
                    y1 = qRound( y1 );
                    y2 = qRound( y2 );
                }

                QwtPainter::drawRect( painter, x1, y1, x2 - x1, y2 - y1 );
            }
        }
    }
    else if ( m_orientations & Qt::Horizontal )
    {
        for ( int i = 1; i < xValues.size(); i++ )
        {
            const QRectF rect( xValues[i - 1], area.top(),
                xValues[i] - xValues[i - 1], area.bottom() );

            painter->setBrush( brush( i - 1, 0, rect ) );

            double x1 = xMap.transform( xValues[i - 1] );
            double x2 = xMap.transform( xValues[i] );

            if ( doAlign )
            {
                x1 = qRound( x1 );
                x2 = qRound( x2 );
            }

            QwtPainter::drawRect( painter,
                x1, canvasRect.top(), x2 - x1, canvasRect.height() );
        }
    }
    else if ( m_orientations & Qt::Vertical )
    {
        for ( int i = 1; i < yValues.size(); i++ )
        {
            const QRectF rect( area.left(), yValues[i - 1],
                area.width(), yValues[i] - yValues[i - 1] );

            painter->setBrush( brush( 0, i - 1, rect ) );

            double y1 = yMap.transform( yValues[i - 1] );
            double y2 = yMap.transform( yValues[i] );

            if ( doAlign )
            {
                y1 = qRound( y1 );
                y2 = qRound( y2 );
            }

            QwtPainter::drawRect( painter, canvasRect.left(), y1,
                                  canvasRect.width(), y2 - y1 );
        }
    }
}
コード例 #22
0
/***********************************************************************
 *Funtion : Move the draged handle to mouse point
 *Return  : DRAG_CROSS_TYPE_E cross type
 *Parameter: integer draged handle id, QPointF mouse local point, scene bonding rect
 **********************************************************************/
QRectF SamDrawItemBase::moveHandleTo(int iDragHandle, QPointF qpLocal, QRectF &qrcBondingRect, bool bFoursquare)
{
    QRectF qrcPosition;

    //qrcPosition = this->sceneBoundingRect();
    qrcPosition = qrcBondingRect;
    switch (iDragHandle)
    {
    case HANDLE_LEFT_TOP:
            qrcPosition.setLeft(qpLocal.x());
            qrcPosition.setTop(qpLocal.y());
            if (bFoursquare)
            {
                qrcPosition.setLeft(qpLocal.x());
                qrcPosition.setTop(qpLocal.y());
                if (qrcPosition.height() > qrcPosition.width())
                {
                    qrcPosition.setLeft(qrcPosition.right() - qrcPosition.height());
                }
                else if (qrcPosition.height() < qrcPosition.width())
                {
                    qrcPosition.setTop(qrcPosition.bottom() - qrcPosition.width());
                }
            }
            break;
    case HANDLE_CENTER_TOP:
            qrcPosition.setTop(qpLocal.y());
            if (bFoursquare)
            {
                qrcPosition.setWidth(qrcPosition.height());
            }
            break;
    case HANDLE_RIGHT_TOP:
            qrcPosition.setRight(qpLocal.x());
            qrcPosition.setTop(qpLocal.y());
            if (bFoursquare)
            {
                if (qrcPosition.height() > qrcPosition.width())
                {
                    qrcPosition.setWidth(qrcPosition.height());
                }
                else if (qrcPosition.height() < qrcPosition.width())
                {
                    qrcPosition.setTop(qrcPosition.bottom() - qrcPosition.width());
                }
            }
            break;
    case HANDLE_RIGHT_CENTER:
            qrcPosition.setRight(qpLocal.x());
            if (bFoursquare)
            {
                qrcPosition.setHeight(qrcPosition.width());
            }
            break;
    case HANDLE_RIGHT_BOTTOM:
            qrcPosition.setRight(qpLocal.x());
            qrcPosition.setBottom(qpLocal.y());
            if (bFoursquare)
            {
                if (qrcPosition.height() > qrcPosition.width())
                {
                    qrcPosition.setWidth(qrcPosition.height());
                }
                else if (qrcPosition.height() < qrcPosition.width())
                {
                    qrcPosition.setHeight(qrcPosition.width());
                }
            }
            break;
    case HANDLE_CENTER_BOTTOM:
            qrcPosition.setBottom(qpLocal.y());
            if (bFoursquare)
            {
                qrcPosition.setWidth(qrcPosition.height());
            }
            break;
    case HANDLE_LEFT_BOTTOM:
            qrcPosition.setLeft(qpLocal.x());
            qrcPosition.setBottom(qpLocal.y());
            if (bFoursquare)
            {
                if (qrcPosition.height() > qrcPosition.width())
                {
                    qrcPosition.setLeft(qrcPosition.right() - qrcPosition.height());
                }
                else if (qrcPosition.height() < qrcPosition.width())
                {
                    qrcPosition.setHeight(qrcPosition.width());
                }
            }
            break;
    case HANDLE_LEFT_CENTER:
            qrcPosition.setLeft(qpLocal.x());
            if (bFoursquare)
            {
                qrcPosition.setHeight(qrcPosition.width());
            }
            break;
    default:
            return qrcPosition;
    }

    return qrcPosition;
}
コード例 #23
0
/*!
  \brief Draw the raster data
  \param painter Painter
  \param xMap X-Scale Map
  \param yMap Y-Scale Map
  \param canvasRect Contents rectangle of the plot canvas
*/
void QwtPlotRasterItem::draw( QPainter *painter,
    const QwtScaleMap &xMap, const QwtScaleMap &yMap,
    const QRectF &canvasRect ) const
{
    if ( canvasRect.isEmpty() || d_data->alpha == 0 )
        return;

    const bool doCache = qwtUseCache( d_data->cache.policy, painter );

    const QwtInterval xInterval = interval( Qt::XAxis );
    const QwtInterval yInterval = interval( Qt::YAxis );

    /*
        Scaling an image always results in a loss of
        precision/quality. So we always render the image in
        paint device resolution.
    */

    QwtScaleMap xxMap, yyMap;
    qwtTransformMaps( painter->transform(), xMap, yMap, xxMap, yyMap );

    QRectF paintRect = painter->transform().mapRect( canvasRect );
    QRectF area = QwtScaleMap::invTransform( xxMap, yyMap, paintRect );

    const QRectF br = boundingRect();
    if ( br.isValid() && !br.contains( area ) )
    {
        area &= br;
        if ( !area.isValid() )
            return;

        paintRect = QwtScaleMap::transform( xxMap, yyMap, area );
    }

    QRectF imageRect;
    QImage image;

    QRectF pixelRect = pixelHint(area);
    if ( !pixelRect.isEmpty() )
    {
        // pixel in target device resolution 
        const double dx = qAbs( xxMap.invTransform( 1 ) - xxMap.invTransform( 0 ) );
        const double dy = qAbs( yyMap.invTransform( 1 ) - yyMap.invTransform( 0 ) );

        if ( dx > pixelRect.width() && dy > pixelRect.height() )
        {
            /*
              When the resolution of the data pixels is higher than
              the resolution of the target device we render in
              target device resolution.
             */
            pixelRect = QRectF();
        }
    }

    if ( pixelRect.isEmpty() )
    {
        if ( QwtPainter::roundingAlignment( painter ) )
        {
            // we want to have maps, where the boundaries of
            // the aligned paint rectangle exactly match the area

            paintRect = qwtAlignRect(paintRect);
            qwtAdjustMaps(xxMap, yyMap, area, paintRect);
        }

        // When we have no information about position and size of
        // data pixels we render in resolution of the paint device.

        image = compose(xxMap, yyMap, 
            area, paintRect, paintRect.size().toSize(), doCache);
        if ( image.isNull() )
            return;

        // Remove pixels at the boundaries, when explicitly
        // excluded in the intervals

        imageRect = qwtStripRect(paintRect, area, 
            xxMap, yyMap, xInterval, yInterval);

        if ( imageRect != paintRect )
        {
            const QRect r( 
                qRound( imageRect.x() - paintRect.x()),
                qRound( imageRect.y() - paintRect.y() ),
                qRound( imageRect.width() ),
                qRound( imageRect.height() ) );
                
            image = image.copy(r);
        }   
    }
    else
    {
        if ( QwtPainter::roundingAlignment( painter ) )
            paintRect = qwtAlignRect(paintRect);

        // align the area to the data pixels
        QRectF imageArea = qwtExpandToPixels(area, pixelRect);

        if ( imageArea.right() == xInterval.maxValue() &&
            !( xInterval.borderFlags() & QwtInterval::ExcludeMaximum ) )
        {
            imageArea.adjust(0, 0, pixelRect.width(), 0);
        }
        if ( imageArea.bottom() == yInterval.maxValue() &&
            !( yInterval.borderFlags() & QwtInterval::ExcludeMaximum ) )
        {
            imageArea.adjust(0, 0, 0, pixelRect.height() );
        }

        QSize imageSize;
        imageSize.setWidth( qRound( imageArea.width() / pixelRect.width() ) );
        imageSize.setHeight( qRound( imageArea.height() / pixelRect.height() ) );
        image = compose(xxMap, yyMap, 
            imageArea, paintRect, imageSize, doCache );
        if ( image.isNull() )
            return;

        imageRect = qwtStripRect(paintRect, area, 
            xxMap, yyMap, xInterval, yInterval);

        if ( ( image.width() > 1 || image.height() > 1 ) &&
            testPaintAttribute( PaintInDeviceResolution ) )
        {
            // Because of rounding errors the pixels 
            // need to be expanded manually to rectangles of 
            // different sizes

            image = qwtExpandImage(image, xxMap, yyMap, 
                imageArea, area, paintRect, xInterval, yInterval );
        }
    }

    painter->save();
    painter->setWorldTransform( QTransform() );
    
    QwtPainter::drawImage( painter, imageRect, image );

    painter->restore();
}
コード例 #24
0
ファイル: pin.cpp プロジェクト: genuser/freesch
QVariant Pin::itemChange(GraphicsItemChange change, const QVariant &value)
{
	// Note that pins are only movable within the symbol editor.

	PageScene *pageScene = dynamic_cast<PageScene *>(scene());
	if (ItemPositionChange == change && pageScene) {
		QPointF p = value.toPointF() + pageScene->reparentOffset(this);	// p is now the position relative to the current parent.
		SymbolEditor *se = dynamic_cast<SymbolEditor *>(pageScene->parent());
		if (se) {
			QGraphicsItem *anchor = se->closestPinAnchor(parentItem()->mapToScene(p), this);
			if (parentItem() != anchor) {
				pageScene->reparentWhileDragging(this, anchor);
				p = value.toPointF() + pageScene->reparentOffset(this);
				setData(FreeSCH::SectionChanged, true);
			}
			if (QGraphicsLineItem::Type == anchor->type()) {
				p.setX(anchor->pos().x());
				if (position.side() != PinPosition::Right) {
					position.setSide(PinPosition::Right);
					attributes.setValue("side", PinPosition::sideNames.at(PinPosition::Right));
					reorient();
				}
			} else if (Section::Type == anchor->type()) {
				Section *section = qgraphicsitem_cast<Section *>(anchor);
				if (section) {
					QRectF r = QRectF(QPointF(0,0), section->rect().size());
					PinPosition::PinSide newside = PinPosition::sideIndex(r, p);
					switch (newside) {
					case PinPosition::Right:
						p.setX(r.right());
						break;
					case PinPosition::Bottom:
						p.setY(r.bottom());
						break;
					case PinPosition::Left:
						p.setX(r.left());
						break;
					default: // top
						p.setY(r.top());
						break;
					}
					if (p.x() < 0)
						p.setX(0);
					if (p.x() > r.width())
						p.setX(r.width());
					if (p.y() < 0)
						p.setY(0);
					if (p.y() > r.height())
						p.setY(r.height());

					if (position.side() != newside) {
						position.setSide(newside);
						attributes.setValue("side", PinPosition::sideNames.at(newside));
						updateOffset(snap(p).toPoint());
						reorient();
						// As the pin moves around a corner of a section, it can switch sides without its pos() changing.
						// In that case the ItemPositionHasChanged event doesn't occur. So we need to emit the moved signal here.

						emit moved();
					}
				}
			}
		}
		return snap(p);
	}
	if (ItemPositionHasChanged == change && pageScene) {
		updateOffset(pos().toPoint());

		if (data(FreeSCH::SectionChanged).toBool()) {
			setData(FreeSCH::SectionChanged, false);
			emit sectionChanged(this, parentItem());
		}
		emit moved();
	}
	return QGraphicsItem::itemChange(change, value);
}
コード例 #25
0
	QRectF resizeRect(const QRectF& rect) const {
		return QRectF(rect.right()-borderSize, rect.bottom()-borderSize, borderSize, borderSize);
	}
コード例 #26
0
ファイル: pageitem_table.cpp プロジェクト: Sheikha443/scribus
TableHandle PageItem_Table::hitTest(const QPointF& point, double threshold) const
{
	const QPointF framePoint = getTransform().inverted().map(point);
	const QPointF gridPoint = framePoint - gridOffset();
	const QRectF gridRect = QRectF(0.0, 0.0, tableWidth(), tableHeight());

	// Test if hit is outside frame.
	if (!QRectF(0.0, 0.0, width(), height()).contains(framePoint))
		return TableHandle(TableHandle::None);

	// Test if hit is outside table.
	if (!gridRect.adjusted(-threshold, -threshold, threshold, threshold).contains(gridPoint))
		return TableHandle(TableHandle::None);

	const double tableHeight = this->tableHeight();
	const double tableWidth = this->tableWidth();
	const double x = gridPoint.x();
	const double y = gridPoint.y();

	// Test if hit is on left edge of table.
	if (x <= threshold)
		return TableHandle(TableHandle::RowSelect);

	// Test if hit is on top edge of table.
	if (y <= threshold)
		return TableHandle(TableHandle::ColumnSelect);

	// Test if hit is on bottom right corner of table.
	if (x >= tableWidth - threshold && y >= tableHeight - threshold)
		return TableHandle(TableHandle::TableResize);

	// Test if hit is on right edge of table.
	if (y >= tableHeight - threshold && y <= tableHeight + threshold)
		return TableHandle(TableHandle::RowResize, rows() - 1);

	// Test if hit is on bottom edge of table.
	if (x >= tableWidth - threshold && x <= tableWidth + threshold)
		return TableHandle(TableHandle::ColumnResize, columns() - 1);

	const TableCell hitCell = cellAt(point);
	const QRectF hitRect = hitCell.boundingRect();

	// Test if hit is on cell interior.
	if (hitRect.adjusted(threshold, threshold, -threshold, -threshold).contains(gridPoint))
		return TableHandle(TableHandle::CellSelect); // Hit interior of cell.

	const double toLeft = x - hitRect.left();
	const double toRight = hitRect.right() - x;
	const double toTop = y - hitRect.top();
	const double toBottom = hitRect.bottom() - y;
	TableHandle handle(TableHandle::None);

	// Test which side of the cell was hit.
	if (qMin(toLeft, toRight) < qMin(toTop, toBottom))
	{
		handle.setType(TableHandle::ColumnResize);
		handle.setIndex((toLeft < toRight ? hitCell.column() : hitCell.column() + hitCell.columnSpan()) - 1);
	}
	else
	{
		handle.setType(TableHandle::RowResize);
		handle.setIndex((toTop < toBottom ? hitCell.row() : hitCell.row() + hitCell.rowSpan()) - 1);
	}
	return handle;
}
コード例 #27
0
/*!
  \brief Draw the scale
*/
void QwtPlotScaleItem::draw( QPainter *painter,
    const QwtScaleMap &xMap, const QwtScaleMap &yMap,
    const QRectF &canvasRect ) const
{
    QwtScaleDraw *sd = d_data->scaleDraw;

    if ( d_data->scaleDivFromAxis )
    {
        const QwtInterval interval = 
            d_data->scaleInterval( canvasRect, xMap, yMap );

        if ( interval != sd->scaleDiv().interval() )
        {
            QwtScaleDiv scaleDiv = sd->scaleDiv();
            scaleDiv.setInterval( interval );
            sd->setScaleDiv( scaleDiv );
        }
    }

    QPen pen = painter->pen();
    pen.setStyle( Qt::SolidLine );
    painter->setPen( pen );

    if ( sd->orientation() == Qt::Horizontal )
    {
        double y;
        if ( d_data->borderDistance >= 0 )
        {
            if ( sd->alignment() == QwtScaleDraw::BottomScale )
                y = canvasRect.top() + d_data->borderDistance;
            else
            {
                y = canvasRect.bottom() - d_data->borderDistance;
            }

        }
        else
        {
            y = yMap.transform( d_data->position );
        }

        if ( y < canvasRect.top() || y > canvasRect.bottom() )
            return;

        sd->move( canvasRect.left(), y );
        sd->setLength( canvasRect.width() - 1 );

        QwtTransform *transform = NULL;
        if ( xMap.transformation() )
            transform = xMap.transformation()->copy();

        sd->setTransformation( transform );
    }
    else // == Qt::Vertical
    {
        double x;
        if ( d_data->borderDistance >= 0 )
        {
            if ( sd->alignment() == QwtScaleDraw::RightScale )
                x = canvasRect.left() + d_data->borderDistance;
            else
            {
                x = canvasRect.right() - d_data->borderDistance;
            }
        }
        else
        {
            x = xMap.transform( d_data->position );
        }
        if ( x < canvasRect.left() || x > canvasRect.right() )
            return;

        sd->move( x, canvasRect.top() );
        sd->setLength( canvasRect.height() - 1 );

        QwtTransform *transform = NULL;
        if ( yMap.transformation() )
            transform = yMap.transformation()->copy();

        sd->setTransformation( transform );
    }

    painter->setFont( d_data->font );

    sd->draw( painter, d_data->palette );
}
コード例 #28
0
ファイル: qwt_plot_layout.cpp プロジェクト: albore/pandora
void QwtPlotLayout::alignScales( int options,
    QRectF &canvasRect, QRectF scaleRect[QwtPlot::axisCnt] ) const
{
    int backboneOffset[QwtPlot::axisCnt];
    for ( int axis = 0; axis < QwtPlot::axisCnt; axis++ )
    {
        backboneOffset[axis] = 0;
        if ( !d_data->alignCanvasToScales )
            backboneOffset[axis] += d_data->canvasMargin[axis];
        if ( !( options & IgnoreFrames ) )
            backboneOffset[axis] += d_data->layoutData.canvas.frameWidth;
    }

    for ( int axis = 0; axis < QwtPlot::axisCnt; axis++ )
    {
        if ( !scaleRect[axis].isValid() )
            continue;

        const int startDist = d_data->layoutData.scale[axis].start;
        const int endDist = d_data->layoutData.scale[axis].end;

        QRectF &axisRect = scaleRect[axis];

        if ( axis == QwtPlot::xTop || axis == QwtPlot::xBottom )
        {
            const QRectF &leftScaleRect = scaleRect[QwtPlot::yLeft];
            const int leftOffset =
                backboneOffset[QwtPlot::yLeft] - startDist;

            if ( leftScaleRect.isValid() )
            {
                const int dx = leftOffset + leftScaleRect.width();
                if ( d_data->alignCanvasToScales && dx < 0 )
                {
                    /*
                      The axis needs more space than the width
                      of the left scale.
                     */
                    canvasRect.setLeft( qMax( canvasRect.left(),
                        axisRect.left() - dx ) );
                }
                else
                {
                    const double minLeft = leftScaleRect.left();
                    const double left = axisRect.left() + leftOffset;
                    axisRect.setLeft( qMax( left, minLeft ) );
                }
            }
            else
            {
                if ( d_data->alignCanvasToScales && leftOffset < 0 )
                {
                    canvasRect.setLeft( qMax( canvasRect.left(),
                        axisRect.left() - leftOffset ) );
                }
                else
                {
                    if ( leftOffset > 0 )
                        axisRect.setLeft( axisRect.left() + leftOffset );
                }
            }

            const QRectF &rightScaleRect = scaleRect[QwtPlot::yRight];
            const int rightOffset =
                backboneOffset[QwtPlot::yRight] - endDist + 1;

            if ( rightScaleRect.isValid() )
            {
                const int dx = rightOffset + rightScaleRect.width();
                if ( d_data->alignCanvasToScales && dx < 0 )
                {
                    /*
                      The axis needs more space than the width
                      of the right scale.
                     */
                    canvasRect.setRight( qMin( canvasRect.right(),
                        axisRect.right() + dx ) );
                }   

                const double maxRight = rightScaleRect.right();
                const double right = axisRect.right() - rightOffset;
                axisRect.setRight( qMin( right, maxRight ) );
            }
            else
            {
                if ( d_data->alignCanvasToScales && rightOffset < 0 )
                {
                    canvasRect.setRight( qMin( canvasRect.right(),
                        axisRect.right() + rightOffset ) );
                }
                else
                {
                    if ( rightOffset > 0 )
                        axisRect.setRight( axisRect.right() - rightOffset );
                }
            }
        }
        else // QwtPlot::yLeft, QwtPlot::yRight
        {
            const QRectF &bottomScaleRect = scaleRect[QwtPlot::xBottom];
            const int bottomOffset =
                backboneOffset[QwtPlot::xBottom] - endDist + 1;

            if ( bottomScaleRect.isValid() )
            {
                const int dy = bottomOffset + bottomScaleRect.height();
                if ( d_data->alignCanvasToScales && dy < 0 )
                {
                    /*
                      The axis needs more space than the height
                      of the bottom scale.
                     */
                    canvasRect.setBottom( qMin( canvasRect.bottom(),
                        axisRect.bottom() + dy ) );
                }
                else
                {
                    const double maxBottom = bottomScaleRect.top() +
                        d_data->layoutData.scale[QwtPlot::xBottom].tickOffset;
                    const double bottom = axisRect.bottom() - bottomOffset;
                    axisRect.setBottom( qMin( bottom, maxBottom ) );
                }
            }
            else
            {
                if ( d_data->alignCanvasToScales && bottomOffset < 0 )
                {
                    canvasRect.setBottom( qMin( canvasRect.bottom(),
                        axisRect.bottom() + bottomOffset ) );
                }
                else
                {
                    if ( bottomOffset > 0 )
                        axisRect.setBottom( axisRect.bottom() - bottomOffset );
                }
            }

            const QRectF &topScaleRect = scaleRect[QwtPlot::xTop];
            const int topOffset = backboneOffset[QwtPlot::xTop] - startDist;

            if ( topScaleRect.isValid() )
            {
                const int dy = topOffset + topScaleRect.height();
                if ( d_data->alignCanvasToScales && dy < 0 )
                {
                    /*
                      The axis needs more space than the height
                      of the top scale.
                     */
                    canvasRect.setTop( qMax( canvasRect.top(),
                        axisRect.top() - dy ) );
                }
                else
                {
                    const double minTop = topScaleRect.bottom() -
                        d_data->layoutData.scale[QwtPlot::xTop].tickOffset;
                    const double top = axisRect.top() + topOffset;
                    axisRect.setTop( qMax( top, minTop ) );
                }
            }
            else
            {
                if ( d_data->alignCanvasToScales && topOffset < 0 )
                {
                    canvasRect.setTop( qMax( canvasRect.top(),
                        axisRect.top() - topOffset ) );
                }
                else
                {
                    if ( topOffset > 0 )
                        axisRect.setTop( axisRect.top() + topOffset );
                }
            }
        }
    }

    if ( d_data->alignCanvasToScales )
    {
        /*
          The canvas has been aligned to the scale with largest
          border distances. Now we have to realign the other scale.
         */

        int fw = 0;
        if ( !( options & IgnoreFrames ) )
            fw = d_data->layoutData.canvas.frameWidth;

        for ( int axis = 0; axis < QwtPlot::axisCnt; axis++ )
        {
            if ( !scaleRect[axis].isValid() )
                continue;

            if ( axis == QwtPlot::xBottom || axis == QwtPlot::xTop )
            {
                scaleRect[axis].setLeft( canvasRect.left() + fw
                    - d_data->layoutData.scale[axis].start );
                scaleRect[axis].setRight( canvasRect.right() - fw - 1
                    + d_data->layoutData.scale[axis].end );
            }   
            else
            {
                scaleRect[axis].setTop( canvasRect.top() + fw
                    - d_data->layoutData.scale[axis].start );
                scaleRect[axis].setBottom( canvasRect.bottom() - fw - 1
                    + d_data->layoutData.scale[axis].end );
            }
        }

        if ( scaleRect[QwtPlot::xTop].isValid() )
            scaleRect[QwtPlot::xTop].setBottom( canvasRect.top() );
        if ( scaleRect[QwtPlot::xBottom].isValid() )
            scaleRect[QwtPlot::xBottom].setTop( canvasRect.bottom() );
        if ( scaleRect[QwtPlot::yLeft].isValid() )
            scaleRect[QwtPlot::yLeft].setRight( canvasRect.left() );
        if ( scaleRect[QwtPlot::yRight].isValid() )
            scaleRect[QwtPlot::yRight].setLeft( canvasRect.right() );
    }
}
コード例 #29
0
static void clipSegmentToRect(qreal x0, qreal y0, qreal x1, qreal y1,
                              const QRectF &clipRect,
                              QVector<qreal> &outPoints,
                              QVector<QPainterPath::ElementType> &outTypes)
{
    int type0 = clipPointType(x0, y0, clipRect);
    int type1 = clipPointType(x1, y1, clipRect);
    bool accept = false;

    while (true) {
        if (!(type0 | type1)) {
            accept = true;
            break;
        } else if (type0 & type1) {
            break;
        } else {
            qreal x = 0.0;
            qreal y = 0.0;
            int outsideType = type0 ? type0 : type1;

            if (outsideType & BottomPoint) {
                x = x0 + (x1 - x0) * (clipRect.bottom() - y0) / (y1 - y0);
                y = clipRect.bottom() - 0.1;
            } else if (outsideType & TopPoint) {
                x = x0 + (x1 - x0) * (clipRect.top() - y0) / (y1 - y0);
                y = clipRect.top() + 0.1;
            } else if (outsideType & RightPoint) {
                y = y0 + (y1 - y0) * (clipRect.right() - x0) / (x1 - x0);
                x = clipRect.right() - 0.1;
            } else if (outsideType & LeftPoint) {
                y = y0 + (y1 - y0) * (clipRect.left() - x0) / (x1 - x0);
                x = clipRect.left() + 0.1;
            }

            if (outsideType == type0) {
                x0 = x;
                y0 = y;
                type0 = clipPointType(x0, y0, clipRect);
            } else {
                x1 = x;
                y1 = y;
                type1 = clipPointType(x1, y1, clipRect);
            }
        }
    }

    if (accept) {
        if (outPoints.size() >= 2) {
            qreal lastX, lastY;
            lastY = outPoints.at(outPoints.size() - 1);
            lastX = outPoints.at(outPoints.size() - 2);

            if (!qFuzzyCompare(lastY, y0) || !qFuzzyCompare(lastX, x0)) {
                outTypes << QPainterPath::MoveToElement;
                outPoints << x0 << y0;
            }
        } else {
            outTypes << QPainterPath::MoveToElement;
            outPoints << x0 << y0;
        }

        outTypes << QPainterPath::LineToElement;
        outPoints << x1 << y1;
    }
}
コード例 #30
0
ファイル: selection.cpp プロジェクト: nhoda/MrWriter
Selection::GrabZone Selection::grabZone(QPointF pagePos, qreal zoom)
{
  GrabZone grabZone = GrabZone::None;
  QRectF bRect = m_selectionPolygon.boundingRect();
  QRectF moveRect = bRect;

  qreal scaled_ad = m_ad / zoom;

  QRectF topRect = bRect;
  topRect.setTop(topRect.top() - scaled_ad);
  topRect.setHeight(scaled_ad);

  QRectF bottomRect = bRect;
  bottomRect.setTop(bottomRect.bottom());
  bottomRect.setHeight(scaled_ad);

  QRectF leftRect = bRect;
  leftRect.setLeft(leftRect.left() - scaled_ad);
  leftRect.setWidth(scaled_ad);

  QRectF rightRect = bRect;
  rightRect.setLeft(rightRect.right());
  rightRect.setWidth(scaled_ad);

  QRectF topLeftRect = bRect;
  topLeftRect.setLeft(topLeftRect.left() - scaled_ad);
  topLeftRect.setTop(topLeftRect.top() - scaled_ad);
  topLeftRect.setWidth(scaled_ad);
  topLeftRect.setHeight(scaled_ad);

  QRectF topRightRect = bRect;
  topRightRect.setLeft(topRightRect.right());
  topRightRect.setTop(topRightRect.top() - scaled_ad);
  topRightRect.setWidth(scaled_ad);
  topRightRect.setHeight(scaled_ad);

  QRectF bottomLeftRect = bRect;
  bottomLeftRect.setLeft(bottomLeftRect.left() - scaled_ad);
  bottomLeftRect.setTop(bottomLeftRect.bottom());
  bottomLeftRect.setWidth(scaled_ad);
  bottomLeftRect.setHeight(scaled_ad);

  QRectF bottomRightRect = bRect;
  bottomRightRect.setLeft(bottomRightRect.right());
  bottomRightRect.setTop(bottomRightRect.bottom());
  bottomRightRect.setWidth(scaled_ad);
  bottomRightRect.setHeight(scaled_ad);

  QRectF rotateRect = bRect;
  rotateRect.setTop(rotateRect.top() - 1.0 * scaled_ad - (m_rotateRectCenter + m_rotateRectRadius) / zoom);
  rotateRect.setLeft(rotateRect.center().x() - m_rotateRectRadius / zoom);
  rotateRect.setWidth(2.0 * m_rotateRectRadius / zoom);
  rotateRect.setHeight(2.0 * m_rotateRectRadius / zoom);

  if (moveRect.contains(pagePos))
  {
    grabZone = GrabZone::Move;
  }
  else if (topRect.contains(pagePos))
  {
    grabZone = GrabZone::Top;
  }
  else if (bottomRect.contains(pagePos))
  {
    grabZone = GrabZone::Bottom;
  }
  else if (leftRect.contains(pagePos))
  {
    grabZone = GrabZone::Left;
  }
  else if (rightRect.contains(pagePos))
  {
    grabZone = GrabZone::Right;
  }
  else if (topLeftRect.contains(pagePos))
  {
    grabZone = GrabZone::TopLeft;
  }
  else if (topRightRect.contains(pagePos))
  {
    grabZone = GrabZone::TopRight;
  }
  else if (bottomLeftRect.contains(pagePos))
  {
    grabZone = GrabZone::BottomLeft;
  }
  else if (bottomRightRect.contains(pagePos))
  {
    grabZone = GrabZone::BottomRight;
  }
  else if (rotateRect.contains(pagePos))
  {
    grabZone = GrabZone::Rotate;
  }
  qInfo() << bRect;
  qInfo() << rotateRect;
  return grabZone;
}