/*! 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();
}
Exemple #2
0
void KPrTimeLineView::mouseMoveEvent(QMouseEvent *event)
{
    // Resize the bar
    if (m_resize) {
        const qreal subSteps = 0.2;
        int startPos = 0;
        for (int i = 0; i < KPrShapeAnimations::StartTime; i++) {
            startPos = startPos + m_mainView->widthOfColumn(i);
        }
        int row = m_resizedRow;
        //calculate real start
        qreal startOffSet = m_mainView->calculateStartOffset(row) / 1000.0;

        qreal start = m_mainView->model()->data(m_mainView->model()->index(row, KPrShapeAnimations::StartTime)).toInt() / 1000.0;
        qreal duration = m_mainView->model()->data(m_mainView->model()->index(row, KPrShapeAnimations::Duration)).toInt() / 1000.0;
        qreal totalSteps = m_mainView->numberOfSteps();
        qreal stepSize  = m_mainView->widthOfColumn( KPrShapeAnimations::StartTime) / totalSteps;

        if ((event->pos().x() > (startPos + startOffSet*stepSize + stepSize * start - 5)) &&
                ((event->pos().x()) < (startPos + m_mainView->widthOfColumn( KPrShapeAnimations::StartTime)))) {
            qreal newLength = (event->pos().x() - startPos - stepSize * start) / (stepSize) - startOffSet;
            newLength = qFloor((newLength - modD(newLength, subSteps)) * 100.0) / 100.0;
            // update bar length
            m_mainView->model()->setData(m_mainView->model()->index(row, KPrShapeAnimations::Duration), newLength * 1000);
            emit timeValuesChanged(m_mainView->model()->index(row, KPrShapeAnimations::Duration));
            m_adjust = false;
            if (newLength < duration)
                m_adjust = true;
        } else if ( ((event->pos().x()) > (startPos + m_mainView->widthOfColumn( KPrShapeAnimations::StartTime)))) {
            m_mainView->incrementScale();
            m_adjust = true;
        }
        update();
    }
    //Move the bar
    if (m_move) {
        const int Padding = 2;
        int startPos = 0;
        const qreal subSteps = 0.2;
        for (int i = 0; i < KPrShapeAnimations::StartTime; i++) {
            startPos = startPos + m_mainView->widthOfColumn(i);
        }
        int row = m_resizedRow;
        //calculate real start
        qreal startOffSet = m_mainView->calculateStartOffset(row) / 1000;
        qreal duration = m_mainView->model()->data(m_mainView->model()->index(row, KPrShapeAnimations::Duration)).toInt() / 1000.0;
        qreal start = m_mainView->model()->data(m_mainView->model()->index(row, KPrShapeAnimations::StartTime)).toInt() / 1000.0;
        qreal totalSteps = m_mainView->numberOfSteps();
        qreal stepSize  = m_mainView->widthOfColumn(KPrShapeAnimations::StartTime) / totalSteps;
        qreal Threshold = 0.4;
        if ((event->pos().x() > (startPos + startDragPos + startOffSet*stepSize)) &&
                ((event->pos().x() + (duration * stepSize - startDragPos) + Padding * 2)  <
                 (startPos+m_mainView->widthOfColumn( KPrShapeAnimations::StartTime)))) {
            qreal newPos = (event->pos().x() - (startPos + startDragPos)) / (stepSize) - startOffSet;
            newPos = qFloor((newPos - modD(newPos, subSteps)) * 100.0) / 100.0;
            // update bar position
            m_mainView->model()->setData(m_mainView->model()->index(row, KPrShapeAnimations::StartTime), newPos * 1000);
            emit timeValuesChanged(m_mainView->model()->index(row, KPrShapeAnimations::StartTime));
            m_adjust = false;
            if (newPos <= start) {
                m_adjust = true;
            }
        }
        else if (((event->pos().x() + (duration*stepSize-startDragPos) + Padding * 2)  >
                    (startPos + m_mainView->widthOfColumn( KPrShapeAnimations::StartTime)))) {
            m_mainView->incrementScale();
        }
        else if (event->pos().x() < (startPos + startDragPos + startOffSet * stepSize + Threshold)) {
            m_mainView->changeStartLimit(row);
        }
        update();
    }
    int row = rowAt(event->y());
    int column = columnAt(event->x());
    if (column == KPrShapeAnimations::StartTime) {
        QRectF lineRect = getRowRect(row, column);
        QRectF endLineRect = QRectF(lineRect.right() - RESIZE_RADIUS, lineRect.top() + BAR_MARGIN,
                                    RESIZE_RADIUS * 2,  lineRect.height() - 2 * BAR_MARGIN);

        // If the user is near the end of the line they could resize
        if (endLineRect.contains(event->x(), event->y())) {
            setCursor(Qt::SizeHorCursor);
        }
        else {
            if (lineRect.contains(event->x(), event->y())) {
                setCursor(
#if QT_VERSION >= 0x040700
                          Qt::DragMoveCursor
#else
                          Qt::ClosedHandCursor
#endif
                          );
            }
            else {
                setCursor(Qt::ArrowCursor);
            }
        }
    }
    QWidget::mouseMoveEvent(event);
}
Exemple #3
0
  //-----------------------------------------------------------------------
  // Class MacroItem
  //-----------------------------------------------------------------------
  void MacroItem::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget)
  {
    app::Macro::Ptr macroInstance = vertex().dataRef().staticCast<app::Macro>();
    Q_ASSERT(!macroInstance.isNull());

    graph::VertexItem::paint(painter,option,widget);
    QRectF rcInner = innerRect();

    // calculate text sizes
    QString macroName = macroInstance->getName();
    QFontMetrics fmName(*Resource::font(Resource::FONT_MACRONAME));
    QRect rectName = fmName.boundingRect(macroName);
    QString macroRuntime = macroInstance->getRuntimeString();
    QFontMetrics fmStatus(*Resource::font(Resource::FONT_MACROSTATUS));
    QRect rectRuntime = fmStatus.boundingRect("000.000 ms");
    QPixmap statusIcon;
    switch(macroInstance->getState())
    {
      case app::Macro::Idle:
        statusIcon = QPixmap(":/icons/resources/bullet_black.png");
        break;
      case app::Macro::Running:
        statusIcon = QPixmap(":/icons/resources/bullet_orange.png");
        break;
      case app::Macro::Ok:
        if (!toolTip().isEmpty()) setToolTip(QString());
        statusIcon = QPixmap(":/icons/resources/bullet_green.png");
        break;
      case app::Macro::Failure:
        setToolTip(macroInstance->getErrorMsg());
        statusIcon = QPixmap(":/icons/resources/bullet_red.png");
        break;
    }
    QString macroOrder = QString(QObject::tr("Order No.: "));
    if (vertex().topologicalOrder() >= 0)
    {
      macroOrder += QString("%1").arg(vertex().topologicalOrder());
    }
    else
    {
      macroOrder += '-';
    }
    QPixmap orderStatus;
    if (vertex().isInCycle() && vertex().topologicalOrder() == 0 && vertex().topologicalOrderForced())
    {
      orderStatus = QPixmap(":/icons/resources/anchor.png");
    }
    else if (vertex().isInCycle() && vertex().topologicalOrder() < 0 && !vertex().topologicalOrderForced())
    {
      orderStatus = QPixmap(":/icons/resources/cycle.png");
    }
    else if (!vertex().isInCycle() && vertex().topologicalOrder() < 0)
    {
      orderStatus = QPixmap(":/icons/resources/error.png");
    }
    QRect rectOrder = fmStatus.boundingRect(macroOrder);
    rectOrder.adjust(0,0,orderStatus.width(),16 - rectOrder.height());

    // paint macro name
    QRectF rcTextName(rcInner.left(),rcInner.top(),rcInner.width(),(qreal)rectName.height());
    painter->setPen(QPen(Qt::black));
    painter->setFont(*Resource::font(Resource::FONT_MACRONAME));
    painter->drawText(rcTextName,Qt::AlignCenter,macroName);
    // paint runtime including indicator
    QRectF rcTextRuntime(rcInner.left() + rcInner.width() * 0.02 + statusIcon.width(),rcInner.top() + rectName.height() + 1.0,rcInner.width() - 2 * rcInner.width() * 0.02 - statusIcon.width(),(qreal)rectRuntime.height());
    painter->setPen(QPen(Qt::blue));
    painter->setFont(*Resource::font(Resource::FONT_MACROSTATUS));
    painter->setClipRect(rcTextRuntime);
    painter->drawText(rcTextRuntime,Qt::AlignRight,macroRuntime);
    painter->setClipRect(rcInner);
    painter->drawPixmap(rcInner.left() + rcInner.width() * 0.02,rcTextRuntime.top(),statusIcon.rect().width(),statusIcon.rect().height(),statusIcon);
    // paint topological order
    QRectF rcTextOrder(rcInner.left() + orderStatus.rect().width() + (rcInner.width() - rectOrder.width()) / 2.0,rcInner.bottom() - (qreal)rectOrder.height(),rcInner.width(),(qreal)rectOrder.height());
    painter->setPen(QPen(Qt::black));
    painter->drawText(rcTextOrder,Qt::AlignLeft,macroOrder);
    if (!orderStatus.isNull())
    {
      painter->drawPixmap(rcTextOrder.left() - orderStatus.rect().width() - 1.0,rcTextOrder.top(),orderStatus.rect().width(),orderStatus.rect().height(),orderStatus);
    }
    painter->setClipRect(itemRect());
  }
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;
    }
}
Exemple #5
0
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() );
    }
}
	QRectF closeButtonRect(const QRectF& rect) const {
		return QRectF(rect.right()-closeButtonRectSize, rect.top(), closeButtonRectSize, closeButtonRectSize);
	}
/*!
  \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 );
}
Exemple #8
0
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;
    }
}
Exemple #9
0
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);
}
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;
    }
}
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;
    }
}
static QPointF topCenter(const QRectF &rect)
{
    return QPointF(rect.center().x(), rect.top());
}
Exemple #13
0
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();
            }
        }
    }
}
Exemple #14
0
QRectF QgsComposerItem::evalItemRect( const QRectF &newRect, const bool resizeOnly, const QgsExpressionContext* context )
{
  QRectF result = newRect;

  //TODO QGIS 3.0
  //maintain pre 2.12 API. remove when API break allowed
  QScopedPointer< QgsExpressionContext > scopedContext;
  const QgsExpressionContext* evalContext = context;
  if ( !evalContext )
  {
    scopedContext.reset( createExpressionContext() );
    evalContext = scopedContext.data();
  }

  //data defined position or size set? if so, update rect with data defined values
  QVariant exprVal;
  //evaulate width and height first, since they may affect position if non-top-left reference point set
  if ( dataDefinedEvaluate( QgsComposerObject::ItemWidth, exprVal, *evalContext ) )
  {
    bool ok;
    double width = exprVal.toDouble( &ok );
    QgsDebugMsg( QString( "exprVal Width:%1" ).arg( width ) );
    if ( ok && !exprVal.isNull() )
    {
      result.setWidth( width );
    }
  }
  if ( dataDefinedEvaluate( QgsComposerObject::ItemHeight, exprVal, *evalContext ) )
  {
    bool ok;
    double height = exprVal.toDouble( &ok );
    QgsDebugMsg( QString( "exprVal Height:%1" ).arg( height ) );
    if ( ok && !exprVal.isNull() )
    {
      result.setHeight( height );
    }
  }

  double x = result.left();
  //initially adjust for position mode to get x coordinate
  if ( !resizeOnly )
  {
    //adjust x-coordinate if placement is not done to a left point
    if ( mLastUsedPositionMode == UpperMiddle || mLastUsedPositionMode == Middle || mLastUsedPositionMode == LowerMiddle )
    {
      x += newRect.width() / 2.0;
    }
    else if ( mLastUsedPositionMode == UpperRight || mLastUsedPositionMode == MiddleRight || mLastUsedPositionMode == LowerRight )
    {
      x += newRect.width();
    }
  }
  else
  {
    if ( mLastUsedPositionMode == UpperMiddle || mLastUsedPositionMode == Middle || mLastUsedPositionMode == LowerMiddle )
    {
      x += rect().width() / 2.0;
    }
    else if ( mLastUsedPositionMode == UpperRight || mLastUsedPositionMode == MiddleRight || mLastUsedPositionMode == LowerRight )
    {
      x += rect().width();
    }
  }
  if ( dataDefinedEvaluate( QgsComposerObject::PositionX, exprVal, *evalContext ) )
  {
    bool ok;
    double positionX = exprVal.toDouble( &ok );
    QgsDebugMsg( QString( "exprVal Position X:%1" ).arg( positionX ) );
    if ( ok && !exprVal.isNull() )
    {
      x = positionX;
    }
  }

  double y = result.top();
  //initially adjust for position mode to get y coordinate
  if ( !resizeOnly )
  {
    //adjust y-coordinate if placement is not done to an upper point
    if ( mLastUsedPositionMode == MiddleLeft || mLastUsedPositionMode == Middle || mLastUsedPositionMode == MiddleRight )
    {
      y += newRect.height() / 2.0;
    }
    else if ( mLastUsedPositionMode == LowerLeft || mLastUsedPositionMode == LowerMiddle || mLastUsedPositionMode == LowerRight )
    {
      y += newRect.height();
    }
  }
  else
  {
    if ( mLastUsedPositionMode == MiddleLeft || mLastUsedPositionMode == Middle || mLastUsedPositionMode == MiddleRight )
    {
      y += rect().height() / 2.0;
    }
    else if ( mLastUsedPositionMode == LowerLeft || mLastUsedPositionMode == LowerMiddle || mLastUsedPositionMode == LowerRight )
    {
      y += rect().height();
    }
  }
  if ( dataDefinedEvaluate( QgsComposerObject::PositionY, exprVal, *evalContext ) )
  {
    bool ok;
    double positionY = exprVal.toDouble( &ok );
    QgsDebugMsg( QString( "exprVal Position Y:%1" ).arg( positionY ) );
    if ( ok && !exprVal.isNull() )
    {
      y = positionY;
    }
  }

  //adjust x-coordinate if placement is not done to a left point
  if ( mLastUsedPositionMode == UpperMiddle || mLastUsedPositionMode == Middle || mLastUsedPositionMode == LowerMiddle )
  {
    x -= result.width() / 2.0;
  }
  else if ( mLastUsedPositionMode == UpperRight || mLastUsedPositionMode == MiddleRight || mLastUsedPositionMode == LowerRight )
  {
    x -= result.width();
  }

  //adjust y-coordinate if placement is not done to an upper point
  if ( mLastUsedPositionMode == MiddleLeft || mLastUsedPositionMode == Middle || mLastUsedPositionMode == MiddleRight )
  {
    y -= result.height() / 2.0;
  }
  else if ( mLastUsedPositionMode == LowerLeft || mLastUsedPositionMode == LowerMiddle || mLastUsedPositionMode == LowerRight )
  {
    y -= result.height();
  }

  result.moveLeft( x );
  result.moveTop( y );

  return result;
}
Exemple #15
0
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 );
        }
    }
}
Exemple #16
0
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;
}
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;
}   
QIcon StereotypeController::createIcon(StereotypeIcon::Element element, const QList<QString> &stereotypes,
                                       const QString &defaultIconPath, const Style *style, const QSize &size,
                                       const QMarginsF &margins, qreal lineWidth)
{
    IconKey key(element, stereotypes, defaultIconPath, style->uid(), size, margins, lineWidth);
    QIcon icon = d->m_iconMap.value(key);
    if (!icon.isNull())
        return icon;
    QString stereotypeIconId = findStereotypeIconId(element, stereotypes);
    if (!stereotypeIconId.isEmpty()) {
        StereotypeIcon stereotypeIcon = findStereotypeIcon(stereotypeIconId);

        // calculate bounding rectangle relativ to original icon size
        ShapeSizeVisitor sizeVisitor(QPointF(0.0, 0.0),
                                     QSizeF(stereotypeIcon.width(), stereotypeIcon.height()),
                                     QSizeF(stereotypeIcon.width(), stereotypeIcon.height()),
                                     QSizeF(stereotypeIcon.width(), stereotypeIcon.height()));
        stereotypeIcon.iconShape().visitShapes(&sizeVisitor);
        QRectF iconBoundingRect = sizeVisitor.boundingRect();

        // calc painting space within margins
        qreal innerWidth = size.width() - margins.left() - margins.right();
        qreal innerHeight = size.height() - margins.top() - margins.bottom();

        // calculate width/height ratio from icon size
        qreal widthRatio = 1.0;
        qreal heightRatio = 1.0;
        qreal ratio = stereotypeIcon.width() / stereotypeIcon.height();
        if (ratio > 1.0)
            heightRatio /= ratio;
        else
            widthRatio *= ratio;

        // calculate inner painting area
        qreal paintWidth = stereotypeIcon.width() * innerWidth / iconBoundingRect.width() * widthRatio;
        qreal paintHeight = stereotypeIcon.height() * innerHeight / iconBoundingRect.height() * heightRatio;
        // icons which renders smaller than their size should not be zoomed
        if (paintWidth > innerWidth) {
            paintHeight *= innerWidth / paintHeight;
            paintWidth = innerWidth;
        }
        if (paintHeight > innerHeight) {
            paintWidth *= innerHeight / paintHeight;
            paintHeight = innerHeight;
        }

        // calculate offset of top/left edge
        qreal paintLeft = iconBoundingRect.left() * paintWidth / stereotypeIcon.width();
        qreal paintTop = iconBoundingRect.top() * paintHeight / stereotypeIcon.height();

        // calculate total painting size
        qreal totalPaintWidth = iconBoundingRect.width() * paintWidth / stereotypeIcon.width();
        qreal totalPaintHeight = iconBoundingRect.height() * paintHeight / stereotypeIcon.height();

        QPixmap pixmap(size);
        pixmap.fill(Qt::transparent);
        QPainter painter(&pixmap);
        painter.setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing | QPainter::SmoothPixmapTransform);
        painter.setBrush(Qt::NoBrush);
        // set painting origin taking margin, offset and centering into account
        painter.translate(QPointF(margins.left(), margins.top()) - QPointF(paintLeft, paintTop)
                          + QPointF((innerWidth - totalPaintWidth) / 2, (innerHeight - totalPaintHeight) / 2));
        QPen linePen = style->linePen();
        linePen.setWidthF(lineWidth);
        painter.setPen(linePen);
        painter.setBrush(style->fillBrush());

        ShapePaintVisitor visitor(&painter, QPointF(0.0, 0.0),
                                  QSizeF(stereotypeIcon.width(), stereotypeIcon.height()),
                                  QSizeF(paintWidth, paintHeight), QSizeF(paintWidth, paintHeight));
        stereotypeIcon.iconShape().visitShapes(&visitor);

        icon = QIcon(pixmap);
    }
    if (icon.isNull() && !defaultIconPath.isEmpty())
        icon = QIcon(defaultIconPath);
    d->m_iconMap.insert(key, icon);
    return icon;

}
GRect GAppHelper::QRectF2GRect(const QRectF &other)
{
    return GRect(other.left(), other.top(),
                 other.right(), other.bottom());
}
Exemple #20
0
void KConfigGroup::writeEntry( const char* key, const QVariant &value,
                               WriteConfigFlags flags )
{
    Q_ASSERT_X(isValid(), "KConfigGroup::writeEntry", "accessing an invalid group");
    Q_ASSERT_X(!d->bConst, "KConfigGroup::writeEntry", "writing to a read-only group");

    if ( writeEntryGui( this, key, value, flags ) )
        return;                     // GUI type that was handled

    QByteArray data;
    // if a type handler is added here you must add a QVConversions definition
    // to conversion_check.h, or ConversionCheck::to_QVariant will not allow
    // writeEntry<T> to convert to QVariant.
    switch( value.type() ) {
        case QVariant::Invalid:
            data = "";
            break;
        case QVariant::ByteArray:
            data = value.toByteArray();
            break;
        case QVariant::String:
        case QVariant::Int:
        case QVariant::UInt:
        case QVariant::Double:
        case QMetaType::Float:
        case QVariant::Bool:
        case QVariant::LongLong:
        case QVariant::ULongLong:
            data = value.toString().toUtf8();
            break;
        case QVariant::List:
            if (!value.canConvert(QVariant::StringList))
                qWarning() << "not all types in \"" << key << "\" can convert to QString,"
                   " information will be lost";
        case QVariant::StringList:
            writeEntry( key, value.toList(), flags );
            return;
        case QVariant::Point: {
            QVariantList list;
            const QPoint rPoint = value.toPoint();
            list.insert( 0, rPoint.x() );
            list.insert( 1, rPoint.y() );

            writeEntry( key, list, flags );
            return;
        }
        case QVariant::PointF: {
            QVariantList list;
            const QPointF point = value.toPointF();
            list.insert( 0, point.x() );
            list.insert( 1, point.y() );

            writeEntry( key, list, flags );
            return;
        }
        case QVariant::Rect:{
            QVariantList list;
            const QRect rRect = value.toRect();
            list.insert( 0, rRect.left() );
            list.insert( 1, rRect.top() );
            list.insert( 2, rRect.width() );
            list.insert( 3, rRect.height() );

            writeEntry( key, list, flags );
            return;
        }
        case QVariant::RectF:{
            QVariantList list;
            const QRectF rRectF = value.toRectF();
            list.insert(0, rRectF.left());
            list.insert(1, rRectF.top());
            list.insert(2, rRectF.width());
            list.insert(3, rRectF.height());

            writeEntry(key, list, flags);
            return;
        }
        case QVariant::Size:{
            QVariantList list;
            const QSize rSize = value.toSize();
            list.insert( 0, rSize.width() );
            list.insert( 1, rSize.height() );

            writeEntry( key, list, flags );
            return;
        }
        case QVariant::SizeF:{
            QVariantList list;
            const QSizeF rSizeF = value.toSizeF();
            list.insert(0, rSizeF.width());
            list.insert(1, rSizeF.height());

            writeEntry(key, list, flags);
            return;
        }
        case QVariant::Date: {
            QVariantList list;
            const QDate date = value.toDate();

            list.insert( 0, date.year() );
            list.insert( 1, date.month() );
            list.insert( 2, date.day() );

            writeEntry( key, list, flags );
            return;
        }
        case QVariant::DateTime: {
            QVariantList list;
            const QDateTime rDateTime = value.toDateTime();

            const QTime time = rDateTime.time();
            const QDate date = rDateTime.date();

            list.insert( 0, date.year() );
            list.insert( 1, date.month() );
            list.insert( 2, date.day() );

            list.insert( 3, time.hour() );
            list.insert( 4, time.minute() );
            list.insert( 5, time.second() );

            writeEntry( key, list, flags );
            return;
        }

        case QVariant::Color:
        case QVariant::Font:
            qWarning() << "KConfigGroup::writeEntry was passed GUI type '"
                     << value.typeName()
                     << "' but kdeui isn't linked! If it is linked to your program, this is a platform bug. "
                        "Please inform the KDE developers";
            break;
        case QVariant::Url:
            data = QUrl(value.toUrl()).toString().toUtf8();
            break;
        default:
            qWarning() << "KConfigGroup::writeEntry - unhandled type" << value.typeName() << "in group" << name();
        }

    writeEntry(key, data, flags);
}
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
}
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();
}
Exemple #23
0
void GlslPainter::paint(QPainter *painter,
                        QRectF target,
                        QQuickWindow *window)
{
    // Need to reenable those after native painting has begun, otherwise we might
    // not be able to paint anything.
    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);

    //////////////////////////////////////////////////////////////
    initTextures();
    //////////////////////////////////////////////////////////////

    // As seen on the telly
#ifdef __GNUC__
#warning DUPLICATED CODE
#endif

    const float textureCoordinates[] = {
        0, 1, // bottom left
        1, 1, // bottom right
        0, 0, // top left
        1, 0, // top right
    };

    const GLfloat targetVertex[] =
    {
        GLfloat(target.left()), GLfloat(target.bottom()),
        GLfloat(target.right()), GLfloat(target.bottom()),
        GLfloat(target.left()) , GLfloat(target.top()),
        GLfloat(target.right()), GLfloat(target.top())
    };
    //

    const int width = window->width();
    const int height = window->height();

    const QTransform transform = painter->deviceTransform();

    const GLfloat wfactor = 2.0 / width;
    const GLfloat hfactor = -2.0 / height;

    const GLfloat positionMatrix[4][4] = {
        {
            GLfloat(wfactor * transform.m11() - transform.m13()),
            GLfloat(hfactor * transform.m12() + transform.m13()),
            0.0,
            GLfloat(transform.m13())
        }, {
            GLfloat(wfactor * transform.m21() - transform.m23()),
            GLfloat(hfactor * transform.m22() + transform.m23()),
            0.0,
            GLfloat(transform.m23())
        }, {
            0.0,
            0.0,
            -1.0,
            0.0
        }, {
            GLfloat(wfactor * transform.dx() - transform.m33()),
            GLfloat(hfactor * transform.dy() + transform.m33()),
            0.0,
            GLfloat(transform.m33())
        }
    };

    _program->bind();

    _program->enableAttributeArray("targetVertex");
    _program->enableAttributeArray("textureCoordinates");
    _program->setAttributeArray("targetVertex", targetVertex, 2);
    _program->setAttributeArray("textureCoordinates", textureCoordinates, 2);
    _program->setUniformValue("positionMatrix", positionMatrix);

    if (_textureCount == 3) {
        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, _textureIds[0]);
        glActiveTexture(GL_TEXTURE1);
        glBindTexture(GL_TEXTURE_2D, _textureIds[1]);
        glActiveTexture(GL_TEXTURE2);
        glBindTexture(GL_TEXTURE_2D, _textureIds[2]);
        glActiveTexture(GL_TEXTURE0);

        _program->setUniformValue("texY", 0);
        _program->setUniformValue("texU", 1);
        _program->setUniformValue("texV", 2);
    }
    _program->setUniformValue("colorMatrix", _colorMatrix);
    _program->setUniformValue("opacity", GLfloat(painter->opacity()));

    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

    _program->release();
    painter->endNativePainting();

#if !defined(Q_OS_WIN)
    // TODO: FPS optional
    calculateFPS();
    addFPSOverlay();
#endif
}
Exemple #24
0
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;
	}
    }
}
QList<KWViewMode::ViewMap> KWViewModeNormal::mapExposedRects(const QRectF &viewRect, KoViewConverter *viewConverter) const
{
    QList<ViewMap> answer;
    if (!viewConverter) return answer;

#if 1
    if (m_pageTops.isEmpty())
        return answer;
    KWPage page  = m_pageManager->begin();
    const int pageOffset = page.pageNumber();

    // Perform a binary search for page-index using our m_pageTops cache.
    int begin = 0;
    int end = m_pageTops.count() - 1;
    int index = 0;
    const qreal value = viewConverter->viewToDocument(viewRect.topLeft()).y();
    if (m_pageTops.value(end) <= value) { // check extremes. Only end is needed since begin is zero.
        begin = end;
        index = end;
    }
    while (end - begin > 1) {
        index = begin + (end - begin) / 2;
        qreal diff = m_pageTops.value(index) - value;
        if (diff < 0)
            begin = index;
        else if (diff > 0)
            end = index;
        else
            break;
    }
    // index is now the number of the first possible page that can
    // contain the viewRect.  The next step is to find the
    // corresponding Page.  Since we have no way to get to the Nth
    // page directly we have to enumerate them from the beginning.
    //
    // We use 1 since we might hit a pagespread in the binary search,
    // so start one page early.
    while (index > 1) { 
        page = page.next();
        --index;
    }

    // From here we loop through some more pages after the found one
    // and see if they intersect with the page in question.  When we
    // have two pages in row that don't intersect we break the loop.
    qreal offsetX = 0.0;
    int emptyPages = 0;
    for(; page.isValid(); page = page.next()) {
        Q_ASSERT_X(page.pageNumber()-pageOffset < m_pageTops.count(), __FUNCTION__,
                   QString("Pagemanager has more pages than viewmode (%1>%2 with pageOffset=%3 and pageNumber=%4 and pageCount=%5). Make sure you add pages via the document!")
                   .arg(page.pageNumber()-pageOffset).arg(m_pageTops.count())
                   .arg(pageOffset).arg(page.pageNumber()).arg(m_pageManager->pageCount()).toLocal8Bit());


        // Some invariants
        const QRectF pageRect = page.rect();
        const qreal offsetY = m_pageTops[page.pageNumber() - pageOffset] - pageRect.top();

        bool pageIntersects = false;

        // 1. First handle the page itself.
        const QRectF zoomedPage = viewConverter->documentToView(pageRect);
        ViewMap vm;
        vm.page = page;
        //kDebug(32003) <<"page" << page.pageNumber();
        vm.distance = viewConverter->documentToView(QPointF(offsetX, offsetY));

        const QRectF targetPage(zoomedPage.x() + vm.distance.x(), zoomedPage.y() + vm.distance.y(),
                                zoomedPage.width(), zoomedPage.height());
        QRectF intersection = targetPage.intersect(viewRect);
        if (! intersection.isEmpty()) {
            intersection.moveTopLeft(intersection.topLeft() - vm.distance);
            vm.clipRect = intersection.toRect();
            answer.append(vm);
            pageIntersects = true;
        }

        // 2. Then handle the annotation area if annotations are active.
        //
        //    The reason we don't do them together with the page
        //    itself is because the pages have a gap between them, but
        //    the annotation area should be unbroken.
        //
        // NOTE: 'annotation' below means the annotation area.
        //
        // FIXME: We should only do this if the annotation area is
        //        actually shown. How can we inside the KWViewMode
        //        know if annotations are active?
        if (1 /* annotations are shown */) {
            const QRectF annotationRect = pageRect.adjusted(page.width(), 0,
                                                            KWCanvasBase::AnnotationAreaWidth, GAP);
            const QRectF zoomedAnnotation = viewConverter->documentToView(annotationRect);
            ViewMap vm2;
            vm2.page = page;
            vm2.distance = viewConverter->documentToView(QPointF(offsetX, offsetY));

            const QRectF targetAnnotation(zoomedAnnotation.x() + vm2.distance.x(),
                                          zoomedAnnotation.y() + vm2.distance.y(),
                                          zoomedAnnotation.width(), zoomedAnnotation.height());
            intersection = targetAnnotation.intersect(viewRect);
            if (! intersection.isEmpty()) {
                intersection.moveTopLeft(intersection.topLeft() - vm2.distance);
                vm2.clipRect = intersection.toRect();
                answer.append(vm2);
                pageIntersects = true;
            }
        }

        // Record whether this page had an intersection with the view rect.
        if (pageIntersects) {
            emptyPages = 0;
        } else {
            ++emptyPages;
        }
        if (emptyPages > 2) // Since we show at max 2 pages side by side this is an easy rule
            break;

        if (m_pageSpreadMode) {
            if (page.pageSide() == KWPage::Left)
                offsetX = page.width() + GAP;
            else
                offsetX = 0.0;
        }
    }
