示例#1
0
void PhaseItem::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget)
{
    Q_UNUSED(option);
    Q_UNUSED(widget);
    
    painter->setRenderHint(QPainter::Antialiasing);
    
    QRectF rect = boundingRect();
    int rounded = 15;
    
    QColor phaseColor = QColor(mData[STATE_COLOR_RED].toInt(),
                               mData[STATE_COLOR_GREEN].toInt(),
                               mData[STATE_COLOR_BLUE].toInt());
    QColor fontColor = getContrastedColor(phaseColor);
    
    painter->setPen(Qt::NoPen);
    painter->setBrush(phaseColor);
    painter->drawRoundedRect(rect, rounded, rounded);
    
    if(mControlsVisible)
    {
        // Checked
        QRectF cRect = checkRect();
        drawCheckBoxBox(*painter, cRect, mState, Qt::white, QColor(150, 150, 150));
        
        // Eye
        QRectF eRect = eyeRect();
        painter->setBrush(Qt::white);
        painter->setPen(Qt::black);
        painter->drawRoundedRect(eRect, 10, 10);
        if(mEyeActivated)
        {
            QPixmap eye(":eye.png");
            painter->drawPixmap(eRect, eye, eye.rect());
        }
    }
    
    // Name
    QRectF tr(rect.x() + mBorderWidth + 2*mEltsMargin + mTitleHeight,
              rect.y() + mBorderWidth + mEltsMargin,
              rect.width() - 2*mBorderWidth - 2*(mTitleHeight + 2*mEltsMargin),
              mTitleHeight);
    
    QFont font = qApp->font();
    painter->setFont(font);
    QFontMetrics metrics(font);
    QString name = mData[STATE_NAME].toString();
    name = metrics.elidedText(name, Qt::ElideRight, tr.width());
    painter->setPen(fontColor);
    painter->drawText(tr, Qt::AlignCenter, name);
    
    // Change font
    font.setPointSizeF(pointSize(11.f));
    painter->setFont(font);
    
    // Type (duration tau)
    QString tauStr = getTauString();
    if(!tauStr.isEmpty())
    {
        QRectF tpr(rect.x() + mBorderWidth + mEltsMargin,
                   rect.y() + rect.height() - mBorderWidth - mEltsMargin - mEltsHeight,
                   rect.width() - 2*mBorderWidth - 2*mEltsMargin,
                   mEltsHeight);
        
        painter->setPen(Qt::black);
        painter->setBrush(Qt::white);
        painter->drawRect(tpr);
        painter->drawText(tpr, Qt::AlignCenter, tauStr);
    }
    
    // Events
    QRectF r(rect.x() + mBorderWidth + mEltsMargin,
             rect.y() + mBorderWidth + mEltsMargin + mTitleHeight + mEltsMargin,
             rect.width() - 2 * (mEltsMargin + mBorderWidth),
             mEltsHeight);
    
    QJsonArray events = getEvents();
    double dy = mEltsMargin + mEltsHeight;
    for(int i=0; i<events.size(); ++i)
    {
        QJsonObject event = events[i].toObject();
        QColor eventColor(event[STATE_COLOR_RED].toInt(),
                          event[STATE_COLOR_GREEN].toInt(),
                          event[STATE_COLOR_BLUE].toInt());
        if(i > 0)
            r.adjust(0, dy, 0, dy);
        
        painter->fillRect(r, eventColor);
        painter->setPen(getContrastedColor(eventColor));
        painter->drawText(r, Qt::AlignCenter, event[STATE_NAME].toString());
    }
    
    // Border
    painter->setBrush(Qt::NoBrush);
    if(isSelected())
    {
        painter->setPen(QPen(Qt::white, 5.f));
        painter->drawRoundedRect(rect.adjusted(1, 1, -1, -1), rounded, rounded);
        
        painter->setPen(QPen(Qt::red, 3.f));
        painter->drawRoundedRect(rect.adjusted(1, 1, -1, -1), rounded, rounded);
    }
}
示例#2
0
QFont QgsMapToolLabel::labelFontCurrentFeature()
{
  QFont font;
  QgsVectorLayer* vlayer = currentLayer();

  bool labelSettingsOk;
  QgsPalLayerSettings& labelSettings = currentLabelSettings( &labelSettingsOk );

  if ( labelSettingsOk && vlayer )
  {
    font = labelSettings.textFont;

    QgsFeature f;
    if ( vlayer->getFeatures( QgsFeatureRequest().setFilterFid( mCurrentLabelPos.featureId ).setFlags( QgsFeatureRequest::NoGeometry ) ).nextFeature( f ) )
    {
      //size
      int sizeIndx = dataDefinedColumnIndex( QgsPalLayerSettings::Size, vlayer );
      if ( sizeIndx != -1 )
      {
        if ( labelSettings.fontSizeInMapUnits )
        {
          font.setPixelSize( labelSettings.sizeToPixel( f.attribute( sizeIndx ).toDouble(),
                             QgsRenderContext(), QgsPalLayerSettings::MapUnits, true ) );
        }
        else
        {
          font.setPointSizeF( f.attribute( sizeIndx ).toDouble() );
        }
      }

      //family
      int fmIndx = dataDefinedColumnIndex( QgsPalLayerSettings::Family, vlayer );
      if ( fmIndx != -1 )
      {
        font.setFamily( f.attribute( fmIndx ).toString() );
      }

      //underline
      int ulIndx = dataDefinedColumnIndex( QgsPalLayerSettings::Underline, vlayer );
      if ( ulIndx != -1 )
      {
        font.setUnderline( f.attribute( ulIndx ).toBool() );
      }

      //strikeout
      int soIndx = dataDefinedColumnIndex( QgsPalLayerSettings::Strikeout, vlayer );
      if ( soIndx != -1 )
      {
        font.setStrikeOut( f.attribute( soIndx ).toBool() );
      }

      //bold
      int boIndx = dataDefinedColumnIndex( QgsPalLayerSettings::Bold, vlayer );
      if ( boIndx != -1 )
      {
        font.setBold( f.attribute( boIndx ).toBool() );
      }

      //italic
      int itIndx = dataDefinedColumnIndex( QgsPalLayerSettings::Italic, vlayer );
      if ( itIndx != -1 )
      {
        font.setItalic( f.attribute( itIndx ).toBool() );
      }

      // TODO: Add other font data defined values (word spacing, etc.)
    }
  }

  return font;
}
void paint(QPaintDevice* pd) {
    QPainter p;
    if (!p.begin(pd)) return;
    QPen pe(QColor("black"));
    pe.setWidthF(6.0);
    pe.setStyle(Qt::DashLine);
    p.setPen(pe);
    p.drawLine(QPointF(0,0),QPointF(100.0,100.0));
    pe.setColor("red");
    pe.setStyle(Qt::DotLine);
    p.setPen(pe);
    p.drawLine(QPointF(0,0),QPointF(50.0,25.0));
    pe.setColor("green");
    pe.setStyle(Qt::SolidLine);
    p.setPen(pe);
    p.drawLine(QPointF(0,0),QPointF(25.0,50.0));
    pe.setColor("blue");
    p.setPen(pe);
    p.drawText(50,10, QString("Hello World!"));
    p.drawLine(50,10,55,15);
    QFont f;
    QImage img(QString("qfe_plotterexportercairo.png"));
    pe.setWidthF(0.5);
    p.setPen(pe);
    p.drawImage(QRectF(50,25,50,50), img);
    //p.drawRect(QRectF(50,25,50,50));
    p.drawImage(QRectF(25,50,15,10), img);
    //p.drawRect(QRectF(25,50,15,10));
    p.drawImage(QRectF(225,50,100,100), img, QRect(5,5,12,12));
    p.drawRect(QRectF(125,50,15,10));
    pe.setWidthF(2);
    pe.setColor("red");
    p.setPen(pe);
    f.setFamily("Times New Roman");
    f.setPointSizeF(10);
    p.setFont(f);
    p.drawText(50,30, QString("Hello World!"));
    p.drawLine(50,30,55,35);

    f.setFamily("Arial");
    f.setPointSizeF(16);
    p.setFont(f);
    p.drawText(250,30, QString("Unicode-test: ")+QChar(0x2190)+QChar(0x2591)+QChar(0x2665)+QChar(0x039B)+QChar(0x03B6));
    p.drawLine(250,30,255,35);

    pe.setWidthF(1);
    p.setPen(pe);
    QBrush b(QColor("salmon"));
    p.fillRect(QRectF(100,10,50,50), b);
    p.drawRect(QRectF(100,10,50,50));
    QColor c=b.color();
    c.setAlphaF(0.5);
    b.setColor(c);
    pe.setWidthF(5);
    p.setPen(pe);
    p.setBrush(b);
    p.drawEllipse(QRectF(130,40,50,30));
    //p.drawRect(QRectF(130,40,50,30));
    QPolygonF poly;
    for (int phi=0; phi<60; phi++) {
        double p=double(phi)/20.0*M_PI;
        poly<<QPointF(50.0+cos(p)*35.0*double(phi)/60.0, 50.0-sin(p)*35.0*double(phi)/60.0);
    }

    p.setClipRect(0,0,200,50);

    pe.setWidthF(1);
    p.setPen(pe);
    p.drawPolygon(poly);
    pe.setColor("red");
    pe.setStyle(Qt::DashDotDotLine);
    p.setPen(pe);
    p.setClipping(false);
    p.drawPolyline(poly);


    p.end();
}
示例#4
0
void PlotExporter::exportPlot(QwtPlot *plot, const QRectF &zoom)
{
  QSizeF guessedDimensions;
  ExportPlotToImageDialog::Parameters p = m_exportDlg->parameters();

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

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

    QString path;

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

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

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

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

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

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

        curvePenWidths.push_back(w);

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

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

      i->attach(&exPlot);
    }

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

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

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

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

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

    exPlot.replot();

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

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

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

        if (curvePenWidths.isEmpty())
          break;

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

        c->setPen(p);
      }

      i->attach(plot);
    }

    break; /* Exit the while loop */
  }
}
示例#5
0
void ColorBar::paint(QPainter *painter) {
    if (_colorScale==NULL) return;

    QFont f = painter->font();
    f.setPointSizeF(16);
    painter->setFont(f);

    //
    painter->setPen(Qt::black);//NoPen);
    painter->setBrush(QColor(255,255,255,180));
    painter->drawRoundedRect(BAR_START_X-10, BAR_START_Y-10,100,BAR_HEIGHT + 20,10,10);
    //painter->drawRect(BAR_START_X, BAR_START_Y, BAR_START_X+BAR_WIDTH+TICK_WIDTH+4+TEXT_WIDTH, TEXT_HEIGHT+ BAR_START_Y-TEXT_HEIGHT/4-1);

    // Draw rectangle with gradient on widget
    painter->setPen(Qt::black);
    painter->setBrush(_gradient);
    painter->drawRect(BAR_START_X, BAR_START_Y, BAR_WIDTH, BAR_HEIGHT);

    // draw ticks and text
    if (_minReal!=_maxReal) {
        int    stepTick = BAR_HEIGHT/TICKS_NUM;
        //    for (int i=BAR_START_Y; i<=BAR_START_Y+BAR_HEIGHT; i+=stepTick) {
        for (int i=BAR_START_Y+BAR_HEIGHT; i>=BAR_START_Y; i-=stepTick) {
            painter->setPen( Qt::black);
            painter->drawLine(BAR_START_X+BAR_WIDTH, i,
                              BAR_START_X+BAR_WIDTH+TICK_WIDTH, i);

            double val = getRealValue(i);
            painter->setPen( Qt::white);
            painter->setBrush( Qt::white );
            painter->drawText(BAR_START_X+BAR_WIDTH+TICK_WIDTH+3, i-TEXT_HEIGHT/4 - 4, TEXT_WIDTH, TEXT_HEIGHT,
                              Qt::KeepAspectRatio,QString::number(val,'f', 2));

            painter->setPen(Qt::blue);
            painter->setBrush( Qt::black );
            painter->drawText(BAR_START_X+BAR_WIDTH+TICK_WIDTH+4, i-TEXT_HEIGHT/4-5, TEXT_WIDTH, TEXT_HEIGHT,
                              Qt::KeepAspectRatio,QString::number(val,'f', 2));
        }
 
        // draw unit
        if (!this->_unit.isEmpty()) {
          QFontMetrics metrics(painter->font());
          int width = metrics.width(this->_unit);
          painter->save();
          painter->translate(BAR_START_X-metrics.descent()-1, BAR_START_Y+BAR_HEIGHT/2);
          painter->rotate(270);
          painter->setPen(Qt::white);
          painter->drawText(-width/2, 0, this->_unit);
          painter->setPen(Qt::black);
          painter->drawText(-width/2+1, -1, this->_unit);
          painter->restore();
        }
    }

    // draw selection
    if (_minSel!=_maxSel) {
        QRect rect(BAR_START_X-2, _minSel, BAR_WIDTH+5, _maxSel-_minSel);
        painter->setPen(QPen(Qt::black, 2));
        painter->setBrush(QColor(128, 128, 128, 50));
        painter->drawRect(rect);
    }
}
示例#6
0
void RadarDiagram::paint( PaintContext* ctx,
                          bool calculateListAndReturnScale,
                          qreal& newZoomX, qreal& newZoomY )
{
    // note: Not having any data model assigned is no bug
    //       but we can not draw a diagram then either.
    if ( !checkInvariants(true) )
        return;
    d->reverseMapper.clear();

    const int rowCount = model()->rowCount( rootIndex() );
    const int colCount = model()->columnCount( rootIndex() );

    int iRow, iCol;

    const qreal min = dataBoundaries().first.y();
    const qreal r = qAbs( min ) + dataBoundaries().second.y();
    const qreal step = ( r - qAbs( min ) ) / ( numberOfGridRings() );
    
    RadarCoordinatePlane* plane = dynamic_cast<RadarCoordinatePlane*>(ctx->coordinatePlane());
    TextAttributes ta = plane->textAttributes();
    QRectF fontRect = ctx->rectangle();    
    fontRect.setSize( QSizeF( fontRect.width(), step / 2.0 ) );
    const qreal labelFontSize = fitFontSizeToGeometry( QString::fromLatin1( "TestXYWQgqy" ), ta.font(), fontRect, ta );
    QFont labelFont = ta.font();
    ctx->painter()->setPen( ta.pen() );
    labelFont.setPointSizeF( labelFontSize );
    const QFontMetricsF metric( labelFont );
    const qreal labelHeight = metric.height();
    QPointF offset;
    QRectF destRect = ctx->rectangle();    
    if ( ta.isVisible() )
    {        
        destRect.setY( destRect.y() + 2 * labelHeight );
        destRect.setHeight( destRect.height() - 4 * labelHeight );
    }
    
    if ( calculateListAndReturnScale ) {
        ctx->painter()->save();
        // Check if all of the data value texts / data comments will fit
        // into the available space:
        d->labelPaintCache.clear();
        ctx->painter()->save();
        for ( iCol=0; iCol < colCount; ++iCol ) {
            for ( iRow=0; iRow < rowCount; ++iRow ) {
                QModelIndex index = model()->index( iRow, iCol, rootIndex() ); // checked
                const qreal value = model()->data( index ).toReal();
                QPointF point = scaleToRealPosition( QPointF( value, iRow ), ctx->rectangle(), destRect, *ctx->coordinatePlane() );
                d->addLabel( &d->labelPaintCache, index, 0, PositionPoints( point ),
                             Position::Center, Position::Center, value );
            }
        }
        ctx->painter()->restore();
        const qreal oldZoomX = coordinatePlane()->zoomFactorX();
        const qreal oldZoomY = coordinatePlane()->zoomFactorY();
        newZoomX = oldZoomX;
        newZoomY = oldZoomY;
        if ( d->labelPaintCache.paintReplay.count() ) {
            QRectF txtRectF;
            d->paintDataValueTextsAndMarkers( ctx, d->labelPaintCache, true, true, &txtRectF );
            const QRect txtRect = txtRectF.toRect();
            const QRect curRect = coordinatePlane()->geometry();
            const qreal gapX = qMin( txtRect.left() - curRect.left(), curRect.right()  - txtRect.right() );
            const qreal gapY = qMin( txtRect.top()  - curRect.top(),  curRect.bottom() - txtRect.bottom() );
            newZoomX = oldZoomX;
            newZoomY = oldZoomY;
            if ( gapX < 0.0 )
                newZoomX *= 1.0 + (gapX-1.0) / curRect.width();
            if ( gapY < 0.0 )
                newZoomY *= 1.0 + (gapY-1.0) / curRect.height();
        }
        ctx->painter()->restore();

    } else {
        // Iterate through data sets and create a list of polygons out of them.
        QList<Polygon> polygons;
        for ( iCol=0; iCol < colCount; ++iCol ) {
            //TODO(khz): As of yet RadarDiagram can not show per-segment line attributes
            //           but it draws every polyline in one go - using one color.
            //           This needs to be enhanced to allow for cell-specific settings
            //           in the same way as LineDiagram does it.
            QPolygonF polygon;
            QPointF point0;
            for ( iRow=0; iRow < rowCount; ++iRow ) {
                QModelIndex index = model()->index( iRow, iCol, rootIndex() ); // checked
                const qreal value = model()->data( index ).toReal();
                QPointF point = scaleToRealPosition( QPointF( value, d->reverseData ? ( rowCount - iRow ) : iRow ), ctx->rectangle(), destRect, *ctx->coordinatePlane() );
                polygon.append( point );
                if ( ! iRow )
                    point0= point;
            }
            if ( closeDatasets() && rowCount )
                polygon.append( point0 );

            QBrush brush = d->datasetAttrs( iCol, KChart::DatasetBrushRole ).value<QBrush>();
            QPen p = d->datasetAttrs( iCol, KChart::DatasetPenRole ).value< QPen >();
            if ( p.style() != Qt::NoPen )
            {
                polygons.append( Polygon( polygon, brush, PrintingParameters::scalePen( p ) ) );
            }
        }

        // first fill the areas with the brush-color and the defined alpha-value.
        if (d->fillAlpha > 0.0) {
            Q_FOREACH(const Polygon& p, polygons) {
                PainterSaver painterSaver( ctx->painter() );
                ctx->painter()->setRenderHint ( QPainter::Antialiasing );
                QBrush br = p.brush;
                QColor c = br.color();
                c.setAlphaF(d->fillAlpha);
                br.setColor(c);
                ctx->painter()->setBrush( br );
                ctx->painter()->setPen( p.pen );
                ctx->painter()->drawPolygon( p.polygon );
            }
        }
void ModelValidationWidget::updateValidation(ValidationInfo val_info)
{
	QTreeWidgetItem *item=new QTreeWidgetItem, *item1=nullptr, *item2=nullptr;
	QLabel *label=new QLabel, *label1=nullptr, *label2=nullptr;
	vector<BaseObject *> refs;
	BaseTable *table=nullptr;
	TableObject *tab_obj=nullptr;
	QString ref_name;

	if(val_info.getValidationType()==ValidationInfo::BROKEN_REFERENCE)
		label->setText(trUtf8("The object <strong>%1</strong> <em>(%2)</em> [id: %3] is being referenced by <strong>%4</strong> object(s) before its creation.")
									.arg(Utf8String::create(val_info.getObject()->getName(true).remove("\"")))
									.arg(val_info.getObject()->getTypeName())
									.arg(val_info.getObject()->getObjectId())
									.arg(val_info.getReferences().size()));
	else if(val_info.getValidationType()==ValidationInfo::NO_UNIQUE_NAME)
	{
		tab_obj=dynamic_cast<TableObject *>(val_info.getObject());

		if(tab_obj)
		{
			table=tab_obj->getParentTable();
			ref_name=table->getName(true).remove("\"") + "." + val_info.getObject()->getName(true).remove("\"");
		}
		else
			ref_name=val_info.getObject()->getName(true).remove("\"");

		label->setText(trUtf8("The object <strong>%1</strong> <em>(%2)</em> has a name that conflicts with <strong>%3</strong> object's name(s).")
									 .arg(Utf8String::create(ref_name))
									 .arg(val_info.getObject()->getTypeName())
									 .arg(val_info.getReferences().size()));

	}
	else if(val_info.getValidationType()==ValidationInfo::SQL_VALIDATION_ERR)
		label->setText(trUtf8("SQL validation failed due to error(s) below."));
	else
		label->setText(val_info.getErrors().at(0));

	output_trw->addTopLevelItem(item);

	if(val_info.getValidationType()==ValidationInfo::SQL_VALIDATION_ERR ||
		 val_info.getValidationType()==ValidationInfo::VALIDATION_ABORTED)
	{
		QStringList errors=val_info.getErrors();
		QFont fnt;
		item->setIcon(0, QPixmap(QString(":/icones/icones/msgbox_alerta.png")));
		validation_prog_pb->setValue(validation_prog_pb->maximum());

		if(val_info.getValidationType()==ValidationInfo::SQL_VALIDATION_ERR)
		{
			//Adding all the sql errors into the output pane
			while(!errors.isEmpty())
			{
				item1=new QTreeWidgetItem(item);
				label1=new QLabel;
				label1->setText(errors.back());
				fnt=label1->font();
				fnt.setPointSizeF(8.0f);
				label1->setFont(fnt);
				output_trw->setItemWidget(item1, 0, label1);
				errors.pop_back();
			}
		}
	}
	else
	{
		item->setIcon(0, QPixmap(QString(":/icones/icones/msgbox_erro.png")));

		//Listing the referrer object on output pane
		refs=val_info.getReferences();
		while(!refs.empty())
		{
			item1=new QTreeWidgetItem(item);
			label1=new QLabel;
			item1->setIcon(0, QPixmap(QString(":/icones/icones/") + refs.back()->getSchemaName() + QString(".png")));


			if(val_info.getValidationType()==ValidationInfo::NO_UNIQUE_NAME)
			{
				TableObject *tab_obj=dynamic_cast<TableObject *>(refs.back());
				ref_name=refs.back()->getName(true);

				//If the referrer object is a table object, concatenates the parent table name
				if(tab_obj)
				{
					ref_name=dynamic_cast<TableObject *>(refs.back())->getParentTable()->getName(true) + "." + ref_name;

					if(tab_obj->isAddedByRelationship())
					{
						QPalette pal;
						item2=new QTreeWidgetItem(item1);
						label2=new QLabel;
						pal.setColor(QPalette::Text, QColor(255,0,0));
						label2->setPalette(pal);
						label2->setText(trUtf8("<em>The above object was created by a relationship. Change the name pattern on it's generator relationship. Fix will not be applied!</em>"));
						output_trw->setItemWidget(item2, 0, label2);
						item1->setExpanded(true);
					}
				}

				label1->setText(trUtf8("Conflicting object: <strong>%1</strong> <em>(%2)</em>.")
												.arg(Utf8String::create(ref_name).remove("\""))
												.arg(Utf8String::create(refs.back()->getTypeName())));
			}
			else
			{
				label1->setText(trUtf8("Referrer object: <strong>%1</strong> <em>(%2)</em> [id: %3].")
												.arg(Utf8String::create(refs.back()->getName(true)))
												.arg(Utf8String::create(refs.back()->getTypeName()))
												.arg(refs.back()->getObjectId()));
			}

			output_trw->setItemWidget(item1, 0, label1);
			refs.pop_back();
		}
	}

	output_trw->setItemWidget(item, 0, label);

	item->setExpanded(false);

	//Stores the validatin on the current tree item
	item->setData(0, Qt::UserRole, QVariant::fromValue<ValidationInfo>(val_info));

	warn_count_lbl->setText(QString("%1").arg(validation_helper.getWarningCount()));
	error_count_lbl->setText(QString("%1").arg(validation_helper.getErrorCount()));
	output_trw->scrollToBottom();
}
示例#8
0
void
PlayableCover::paintEvent( QPaintEvent* event )
{
    Q_UNUSED( event );

    QPainter painter( this );
    painter.setRenderHint( QPainter::Antialiasing );
    painter.drawPixmap( 0, 0, pixmap() );

    if ( !m_showText )
        return;

    QRect r = contentsRect().adjusted( margin(), margin(), -margin(), -margin() );
    QPixmap buffer( r.size() );
    buffer.fill( Qt::transparent );
    QPainter bufpainter( &buffer );
    bufpainter.setRenderHint( QPainter::Antialiasing );

    QTextOption to;
    to.setWrapMode( QTextOption::NoWrap );

    QColor c1;
    c1.setRgb( 0, 0, 0 );
    c1.setAlphaF( 0.00 );
    QColor c2;
    c2.setRgb( 0, 0, 0 );
    c2.setAlphaF( 0.88 );

    QString text;
    QFont font = QLabel::font();
    font.setPointSize( TomahawkUtils::defaultFontSize() );
    QFont boldFont = font;
    boldFont.setBold( true );
    boldFont.setPointSize( TomahawkUtils::defaultFontSize() + 5 );

    QString top, bottom;
    if ( m_artist )
    {
        top = m_artist->name();
    }
    else if ( m_album )
    {
        top = m_album->name();
        bottom = m_album->artist()->name();
    }
    else if ( m_query )
    {
        top = m_query->queryTrack()->track();
        bottom = m_query->queryTrack()->artist();
    }

    int bottomHeight = QFontMetrics( font ).boundingRect( bottom ).height();
    int topHeight = QFontMetrics( boldFont ).boundingRect( top ).height();
    int frameHeight = bottomHeight + topHeight + 4;

    QRect gradientRect = r.adjusted( 0, r.height() - frameHeight * 3, 0, 0 );
    QLinearGradient gradient( QPointF( 0, 0 ), QPointF( 0, 1 ) );
    gradient.setCoordinateMode( QGradient::ObjectBoundingMode );
    gradient.setColorAt( 0.0, c1 );
    gradient.setColorAt( 0.6, c2 );
    gradient.setColorAt( 1.0, c2 );

    bufpainter.save();
    bufpainter.setPen( Qt::transparent );
    bufpainter.setBrush( gradient );
    bufpainter.drawRect( gradientRect );
    bufpainter.restore();

    bufpainter.setPen( Qt::white );

    QRect textRect = r.adjusted( 8, r.height() - frameHeight - 16, -8, -16 );
    bool oneLiner = false;
    if ( bottom.isEmpty() )
        oneLiner = true;

    bufpainter.setFont( boldFont );
    if ( oneLiner )
    {
        bufpainter.save();
        QFont f = bufpainter.font();

        while ( f.pointSizeF() > 9 && bufpainter.fontMetrics().width( top ) > textRect.width() )
        {
            f.setPointSizeF( f.pointSizeF() - 0.2 );
            bufpainter.setFont( f );
        }

        to.setAlignment( Qt::AlignHCenter | Qt::AlignVCenter );
        text = bufpainter.fontMetrics().elidedText( top, Qt::ElideRight, textRect.width() - 3 );
        bufpainter.drawText( textRect, text, to );

        bufpainter.restore();
    }
    else
    {
        to.setAlignment( Qt::AlignHCenter | Qt::AlignTop );
        text = bufpainter.fontMetrics().elidedText( top, Qt::ElideRight, textRect.width() - 3 );
        bufpainter.drawText( textRect, text, to );

        bufpainter.setFont( font );

        QRect r = textRect;
        r.setTop( r.bottom() - bufpainter.fontMetrics().height() );
        r.adjust( 4, 0, -4, -1 );

        text = bufpainter.fontMetrics().elidedText( bottom, Qt::ElideRight, textRect.width() - 16 );
        int textWidth = bufpainter.fontMetrics().width( text );
        r.adjust( ( r.width() - textWidth ) / 2 - 6, 0, - ( ( r.width() - textWidth ) / 2 - 6 ), 0 );

        m_itemRects.clear();
        m_itemRects << r;

        if ( m_hoveredRect == r )
        {
            TomahawkUtils::drawQueryBackground( &bufpainter, r );
            bufpainter.setPen( TomahawkUtils::Colors::SELECTION_FOREGROUND );
        }

        to.setAlignment( Qt::AlignHCenter | Qt::AlignBottom );
        bufpainter.drawText( textRect.adjusted( 5, -1, -5, -1 ), text, to );
    }

    {
        QBrush brush( buffer );
        QPen pen;
        pen.setColor( Qt::transparent );
        pen.setJoinStyle( Qt::RoundJoin );

        float frameWidthPct = 0.20;
        painter.setBrush( brush );
        painter.setPen( pen );
        painter.drawRoundedRect( r, frameWidthPct * 100.0, frameWidthPct * 100.0, Qt::RelativeSize );
    }
}
示例#9
0
void ReceiveRequestDialog::update()
{
    if(!model)
        return;
    QString target = info.label;
    if(target.isEmpty())
        target = info.address;
    setWindowTitle(tr("Request payment to %1").arg(target));

    QString uri = GUIUtil::formatBitcoinURI(info);
    ui->btnSaveAs->setEnabled(false);
    QString html;
    html += "<html><font face='verdana, arial, helvetica, sans-serif'>";
    html += "<b>"+tr("Payment information")+"</b><br>";
    html += "<b>"+tr("URI")+"</b>: ";
    html += "<a href=\""+uri+"\">" + GUIUtil::HtmlEscape(uri) + "</a><br>";
    html += "<b>"+tr("Address")+"</b>: " + GUIUtil::HtmlEscape(info.address) + "<br>";
    if(info.amount)
        html += "<b>"+tr("Amount")+"</b>: " + BitcoinUnits::formatHtmlWithUnit(model->getOptionsModel()->getDisplayUnit(), info.amount) + "<br>";
    if(!info.label.isEmpty())
        html += "<b>"+tr("Label")+"</b>: " + GUIUtil::HtmlEscape(info.label) + "<br>";
    if(!info.message.isEmpty())
        html += "<b>"+tr("Message")+"</b>: " + GUIUtil::HtmlEscape(info.message) + "<br>";
    if(model->isMultiwallet()) {
        html += "<b>"+tr("Wallet")+"</b>: " + GUIUtil::HtmlEscape(model->getWalletName()) + "<br>";
    }
    ui->outUri->setText(html);

#ifdef USE_QRCODE
    ui->lblQRCode->setText("");
    if(!uri.isEmpty())
    {
        // limit URI length
        if (uri.length() > MAX_URI_LENGTH)
        {
            ui->lblQRCode->setText(tr("Resulting URI too long, try to reduce the text for label / message."));
        } else {
            QRcode *code = QRcode_encodeString(uri.toUtf8().constData(), 0, QR_ECLEVEL_L, QR_MODE_8, 1);
            if (!code)
            {
                ui->lblQRCode->setText(tr("Error encoding URI into QR Code."));
                return;
            }
            QImage qrImage = QImage(code->width + 8, code->width + 8, QImage::Format_RGB32);
            qrImage.fill(0xffffff);
            unsigned char *p = code->data;
            for (int y = 0; y < code->width; y++)
            {
                for (int x = 0; x < code->width; x++)
                {
                    qrImage.setPixel(x + 4, y + 4, ((*p & 1) ? 0x0 : 0xffffff));
                    p++;
                }
            }
            QRcode_free(code);

            QImage qrAddrImage = QImage(QR_IMAGE_SIZE, QR_IMAGE_SIZE+20, QImage::Format_RGB32);
            qrAddrImage.fill(0xffffff);
            QPainter painter(&qrAddrImage);
            painter.drawImage(0, 0, qrImage.scaled(QR_IMAGE_SIZE, QR_IMAGE_SIZE));
            QFont font = GUIUtil::fixedPitchFont();
            QRect paddedRect = qrAddrImage.rect();

            // calculate ideal font size
            qreal font_size = GUIUtil::calculateIdealFontSize(paddedRect.width() - 20, info.address, font);
            font.setPointSizeF(font_size);

            painter.setFont(font);
            paddedRect.setHeight(QR_IMAGE_SIZE+12);
            painter.drawText(paddedRect, Qt::AlignBottom|Qt::AlignCenter, info.address);
            painter.end();

            ui->lblQRCode->setPixmap(QPixmap::fromImage(qrAddrImage));
            ui->btnSaveAs->setEnabled(true);
        }
    }
#endif
}
示例#10
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);
    }
