void MercatorProjectionTest::screenCoordinatesOfCenter()
{
    QFETCH( qreal, lon );
    QFETCH( qreal, lat );

    const GeoDataCoordinates coordinates( lon, lat, 0, GeoDataCoordinates::Degree );

    ViewportParams viewport;
    viewport.setProjection( Mercator );
    viewport.setRadius( 360 / 4 ); // for easy mapping of lon <-> x
    viewport.setSize( QSize( 2, 2 ) );
    viewport.centerOn( lon * DEG2RAD, lat * DEG2RAD );

    {
        qreal x;
        qreal y;

        const bool retval = viewport.screenCoordinates( lon * DEG2RAD, lat * DEG2RAD, x, y );

        QVERIFY( retval ); // FIXME: this should fail for lon < -180 || 180 < lon
        QCOMPARE( x, lon - viewport.centerLongitude() * RAD2DEG + 1.0 );
        QCOMPARE( y, 1.0 );
    }

    {
        qreal x;
        qreal y;
        bool globeHidesPoint = true;

        const bool retval = viewport.screenCoordinates( coordinates, x, y, globeHidesPoint );

        QVERIFY( retval ); // FIXME: this should fail for lon < -180 || 180 < lon
        QVERIFY( !globeHidesPoint );
        QCOMPARE( x, lon - viewport.centerLongitude() * RAD2DEG + 1.0 );
        QCOMPARE( y, 1.0 );
    }

    QVERIFY( viewport.currentProjection()->repeatX() );

    {
        qreal x[2];
        qreal y;
        int pointRepeatNum = 1000;
        bool globeHidesPoint = true;

        const bool retval = viewport.screenCoordinates( coordinates, x, y, pointRepeatNum, QSizeF( 0, 0 ), globeHidesPoint );

        QVERIFY( retval );
        QCOMPARE( pointRepeatNum, 1 );
        QVERIFY( !globeHidesPoint );
        QCOMPARE( x[0], 1.0 );
        QCOMPARE( y, 1.0 );
    }
}
Exemple #2
0
        QList<QSizeF> ratioList;
        const qreal sqrt2 = qSqrt(2.);
        ratioList
                << QSizeF(7, 5)
                << QSizeF(3, 2)
                << QSizeF(4, 3)
                << QSizeF(5, 4);

        addRatioToComboBox(QSizeF(1, 1), i18n("Square"));
        addRatioToComboBox(screenRatio(), i18n("This Screen"));
        addSectionHeaderToComboBox(i18n("Landscape"));

        Q_FOREACH(const QSizeF& size, ratioList) {
            addRatioToComboBox(size);
        }
        addRatioToComboBox(QSizeF(sqrt2, 1), i18n("ISO Size (A4, A3...)"));
        addRatioToComboBox(QSizeF(11, 8.5), i18n("US Letter"));
        addSectionHeaderToComboBox(i18n("Portrait"));
        Q_FOREACH(QSizeF size, ratioList) {
            size.transpose();
            addRatioToComboBox(size);
        }
        addRatioToComboBox(QSizeF(1, sqrt2), i18n("ISO Size (A4, A3...)"));
        addRatioToComboBox(QSizeF(8.5, 11), i18n("US Letter"));

        ratioComboBox->setMaxVisibleItems(ratioComboBox->count());
        ratioComboBox->clearEditText();

        QLineEdit* edit = qobject_cast<QLineEdit*>(ratioComboBox->lineEdit());
        Q_ASSERT(edit);
        // Do not use i18n("%1:%2") because ':' should not be translated, it is
