void  QQuickTextNodeEngine::addToSceneGraph(QQuickTextNode *parentNode,
                                            QQuickText::TextStyle style,
                                            const QColor &styleColor)
{
    if (m_currentLine.isValid())
        processCurrentLine();


    for (int i=0; i<m_backgrounds.size(); ++i) {
        const QRectF &rect = m_backgrounds.at(i).first;
        const QColor &color = m_backgrounds.at(i).second;

        parentNode->appendChildNode(new QSGSimpleRectNode(rect, color));
    }

    // First, prepend all selection rectangles to the tree
    for (int i=0; i<m_selectionRects.size(); ++i) {
        const QRectF &rect = m_selectionRects.at(i);

        parentNode->appendChildNode(new QSGSimpleRectNode(rect, m_selectionColor));
    }

    // Finally, add decorations for each node to the tree.
    for (int i=0; i<m_lines.size(); ++i) {
        const TextDecoration &textDecoration = m_lines.at(i);

        QColor color = textDecoration.selectionState == Selected
                ? m_selectedTextColor
                : textDecoration.color;

        parentNode->appendChildNode(new QSGSimpleRectNode(textDecoration.rect, color));
    }

    // Then, go through all the nodes for all lines and combine all QGlyphRuns with a common
    // font, selection state and clip node.
    typedef QPair<QFontEngine *, QPair<QQuickDefaultClipNode *, QPair<QRgb, int> > > KeyType;
    QHash<KeyType, BinaryTreeNode *> map;
    QList<BinaryTreeNode *> nodes;
    for (int i = 0; i < m_processedNodes.size(); ++i) {
        BinaryTreeNode *node = m_processedNodes.data() + i;

        if (node->image.isNull()) {
            QGlyphRun glyphRun = node->glyphRun;
            QRawFont rawFont = glyphRun.rawFont();
            QRawFontPrivate *rawFontD = QRawFontPrivate::get(rawFont);

            QFontEngine *fontEngine = rawFontD->fontEngine;

            KeyType key(qMakePair(fontEngine,
                                  qMakePair(node->clipNode,
                                            qMakePair(node->color.rgba(), int(node->selectionState)))));

            BinaryTreeNode *otherNode = map.value(key, 0);
            if (otherNode != 0) {
                QGlyphRun &otherGlyphRun = otherNode->glyphRun;

                QVector<quint32> otherGlyphIndexes = otherGlyphRun.glyphIndexes();
                QVector<QPointF> otherGlyphPositions = otherGlyphRun.positions();

                otherGlyphIndexes += glyphRun.glyphIndexes();

                QVector<QPointF> glyphPositions = glyphRun.positions();
                otherGlyphPositions.reserve(otherGlyphPositions.size() + glyphPositions.size());
                for (int j = 0; j < glyphPositions.size(); ++j) {
                    otherGlyphPositions += glyphPositions.at(j) + (node->position - otherNode->position);
                }

                otherGlyphRun.setGlyphIndexes(otherGlyphIndexes);
                otherGlyphRun.setPositions(otherGlyphPositions);

            } else {
                map.insert(key, node);
                nodes.append(node);
            }
        } else {
            parentNode->addImage(node->boundingRect, node->image);
            if (node->selectionState == Selected) {
                QColor color = m_selectionColor;
                color.setAlpha(128);
                parentNode->appendChildNode(new QSGSimpleRectNode(node->boundingRect, color));
            }
        }
    }

    foreach (const BinaryTreeNode *node, nodes) {

        QQuickDefaultClipNode *clipNode = node->clipNode;
        if (clipNode != 0 && clipNode->parent() == 0 )
            parentNode->appendChildNode(clipNode);

        QColor color = node->selectionState == Selected
                ? m_selectedTextColor
                : node->color;

        parentNode->addGlyphs(node->position, node->glyphRun, color, style, styleColor, clipNode);
    }
QColor AsemanDesktopTools::titleBarTransparentColor() const
{
    QColor color = titleBarColor();
    color.setAlpha(160);
    return color;
}
Beispiel #3
0
void QcMultiSlider::paintEvent( QPaintEvent *e )
{
  using namespace QtCollider::Style;
  using QtCollider::Style::Ellipse;
  using QtCollider::Style::RoundRect;

  Q_UNUSED(e);
  QPainter p(this);
  p.setRenderHint( QPainter::Antialiasing, true );

  RoundRect frame(rect(), 2);
  drawSunken( &p, palette(), frame, background(), hasFocus() ? focusColor() : QColor() );

  if( !_values.count() ) return;

  p.setRenderHint( QPainter::Antialiasing, false );

  bool horiz = ort == Qt::Horizontal;

  QRect bounds( contentsRect() );

  p.setClipRect( bounds );

  if( horiz ) {
    p.translate( bounds.topLeft() );
    p.rotate(90);
    p.scale(1.0, -1.0);
    bounds.setSize( QSize( bounds.height(), bounds.width() ) );
  }
  else {
    p.translate( bounds.left(), bounds.top() + bounds.height() );
    p.scale(1.0, -1.0);
  }

  int count = _values.count() - startIndex;
  double spacing, width, yscale;

  spacing = elastic ? (double) bounds.width() / count : thumbSize.width() + gap;
  width = elastic ? qMin( spacing, (double) thumbSize.width() ) : thumbSize.width();
  yscale = bounds.height();
  if( !isFilled ) yscale -= thumbSize.height();

  const QColor & fillClr = fillColor();

  // selection

  if( highlight ) {
    int i = _currentIndex - startIndex;
    int c = qMin( count - i, _selectionSize );
    if(c) {
      QRect r;
      r.setHeight( bounds.height() );
      r.setWidth( c * spacing );
      r.moveLeft( i * spacing );

      QColor hlColor = fillClr;
      hlColor.setAlpha( 70 );
      p.fillRect( r, hlColor );
    }
  }

  p.setPen( strokeColor() );

  // lines

  if( drawLines ) {
    bool fill = isFilled & !drawRects;

    p.save();

    p.setRenderHint( QPainter::Antialiasing, true );
    p.translate( spacing * 0.5, isFilled ? 0.0 : thumbSize.height() * 0.5 );
    p.scale( 1.0, (qreal) yscale );
    if( fill ) p.setBrush( fillClr );

    QPainterPath path;

    // value line

    path.moveTo( 0, _values[startIndex] );
    for( int i = 1; i < count; ++i )
      path.lineTo( (qreal) i * spacing, _values[i + startIndex] );

    // reference line

    int refcount = _ref.count() - startIndex;
    if( refcount > 0 || fill ) {
      qreal x, y;
      int i = count - 1;

      x = i * spacing;
      y = i < refcount ? _ref[i + startIndex] : 0.f;
      if( fill ) path.lineTo(x, y);
      else path.moveTo(x, y);

      while( --i >= 0 ) {
        x = i * spacing;
        y = i < refcount ? _ref[i + startIndex] : 0.f;
        path.lineTo(x, y);
      }

      if( fill ) path.closeSubpath();
    }

    p.drawPath( path );

    p.restore();
  }

  // rects

  if( drawRects ) {
    p.setRenderHint( QPainter::Antialiasing, false );
    p.translate( (spacing - width) * 0.5, 0 );
    p.setBrush( fillClr );

    QRectF r;
    r.setWidth( width );

    if( isFilled ) {
      int refcount = _ref.count() - startIndex;
      for( int i = 0; i < count; ++i ) {
        int ref = (i < refcount ? _ref[i + startIndex] : 0.f) * yscale;
        int val = _values[i + startIndex] * yscale;
        r.moveLeft( i * spacing );
        r.moveTop( ref );
        r.setHeight( val - ref );
        if(horiz) p.drawRect(r.normalized().adjusted(0,0,-1,-1));
        else p.drawRect(r.normalized().adjusted(0,1,-1,0));
      }
    }
    else {
      r.setHeight( thumbSize.height() );
      for( int i = 0; i < count; ++i ) {
        r.moveLeft( i * spacing );
        r.moveTop( _values[i + startIndex] * yscale );
        if(horiz) p.drawRect(r.adjusted(0,0,-1,-1));
        else p.drawRect(r.adjusted(0,1,-1,0));
      }
    }
  }
}
Beispiel #4
0
void GenericCodeEditor::paintLineIndicator( QPaintEvent *e )
{
    QPalette plt( mLineIndicator->palette() );
    QRect r( e->rect() );
    QPainter p( mLineIndicator );

    p.fillRect( r, plt.color( QPalette::Mid ) );
    p.setPen( plt.color(QPalette::Dark) );
    p.drawLine( r.topRight(), r.bottomRight() );

    p.setPen( plt.color(QPalette::ButtonText) );

    QTextDocument *doc = QPlainTextEdit::document();
    QTextCursor cursor(textCursor());
    int selStartBlock, selEndBlock;
    if (cursor.hasSelection()) {
        selStartBlock = doc->findBlock(cursor.selectionStart()).blockNumber();
        selEndBlock = doc->findBlock(cursor.selectionEnd()).blockNumber();
    }
    else
        selStartBlock = selEndBlock = -1;

    QTextBlock block = firstVisibleBlock();
    int blockNumber = block.blockNumber();
    qreal top = blockBoundingGeometry(block).translated(contentOffset()).top();
    qreal bottom = top + blockBoundingRect(block).height();

    while (block.isValid() && top <= e->rect().bottom()) {
        if (block.isVisible() && bottom >= e->rect().top()) {
            p.save();

            QRectF numRect( 0, top, mLineIndicator->width() - 1, bottom - top );

            int num = blockNumber;
            if (num >= selStartBlock && num <= selEndBlock) {
                num -= selStartBlock;
                p.setPen(Qt::NoPen);
                p.setBrush(plt.color(QPalette::Highlight));
                p.drawRect(numRect);
                p.setPen(plt.color(QPalette::HighlightedText));
            }

            QString number = QString::number(num + 1);
            p.drawText(0, top, mLineIndicator->width() - 4, bottom - top,
                       Qt::AlignRight, number);

            p.restore();
        }

        block = block.next();
        top = bottom;
        bottom = top + blockBoundingRect(block).height();
        ++blockNumber;
    }
    
    if(!mEditorBoxIsActive) {
        QColor color = plt.color(QPalette::Mid);
        if(color.lightness() >= 128)
            color = color.darker(60);
        else
            color = color.lighter(50);
        
        color.setAlpha(inactiveFadeAlpha());
        p.fillRect( r, color );
    }
}
void ButtonProgress::setColor(QColor newColor)
{
    newColor.setAlpha(opasityColor);
    progressColor = newColor;
}
Beispiel #6
0
void CreateMode::drawControls(QPainter* p) 
{
	if (!inItemCreation) return;

	QPointF topLeft(createObjectPos.x(), createObjectPos.y());
	QPointF btRight(canvasCurrCoord.x(), canvasCurrCoord.y());
	QColor  drawColor = qApp->palette().color(QPalette::Active, QPalette::Highlight);

	if (createObjectMode != modeDrawLine)
	{
		QRectF bounds = QRectF(topLeft, btRight).normalized();
		//Lock Height to Width for Control Modifier for region drawing
		if (modifiers==Qt::ControlModifier)
		{
			bounds.setHeight(bounds.width());
			if (btRight.y()<topLeft.y())
				bounds.moveBottom(topLeft.y());
			if (btRight.x()<topLeft.x() && btRight.y()>topLeft.y())
				bounds.moveTop(topLeft.y());
		}
		QRect localRect = m_canvas->canvasToLocal(bounds);
		if (localRect.width() <= 0 || localRect.height() <= 0)
			return;
		p->setRenderHint(QPainter::Antialiasing);

		p->save();
		p->setPen(QPen(drawColor, 1, Qt::SolidLine, Qt::FlatCap, Qt::MiterJoin));
		drawColor.setAlpha(64);
		p->setBrush(drawColor);
		p->drawRect(localRect);

		drawColor.setAlpha(255);
		p->setBrush(Qt::NoBrush);
		p->setPen(QPen(drawColor, 1, Qt::DashLine, Qt::FlatCap, Qt::MiterJoin));

		int frameType = 0, itemType = 0;
		getFrameItemTypes(itemType, frameType);
		if (frameType == PageItem::Ellipse)
		{
			p->drawEllipse(localRect);
		}
		else if (createObjectMode == modeDrawArc)
		{
			QPainterPath path;
			path.moveTo(localRect.width() / 2.0, localRect.height() / 2.0);
			path.arcTo(0.0, 0.0, localRect.width(), localRect.height(), m_doc->itemToolPrefs().arcStartAngle, m_doc->itemToolPrefs().arcSweepAngle);
			path.closeSubpath();
			p->translate(localRect.left(), localRect.top());
			p->drawPath(path);
		}
		else if (createObjectMode == modeDrawRegularPolygon)
		{
			QPainterPath path = RegularPolygonPath(localRect.width(), localRect.height(), m_doc->itemToolPrefs().polyCorners, m_doc->itemToolPrefs().polyUseFactor, m_doc->itemToolPrefs().polyFactor, m_doc->itemToolPrefs().polyRotation, m_doc->itemToolPrefs().polyCurvature, m_doc->itemToolPrefs().polyInnerRot, m_doc->itemToolPrefs().polyOuterCurvature);
			p->translate(localRect.left(), localRect.top());
			p->drawPath(path);
		}
		else if (createObjectMode == modeDrawSpiral)
		{
			QPainterPath path = SpiralPath(localRect.width(), localRect.height(), m_doc->itemToolPrefs().spiralStartAngle, m_doc->itemToolPrefs().spiralEndAngle, m_doc->itemToolPrefs().spiralFactor);
			p->translate(localRect.left(), localRect.top());
			p->drawPath(path);
		}
		else if ((createObjectMode == modeDrawShapes) && (createObjectSubMode > 1))
		{
			FPointArray poly;
			int valCount = m_doc->ValCount;
			double *vals = m_doc->ShapeValues;
			for (int a = 0; a < valCount-3; a += 4)
			{
				if (vals[a] < 0)
				{
					poly.setMarker();
					continue;
				}
				double x1 = localRect.width()  * vals[a] / 100.0;
				double y1 = localRect.height() * vals[a+1] / 100.0;
				double x2 = localRect.width()  * vals[a+2] / 100.0;
				double y2 = localRect.height() * vals[a+3] / 100.0;
				poly.addPoint(x1, y1);
				poly.addPoint(x2, y2);
			}
			QPainterPath path = poly.toQPainterPath(false);
			p->translate(localRect.left(), localRect.top());
			p->drawPath(path);
		}
		p->restore();
	}
	else
	{
		QPoint p1 = m_canvas->canvasToLocal(topLeft);
		QPoint p2 = m_canvas->canvasToLocal(btRight);
		
		p->save();
		p->setPen(QPen(drawColor, 1, Qt::SolidLine, Qt::FlatCap, Qt::MiterJoin));
		p->setBrush(drawColor);
		p->drawLine(p1, p2);
		p->restore();
	}
}
void QSGPropertyAnimator::updateProperty(QObject *target, const QString& p)
{
    QSGAnimatedProperty *ap = m_controller->registeredProperty(p, target);
    if (ap && m_duration > 0) {
        if (m_elapsed > m_startTime && ((m_elapsed < m_startTime + m_loops * m_duration) || (m_loops < 0))) {

            QVariant value = ap->value();
            qreal tx = int(m_elapsed - m_startTime) % int(m_duration);

            switch (value.type()) {
            case QMetaType::Double:
                value = QVariant(m_from.toReal() + (m_to.toReal() - m_from.toReal()) * m_easing.valueForProgress(tx / m_duration));
                break;
            case QMetaType::QColor:
                {
                QColor from = qvariant_cast<QColor>(m_from);
                QColor to = qvariant_cast<QColor>(m_to);
                QColor result = qvariant_cast<QColor>(value);
                result.setRed(from.red() + (to.red() - from.red()) * m_easing.valueForProgress(tx / m_duration));
                result.setGreen(from.green() + (to.green() - from.green()) * m_easing.valueForProgress(tx / m_duration));
                result.setBlue(from.blue() + (to.blue() - from.blue()) * m_easing.valueForProgress(tx / m_duration));
                result.setAlpha(from.alpha() + (to.alpha() - from.alpha()) * m_easing.valueForProgress(tx / m_duration));
                value = result;
                break;
                }
            case QMetaType::Int:
                value = QVariant(m_from.toInt() + (m_to.toInt() - m_from.toInt()) * m_easing.valueForProgress(tx / m_duration));
                break;
            case QMetaType::QSize:
                {
                QSize from = m_from.toSize();
                QSize to = m_to.toSize();
                QSize result = value.toSize();
                result.setWidth(from.width() + (to.width() - from.width()) * m_easing.valueForProgress(tx / m_duration));
                result.setHeight(from.height() + (to.height() - from.height()) * m_easing.valueForProgress(tx / m_duration));
                value = result;
                break;
                }
            case QMetaType::QSizeF:
                {
                QSizeF from = m_from.toSize();
                QSizeF to = m_to.toSize();
                QSizeF result = value.toSize();
                result.setWidth(from.width() + (to.width() - from.width()) * m_easing.valueForProgress(tx / m_duration));
                result.setHeight(from.height() + (to.height() - from.height()) * m_easing.valueForProgress(tx / m_duration));
                value = result;
                break;
                }
            case QMetaType::QPoint:
                {
                QPoint from = m_from.toPoint();
                QPoint to = m_to.toPoint();
                QPoint result = value.toPoint();
                result.setX(from.x() + (to.x() - from.x()) * m_easing.valueForProgress(tx / m_duration));
                result.setY(from.y() + (to.y() - from.y()) * m_easing.valueForProgress(tx / m_duration));
                value = result;
                break;
                }
            case QMetaType::QPointF:
                {
                QPointF from = m_from.toPointF();
                QPointF to = m_to.toPointF();
                QPointF result = value.toPointF();
                result.setX(from.x() + (to.x() - from.x()) * m_easing.valueForProgress(tx / m_duration));
                result.setY(from.y() + (to.y() - from.y()) * m_easing.valueForProgress(tx / m_duration));
                value = result;
                break;
                }
            case QMetaType::QRect:
                {
                QRect from = m_from.toRect();
                QRect to = m_to.toRect();
                QRect result = value.toRect();
                result.setX(from.x() + (to.x() - from.x()) * m_easing.valueForProgress(tx / m_duration));
                result.setY(from.y() + (to.y() - from.y()) * m_easing.valueForProgress(tx / m_duration));
                result.setWidth(from.width() + (to.width() - from.width()) * m_easing.valueForProgress(tx / m_duration));
                result.setHeight(from.height() + (to.height() - from.height()) * m_easing.valueForProgress(tx / m_duration));
                value = result;
                break;
                }
            case QMetaType::QRectF:
                {
                QRectF from = m_from.toRectF();
                QRectF to = m_to.toRectF();
                QRectF result = value.toRectF();
                result.setX(from.x() + (to.x() - from.x()) * m_easing.valueForProgress(tx / m_duration));
                result.setY(from.y() + (to.y() - from.y()) * m_easing.valueForProgress(tx / m_duration));
                result.setWidth(from.width() + (to.width() - from.width()) * m_easing.valueForProgress(tx / m_duration));
                result.setHeight(from.height() + (to.height() - from.height()) * m_easing.valueForProgress(tx / m_duration));
                value = result;
                break;
                }
            case QMetaType::QVector3D:
                {
                QVector3D from = qvariant_cast<QVector3D>(m_from);
                QVector3D to = qvariant_cast<QVector3D>(m_to);
                QVector3D result = qvariant_cast<QVector3D>(value);
                result.setX(from.x() + (to.x() - from.x()) * m_easing.valueForProgress(tx / m_duration));
                result.setY(from.y() + (to.y() - from.y()) * m_easing.valueForProgress(tx / m_duration));
                result.setZ(from.z() + (to.z() - from.z()) * m_easing.valueForProgress(tx / m_duration));
                value = result;
                break;
                }
            default:
                break;
            }
            ap->setValue(value);
        }
    }
}
Beispiel #8
0
void
CpintPlot::calculate(RideItem *rideItem)
{
    if (!rideItem) return;

    QString fileName = rideItem->fileName;
    QDateTime dateTime = rideItem->dateTime;
    QDir dir(path);
    QFileInfo file(fileName);

    // zap any existing ridefilecache then get new one
    if (current) delete current;
    current = new RideFileCache(context, context->athlete->home.absolutePath() + "/" + fileName);

    // get aggregates - incase not initialised from date change
    if (bests == NULL) bests = new RideFileCache(context, startDate, endDate, isFiltered, files, rangemode);

    //
    // PLOT MODEL CURVE (DERIVED)
    //
    if (series == RideFile::aPower || series == RideFile::xPower || series == RideFile::NP || series == RideFile::watts  || series == RideFile::wattsKg || series == RideFile::none) {

        if (bests->meanMaxArray(series).size() > 1) {
            // calculate CP model from all-time best data
            cp  = tau = t0  = 0;
            deriveCPParameters();

            if (useExtendedCP) {
                // calculate extended CP model from all-time best data
                //athleteModeleCP2 = ecp->deriveExtendedCP_2_3_Parameters(bests, series, sanI1, sanI2, anI1, anI2, aeI1, aeI2, laeI1, laeI2);

                athleteModeleCP4 = ecp->deriveExtendedCP_4_3_Parameters(true, bests, series, sanI1, sanI2, anI1, anI2, aeI1, aeI2, laeI1, laeI2);


                /*double best5sec = context->ride->ride()->getWeight() * 24.04;
                double best1min = context->ride->ride()->getWeight() * 11.50;
                double best5min = context->ride->ride()->getWeight() * 7.60;
                double best1hour = context->ride->ride()->getWeight() * 6.40;
                //worldClassModeleCP2 = ecp->deriveExtendedCP_2_3_ParametersForBest(best5sec, best1min, best5min, best1hour);
                worldClassModeleCP4 = ecp->deriveExtendedCP_4_3_ParametersForBest(best5sec, best1min, best5min, best1hour);*/
            }
        }

        //
        // CP curve only relevant for Energy or Watts (?)
        //
        if (series == RideFile::aPower || series == RideFile::NP || series == RideFile::xPower ||
            series == RideFile::watts || series == RideFile::wattsKg || series == RideFile::none) {

            if (!CPCurve) plot_CP_curve(this, cp, tau, t0);
            else {
                // make sure color reflects latest config
                QPen pen(GColor(CCP));
                pen.setWidth(1.0);
                pen.setStyle(Qt::DashLine);
                CPCurve->setPen(pen);
            }

            if (useExtendedCP && CPCurve) CPCurve->setVisible(false);
            else if (CPCurve) CPCurve->setVisible(true);
        }

        //
        // PLOT ZONE (RAINBOW) AGGREGATED CURVE
        //
        if (bests->meanMaxArray(series).size()) {
            int maxNonZero = 0;
            for (int i = 0; i < bests->meanMaxArray(series).size(); ++i) {
                if (bests->meanMaxArray(series)[i] > 0) maxNonZero = i;
            }
            plot_allCurve(this, maxNonZero, bests->meanMaxArray(series).constData() + 1);
        }
    } else {

        //
        // PLOT BESTS IN SERIES COLOR
        //
        if (allCurve) {
            delete allCurve;
            allCurve = NULL;
        }
        if (bests->meanMaxArray(series).size()) {

            int maxNonZero = 0;
            QVector<double> timeArray(bests->meanMaxArray(series).size());
            for (int i = 0; i < bests->meanMaxArray(series).size(); ++i) {
                timeArray[i] = i / 60.0;
                if (bests->meanMaxArray(series)[i] > 0) maxNonZero = i;
            }

            if (maxNonZero > 1) {

                allCurve = new QwtPlotCurve(dateTime.toString(tr("ddd MMM d, yyyy h:mm AP")));
                allCurve->setRenderHint(QwtPlotItem::RenderAntialiased);

                QPen line;
                QColor fill;
                switch (series) {

                    case RideFile::kph:
                        line.setColor(GColor(CSPEED).darker(200));
                        fill = (GColor(CSPEED));
                        break;

                    case RideFile::cad:
                        line.setColor(GColor(CCADENCE).darker(200));
                        fill = (GColor(CCADENCE));
                        break;

                    case RideFile::nm:
                        line.setColor(GColor(CTORQUE).darker(200));
                        fill = (GColor(CTORQUE));
                        break;

                    case RideFile::hr:
                        line.setColor(GColor(CHEARTRATE).darker(200));
                        fill = (GColor(CHEARTRATE));
                        break;

                    case RideFile::vam:
                        line.setColor(GColor(CALTITUDE).darker(200));
                        fill = (GColor(CALTITUDE));
                        break;

                    default:
                    case RideFile::watts: // won't ever get here
                    case RideFile::NP:
                    case RideFile::xPower:
                        line.setColor(GColor(CPOWER).darker(200));
                        fill = (GColor(CPOWER));
                        break;
                }

                // wow, QVector really doesn't have a max/min method!
                double ymax = 0;
                double ymin = 100000;
                foreach(double v, current->meanMaxArray(series)) {
                    if (v > ymax) ymax = v;
                    if (v && v < ymin) ymin = v;
                }
                foreach(double v, bests->meanMaxArray(series)) {
                    if (v > ymax) ymax = v;
                    if (v&& v < ymin) ymin = v;
                }
                if (ymin == 100000) ymin = 0;

                // VAM is a bit special
                if (series == RideFile::vam) {
                    if (bests->meanMaxArray(series).size() > 300)
                        ymax = bests->meanMaxArray(series)[300];
                    else
                        ymax = 2000;
                }

                ymax *= 1.1; // bit of headroom
                ymin *= 0.9;

                // xmax is directly related to the size of the arrays
                double xmax = current->meanMaxArray(series).size();
                if (bests->meanMaxArray(series).size() > xmax)
                    xmax = bests->meanMaxArray(series).size();
                xmax /= 60; // its in minutes not seconds

                setAxisScale(yLeft, ymin, ymax);

                QwtScaleDiv div((series == RideFile::vam ? (double) 4.993: (double) 0.017), (double)xmax);
                div.setTicks(QwtScaleDiv::MajorTick, LogTimeScaleDraw::ticks);
                setAxisScaleDiv(QwtPlot::xBottom, div);

                allCurve->setPen(line);
                fill.setAlpha(64);
                // use a linear gradient
                fill.setAlpha(64);
                QColor fill1 = fill.darker();
                QLinearGradient linearGradient(0, 0, 0, height());
                linearGradient.setColorAt(0.0, fill);
                linearGradient.setColorAt(1.0, fill1);
                linearGradient.setSpread(QGradient::PadSpread);
                allCurve->setBrush(linearGradient);
                allCurve->attach(this);
                allCurve->setSamples(timeArray.data() + 1, bests->meanMaxArray(series).constData() + 1, maxNonZero - 1);
            }
        }
void SProgressListItem::setup()
{
    p = new SProgressListItemPrivate;

    setStyleSheet( "QFrame{ background-color: transparent; }" );

    p->animation = new SAnimation( this );
        p->animation->setFixOptions( SAnimation::WIDTH_FIX );
        p->animation->setFrameRate( 10 );

    QFont font = QWidget::font();
        font.setBold( true );
        font.setItalic( true );

    QColor color = palette().color( QPalette::Base );
        color.setAlpha( 0 );

    QPalette palette1 = palette();
        palette1.setColor( QPalette::Base , color );

    color.setAlpha(73);

    QPalette palette2 = palette();
        palette2.setColor( QPalette::Window , color );

    p->titleLabel = new QLabel();
        p->titleLabel->setFont( font );

    p->infsLine = new QLineEdit();
        p->infsLine->setReadOnly( true );

    p->fake_extra_widget = new QWidget();
        p->fake_extra_widget->setHidden( true );
        p->fake_extra_widget->setSizePolicy( QSizePolicy::Minimum ,QSizePolicy::Maximum );
        p->fake_extra_widget->setFixedHeight( 75 );

    p->extra_widget = new QWidget();
        p->extra_widget->setSizePolicy( QSizePolicy::Minimum ,QSizePolicy::Maximum );
        p->extra_widget->setHidden( true );
        p->extra_widget->setFixedHeight( 75 );

    p->progressBar = new QProgressBar();
        p->progressBar->setValue( 0 );
        p->progressBar->setPalette( palette2 );

    p->stopButton = new QPushButton();
        p->stopButton->setFixedSize( 24 , 24 );
        p->stopButton->setIcon( SMasterIcons::icon( QSize(48,48) , "process-stop.png" ) );

    p->moreButton = new QPushButton();
        p->moreButton->setFixedSize( 75 , 24 );
        p->moreButton->setText( tr("More") );
        p->moreButton->setIcon( SMasterIcons::icon( QSize(48,48) , "go-down.png" ) );

    p->progressHLayout = new QHBoxLayout();
        p->progressHLayout->addWidget( p->progressBar );
        p->progressHLayout->addWidget( p->stopButton );
        p->progressHLayout->addWidget( p->moreButton );
        p->progressHLayout->setContentsMargins(0,0,0,0);
        p->progressHLayout->setSpacing(0);

    p->baseVLayout = new QVBoxLayout();
        p->baseVLayout->addWidget( p->titleLabel );
        p->baseVLayout->addWidget( p->infsLine );
        p->baseVLayout->addWidget( p->fake_extra_widget );
        p->baseVLayout->addWidget( p->extra_widget );
        p->baseVLayout->addLayout( p->progressHLayout );
        p->baseVLayout->setContentsMargins(0,0,0,0);
        p->baseVLayout->setSpacing(0);

    p->frame = new QFrame();
        p->frame->setLayout( p->baseVLayout );

    p->icon = new SPictureWidget();
        p->icon->setFixedSize( 48 , 48 );

    p->layout = new QHBoxLayout(this);
    p->layout->addWidget( p->icon );
        p->layout->addWidget( p->frame );
        p->layout->setSpacing(0);
        p->layout->setContentsMargins( 0 , 0 , 0 , 0 );

    QObject::connect( p->moreButton , SIGNAL(clicked()) , this , SLOT(autoExpand())        );
    QObject::connect( p->animation , SIGNAL(finished()) , this , SLOT(animationFinished()) );

    registerItem();
}
Beispiel #10
0
void KeyWidget::paintEvent(QPaintEvent*){
    const QColor bgColor(68, 64, 64);
    const QColor keyColor(112, 110, 110);
    const QColor sniperColor(130, 90, 90);
    const QColor highlightColor(136, 176, 240);
    const QColor highlightAnimColor(136, 200, 240);
    const QColor animColor(112, 200, 110);

    // Determine which keys to highlight
    QBitArray highlight;
    switch(mouseDownMode){
    case SET:
        highlight = newSelection;
        break;
    case ADD:
        highlight = selection | newSelection;
        break;
    case SUBTRACT:
        highlight = selection & ~newSelection;
        break;
    case TOGGLE:
        highlight = selection ^ newSelection;
        break;
    default:
        highlight = selection;
    }

    QPainter painter(this);
#if QT_VERSION >= QT_VERSION_CHECK(5, 3, 0)
    int ratio = painter.device()->devicePixelRatio();
#else
    int ratio = 1;
#endif
    int wWidth = width(), wHeight = height();
    KeyMap::Model model = keyMap.model();
    float scale, offX, offY;
    drawInfo(scale, offX, offY);
    // Draw background
    painter.setPen(Qt::NoPen);
    painter.setRenderHint(QPainter::Antialiasing, true);

    if(model == KeyMap::M65){
        // M65: Draw overlay
        if(!m65Overlay)
            m65Overlay = new QImage(":/img/overlay_m65.png");
        const QImage& overlay = *m65Overlay;
        painter.setBrush(palette().brush(QPalette::Window));
        painter.drawRect(0, 0, width(), height());
        float oXScale = scale / 9.f, oYScale = scale / 9.f;             // The overlay has a resolution of 9px per keymap unit
        float x = (2.f + offX) * scale, y = (-2.f + offY) * scale;      // It is positioned at (2, -2)
        int w = overlay.width() * oXScale, h = overlay.height() * oYScale;
        // We need to transform the image with QImage::scaled() because painter.drawImage() will butcher it, even with smoothing enabled
        // However, the width/height need to be rounded to integers
        int iW = round(w), iH = round(h);
        painter.drawImage(QRectF(x - (iW - w) / 2.f, y - (iH - h) / 2.f, iW, iH), overlay.scaled(iW, iH, Qt::IgnoreAspectRatio, Qt::SmoothTransformation));
    } else {
        // Otherwise, draw a solid background
        painter.setBrush(QBrush(bgColor));
        painter.drawRect(0, 0, width(), height());
    }

    // Draw mouse highlight (if any)
    if(mouseDownMode != NONE && (mouseDownX != mouseCurrentX || mouseDownY != mouseCurrentY)){
        int x1 = (mouseDownX > mouseCurrentX) ? mouseCurrentX : mouseDownX;
        int x2 = (mouseDownX > mouseCurrentX) ? mouseDownX : mouseCurrentX;
        int y1 = (mouseDownY > mouseCurrentY) ? mouseCurrentY : mouseDownY;
        int y2 = (mouseDownY > mouseCurrentY) ? mouseDownY : mouseCurrentY;
        painter.setPen(QPen(highlightColor, 0.5));
        QColor bColor = highlightColor;
        bColor.setAlpha(128);
        painter.setBrush(QBrush(bColor));
        painter.drawRect(x1, y1, x2 - x1, y2 - y1);
    }

    // Draw key backgrounds on a separate pixmap so that a drop shadow can be applied to them.
    QPixmap keyBG(wWidth * ratio, wHeight * ratio);
    keyBG.fill(QColor(0, 0, 0, 0));
    QPainter bgPainter(&keyBG);
    bgPainter.setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing);
    bgPainter.setPen(Qt::NoPen);
    QHashIterator<QString, Key> k(keyMap);
    uint i = -1;
    while(k.hasNext()){
        k.next();
        i++;
        const Key& key = k.value();
        float x = key.x + offX - key.width / 2.f + 1.f;
        float y = key.y + offY - key.height / 2.f + 1.f;
        float w = key.width - 2.f;
        float h = key.height - 2.f;
        // In RGB mode, ignore keys without LEDs
        if((_rgbMode && !key.hasLed)
                || (!_rgbMode && !key.hasScan))
            continue;
        // Set color based on key highlight
        bgPainter.setOpacity(1.);
        if(highlight.testBit(i)){
            if(animation.testBit(i))
                bgPainter.setBrush(QBrush(highlightAnimColor));
            else
                bgPainter.setBrush(QBrush(highlightColor));
        } else if(animation.testBit(i)){
            bgPainter.setBrush(QBrush(animColor));
        } else {
            if(!strcmp(key.name, "sniper"))
                // Sniper key uses a reddish base color instead of the usual grey
                bgPainter.setBrush(QBrush(sniperColor));
            else {
                bgPainter.setBrush(QBrush(keyColor));
                if(KeyMap::isMouse(model))
                    bgPainter.setOpacity(0.7);
            }
        }
        if(!strcmp(key.name, "mr") || !strcmp(key.name, "m1") || !strcmp(key.name, "m2") || !strcmp(key.name, "m3")
                || !strcmp(key.name, "light") || !strcmp(key.name, "lock") || (model == KeyMap::K65 && !strcmp(key.name, "mute"))){
            // Switch keys are circular
            x += w / 8.f;
            y += h / 8.f;
            w *= 0.75f;
            h *= 0.75f;
            bgPainter.drawEllipse(QRectF(x * scale, y * scale, w * scale, h * scale));
        } else {
            if(!strcmp(key.name, "enter")){
                if(key.height == 24){
                    // ISO enter key isn't rectangular
                    y = key.y + 1.f;
                    h = 10.f;
                    bgPainter.drawRect(QRectF((x + w - 13.f) * scale, y * scale, 13.f * scale, 22.f * scale));
                } else {
                    // US enter key isn't perfectly centered, needs an extra pixel on the left to appear correctly
                    x -= 1.f;
                    w += 1.f;
                }
            } else if(!strcmp(key.name, "rshift") || !strcmp(key.name, "stop")){
                // A few other keys also need extra pixels
                x -= 1.f;
                w += 1.f;
            } else if(!strcmp(key.name, "caps") || !strcmp(key.name, "lshift") || !strcmp(key.name, "next")){
                w += 1.f;
            }
            bgPainter.drawRect(QRectF(x * scale, y * scale, w * scale, h * scale));
        }
    }

    // Render the key decorations (RGB -> light circles, binding -> key names) on yet another layer
    QPixmap decoration(wWidth * ratio, wHeight * ratio);
    decoration.fill(QColor(0, 0, 0, 0));
    QPainter decPainter(&decoration);
    decPainter.setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing);
    if(_rgbMode){
        // Draw key colors (RGB mode)
        decPainter.setPen(QPen(QColor(255, 255, 255), 1.5));
        QHashIterator<QString, Key> k(keyMap);
        uint i = -1;
        while(k.hasNext()){
            k.next();
            i++;
            const Key& key = k.value();
            if(!key.hasLed)
                continue;
            float x = key.x + offX - 1.8f;
            float y = key.y + offY - 1.8f;
            float w = 3.6f;
            float h = 3.6f;
            if(_displayColorMap.contains(key.name))
                decPainter.setBrush(QBrush(_displayColorMap.value(key.name)));
            else
                decPainter.setBrush(QBrush(_colorMap.value(key.name)));
            decPainter.drawEllipse(QRectF(x * scale, y * scale, w * scale, h * scale));
        }
    } else {
        // Draw key names
        decPainter.setBrush(Qt::NoBrush);
        QFont font = painter.font();
        font.setBold(true);
        font.setPixelSize(5.25f * scale);
        QFont font0 = font;
        QHashIterator<QString, Key> k(keyMap);
        uint i = -1;
        while(k.hasNext()){
            k.next();
            i++;
            const Key& key = k.value();
            if(!key.hasScan)
                continue;
            float x = key.x + offX - key.width / 2.f + 1.f;
            float y = key.y + offY - key.height / 2.f;
            float w = key.width - 2.f;
            float h = key.height;
            // Print the key's friendly name (with some exceptions)
            QString keyName = KbBind::globalRemap(key.name);
            QString name = key.friendlyName(false);
            name = name.split(" ").last();
            struct {
                const char* keyName, *displayName;
            } names[] = {
                {"light", "☼"}, {"lock", "☒"}, {"mute", "◖⊘"}, {"volup", keyMap.model() == KeyMap::K65 ? "◖))" : "▲"}, {"voldn", keyMap.model() == KeyMap::K65 ? "◖)" : "▼"},
                {"prtscn",  "PrtScn\nSysRq"}, {"scroll", "Scroll\nLock"}, {"pause", "Pause\nBreak"}, {"stop", "▪"}, {"prev", "|◂◂"}, {"play", "▸||"}, {"next", "▸▸|"},
                {"pgup", "Page\nUp"}, {"pgdn", "Page\nDown"}, {"numlock", "Num\nLock"},
                {"caps", "Caps"}, {"lshift", "Shift"}, {"rshift", "Shift"},
#ifdef Q_OS_MACX
                {"lctrl", "⌃"}, {"rctrl", "⌃"}, {"lwin", "⌘"}, {"rwin", "⌘"}, {"lalt", "⌥"}, {"ralt", "⌥"},
#else
                {"lctrl", "Ctrl"}, {"rctrl", "Ctrl"}, {"lwin", "❖"}, {"rwin", "❖"}, {"lalt", "Alt"}, {"ralt", "Alt"},
#endif
                {"rmenu", "▤"}, {"up", "▲"}, {"left", "◀"}, {"down", "▼"}, {"right", "▶"},
                {"mouse1", ""}, {"mouse2", ""}, {"mouse3", "∙"}, {"dpiup", "▲"}, {"dpidn", "▼"}, {"wheelup", "▲"}, {"wheeldn", "▼"}, {"dpi", "◉"}, {"mouse5", "▲"}, {"mouse4", "▼"}, {"sniper", "⊕"}
            };
            for(uint k = 0; k < sizeof(names) / sizeof(names[0]); k++){
                if(keyName == names[k].keyName){
                    name = names[k].displayName;
                    break;
                }
            }
            if(keyName == "mr" || keyName == "m1" || keyName == "m2" || keyName == "m3" || keyName == "up" || keyName == "down" || keyName == "left" || keyName == "right")
                // Use a smaller size for MR, M1 - M3, and arrow keys
                font.setPixelSize(font.pixelSize() * 0.75);
            else if(keyName == "end")
                // Use a smaller size for "End" to match everything else in that area
                font.setPixelSize(font.pixelSize() * 0.65);
            else if(keyName == "light"
#ifndef Q_OS_MACX
                    || keyName == "lwin" || keyName == "rwin"
#endif
                    )
                // Use a larger font size for Super (Linux only) and Brightness to compensate for the unicode symbols looking smaller
                font.setPixelSize(font.pixelSize() * 1.3);
            // Determine the appropriate size to draw the text at
            decPainter.setFont(font);
            QRectF rect(x * scale, y * scale - 1, w * scale, h * scale);
            int flags = Qt::AlignHCenter | Qt::AlignVCenter | Qt::TextWordWrap;
            QRectF bounds = decPainter.boundingRect(rect, flags, name);
            while((bounds.height() >= rect.height() - 8. || bounds.width() >= rect.width() - 2.) && font.pixelSize() >= 5){
                // Scale font size down until it fits inside the key
                font.setPixelSize(font.pixelSize() - 2);
                decPainter.setFont(font);
                bounds = decPainter.boundingRect(rect, flags, name);
            }
            // Pick color based on key function
            QString bind = _bindMap.value(key.name);
            QString def = KbBind::defaultAction(key.name);
            if(bind.isEmpty())
                // Unbound - red
                decPainter.setPen(QColor(255, 136, 136));
            else if(KeyAction(bind).isProgram())
                // Custom program - orange
                decPainter.setPen(QColor(255, 224, 192));
            else if(KeyAction(bind).isSpecial() && (bind == def || !KeyAction(def).isSpecial()))
                // Special function - blue (only if not mapped to a different function - if a special function is remapped, color it yellow)
                decPainter.setPen(QColor(128, 224, 255));
            else if(KeyAction(bind).isMedia() && (bind == def || !KeyAction(def).isMedia()))
                // Media key - green
                decPainter.setPen(QColor(160, 255, 168));
            else if(bind == def)
                // Standard key - white
                decPainter.setPen(QColor(255, 255, 255));
            else
                // Remapped key - yellow
                decPainter.setPen(QColor(255, 248, 128));
            decPainter.drawText(rect, flags, name);
            font = font0;
        }
    }
    // Create drop shadow effects
    QGraphicsDropShadowEffect* bgEffect = new QGraphicsDropShadowEffect;  // Have to use "new", creating these on the stack causes a crash...
    bgEffect->setBlurRadius(2.);
    bgEffect->setColor(QColor(0, 0, 0, 32));
    bgEffect->setOffset(0, 1);
    QGraphicsDropShadowEffect* decEffect = new QGraphicsDropShadowEffect;
    decEffect->setBlurRadius(4.);
    decEffect->setColor(QColor(0, 0, 0, 104));
    decEffect->setOffset(0, 1);
    // Apply them to the pixmaps
    QGraphicsPixmapItem* bgItem = new QGraphicsPixmapItem(keyBG);
    bgItem->setGraphicsEffect(bgEffect);
    QGraphicsPixmapItem* decItem = new QGraphicsPixmapItem(decoration);
    decItem->setGraphicsEffect(decEffect);
    // Render everything
    QGraphicsScene* scene = new QGraphicsScene;
    scene->addItem(bgItem);
    scene->addItem(decItem);
    // It has to be rendered onto yet another pixmap or else DPI scaling will look terrible...
    QPixmap final(wWidth * ratio, wHeight * ratio);
    final.fill(QColor(0, 0, 0, 0));
Beispiel #11
0
// plot the all curve, with shading according to the shade mode
void
CpintPlot::plot_allCurve(CpintPlot *thisPlot,
                         int n_values,
                         const double *power_values)
{
    clear_CP_Curves();

    QVector<double> energyBests(n_values);
    QVector<double> time_values(n_values);
    // generate an array of time values
    for (int t = 0; t < n_values; t++) {
        time_values[t] = (t + 1) / 60.0;
        energyBests[t] = power_values[t] * time_values[t] * 60.0 / 1000.0;
    }

    // lets work out how we are shading it
    switch(shadeMode) {
        case 0 : // not shading!!
            break;

        case 1 : // value for current date
                 // or average for date range if a range
            shadingCP = dateCP;
            break;

        default:
        case 2 : // derived value
            shadingCP = cp;
            break;
    }

    // generate zones from shading CP value
    if (shadingCP > 0) {
        QList <int> power_zone;
        int n_zones = zones->lowsFromCP(&power_zone, (int) int(shadingCP));
        int high = n_values - 1;
        int zone = 0;
        while (zone < n_zones && high > 0) {
            int low = high - 1;
            int nextZone = zone + 1;
            if (nextZone >= power_zone.size())
                low = 0;
            else {
                while ((low > 0) && (power_values[low] < power_zone[nextZone]))
                    --low;
            }

            QColor color = zoneColor(zone, n_zones);
            QString name = zones->getDefaultZoneName(zone);
            QwtPlotCurve *curve = new QwtPlotCurve(name);
            if (appsettings->value(this, GC_ANTIALIAS, false).toBool() == true)
                curve->setRenderHint(QwtPlotItem::RenderAntialiased);
            QPen pen(color.darker(200));
            pen.setWidth(2.0);
            curve->setPen(pen);
            curve->attach(thisPlot);

            // use a linear gradient
            if (shadeMode && shadingCP) { // 0 value means no shading please - and only if proper value for shadingCP
                color.setAlpha(64);
                QColor color1 = color.darker();
                QLinearGradient linearGradient(0, 0, 0, height());
                linearGradient.setColorAt(0.0, color);
                linearGradient.setColorAt(1.0, color1);
                linearGradient.setSpread(QGradient::PadSpread);
                curve->setBrush(linearGradient);   // fill below the line
            }

            if (series == RideFile::none) { // this is Energy mode 
                curve->setSamples(time_values.data() + low,
                               energyBests.data() + low, high - low + 1);
            } else {
                curve->setSamples(time_values.data() + low,
                               power_values + low, high - low + 1);
            }
            allCurves.append(curve);

            if (shadeMode && (series != RideFile::none || energyBests[high] > 100.0)) {
                QwtText text(name);
                text.setFont(QFont("Helvetica", 20, QFont::Bold));
                color.setAlpha(255);
                text.setColor(color);
                QwtPlotMarker *label_mark = new QwtPlotMarker();
                // place the text in the geometric mean in time, at a decent power
                double x, y;
                if (series == RideFile::none) {
                    x = (time_values[low] + time_values[high]) / 2;
                    y = (energyBests[low] + energyBests[high]) / 5;
                }
                else {
                    x = sqrt(time_values[low] * time_values[high]);
                    y = (power_values[low] + power_values[high]) / 5;
                }
                label_mark->setValue(x, y);
                label_mark->setLabel(text);
                label_mark->attach(thisPlot);
                allZoneLabels.append(label_mark);
            }

            high = low;
            ++zone;
        }
    }
    // no zones available: just plot the curve without zones
    else {
        QwtPlotCurve *curve = new QwtPlotCurve(tr("maximal power"));
        if (appsettings->value(this, GC_ANTIALIAS, false).toBool() == true)
            curve->setRenderHint(QwtPlotItem::RenderAntialiased);
        QPen pen(GColor(CCP));
        pen.setWidth(appsettings->value(this, GC_LINEWIDTH, 2.0).toDouble());
        curve->setPen(pen);
        QColor brush_color = GColor(CCP);
        brush_color.setAlpha(200);
        //curve->setBrush(QBrush::None);   // brush fills below the line
        if (series == RideFile::none)
            curve->setSamples(time_values.data(), energyBests.data(), n_values);
        else
            curve->setSamples(time_values.data(), power_values, n_values);
        curve->attach(thisPlot);
        allCurves.append(curve);
    }

    // Energy mode is really only interesting in the range where energy is
    // linear in interval duration--up to about 1 hour.
    double xmax = (series == RideFile::none)  ? 60.0 : time_values[n_values - 1];

    QwtScaleDiv div((series == RideFile::vam ? (double) 4.993: (double) 0.017), (double)xmax);
    if (series == RideFile::none)
        div.setTicks(QwtScaleDiv::MajorTick, LogTimeScaleDraw::ticksEnergy);
    else
        div.setTicks(QwtScaleDiv::MajorTick, LogTimeScaleDraw::ticks);

    thisPlot->setAxisScaleDiv(QwtPlot::xBottom, div);


    double ymax;
    if (series == RideFile::none) {
        int i = std::lower_bound(time_values.begin(), time_values.end(), 60.0) - time_values.begin();
        ymax = 10 * ceil(energyBests[i] / 10);
    }
    else {
        ymax = 100 * ceil(power_values[0] / 100);
        if (ymax == 100)
            ymax = 5 * ceil(power_values[0] / 5);
    }
    thisPlot->setAxisScale(thisPlot->yLeft, 0, ymax);
}
Beispiel #12
0
void Document::loadTheme(const Theme& theme)
{
    m_text->document()->blockSignals(true);

    // Update colors
    QString contrast = (qGray(theme.textColor().rgb()) > 127) ? "black" : "white";
    QColor color = theme.foregroundColor();
    color.setAlpha(theme.foregroundOpacity() * 2.55f);
    m_text->setStyleSheet(
        QString("QTextEdit { background: rgba(%1, %2, %3, %4); color: %5; selection-background-color: %6; selection-color: %7; padding: %8px; border-radius: %9px; }")
        .arg(color.red())
        .arg(color.green())
        .arg(color.blue())
        .arg(color.alpha())
        .arg(theme.textColor().name())
        .arg(theme.textColor().name())
        .arg(contrast)
        .arg(theme.foregroundPadding())
        .arg(theme.foregroundRounding())
    );
    m_highlighter->setMisspelledColor(theme.misspelledColor());
    m_focusmode->setBlurredTextColor(theme.blurredTextColor());

    // Update text
    QFont font = theme.textFont();
    font.setStyleStrategy(m_text->font().styleStrategy());
    if (m_text->font() != font) {
        m_text->setFont(font);
    }
    m_text->setCursorWidth(!m_block_cursor ? 1 : m_text->fontMetrics().averageCharWidth());

    int margin = theme.foregroundMargin();
    m_layout->setColumnMinimumWidth(0, margin);
    m_layout->setColumnMinimumWidth(2, margin);
    if (theme.foregroundPosition() < 3) {
        m_text->setFixedWidth(theme.foregroundWidth());

        switch (theme.foregroundPosition()) {
        case 0:
            m_layout->setColumnStretch(0, 0);
            m_layout->setColumnStretch(2, 1);
            break;

        case 2:
            m_layout->setColumnStretch(0, 1);
            m_layout->setColumnStretch(2, 0);
            break;

        case 1:
        default:
            m_layout->setColumnStretch(0, 1);
            m_layout->setColumnStretch(2, 1);
            break;
        };
    } else {
        m_text->setMinimumWidth(theme.foregroundWidth());
        m_text->setMaximumWidth(maximumSize().height());

        m_layout->setColumnStretch(0, 0);
        m_layout->setColumnStretch(2, 0);
    }

    centerCursor(true);
    m_text->document()->blockSignals(false);
}
Beispiel #13
0
Plot::Plot(int width, int height, QWidget *parent, const char *)
: QwtPlot(parent)
{
	setAutoReplot (false);

	marker_key = 0;
	curve_key = 0;

	minTickLength = 5;
	majTickLength = 9;

	setGeometry(QRect(0, 0, width, height));
	setAxisTitle(QwtPlot::yLeft, tr("Y Axis Title"));
	setAxisTitle(QwtPlot::xBottom, tr("X Axis Title"));
	//due to the plot layout updates, we must always have a non empty title
	setAxisTitle(QwtPlot::yRight, tr(" "));
	setAxisTitle(QwtPlot::xTop, tr(" "));

	// grid
	d_grid = new Grid();
	d_grid->attach(this);

	//custom scale
	for (int i= 0; i<QwtPlot::axisCnt; i++) {
		QwtScaleWidget *scale = (QwtScaleWidget *) axisWidget(i);
		if (scale) {
			scale->setMargin(0);

			//the axis title color must be initialized...
			QwtText title = scale->title();
			title.setColor(Qt::black);
			scale->setTitle(title);

            //...same for axis color
            QPalette pal = scale->palette();
            pal.setColor(QPalette::Foreground, QColor(Qt::black));
            scale->setPalette(pal);

			ScaleDraw *sd = new ScaleDraw(this);
			sd->setTickLength(QwtScaleDiv::MinorTick, minTickLength);
			sd->setTickLength(QwtScaleDiv::MediumTick, minTickLength);
			sd->setTickLength(QwtScaleDiv::MajorTick, majTickLength);

			setAxisScaleDraw (i, sd);
			setAxisScaleEngine (i, new ScaleEngine());
		}
	}

	QwtPlotLayout *pLayout = plotLayout();
	pLayout->setCanvasMargin(0);
	pLayout->setAlignCanvasToScales (true);

	QwtPlotCanvas* plCanvas = canvas();
	plCanvas->setFocusPolicy(Qt::StrongFocus);
	plCanvas->setFocusIndicator(QwtPlotCanvas::ItemFocusIndicator);
	//plCanvas->setFocus();
	plCanvas->setFrameShadow(QwtPlot::Plain);
	plCanvas->setCursor(Qt::arrowCursor);
	plCanvas->setLineWidth(0);
	plCanvas->setPaintAttribute(QwtPlotCanvas::PaintCached, false);
	plCanvas->setPaintAttribute(QwtPlotCanvas::PaintPacked, false);

    QColor background = QColor(Qt::white);
    background.setAlpha(255);

	QPalette palette;
    palette.setColor(QPalette::Window, background);
    setPalette(palette);

	setCanvasBackground (background);
	setFocusPolicy(Qt::StrongFocus);
	//setFocusProxy(plCanvas);
	setFrameShape(QFrame::Box);
	setLineWidth(0);
}
void OrthogonalRenderer::drawMapObject(QPainter *painter,
                                       const MapObject *object,
                                       const QColor &color) const
{
    painter->save();

    const QRectF bounds = object->bounds();
    QRectF rect(tileToPixelCoords(bounds.topLeft()),
                tileToPixelCoords(bounds.bottomRight()));

    painter->translate(rect.topLeft());
    rect.moveTopLeft(QPointF(0, 0));

    if (!object->cell().isEmpty()) {
        const Cell &cell = object->cell();

        drawCell(painter, cell,
                 QPointF(),
                 BottomLeft,
                 painter->transform());

        if (testFlag(ShowTileObjectOutlines)) {
            const QRect rect = cell.tile->image().rect();
            QPen pen(Qt::SolidLine);
            painter->setPen(pen);
            painter->drawRect(rect);
            pen.setStyle(Qt::DotLine);
            pen.setColor(color);
            painter->setPen(pen);
            painter->drawRect(rect);
        }
    } else {
        const QPen linePen(color, 2);
        const QPen shadowPen(Qt::black, 2);

        QColor brushColor = color;
        brushColor.setAlpha(50);
        const QBrush fillBrush(brushColor);

        painter->setRenderHint(QPainter::Antialiasing);

        switch (object->shape()) {
        case MapObject::Rectangle: {
            if (rect.isNull())
                rect = QRectF(QPointF(-10, -10), QSizeF(20, 20));

            const QFontMetrics fm = painter->fontMetrics();
            QString name = fm.elidedText(object->name(), Qt::ElideRight,
                                         rect.width() + 2);

            // Draw the shadow
            painter->setPen(shadowPen);
            painter->drawRect(rect.translated(QPointF(1, 1)));
            if (!name.isEmpty())
                painter->drawText(QPoint(1, -5 + 1), name);

            painter->setPen(linePen);
            painter->setBrush(fillBrush);
            painter->drawRect(rect);
            if (!name.isEmpty())
                painter->drawText(QPoint(0, -5), name);

            break;
        }

        case MapObject::Polyline: {
            QPolygonF screenPolygon = tileToPixelCoords(object->polygon());

            painter->setPen(shadowPen);
            painter->drawPolyline(screenPolygon.translated(1, 1));

            painter->setPen(linePen);
            painter->setBrush(fillBrush);
            painter->drawPolyline(screenPolygon);
            break;
        }

        case MapObject::Polygon: {
            QPolygonF screenPolygon = tileToPixelCoords(object->polygon());

            painter->setPen(shadowPen);
            painter->drawPolygon(screenPolygon.translated(1, 1));

            painter->setPen(linePen);
            painter->setBrush(fillBrush);
            painter->drawPolygon(screenPolygon);
            break;
        }

        case MapObject::Ellipse: {
            if (rect.isNull())
                rect = QRectF(QPointF(-10, -10), QSizeF(20, 20));

            const QFontMetrics fm = painter->fontMetrics();
            QString name = fm.elidedText(object->name(), Qt::ElideRight,
                                         rect.width() + 2);

            // Draw the shadow
            painter->setPen(shadowPen);
            painter->drawEllipse(rect.translated(QPointF(1, 1)));
            if (!name.isEmpty())
                painter->drawText(QPoint(1, -5 + 1), name);

            painter->setPen(linePen);
            painter->setBrush(fillBrush);
            painter->drawEllipse(rect);
            if (!name.isEmpty())
                painter->drawText(QPoint(0, -5), name);

            break;
        }
        }
    }

    painter->restore();
}
Beispiel #15
0
void DrawWidget::drawChannelFilled(Channel *ch, QPainter &p, double leftTime, double currentTime, double zoomX, double viewBottom, double zoomY, int viewType)
{
  ZoomLookup *z;
  if(viewType == DRAW_VIEW_SUMMARY) z = &ch->summaryZoomLookup;
  else z = &ch->normalZoomLookup;
    
  ChannelLocker channelLocker(ch);

  QColor current = ch->color;
  QColor invert(255 - current.red(), 255 - current.green(), 255 - current.blue());
  p.setPen(current);

  int viewBottomOffset = toInt(viewBottom / zoomY);
  viewBottom = double(viewBottomOffset) * zoomY;
  
  // baseX is the no. of chunks a pixel must represent.
  double baseX = zoomX / ch->timePerChunk();

  z->setZoomLevel(baseX);
  
  double currentChunk = ch->chunkFractionAtTime(currentTime);
  double leftFrameTime = currentChunk - ((currentTime - leftTime) / ch->timePerChunk());
  
  //double leftFrameTime = leftTime / ch->timePerChunk();

  double frameTime = leftFrameTime;
  //if(frameTime < 0.0) frameTime = 0.0;
  int n = 0;
  int baseElement = int(floor(frameTime / baseX));
  if(baseElement < 0) { n -= baseElement; baseElement = 0; }
  int lastBaseElement = int(floor(double(ch->totalChunks()) / baseX));
  
  int firstN = n;
  int lastN = firstN;
  
  //QPointArray pointArray(width()*2);
  //QPointArray topPoints(width()*2);
/*  Q3PointArray bottomPoints(width()*2);
  Q3PointArray evenMidPoints(width()*2);
  Q3PointArray oddMidPoints(width()*2);
  Q3PointArray evenMidPoints2(width()*2);
  Q3PointArray oddMidPoints2(width()*2);*/
  QPolygon bottomPoints(width()*2);
  QPolygon evenMidPoints(width()*2);
  QPolygon oddMidPoints(width()*2);
  QPolygon evenMidPoints2(width()*2);
  QPolygon oddMidPoints2(width()*2);
  std::vector<QRect> noteRect(width()*2);
  std::vector<QRect> noteRect2(width()*2);
  std::vector<bool> isNoteRectEven(width()*2);
  //int pointIndex = 0;
  int pointIndex = 0;
  int evenMidPointIndex = 0;
  int oddMidPointIndex = 0;
  int evenMidPointIndex2 = 0;
  int oddMidPointIndex2 = 0;
  int rectIndex = 0;
  int rectIndex2 = 0;

  if (baseX > 1) { // More samples than pixels
    int theWidth = width();
    //if(baseElement + theWidth > z->size()) z->setSize(baseElement + theWidth);
    if(lastBaseElement > z->size()) z->setSize(lastBaseElement);
    for(; n < theWidth && baseElement < lastBaseElement; n++, baseElement++) {
      myassert(baseElement >= 0);
      ZoomElement &ze = z->at(baseElement);
      //if(!z->hasValue(baseElement)) {
      if(!ze.isValid()) {
        if(!calcZoomElement(ch, ze, baseElement, baseX)) continue;
      }
     
      /*p.setPen(gdata->shading1Color());
      p.moveTo(n, 0);
      p.lineTo(n, height() - 1 - toInt(ze.high / zoomY) + viewBottomOffset);
      p.setPen(gdata->shading2Color());
      p.lineTo(n, height());*/
      int y = height() - 1 - toInt(ze.high() / zoomY) + viewBottomOffset;
      int y2, y3;
      //if(ze.noteIndex >= 0) {
      if(ze.noteIndex() != -1 && ch->dataAtChunk(ze.midChunk())->getNoteIndex() != -1) {
        myassert(ze.noteIndex() >= 0);
        myassert(ze.noteIndex() < int(ch->noteData.size()));
        myassert(ch->isValidChunk(ze.midChunk()));
        AnalysisData *data = ch->dataAtChunk(ze.midChunk());
        //double avgNote = ch->noteData[ze.noteIndex()].avgNote();
        //printf("avgFreq = %f, ", ch->noteData[ze.noteIndex].avgFreq());
        //printf("numPeriods = %f, ", ch->noteData[ze.noteIndex].numPeriods());
        //printf("noteLength = %f\n", ch->noteData[ze.noteIndex].noteLength());
        //y2 = height() - 1 - toInt((avgNote+0.5) / zoomY) + viewBottomOffset;
        //y3 = height() - 1 - toInt((avgNote-0.5) / zoomY) + viewBottomOffset;
        //y2 = height() - 1 - toInt((data->shortTermMean + data->shortTermDeviation) / zoomY) + viewBottomOffset;
        //y3 = height() - 1 - toInt((data->shortTermMean - data->shortTermDeviation) / zoomY) + viewBottomOffset;

        if(gdata->showMeanVarianceBars()) {
          //longTermMean bars
          y2 = height() - 1 - toInt((data->getLongTermMean() + data->getLongTermDeviation()) / zoomY) + viewBottomOffset;
          y3 = height() - 1 - toInt((data->getLongTermMean() - data->getLongTermDeviation()) / zoomY) + viewBottomOffset;
          if(ze.noteIndex() % 2 == 0) {
            evenMidPoints.setPoint(evenMidPointIndex++, n, y2);
            evenMidPoints.setPoint(evenMidPointIndex++, n, y3);
          } else {
            oddMidPoints.setPoint(oddMidPointIndex++, n, y2);
            oddMidPoints.setPoint(oddMidPointIndex++, n, y3);
          }
  
          //shortTermMean bars
          y2 = height() - 1 - toInt((data->getShortTermMean() + data->getShortTermDeviation()) / zoomY) + viewBottomOffset;
          y3 = height() - 1 - toInt((data->getShortTermMean() - data->getShortTermDeviation()) / zoomY) + viewBottomOffset;
          if(ze.noteIndex() % 2 == 0) {
            evenMidPoints2.setPoint(evenMidPointIndex2++, n, y2);
            evenMidPoints2.setPoint(evenMidPointIndex2++, n, y3);
          } else {
            oddMidPoints2.setPoint(oddMidPointIndex2++, n, y2);
            oddMidPoints2.setPoint(oddMidPointIndex2++, n, y3);
          }
        }
      //} else {
      //  y2 = y3 = 0;
      }
      //topPoints.setPoint(pointIndex, n, 0);
      //topPoints.setPoint(pointIndex, n, y);
      bottomPoints.setPoint(pointIndex++, n, y);
      bottomPoints.setPoint(pointIndex++, n, height());
      lastN = n;
    }
    //p.setPen(gdata->shading1Color());
    //p.drawLineSegments(topPoints, 0, pointIndex/2);
    p.setPen(Qt::NoPen);
    p.setBrush(gdata->shading1Color());
    p.drawRect(firstN, 0, lastN, height());
    p.setPen(gdata->shading2Color());
    //p.drawLineSegments(bottomPoints, 0, pointIndex/2);
    if(pointIndex > 1) p.drawLines(bottomPoints.constData(), pointIndex/2);

    if(gdata->showMeanVarianceBars()) {
      //shortTermMean bars
      p.setPen(Qt::green);
      //p.drawLineSegments(evenMidPoints2, 0, evenMidPointIndex2/2);
      if(evenMidPointIndex2 > 1) p.drawLines(evenMidPoints2.constData(), evenMidPointIndex2/2);
      p.setPen(Qt::yellow);
      //p.drawLineSegments(oddMidPoints2, 0, oddMidPointIndex2/2);
      if(oddMidPointIndex2 > 1) p.drawLines(oddMidPoints2.constData(), oddMidPointIndex2/2);

      //longTermMean bars
      p.setPen(Qt::yellow);
      //p.drawLineSegments(evenMidPoints, 0, evenMidPointIndex/2);
      if(evenMidPointIndex > 1) p.drawLines(evenMidPoints.constData(), evenMidPointIndex/2);
      p.setPen(Qt::green);
      //p.drawLineSegments(oddMidPoints, 0, oddMidPointIndex/2);
      if(oddMidPointIndex > 1) p.drawLines(oddMidPoints.constData(), oddMidPointIndex/2);
    }
  } else { // More pixels than samples
    float err = 0.0;
    float pitch = 0.0;
    int intChunk = (int) floor(frameTime); // Integer version of frame time
    if(intChunk < 0) intChunk = 0;
    double stepSize = 1.0 / baseX; // So we skip some pixels
    int x = 0, y, y2, y3;
  
    //double start = 0 - stepSize;
    double start = (double(intChunk) - frameTime) * stepSize;
    double stop = width() + (2 * stepSize);
    //int squareSize = (int(sqrt(stepSize)) / 2) * 2 + 1; //make it an odd number
    //int halfSquareSize = squareSize/2;
    //QPointArray topPoints(0);
    //QPointArray bottomPoints(0);
    //int pointIndex = 0;
    //topPoints.putPoints(pointIndex, 1, toInt(start), 0);
    //bottomPoints.putPoints(pointIndex, 1, toInt(start), height());
    //pointIndex++;
    //topPoints.setPoint(pointIndex, toInt(start), 0);
    bottomPoints.setPoint(pointIndex++, toInt(start), height());
    lastN = firstN = toInt(start);
    for (double n = start; n < stop && intChunk < (int)ch->totalChunks(); n += stepSize, intChunk++) {
      myassert(intChunk >= 0);
      //if (intChunk < 0) continue; // So we don't go off the beginning of the array
      AnalysisData *data = ch->dataAtChunk(intChunk);
      err = data->getCorrelation();
      //if (err >= CERTAIN_THRESHOLD) {
      
      //float val = MIN(ch->dataAtChunk(intChunk)->volumeValue, 1.0);
      if(gdata->pitchContourMode() == 0)
        //p.setPen(QPen(colorBetween(colorGroup().background(), ch->color, err*2.0-1.0), lineWidth));
        //p.setPen(QPen(colorBetween(gdata->backgroundColor(),  ch->color, err*sqrt(data->rms)*10.0), lineWidth));
        p.setPen(QPen(colorBetween(QColor(255, 255, 255), ch->color, err * dB2ViewVal(data->getLogRms())), lineWidth));
      else
        p.setPen(QPen(ch->color, lineWidth));
      
      x = toInt(n);
      lastN = x;
      //note = (data->isValid()) ? data->note : 0.0f;
      //note = (ch->isVisibleNote(data->noteIndex)) ? data->note : 0.0f;
      pitch = (ch->isVisibleChunk(data)) ? data->getPitch() : 0.0f;
      //if(ch->isVisibleChunk(data)) {
      if(data->getNoteIndex() >= 0) {
        isNoteRectEven[rectIndex] = (data->getNoteIndex() % 2) == 0;
        //note = data->note;
        //double avgNote = ch->noteData[data->noteIndex].avgNote();
        //y2 = height() - 1 - toInt((avgNote+0.5) / zoomY) + viewBottomOffset;
        //y3 = height() - 1 - toInt((avgNote-0.5) / zoomY) + viewBottomOffset;
        //y2 = height() - 1 - toInt((data->shortTermMean + data->shortTermDeviation) / zoomY) + viewBottomOffset;
        //y3 = height() - 1 - toInt((data->shortTermMean - data->shortTermDeviation) / zoomY) + viewBottomOffset;

        if(gdata->showMeanVarianceBars()) {
          //longTermMean bars
          y2 = height() - 1 - toInt((data->getLongTermMean() + data->getLongTermDeviation()) / zoomY) + viewBottomOffset;
          y3 = height() - 1 - toInt((data->getLongTermMean() - data->getLongTermDeviation()) / zoomY) + viewBottomOffset;
          noteRect[rectIndex].setLeft(x);
          noteRect[rectIndex].setRight(toInt(n+stepSize));
          noteRect[rectIndex].setTop(y2);
          noteRect[rectIndex++].setBottom(y3);
  
          //shortTermMean bars
          y2 = height() - 1 - toInt((data->getShortTermMean() + data->getShortTermDeviation()) / zoomY) + viewBottomOffset;
          y3 = height() - 1 - toInt((data->getShortTermMean() - data->getShortTermDeviation()) / zoomY) + viewBottomOffset;
          noteRect2[rectIndex2].setLeft(x);
          noteRect2[rectIndex2].setRight(toInt(n+stepSize));
          noteRect2[rectIndex2].setTop(y2);
          noteRect2[rectIndex2++].setBottom(y3);
        }
      //} else {
      //  note = 0.0f;
      }
      myassert(pitch >= 0.0 && pitch <= gdata->topPitch());
      //note = bound(note, 0, gdata->topNote());
      y = height() - 1 - toInt(pitch / zoomY) + viewBottomOffset;
      //y = height() - 1 - int((note / zoomY) - (viewBottom / zoomY));
      //topPoints.putPoints(pointIndex, 1, x, y);
      //bottomPoints.putPoints(pointIndex, 1, x, y);
      //pointIndex++;
      //topPoints.setPoint(pointIndex, x, y);
      bottomPoints.setPoint(pointIndex++, x, y);
    }
    //topPoints.putPoints(pointIndex, 1, topPoints.point(pointIndex-1).x(), 0);
    //bottomPoints.putPoints(pointIndex, 1, bottomPoints.point(pointIndex-1).x(), height());
    //pointIndex++;
    //topPoints.setPoint(pointIndex, topPoints.point(pointIndex-1).x(), 0);
    bottomPoints.setPoint(pointIndex, bottomPoints.point(pointIndex-1).x(), height());
    pointIndex++;

    //p.setPen(gdata->shading1Color());
    //p.setBrush(gdata->shading1Color());
    //p.drawPolygon(topPoints);
    //p.setPen(gdata->shading2Color());
    //p.setBrush(gdata->shading2Color());
    //p.drawPolygon(bottomPoints);
  
    myassert(pointIndex <= width()*2);
    //p.setPen(gdata->shading1Color());
    p.setPen(Qt::NoPen);
    p.setBrush(gdata->shading1Color());
    //p.drawPolygon(topPoints, false, 0, pointIndex);
    p.drawRect(firstN, 0, lastN, height());
    //p.setPen(gdata->shading2Color());
    p.setBrush(gdata->shading2Color());
    //p.drawPolygon(bottomPoints, false, 0, pointIndex);
    p.drawPolygon(bottomPoints.constData(), pointIndex, Qt::OddEvenFill);

    if(gdata->showMeanVarianceBars()) {
      //shortTermMean bars
      for(int j=0; j<rectIndex2; j++) {
        if(isNoteRectEven[j]) p.setBrush(Qt::green);
        else p.setBrush(Qt::yellow);
        p.drawRect(noteRect2[j]);
      }
      //longTermMean bars
      QColor seeThroughYellow = Qt::yellow;
      seeThroughYellow.setAlpha(255);
      QColor seeThroughGreen = Qt::green;
      seeThroughGreen.setAlpha(255);
      for(int j=0; j<rectIndex; j++) {
        //if(isNoteRectEven[j]) p.setBrush(QBrush(Qt::yellow, Qt::Dense3Pattern));
        //else p.setBrush(QBrush(Qt::green, Qt::Dense3Pattern));
        if(isNoteRectEven[j]) p.setBrush(seeThroughYellow);
        else p.setBrush(seeThroughGreen);
        p.drawRect(noteRect[j]);
      }
    }
  }
}
Beispiel #16
0
void Histogram::setColor( const QColor &color )
{
    QColor c = color;
    c.setAlpha( 180 );
    setBrush( QBrush( c ) );
}
Beispiel #17
0
void TrackGraphicItem_v4::paint(QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget)
{
Q_UNUSED(option)
   //! get data
   const int width       = _width < 530 ? 530 : _width;
   const int title_width = _width < 530 ? 150 : (_width - 150)/3;

   //! Get color for state
   QColor c = QApplication::palette().color(QPalette::Normal,QPalette::Highlight);

   if(isSelected())
   {
     opt.state |= QStyle::State_Selected;
     opt.palette.setColor(QPalette::Normal, QPalette::Highlight, c);
   }
   else if (opt.state & QStyle::State_MouseOver) {
     opt.state |= QStyle::State_Selected;
     c.setAlpha(100);
     opt.palette.setColor(QPalette::Normal, QPalette::Highlight, c);
   }
   else {
     opt.state &= ~QStyle::State_Selected;
   }

   //! Draw frame for State_HasFocus item
   opt.rect = boundingRect().toRect();
   UTIL::getStyle()->drawControl(QStyle::CE_ItemViewItem, &opt, painter, widget);

   if(!media)
   {
     painter->setPen( opt.palette.color ( isSelected() ? QPalette::Normal : QPalette::Disabled, isSelected() ? QPalette::HighlightedText : QPalette::WindowText) );
     painter->setFont(opt.font);

     const QString name_elided = opt.fontMetrics.elidedText ( m_path, Qt::ElideRight, width -20);
     painter->drawText(QRect(30, 0,  width -20, 22), Qt::AlignLeft | Qt::AlignVCenter, name_elided);
   }    
   else
   {
      bool isTrack       = (media->type() == TYPE_TRACK) ? true : false;
      //! TRACK in collection
      if(isTrack /*&& media->id != -1*/)
      {
        painter->setPen(opt.palette.color ( QPalette::Normal, isSelected() ? QPalette::HighlightedText : QPalette::WindowText));

        painter->setFont(opt.font);

        //! paint artist name
        const QString artist_elided = opt.fontMetrics.elidedText ( media->artist, Qt::ElideRight, title_width);
        painter->drawText(QRect(30, 0, title_width-50, 22), Qt::AlignLeft | Qt::AlignVCenter,artist_elided);

        //! paint album name
        const QString album_elided = opt.fontMetrics.elidedText ( media->album, Qt::ElideRight, title_width);
        painter->drawText(QRect(60+title_width-50, 0, title_width, 22), Qt::AlignLeft | Qt::AlignVCenter,album_elided);

        //! paint track name
        const QString title_elided = opt.fontMetrics.elidedText ( media->title, Qt::ElideRight, title_width);
        painter->drawText(QRect(60+title_width*2-50, 0, title_width, 22), Qt::AlignLeft | Qt::AlignVCenter,title_elided);

        //! paint track duration
        const QString duree_elided = opt.fontMetrics.elidedText ( media->durationToString(), Qt::ElideRight, 50);
        painter->drawText(QRect(60+title_width*3-50, 0, 50, 22), Qt::AlignRight | Qt::AlignVCenter,duree_elided);

        //! paint track rating
        const float rating_ = media->rating;
        RatingPainter::instance()->Paint(painter, QRect(title_width*3-50 + 115, 0, 80, 22), rating_ , true);
      }
      else {
        painter->setPen( opt.palette.color ( isSelected() ? QPalette::Normal : QPalette::Disabled, isSelected() ? QPalette::HighlightedText : QPalette::WindowText) );
        painter->setFont(opt.font);

        const QString name_elided = opt.fontMetrics.elidedText ( media->url, Qt::ElideRight, width -20);
        painter->drawText(QRect(30, 0,  width -20, 22), Qt::AlignLeft | Qt::AlignVCenter, name_elided);
      }
      
      //! paint activated item
      if(media->isPlaying)
        UTIL::drawPlayingIcon(painter,18, 1, QPoint(5,2));
      else if(media->isBroken)
        painter->drawPixmap(1, 1, QPixmap(":/images/media-broken-18x18.png"));
      else if (!isTrack)
        painter->drawPixmap(1, 1, QPixmap(":/images/files-18x18.png"));      
   }



}
void PropertyEditorView::changeValue(const QString &name)
{
    PropertyName propertyName = name.toUtf8();

    if (propertyName.isNull())
        return;

    if (m_locked)
        return;

    if (propertyName == "type")
        return;

    if (!m_selectedNode.isValid())
        return;

    if (propertyName == "id") {
        PropertyEditorValue *value = m_qmlBackEndForCurrentType->propertyValueForName(propertyName);
        const QString newId = value->value().toString();

        if (newId == m_selectedNode.id())
            return;

        if (m_selectedNode.isValidId(newId)  && !hasId(newId)) {
            m_selectedNode.setIdWithRefactoring(newId);
        } else {
            m_locked = true;
            value->setValue(m_selectedNode.id());
            m_locked = false;
            if (!m_selectedNode.isValidId(newId))
                Core::AsynchronousMessageBox::warning(tr("Invalid Id"),  tr("%1 is an invalid id.").arg(newId));
            else
                Core::AsynchronousMessageBox::warning(tr("Invalid Id"),  tr("%1 already exists.").arg(newId));
        }
        return;
    }

    PropertyName underscoreName(propertyName);
    underscoreName.replace('.', '_');
    PropertyEditorValue *value = m_qmlBackEndForCurrentType->propertyValueForName(underscoreName);

    if (value ==0)
        return;

    QmlObjectNode qmlObjectNode(m_selectedNode);

    QVariant castedValue;

    if (qmlObjectNode.modelNode().metaInfo().isValid() && qmlObjectNode.modelNode().metaInfo().hasProperty(propertyName)) {
        castedValue = qmlObjectNode.modelNode().metaInfo().propertyCastedValue(propertyName, value->value());
    } else if (propertyIsAttachedLayoutProperty(propertyName)) {
        castedValue = value->value();
    } else {
        qWarning() << "PropertyEditor:" <<propertyName << "cannot be casted (metainfo)";
        return ;
    }

    if (value->value().isValid() && !castedValue.isValid()) {
        qWarning() << "PropertyEditor:" << propertyName << "not properly casted (metainfo)";
        return ;
    }

    if (qmlObjectNode.modelNode().metaInfo().isValid() && qmlObjectNode.modelNode().metaInfo().hasProperty(propertyName))
        if (qmlObjectNode.modelNode().metaInfo().propertyTypeName(propertyName) == "QUrl"
                || qmlObjectNode.modelNode().metaInfo().propertyTypeName(propertyName) == "url") { //turn absolute local file paths into relative paths
            QString filePath = castedValue.toUrl().toString();
        if (QFileInfo(filePath).exists() && QFileInfo(filePath).isAbsolute()) {
            QDir fileDir(QFileInfo(model()->fileUrl().toLocalFile()).absolutePath());
            castedValue = QUrl(fileDir.relativeFilePath(filePath));
        }
    }

        if (castedValue.type() == QVariant::Color) {
            QColor color = castedValue.value<QColor>();
            QColor newColor = QColor(color.name());
            newColor.setAlpha(color.alpha());
            castedValue = QVariant(newColor);
        }

        try {
            if (!value->value().isValid()) { //reset
                qmlObjectNode.removeProperty(propertyName);
            } else {
                if (castedValue.isValid() && !castedValue.isNull()) {
                    m_locked = true;
                    qmlObjectNode.setVariantProperty(propertyName, castedValue);
                    m_locked = false;
                }
            }
        }
        catch (const RewritingException &e) {
            e.showException();
        }
}
Beispiel #19
0
void setScale (NV_FLOAT32 actual_min, NV_FLOAT32 actual_max, NV_FLOAT32 attr_min, NV_FLOAT32 attr_max, MISC *misc, OPTIONS *options, NV_BOOL min_lock,
               NV_BOOL max_lock)
{
  //  Set the scale colors for the current range.

  NV_FLOAT32 numshades = (NV_FLOAT32) (NUMSHADES - 1);
  NV_FLOAT32 inc = 1.0, min_z, max_z, range;
  NV_FLOAT32 value = 0.0;


  min_z = actual_min;
  max_z = actual_max;


  //  Color by uncertainty/attribute

  if (options->color_index == 2 || options->color_index == 3 || (options->color_index >= PRE_ATTR && options->color_index < PRE_ATTR + 10))
    {
      min_z = attr_min;
      max_z = attr_max;
    }

  range = max_z - min_z;

  if (fabs (range) < 0.0000001) range = 1.0;

  inc = range / (NV_FLOAT32) (NUM_SCALE_LEVELS - 1);


  for (NV_INT32 i = 0 ; i < NUM_SCALE_LEVELS ; i++)
    {
      value = min_z + (NV_FLOAT32) i * inc;

      NV_INT32 c_index = 0;


      //  Color by depth

      if (!options->color_index)
        {
          c_index = NINT (numshades - ((value) - misc->color_min_z) / misc->color_range_z * numshades);
        }


      //  Color by uncertainty or attribute

      else if (options->color_index == 2 || options->color_index == 3 || (options->color_index >= PRE_ATTR && options->color_index < PRE_ATTR + 10))
        {
          c_index = NINT (numshades - (value - misc->attr_color_min) / misc->attr_color_range * numshades);
        }


      //  Check for out of range values (this is the easy way to work the locked color scale.

      if (c_index < 0) c_index = 0;
      if (c_index > NUMSHADES - 1) c_index = NUMSHADES - 1;


      //  Blank out the scale if we're coloring by line.

      if (options->color_index == 1)
        {
          misc->scale[i]->setContents (Qt::white, 99999.99);
        }
      else
        {
          //  If we've locked the first or last scaleBox, set the flag to draw the lock image.

          NV_INT32 lock = 0;

          if (!i)
            {
              if (!options->color_index)
                {
                  if (min_lock)
                    {
                      lock = 1;
                    }
                  else
                    {
                      lock = -1;
                    }
                }
              else
                {
                  if (max_lock)
                    {
                      lock = 1;
                    }
                  else
                    {
                      lock = -1;
                    }
                }
            }

          if (i == NUM_SCALE_LEVELS - 1)
            {
              if (!options->color_index)
                {
                  if (max_lock)
                    {
                      lock = 1;
                    }
                  else
                    {
                      lock = -1;
                    }
                }
              else
                {
                  if (min_lock)
                    {
                      lock = 1;
                    }
                  else
                    {
                      lock = -1;
                    }
                }
            }

          QColor clr;
          clr.setRed (misc->color_array[0][c_index][0]);
          clr.setGreen (misc->color_array[0][c_index][1]);
          clr.setBlue (misc->color_array[0][c_index][2]);
          clr.setAlpha (misc->color_array[0][c_index][3]);
          if (!options->color_index)
            {
              misc->scale[(NUM_SCALE_LEVELS - 1) - i]->setContents (clr, -value, lock);
            }
          else
            {
              misc->scale[(NUM_SCALE_LEVELS - 1) - i]->setContents (clr, value, lock);
            }
        }
    }
}
std::unique_ptr<QgsMarkerSymbolLayer> backgroundToMarkerLayer( const QgsTextBackgroundSettings &settings )
{
  std::unique_ptr<QgsMarkerSymbolLayer> layer;
  switch ( settings.type() )
  {
    case QgsTextBackgroundSettings::ShapeSVG:
    {
      QgsSvgMarkerSymbolLayer *svg = new QgsSvgMarkerSymbolLayer( settings.svgFile() );
      svg->setStrokeWidth( settings.strokeWidth() );
      svg->setStrokeWidthUnit( settings.strokeWidthUnit() );
      layer.reset( svg );
      break;
    }
    case QgsTextBackgroundSettings::ShapeCircle:
    case QgsTextBackgroundSettings::ShapeEllipse:
    case QgsTextBackgroundSettings::ShapeRectangle:
    case QgsTextBackgroundSettings::ShapeSquare:
    {
      QgsSimpleMarkerSymbolLayer *marker = new QgsSimpleMarkerSymbolLayer();
      // default value
      QgsSimpleMarkerSymbolLayerBase::Shape shape = QgsSimpleMarkerSymbolLayerBase::Diamond;
      switch ( settings.type() )
      {
        case QgsTextBackgroundSettings::ShapeCircle:
        case QgsTextBackgroundSettings::ShapeEllipse:
          shape = QgsSimpleMarkerSymbolLayerBase::Circle;
          break;
        case QgsTextBackgroundSettings::ShapeRectangle:
        case QgsTextBackgroundSettings::ShapeSquare:
          shape = QgsSimpleMarkerSymbolLayerBase::Square;
          break;
        case QgsTextBackgroundSettings::ShapeSVG:
          break;
      }

      marker->setShape( shape );
      marker->setStrokeWidth( settings.strokeWidth() );
      marker->setStrokeWidthUnit( settings.strokeWidthUnit() );
      layer.reset( marker );
    }
  }
  layer->setEnabled( true );
  // a marker does not have a size x and y, just a size (and it should be at least one)
  QSizeF size = settings.size();
  layer->setSize( std::max( 1., std::max( size.width(), size.height() ) ) );
  layer->setSizeUnit( settings.sizeUnit() );
  // fill and stroke
  QColor fillColor = settings.fillColor();
  QColor strokeColor = settings.strokeColor();
  if ( settings.opacity() < 1 )
  {
    int alpha = std::round( settings.opacity() * 255 );
    fillColor.setAlpha( alpha );
    strokeColor.setAlpha( alpha );
  }
  layer->setFillColor( fillColor );
  layer->setStrokeColor( strokeColor );
  // rotation
  if ( settings.rotationType() == QgsTextBackgroundSettings::RotationFixed )
  {
    layer->setAngle( settings.rotation() );
  }
  // offset
  layer->setOffset( settings.offset() );
  layer->setOffsetUnit( settings.offsetUnit() );

  return layer;
}
bool KTPaletteParser::startTag(const QString &tag, const QXmlAttributes &atts)
{
    if (root() == "Palette") {
        if (tag == root()) {
            k->paletteName = atts.value("name");
            if (atts.value("editable") == "true")
                k->isEditable = true;
            else
                k->isEditable = false;
        } else if (tag == "Color") {
                   QColor c = QColor(atts.value("colorName"));
                   c.setAlpha( atts.value("alpha").toInt() );

                   if (c.isValid()) {
                       k->brushes << c;
                   } else {
                    #ifdef K_DEBUG
		           kError() << "Invalid Color";
                    #endif
                   }
        } else if (tag == "Gradient") {
                   if (k->gradient) 
                       delete k->gradient;

                   k->gradient = 0;
                   k->gradientStops.clear();

                   QGradient::Type type = QGradient::Type(atts.value("type").toInt());
                   QGradient::Spread spread = QGradient::Spread(atts.value("spread").toInt());

                   switch (type) {
                           case QGradient::LinearGradient:
                             {
                               k->gradient = new QLinearGradient(atts.value("startX").toDouble(),
                                             atts.value("startY").toDouble(),atts.value("finalX").toDouble(), 
                                             atts.value("finalY").toDouble());
                             }
                             break;
                           case QGradient::RadialGradient:
                             {
                               k->gradient = new QRadialGradient(atts.value("centerX").toDouble(),
                                             atts.value("centerY").toDouble(), atts.value("radius").toDouble(),
                                             atts.value("focalX").toDouble(),atts.value("focalY").toDouble() );
                             }
                             break;
                           case QGradient::ConicalGradient:
                             {
                               k->gradient = new QConicalGradient(atts.value("centerX").toDouble(),
                                             atts.value("centerY").toDouble(),atts.value("angle").toDouble());
                             }
                             break;
                           default:
                             {
                               #ifdef K_DEBUG
                                      kFatal() << "No gradient type: " << type;
                               #endif
                             }
                           break;
                   }
                   k->gradient->setSpread(spread);
        } else if (tag == "Stop") {
                   QColor c(atts.value("colorName") );
                   c.setAlpha(atts.value("alpha").toInt() );
                   k->gradientStops << qMakePair(atts.value("value").toDouble(), c);	
        }
     }

     return true;
}
QgsPalettedRasterRenderer::ClassData QgsPalettedRasterRenderer::classDataFromString( const QString &string )
{
  QgsPalettedRasterRenderer::ClassData classes;

  QRegularExpression linePartRx( QStringLiteral( "[\\s,:]+" ) );

  QStringList parts = string.split( '\n', QString::SkipEmptyParts );
  Q_FOREACH ( const QString &part, parts )
  {
    QStringList lineParts = part.split( linePartRx, QString::SkipEmptyParts );
    bool ok = false;
    switch ( lineParts.count() )
    {
      case 1:
      {
        int value = lineParts.at( 0 ).toInt( &ok );
        if ( !ok )
          continue;

        classes << Class( value );
        break;
      }

      case 2:
      {
        int value = lineParts.at( 0 ).toInt( &ok );
        if ( !ok )
          continue;

        QColor c( lineParts.at( 1 ) );

        classes << Class( value, c );
        break;
      }

      default:
      {
        if ( lineParts.count() < 4 )
          continue;

        int value = lineParts.at( 0 ).toInt( &ok );
        if ( !ok )
          continue;

        bool rOk = false;
        double r = lineParts.at( 1 ).toDouble( &rOk );
        bool gOk = false;
        double g = lineParts.at( 2 ).toDouble( &gOk );
        bool bOk = false;
        double b = lineParts.at( 3 ).toDouble( &bOk );

        QColor c;
        if ( rOk && gOk && bOk )
        {
          c = QColor( r, g, b );
        }

        if ( lineParts.count() >= 5 )
        {
          double alpha = lineParts.at( 4 ).toDouble( &ok );
          if ( ok )
            c.setAlpha( alpha );
        }

        QString label;
        if ( lineParts.count() > 5 )
        {
          label = lineParts.mid( 5 ).join( ' ' );
        }

        classes << Class( value, c, label );
        break;
      }
    }

  }
void
Style::drawGroupBox(const QStyleOptionComplex *option, QPainter *painter, const QWidget *widget) const
{
    ASSURE_OPTION(groupBox, GroupBox);
    OPT_ENABLED

    // Frame
    if (groupBox->subControls & QStyle::SC_GroupBoxFrame)
    {
        QStyleOptionFrameV2 frame;
        frame.QStyleOption::operator=(*groupBox);
        frame.features = groupBox->features;
        frame.lineWidth = groupBox->lineWidth;
        frame.midLineWidth = groupBox->midLineWidth;
        frame.rect = subControlRect(CC_GroupBox, option, SC_GroupBoxFrame, widget);
        drawGroupBoxFrame(&frame, painter, widget);
    }

    // Title
    if ((groupBox->subControls & QStyle::SC_GroupBoxLabel) && !groupBox->text.isEmpty())
    {
        QColor textColor = groupBox->textColor;
        QPalette::ColorRole role = QPalette::WindowText;
        // NOTICE, WORKAROUND: groupBox->textColor is black by def. and should be invalid - but it's not
        // so assuming everything is optimized for a black on white world, we assume the
        // CUSTOM groupBox->textColor to be only valid if it's != Qt::black
        // THIS IS A HACK!
        if (textColor.isValid() && textColor != Qt::black)
        {
            if (!isEnabled)
                textColor.setAlpha(48);
            painter->setPen(textColor);
            role = QPalette::NoRole;
        }
        setTitleFont(painter, groupBox->text, RECT.width());
        QStyleOptionGroupBox copy = *groupBox;
        copy.fontMetrics = QFontMetrics(painter->font());
        QRect textRect = subControlRect(CC_GroupBox, &copy, SC_GroupBoxLabel, widget);
        drawItemText(painter, textRect, BESPIN_MNEMONIC, groupBox->palette, isEnabled, groupBox->text, role);
        if (groupBox->features & QStyleOptionFrameV2::Flat)
        {
            Tile::PosFlags pf = Tile::Center;
            if (option->direction == Qt::LeftToRight)
            {
                textRect.setLeft(RECT.left());
                textRect.setRight(textRect.right() + (RECT.right()-textRect.right())/2);
                pf |= Tile::Right;
            }
            else
            {
                textRect.setRight(RECT.right());
                textRect.setLeft(textRect.left() - (textRect.left() - RECT.left())/2);
                pf |= Tile::Left;
            }
            shadows.line[0][Sunken].render(textRect, painter, pf, true);

//             const int x = textRect.right();
//             textRect.setRight(RECT.right()); textRect.setLeft(x);
//             shadows.line[0][Sunken].render(textRect, painter, Tile::Center | Tile::Right, true);
        }
        else if (config.groupBoxMode)
        {
            const int x = textRect.width()/8;
            textRect.adjust(x,0,-x,0);
            shadows.line[0][Sunken].render(textRect, painter, Tile::Full, true);
        }
    }

    // Checkbox
    // TODO: doesn't hover - yet.
    if (groupBox->subControls & SC_GroupBoxCheckBox)
    {
        QStyleOptionButton box;
        box.QStyleOption::operator=(*groupBox);
        box.rect = subControlRect(CC_GroupBox, option, SC_GroupBoxCheckBox, widget);
//       box.state |= State_HasFocus; // focus to signal this to the user
        if (groupBox->activeSubControls & SC_GroupBoxCheckBox)
            box.state |= State_MouseOver;
        drawRadio(&box, painter, 0L);
    }
}
Beispiel #24
0
/*
The ultimate line painting function.
Currently missing features:
- draw indent lines
*/
void KateRenderer::paintTextLine(QPainter& paint, KateLineLayoutPtr range, int xStart, int xEnd, const KTextEditor::Cursor* cursor)
{
  Q_ASSERT(range->isValid());

//   kDebug( 13033 )<<"KateRenderer::paintTextLine";

  // font data
  const QFontMetricsF &fm = config()->fontMetrics();

  int currentViewLine = -1;
  if (cursor && cursor->line() == range->line())
    currentViewLine = range->viewLineForColumn(cursor->column());

  paintTextLineBackground(paint, range, currentViewLine, xStart, xEnd);

  if (range->layout()) {
    bool drawSelection = m_view->selection() && showSelections() && m_view->selectionRange().overlapsLine(range->line());
    // Draw selection in block selecton mode. We need 2 kinds of selections that QTextLayout::draw can't render:
    //   - past-end-of-line selection and
    //   - 0-column-wide selection (used to indicate where text will be typed)
    if (drawSelection && m_view->blockSelection()) {
      int selectionStartColumn = m_doc->fromVirtualColumn(range->line(), m_doc->toVirtualColumn(m_view->selectionRange().start()));
      int selectionEndColumn   = m_doc->fromVirtualColumn(range->line(), m_doc->toVirtualColumn(m_view->selectionRange().end()));
      QBrush selectionBrush = config()->selectionColor();
      if (selectionStartColumn != selectionEndColumn) {
        KateTextLayout lastLine = range->viewLine(range->viewLineCount() - 1);
        if (selectionEndColumn > lastLine.startCol()) {
          int selectionStartX = (selectionStartColumn > lastLine.startCol()) ? cursorToX(lastLine, selectionStartColumn, true) : 0;
          int selectionEndX = cursorToX(lastLine, selectionEndColumn, true);
          paint.fillRect(QRect(selectionStartX - xStart, (int)lastLine.lineLayout().y(), selectionEndX - selectionStartX, lineHeight()), selectionBrush);
        }
      } else {
        const int selectStickWidth = 2;
        KateTextLayout selectionLine = range->viewLine(range->viewLineForColumn(selectionStartColumn));
        int selectionX = cursorToX(selectionLine, selectionStartColumn, true);
        paint.fillRect(QRect(selectionX - xStart, (int)selectionLine.lineLayout().y(), selectStickWidth, lineHeight()), selectionBrush);
      }
    }

    QVector<QTextLayout::FormatRange> additionalFormats;
    if (range->length() > 0) {
      // We may have changed the pen, be absolutely sure it gets set back to
      // normal foreground color before drawing text for text that does not
      // set the pen color
      paint.setPen(attribute(KTextEditor::HighlightInterface::dsNormal)->foreground().color());
      // Draw the text :)
      if (drawSelection) {
        // FIXME toVector() may be a performance issue
        additionalFormats = decorationsForLine(range->textLine(), range->line(), true).toVector();
        range->layout()->draw(&paint, QPoint(-xStart,0), additionalFormats);

      } else {
        range->layout()->draw(&paint, QPoint(-xStart,0));
      }
    }

    QBrush backgroundBrush;
    bool backgroundBrushSet = false;

    // Loop each individual line for additional text decoration etc.
    QListIterator<QTextLayout::FormatRange> it = range->layout()->additionalFormats();
    QVectorIterator<QTextLayout::FormatRange> it2 = additionalFormats;
    for (int i = 0; i < range->viewLineCount(); ++i) {
      KateTextLayout line = range->viewLine(i);

      // Determine the background to use, if any, for the end of this view line
      backgroundBrushSet = false;
      while (it2.hasNext()) {
        const QTextLayout::FormatRange& fr = it2.peekNext();
        if (fr.start > line.endCol())
          break;

        if (fr.start + fr.length > line.endCol()) {
          if (fr.format.hasProperty(QTextFormat::BackgroundBrush)) {
            backgroundBrushSet = true;
            backgroundBrush = fr.format.background();
          }

          goto backgroundDetermined;
        }

        it2.next();
      }

      while (it.hasNext()) {
        const QTextLayout::FormatRange& fr = it.peekNext();
        if (fr.start > line.endCol())
          break;

        if (fr.start + fr.length > line.endCol()) {
          if (fr.format.hasProperty(QTextFormat::BackgroundBrush)) {
            backgroundBrushSet = true;
            backgroundBrush = fr.format.background();
          }

          break;
        }

        it.next();
      }

      backgroundDetermined:

      // Draw selection or background color outside of areas where text is rendered
      if (!m_printerFriendly ) {
        bool draw = false;
        QBrush drawBrush;
        if (m_view->selection() && !m_view->blockSelection() && m_view->lineEndSelected(line.end(true))) {
          draw = true;
          drawBrush = config()->selectionColor();
        } else if (backgroundBrushSet && !m_view->blockSelection()) {
          draw = true;
          drawBrush = backgroundBrush;
        }

        if (draw) {
          int fillStartX = line.endX() - line.startX() + line.xOffset() - xStart;
          int fillStartY = lineHeight() * i;
          int width= xEnd - xStart - fillStartX;
          int height= lineHeight();

          // reverse X for right-aligned lines
          if (range->layout()->textOption().alignment() == Qt::AlignRight)
            fillStartX = 0;

          if (width > 0) {
            QRect area(fillStartX, fillStartY, width, height);
            paint.fillRect(area, drawBrush);
          }
        }
      }
      // Draw indent lines
      if (showIndentLines() && i == 0)
      {
        const qreal w = spaceWidth();
        const int lastIndentColumn = range->textLine()->indentDepth(m_tabWidth);

        for (int x = m_indentWidth; x < lastIndentColumn; x += m_indentWidth)
        {
          paintIndentMarker(paint, x * w + 1 - xStart, range->line());
        }
      }

      // draw an open box to mark non-breaking spaces
      const QString& text = range->textLine()->string();
      int y = lineHeight() * i + fm.ascent() - fm.strikeOutPos();
      int nbSpaceIndex = text.indexOf(nbSpaceChar, line.lineLayout().xToCursor(xStart));

      while (nbSpaceIndex != -1 && nbSpaceIndex < line.endCol()) {
        int x = line.lineLayout().cursorToX(nbSpaceIndex);
        if (x > xEnd)
          break;
        paintNonBreakSpace(paint, x - xStart, y);
        nbSpaceIndex = text.indexOf(nbSpaceChar, nbSpaceIndex + 1);
      }

      // draw tab stop indicators
      if (showTabs()) {
        int tabIndex = text.indexOf(tabChar, line.lineLayout().xToCursor(xStart));
        while (tabIndex != -1 && tabIndex < line.endCol()) {
          int x = line.lineLayout().cursorToX(tabIndex);
          if (x > xEnd)
            break;
          paintTabstop(paint, x - xStart + spaceWidth()/2.0, y);
          tabIndex = text.indexOf(tabChar, tabIndex + 1);
        }
      }

      // draw trailing spaces
      if (showTrailingSpaces()) {
        int spaceIndex = line.endCol() - 1;
        int trailingPos = range->textLine()->lastChar();
        if (trailingPos < 0)
          trailingPos = 0;
        if (spaceIndex >= trailingPos) {
          while (spaceIndex >= line.startCol() && text.at(spaceIndex).isSpace()) {
            if (text.at(spaceIndex) != '\t' || !showTabs())
              paintTrailingSpace(paint, line.lineLayout().cursorToX(spaceIndex) - xStart + spaceWidth()/2.0, y);
            --spaceIndex;
          }
        }
      }
    }

    // draw word-wrap-honor-indent filling
    if ( (range->viewLineCount() > 1)  && range->shiftX() && (range->shiftX() > xStart) )
    {
      if (backgroundBrushSet)
        paint.fillRect(0, lineHeight(), range->shiftX() - xStart, lineHeight() * (range->viewLineCount() - 1),
          backgroundBrush);
      paint.fillRect(0, lineHeight(), range->shiftX() - xStart, lineHeight() * (range->viewLineCount() - 1),
        QBrush(config()->wordWrapMarkerColor(), Qt::Dense4Pattern));
    }

    // Draw caret
    if (drawCaret() && cursor && range->includesCursor(*cursor)) {
      int caretWidth, lineWidth = 2;
      QColor color;
      QTextLine line = range->layout()->lineForTextPosition(qMin(cursor->column(), range->length()));

      // Determine the caret's style
      caretStyles style = caretStyle();

      // Make the caret the desired width
      if (style == Line) {
        caretWidth = lineWidth;
      } else if (line.isValid() && cursor->column() < range->length()) {
        caretWidth = int(line.cursorToX(cursor->column() + 1) - line.cursorToX(cursor->column()));
        if (caretWidth < 0) {
          caretWidth = -caretWidth;
        }
      } else {
        caretWidth = spaceWidth();
      }

      // Determine the color
      if (m_caretOverrideColor.isValid()) {
        // Could actually use the real highlighting system for this...
        // would be slower, but more accurate for corner cases
        color = m_caretOverrideColor;
      } else {
        // search for the FormatRange that includes the cursor
        foreach (const QTextLayout::FormatRange &r, range->layout()->additionalFormats()) {
          if ((r.start <= cursor->column() ) && ( (r.start + r.length)  > cursor->column())) {
            // check for Qt::NoBrush, as the returned color is black() and no invalid QColor
            QBrush foregroundBrush = r.format.foreground();
            if (foregroundBrush != Qt::NoBrush) {
              color = r.format.foreground().color();
            }
            break;
          }
        }
        // still no color found, fall back to default style
        if (!color.isValid())
          color = attribute(KTextEditor::HighlightInterface::dsNormal)->foreground().color();
      }

      // Clip the caret - Qt's caret has a habit of intruding onto other lines.
      paint.save();
      paint.setClipRect(0, line.lineNumber() * lineHeight(), xEnd - xStart, lineHeight());
      switch(style) {
      case Line :
        paint.setPen(QPen(color, caretWidth));
        break;
      case Block :
        // use a gray caret so it's possible to see the character
        color.setAlpha(128);
        paint.setPen(QPen(color, caretWidth));
        break;
      case Underline :
        paint.setClipRect(0, lineHeight() - lineWidth, xEnd - xStart, lineWidth);
        break;
      case Half :
        color.setAlpha(128);
        paint.setPen(QPen(color, caretWidth));
        paint.setClipRect(0, lineHeight() / 2, xEnd - xStart, lineHeight() / 2);
        break;
      }

      if (cursor->column() <= range->length()) {
        range->layout()->drawCursor(&paint, QPoint(-xStart,0), cursor->column(), caretWidth);
      } else {
        // Off the end of the line... must be block mode. Draw the caret ourselves.
        const KateTextLayout& lastLine = range->viewLine(range->viewLineCount() - 1);
        int x = cursorToX(lastLine, KTextEditor::Cursor(range->line(), cursor->column()), true);
        if ((x >= xStart) && (x <= xEnd)) {
          paint.fillRect(x - xStart, (int)lastLine.lineLayout().y(), caretWidth, lineHeight(), color);
        }
      }

      paint.restore();
    }
// TODO margin
void ReplayGainFileListItemDelegate::paint( QPainter *painter, const QStyleOptionViewItem& option, const QModelIndex& index ) const
{
    ReplayGainFileListItem *item =  static_cast<ReplayGainFileListItem*>( index.internalPointer() );

    QColor backgroundColor;

    painter->save();

    QStyleOptionViewItem _option = option;

    bool isProcessing = false;
    bool isSucceeded = false;
    bool isFailed = false;
    if( item )
    {
        switch( item->state )
        {
            case ReplayGainFileListItem::Waiting:
            case ReplayGainFileListItem::WaitingForReplayGain:
            {
                break;
            }
            case ReplayGainFileListItem::Processing:
            {
                isProcessing = true;
                break;
            }
            case ReplayGainFileListItem::Stopped:
            {
                switch( item->returnCode )
                {
                    case ReplayGainFileListItem::Succeeded:
                    case ReplayGainFileListItem::SucceededWithProblems:
                    {
                        isSucceeded = true;
                        break;
                    }
                    case ReplayGainFileListItem::Skipped:
                    case ReplayGainFileListItem::StoppedByUser:
                    {
                        break;
                    }
                    case ReplayGainFileListItem::BackendNeedsConfiguration:
                    case ReplayGainFileListItem::Failed:
                    {
                        isFailed = true;
                        break;
                    }
                }
                break;
            }
        }
    }

    if( isProcessing )
    {
        if( option.state & QStyle::State_Selected )
        {
            backgroundColor = QColor(215,102,102); // hsv:   0, 134, 215
        }
        else
        {
            backgroundColor = QColor(255,234,234); // hsv:   0,  21, 255
        }
    }
    else if( isSucceeded )
    {
        if( option.state & QStyle::State_Selected )
        {
            backgroundColor = QColor(125,205,139); // hsv: 131, 100, 205
        }
        else
        {
            backgroundColor = QColor(234,255,238); // hsv: 131,  21, 255
        }
    }
    else if( isFailed )
    {
        if( option.state & QStyle::State_Selected )
        {
            backgroundColor = QColor(235,154, 49); // hsv:  34, 202, 235
        }
        else
        {
            backgroundColor = QColor(255,204,156); // hsv:  29,  99, 255
        }
    }
    else
    {
        if( option.state & QStyle::State_Selected )
        {
            backgroundColor = option.palette.highlight().color();
        }
        else
        {
            backgroundColor = option.palette.base().color();
        }
    }

    painter->fillRect( option.rect, backgroundColor );

    int m_left, m_top, m_right, m_bottom;
    item->treeWidget()->getContentsMargins( &m_left, &m_top, &m_right, &m_bottom );
    //QRect m_rect = QRect( option.rect.x()+m_left, option.rect.y()+m_top, option.rect.width()-m_left-m_right, option.rect.height()-m_top-m_bottom );
    QRect m_rect = QRect( option.rect.x()+m_left, option.rect.y(), option.rect.width()-m_left-m_right, option.rect.height() );

    QRect textRect = painter->boundingRect( QRect(), Qt::AlignLeft|Qt::TextSingleLine, item->text(index.column()) );

    if ( textRect.width() < m_rect.width() )
    {
        painter->drawText( m_rect, Qt::TextSingleLine|Qt::TextExpandTabs, item->text(index.column()) );
    }
    else
    {
        painter->drawText( m_rect, Qt::AlignRight|Qt::TextSingleLine|Qt::TextExpandTabs, item->text(index.column()) );
        QLinearGradient linearGrad( QPoint(m_rect.x(),0), QPoint(m_rect.x()+15,0) );
        linearGrad.setColorAt( 0, backgroundColor );
        backgroundColor.setAlpha( 0 );
        linearGrad.setColorAt( 1, backgroundColor );
        painter->fillRect( m_rect.x(), m_rect.y(), 15, m_rect.height(), linearGrad );
    }
//     painter->drawText( m_rect, Qt::TextSingleLine|Qt::TextExpandTabs, item->text(index.column()) );

//     QItemDelegate::paint( painter, _option, index );

    painter->restore();

//     int progress = (index.row() != 0 ? 100 / index.row() : 0);
//
//     // draw your cool progress bar here
//     QStyleOptionProgressBar opt;
//     opt.rect = option.rect;
//     opt.minimum = 0;
//     opt.maximum = 100;
//     opt.progress = progress;
//     opt.text = QString("%1%").arg(progress);
//     opt.textVisible = true;
//     QApplication::style()->drawControl(QStyle::CE_ProgressBar, &opt, painter, 0);

    // maybe even let default implementation draw list item contents?
    // QItemDelegate::paint(painter, option, index);
}
Beispiel #26
0
void knob::drawKnob( QPainter * _p )
{
	if( updateAngle() == false && !m_cache.isNull() )
	{
		_p->drawImage( 0, 0, m_cache );
		return;
	}

	m_cache = QImage( size(), QImage::Format_ARGB32 );
	m_cache.fill( qRgba( 0, 0, 0, 0 ) );

	QPainter p( &m_cache );

	QPoint mid;

	if( m_knobNum == knobStyled )
	{
		p.setRenderHint( QPainter::Antialiasing );

		// Perhaps this can move to setOuterRadius()
		if( m_outerColor )
		{
			QRadialGradient gradient( centerPoint(), outerRadius() );
			gradient.setColorAt(0.4, _p->pen().brush().color() );
			gradient.setColorAt(1, *m_outerColor );

			p.setPen( QPen( gradient, lineWidth(),
						Qt::SolidLine, Qt::RoundCap ) );
		}
		else {
			QPen pen = p.pen();
			pen.setWidth( (int) lineWidth() );
			pen.setCapStyle( Qt::RoundCap );

			p.setPen( pen );
		}

		p.drawLine( calculateLine( centerPoint(), outerRadius(),
							innerRadius() ) );
		p.end();
		_p->drawImage( 0, 0, m_cache );
		return;
	}


	// Old-skool knobs
	const float radius = m_knobPixmap->width() / 2.0f - 1;
	mid = QPoint( width() / 2, m_knobPixmap->height() / 2 );

	p.drawPixmap( static_cast<int>(
				width() / 2 - m_knobPixmap->width() / 2 ), 0,
				*m_knobPixmap );

	p.setRenderHint( QPainter::Antialiasing );

	const int centerAngle = angleFromValue( model()->centerValue(), model()->minValue(), model()->maxValue(), m_totalAngle );

	const int arcLineWidth = 2;
	const int arcRectSize = m_knobPixmap->width() - arcLineWidth;

	QColor col;
	if( m_knobNum == knobVintage_32 )
	{	col = QApplication::palette().color( QPalette::Active, QPalette::Shadow ); }
	else
	{	col = QApplication::palette().color( QPalette::Active, QPalette::WindowText ); }
	col.setAlpha( 70 );

	p.setPen( QPen( col, 2 ) );
	p.drawArc( mid.x() - arcRectSize/2, 1, arcRectSize, arcRectSize, 315*16, 16*m_totalAngle );

	switch( m_knobNum )
	{
		case knobSmall_17:
		{
			p.setPen( QPen( QApplication::palette().color( QPalette::Active,
							QPalette::WindowText ), 2 ) );
			p.drawLine( calculateLine( mid, radius-2 ) );
			break;
		}
		case knobBright_26:
		{
			p.setPen( QPen( QApplication::palette().color( QPalette::Active, QPalette::WindowText ), 2 ) );
			p.drawLine( calculateLine( mid, radius-5 ) );
			break;
		}
		case knobDark_28:
		{
			p.setPen( QPen( QApplication::palette().color( QPalette::Active, QPalette::WindowText ), 2 ) );
			const float rb = qMax<float>( ( radius - 10 ) / 3.0,
									0.0 );
			const float re = qMax<float>( ( radius - 4 ), 0.0 );
			QLineF ln = calculateLine( mid, re, rb );
			ln.translate( 1, 1 );
			p.drawLine( ln );
			break;
		}
		case knobGreen_17:
		{
			p.setPen( QPen( QApplication::palette().color( QPalette::Active,
							QPalette::BrightText), 2 ) );
			p.drawLine( calculateLine( mid, radius ) );
			break;
		}
		case knobVintage_32:
		{
			p.setPen( QPen( QApplication::palette().color( QPalette::Active,
							QPalette::Shadow), 2 ) );
			p.drawLine( calculateLine( mid, radius-2, 2 ) );
			break;
		}
	}

	p.drawArc( mid.x() - arcRectSize/2, 1, arcRectSize, arcRectSize, (90-centerAngle)*16, -16*(m_angle-centerAngle) );

	p.end();

	_p->drawImage( 0, 0, m_cache );
}
Beispiel #27
0
QList<ZObject3dScan*> ZFlyEmBodyMergeDoc::extractAllObject()
{
  QList<ZObject3dScan*> objList;

  if (m_originalLabel == NULL) {
    return objList;
  }

  if (m_originalLabel->isEmpty()) {
    return objList;
  }

  ZFlyEmBodyMerger::TLabelMap finalMap = m_bodyMerger.getFinalMap();

  std::map<uint64_t, ZObject3dScan*> bodySet;
  uint64_t *array = m_originalLabel->getDataPointer<uint64_t>();
  int width = m_originalLabel->getDim(0);
  int height = m_originalLabel->getDim(1);
  int depth = m_originalLabel->getDim(2);
  int x0 = m_originalLabel->getStartCoordinate(0);
  int y0 = m_originalLabel->getStartCoordinate(1);
  int z0 = m_originalLabel->getStartCoordinate(2);


  ZObject3dScan *obj = NULL;
  for (int z = 0; z < depth; ++z) {
    for (int y = 0; y < height; ++y) {
      int x = 0;
      while (x < width) {
        uint64_t v = array[x];
        if (finalMap.contains(v)) {
          v = finalMap[v];
        }
        std::map<uint64_t, ZObject3dScan*>::iterator iter = bodySet.find(v);
        if (iter == bodySet.end()) {
          obj = new ZObject3dScan;
          obj->setLabel(v);
          //(*bodySet)[v] = obj;
          bodySet.insert(std::map<uint64_t, ZObject3dScan*>::value_type(v, obj));
        } else {
          obj = iter->second;
        }
        int length = obj->scanArray(array, x, y + y0, z + z0, width, x0);
        x += length;
      }
      array += width;
    }
  }

  for (std::map<uint64_t, ZObject3dScan*>::iterator iter = bodySet.begin();
       iter != bodySet.end(); ++iter) {
    ZObject3dScan *obj = iter->second;
    obj->setRole(ZStackObjectRole::ROLE_SEGMENTATION);
    QColor color = m_objColorSheme.getColor(abs((int) obj->getLabel()));
    color.setAlpha(64);
    obj->setColor(color);
    objList.append(obj);
  }

  return objList;
}
Beispiel #28
0
/**
\param appSplash
\param appName
\param appVersion
**/
BlSplashScreen::BlSplashScreen ( QString appSplash, QString appName, QString appVersion ) : QSplashScreen ()
{

    BL_FUNC_DEBUG

    QFile archivo ( appSplash );
    if ( !archivo.exists() ) {
#ifdef CONFIG_DEBUG
        QString mensaje = "BlSplashScreen: No existe el archivo " + appSplash + "\n";
        fprintf ( stderr, "%s", mensaje.toLatin1().constData() );
#endif
        m_image0 = new QPixmap ( 350, 263 );
        m_image0->fill ( QColor ( QColor ( 150, 150, 200 ) ) );
    } else {
        m_image0 = new QPixmap();
        m_image0->load ( appSplash );
    }// end if

    /// Se modifica la paleta para que utilize la imagen como fondo.
    QPalette p = this->palette();
    m_brush = new QBrush();
    m_brush->setTexture(*m_image0);
    p.setBrush ( QPalette::Window, *m_brush  );
    this->setPalette ( p );

    /// Centramos la ventana en la pantalla.
    QDesktopWidget *pantalla = new QDesktopWidget();
    setGeometry ( ( pantalla->screenGeometry().width() / 2 ) - ( m_image0->width() / 2 ), ( pantalla->screenGeometry().height() / 2 ) - ( ( m_image0->height() + 58 ) / 2 ), m_image0->width(), m_image0->height() );
    delete pantalla;

#ifndef Q_OS_WIN32
    l0 = new QLabel ( this );
    l0->setTextFormat ( Qt::RichText );
    l0->setGeometry ( 0, 0, m_image0->width(), m_image0->height() );
    l0->setAlignment ( Qt::AlignTop );
    l0->setFont ( QFont ( "Arial", 20, QFont::Bold ) );
    l0->setText ( "<center><font size=+1 color=\"#a3ffa3\">" + appName + "</font><br/><font color=\"#0000ff\">" + appVersion + "</font></center>" );
#endif

    m_label = new QLabel ( this );
    m_label->setTextFormat ( Qt::RichText );
    m_label->setGeometry ( 0, m_image0->height() - 80, m_image0->width(), 15 );
    m_label->setAlignment ( Qt::AlignTop );
    m_label->setFont ( QFont ( "helvetica", 8, QFont::Bold ) );
    m_label->show();

    m_label1 = new QLabel ( this );
    m_label1->setAlignment ( Qt::AlignBottom );
    m_label1->setFont ( QFont ( "helvetica", 9, QFont::Normal ) );
    m_label1->setGeometry ( 0, m_image0->height() - 50, m_image0->width(), 50 );

    m_barra = new QProgressBar ( this );
    m_barra->setTextVisible ( false );
    /// Poniendo el minimo y maximo a 0 hace el efecto especial.
    m_barra->setRange ( 0, 100 );
    m_barra->setGeometry ( 0, m_image0->height() - 65, m_image0->width(), 15 );
    QPalette pbarra = m_barra->palette();
    QColor colorfondobarra = QColor ( "#000000" );
    colorfondobarra.setAlpha ( 100 );
    pbarra.setBrush ( QPalette::Base, colorfondobarra );
    m_barra->setPalette ( pbarra );

}
void  QQuickTextNodeEngine::addToSceneGraph(QQuickTextNode *parentNode,
                                            QQuickText::TextStyle style,
                                            const QColor &styleColor)
{
    if (m_currentLine.isValid())
        processCurrentLine();

    QList<BinaryTreeNode *> nodes;
    QList<BinaryTreeNode *> imageNodes;
    mergeProcessedNodes(&nodes, &imageNodes);

    for (int i = 0; i < m_backgrounds.size(); ++i) {
        const QRectF &rect = m_backgrounds.at(i).first;
        const QColor &color = m_backgrounds.at(i).second;

        parentNode->addRectangleNode(rect, color);
    }

    // Add all unselected text first
    for (int i = 0; i < nodes.size(); ++i) {
        const BinaryTreeNode *node = nodes.at(i);
        if (node->selectionState == Unselected)
            parentNode->addGlyphs(node->position, node->glyphRun, node->color, style, styleColor, 0);
    }

    for (int i = 0; i < imageNodes.size(); ++i) {
        const BinaryTreeNode *node = imageNodes.at(i);
        if (node->selectionState == Unselected)
            parentNode->addImage(node->boundingRect, node->image);
    }

    // Then, prepend all selection rectangles to the tree
    for (int i = 0; i < m_selectionRects.size(); ++i) {
        const QRectF &rect = m_selectionRects.at(i);

        parentNode->addRectangleNode(rect, m_selectionColor);
    }

    // Add decorations for each node to the tree.
    for (int i = 0; i < m_lines.size(); ++i) {
        const TextDecoration &textDecoration = m_lines.at(i);

        QColor color = textDecoration.selectionState == Selected
                ? m_selectedTextColor
                : textDecoration.color;

        parentNode->addRectangleNode(textDecoration.rect, color);
    }

    // Finally add the selected text on top of everything
    for (int i = 0; i < nodes.size(); ++i) {
        const BinaryTreeNode *node = nodes.at(i);
        QQuickDefaultClipNode *clipNode = node->clipNode;
        if (clipNode != 0 && clipNode->parent() == 0)
            parentNode->appendChildNode(clipNode);

        if (node->selectionState == Selected) {
            QColor color = m_selectedTextColor;
            int previousNodeIndex = i - 1;
            int nextNodeIndex = i + 1;
            const BinaryTreeNode *previousNode = previousNodeIndex < 0 ? 0 : nodes.at(previousNodeIndex);
            while (previousNode != 0 && qFuzzyCompare(previousNode->boundingRect.left(), node->boundingRect.left()))
                previousNode = --previousNodeIndex < 0 ? 0 : nodes.at(previousNodeIndex);

            const BinaryTreeNode *nextNode = nextNodeIndex == nodes.size() ? 0 : nodes.at(nextNodeIndex);

            if (previousNode != 0 && previousNode->selectionState == Unselected)
                parentNode->addGlyphs(previousNode->position, previousNode->glyphRun, color, style, styleColor, clipNode);

            if (nextNode != 0 && nextNode->selectionState == Unselected)
                parentNode->addGlyphs(nextNode->position, nextNode->glyphRun, color, style, styleColor, clipNode);

            // If the previous or next node completely overlaps this one, then we have already drawn the glyphs of
            // this node
            bool drawCurrent = false;
            if (previousNode != 0 || nextNode != 0) {
                for (int i = 0; i < node->ranges.size(); ++i) {
                    const QPair<int, int> &range = node->ranges.at(i);

                    int rangeLength = range.second - range.first + 1;
                    if (previousNode != 0) {
                        for (int j = 0; j < previousNode->ranges.size(); ++j) {
                            const QPair<int, int> &otherRange = previousNode->ranges.at(j);
                            if (range.first <= otherRange.second && range.second >= otherRange.first) {
                                int start = qMax(range.first, otherRange.first);
                                int end = qMin(range.second, otherRange.second);
                                rangeLength -= end - start + 1;
                                if (rangeLength == 0)
                                    break;
                            }
                        }
                    }

                    if (nextNode != 0 && rangeLength > 0) {
                        for (int j = 0; j < nextNode->ranges.size(); ++j) {
                            const QPair<int, int> &otherRange = nextNode->ranges.at(j);

                            if (range.first <= otherRange.second && range.second >= otherRange.first) {
                                int start = qMax(range.first, otherRange.first);
                                int end = qMin(range.second, otherRange.second);
                                rangeLength -= end - start + 1;
                                if (rangeLength == 0)
                                    break;
                            }
                        }
                    }

                    if (rangeLength > 0) {
                        drawCurrent = true;
                        break;
                    }
                }
            } else {
                drawCurrent = true;
            }

            if (drawCurrent)
                parentNode->addGlyphs(node->position, node->glyphRun, color, style, styleColor, clipNode);
        }
    }

    for (int i = 0; i < imageNodes.size(); ++i) {
        const BinaryTreeNode *node = imageNodes.at(i);
        if (node->selectionState == Selected) {
            parentNode->addImage(node->boundingRect, node->image);
            if (node->selectionState == Selected) {
                QColor color = m_selectionColor;
                color.setAlpha(128);
                parentNode->addRectangleNode(node->boundingRect, color);
            }
        }
    }
}
Beispiel #30
0
QBrush XMLParseBase::parseGradient(const QDomElement &element)
{
    QBrush brush;
    QString gradientStart = element.attribute("start", "");
    QString gradientEnd = element.attribute("end", "");
    int gradientAlpha = element.attribute("alpha", "255").toInt();
    QString direction = element.attribute("direction", "vertical");

    QGradientStops stops;

    if (!gradientStart.isEmpty())
    {
        QColor startColor = QColor(gradientStart);
        startColor.setAlpha(gradientAlpha);
        QGradientStop stop(0.0, startColor);
        stops.append(stop);
    }

    for (QDomNode child = element.firstChild(); !child.isNull();
        child = child.nextSibling())
    {
        QDomElement childElem = child.toElement();
        if (childElem.tagName() == "stop")
        {
            float position = childElem.attribute("position", "0").toFloat();
            QString color = childElem.attribute("color", "");
            int alpha = childElem.attribute("alpha", "-1").toInt();
            if (alpha < 0)
                alpha = gradientAlpha;
            QColor stopColor = QColor(color);
            stopColor.setAlpha(alpha);
            QGradientStop stop((position / 100), stopColor);
            stops.append(stop);
        }
    }

    if (!gradientEnd.isEmpty())
    {
        QColor endColor = QColor(gradientEnd);
        endColor.setAlpha(gradientAlpha);
        QGradientStop stop(1.0, endColor);
        stops.append(stop);
    }

    if (direction == "radial")
    {
        QRadialGradient gradient;
        gradient.setCoordinateMode(QGradient::ObjectBoundingMode);
        float x1 = 0.5, y1 = 0.5, radius = 0.5;
        gradient.setCenter(x1,y1);
        gradient.setFocalPoint(x1,y1);
        gradient.setRadius(radius);
        gradient.setStops(stops);
        brush = QBrush(gradient);
    }
    else // Linear
    {
        QLinearGradient gradient;
        gradient.setCoordinateMode(QGradient::ObjectBoundingMode);
        float x1 = 0.0, y1 = 0.0, x2 = 0.0, y2 = 0.0;
        if (direction == "vertical")
        {
            x1 = 0.5;
            x2 = 0.5;
            y1 = 0.0;
            y2 = 1.0;
        }
        else if (direction == "diagonal")
        {
            x1 = 0.0;
            x2 = 1.0;
            y1 = 0.0;
            y2 = 1.0;
        }
        else // Horizontal
        {
            x1 = 0.0;
            x2 = 1.0;
            y1 = 0.5;
            y2 = 0.5;
        }

        gradient.setStart(x1, y1);
        gradient.setFinalStop(x2, y2);
        gradient.setStops(stops);
        brush = QBrush(gradient);
    }


    return brush;
}