#else
    KWPage page  = m_pageManager->begin();
    Q_ASSERT(page.isValid());
    qreal offsetX = 0.0;
    const int pageOffset = page.pageNumber();
    for(; page.isValid(); page = page.next()) {
        const QRectF pageRect = page.rect();
        const QRectF zoomedPage = viewConverter->documentToView(pageRect);
        ViewMap vm;
        vm.page = page;

        const qreal offsetY = m_pageTops[page.pageNumber() - pageOffset] - pageRect.top();
        vm.distance = viewConverter->documentToView(QPointF(offsetX, offsetY));
#if 0
        const QRectF targetPage(zoomedPage.x() + vm.distance.x(), zoomedPage.y() + vm.distance.y(), zoomedPage.width() , zoomedPage.height());
        QRectF intersection = targetPage.intersect(viewRect);
        if (! intersection.isEmpty()) {
            intersection.moveTopLeft(intersection.topLeft() - vm.distance);
            vm.clipRect = intersection.toRect();
            answer.append(vm);
        }
#else
        const QRectF targetPage(zoomedPage.x() + vm.distance.x(), zoomedPage.y() + vm.distance.y(), zoomedPage.width() , zoomedPage.height());
        vm.clipRect = targetPage.toRect();
        answer.append(vm);
#endif
    }