void LvlScene::setPhysEnvResizer(QGraphicsItem * targetRect, bool enabled, bool accept)
{
    if((enabled)&&(pResizer==NULL))
    {
        MainWinConnect::pMainWin->on_actionSelect_triggered(); //Reset mode

        int x = ((ItemWater *)targetRect)->waterData.x;
        int y = ((ItemWater *)targetRect)->waterData.y;
        int w = ((ItemWater *)targetRect)->waterData.w;
        int h = ((ItemWater *)targetRect)->waterData.h;

        pResizer = new ItemResizer( QSize(w, h), Qt::darkYellow, 16 );
        this->addItem(pResizer);
        pResizer->setPos(x, y);
        pResizer->type=3;
        pResizer->targetItem = targetRect;
        pResizer->_minSize = QSizeF(16, 16);
        this->setFocus(Qt::ActiveWindowFocusReason);
        //DrawMode=true;
        //MainWinConnect::pMainWin->activeLvlEditWin()->changeCursor(leveledit::MODE_Resizing);
        SwitchEditingMode(MODE_Resizing);
        MainWinConnect::pMainWin->resizeToolbarVisible(true);
    }
    else
    {
        if(pResizer!=NULL)
        {
            if(accept)
            {
                #ifdef _DEBUG_
                WriteToLog(QtDebugMsg, QString("Water RESIZE -> to %1 x %2").arg(pResizer->_width).arg(pResizer->_height));
                #endif
                long x = pResizer->pos().x();
                long y = pResizer->pos().y();
                long w = pResizer->_width;
                long h = pResizer->_height;
                long oldX = ((ItemWater *)pResizer->targetItem)->waterData.x;
                long oldY = ((ItemWater *)pResizer->targetItem)->waterData.y;
                long oldW = ((ItemWater *)pResizer->targetItem)->waterData.w;
                long oldH = ((ItemWater *)pResizer->targetItem)->waterData.h;
                ((ItemWater *)pResizer->targetItem)->waterData.x = x;
                ((ItemWater *)pResizer->targetItem)->waterData.y = y;
                ((ItemWater *)pResizer->targetItem)->waterData.w = w;
                ((ItemWater *)pResizer->targetItem)->waterData.h = h;

                ((ItemWater *)pResizer->targetItem)->setRectSize( QRect(x,y,w,h) );
                LvlData->modified = true;

                addResizeWaterHistory(((ItemWater *)pResizer->targetItem)->waterData, oldX, oldY, oldX+oldW, oldY+oldH, x, y, x+w, y+h);

                //ChangeSectionBG(LvlData->sections[LvlData->CurSection].background);
                //drawSpace();
            }
            delete pResizer;
            pResizer = NULL;
            MainWinConnect::pMainWin->on_actionSelect_triggered();
            MainWinConnect::pMainWin->resizeToolbarVisible(false);
            //resetResizingSection=true;
        }
        DrawMode=false;
    }
}
Exemple #4
0
bool ChartShape::Private::loadOdfLabel(KoShape *label, KoXmlElement &labelElement, KoShapeLoadingContext &context)
{
    TextLabelData *labelData = qobject_cast<TextLabelData*>(label->userData());
    if (!labelData)
        return false;

    // Following will always return false cause KoTextShapeData::loadOdf will try to load
    // a frame while our text:p is not within a frame. So, let's just not call loadOdf then...
    //label->loadOdf(labelElement, context);

    // 1. set the text
    KoXmlElement  pElement = KoXml::namedItemNS(labelElement, KoXmlNS::text, "p");

    QTextDocument* doc = labelData->document();
    doc->setPlainText(pElement.text());

    // 2. set the position
    QPointF pos = label->position();
    bool posChanged = false;
    if (labelElement.hasAttributeNS(KoXmlNS::svg, "x")) {
        pos.setX(KoUnit::parseValue(labelElement.attributeNS(KoXmlNS::svg, "x", QString())));
        posChanged = true;
    }
    if (labelElement.hasAttributeNS(KoXmlNS::svg, "y")) {
        pos.setY(KoUnit::parseValue(labelElement.attributeNS(KoXmlNS::svg, "y", QString())));
        posChanged = true;
    }
    if (posChanged) {
        label->setPosition(pos);
    }

    // 3. set the styles
    if (labelElement.hasAttributeNS(KoXmlNS::chart, "style-name")) {
        KoStyleStack &styleStack = context.odfLoadingContext().styleStack();
        styleStack.clear();
        context.odfLoadingContext().fillStyleStack(labelElement, KoXmlNS::chart, "style-name", "chart");

        styleStack.setTypeProperties("chart");
        if (styleStack.hasProperty(KoXmlNS::style, "rotation-angle")) {
            qreal rotationAngle = 360 - KoUnit::parseValue(styleStack.property(KoXmlNS::style, "rotation-angle"));
            label->rotate(rotationAngle);
        }

        styleStack.setTypeProperties("text");

        if (styleStack.hasProperty(KoXmlNS::fo, "font-size")) {
            const qreal fontSize = KoUnit::parseValue(styleStack.property(KoXmlNS::fo, "font-size"));
            QFont font = doc->defaultFont();
            font.setPointSizeF(fontSize);
            doc->setDefaultFont(font);
        }

        if (styleStack.hasProperty(KoXmlNS::fo, "font-family")) {
            const QString fontFamily = styleStack.property(KoXmlNS::fo, "font-family");
            QFont font = doc->defaultFont();
            font.setFamily(fontFamily);
            doc->setDefaultFont(font);
        }
    }

    // 4. set the size
    if (labelElement.hasAttributeNS(KoXmlNS::svg, "width")
        && labelElement.hasAttributeNS(KoXmlNS::svg, "height"))
    {
        const qreal width = KoUnit::parseValue(labelElement.attributeNS(KoXmlNS::svg, "width"));
        const qreal height = KoUnit::parseValue(labelElement.attributeNS(KoXmlNS::svg, "height"));
        label->setSize(QSizeF(width, height));
    } else {
        QSizeF size = shape->size();
        QRect r = QFontMetrics(doc->defaultFont()).boundingRect(
                        labelData->shapeMargins().left, labelData->shapeMargins().top,
                        qMax(CM_TO_POINT(5), qreal(size.width() - pos.x() * 2.0 - labelData->shapeMargins().right)),
                        qMax(CM_TO_POINT(0.6), qreal(size.height() - labelData->shapeMargins().bottom)),
                        Qt::AlignLeft | Qt::AlignTop | Qt::TextWordWrap, doc->toPlainText());
        label->setSize(r.size());
    }

    return true;
}
void KCategoryDrawer::drawCategory(const QModelIndex &index,
                                   int /*sortRole*/,
                                   const QStyleOption &option,
                                   QPainter *painter) const
{
    painter->setRenderHint(QPainter::Antialiasing);

    const QString category = index.model()->data(index, KCategorizedSortFilterProxyModel::CategoryDisplayRole).toString();
    const QRect optRect = option.rect;
    QFont font(QApplication::font());
    font.setBold(true);
    const QFontMetrics fontMetrics = QFontMetrics(font);

    QColor outlineColor = option.palette.text().color();
    outlineColor.setAlphaF(0.35);

    //BEGIN: top left corner
    {
        painter->save();
        painter->setPen(outlineColor);
        const QPointF topLeft(optRect.topLeft());
        QRectF arc(topLeft, QSizeF(4, 4));
        arc.translate(0.5, 0.5);
        painter->drawArc(arc, 1440, 1440);
        painter->restore();
    }
    //END: top left corner

    //BEGIN: left vertical line
    {
        QPoint start(optRect.topLeft());
        start.ry() += 3;
        QPoint verticalGradBottom(optRect.topLeft());
        verticalGradBottom.ry() += fontMetrics.height() + 5;
        QLinearGradient gradient(start, verticalGradBottom);
        gradient.setColorAt(0, outlineColor);
        gradient.setColorAt(1, Qt::transparent);
        painter->fillRect(QRect(start, QSize(1, fontMetrics.height() + 5)), gradient);
    }
    //END: left vertical line

    //BEGIN: horizontal line
    {
        QPoint start(optRect.topLeft());
        start.rx() += 3;
        QPoint horizontalGradTop(optRect.topLeft());
        horizontalGradTop.rx() += optRect.width() - 6;
        painter->fillRect(QRect(start, QSize(optRect.width() - 6, 1)), outlineColor);
    }
    //END: horizontal line

    //BEGIN: top right corner
    {
        painter->save();
        painter->setPen(outlineColor);
        QPointF topRight(optRect.topRight());
        topRight.rx() -= 4;
        QRectF arc(topRight, QSizeF(4, 4));
        arc.translate(0.5, 0.5);
        painter->drawArc(arc, 0, 1440);
        painter->restore();
    }
    //END: top right corner

    //BEGIN: right vertical line
    {
        QPoint start(optRect.topRight());
        start.ry() += 3;
        QPoint verticalGradBottom(optRect.topRight());
        verticalGradBottom.ry() += fontMetrics.height() + 5;
        QLinearGradient gradient(start, verticalGradBottom);
        gradient.setColorAt(0, outlineColor);
        gradient.setColorAt(1, Qt::transparent);
        painter->fillRect(QRect(start, QSize(1, fontMetrics.height() + 5)), gradient);
    }
    //END: right vertical line

    //BEGIN: text
    {
        QRect textRect(option.rect);
        textRect.setTop(textRect.top() + 7);
        textRect.setLeft(textRect.left() + 7);
        textRect.setHeight(fontMetrics.height());
        textRect.setRight(textRect.right() - 7);

        painter->save();
        painter->setFont(font);
        QColor penColor(option.palette.text().color());
        penColor.setAlphaF(0.6);
        painter->setPen(penColor);
        painter->drawText(textRect, Qt::AlignLeft | Qt::AlignVCenter, category);
        painter->restore();
    }
    //END: text
}
QSizeF QgsLayoutTable::fixedFrameSize( const int frameIndex ) const
{
  Q_UNUSED( frameIndex );
  return QSizeF( mTableSize.width(), 0 );
}
Exemple #7
0
QRectF MyPixmapItem::boundingRect() const{
    return QRectF(QPointF(0, 0), QSizeF(sizex, sizey));
}
void QgsComposerLegend::setSymbolWidth( double w ) { mSettings.setSymbolSize( QSizeF( w, mSettings.symbolSize().height() ) ); }
void QgsComposerLegend::setSymbolHeight( double h ) { mSettings.setSymbolSize( QSizeF( mSettings.symbolSize().width(), h ) ); }
QSizeF ImageLoaderFreeImage::size(Types::UnitsOfLength unit) const
{
    const QSize sizePixels = this->sizePixels();
    return QSizeF(sizePixels.width() / horizontalDotsPerUnitOfLength(unit), sizePixels.height() / verticalDotsPerUnitOfLength(unit));
}
Exemple #11
0
**     contributors may be used to endorse or promote products derived
**     from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/

//! [0]
QRect r1(100, 200, 11, 16);
QRect r2(QPoint(100, 200), QSize(11, 16));
//! [0]