示例#11
0
/**
   Take data from image, draw text at x|y with specified parameters.
   If destPainter is null, draw to image,
   if destPainter is not null, draw directly using the painter.
   Returns modified area of image.
*/
QRect InsertTextWidget::composeImage(DImg* const image, QPainter* const destPainter,
                                     int x, int y,
                                     QFont font, float pointSize, int textRotation, QColor textColor,
                                     int alignMode, const QString& textString,
                                     bool transparentBackground, QColor backgroundColor,
                                     BorderMode borderMode, int borderWidth, int spacing)
{
    /*
        The problem we have to solve is that we have no pixel access to font rendering,
        we have to let Qt do the drawing. On the other hand we need to support 16 bit, which
        cannot be done with QPixmap.
        The current solution cuts out the text area, lets Qt do its drawing, converts back and blits to original.
    */
    DColorComposer* composer = DColorComposer::getComposer(DColorComposer::PorterDuffNone);

    int maxWidth, maxHeight;

    if (x == -1 && y == -1)
    {
        maxWidth = image->width();
        maxHeight = image->height();
    }
    else
    {
        maxWidth = image->width() - x;
        maxHeight = image->height() - y;
    }

    // find out size of the area that we are drawing to
    font.setPointSizeF(pointSize);
    QFontMetrics fontMt( font );
    QRect fontRect = fontMt.boundingRect(0, 0, maxWidth, maxHeight, 0, textString);

    int fontWidth, fontHeight;

    switch (textRotation)
    {
        case ROTATION_NONE:
        case ROTATION_180:
        default:
            fontWidth = fontRect.width();
            fontHeight = fontRect.height();
            break;

        case ROTATION_90:
        case ROTATION_270:
            fontWidth = fontRect.height();
            fontHeight = fontRect.width();
            break;
    }

    // x, y == -1 means that we have to find a good initial position for the text here
    if (x == -1 && y == -1)
    {
        // was a valid position hint stored from last use?
        if (d->positionHint.isValid())
        {
            // We assume that people tend to orient text along the edges,
            // so we do some guessing so that positions such as "in the lower right corner"
            // will be remembered across different image sizes.

            // get relative positions
            float fromTop =          (float)d->positionHint.top()    / 10000.0;
            float fromBottom = 1.0 - (float)d->positionHint.bottom() / 10000.0;
            float fromLeft =         (float)d->positionHint.left()   / 10000.0;
            float fromRight =  1.0 - (float)d->positionHint.right()  / 10000.0;

            // calculate horizontal position
            if (fromLeft < fromRight)
            {
                x = (int)(fromLeft * maxWidth);

                // we are placing from the smaller distance,
                // so if now the larger distance is actually too small,
                // fall back to standard placement, nothing to lose.
                if (x + fontWidth > maxWidth)
                {
                    x = qMax( (maxWidth - fontWidth) / 2, 0);
                }
            }
            else
            {
                x = maxWidth - (int)(fromRight * maxWidth) - fontWidth;

                if ( x < 0 )
                {
                    x = qMax( (maxWidth - fontWidth) / 2, 0);
                }
            }

            // calculate vertical position
            if (fromTop < fromBottom)
            {
                y = (int)(fromTop * maxHeight);

                if (y + fontHeight > maxHeight)
                {
                    y = qMax( (maxHeight - fontHeight) / 2, 0);
                }
            }
            else
            {
                y = maxHeight - (int)(fromBottom * maxHeight) - fontHeight;

                if ( y < 0 )
                {
                    y = qMax( (maxHeight - fontHeight) / 2, 0);
                }
            }

            if (! QRect(x, y, fontWidth, fontHeight).
                intersects(QRect(0, 0, maxWidth, maxHeight)) )
            {
                // emergency fallback - nothing is visible
                x = qMax( (maxWidth - fontWidth) / 2, 0);
                y = qMax( (maxHeight - fontHeight) / 2, 0);
            }

            // invalidate position hint, use only once
            d->positionHint = QRect();
        }
        else
        {
            // use standard position
            x = qMax( (maxWidth - fontWidth) / 2, 0);
            y = qMax( (maxHeight - fontHeight) / 2, 0);
        }
    }

    // create a rectangle relative to image
    QRect drawRect( x, y, fontWidth + 2 * borderWidth + 2 * spacing, fontHeight + 2 * borderWidth  + 2 * spacing);

    // create a rectangle relative to textArea, excluding the border
    QRect textAreaBackgroundRect( borderWidth, borderWidth, fontWidth + 2 * spacing, fontHeight + 2 * spacing);

    // create a rectangle relative to textArea, excluding the border and spacing
    QRect textAreaTextRect( borderWidth + spacing, borderWidth + spacing, fontWidth, fontHeight );

    // create a rectangle relative to textArea, including the border,
    // for drawing the rectangle, taking into account that the width of the QPen goes in and out in equal parts
    QRect textAreaDrawRect( borderWidth / 2, borderWidth / 2, fontWidth + borderWidth + 2 * spacing,
                            fontHeight + borderWidth + 2 * spacing );

    // cut out the text area
    DImg textArea = image->copy(drawRect);

    if (textArea.isNull())
    {
        return QRect();
    }

    // compose semi-transparent background over textArea
    if (transparentBackground)
    {
        DImg transparentLayer(textAreaBackgroundRect.width(), textAreaBackgroundRect.height(), textArea.sixteenBit(), true);
        DColor transparent(backgroundColor);
        transparent.setAlpha(d->transparency);

        if (image->sixteenBit())
        {
            transparent.convertToSixteenBit();
        }

        transparentLayer.fill(transparent);
        textArea.bitBlendImage(composer, &transparentLayer, 0, 0, transparentLayer.width(), transparentLayer.height(),
                               textAreaBackgroundRect.x(), textAreaBackgroundRect.y());
    }

    DImg textNotDrawn;

    if (textArea.sixteenBit())
    {
        textNotDrawn = textArea.copy();
        textNotDrawn.convertToEightBit();
    }
    else
    {
        textNotDrawn = textArea;
    }

    // We have no direct pixel access to font rendering, so now we need to use Qt/X11 for the drawing

    // convert text area to pixmap
    QPixmap pixmap;

    if (destPainter)
    {
        // We working on tool preview, deal with CM as well
        pixmap = d->iface->convertToPixmap(textNotDrawn);
    }
    else
    {
        // We working on target image. Do no apply double CM adjustement here.
        pixmap = textNotDrawn.convertToPixmap();
    }

    // paint on pixmap
    QPainter p(&pixmap);
    p.setPen( QPen(textColor, 1) ) ;
    p.setFont( font );
    p.save();

    // translate to origin of text, leaving space for the border
    p.translate(textAreaTextRect.x(), textAreaTextRect.y());

    switch (textRotation)
    {
        case ROTATION_NONE:
            p.drawText( 0, 0, textAreaTextRect.width(),
                        textAreaTextRect.height(), alignMode, textString );
            break;
        case ROTATION_90:
            p.translate(textAreaTextRect.width(), 0);
            p.rotate(90.0);
            p.drawText( 0, 0, textAreaTextRect.height(), textAreaTextRect.width(),
                        alignMode, textString );
            break;
        case ROTATION_180:
            p.translate(textAreaTextRect.width(), textAreaTextRect.height());
            p.rotate(180.0);
            p.drawText( 0, 0, textAreaTextRect.width(), textAreaTextRect.height(),
                        alignMode, textString );
            break;
        case ROTATION_270:
            p.translate(0, textAreaTextRect.height());
            p.rotate(270.0);
            p.drawText( 0, 0, textAreaTextRect.height(), textAreaTextRect.width(),
                        alignMode, textString );
            break;
    }

    p.restore();

    // Drawing rectangle around text.

    if (borderMode == BORDER_NORMAL)      // Decorative border using text color.
    {
        p.setPen( QPen(textColor, borderWidth, Qt::SolidLine,
                       Qt::SquareCap, Qt::RoundJoin) ) ;
        p.drawRect(textAreaDrawRect);
    }
    else if (borderMode == BORDER_SUPPORT)  // Make simple dot line border to help user.
    {
        p.setPen(QPen(Qt::white, 1, Qt::SolidLine));
        p.drawRect(textAreaDrawRect);
        p.setPen(QPen(Qt::red, 1, Qt::DotLine));
        p.drawRect(textAreaDrawRect);
    }

    p.end();

    if (!destPainter)
    {
        // convert to QImage, then to DImg
        QImage pixmapImage = pixmap.toImage();
        DImg textDrawn(pixmapImage.width(), pixmapImage.height(), false, true, pixmapImage.bits());

        // This does not work: during the conversion, colors are altered significantly (diffs of 1 to 10 in each component),
        // so we cannot find out which pixels have actually been touched.
        /*
        // Compare the result of drawing with the previous version.
        // Set all unchanged pixels to transparent
        DColor color, ncolor;
        uchar *ptr, *nptr;
        ptr = textDrawn.bits();
        nptr = textNotDrawn.bits();
        int bytesDepth = textDrawn.bytesDepth();
        int numPixels = textDrawn.width() * textDrawn.height();
        for (int i = 0; i < numPixels; ++i, ptr+= bytesDepth, nptr += bytesDepth)
        {
            color.setColor(ptr, false);
            ncolor.setColor(nptr, false);
            if ( color.red()   == ncolor.red() &&
                color.green() == ncolor.green() &&
                color.blue()  == ncolor.blue())
            {
                color.setAlpha(0);
                color.setPixel(ptr);
            }
        }
        // convert to 16 bit if needed
        */
        textDrawn.convertToDepthOfImage(&textArea);

        // now compose to original: only pixels affected by drawing text and border are changed, not whole area
        textArea.bitBlendImage(composer, &textDrawn, 0, 0, textDrawn.width(), textDrawn.height(), 0, 0);

        // copy result to original image
        image->bitBltImage(&textArea, drawRect.x(), drawRect.y());
    }
    else
    {
        destPainter->drawPixmap(drawRect.x(), drawRect.y(), pixmap, 0, 0, pixmap.width(), pixmap.height());
    }

    delete composer;

    return drawRect;
}
示例#12
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;
}
示例#13
0
//! Initialized the syntax highlighter with default values.
void ModelicaTextHighlighter::initializeSettings()
{
  QFont font;
  font.setFamily(mpModelicaEditorPage->getOptionsDialog()->getTextEditorPage()->getFontFamilyComboBox()->currentFont().family());
  font.setPointSizeF(mpModelicaEditorPage->getOptionsDialog()->getTextEditorPage()->getFontSizeSpinBox()->value());
  mpPlainTextEdit->document()->setDefaultFont(font);
  mpPlainTextEdit->setTabStopWidth(mpModelicaEditorPage->getOptionsDialog()->getTextEditorPage()->getTabSizeSpinBox()->value() * QFontMetrics(font).width(QLatin1Char(' ')));
  // set color highlighting
  mHighlightingRules.clear();
  HighlightingRule rule;
  mTextFormat.setForeground(mpModelicaEditorPage->getTextRuleColor());
  mKeywordFormat.setForeground(mpModelicaEditorPage->getKeywordRuleColor());
  mTypeFormat.setForeground(mpModelicaEditorPage->getTypeRuleColor());
  mSingleLineCommentFormat.setForeground(mpModelicaEditorPage->getCommentRuleColor());
  mMultiLineCommentFormat.setForeground(mpModelicaEditorPage->getCommentRuleColor());
  mFunctionFormat.setForeground(mpModelicaEditorPage->getFunctionRuleColor());
  mQuotationFormat.setForeground(QColor(mpModelicaEditorPage->getQuotesRuleColor()));
  // Priority: keyword > func() > ident > number. Yes, the order matters :)
  mNumberFormat.setForeground(mpModelicaEditorPage->getNumberRuleColor());
  rule.mPattern = QRegExp("[0-9][0-9]*([.][0-9]*)?([eE][+-]?[0-9]*)?");
  rule.mFormat = mNumberFormat;
  mHighlightingRules.append(rule);
  rule.mPattern = QRegExp("\\b[A-Za-z_][A-Za-z0-9_]*");
  rule.mFormat = mTextFormat;
  mHighlightingRules.append(rule);
  // keywords
  QStringList keywordPatterns;
  keywordPatterns << "\\balgorithm\\b"
                  << "\\band\\b"
                  << "\\bannotation\\b"
                  << "\\bassert\\b"
                  << "\\bblock\\b"
                  << "\\bbreak\\b"
                  << "\\bBoolean\\b"
                  << "\\bclass\\b"
                  << "\\bconnect\\b"
                  << "\\bconnector\\b"
                  << "\\bconstant\\b"
                  << "\\bconstrainedby\\b"
                  << "\\bder\\b"
                  << "\\bdiscrete\\b"
                  << "\\beach\\b"
                  << "\\belse\\b"
                  << "\\belseif\\b"
                  << "\\belsewhen\\b"
                  << "\\bencapsulated\\b"
                  << "\\bend\\b"
                  << "\\benumeration\\b"
                  << "\\bequation\\b"
                  << "\\bexpandable\\b"
                  << "\\bextends\\b"
                  << "\\bexternal\\b"
                  << "\\bfalse\\b"
                  << "\\bfinal\\b"
                  << "\\bflow\\b"
                  << "\\bfor\\b"
                  << "\\bfunction\\b"
                  << "\\bif\\b"
                  << "\\bimport\\b"
                  << "\\bimpure\\b"
                  << "\\bin\\b"
                  << "\\binitial\\b"
                  << "\\binner\\b"
                  << "\\binput\\b"
                  << "\\bloop\\b"
                  << "\\bmodel\\b"
                  << "\\bnot\\b"
                  << "\\boperator\\b"
                  << "\\bor\\b"
                  << "\\bouter\\b"
                  << "\\boutput\\b"
                  << "\\boptimization\\b"
                  << "\\bpackage\\b"
                  << "\\bparameter\\b"
                  << "\\bpartial\\b"
                  << "\\bprotected\\b"
                  << "\\bpublic\\b"
                  << "\\bpure\\b"
                  << "\\brecord\\b"
                  << "\\bredeclare\\b"
                  << "\\breplaceable\\b"
                  << "\\breturn\\b"
                  << "\\bstream\\b"
                  << "\\bthen\\b"
                  << "\\btrue\\b"
                  << "\\btype\\b"
                  << "\\bwhen\\b"
                  << "\\bwhile\\b"
                  << "\\bwithin\\b";
  foreach (const QString &pattern, keywordPatterns)
  {
    rule.mPattern = QRegExp(pattern);
    rule.mFormat = mKeywordFormat;
    mHighlightingRules.append(rule);
  }
// Configuration widget
CMakeRunConfigurationWidget::CMakeRunConfigurationWidget(CMakeRunConfiguration *cmakeRunConfiguration, QWidget *parent)
    : QWidget(parent), m_ignoreChange(false), m_cmakeRunConfiguration(cmakeRunConfiguration)
{
    QFormLayout *fl = new QFormLayout();
    fl->setMargin(0);
    fl->setFieldGrowthPolicy(QFormLayout::ExpandingFieldsGrow);
    QLineEdit *argumentsLineEdit = new QLineEdit();
    argumentsLineEdit->setText(cmakeRunConfiguration->commandLineArguments());
    connect(argumentsLineEdit, SIGNAL(textChanged(QString)),
            this, SLOT(setArguments(QString)));
    fl->addRow(tr("Arguments:"), argumentsLineEdit);

    m_workingDirectoryEdit = new Utils::PathChooser();
    m_workingDirectoryEdit->setExpectedKind(Utils::PathChooser::Directory);
    m_workingDirectoryEdit->setBaseDirectory(m_cmakeRunConfiguration->target()->project()->projectDirectory());
    m_workingDirectoryEdit->setPath(m_cmakeRunConfiguration->baseWorkingDirectory());
    m_workingDirectoryEdit->setPromptDialogTitle(tr("Select Working Directory"));

    QToolButton *resetButton = new QToolButton();
    resetButton->setToolTip(tr("Reset to default"));
    resetButton->setIcon(QIcon(QLatin1String(Core::Constants::ICON_RESET)));

    QHBoxLayout *boxlayout = new QHBoxLayout();
    boxlayout->addWidget(m_workingDirectoryEdit);
    boxlayout->addWidget(resetButton);

    fl->addRow(tr("Working directory:"), boxlayout);

    QCheckBox *runInTerminal = new QCheckBox;
    fl->addRow(tr("Run in Terminal"), runInTerminal);

    m_detailsContainer = new Utils::DetailsWidget(this);
    m_detailsContainer->setState(Utils::DetailsWidget::NoSummary);

    QWidget *m_details = new QWidget(m_detailsContainer);
    m_detailsContainer->setWidget(m_details);
    m_details->setLayout(fl);

    QVBoxLayout *vbx = new QVBoxLayout(this);
    vbx->setMargin(0);;
    vbx->addWidget(m_detailsContainer);

    QLabel *environmentLabel = new QLabel(this);
    environmentLabel->setText(tr("Run Environment"));
    QFont f = environmentLabel->font();
    f.setBold(true);
    f.setPointSizeF(f.pointSizeF() *1.2);
    environmentLabel->setFont(f);
    vbx->addWidget(environmentLabel);

    QWidget *baseEnvironmentWidget = new QWidget;
    QHBoxLayout *baseEnvironmentLayout = new QHBoxLayout(baseEnvironmentWidget);
    baseEnvironmentLayout->setMargin(0);
    QLabel *label = new QLabel(tr("Base environment for this runconfiguration:"), this);
    baseEnvironmentLayout->addWidget(label);
    m_baseEnvironmentComboBox = new QComboBox(this);
    m_baseEnvironmentComboBox->addItems(QStringList()
                                        << tr("Clean Environment")
                                        << tr("System Environment")
                                        << tr("Build Environment"));
    m_baseEnvironmentComboBox->setCurrentIndex(m_cmakeRunConfiguration->baseEnvironmentBase());
    connect(m_baseEnvironmentComboBox, SIGNAL(currentIndexChanged(int)),
            this, SLOT(baseEnvironmentComboBoxChanged(int)));
    baseEnvironmentLayout->addWidget(m_baseEnvironmentComboBox);
    baseEnvironmentLayout->addStretch(10);

    m_environmentWidget = new ProjectExplorer::EnvironmentWidget(this, baseEnvironmentWidget);
    m_environmentWidget->setBaseEnvironment(m_cmakeRunConfiguration->baseEnvironment());
    m_environmentWidget->setBaseEnvironmentText(m_cmakeRunConfiguration->baseEnvironmentText());
    m_environmentWidget->setUserChanges(m_cmakeRunConfiguration->userEnvironmentChanges());

    vbx->addWidget(m_environmentWidget);

    connect(m_workingDirectoryEdit, SIGNAL(changed(QString)),
            this, SLOT(setWorkingDirectory()));

    connect(resetButton, SIGNAL(clicked()),
            this, SLOT(resetWorkingDirectory()));

    connect(runInTerminal, SIGNAL(toggled(bool)),
            this, SLOT(runInTerminalToggled(bool)));

    connect(m_environmentWidget, SIGNAL(userChangesChanged()),
            this, SLOT(userChangesChanged()));

    connect(m_cmakeRunConfiguration, SIGNAL(baseWorkingDirectoryChanged(QString)),
            this, SLOT(workingDirectoryChanged(QString)));
    connect(m_cmakeRunConfiguration, SIGNAL(baseEnvironmentChanged()),
            this, SLOT(baseEnvironmentChanged()));
    connect(m_cmakeRunConfiguration, SIGNAL(userEnvironmentChangesChanged(QList<Utils::EnvironmentItem>)),
            this, SLOT(userEnvironmentChangesChanged()));

    setEnabled(m_cmakeRunConfiguration->isEnabled());
}
示例#15
0
BasepointPixmap OverlayTextLine::createPixmap(unsigned int maxwidth, unsigned int height, QColor col) {
	float twice_edge = 2.0f * fEdge;

	if (! height || ! maxwidth)
		return BasepointPixmap();

	if (qpp.isEmpty() || iCurWidth > static_cast<int>(maxwidth) || iCurHeight != static_cast<int>(height) || (static_cast<int>(maxwidth) > iCurWidth && bElided)) {
		QFont f = qfFont;
		QFontMetrics fm(f);

		// fit the font into a bounding box with padding
		float ps = static_cast<float>(f.pointSizeF());
		float f_ad = static_cast<float>(fm.ascent() + fm.descent()+1) / ps;

		float pointsize = static_cast<float>(height) / (f_ad + 2.0f*fEdgeFactor);

		if (fEdgeFactor * ps > 1.0f) {
			pointsize = static_cast<float>(height-2) / f_ad;
		}

		if (pointsize <= 0.0f) {
			return BasepointPixmap();
		}

		f.setPointSizeF(pointsize);
		setFont(f);
		fm = QFontMetrics(f);
		twice_edge = 2.0f * fEdge;

		if (!qpp.isEmpty()) {
			qpp = QPainterPath();
		}

		// calculate text metrics for eliding and scaling
		QRectF bb;
		qpp.addText(0.0f, 0.0f, f, qsText);
		bb = qpp.controlPointRect();

		qreal effective_ascent = -bb.top();
		qreal effective_descent = bb.bottom();
		float scale = 1.0f;
		bool keep_baseline = true;
		if (effective_descent > fDescent || effective_ascent > fAscent) {
			qreal scale_ascent = effective_ascent > 0.0f ? fAscent / effective_ascent : 1.0f;
			qreal scale_descent = effective_descent > 0.0f ? fDescent / effective_descent : 1.0f;
			scale = static_cast<float>(qMin(scale_ascent, scale_descent));

			if (scale < fBaseliningThreshold) {
				float text_height = static_cast<float>(bb.height()) + twice_edge;
				scale = static_cast<float>(height) / text_height;
				keep_baseline = false;
			}

			qWarning() << QString(QLatin1String("Text \"%1\" did not fit (+%2/-%3): (+%4/-%5). Scaling to %6.")).arg(qsText).arg(fAscent).arg(fDescent).arg(effective_ascent).arg(effective_descent).arg(scale);
		}

		// eliding by previously calculated width
		if ((bb.width()*scale) + twice_edge > maxwidth) {
			int eliding_width = iroundf((static_cast<float>(maxwidth) / scale) - twice_edge + 0.5f);
			QString str = fm.elidedText(qsText, Qt::ElideRight, eliding_width);

			// use ellipsis as shortest possible string
			if (str.trimmed().isEmpty()) {
				str = QString(QChar(0x2026));
			}

			qpp = QPainterPath();
			qpp.addText(0.0f, 0.0f, f, str);
			bb = qpp.controlPointRect();
			bElided = true;
		} else {
			bElided = false;
		}

		// translation to "pixmap space":
		QMatrix correction;
		//  * adjust left edge
		correction.translate(-bb.x() + fEdge, 0.0f);
		//  * scale overly high text (still on baseline)
		correction.scale(scale, scale);

		if (keep_baseline) {
			//  * translate down to baseline
			correction.translate(0.0f, (fAscent + fEdge) / scale);
		} else {
			//  * translate into bounding box
			correction.translate(0.0f, -bb.top() + fEdge);
		}

		qpp = correction.map(qpp);
		iCurWidth = iroundf(bb.width() * scale + 0.5f);
		iCurHeight = height;
	}

	QRectF qr = qpp.controlPointRect();

	return render(
	           iroundf(qr.width() + twice_edge + 0.5f),
	           iroundf(fAscent + fDescent + twice_edge + 0.5f),
	           col,
	           QPoint(0, iroundf(fAscent + fEdge + 0.5f))
	       );
}
RunSettingsWidget::RunSettingsWidget(Target *target)
    : m_target(target),
      m_runConfigurationsModel(new RunConfigurationModel(target, this)),
      m_deployConfigurationModel(new DeployConfigurationModel(target, this)),
      m_runConfigurationWidget(0),
      m_runLayout(0),
      m_deployConfigurationWidget(0),
      m_deployLayout(0),
      m_deploySteps(0),
      m_ignoreChange(false)
{
    Q_ASSERT(m_target);

    m_deployConfigurationCombo = new QComboBox(this);
    m_addDeployToolButton = new QPushButton(tr("Add"), this);
    m_removeDeployToolButton = new QPushButton(tr("Remove"), this);
    m_renameDeployButton = new QPushButton(tr("Rename..."), this);

    QWidget *deployWidget = new QWidget(this);

    m_runConfigurationCombo = new QComboBox(this);
    m_runConfigurationCombo->setSizeAdjustPolicy(QComboBox::AdjustToContents);
    m_runConfigurationCombo->setMinimumContentsLength(15);

    m_addRunToolButton = new QPushButton(tr("Add"), this);
    m_removeRunToolButton = new QPushButton(tr("Remove"), this);
    m_renameRunButton = new QPushButton(tr("Rename..."), this);

    QSpacerItem *spacer1 =
        new QSpacerItem(10, 10, QSizePolicy::Expanding, QSizePolicy::Minimum);
    QSpacerItem *spacer2 =
        new QSpacerItem(10, 10, QSizePolicy::Minimum, QSizePolicy::Expanding);

    QWidget *runWidget = new QWidget(this);

    QLabel *deployTitle = new QLabel(tr("Deployment"), this);
    QLabel *deployLabel = new QLabel(tr("Method:"), this);
    QLabel *runTitle = new QLabel(tr("Run"), this);
    QLabel *runLabel = new QLabel(tr("Run configuration:"), this);

    runLabel->setBuddy(m_runConfigurationCombo);

    QFont f = runLabel->font();
    f.setBold(true);
    f.setPointSizeF(f.pointSizeF() * 1.2);

    runTitle->setFont(f);
    deployTitle->setFont(f);

    m_gridLayout = new QGridLayout(this);
    m_gridLayout->setContentsMargins(0, 20, 0, 0);
    m_gridLayout->setHorizontalSpacing(6);
    m_gridLayout->setVerticalSpacing(8);
    m_gridLayout->addWidget(deployTitle, 0, 0, 1, 6);
    m_gridLayout->addWidget(deployLabel, 1, 0, 1, 1);
    m_gridLayout->addWidget(m_deployConfigurationCombo, 1, 1, 1, 1);
    m_gridLayout->addWidget(m_addDeployToolButton, 1, 2, 1, 1);
    m_gridLayout->addWidget(m_removeDeployToolButton, 1, 3, 1, 1);
    m_gridLayout->addWidget(m_renameDeployButton, 1, 4, 1, 1);
    m_gridLayout->addWidget(deployWidget, 2, 0, 1, 6);

    m_gridLayout->addWidget(runTitle, 3, 0, 1, 6);
    m_gridLayout->addWidget(runLabel, 4, 0, 1, 1);
    m_gridLayout->addWidget(m_runConfigurationCombo, 4, 1, 1, 1);
    m_gridLayout->addWidget(m_addRunToolButton, 4, 2, 1, 1);
    m_gridLayout->addWidget(m_removeRunToolButton, 4, 3, 1, 1);
    m_gridLayout->addWidget(m_renameRunButton, 4, 4, 1, 1);
    m_gridLayout->addItem(spacer1, 4, 5, 1, 1);
    m_gridLayout->addWidget(runWidget, 5, 0, 1, 6);
    m_gridLayout->addItem(spacer2, 6, 0, 1, 1);

    // deploy part
    deployWidget->setContentsMargins(0, 10, 0, 25);
    m_deployLayout = new QVBoxLayout(deployWidget);
    m_deployLayout->setMargin(0);
    m_deployLayout->setSpacing(5);

    m_deployConfigurationCombo->setModel(m_deployConfigurationModel);

    m_addDeployMenu = new QMenu(m_addDeployToolButton);
    m_addDeployToolButton->setMenu(m_addDeployMenu);

    updateDeployConfiguration(m_target->activeDeployConfiguration());

    // Some projects may not support deployment, so we need this:
    m_addDeployToolButton->setEnabled(m_target->activeDeployConfiguration());
    m_deployConfigurationCombo->setEnabled(m_target->activeDeployConfiguration());

    m_removeDeployToolButton->setEnabled(m_target->deployConfigurations().count() > 1);
    m_renameDeployButton->setEnabled(m_target->activeDeployConfiguration());

    connect(m_addDeployMenu, SIGNAL(aboutToShow()),
            this, SLOT(aboutToShowDeployMenu()));
    connect(m_deployConfigurationCombo, SIGNAL(currentIndexChanged(int)),
            this, SLOT(currentDeployConfigurationChanged(int)));
    connect(m_removeDeployToolButton, SIGNAL(clicked(bool)),
            this, SLOT(removeDeployConfiguration()));
    connect(m_renameDeployButton, SIGNAL(clicked()),
            this, SLOT(renameDeployConfiguration()));

    connect(m_target, SIGNAL(activeDeployConfigurationChanged(ProjectExplorer::DeployConfiguration*)),
            this, SLOT(activeDeployConfigurationChanged()));

    // run part
    runWidget->setContentsMargins(0, 10, 0, 25);
    m_runLayout = new QVBoxLayout(runWidget);
    m_runLayout->setMargin(0);
    m_runLayout->setSpacing(5);

    m_addRunMenu = new QMenu(m_addRunToolButton);
    m_addRunToolButton->setMenu(m_addRunMenu);
    m_runConfigurationCombo->setModel(m_runConfigurationsModel);
    m_runConfigurationCombo->setCurrentIndex(
            m_runConfigurationsModel->indexFor(m_target->activeRunConfiguration()).row());

    m_removeRunToolButton->setEnabled(m_target->runConfigurations().size() > 1);
    m_renameRunButton->setEnabled(m_target->activeRunConfiguration());

    setConfigurationWidget(m_target->activeRunConfiguration());

    connect(m_addRunMenu, SIGNAL(aboutToShow()),
            this, SLOT(aboutToShowAddMenu()));
    connect(m_runConfigurationCombo, SIGNAL(currentIndexChanged(int)),
            this, SLOT(currentRunConfigurationChanged(int)));
    connect(m_removeRunToolButton, SIGNAL(clicked(bool)),
            this, SLOT(removeRunConfiguration()));
    connect(m_renameRunButton, SIGNAL(clicked()),
            this, SLOT(renameRunConfiguration()));

    connect(m_target, SIGNAL(activeRunConfigurationChanged(ProjectExplorer::RunConfiguration*)),
            this, SLOT(activeRunConfigurationChanged()));
}
示例#17
0
void RelationshipView::configureAttributes(void)
{
	Relationship *rel=dynamic_cast<Relationship *>(this->getSourceObject());

	if(rel)
	{
		int i, count;
		Column *col=nullptr;
		QGraphicsItemGroup *attrib=nullptr;
		QGraphicsLineItem *lin=nullptr;
		QGraphicsEllipseItem *desc=nullptr;
		QGraphicsPolygonItem *sel_attrib=nullptr;
		QGraphicsSimpleTextItem *text=nullptr;
		QGraphicsItemGroup *item=nullptr;
		QPointF p_aux;
		QTextCharFormat fmt;
		QFont font;
		QRectF rect;
    QPolygonF pol;
    float py, px,
				factor=font_config[ParsersAttributes::GLOBAL].font().pointSizeF()/DEFAULT_FONT_SIZE;

		fmt=font_config[ParsersAttributes::ATTRIBUTE];
		font=fmt.font();
		font.setPointSizeF(font.pointSizeF() * 0.80f);

		//Configures the rectangle used as base for creation of attribute descriptor
		rect.setTopLeft(QPointF(0,0));
		rect.setSize(QSizeF(8 * factor, 8 * factor));

		//Calculates the first attribute position based upon the attribute count and descriptor size
    count=rel->getAttributeCount();
		px=descriptor->pos().x() + descriptor->boundingRect().width() + ((3 * HORIZ_SPACING) * factor);
		py=descriptor->pos().y() - (count * rect.height()/(4.0f * factor));

    for(i=0; i < count; i++)
    {
      col=rel->getAttribute(i);

			if(i >= static_cast<int>(attributes.size()))
			{
				attrib=new QGraphicsItemGroup;
				attrib->setZValue(-1);

				//Creates the line that connects the attribute to the relationship descriptor
				lin=new QGraphicsLineItem;
				lin->setZValue(-1);
				attrib->addToGroup(lin);

				//Creates the attribute descriptor
				desc=new QGraphicsEllipseItem;
				desc->setZValue(0);
				attrib->addToGroup(desc);

				//Creates the attribute text
				text=new QGraphicsSimpleTextItem;
				text->setZValue(0);
				attrib->addToGroup(text);

				sel_attrib=new QGraphicsPolygonItem;
				sel_attrib->setZValue(1);
				sel_attrib->setVisible(false);
				attrib->addToGroup(sel_attrib);

				this->addToGroup(attrib);
				attributes.push_back(attrib);
			}
			else
			{
				attrib=attributes[i];
				lin=dynamic_cast<QGraphicsLineItem *>(attrib->childItems().at(0));
				desc=dynamic_cast<QGraphicsEllipseItem *>(attrib->childItems().at(1));
				text=dynamic_cast<QGraphicsSimpleTextItem *>(attrib->childItems().at(2));
				sel_attrib=dynamic_cast<QGraphicsPolygonItem *>(attrib->childItems().at(3));
			}

			desc->setRect(rect);
			desc->setPen(BaseObjectView::getBorderStyle(ParsersAttributes::ATTRIBUTE));
			desc->setBrush(BaseObjectView::getFillStyle(ParsersAttributes::ATTRIBUTE));
			lin->setPen(BaseObjectView::getBorderStyle(ParsersAttributes::RELATIONSHIP));
			text->setBrush(fmt.foreground());
			text->setFont(font);
			sel_attrib->setPen(BaseObjectView::getBorderStyle(ParsersAttributes::OBJ_SELECTION));
			sel_attrib->setBrush(BaseObjectView::getFillStyle(ParsersAttributes::OBJ_SELECTION));

			attrib->setPos(px, py);

      text->setText(/*Utf8String::create(*/col->getName());
			text->setPos(QPointF(desc->pos().x() + desc->boundingRect().width() + (HORIZ_SPACING * factor), 0));
			desc->setPos(0, VERT_SPACING * factor);

			pol.clear();
			pol.append(text->boundingRect().topLeft());
			pol.append(text->boundingRect().topRight()  + QPointF(desc->boundingRect().width() + (HORIZ_SPACING * factor), 0));
			pol.append(text->boundingRect().bottomRight() + QPointF(desc->boundingRect().width() + (HORIZ_SPACING * factor), 0));
			pol.append(text->boundingRect().bottomLeft());
			sel_attrib->setPolygon(pol);

			p_aux=this->mapToItem(attrib, descriptor->pos().x() + (descriptor->boundingRect().width()/2.0f),
														descriptor->pos().y() + (descriptor->boundingRect().height()/2.0f));
			lin->setLine(QLineF(p_aux, desc->boundingRect().center()));

			py+=desc->boundingRect().height() + (2 * VERT_SPACING);
		}

		i=attributes.size()-1;
		while(i > count-1)
		{
			item=attributes.back();
			attributes.pop_back();
			this->removeFromGroup(item);
			delete(item);
			i--;
		}
	}
}
示例#18
0
/*!
 * \brief TextAnnotation::drawTextAnnotaion
 * Draws the Text annotation
 * \param painter
 */
void TextAnnotation::drawTextAnnotaion(QPainter *painter)
{
  applyLinePattern(painter);
  /* Don't apply the fill patterns on Text shapes. */
  /*applyFillPattern(painter);*/
  // first we invert the painter since we have our coordinate system inverted.
  painter->scale(1.0, -1.0);
  painter->translate(0, ((-boundingRect().top()) - boundingRect().bottom()));
  mTextString = StringHandler::removeFirstLastQuotes(mTextString);
  mTextString = StringHandler::unparse(QString("\"").append(mTextString).append("\""));
  QFont font;
  if (mFontSize > 0) {
    font = QFont(mFontName, mFontSize, StringHandler::getFontWeight(mTextStyles), StringHandler::getFontItalic(mTextStyles));
    // set font underline
    if(StringHandler::getFontUnderline(mTextStyles)) {
      font.setUnderline(true);
    }
    font.setPointSizeF(mFontSize/4);
    painter->setFont(font);
  } else {
    font = QFont(mFontName, mFontSize, StringHandler::getFontWeight(mTextStyles), StringHandler::getFontItalic(mTextStyles));
    // set font underline
    if(StringHandler::getFontUnderline(mTextStyles)) {
      font.setUnderline(true);
    }
    painter->setFont(font);
    QRect fontBoundRect = painter->fontMetrics().boundingRect(boundingRect().toRect(), Qt::TextDontClip, mTextString);
    float xFactor = boundingRect().width() / fontBoundRect.width();
    float yFactor = boundingRect().height() / fontBoundRect.height();
    float factor = xFactor < yFactor ? xFactor : yFactor;
    QFont f = painter->font();
    qreal fontSizeFactor = f.pointSizeF()*factor;
    if ((fontSizeFactor < 12) && mpComponent) {
      f.setPointSizeF(12);
    } else if (fontSizeFactor <= 0) {
      f.setPointSizeF(1);
    } else {
      f.setPointSizeF(fontSizeFactor);
    }
    painter->setFont(f);
  }
  if (mpComponent) {
    Component *pComponent = mpComponent->getRootParentComponent();
    if (pComponent && pComponent->getTransformation()) {
      QPointF extent1 = pComponent->getTransformation()->getExtent1();
      QPointF extent2 = pComponent->getTransformation()->getExtent2();
      qreal dy = ((-boundingRect().top()) - boundingRect().bottom());
      // if horizontal flip
      if (extent2.x() < extent1.x()) {
        painter->scale(-1.0, 1.0);
      }
      // if vertical flip
      if (extent2.y() < extent1.y()) {
        painter->scale(1.0, -1.0);
        painter->translate(0, dy);
      }
      qreal angle = StringHandler::getNormalizedAngle(pComponent->getTransformation()->getRotateAngle());
      if (angle == 180) {
        painter->scale(-1.0, -1.0);
        painter->translate(0, dy);
      }
    }
  } else {
    qreal angle = StringHandler::getNormalizedAngle(mpTransformation->getRotateAngle());
    if (angle == 180) {
      painter->scale(-1.0, -1.0);
      painter->translate(((-boundingRect().left()) - boundingRect().right()), ((-boundingRect().top()) - boundingRect().bottom()));
    }
  }
  // draw the font
  if (mpComponent) {
    painter->drawText(boundingRect(), StringHandler::getTextAlignment(mHorizontalAlignment) | Qt::AlignVCenter | Qt::TextDontClip, mTextString);
  } else if (boundingRect().width() > 0 && boundingRect().height() > 0) {
    painter->drawText(boundingRect(), StringHandler::getTextAlignment(mHorizontalAlignment) | Qt::AlignVCenter | Qt::TextDontClip, mTextString);
  }
}
示例#19
0
void BaseObjectView::loadObjectsStyle(void)
{
	QColor *colors=nullptr;
	QTextCharFormat font_fmt;
	QFont font;
	attribs_map attribs;
	map<QString, QTextCharFormat>::iterator itr;
	QStringList list;
	QString elem,
			config_file=GlobalAttributes::CONFIGURATIONS_DIR + GlobalAttributes::DIR_SEPARATOR +
									GlobalAttributes::OBJECTS_STYLE_CONF + GlobalAttributes::CONFIGURATION_EXT;

	try
	{
		XMLParser::restartParser();
		XMLParser::setDTDFile(GlobalAttributes::CONFIGURATIONS_DIR +
													GlobalAttributes::DIR_SEPARATOR +
													GlobalAttributes::OBJECT_DTD_DIR +
													GlobalAttributes::DIR_SEPARATOR +
													GlobalAttributes::OBJECTS_STYLE_CONF +
													GlobalAttributes::OBJECT_DTD_EXT, GlobalAttributes::OBJECTS_STYLE_CONF);
		XMLParser::loadXMLFile(config_file);

		if(XMLParser::accessElement(XMLParser::CHILD_ELEMENT))
		{
			do
			{
				if(XMLParser::getElementType()==XML_ELEMENT_NODE)
				{
					XMLParser::getElementAttributes(attribs);
					elem=XMLParser::getElementName();

					if(elem==ParsersAttributes::GLOBAL)
					{
						font.setFamily(attribs[ParsersAttributes::FONT]);
						font.setPointSizeF(attribs[ParsersAttributes::SIZE].toFloat());
						font.setBold(attribs[ParsersAttributes::BOLD]==ParsersAttributes::_TRUE_);
						font.setItalic(attribs[ParsersAttributes::ITALIC]==ParsersAttributes::_TRUE_);
						font.setUnderline(attribs[ParsersAttributes::UNDERLINE]==ParsersAttributes::_TRUE_);
						font_fmt.setFont(font);
						font_config[ParsersAttributes::GLOBAL]=font_fmt;
					}
					else if(elem==ParsersAttributes::FONT)
					{
						font_config[attribs[ParsersAttributes::ID]]=font_fmt;
						itr=font_config.find(attribs[ParsersAttributes::ID]);
						font=font_fmt.font();
						font.setBold(attribs[ParsersAttributes::BOLD]==ParsersAttributes::_TRUE_);
						font.setItalic(attribs[ParsersAttributes::ITALIC]==ParsersAttributes::_TRUE_);
						font.setUnderline(attribs[ParsersAttributes::UNDERLINE]==ParsersAttributes::_TRUE_);
						(itr->second).setFont(font);
						(itr->second).setForeground(QColor(attribs[ParsersAttributes::COLOR]));
					}
					else if(elem==ParsersAttributes::OBJECT)
					{
						list=attribs[ParsersAttributes::FILL_COLOR].split(",");
						colors=new QColor[3];
						colors[0]=(!list.isEmpty() ? QColor(list[0]) : QColor(0,0,0));
						colors[1]=(list.size()==2 ? QColor(list[1]) : colors[0]);
						colors[2]=QColor(attribs[ParsersAttributes::BORDER_COLOR]);
						color_config[attribs[ParsersAttributes::ID]]=colors;
					}
				}
			}
			while(XMLParser::accessElement(XMLParser::NEXT_ELEMENT));
		}
	}
	catch(Exception &e)
	{
		throw Exception(e.getErrorMessage(), e.getErrorType(), __PRETTY_FUNCTION__, __FILE__, __LINE__, &e);
	}
}
void TravelStageListDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option,
                              const QModelIndex &index) const {
    QStyledItemDelegate::paint(painter, option, index);

    TravelStage *e = qVariantValue<TravelStage *>(index.data());

    QFont font = option.font;
    QRect rect = option.rect;
    QSize iconSize(48, 48);
    if(dialog->portraitMode()) {
        rect.adjust(2, 2, -10, -2);
    } else {
        rect.adjust(2, 2, -10, -5);
    }
    QPoint iconPosition = rect.topLeft();
    iconPosition.setY(iconPosition.y() + 5);

    rect.adjust(60, 0, 0, 0);

    painter->save();

    int maxLabelLength;
    if (dialog->portraitMode()) {
        maxLabelLength = 24;
    } else {
        maxLabelLength = 40;
    }

    QString lineAndDestination;
    if(e->transportation == "Walking") {
        lineAndDestination = tr("Walking");
    } else {
        QString lineDestination;
        if(e->destination.length() > maxLabelLength) {
            lineDestination = e->destination.left(maxLabelLength - 2) + "...";
        } else {
            lineDestination = e->destination;
        }
        lineAndDestination = e->lineName + " " + lineDestination;
    }
    QString departureStopPlaceName;
    if(e->departureStop.placeName.length() > maxLabelLength) {
        departureStopPlaceName = e->departureStop.placeName.left(maxLabelLength - 2) + "...";
    } else {
        departureStopPlaceName = e->departureStop.placeName;
    }
    QString arrivalStopPlaceName;
    if(e->arrivalStop.placeName.length() > maxLabelLength) {
        arrivalStopPlaceName = e->arrivalStop.placeName.left(maxLabelLength - 2) + "...";
    } else {
        arrivalStopPlaceName = e->arrivalStop.placeName;
    }

    int minutes = (int)((double)e->departureTime.secsTo(e->arrivalTime) / 60.0);

    if(dialog->portraitMode()) {

        font.setPointSizeF(font.pointSizeF() * 0.70);
        painter->setFont(font);

        painter->drawText(rect, Qt::AlignTop | Qt::AlignLeft, lineAndDestination);
        painter->drawText(rect, Qt::AlignTop | Qt::AlignRight, tr("%n min", "", minutes));
        painter->setPen(option.palette.mid().color());
        painter->drawText(rect, Qt::AlignVCenter | Qt::AlignLeft, departureStopPlaceName + " " + e->departureTime.toString("hh:mm"));
        painter->drawText(rect, Qt::AlignBottom | Qt::AlignLeft, arrivalStopPlaceName + " " + e->arrivalTime.toString("hh:mm"));
    } else {
        painter->drawText(rect, Qt::AlignTop | Qt::AlignLeft, lineAndDestination);
        painter->drawText(rect, Qt::AlignTop | Qt::AlignRight, departureStopPlaceName + " " + e->departureTime.toString("hh:mm"));

        painter->setPen(option.palette.mid().color());
        font.setPointSizeF(font.pointSizeF() * 0.70);
        painter->setFont(font);

        painter->drawText(rect, Qt::AlignBottom | Qt::AlignRight, arrivalStopPlaceName + " " + e->arrivalTime.toString("hh:mm"));
        painter->drawText(rect, Qt::AlignBottom | Qt::AlignLeft, tr("%n min", "", minutes));
    }

    if(e->transportation == "Bus" || e->transportation == "AirportBus") {
        QImage icon = QImage(":/images/bus.png").scaled(iconSize);
        painter->drawImage(iconPosition, icon);
    } else if(e->transportation == "Tram") {
        QImage icon = QImage(":/images/tram.png").scaled(iconSize);
        painter->drawImage(iconPosition, icon);
    } else if(e->transportation == "Metro") {
        QImage icon = QImage(":/images/tbane.png").scaled(iconSize);
        painter->drawImage(iconPosition, icon);
    } else if(e->transportation == "Train" || e->transportation == "AirportTrain") {
        QImage icon = QImage(":/images/train.png").scaled(iconSize);
        painter->drawImage(iconPosition, icon);
    }
    painter->restore();
}
示例#21
0
void Font::Create(const FontParameters &fp)
{
    Release();

    QFont *f = new QFont();

    QFont::StyleStrategy strategy;

    switch (fp.extraFontFlag & SC_EFF_QUALITY_MASK)
    {
    case SC_EFF_QUALITY_NON_ANTIALIASED:
        strategy = QFont::NoAntialias;
        break;

    case SC_EFF_QUALITY_ANTIALIASED:
        strategy = QFont::PreferAntialias;
        break;

    default:
        strategy = QFont::PreferDefault;
    }

#if defined(Q_OS_MAC)
#if QT_VERSION >= 0x040700
    strategy = static_cast<QFont::StyleStrategy>(strategy | QFont::ForceIntegerMetrics);
#else
#warning "Correct handling of QFont metrics requires Qt v4.7.0 or later"
#endif
#endif

    f->setStyleStrategy(strategy);

    // If name of the font begins with a '-', assume, that it is an XLFD.
    if (fp.faceName[0] == '-')
    {
        f->setRawName(fp.faceName);
    }
    else
    {
        f->setFamily(fp.faceName);
        f->setPointSizeF(fp.size);

        // See if the Qt weight has been passed via the back door.   Otherwise
        // map Scintilla weights to Qt weights ensuring that the SC_WEIGHT_*
        // values get mapped to the correct QFont::Weight values.
        int qt_weight;

        if (fp.weight < 0)
            qt_weight = -fp.weight;
        else if (fp.weight <= 200)
            qt_weight = QFont::Light;
        else if (fp.weight <= QsciScintillaBase::SC_WEIGHT_NORMAL)
            qt_weight = QFont::Normal;
        else if (fp.weight <= 600)
            qt_weight = QFont::DemiBold;
        else if (fp.weight <= 850)
            qt_weight = QFont::Bold;
        else
            qt_weight = QFont::Black;

        f->setWeight(qt_weight);

        f->setItalic(fp.italic);
    }

    fid = f;
}
示例#22
0
void renderGraph(QPainter & paint, const QRect & rect, ORGraphData & gData, XSqlQuery * query, const QMap<QString, QColor> & _colorMap) {
    int dpi = paint.device()->logicalDpiX();

    QFont fnt;

    tGraph graph(rect);
    fnt = gData.font;
    fnt.setPointSizeF((100.0/dpi)*fnt.pointSize());
    graph.setFont(fnt);
    if(gData.title.string.length() > 0) {
        graph.setTitle(gData.title.string);
        if(gData.title.font_defined) {
            fnt = gData.title.font;
            fnt.setPointSizeF((100.0/dpi)*fnt.pointSize());
            graph.setTitleFont(&fnt);
        }
    }

    QString lbl_clmn = gData.dataaxis.column;
    if(lbl_clmn.length() > 0 && gData.dataaxis.font_defined) {
        fnt = gData.dataaxis.font;
        fnt.setPointSizeF((100.0/dpi)*fnt.pointSize());
        graph.setDataFont(&fnt);
    }
    if(gData.dataaxis.title.string.length() > 0) {
        graph.setDataLabel(gData.dataaxis.title.string);
        if(gData.dataaxis.title.font_defined) {
            fnt = gData.dataaxis.title.font;
            fnt.setPointSizeF((100.0/dpi)*fnt.pointSize());
            graph.setDataLabelFont(&fnt);
        }
    }

    graph.setAutoMinMax(gData.valueaxis.autominmax);
    graph.setMinValue(gData.valueaxis.min);
    graph.setMaxValue(gData.valueaxis.max);
    if(gData.valueaxis.font_defined) {
        fnt = gData.valueaxis.font;
        fnt.setPointSizeF((100.0/dpi)*fnt.pointSize());
        graph.setValueFont(&fnt);
    }
    if(gData.valueaxis.title.string.length() > 0) {
        graph.setValueLabel(gData.valueaxis.title.string);
        if(gData.valueaxis.title.font_defined) {
            fnt = gData.valueaxis.title.font;
            fnt.setPointSizeF((100.0/dpi)*fnt.pointSize());
            graph.setValueLabelFont(&fnt);
        }
    }

    // setup the sets/series
    int snum = 0;
    ORSeriesData * sd = 0;
    for(snum = 0; snum < gData.series.count(); snum++) {
        sd = gData.series.at(snum);
        if(sd) {
            graph.setSetColor(snum, _colorMap[sd->color]);
            graph.setSetStyle(snum, sd->style);
        }
    }

    // populate the data
    if(query->first()) {
        do {
            if(lbl_clmn.length() > 0) {
                graph.setReferenceLabel(query->at(), query->value(lbl_clmn).toString());
            }
            for(snum = 0; snum < gData.series.count(); snum++) {
                sd = gData.series.at(snum);
                if(sd) {
                    graph.setSetValue(query->at(), snum, query->value(sd->column).toDouble());
                }
            }
        } while(query->next());
    }

    // draw the graph
    graph.draw(paint);
}
示例#23
0
void QFontProto::setPointSizeF(qreal pointSize)
{
  QFont *item = qscriptvalue_cast<QFont*>(thisObject());
  if (item)
    item->setPointSizeF(pointSize);
}
示例#24
0
void
Style::readSettings(QString appName)
{
    QSettings *iSettings = new QSettings("BE", "Style");
    iSettings->beginGroup("Current");
    //BEGIN read some user personal settings (i.e. not preset related)
    config.leftHanded = readBool(LEFTHANDED) ? Qt::RightToLeft : Qt::LeftToRight;
    // item single vs. double click, wizard appereance
    config.macStyle = readBool(MACSTYLE);
    config.dialogBtnLayout = readInt(DIALOG_BTN_LAYOUT);
    config.fadeInactive = readBool(FADE_INACTIVE);
    // Hacks ==================================
    Hacks::config.windowMovement = readBool(HACK_WINDOWMOVE);
    Hacks::config.fixGwenview = readBool(HACK_FIX_GWENVIEW);
    Hacks::config.lockToolBars = readBool(HACK_TOOLBAR_LOCKING);
    Hacks::config.lockDocks = readBool(HACK_DOCK_LOCKING);
    Hacks::config.panning = readBool(HACK_PANNING);
    Hacks::config.suspendFullscreenPlayers = readBool(HACK_SUSPEND_FULLSCREEN_PLAYERS);
    if (Hacks::config.suspendFullscreenPlayers)
        Hacks::config.suspendFullscreenPlayers = (  appName == "dragonplayer" || appName == "smplayer" ||
                                                    appName == "minitube" || appName == "vlc"  );
    Hacks::config.titleWidgets = readBool(HACK_TITLE_WIDGET);
    Hacks::config.suppressBrightnessOSD = readBool(HACK_BRIGHTNESS_OSD);

    // Font fixing offsets
    config.fontOffset[0] = fontOffset(false, &config.fontExtent);
    config.fontExtent = iSettings->value( "FontExtent", config.fontExtent ).toInt();
    config.fontOffset[1] = fontOffset(true);
    QStringList lst = iSettings->value( "FontOffset", QStringList() ).toStringList();
    if ( lst.count() > 0 )
    {
        config.fontOffset[0] = lst.at(0).toInt();
        if ( lst.count() > 1 )
            config.fontOffset[1] = lst.at(1).toInt();
        else
            config.fontOffset[1] = config.fontOffset[0];
    }

    // PW Echo Char ===========================
    config.input.pwEchoChar = ushort(iSettings->value(INPUT_PWECHOCHAR).toUInt());

    config.menu.delay = readInt(MENU_DELAY);
    const bool menuIconsVis = readBool(MENU_SHOWICONS);
    // allow (K)Application to manipulate this first
    QMetaObject::invokeMethod(this, "setMenuIconsVisible", Qt::QueuedConnection, Q_ARG(bool, menuIconsVis));
    config.menu.indent = readBool(MENU_INDENT);

    config.winBtnStyle = 2; // this is a kwin deco setting, TODO: read from there?

    Animator::Tab::setTransition((Animator::Transition) readInt(TAB_TRANSITION));
    Animator::Tab::setDuration(clamp(iSettings->value(TAB_DURATION).toUInt(), 150, 4000));
    //END personal settings
    //NOTICE we do not end group here, but below. this way it's open if we don't make use of presets

    // Background ===========================
    config.invert.docks = readBool(INVERT_DOCKS);
    config.invert.headers = readBool(INVERT_HEADERS);
    config.invert.menubars = readBool(INVERT_MENUBARS);
    config.invert.menus = readBool(INVERT_MENUS);
    config.invert.modals = (appType != KDM) && readBool(INVERT_MODALS);
    config.invert.titlebars = readBool(INVERT_TITLEBARS);
    config.invert.toolbars = readBool(INVERT_TOOLBARS);

    config.bg.opacity = readInt(BG_OPACITY);
    config.bg.modal.opacity = readInt(BG_MODAL_OPACITY);
    if (config.bg.opacity || config.bg.modal.opacity)
        config.bg.blur = readBool(BG_BLUR);
    else
        config.bg.blur = false;

    config.bg.ringOverlay = readInt(BG_RING_OVERLAY);


    // Buttons ===========================
    config.btn.minHeight = readInt(BTN_MIN_HEIGHT);

    // .Tool
    config.btn.tool.disabledStyle = readInt(BTN_DISABLED_TOOLS);

    //--------
    config.slider.buttons = readBool(SLIDER_BUTTONS);

    if (readBool(SHOW_MNEMONIC))
        config.mnemonic = Qt::TextShowMnemonic;
    else
        config.mnemonic = Qt::TextHideMnemonic;

    // Tabs ===========================
    Animator::Tab::setFPS(25);

    // General ===========================
    QWidget dummy;  // calling out to qApp->desktopWidget() would seem natural
                    // BUT BREAKS THE CLIPBOARD!
    config.scale = (dummy.logicalDpiX() + dummy.logicalDpiY()) /  170.0f;
    QFont fnt = qApp->font();
    if (fnt.pointSizeF() > -1)
        config.scale *= fnt.pointSizeF()/10.0f;
    if (const char *scale = getenv("VIRTUALITY_SCALE")) {
        bool ok = false;
        const float envScale = QString(scale).toFloat(&ok); // CLAMP(envScale, 1.0f, 3.0f);
        if (ok) {
            if (envScale != config.scale) {
                scale = getenv("VIRTUALITY_SCALE_FONT");
                if (!qstrcmp(scale, "true")) {
                    if (fnt.pointSize() > -1)
                        fnt.setPointSizeF(fnt.pointSizeF()*envScale/config.scale);
                    else
                        fnt.setPixelSize(fnt.pixelSize()*envScale/config.scale);
                    qApp->setFont(fnt);
                }
            }
            config.scale = envScale;
        }
    }

    config.frame.roundness = SCALE(readInt(ROUNDNESS));
//     config.strokeWidth = qMin(config.frame.roundness, SCALE(readInt(STROKE_WIDTH)));
    config.strokeWidth = SCALE(readInt(STROKE_WIDTH));
    halfStroke = 0.5*config.strokeWidth;

    //NOTICE gtk-qt fails on several features
    // a key problem seems to be fixed text colors
    // also it will segfault if we hide scrollbar buttons
    // so we adjust some settings here
    if (appType == GTK || appType == OpenOffice)
    {
        config.bg.modal.opacity = 255;
        config.invert.docks = config.invert.menubars = config.invert.menus = config.invert.modals =
        config.invert.toolbars = config.invert.headers = false;
    }

    delete iSettings;

}
示例#25
0
qreal PdfElementText::paint(QPainter *painter) {
	qreal width = toQReal(_attributes.value("stroke", "2"));
	QString strokeColor = _attributes.value("strokecolor", "black");
	QString fillColor = _attributes.value("fillcolor", "");
	QString valign = _attributes.value("valign", "justify");
	QString halign = _attributes.value("halign", "top");
	QString fontfamily = _attributes.value("font", "Aller light");
	QString weight = _attributes.value("weight", "normal");
	qreal size = _attributes.value("size", "12").toFloat();
	bool italic = _attributes.value("italic", "false").toLower() == "true";
	bool underline = _attributes.value("underline", "false").toLower() == "true";
	bool wordwrap = _attributes.value("wordwrap", "true").toLower() == "true";
	qreal x = toQReal(_attributes.value("x", "0"));
	qreal y = toQReal(_attributes.value("y", "0")) + _offsetY;
	qreal w = toQReal(_attributes.value("width", "0"));
	qreal h = toQReal(_attributes.value("height", "0"));
	qreal s = toQReal(_attributes.value("spacing", "0"));

	if (w > 0 && h > 0) {
		QFont font = QApplication::font();
		font.setFamily(fontfamily);
		if (weight == "light") {
			font.setWeight(QFont::Light);
		} else if (weight == "normal") {
			font.setWeight(QFont::Normal);
		} else if (weight == "demibold") {
			font.setWeight(QFont::DemiBold);
		} else if (weight == "bold") {
			font.setWeight(QFont::Bold);
		} else if (weight == "black") {
			font.setWeight(QFont::Black);
		} else {
			font.setWeight(QFont::Normal);
		}
		font.setItalic(italic);
		font.setUnderline(underline);
		font.setPointSizeF(size);

		QPen pen(Qt::black, width, Qt::SolidLine, Qt::SquareCap, Qt::BevelJoin);
		painter->setPen(pen);
		painter->setBrush(Qt::black);
		painter->setFont(font);

		int flags = Qt::TextDontClip;
		if (halign == "left") flags |= Qt::AlignLeft;
		else if (halign == "right") flags |= Qt::AlignRight;
		else if (halign == "justify") flags |= Qt::AlignJustify;
		else if (halign == "center") flags |= Qt::AlignHCenter;

		if (valign == "top") flags |= Qt::AlignTop;
		else if (valign == "bottom") flags |= Qt::AlignBottom;
		else if (valign == "center") flags |= Qt::AlignVCenter;

		if (wordwrap) flags |= Qt::TextWordWrap;

		// Replace repeating variables and static ones after
		QString cdata = _attributes.value("cdata", "");
		QHash<QString, QString>::const_iterator it;
		if (_repeating != 0) {
			for (it = _repeating->constBegin(); it != _repeating->constEnd(); it++) {
				cdata.replace(QString("{%1}").arg(it.key()), it.value(), Qt::CaseInsensitive);
			}
		}
		if (_variables != 0) {
			for (it = _variables->constBegin(); it != _variables->constEnd(); it++) {
				// #14 Variables can occure in expressions and show different content in different situations
				evalExpression(&cdata, it.key(), it.value());

				// Replace variables with it's value
				cdata.replace(QString("{%1}").arg(it.key()), it.value(), Qt::CaseInsensitive);
			}
		}

		// split into different paragraphs
		QStringList paragraphs = cdata.split(QRegExp("(\r|\n)"), QString::SkipEmptyParts);

		// paint the text
		QRectF *bounding = new QRectF;
		QRectF rect = QRectF(QPointF(x, y), QSizeF(w, h));
		for (int i = 0; i < paragraphs.size(); i++) {
			painter->drawText(rect, flags, paragraphs.at(i).trimmed(), bounding);
			rect.adjust(0, bounding->height() + s, 0, 0);
		}
	}
	return bottom();
}
示例#26
0
void population::draw(QPainter *painter, float GLscale, float viewX, float viewY, int width, int height, QImage image, drawStyle style)
{
    float scale = GLscale/200.0;

    this->setupTrans(GLscale, viewX, viewY, width, height);

    if (this->isSpikeSource) {
        style = spikeSourceDrawStyle;
    }

    switch (style) {
    case microcircuitDrawStyle:
    {
        // draw circle
        QPen oldPen = painter->pen();
        QPen pen = painter->pen();
        pen.setWidthF((pen.widthF()+1.0)*2*scale);
        painter->setPen(pen);
        painter->drawEllipse(transformPoint(QPointF(this->x, this->y)),0.5*GLscale/2.0,0.5*GLscale/2.0);
        painter->setPen(oldPen);
        QFont oldFont = painter->font();
        QFont font = painter->font();
        font.setPointSizeF(GLscale/10.0);
        painter->setFont(font);
        // print label
        QStringList text = this->name.split(" ");
        if (text.size()>0) {
            QString title = text.at(0);
            if (title.size() > 5)
                title.resize(5);
            painter->drawText(QRectF(transformPoint(QPointF(this->x-0.5, this->y-0.2)),transformPoint(QPointF(this->x+0.5, this->y+0.2))), Qt::AlignCenter, title);
            painter->setFont(oldFont);
        }
        return;
    }
    case layersDrawStyle:
    {
        return;
    }
    case spikeSourceDrawStyle:
    {
        // draw circle
        QPen oldPen = painter->pen();
        QPen pen = painter->pen();
        pen.setWidthF((pen.widthF()+1.0));//*GLscale/100.0
        pen.setColor(QColor(200,200,200,0));
        painter->setPen(pen);
        QBrush brush;
        brush.setStyle(Qt::SolidPattern);
        QColor col(this->colour);
        col.setAlpha(100);
        brush.setColor(col);
        QBrush oldBrush = painter->brush();
        painter->setBrush(brush);
        painter->drawEllipse(transformPoint(QPointF(this->x, this->y)),0.5*GLscale/2.0,0.5*GLscale/2.0);
        QFont oldFont = painter->font();
        QFont font = painter->font();
        font.setPointSizeF(GLscale/10.0);
        painter->setFont(font);
        // print label
        pen.setColor(QColor(0,0,0,255));
        painter->setPen(pen);
        //painter->drawText(QRectF(transformPoint(QPointF(this->x-0.5, this->y-0.2)),transformPoint(QPointF(this->x+0.5, this->y+0.2))), Qt::AlignCenter, "SS");
        painter->setFont(oldFont);
        painter->setBrush(oldBrush);
        painter->setPen(oldPen);
        QImage ssimage(":/images/ssBig.png");
        QRectF imRect(transformPoint(QPointF(this->x, this->y))-QPointF(0.4*GLscale/2.0,0.4*GLscale/2.0),QSizeF(0.4*GLscale,0.4*GLscale));
        painter->drawImage(imRect, ssimage);
        return;
        break;
    }
    case standardDrawStyle:
    case standardDrawStyleExcitatory:
    case saveNetworkImageDrawStyle:
    default:
        // do nothing here, break out into the code below.
        break;
    }

    // transform the co-ordinates manually (using the qt transformation leads to blurry fonts!)
    float left = ((this->left+viewX)*GLscale+float(width))/2;
    float right = ((this->right+viewX)*GLscale+float(width))/2;
    float top = ((-this->top+viewY)*GLscale+float(height))/2;
    float bottom = ((-this->bottom+viewY)*GLscale+float(height))/2;

    QRectF rectangle(left, top, right-left, bottom-top);

    QRectF rectangleInner(left+2*scale, top+2*scale, right-left-8*scale, bottom-top-4*scale);

    QColor col(this->colour);
    col.setAlpha(100);
    QPainterPath path;
    path.addRoundedRect(rectangle,0.05*GLscale,0.05*GLscale);

    painter->fillPath(path, col);

    painter->drawImage(rectangle, image);

    // Draw a dark grey border around the population
    painter->setPen(QColor(200,200,200,255));
    painter->drawRoundedRect(rectangle,0.05*GLscale,0.05*GLscale);
    painter->setPen(QColor(0,0,0,255));

    QString displayed_name = this->name;

    if (displayed_name.size() > 13) {
        displayed_name.resize(10);
        displayed_name = displayed_name + "...";
    }

    QString displayed_comp_name = this->neuronType->component->name;

    if (displayed_comp_name.size() > 14) {
        displayed_comp_name.resize(11);
        displayed_comp_name = displayed_comp_name + "...";
    }

    QFont oldFont = painter->font();
    QFont font = painter->font();

    QString text = displayed_name + "\n" + QString::number(this->numNeurons);// + "\n" + displayed_comp_name;
    font.setPointSizeF(1.5*GLscale/20.0);
    painter->setFont(font);
    painter->drawText(rectangleInner, Qt::AlignRight|Qt::AlignTop, text);

    font.setPointSizeF(1.3*GLscale/20.0);
    painter->setFont(font);
    painter->setPen(QColor(60,60,60,255));
    painter->drawText(rectangleInner, Qt::AlignRight|Qt::AlignBottom, displayed_comp_name);

    painter->setFont(oldFont);
}
示例#27
0
SyntaxEditorWindow::SyntaxEditorWindow(const QSharedPointer<SyntaxList> &syntaxList, const QString &syntaxName,
		const QString &category, const QString &syntaxHint, QWidget *parent) :
		QWidget(parent), syntaxList(syntaxList), syntaxName(syntaxName)
{
	setWindowRole("kadu-syntax-editor");

	setWindowTitle(tr("Kadu syntax editor"));
	setAttribute(Qt::WA_DeleteOnClose);

	QVBoxLayout *layout = new QVBoxLayout(this);

	QSplitter *splitter = new QSplitter(this);
	layout->addWidget(splitter);
	splitter->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
	splitter->setChildrenCollapsible(false);

	QWidget *splitterleft = new QWidget(splitter);
	QVBoxLayout *splitterleftlayout = new QVBoxLayout(splitterleft);
	splitterleftlayout->setMargin(0);
	splitterleftlayout->setSpacing(5);

	editor = new QTextEdit(this);
	splitterleftlayout->addWidget(editor);
	editor->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
	editor->setAcceptRichText(true);
	editor->setPlainText(syntaxList->readSyntax(syntaxName));
	QFont font = this->font();
	font.setFamily("monospace");
	if(font.pixelSize() == -1)
		font.setPointSizeF(font.pointSizeF() - 0.5);
	else
		font.setPixelSize(font.pixelSize() - 2);
	editor->setFont(font);
	editor->setMinimumSize(EDITOR_MINIMUM_SIZE);

	if (!syntaxHint.isEmpty())
	{
		QLabel *editorhint = new QLabel(this);
		splitterleftlayout->addWidget(editorhint);
		editorhint->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Minimum);
		editorhint->setWordWrap(true);
		editorhint->setText(syntaxHint);
	}

	QWidget *splitterright = new QWidget(splitter);
	QVBoxLayout *splitterrightlayout = new QVBoxLayout(splitterright);
	splitterrightlayout->setMargin(0);
	splitterrightlayout->setSpacing(5);

	previewPanel = new Preview(this);
	splitterrightlayout->addWidget(previewPanel);
	previewPanel->setMinimumHeight(0);
	previewPanel->setMaximumHeight(QWIDGETSIZE_MAX);
	previewPanel->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding);
	previewPanel->setResetBackgroundColor(config_file.readEntry("Look", category + "BgColor"));
	previewPanel->setMinimumSize(PREVIEW_MINIMUM_SIZE);

	QPushButton *previewbutton = new QPushButton(qApp->style()->standardIcon(QStyle::SP_BrowserReload), tr("Refresh Preview"), this);
	splitterrightlayout->addWidget(previewbutton);
	connect(previewbutton, SIGNAL(clicked()), this, SLOT(refreshPreview()));

	QDialogButtonBox *buttonslayout = new QDialogButtonBox(Qt::Horizontal, this);
	layout->addWidget(buttonslayout);
	QPushButton *saveSyntax = new QPushButton(qApp->style()->standardIcon(QStyle::SP_DialogOkButton), tr("Save"), this);
	QPushButton *saveAsSyntax = new QPushButton(qApp->style()->standardIcon(QStyle::SP_DialogSaveButton), tr("Save as..."), this);
	QPushButton *cancel = new QPushButton(qApp->style()->standardIcon(QStyle::SP_DialogCancelButton), tr("Cancel"), this);
	buttonslayout->addButton(saveSyntax, QDialogButtonBox::YesRole);
	buttonslayout->addButton(saveAsSyntax, QDialogButtonBox::ActionRole);
	buttonslayout->addButton(cancel, QDialogButtonBox::RejectRole);

	splitter->setSizes( QList<int>() << splitter->sizeHint().width() << 1 );

	if (syntaxList->isGlobal(syntaxName))
		saveSyntax->setDisabled(true);
	else
		connect(saveSyntax, SIGNAL(clicked()), this, SLOT(save()));
	connect(saveAsSyntax, SIGNAL(clicked()), this, SLOT(saveAs()));
	connect(cancel, SIGNAL(clicked()), this, SLOT(close()));

	loadWindowGeometry(this, "Look", "SyntaxEditorGeometry", 0, 50, 790, 480);
}
示例#28
0
void PreferencesDialog::loadSettings()
{
    // This code was on the mainwindow, it should belong nowhere, but since we dind't
    // correctly fixed this code yet ( too much stuff on the code calling preferences )
    // force this here.

    QSettings s;
    QVariant v;
    s.beginGroup("Units");
    if (s.value("unit_system").toString() == "metric") {
        prefs.unit_system = METRIC;
        prefs.units = SI_units;
    } else if (s.value("unit_system").toString() == "imperial") {
        prefs.unit_system = IMPERIAL;
        prefs.units = IMPERIAL_units;
    } else {
        prefs.unit_system = PERSONALIZE;
        GET_UNIT("length", length, units::FEET, units::METERS);
        GET_UNIT("pressure", pressure, units::PSI, units::BAR);
        GET_UNIT("volume", volume, units::CUFT, units::LITER);
        GET_UNIT("temperature", temperature, units::FAHRENHEIT, units::CELSIUS);
        GET_UNIT("weight", weight, units::LBS, units::KG);
    }
    GET_UNIT("vertical_speed_time", vertical_speed_time, units::MINUTES, units::SECONDS);
    s.endGroup();
    s.beginGroup("TecDetails");
    GET_BOOL("po2graph", pp_graphs.po2);
    GET_BOOL("pn2graph", pp_graphs.pn2);
    GET_BOOL("phegraph", pp_graphs.phe);
    GET_DOUBLE("po2threshold", pp_graphs.po2_threshold);
    GET_DOUBLE("pn2threshold", pp_graphs.pn2_threshold);
    GET_DOUBLE("phethreshold", pp_graphs.phe_threshold);
    GET_BOOL("mod", mod);
    GET_DOUBLE("modppO2", mod_ppO2);
    GET_BOOL("ead", ead);
    GET_BOOL("redceiling", profile_red_ceiling);
    GET_BOOL("dcceiling", profile_dc_ceiling);
    GET_BOOL("calcceiling", profile_calc_ceiling);
    GET_BOOL("calcceiling3m", calc_ceiling_3m_incr);
    GET_BOOL("calcndltts", calc_ndl_tts);
    GET_BOOL("calcalltissues", calc_all_tissues);
    GET_INT("gflow", gflow);
    GET_INT("gfhigh", gfhigh);
    GET_BOOL("gf_low_at_maxdepth", gf_low_at_maxdepth);
    GET_BOOL("zoomed_plot", zoomed_plot);
    set_gf(prefs.gflow, prefs.gfhigh, prefs.gf_low_at_maxdepth);
    GET_BOOL("show_sac", show_sac);
    GET_BOOL("display_unused_tanks", display_unused_tanks);
    s.endGroup();

    s.beginGroup("GeneralSettings");
    GET_TXT("default_filename", default_filename);
    GET_TXT("default_cylinder", default_cylinder);
    s.endGroup();

    s.beginGroup("Display");
    QFont defaultFont = s.value("divelist_font", qApp->font()).value<QFont>();
    defaultFont.setPointSizeF(s.value("font_size", qApp->font().pointSizeF()).toFloat());
    qApp->setFont(defaultFont);

    GET_TXT("divelist_font", divelist_font);
    GET_INT("font_size", font_size);
    if (prefs.font_size < 0)
        prefs.font_size = defaultFont.pointSizeF();
    GET_INT("displayinvalid", display_invalid_dives);
    s.endGroup();
}
示例#29
0
QFont QgsMapToolLabel::labelFontCurrentFeature()
{
    QFont font;
    QgsVectorLayer* vlayer = currentLayer();

    bool labelSettingsOk;
    QgsPalLayerSettings& layerSettings = currentLabelSettings( &labelSettingsOk );

    if ( labelSettingsOk && vlayer )
    {
        font = layerSettings.textFont;

        QgsFeature f;
        if ( vlayer->featureAtId( mCurrentLabelPos.featureId, f, false, true ) )
        {
            const QgsAttributeMap& attributes = f.attributeMap();
            QMap< QgsPalLayerSettings::DataDefinedProperties, int > ddProperties = layerSettings.dataDefinedProperties;

            //size
            QMap< QgsPalLayerSettings::DataDefinedProperties, int >::const_iterator sizeIt = ddProperties.find( QgsPalLayerSettings::Size );
            if ( sizeIt != ddProperties.constEnd() )
            {
                if ( layerSettings.fontSizeInMapUnits )
                {
                    font.setPixelSize( layerSettings.sizeToPixel( attributes[*sizeIt].toDouble(), QgsRenderContext() ) );
                }
                else
                {
                    font.setPointSizeF( attributes[*sizeIt].toDouble() );
                }
            }

            //family
            QMap< QgsPalLayerSettings::DataDefinedProperties, int >::const_iterator familyIt = ddProperties.find( QgsPalLayerSettings::Family );
            if ( familyIt != ddProperties.constEnd() )
            {
                font.setFamily( attributes[*sizeIt].toString() );
            }

            //underline
            QMap< QgsPalLayerSettings::DataDefinedProperties, int >::const_iterator underlineIt = ddProperties.find( QgsPalLayerSettings::Underline );
            if ( familyIt != ddProperties.constEnd() )
            {
                font.setUnderline( attributes[*underlineIt].toBool() );
            }

            //strikeout
            QMap< QgsPalLayerSettings::DataDefinedProperties, int >::const_iterator strikeoutIt = ddProperties.find( QgsPalLayerSettings::Strikeout );
            if ( strikeoutIt != ddProperties.constEnd() )
            {
                font.setStrikeOut( attributes[*strikeoutIt].toBool() );
            }

            //bold
            QMap< QgsPalLayerSettings::DataDefinedProperties, int >::const_iterator boldIt = ddProperties.find( QgsPalLayerSettings::Bold );
            if ( boldIt != ddProperties.constEnd() )
            {
                font.setBold( attributes[*boldIt].toBool() );
            }

            //italic
            QMap< QgsPalLayerSettings::DataDefinedProperties, int >::const_iterator italicIt = ddProperties.find( QgsPalLayerSettings::Italic );
            if ( italicIt != ddProperties.constEnd() )
            {
                font.setItalic( attributes[*italicIt].toBool() );
            }
        }
    }

    return font;
}
示例#30
0
MainWindow::MainWindow(QWidget *parent, Qt::WindowFlags flags)
: QMainWindow(parent,flags),
	reset_button(new QPushButton("Reset Tracking",this)),
	gui_button(new QPushButton(this)),
	show_user_button(new QCheckBox("Show User",this)),
	show_tracking_mesh_button(new QCheckBox("Show Tracking",this)),
	show_avatar_selection_button(new QPushButton(this)),
	graphics_view(new MainWindowGraphicsView(this)),
	graphics_scene(new QGraphicsScene(this)),
	tracking_health(new QProgressBar(this)),
	status_message(new QLabel("Waiting for Camera", this))
{	
	show_avatar_selection_button->setCheckable(true);
																			
	QGraphicsPixmapItem *graphics_input_item  = new QGraphicsPixmapItem();
	QGraphicsPixmapItem *graphics_avatar_item = new QGraphicsPixmapItem();
	QGraphicsTextItem   *graphics_face_out_of_bounds_user_item = new QGraphicsTextItem();
	QGraphicsTextItem   *graphics_face_out_of_bounds_avatar_item = new QGraphicsTextItem();	
	graphics_face_out_of_bounds_user_item->setPlainText("Face outside the image!");
	graphics_face_out_of_bounds_avatar_item->setPlainText("Face outside the image!");		
	{
		QFont  font;
		font.setPointSizeF(24.0);
				
		graphics_face_out_of_bounds_user_item->setFont(font);
		graphics_face_out_of_bounds_avatar_item->setFont(font);
		graphics_face_out_of_bounds_user_item->setDefaultTextColor(QColor::fromRgb(255, 0, 0));
		graphics_face_out_of_bounds_avatar_item->setDefaultTextColor(QColor::fromRgb(255, 0, 0));		
	}
	
	user_input_view = new GraphicsPixmapItemController(graphics_input_item, this);
	avatar_view     = new GraphicsPixmapItemController(graphics_avatar_item, this);
	face_out_of_bounds_warning_user = new GraphicsTextItemController(graphics_face_out_of_bounds_user_item, this);
	face_out_of_bounds_warning_avatar = new GraphicsTextItemController(graphics_face_out_of_bounds_avatar_item, this);	
	
	graphics_scene->addItem(graphics_input_item);
	graphics_scene->addItem(graphics_avatar_item);
	graphics_scene->addItem(graphics_face_out_of_bounds_user_item);
	graphics_scene->addItem(graphics_face_out_of_bounds_avatar_item);	
		
	AvatarSelection * selection = new AvatarSelection();
	avatar_selector = new AvatarSelectionItemController(selection);
	graphics_scene->addItem(selection);
	
	MeshDrawer *mesh_drawer = new MeshDrawer();
	tracking_mesh = new MeshDrawerItemController(mesh_drawer, this);
	graphics_scene->addItem(mesh_drawer);
			
	connect(graphics_scene,SIGNAL(sceneRectChanged(const QRectF &)),this,SLOT(sceneRectChanged(const QRectF &)));
	connect(selection,SIGNAL(selectionChanged(int)), SIGNAL(avatarSelectionChanged(int)));

	graphics_view->setScene(graphics_scene);
	graphics_view->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
	graphics_view->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
	graphics_view->setRenderHint(QPainter::Antialiasing);
	graphics_view->setInteractive(true);
	
	// Layout
	QVBoxLayout *vl = new QVBoxLayout();
	{
		QHBoxLayout *hl = new QHBoxLayout();
		hl->addStretch(1);
		hl->addWidget(status_message);
		hl->addStretch(1);
		
		vl->addLayout(hl,0);
	}
	{
		vl->addWidget(graphics_view,1);
	}
	{
		QHBoxLayout *hl = new QHBoxLayout();
		hl->addWidget(gui_button);
		hl->addWidget(show_avatar_selection_button);
		hl->addWidget(show_user_button);
		hl->addStretch(1);
		hl->addWidget(show_tracking_mesh_button);
		hl->addWidget(reset_button);
		hl->addWidget(tracking_health);
		vl->addLayout(hl,0);
	}

	QWidget *central_widget = new QWidget(this);
	central_widget->setLayout(vl);
	setCentralWidget(central_widget);
}