#endif
    return answer;
}
void WTextSourceViewerLine::paintEvent ( QPaintEvent * ev_p )
{
  QPainter p(this);
  bool place_for_comment=!commented_lines.isEmpty();

  p.setRenderHint(QPainter::SmoothPixmapTransform );
  p.setRenderHint( QPainter::Antialiasing);
  
  p.setClipRect(ev_p->rect());
  p.translate(1,-translation_y);
  p.setFont(font());
  p.setPen(QPen(Qt::black,0));
  QAbstractTextDocumentLayout::PaintContext context;
  QRect r=ev_p->rect();
  if (text_document_p)
  {
    QRectF lineRect;
    int last_line=0;
    QPointF folding_pos_close;
    QPointF folding_pos_open_start;
    QPointF folding_pos_open_end;
    bool has_folding_close=false;
    bool has_folding_open=false;
    bool last_block_contains_instrumentation=true;
    for (QTextBlock textBlock=text_document_p->begin();
        textBlock!=text_document_p->end();
        textBlock=textBlock.next())
    {
      TextSourceInstrumentationData *instrumentationData=dynamic_cast<TextSourceInstrumentationData*> (textBlock.userData());
      if (instrumentationData)
      {
        int current_line = instrumentationData->current_line;
        lineRect=text_document_p->documentLayout()->blockBoundingRect(textBlock);
        QRectF line_text_area(char_space*(2.0f+ (place_for_comment?1:0) ),lineRect.top(),width()-char_space*2.0f,lineRect.height());
        QRectF comment_area(char_space*2,lineRect.top(),img_comment_scaled.width(),img_comment_scaled.height());

        bool instrumentation_point=false;
        for (QVector<TextSourceInstrumentationData::InstrumentationData>::const_iterator it=instrumentationData->instrumentations.begin();it!=instrumentationData->instrumentations.end();++it)
        {
          Instrumentation::status_t st=(*it).status(instrumentationData->coverage_level,instrumentationData->coverage_method);
          if ( st != Instrumentation::STATUS_NONE )
          {
            instrumentation_point=true;
            break;
          }
        }

        if (instrumentation_point)
        {
          QRectF backRect(0,lineRect.top(),width(),lineRect.height());
          p.drawText(line_text_area,Qt::AlignVCenter|Qt::AlignLeft,QString::number(current_line));
          last_block_contains_instrumentation=true;
          if (has_folding_open)
            drawFoldingLineVisible(p,folding_pos_open_start,folding_pos_open_end);
          bool current_line_has_comment=commented_lines.contains(current_line);
          if (current_line_has_comment)
            p.drawImage(comment_area,img_comment_scaled);
          if (last_line+1!=current_line)
          {
            if (has_folding_close)
              drawFoldingLineHidden(p,folding_pos_close);
            if (current_line_has_comment || !place_for_comment)
              folding_pos_close.setX(char_space*1.5f);
            else
              folding_pos_close.setX(char_space*2.5f);
            folding_pos_close.setY((lineRect.bottom()+lineRect.top())/2);
            drawFoldingLineHidden(p,folding_pos_close);
          }
          else
          {
            if (current_line_has_comment || !place_for_comment)
              folding_pos_close.setX(char_space*1.5f);
            else
              folding_pos_close.setX(char_space*2.5f);
            folding_pos_close.setY((lineRect.bottom()+lineRect.top())/2);
          }
          has_folding_open=false;
          has_folding_close=true;
        }
        else
        {
          if ( (has_folding_close) && (last_line+1!=current_line) )
            drawFoldingLineHidden(p,folding_pos_close);
          if (place_for_comment)
             folding_pos_open_end.setX(char_space*2.5f);
          else
             folding_pos_open_end.setX(char_space*1.5f);
          folding_pos_open_end.setY((lineRect.bottom()+lineRect.top())/2);
          if (last_block_contains_instrumentation)
            folding_pos_open_start=folding_pos_open_end;

          p.drawText(line_text_area,Qt::AlignVCenter|Qt::AlignLeft,QString::number(current_line));
          last_block_contains_instrumentation=false;
          has_folding_close=false;
          has_folding_open=true;
        }
        last_line=current_line;
      }
    }
    if (has_folding_close)
      drawFoldingLineHidden(p,folding_pos_close);
    if (has_folding_open)
      drawFoldingLineVisible(p,folding_pos_open_start,folding_pos_open_end);
  }
  r.translate(-1,+translation_y);
  context.clip=r;
}
Exemple #27
0
NATRON_NAMESPACE_ENTER
QImage
NodeGraph::getFullSceneScreenShot()
{
    _imp->isDoingPreviewRender = true;

    // The bbox of all nodes in the nodegraph
    QRectF sceneR = _imp->calcNodesBoundingRect();

    // The visible portion of the nodegraph
    QRectF viewRect = visibleSceneRect();

    // Make sure the visible rect is included in the scene rect
    sceneR = sceneR.united(viewRect);

    int navWidth = std::ceil(width() * NATRON_NAVIGATOR_BASE_WIDTH);
    int navHeight = std::ceil(height() * NATRON_NAVIGATOR_BASE_HEIGHT);

    // Make sceneR and viewRect keep the same aspect ratio as the navigator
    double xScale = navWidth / sceneR.width();
    double yScale =  navHeight / sceneR.height();
    double scaleFactor = std::max( 0.001, std::min(xScale, yScale) );
    int sceneW_navPixelCoord = std::floor(sceneR.width() * scaleFactor);
    int sceneH_navPixelCoord = std::floor(sceneR.height() * scaleFactor);

    // Render the scene in an image with the same aspect ratio  as the scene rect
    QImage renderImage(sceneW_navPixelCoord, sceneH_navPixelCoord, QImage::Format_ARGB32_Premultiplied);

    // Fill the background
    renderImage.fill( QColor(71, 71, 71, 255) );

    // Offset the visible rect corner as an offset relative to the scene rect corner
    viewRect.setX( viewRect.x() - sceneR.x() );
    viewRect.setY( viewRect.y() - sceneR.y() );
    viewRect.setWidth( viewRect.width() - sceneR.x() );
    viewRect.setHeight( viewRect.height() - sceneR.y() );

    QRectF viewRect_navCoordinates = viewRect;
    viewRect_navCoordinates.setLeft(viewRect.left() * scaleFactor);
    viewRect_navCoordinates.setBottom(viewRect.bottom() * scaleFactor);
    viewRect_navCoordinates.setRight(viewRect.right() * scaleFactor);
    viewRect_navCoordinates.setTop(viewRect.top() * scaleFactor);

    // Paint the visible portion with a highlight
    QPainter painter(&renderImage);

    // Remove the overlays from the scene before rendering it
    scene()->removeItem(_imp->_cacheSizeText);
    scene()->removeItem(_imp->_navigator);

    // Render into the QImage with downscaling
    scene()->render(&painter, renderImage.rect(), sceneR, Qt::KeepAspectRatio);

    // Add the overlays back
    scene()->addItem(_imp->_navigator);
    scene()->addItem(_imp->_cacheSizeText);

    // Fill the highlight with a semi transparent whitish grey
    painter.fillRect( viewRect_navCoordinates, QColor(200, 200, 200, 100) );

    // Draw a border surrounding the
    QPen p;
    p.setWidth(2);
    p.setBrush(Qt::yellow);
    painter.setPen(p);
    // Make sure the border is visible
    viewRect_navCoordinates.adjust(2, 2, -2, -2);
    painter.drawRect(viewRect_navCoordinates);

    // Now make an image of the requested size of the navigator and center the render image into it
    QImage img(navWidth, navHeight, QImage::Format_ARGB32_Premultiplied);
    img.fill( QColor(71, 71, 71, 255) );

    int xOffset = ( img.width() - renderImage.width() ) / 2;
    int yOffset = ( img.height() - renderImage.height() ) / 2;
    int dstY = yOffset;
    for (int srcY = 0; srcY < renderImage.height(); ++srcY, ++dstY) {
        if ( dstY < 0 || dstY >= img.height() ) {
            break;
        }
        QRgb* dst_pixels = (QRgb*)img.scanLine(dstY);
        assert(dst_pixels);

        const QRgb* src_pixels = (const QRgb*)renderImage.scanLine(srcY);
        assert(src_pixels);

        int dstX = xOffset;
        for (int srcX = 0; srcX < renderImage.width(); ++srcX, ++dstX) {
            if ( dstX < 0 || dstX >= img.width() ) {
                dst_pixels[dstX] = qRgba(0, 0, 0, 0);
            } else {
                dst_pixels[dstX] = src_pixels[srcX];
            }
        }
    }

    _imp->isDoingPreviewRender = false;

    return img;
} // getFullSceneScreenShot
Exemple #28
0
/*!
   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();
}
Exemple #29
0
 void MacroPinItem::paint(QPainter* painter, const QStyleOptionGraphicsItem* /*option*/, QWidget* /*widget*/)
 {
   graph::VertexItem* vertexItem = static_cast<graph::VertexItem*>(parentItem());
   Q_ASSERT(vertexItem != 0);
   const graph::Palette& pal = palette();
   QRectF rect = boundingRect();
   switch(vertexItem->itemLayout())
   {
     case graph::Defines::TopToBottom:
     {
       QPainterPath pinPath;
       if (pin().direction() == graph::Defines::Incoming)
       {
         painter->setPen(pal.pen(graph::Palette::PinIncomingBorder));
         pinPath.moveTo(rect.right(),rect.top() + rect.height() / 2.0);
         pinPath.lineTo(rect.topRight());
         pinPath.lineTo(rect.topLeft());
         pinPath.lineTo(rect.left(),rect.top() + rect.height() / 2.0);
         pinPath.arcTo(rect,180.0,180.0);
         pinPath.closeSubpath();
         painter->setBrush(pal.brush(graph::Palette::PinIncomingFill));
         painter->drawPath(pinPath);
       }
       else
       {
         painter->setPen(pal.pen(graph::Palette::PinOutgoingBorder));
         pinPath.moveTo(rect.right(),rect.top() + rect.height() / 2.0);
         pinPath.lineTo(rect.bottomRight());
         pinPath.lineTo(rect.bottomLeft());
         pinPath.lineTo(rect.left(),rect.top() + rect.height() / 2.0);
         pinPath.arcTo(rect,180.0,-180.0);
         pinPath.closeSubpath();
         painter->setBrush(pal.brush(graph::Palette::PinOutgoingFill));
         painter->drawPath(pinPath);
       }
       break;
     }
     case graph::Defines::LeftToRight:
     {
       QPainterPath pinPath;
       if (pin().direction() == graph::Defines::Incoming)
       {
         painter->setPen(pal.pen(graph::Palette::PinIncomingBorder));
         pinPath.moveTo(rect.left() + rect.width() / 2.0,rect.top());
         pinPath.lineTo(rect.topLeft());
         pinPath.lineTo(rect.bottomLeft());
         pinPath.lineTo(rect.left() + rect.width() / 2.0,rect.bottom());
         pinPath.arcTo(rect,270.0,180.0);
         pinPath.closeSubpath();
         painter->setBrush(pal.brush(graph::Palette::PinIncomingFill));
         painter->drawPath(pinPath);
       }
       else
       {
         painter->setPen(pal.pen(graph::Palette::PinOutgoingBorder));
         pinPath.moveTo(rect.left() + rect.width() / 2.0,rect.top());
         pinPath.lineTo(rect.topRight());
         pinPath.lineTo(rect.bottomRight());
         pinPath.lineTo(rect.left() + rect.width() / 2.0,rect.bottom());
         pinPath.arcTo(rect,270.0,-180.0);
         pinPath.closeSubpath();
         painter->setBrush(pal.brush(graph::Palette::PinOutgoingFill));
         painter->drawPath(pinPath);
       }
       break;
     }
     case graph::Defines::RightToLeft:
     {
       QPainterPath pinPath;
       if (pin().direction() == graph::Defines::Incoming)
       {
         painter->setPen(pal.pen(graph::Palette::PinIncomingBorder));
         pinPath.moveTo(rect.left() + rect.width() / 2.0,rect.top());
         pinPath.lineTo(rect.topRight());
         pinPath.lineTo(rect.bottomRight());
         pinPath.lineTo(rect.left() + rect.width() / 2.0,rect.bottom());
         pinPath.arcTo(rect,270.0,-180.0);
         pinPath.closeSubpath();
         painter->setBrush(pal.brush(graph::Palette::PinIncomingFill));
         painter->drawPath(pinPath);
       }
       else
       {
         painter->setPen(pal.pen(graph::Palette::PinOutgoingBorder));
         pinPath.moveTo(rect.left() + rect.width() / 2.0,rect.top());
         pinPath.lineTo(rect.topLeft());
         pinPath.lineTo(rect.bottomLeft());
         pinPath.lineTo(rect.left() + rect.width() / 2.0,rect.bottom());
         pinPath.arcTo(rect,270.0,180.0);
         pinPath.closeSubpath();
         painter->setBrush(pal.brush(graph::Palette::PinOutgoingFill));
         painter->drawPath(pinPath);
       }
       break;
     }
   }
 }