//! [1]
QRectF r1(100.0, 200.1, 11.2, 16.3);
QRectF r2(QPointF(100.0, 200.1), QSizeF(11.2, 16.3));
//! [1]
QSizeF PageMetrics::pxPageSize() const
{
	return QSizeF(m_pxPageSize.width(),
				  m_pxPageSize.height());
}
QSizeF QgsSymbolV2LegendNode::drawSymbol( const QgsLegendSettings& settings, ItemContext* ctx, double itemHeight ) const
{
  QgsSymbolV2* s = mItem.symbol();
  if ( !s )
  {
    return QSizeF();
  }

  // setup temporary render context
  QgsRenderContext context;
  context.setScaleFactor( settings.dpi() / 25.4 );
  context.setRendererScale( settings.mapScale() );
  context.setMapToPixel( QgsMapToPixel( 1 / ( settings.mmPerMapUnit() * context.scaleFactor() ) ) );
  context.setForceVectorOutput( true );
  context.setPainter( ctx ? ctx->painter : 0 );

  //Consider symbol size for point markers
  double height = settings.symbolSize().height();
  double width = settings.symbolSize().width();
  double size = 0;
  //Center small marker symbols
  double widthOffset = 0;
  double heightOffset = 0;

  if ( QgsMarkerSymbolV2* markerSymbol = dynamic_cast<QgsMarkerSymbolV2*>( s ) )
  {
    // allow marker symbol to occupy bigger area if necessary
    size = markerSymbol->size() * QgsSymbolLayerV2Utils::lineWidthScaleFactor( context, s->outputUnit(), s->mapUnitScale() ) / context.scaleFactor();
    height = size;
    width = size;
    if ( width < settings.symbolSize().width() )
    {
      widthOffset = ( settings.symbolSize().width() - width ) / 2.0;
    }
    if ( height < settings.symbolSize().height() )
    {
      heightOffset = ( settings.symbolSize().height() - height ) / 2.0;
    }
  }

  if ( ctx )
  {
    double currentXPosition = ctx->point.x();
    double currentYCoord = ctx->point.y() + ( itemHeight - settings.symbolSize().height() ) / 2;
    QPainter* p = ctx->painter;

    //setup painter scaling to dots so that raster symbology is drawn to scale
    double dotsPerMM = context.scaleFactor();

    int opacity = 255;
    if ( QgsVectorLayer* vectorLayer = dynamic_cast<QgsVectorLayer*>( layerNode()->layer() ) )
      opacity = 255 - ( 255 * vectorLayer->layerTransparency() / 100 );

    p->save();
    p->setRenderHint( QPainter::Antialiasing );
    p->translate( currentXPosition + widthOffset, currentYCoord + heightOffset );
    p->scale( 1.0 / dotsPerMM, 1.0 / dotsPerMM );
    if ( opacity != 255 && settings.useAdvancedEffects() )
    {
      //semi transparent layer, so need to draw symbol to an image (to flatten it first)
      //create image which is same size as legend rect, in case symbol bleeds outside its alloted space
      QSize tempImageSize( width * dotsPerMM, height * dotsPerMM );
      QImage tempImage = QImage( tempImageSize, QImage::Format_ARGB32 );
      tempImage.fill( Qt::transparent );
      QPainter imagePainter( &tempImage );
      context.setPainter( &imagePainter );
      s->drawPreviewIcon( &imagePainter, tempImageSize, &context );
      context.setPainter( ctx->painter );
      //reduce opacity of image
      imagePainter.setCompositionMode( QPainter::CompositionMode_DestinationIn );
      imagePainter.fillRect( tempImage.rect(), QColor( 0, 0, 0, opacity ) );
      imagePainter.end();
      //draw rendered symbol image
      p->drawImage( 0, 0, tempImage );
    }
    else
    {
      s->drawPreviewIcon( p, QSize( width * dotsPerMM, height * dotsPerMM ), &context );
    }
    p->restore();
  }

  return QSizeF( qMax( width + 2 * widthOffset, ( double ) settings.symbolSize().width() ),
                 qMax( height + 2 * heightOffset, ( double ) settings.symbolSize().height() ) );
}
void MercatorProjectionTest::screenCoordinatesValidLat()
{
    QFETCH( qreal, lon );
    QFETCH( qreal, lat );
    QFETCH( bool, validLat );

    const GeoDataCoordinates coordinates( lon, lat, 0, GeoDataCoordinates::Degree );

    ViewportParams viewport;
    viewport.setProjection( Mercator );
    viewport.setRadius( 360 / 4 ); // for easy mapping of lon <-> x
    viewport.centerOn( 0.0, 0.0 );
    viewport.setSize( QSize( 360, 361 ) ); // TODO: check why height == 360 doesn't hold

    {
        qreal x;
        qreal y;

        const bool retval = viewport.screenCoordinates( lon * DEG2RAD, lat * DEG2RAD, x, y );

        QVERIFY( retval == validLat );
    }

    {
        qreal x;
        qreal y;
        bool globeHidesPoint = true;

        const bool retval = viewport.screenCoordinates( coordinates, x, y, globeHidesPoint );

        QVERIFY( retval == validLat );
        QVERIFY( !globeHidesPoint );
    }

    QVERIFY( viewport.currentProjection()->repeatX() );

    {
        qreal x[2];
        qreal y;
        int pointRepeatNum = 1000;
        bool globeHidesPoint = true;

        const bool retval = viewport.screenCoordinates( coordinates, x, y, pointRepeatNum, QSizeF( 0, 0 ), globeHidesPoint );

        QVERIFY( retval == validLat );
        QCOMPARE( pointRepeatNum, 1 );
        QVERIFY( !globeHidesPoint );
    }
}
Exemple #15
0
QSizeF VlcQmlVideoObject::ratioSize(Vlc::Ratio ratio)
{
    switch( ratio )
    {
        default:
        case Vlc::Original:
            return QSizeF(0,0);
        break;
        case Vlc::R_16_9:
            return QSizeF(16,9);
        break;
        case Vlc::R_16_10:
            return QSizeF(16,10);
        break;
        case Vlc::R_185_100:
            return QSizeF(185,100);
        break;
        case Vlc::R_221_100:
            return QSizeF(221,100);
        break;
        case Vlc::R_235_100:
            return QSizeF(235,100);
        break;
        case Vlc::R_239_100:
            return QSizeF(239,100);
        break;
        case Vlc::R_4_3:
            return QSizeF(4,3);
        break;
        case Vlc::R_5_4:
            return QSizeF(5,4);
        break;
        case Vlc::R_5_3:
            return QSizeF(5,3);
        break;
        case Vlc::R_1_1:
            return QSizeF(1,1);
        break;
    }
    return QSizeF(0,0);
}
Exemple #16
0
void QgsComposerLegend::setWmsLegendWidth( double w ) { mSettings.setWmsLegendSize( QSizeF( w, mSettings.wmsLegendSize().height() ) ); }
Exemple #17
0
void renderCodeEAN13(OROPage * page, const QRectF & r, const QString & _str, ORBarcodeData * bc)
{
  int val[13];
  int i = 0;

  // initialize all the values just so we can be predictable
  for(i = 0; i < 13; i++)
    val[i] = -1;

  // verify that the passed in string is valid
  // if it's not either twelve or thirteen characters
  // then it must be invalid to begin with
  if(_str.length() != 12 && _str.length() != 13)
    return;
  // loop through and convert each char to a digit.
  // if we can't convert all characters then this is
  // an invalid number
  for(i = 0; i < _str.length(); i++)
  {
    val[i] = ((QChar)_str.at(i)).digitValue();
    if(val[i] == -1)
      return;
  }

  // calculate and append the checksum value
  int old_sum = val[12]; // get the old check sum value (-1 if none was set)
  int checksum = 0;
  for(i = 0; i < 12; i++)
    checksum += val[i] * (i % 2 ? 3 : 1);
  checksum = (checksum % 10);
  if(checksum) checksum = 10 - checksum;
  val[12] = checksum;

  // if we had an old checksum value and if it doesn't match what we came
  // up with then the string must be invalid so we will bail
  if(old_sum != -1 && old_sum != checksum)
    return;


  // lets determine some core attributes about this barcode
  qreal bar_width = bc->narrowBarWidth; 

  // this is are mandatory minimum quiet zone
  qreal quiet_zone = bar_width * 10;
  if(quiet_zone < 0.1)
    quiet_zone = 0.1;

  // what kind of area do we have to work with
  qreal draw_width = r.width();
  qreal draw_height = r.height() - 0.02;

  // L = 95X
  // L length of barcode (excluding quite zone) in units same as X and I
  // X the width of a bar (pixels in our case)
  qreal L;

  qreal X = bar_width;

  L = (95.0 * X);

  // now we have the actual width the barcode will be so can determine the actual
  // size of the quiet zone (we assume we center the barcode in the given area
  // what should we do if the area is too small????
  // At the moment the way the code is written is we will always start at the minimum
  // required quiet zone if we don't have enough space.... I guess we'll just have over-run
  // to the right
  //
  // calculate the starting position based on the alignment option
  // for left align we don't need to do anything as the values are already setup for it
  if(bc->align == 1) // center
  {
    qreal nqz = (draw_width - L) / 2;
    if(nqz > quiet_zone)
      quiet_zone = nqz;
  }
  else if(bc->align > 1) // right
    quiet_zone = draw_width - (L + quiet_zone);
  // else if(align < 1) {} // left : do nothing

  qreal pos = r.left() + quiet_zone;
  qreal top = r.top();


  QPen pen(Qt::NoPen);
  QBrush brush(QColor("black"));

  int b = 0;
  int w = 0;

  // render open guard
  ORORect * rect = new ORORect(bc);
  rect->setPen(pen);
  rect->setBrush(brush);
  rect->setRect(QRectF(pos,top, bar_width,draw_height));
  rect->setRotationAxis(r.topLeft());
  page->addPrimitive(rect);

  pos += (bar_width * 2.0);

  rect = new ORORect(bc);
  rect->setPen(pen);
  rect->setBrush(brush);
  rect->setRect(QRectF(pos,top, bar_width,draw_height));
  rect->setRotationAxis(r.topLeft());
  page->addPrimitive(rect);

  pos += bar_width;

  // render first set
  for(i = 0; i < 6; i++)
  {
    b = val[i+1];
    for(w = 0; w < 7; w++)
    {
      if(_encodings[b][_parity[val[0]][i]][w])
      {
        rect = new ORORect(bc);
        rect->setPen(pen);
        rect->setBrush(brush);
        rect->setRect(QRectF(pos,top, bar_width,draw_height-0.07));
		rect->setRotationAxis(r.topLeft());
        page->addPrimitive(rect);
      }
      pos += bar_width;
    }
  }

  // render center guard
  pos += bar_width;

  rect = new ORORect(bc);
  rect->setPen(pen);
  rect->setBrush(brush);
  rect->setRect(QRectF(pos,top, bar_width,draw_height));
  rect->setRotationAxis(r.topLeft());
  page->addPrimitive(rect);

  pos += (bar_width * 2.0);

  rect = new ORORect(bc);
  rect->setPen(pen);
  rect->setBrush(brush);
  rect->setRect(QRectF(pos,top, bar_width,draw_height));
  rect->setRotationAxis(r.topLeft());
  page->addPrimitive(rect);

  pos += (bar_width * 2.0);

  // render last set
  for(i = 0; i < 6; i++)
  {
    b = val[i+7];
    for(w = 0; w < 7; w++)
    {
      if(_encodings[b][RIGHTHAND][w])
      {
        rect = new ORORect(bc);
        rect->setPen(pen);
        rect->setBrush(brush);
        rect->setRect(QRectF(pos,top, bar_width,draw_height-0.07));
		rect->setRotationAxis(r.topLeft());
        page->addPrimitive(rect);
      }
      pos += bar_width;
    }
  }

  // render close guard
  rect = new ORORect(bc);
  rect->setPen(pen);
  rect->setBrush(brush);
  rect->setRect(QRectF(pos,top, bar_width,draw_height));
  rect->setRotationAxis(r.topLeft());
  page->addPrimitive(rect);

  pos += (bar_width * 2.0);

  rect = new ORORect(bc);
  rect->setPen(pen);
  rect->setBrush(brush);
  rect->setRect(QRectF(pos,top, bar_width,draw_height));
  rect->setRotationAxis(r.topLeft());
  page->addPrimitive(rect);

  QString parstr = QString("%1").arg(val[0]);
  QString leftstr = QString().sprintf("%d%d%d%d%d%d",
                     val[1], val[2], val[3], val[4], val[5], val[6]);
  QString rightstr = QString().sprintf("%d%d%d%d%d%d",
                     val[7], val[8], val[9], val[10], val[11], val[12]);
  QFont font("Arial", 6);

  OROTextBox * tb = new OROTextBox(bc);
  tb->setPosition(QPointF(r.left(), r.top() + draw_height - 0.12));
  tb->setSize(QSizeF(quiet_zone - 0.02, 0.12));
  tb->setFont(font);
  tb->setText(parstr);
  tb->setFlags(Qt::AlignRight | Qt::AlignTop);
  tb->setRotationAxis(r.topLeft());
  page->addPrimitive(tb);
                     
  tb = new OROTextBox(bc);
  tb->setPosition(QPointF(r.left() + quiet_zone + bar_width*3, (r.top() + draw_height) - 0.07));
  tb->setSize(QSizeF(bar_width*40, 0.1));
  tb->setFont(font);
  tb->setText(leftstr);
  tb->setFlags(Qt::AlignHCenter | Qt::AlignTop);
  tb->setRotationAxis(r.topLeft());
  page->addPrimitive(tb);

  tb = new OROTextBox(bc);
  tb->setPosition(QPointF(r.left() + quiet_zone + bar_width*50, (r.top() + draw_height) - 0.07));
  tb->setSize(QSizeF(bar_width*40, 0.1));
  tb->setFont(font);
  tb->setText(rightstr);
  tb->setFlags(Qt::AlignHCenter | Qt::AlignTop);
  tb->setRotationAxis(r.topLeft());
  page->addPrimitive(tb);

  return;
} 
Exemple #18
0
void QgsComposerLegend::setWmsLegendHeight( double h ) { mSettings.setWmsLegendSize( QSizeF( mSettings.wmsLegendSize().width(), h ) ); }
void QgsLayoutTable::recalculateFrameSizes()
{
  mTableSize = QSizeF( totalWidth(), totalHeight() );
  QgsLayoutMultiFrame::recalculateFrameSizes();
}
Exemple #20
0
bool QgsComposerLegend::readXml( const QDomElement &itemElem, const QDomDocument &doc )
{
  if ( itemElem.isNull() )
  {
    return false;
  }

  //read general properties
  mTitle = itemElem.attribute( QStringLiteral( "title" ) );
  mSettings.setTitle( mTitle );
  if ( !itemElem.attribute( QStringLiteral( "titleAlignment" ) ).isEmpty() )
  {
    mSettings.setTitleAlignment( static_cast< Qt::AlignmentFlag >( itemElem.attribute( QStringLiteral( "titleAlignment" ) ).toInt() ) );
  }
  int colCount = itemElem.attribute( QStringLiteral( "columnCount" ), QStringLiteral( "1" ) ).toInt();
  if ( colCount < 1 ) colCount = 1;
  mColumnCount = colCount;
  mSettings.setColumnCount( mColumnCount );
  mSettings.setSplitLayer( itemElem.attribute( QStringLiteral( "splitLayer" ), QStringLiteral( "0" ) ).toInt() == 1 );
  mSettings.setEqualColumnWidth( itemElem.attribute( QStringLiteral( "equalColumnWidth" ), QStringLiteral( "0" ) ).toInt() == 1 );

  QDomNodeList stylesNodeList = itemElem.elementsByTagName( QStringLiteral( "styles" ) );
  if ( !stylesNodeList.isEmpty() )
  {
    QDomNode stylesNode = stylesNodeList.at( 0 );
    for ( int i = 0; i < stylesNode.childNodes().size(); i++ )
    {
      QDomElement styleElem = stylesNode.childNodes().at( i ).toElement();
      QgsLegendStyle style;
      style.readXml( styleElem, doc );
      QString name = styleElem.attribute( QStringLiteral( "name" ) );
      QgsLegendStyle::Style s;
      if ( name == QLatin1String( "title" ) ) s = QgsLegendStyle::Title;
      else if ( name == QLatin1String( "group" ) ) s = QgsLegendStyle::Group;
      else if ( name == QLatin1String( "subgroup" ) ) s = QgsLegendStyle::Subgroup;
      else if ( name == QLatin1String( "symbol" ) ) s = QgsLegendStyle::Symbol;
      else if ( name == QLatin1String( "symbolLabel" ) ) s = QgsLegendStyle::SymbolLabel;
      else continue;
      setStyle( s, style );
    }
  }

  //font color
  QColor fontClr;
  fontClr.setNamedColor( itemElem.attribute( QStringLiteral( "fontColor" ), QStringLiteral( "#000000" ) ) );
  mSettings.setFontColor( fontClr );

  //spaces
  mSettings.setBoxSpace( itemElem.attribute( QStringLiteral( "boxSpace" ), QStringLiteral( "2.0" ) ).toDouble() );
  mSettings.setColumnSpace( itemElem.attribute( QStringLiteral( "columnSpace" ), QStringLiteral( "2.0" ) ).toDouble() );

  mSettings.setSymbolSize( QSizeF( itemElem.attribute( QStringLiteral( "symbolWidth" ), QStringLiteral( "7.0" ) ).toDouble(), itemElem.attribute( QStringLiteral( "symbolHeight" ), QStringLiteral( "14.0" ) ).toDouble() ) );
  mSettings.setWmsLegendSize( QSizeF( itemElem.attribute( QStringLiteral( "wmsLegendWidth" ), QStringLiteral( "50" ) ).toDouble(), itemElem.attribute( QStringLiteral( "wmsLegendHeight" ), QStringLiteral( "25" ) ).toDouble() ) );
  mSettings.setLineSpacing( itemElem.attribute( QStringLiteral( "lineSpacing" ), "1.0" ).toDouble() );

  mSettings.setDrawRasterStroke( itemElem.attribute( QStringLiteral( "rasterBorder" ), QStringLiteral( "1" ) ) != QLatin1String( "0" ) );
  mSettings.setRasterStrokeColor( QgsSymbolLayerUtils::decodeColor( itemElem.attribute( QStringLiteral( "rasterBorderColor" ), QStringLiteral( "0,0,0" ) ) ) );
  mSettings.setRasterStrokeWidth( itemElem.attribute( QStringLiteral( "rasterBorderWidth" ), QStringLiteral( "0" ) ).toDouble() );

  mSettings.setWrapChar( itemElem.attribute( QStringLiteral( "wrapChar" ) ) );

  mSizeToContents = itemElem.attribute( QStringLiteral( "resizeToContents" ), QStringLiteral( "1" ) ) != QLatin1String( "0" );

  //composer map
  mLegendFilterByMap = itemElem.attribute( QStringLiteral( "legendFilterByMap" ), QStringLiteral( "0" ) ).toInt();
  if ( !itemElem.attribute( QStringLiteral( "map" ) ).isEmpty() )
  {
    setComposerMap( mComposition->getComposerMapById( itemElem.attribute( QStringLiteral( "map" ) ).toInt() ) );
  }

  // QGIS >= 2.6
  QDomElement layerTreeElem = itemElem.firstChildElement( QStringLiteral( "layer-tree" ) );
  if ( layerTreeElem.isNull() )
    layerTreeElem = itemElem.firstChildElement( QStringLiteral( "layer-tree-group" ) );

  setCustomLayerTree( QgsLayerTree::readXml( layerTreeElem ) );

  //restore general composer item properties
  QDomNodeList composerItemList = itemElem.elementsByTagName( QStringLiteral( "ComposerItem" ) );
  if ( !composerItemList.isEmpty() )
  {
    QDomElement composerItemElem = composerItemList.at( 0 ).toElement();
    _readXml( composerItemElem, doc );
  }

  // < 2.0 projects backward compatibility >>>>>
  //title font
  QString titleFontString = itemElem.attribute( QStringLiteral( "titleFont" ) );
  if ( !titleFontString.isEmpty() )
  {
    rstyle( QgsLegendStyle::Title ).rfont().fromString( titleFontString );
  }
  //group font
  QString groupFontString = itemElem.attribute( QStringLiteral( "groupFont" ) );
  if ( !groupFontString.isEmpty() )
  {
    rstyle( QgsLegendStyle::Group ).rfont().fromString( groupFontString );
  }

  //layer font
  QString layerFontString = itemElem.attribute( QStringLiteral( "layerFont" ) );
  if ( !layerFontString.isEmpty() )
  {
    rstyle( QgsLegendStyle::Subgroup ).rfont().fromString( layerFontString );
  }
  //item font
  QString itemFontString = itemElem.attribute( QStringLiteral( "itemFont" ) );
  if ( !itemFontString.isEmpty() )
  {
    rstyle( QgsLegendStyle::SymbolLabel ).rfont().fromString( itemFontString );
  }

  if ( !itemElem.attribute( QStringLiteral( "groupSpace" ) ).isEmpty() )
  {
    rstyle( QgsLegendStyle::Group ).setMargin( QgsLegendStyle::Top, itemElem.attribute( QStringLiteral( "groupSpace" ), QStringLiteral( "3.0" ) ).toDouble() );
  }
  if ( !itemElem.attribute( QStringLiteral( "layerSpace" ) ).isEmpty() )
  {
    rstyle( QgsLegendStyle::Subgroup ).setMargin( QgsLegendStyle::Top, itemElem.attribute( QStringLiteral( "layerSpace" ), QStringLiteral( "3.0" ) ).toDouble() );
  }
  if ( !itemElem.attribute( QStringLiteral( "symbolSpace" ) ).isEmpty() )
  {
    rstyle( QgsLegendStyle::Symbol ).setMargin( QgsLegendStyle::Top, itemElem.attribute( QStringLiteral( "symbolSpace" ), QStringLiteral( "2.0" ) ).toDouble() );
    rstyle( QgsLegendStyle::SymbolLabel ).setMargin( QgsLegendStyle::Top, itemElem.attribute( QStringLiteral( "symbolSpace" ), QStringLiteral( "2.0" ) ).toDouble() );
  }
  // <<<<<<< < 2.0 projects backward compatibility

  emit itemChanged();
  return true;
}
void KateCategoryDrawer::drawCategory(const QModelIndex &index,
                                      int sortRole,
                                      const QStyleOption &option,
                                      QPainter *painter) const
{
    Q_UNUSED(sortRole)

    painter->setRenderHint(QPainter::Antialiasing);

    const QRect optRect = option.rect;
    QFont font(QApplication::font());
    font.setBold(true);
    const int height = categoryHeight(index, option);
    const bool leftToRight = painter->layoutDirection() == Qt::LeftToRight;

    //BEGIN: decoration gradient
    {
        QPainterPath path(optRect.bottomLeft());

        path.lineTo(QPoint(optRect.topLeft().x(), optRect.topLeft().y() - 3));
        const QPointF topLeft(optRect.topLeft());
        QRectF arc(topLeft, QSizeF(4, 4));
        path.arcTo(arc, 180, -90);
        path.lineTo(optRect.topRight());
        path.lineTo(optRect.bottomRight());
        path.lineTo(optRect.bottomLeft());

        QColor window(option.palette.window().color());
        const QColor base(option.palette.base().color());

        window.setAlphaF(0.4);

        QLinearGradient decoGradient1;
        if (leftToRight) {
            decoGradient1.setStart(optRect.topLeft());
            decoGradient1.setFinalStop(optRect.bottomLeft());
        } else {
            decoGradient1.setStart(optRect.topRight());
            decoGradient1.setFinalStop(optRect.bottomRight());
        }
        decoGradient1.setColorAt(0, window);
        decoGradient1.setColorAt(1, Qt::transparent);

        QLinearGradient decoGradient2;
        if (leftToRight) {
            decoGradient2.setStart(optRect.topLeft());
            decoGradient2.setFinalStop(optRect.topRight());
        } else {
            decoGradient2.setStart(optRect.topRight());
            decoGradient2.setFinalStop(optRect.topLeft());
        }
        decoGradient2.setColorAt(0, Qt::transparent);
        decoGradient2.setColorAt(1, base);

        painter->fillPath(path, decoGradient1);
        painter->fillPath(path, decoGradient2);
    }
    //END: decoration gradient

    {
        QRect newOptRect(optRect);

        if (leftToRight) {
            newOptRect.translate(1, 1);
        } else {
            newOptRect.translate(-1, 1);
        }

        //BEGIN: inner top left corner
        {
            painter->save();
            painter->setPen(option.palette.base().color());
            QRectF arc;
            if (leftToRight) {
                const QPointF topLeft(newOptRect.topLeft());
                arc = QRectF(topLeft, QSizeF(4, 4));
                arc.translate(0.5, 0.5);
                painter->drawArc(arc, 1440, 1440);
            } else {
                QPointF topRight(newOptRect.topRight());
                topRight.rx() -= 4;
                arc = QRectF(topRight, QSizeF(4, 4));
                arc.translate(-0.5, 0.5);
                painter->drawArc(arc, 0, 1440);
            }
            painter->restore();
        }
        //END: inner top left corner

        //BEGIN: inner left vertical line
        {
            QPoint start;
            QPoint verticalGradBottom;
            if (leftToRight) {
                start = newOptRect.topLeft();
                verticalGradBottom = newOptRect.topLeft();
            } else {
                start = newOptRect.topRight();
                verticalGradBottom = newOptRect.topRight();
            }
            start.ry() += 3;
            verticalGradBottom.ry() += newOptRect.height() - 3;
            QLinearGradient gradient(start, verticalGradBottom);
            gradient.setColorAt(0, option.palette.base().color());
            gradient.setColorAt(1, Qt::transparent);
            painter->fillRect(QRect(start, QSize(1, newOptRect.height() - 3)), gradient);
        }
        //END: inner left vertical line

        //BEGIN: inner horizontal line
        {
            QPoint start;
            QPoint horizontalGradTop;
            if (leftToRight) {
                start = newOptRect.topLeft();
                horizontalGradTop = newOptRect.topLeft();
                start.rx() += 3;
                horizontalGradTop.rx() += newOptRect.width() - 3;
            } else {
                start = newOptRect.topRight();
                horizontalGradTop = newOptRect.topRight();
                start.rx() -= 3;
                horizontalGradTop.rx() -= newOptRect.width() - 3;
            }
            QLinearGradient gradient(start, horizontalGradTop);
            gradient.setColorAt(0, option.palette.base().color());
            gradient.setColorAt(1, Qt::transparent);
            QSize rectSize;
            if (leftToRight) {
                rectSize = QSize(newOptRect.width() - 3, 1);
            } else {
                rectSize = QSize(-newOptRect.width() + 3, 1);
            }
            painter->fillRect(QRect(start, rectSize), gradient);
        }
        //END: inner horizontal line
    }

    QColor outlineColor = option.palette.text().color();
    outlineColor.setAlphaF(0.35);

    //BEGIN: top left corner
    {
        painter->save();
        painter->setPen(outlineColor);
        QRectF arc;
        if (leftToRight) {
            const QPointF topLeft(optRect.topLeft());
            arc = QRectF(topLeft, QSizeF(4, 4));
            arc.translate(0.5, 0.5);
            painter->drawArc(arc, 1440, 1440);
        } else {
            QPointF topRight(optRect.topRight());
            topRight.rx() -= 4;
            arc = QRectF(topRight, QSizeF(4, 4));
            arc.translate(-0.5, 0.5);
            painter->drawArc(arc, 0, 1440);
        }
        painter->restore();
    }
    //END: top left corner

    //BEGIN: left vertical line
    {
        QPoint start;
        QPoint verticalGradBottom;
        if (leftToRight) {
            start = optRect.topLeft();
            verticalGradBottom = optRect.topLeft();
        } else {
            start = optRect.topRight();
            verticalGradBottom = optRect.topRight();
        }
        start.ry() += 3;
        verticalGradBottom.ry() += optRect.height() - 3;
        QLinearGradient gradient(start, verticalGradBottom);
        gradient.setColorAt(0, outlineColor);
        gradient.setColorAt(1, option.palette.base().color());
        painter->fillRect(QRect(start, QSize(1, optRect.height() - 3)), gradient);
    }
    //END: left vertical line

    //BEGIN: horizontal line
    {
        QPoint start;
        QPoint horizontalGradTop;
        if (leftToRight) {
            start = optRect.topLeft();
            horizontalGradTop = optRect.topLeft();
            start.rx() += 3;
            horizontalGradTop.rx() += optRect.width() - 3;
        } else {
            start = optRect.topRight();
            horizontalGradTop = optRect.topRight();
            start.rx() -= 3;
            horizontalGradTop.rx() -= optRect.width() - 3;
        }
        QLinearGradient gradient(start, horizontalGradTop);
        gradient.setColorAt(0, outlineColor);
        gradient.setColorAt(1, option.palette.base().color());
        QSize rectSize;
        if (leftToRight) {
            rectSize = QSize(optRect.width() - 3, 1);
        } else {
            rectSize = QSize(-optRect.width() + 3, 1);
        }
        painter->fillRect(QRect(start, rectSize), gradient);
    }
    //END: horizontal line

    //BEGIN: draw text
    {
        const QString category = index.model()->data(index, Qt::DisplayRole).toString(); // KCategorizedSortFilterProxyModel::CategoryDisplayRole).toString();
        QRect textRect = QRect(option.rect.topLeft(), QSize(option.rect.width() - 2 - 3 - 3, height));
        textRect.setTop(textRect.top() + 2 + 3 /* corner */);
        textRect.setLeft(textRect.left() + 2 + 3 /* corner */ + 3 /* a bit of margin */);
        painter->save();
        painter->setFont(font);
        QColor penColor(option.palette.text().color());
        penColor.setAlphaF(0.6);
        painter->setPen(penColor);
        painter->drawText(textRect, Qt::AlignLeft | Qt::AlignTop, category);
        painter->restore();
    }
    //END: draw text
}
Exemple #22
0
void QgsComposerLegend::paint( QPainter *painter, const QStyleOptionGraphicsItem *itemStyle, QWidget *pWidget )
{
  Q_UNUSED( itemStyle );
  Q_UNUSED( pWidget );

  if ( !painter )
    return;

  if ( !shouldDrawItem() )
  {
    return;
  }

  if ( mFilterAskedForUpdate )
  {
    mFilterAskedForUpdate = false;
    doUpdateFilterByMap();
  }

  int dpi = painter->device()->logicalDpiX();
  double dotsPerMM = dpi / 25.4;

  if ( mComposition )
  {
    mSettings.setUseAdvancedEffects( mComposition->useAdvancedEffects() );
    mSettings.setDpi( dpi );
  }
  if ( mComposerMap )
  {
    mSettings.setMmPerMapUnit( mComposerMap->mapUnitsToMM() );

    // use a temporary QgsMapSettings to find out real map scale
    QSizeF mapSizePixels = QSizeF( mComposerMap->rect().width() * dotsPerMM, mComposerMap->rect().height() * dotsPerMM );
    QgsRectangle mapExtent = *mComposerMap->currentMapExtent();

    QgsMapSettings ms = mComposerMap->mapSettings( mapExtent, mapSizePixels, dpi );
    mSettings.setMapScale( ms.scale() );
  }
  mInitialMapScaleCalculated = true;

  QgsLegendRenderer legendRenderer( mLegendModel, mSettings );
  legendRenderer.setLegendSize( mForceResize && mSizeToContents ? QSize() : rect().size() );

  //adjust box if width or height is too small
  if ( mSizeToContents )
  {
    QSizeF size = legendRenderer.minimumSize();
    if ( mForceResize )
    {
      mForceResize = false;
      //set new rect, respecting position mode and data defined size/position
      QRectF targetRect = QRectF( pos().x(), pos().y(), size.width(), size.height() );
      setSceneRect( evalItemRect( targetRect, true ) );
    }
    else if ( size.height() > rect().height() || size.width() > rect().width() )
    {
      //need to resize box
      QRectF targetRect = QRectF( pos().x(), pos().y(), rect().width(), rect().height() );
      if ( size.height() > targetRect.height() )
        targetRect.setHeight( size.height() );
      if ( size.width() > rect().width() )
        targetRect.setWidth( size.width() );

      //set new rect, respecting position mode and data defined size/position
      setSceneRect( evalItemRect( targetRect, true ) );
    }
  }

  drawBackground( painter );
  painter->save();
  //antialiasing on
  painter->setRenderHint( QPainter::Antialiasing, true );
  painter->setPen( QPen( QColor( 0, 0, 0 ) ) );

  if ( !mSizeToContents )
  {
    // set a clip region to crop out parts of legend which don't fit
    QRectF thisPaintRect = QRectF( 0, 0, rect().width(), rect().height() );
    painter->setClipRect( thisPaintRect );
  }

  legendRenderer.drawLegend( painter );

  painter->restore();

  //draw frame and selection boxes if necessary
  drawFrame( painter );
  if ( isSelected() )
  {
    drawSelectionBoxes( painter );
  }
}
Exemple #23
0
ChartShape::ChartShape(KoDocumentResourceManager *resourceManager)
    : KoFrameShape(KoXmlNS::draw, "object")
    , KoShapeContainer(new ChartLayout)
    , d (new Private(this))
{
    d->resourceManager = resourceManager;
    setShapeId(ChartShapeId);

    // Instantiated all children first
    d->proxyModel = new ChartProxyModel(this, &d->tableSource);

    d->plotArea = new PlotArea(this);
    d->document = new ChartDocument(this);
    d->legend   = new Legend(this);

    // Configure the plotarea.
    // We need this as the very first step, because some methods
    // here rely on the d->plotArea pointer.
    addShape(d->plotArea);
    d->plotArea->plotAreaInit();
    d->plotArea->setZIndex(0);
    setClipped(d->plotArea, true);
    setInheritsTransform(d->plotArea, true);

    // Configure the legend.
    d->legend->setVisible(true);
    d->legend->setZIndex(1);
    setClipped(d->legend, true);
    setInheritsTransform(d->legend, true);

    // A few simple defaults (chart type and subtype in this case)
    setChartType(BarChartType);
    setChartSubType(NormalChartSubtype);

    // Create the Title, which is a standard TextShape.
    KoShapeFactoryBase *textShapeFactory = KoShapeRegistry::instance()->value(TextShapeId);
    if (textShapeFactory)
        d->title = textShapeFactory->createDefaultShape(resourceManager);
    // Potential problem 1) No TextShape installed
    if (!d->title) {
        d->title = new TextLabelDummy;
        if (ENABLE_USER_INTERACTION)
            KMessageBox::error(0, i18n("The plugin needed for displaying text labels in a chart is not available."),
                                   i18n("Plugin Missing"));
    // Potential problem 2) TextShape incompatible
    } else if (dynamic_cast<TextLabelData*>(d->title->userData()) == 0 &&
                ENABLE_USER_INTERACTION)
            KMessageBox::error(0, i18n("The plugin needed for displaying text labels is not compatible with the current version of the chart Flake shape."),
                                   i18n("Plugin Incompatible"));

    // In both cases we need a KoTextShapeData instance to function. This is
    // enough for unit tests, so there has to be no TextShape plugin doing the
    // actual text rendering, we just need KoTextShapeData which is in the libs.
    if (dynamic_cast<TextLabelData*>(d->title->userData()) == 0) {
        TextLabelData *dataDummy = new TextLabelData;
        KoTextDocumentLayout *documentLayout = new KoTextDocumentLayout(dataDummy->document());
        dataDummy->document()->setDocumentLayout(documentLayout);
        d->title->setUserData(dataDummy);
    }

    // Start with a reasonable default size that we can base all following relative
    // positions of chart elements on.
    setSize(QSizeF(CM_TO_POINT(8), CM_TO_POINT(5)));

    // Add the title to the shape
    addShape(d->title);
    QFont font = titleData()->document()->defaultFont();
    font.setPointSizeF(12.0);
    titleData()->document()->setDefaultFont(font);
    titleData()->document()->setHtml("<div align=\"center\">" + i18n("Title") + "</font></div>");
    // Position the title center at the very top.
    d->title->setSize(QSizeF(CM_TO_POINT(5), CM_TO_POINT(0.7)));
    d->title->setPosition(QPointF(size().width() / 2.0 - d->title->size().width() / 2.0, 0.0));
    d->title->setVisible(false);
    d->title->setZIndex(2);
    setClipped(d->title, true);
    setInheritsTransform(d->title, true);

    // Create the Subtitle and add it to the shape.
    if (textShapeFactory)
        d->subTitle = textShapeFactory->createDefaultShape(resourceManager);
    if (!d->subTitle) {
        d->subTitle = new TextLabelDummy;
    }
    if (dynamic_cast<TextLabelData*>(d->subTitle->userData()) == 0) {
        TextLabelData *dataDummy = new TextLabelData;
        KoTextDocumentLayout *documentLayout = new KoTextDocumentLayout(dataDummy->document());
        dataDummy->document()->setDocumentLayout(documentLayout);
        d->subTitle->setUserData(dataDummy);
    }
    addShape(d->subTitle);
    font = subTitleData()->document()->defaultFont();
    font.setPointSizeF(10.0);
    subTitleData()->document()->setDefaultFont(font);
    subTitleData()->document()->setHtml("<div align=\"center\">" + i18n("Subtitle") + "</div>");

    // Position it in the center, just below the title.
    d->subTitle->setSize(QSizeF(CM_TO_POINT(5), CM_TO_POINT(0.6)));
    d->subTitle->setPosition(QPointF(size().width() / 2.0 - d->title->size().width() / 2.0,
                                       d->title->size().height()));
    d->subTitle->setVisible(false);
    d->subTitle->setZIndex(3);
    setClipped(d->subTitle, true);
    setInheritsTransform(d->subTitle, true);

    // Create the Footer and add it to the shape.
    if (textShapeFactory)
        d->footer = textShapeFactory->createDefaultShape(resourceManager);
    if (!d->footer) {
        d->footer = new TextLabelDummy;
    }
    if (dynamic_cast<TextLabelData*>(d->footer->userData()) == 0) {
        TextLabelData *dataDummy = new TextLabelData;
        KoTextDocumentLayout *documentLayout = new KoTextDocumentLayout(dataDummy->document());
        dataDummy->document()->setDocumentLayout(documentLayout);
        d->footer->setUserData(dataDummy);
    }
    addShape(d->footer);
    font = footerData()->document()->defaultFont();
    font.setPointSizeF(10.0);
    footerData()->document()->setDefaultFont(font);
    footerData()->document()->setHtml("<div align=\"center\">" + i18n("Footer") + "</div>");

    // Position the footer in the center, at the bottom.
    d->footer->setSize(QSizeF(CM_TO_POINT(5), CM_TO_POINT(0.6)));
    d->footer->setPosition(QPointF(size().width() / 2.0 - d->footer->size().width() / 2.0,
                                   size().height() - d->footer->size().height()));
    d->footer->setVisible(false);
    d->footer->setZIndex(4);
    setClipped(d->footer, true);
    setInheritsTransform(d->footer, true);

    // Set default contour (for how text run around is done around this shape)
    // to prevent a crash in LO
    setTextRunAroundContour(KoShape::ContourBox);

    // Enable auto-resizing of chart labels
    foreach(KoShape *label, labels()) {
        TextLabelData *labelData = qobject_cast<TextLabelData*>(label->userData());
        KoTextDocument doc(labelData->document());
//FIXME        doc.setResizeMethod(KoTextDocument::AutoResize);
    }
Exemple #24
0
void PageFormat::setSize(const PaperSize* size)
      {
      _size = QSizeF(size->w, size->h);
      }
void QgsMapRenderer::setOutputSize( QSize size, int dpi )
{
  mSize = QSizeF( size.width(), size.height() );
  mScaleCalculator->setDpi( dpi );
  adjustExtentToSize();
}
void QgsComposerMultiFrame::recalculateFrameSizes()
{
  if ( mFrameItems.size() < 1 )
  {
    return;
  }

  QSizeF size = totalSize();
  double totalHeight = size.height();

  if ( totalHeight < 1 )
  {
    return;
  }

  double currentY = 0;
  double currentHeight = 0;
  QgsComposerFrame *currentItem = nullptr;

  for ( int i = 0; i < mFrameItems.size(); ++i )
  {
    if ( mResizeMode != RepeatOnEveryPage && currentY >= totalHeight )
    {
      if ( mResizeMode == RepeatUntilFinished || mResizeMode == ExtendToNextPage ) //remove unneeded frames in extent mode
      {
        bool removingPages = true;
        for ( int j = mFrameItems.size(); j > i; --j )
        {
          int numPagesBefore = mComposition->numPages();
          removeFrame( j - 1, removingPages );
          //if removing the frame didn't also remove the page, then stop removing pages
          removingPages = removingPages && ( mComposition->numPages() < numPagesBefore );
        }
        return;
      }
    }

    currentItem = mFrameItems.value( i );
    currentHeight = currentItem->rect().height();
    if ( mResizeMode == RepeatOnEveryPage )
    {
      currentItem->setContentSection( QRectF( 0, 0, currentItem->rect().width(), currentHeight ) );
    }
    else
    {
      currentHeight = findNearbyPageBreak( currentY + currentHeight ) - currentY;
      currentItem->setContentSection( QRectF( 0, currentY, currentItem->rect().width(), currentHeight ) );
    }
    currentItem->update();
    currentY += currentHeight;
  }

  //at end of frames but there is  still content left. Add other pages if ResizeMode ==
  if ( mResizeMode != UseExistingFrames )
  {
    while ( ( mResizeMode == RepeatOnEveryPage ) || currentY < totalHeight )
    {
      //find out on which page the lower left point of the last frame is
      int page = qFloor( ( currentItem->pos().y() + currentItem->rect().height() ) / ( mComposition->paperHeight() + mComposition->spaceBetweenPages() ) ) + 1;

      if ( mResizeMode == RepeatOnEveryPage )
      {
        if ( page >= mComposition->numPages() )
        {
          break;
        }
      }
      else
      {
        //add an extra page if required
        if ( mComposition->numPages() < ( page + 1 ) )
        {
          mComposition->setNumPages( page + 1 );
        }
      }

      double frameHeight = 0;
      if ( mResizeMode == RepeatUntilFinished || mResizeMode == RepeatOnEveryPage )
      {
        frameHeight = currentItem->rect().height();
      }
      else //mResizeMode == ExtendToNextPage
      {
        frameHeight = ( currentY + mComposition->paperHeight() ) > totalHeight ?  totalHeight - currentY : mComposition->paperHeight();
      }

      double newFrameY = page * ( mComposition->paperHeight() + mComposition->spaceBetweenPages() );
      if ( mResizeMode == RepeatUntilFinished || mResizeMode == RepeatOnEveryPage )
      {
        newFrameY += currentItem->pos().y() - ( page - 1 ) * ( mComposition->paperHeight() + mComposition->spaceBetweenPages() );
      }

      //create new frame
      QgsComposerFrame *newFrame = createNewFrame( currentItem,
                                   QPointF( currentItem->pos().x(), newFrameY ),
                                   QSizeF( currentItem->rect().width(), frameHeight ) );

      if ( mResizeMode == RepeatOnEveryPage )
      {
        newFrame->setContentSection( QRectF( 0, 0, newFrame->rect().width(), newFrame->rect().height() ) );
        currentY += frameHeight;
      }
      else
      {
        double contentHeight = findNearbyPageBreak( currentY + newFrame->rect().height() ) - currentY;
        newFrame->setContentSection( QRectF( 0, currentY, newFrame->rect().width(), contentHeight ) );
        currentY += contentHeight;
      }

      currentItem = newFrame;
    }
  }
}
QTM_BEGIN_NAMESPACE

/*!
    \class QGraphicsGeoMap
    \brief The QGraphicsGeoMap class is used to display a map and manager the
    interactions between the user and the map.

    \inmodule QtLocation

    \ingroup maps-mapping

    Most of the functionality is provided by QGeoMappingManager, which
    handles most aspects of the display.

    The map viewport can be panned, the zoom level can be changed and the
    center coordinate of the viewport can be set explicitly.

    The screenPositionToCoordinate() and coordinateToScreenPoisition()
    functions can be used to convert between positions on the screen and
    global coordinates.

    Mouse and keyboard events should be handled by subclassing QGraphicsGeoMap
    and providing implementations of the event handling functions present in
    QGraphicsWidget.
*/

/*!
\enum QGraphicsGeoMap::MapType

Describes a type of map data.

\value NoMap
Indicates a lack of map valid data.

\value StreetMap
The map data is a graphical representation of streets and building boundaries.

\value SatelliteMapDay
The map data is composed of images collected by satellites during the daytime.

\value SatelliteMapNight
The map data is composed of images collected by satellites during the nighttime.

\value TerrainMap
The map data is a graphical representation of terrain features.  This may also
include some of the information provided by QGraphicsGeoMap::StreetMap.
*/

/*!
\enum QGraphicsGeoMap::ConnectivityMode

Describes the method of obtaining the mapping data.

\value NoConnectivity
There is no map data.

\value OfflineMode
The map data will come from an offline source.

\value OnlineMode
The map data will come from an online source.

\value HybridMode
The map data will come from a combination of offline and online sources.
*/

/*!
    Creates a new mapping widget, with the mapping operations managed by
    \a manager, and the specified \a parent.

    Note that the \a manager will typically be accessed from an instance of
    QGeoServiceProvider:
    \code
        QGeoServiceProvider serviceProvider("nokia");
        QGeoMappingManager *manager = serviceProvider.mappingManager();
        QGraphicsGeoMap *widget = new QGraphicsGeoMap(manager);
    \endcode
*/
QGraphicsGeoMap::QGraphicsGeoMap(QGeoMappingManager *manager, QGraphicsItem *parent)
    : QGraphicsWidget(parent),
      d_ptr(new QGraphicsGeoMapPrivate())
{
    Q_ASSERT(manager != 0);
    d_ptr->manager = manager;

    d_ptr->mapData = d_ptr->manager->createMapData();
    d_ptr->mapData->init();

    connect(d_ptr->mapData,
            SIGNAL(updateMapDisplay(QRectF)),
            this,
            SLOT(updateMapDisplay(QRectF)));

    setMapType(QGraphicsGeoMap::StreetMap);
    d_ptr->mapData->setWindowSize(size());

    connect(d_ptr->mapData,
            SIGNAL(zoomLevelChanged(qreal)),
            this,
            SIGNAL(zoomLevelChanged(qreal)));
    connect(d_ptr->mapData,
            SIGNAL(mapTypeChanged(QGraphicsGeoMap::MapType)),
            this,
            SIGNAL(mapTypeChanged(QGraphicsGeoMap::MapType)));
    connect(d_ptr->mapData,
            SIGNAL(centerChanged(QGeoCoordinate)),
            this,
            SIGNAL(centerChanged(QGeoCoordinate)));
    connect(d_ptr->mapData,
            SIGNAL(connectivityModeChanged(QGraphicsGeoMap::ConnectivityMode)),
            this,
            SIGNAL(connectivityModeChanged(QGraphicsGeoMap::ConnectivityMode)));

    setFlag(QGraphicsItem::ItemIsFocusable);
    setFocus();

    setMinimumSize(QSizeF(0, 0));
    setPreferredSize(QSizeF(500, 500));
}
QSizeF GraphicsLinearLayoutStretchItemObject::sizeHint(Qt::SizeHint which, const QSizeF &constraint) const
{
    Q_UNUSED(which);
    Q_UNUSED(constraint);
    return QSizeF();
}
QSizeF KisAutoBrushWidget::brushSize() const
{
    return QSizeF(inputRadius->value(), inputRadius->value() * inputRatio->value());
}
QgsLabelFeature* QgsVectorLayerDiagramProvider::registerDiagram( QgsFeature& feat, QgsRenderContext &context, QgsGeometry* obstacleGeometry )
{
  const QgsMapSettings& mapSettings = mEngine->mapSettings();

  QgsDiagramRendererV2* dr = mSettings.renderer;
  if ( dr )
  {
    QList<QgsDiagramSettings> settingList = dr->diagramSettings();
    if ( !settingList.isEmpty() && settingList.at( 0 ).scaleBasedVisibility )
    {
      double minScale = settingList.at( 0 ).minScaleDenominator;
      if ( minScale > 0 && context.rendererScale() < minScale )
      {
        return 0;
      }

      double maxScale = settingList.at( 0 ).maxScaleDenominator;
      if ( maxScale > 0 && context.rendererScale() > maxScale )
      {
        return 0;
      }
    }
  }

  //convert geom to geos
  const QgsGeometry* geom = feat.constGeometry();
  QScopedPointer<QgsGeometry> extentGeom( QgsGeometry::fromRect( mapSettings.visibleExtent() ) );
  if ( !qgsDoubleNear( mapSettings.rotation(), 0.0 ) )
  {
    //PAL features are prerotated, so extent also needs to be unrotated
    extentGeom->rotate( -mapSettings.rotation(), mapSettings.visibleExtent().center() );
  }

  const GEOSGeometry* geos_geom = 0;
  QScopedPointer<QgsGeometry> preparedGeom;
  if ( QgsPalLabeling::geometryRequiresPreparation( geom, context, mSettings.ct, extentGeom.data() ) )
  {
    preparedGeom.reset( QgsPalLabeling::prepareGeometry( geom, context, mSettings.ct, extentGeom.data() ) );
    if ( !preparedGeom.data() )
      return 0;
    geos_geom = preparedGeom.data()->asGeos();
  }
  else
  {
    geos_geom = geom->asGeos();
  }

  if ( geos_geom == 0 )
  {
    return 0; // invalid geometry
  }
  GEOSGeometry* geomCopy = GEOSGeom_clone_r( QgsGeometry::getGEOSHandler(), geos_geom );

  const GEOSGeometry* geosObstacleGeom = 0;
  QScopedPointer<QgsGeometry> scopedObstacleGeom;
  if ( mSettings.obstacle && obstacleGeometry && QgsPalLabeling::geometryRequiresPreparation( obstacleGeometry, context, mSettings.ct, extentGeom.data() ) )
  {
    scopedObstacleGeom.reset( QgsPalLabeling::prepareGeometry( obstacleGeometry, context, mSettings.ct, extentGeom.data() ) );
    geosObstacleGeom = scopedObstacleGeom.data()->asGeos();
  }
  else if ( mSettings.obstacle && obstacleGeometry )
  {
    geosObstacleGeom = obstacleGeometry->asGeos();
  }
  GEOSGeometry* geosObstacleGeomClone = 0;
  if ( geosObstacleGeom )
  {
    geosObstacleGeomClone = GEOSGeom_clone_r( QgsGeometry::getGEOSHandler(), geosObstacleGeom );
  }


  double diagramWidth = 0;
  double diagramHeight = 0;
  if ( dr )
  {
    QSizeF diagSize = dr->sizeMapUnits( feat, context );
    if ( diagSize.isValid() )
    {
      diagramWidth = diagSize.width();
      diagramHeight = diagSize.height();
    }
  }

  //  feature to the layer
  bool alwaysShow = mSettings.showAll;
  int ddColX = mSettings.xPosColumn;
  int ddColY = mSettings.yPosColumn;
  double ddPosX = 0.0;
  double ddPosY = 0.0;
  bool ddPos = ( ddColX >= 0 && ddColY >= 0 );
  if ( ddPos )
  {
    bool posXOk, posYOk;
    ddPosX = feat.attribute( ddColX ).toDouble( &posXOk );
    ddPosY = feat.attribute( ddColY ).toDouble( &posYOk );
    if ( !posXOk || !posYOk )
    {
      ddPos = false;
    }
    else
    {
      const QgsCoordinateTransform* ct = mSettings.ct;
      if ( ct )
      {
        double z = 0;
        ct->transformInPlace( ddPosX, ddPosY, z );
      }
      //data defined diagram position is always centered
      ddPosX -= diagramWidth / 2.0;
      ddPosY -= diagramHeight / 2.0;
    }
  }

  QgsDiagramLabelFeature* lf = new QgsDiagramLabelFeature( feat.id(), geomCopy, QSizeF( diagramWidth, diagramHeight ) );
  lf->setHasFixedPosition( ddPos );
  lf->setFixedPosition( QgsPoint( ddPosX, ddPosY ) );
  lf->setHasFixedAngle( true );
  lf->setFixedAngle( 0 );
  lf->setAlwaysShow( alwaysShow );
  lf->setIsObstacle( mSettings.obstacle );
  if ( geosObstacleGeomClone )
  {
    lf->setObstacleGeometry( geosObstacleGeomClone );
  }

  if ( dr )
  {
    //append the diagram attributes to lbl
    lf->setAttributes( feat.attributes() );
  }

  QgsPoint ptZero = mSettings.xform->toMapCoordinates( 0, 0 );
  QgsPoint ptOne = mSettings.xform->toMapCoordinates( 1, 0 );
  lf->setDistLabel( qAbs( ptOne.x() - ptZero.x() ) * mSettings.dist );
  return lf;
}