void QwtScaleWidget::drawTitle( QPainter *painter,
    QwtScaleDraw::Alignment align, const QRectF &rect ) const
{
    QRectF r = rect;
    double angle;
    int flags = d_data->title.renderFlags() &
        ~( Qt::AlignTop | Qt::AlignBottom | Qt::AlignVCenter );

    switch ( align )
    {
        case QwtScaleDraw::LeftScale:
            angle = -90.0;
            flags |= Qt::AlignTop;
            r.setRect( r.left(), r.bottom(),
                r.height(), r.width() - d_data->titleOffset );
            break;

        case QwtScaleDraw::RightScale:
            angle = -90.0;
            flags |= Qt::AlignTop;
            r.setRect( r.left() + d_data->titleOffset, r.bottom(),
                r.height(), r.width() - d_data->titleOffset );
            break;

        case QwtScaleDraw::BottomScale:
            angle = 0.0;
            flags |= Qt::AlignBottom;
            r.setTop( r.top() + d_data->titleOffset );
            break;

        case QwtScaleDraw::TopScale:
        default:
            angle = 0.0;
            flags |= Qt::AlignTop;
            r.setBottom( r.bottom() - d_data->titleOffset );
            break;
    }

    if ( d_data->layoutFlags & TitleInverted )
    {
        if ( align == QwtScaleDraw::LeftScale
            || align == QwtScaleDraw::RightScale )
        {
            angle = -angle;
            r.setRect( r.x() + r.height(), r.y() - r.width(),
                r.width(), r.height() );
        }
    }

    painter->save();
    painter->setFont( font() );
    painter->setPen( palette().color( QPalette::Text ) );

    painter->translate( r.x(), r.y() );
    if ( angle != 0.0 )
        painter->rotate( angle );

    QwtText title = d_data->title;
    title.setRenderFlags( flags );
    title.draw( painter, QRectF( 0.0, 0.0, r.width(), r.height() ) );

    painter->restore();
}