Ejemplo n.º 1
0
void MythPainter::DrawTextPriv(MythImage *im, const QString &msg, int flags,
                               const QRect &r, const MythFontProperties &font)
{
    if (!im)
        return;

    QColor outlineColor;
    int outlineSize = 0;
    int outlineAlpha;
    if (font.hasOutline())
        font.GetOutline(outlineColor, outlineSize, outlineAlpha);

    QPoint shadowOffset(0, 0);
    QColor shadowColor;
    int shadowAlpha;
    if (font.hasShadow())
        font.GetShadow(shadowOffset, shadowColor, shadowAlpha);

    QFontMetrics fm(font.face());
    int totalHeight = fm.height() + outlineSize +
        std::max(outlineSize, std::abs(shadowOffset.y()));

    // initialPaddingX is the number of pixels from the left of the
    // input QRect to the left of the actual text.  It is always 0
    // because we don't add padding to the text rectangle.
    int initialPaddingX = 0;

    // initialPaddingY is the number of pixels from the top of the
    // input QRect to the top of the actual text.  It may be nonzero
    // because of extra vertical padding.
    int initialPaddingY = (r.height() - totalHeight) / 2;
    // Hack.  Normally we vertically center the text due to some
    // (solvable) issues in the SubtitleScreen code - the text rect
    // and the background rect are both created with PAD_WIDTH extra
    // padding, and to honor Qt::AlignTop, the text rect needs to be
    // without padding.  This doesn't work for Qt::TextWordWrap, since
    // the first line will be vertically centered with subsequence
    // lines below.  So if Qt::TextWordWrap is set, we do top
    // alignment.
    if (flags & Qt::TextWordWrap)
        initialPaddingY = 0;

    // textOffsetX is the number of pixels from r.left() to the left
    // edge of the core text.  This assumes that flags contains
    // Qt::AlignLeft.
    int textOffsetX =
        initialPaddingX + std::max(outlineSize, -shadowOffset.x());

    // textOffsetY is the number of pixels from r.top() to the top
    // edge of the core text.  This assumes that flags contains
    // Qt::AlignTop.
    int textOffsetY =
        initialPaddingY + std::max(outlineSize, -shadowOffset.y());

    QImage pm(r.size(), QImage::Format_ARGB32);
    QColor fillcolor = font.color();
    if (font.hasOutline())
        fillcolor = outlineColor;
    fillcolor.setAlpha(0);
    pm.fill(fillcolor.rgba());

    QPainter tmp(&pm);
    QFont tmpfont = font.face();
    tmpfont.setStyleStrategy(QFont::OpenGLCompatible);
    tmp.setFont(tmpfont);

    QPainterPath path;
    if (font.hasOutline())
        path.addText(0, 0, tmpfont, msg);

    if (font.hasShadow())
    {
        QRect a = QRect(0, 0, r.width(), r.height());
        a.translate(shadowOffset.x() + textOffsetX,
                    shadowOffset.y() + textOffsetY);

        shadowColor.setAlpha(shadowAlpha);
        tmp.setPen(shadowColor);
        tmp.drawText(a, flags, msg);
    }

    if (font.hasOutline())
    {
        // QPainter::drawText() treats the Y coordinate as the top of
        // the text (when Qt::AlignTop is used).  However,
        // QPainterPath::addText() treats the Y coordinate as the base
        // line of the text.  To translate from the top to the base
        // line, we need to add QFontMetrics::ascent().
        int adjX = 0;
        int adjY = fm.ascent();

        outlineColor.setAlpha(outlineAlpha);
        tmp.setPen(outlineColor);

        path.translate(adjX + textOffsetX, adjY + textOffsetY);
        QPen pen = tmp.pen();
        pen.setWidth(outlineSize * 2 + 1);
        pen.setCapStyle(Qt::RoundCap);
        pen.setJoinStyle(Qt::RoundJoin);
        tmp.setPen(pen);
        tmp.drawPath(path);

        path.translate(outlineSize, outlineSize);
    }

    tmp.setPen(QPen(font.GetBrush(), 0));
    tmp.setBrush(font.GetBrush());
    tmp.drawText(textOffsetX, textOffsetY, r.width(), r.height(),
                 flags, msg);
    tmp.end();
    im->Assign(pm);
}
Ejemplo n.º 2
0
/**
 * Renders the text data into painter paths.
 */
void RTextRenderer::render() {
    boundingBox = RBox();
    painterPaths.clear();
    richText = "";

    QString text = textData.getEscapedText();
    //RVector position = textData.getPosition();
    RVector position = textData.getAlignmentPoint();
    double textHeight = textData.getTextHeight();
    RS::VAlign verticalAlignment = textData.getVAlign();
    RS::HAlign horizontalAlignment = textData.getHAlign();
    double lineSpacingFactor = textData.getLineSpacingFactor();
    QString fontName = textData.getFontName();
    bool bold = textData.isBold();
    bool italic = textData.isItalic();
    double angle = textData.getAngle();
    //RColor color = textData.getColor(true);

    // split up text where separation is required due to line feed,
    // or any type of height change (\P, \H[0-9]*.?[0-9]+;, \S*/*;)

    // split up text at every formatting change:
    QRegExp regExpAll(rxAll);
    QStringList literals = text.split(regExpAll);

    // collect formatting change information for every literal:
    QStringList formattings;
    int pos = 0;
    while ((pos = regExpAll.indexIn(text, pos)) != -1) {
        formattings << regExpAll.cap(1);
        pos += regExpAll.matchedLength();
    }

    // x position in real units:
    double xCursor = 0.0;
    // y position for next text line:
    double yCursor = 0.0;
    // painter paths for current text line:
    QList<RPainterPath> linePaths;
    // max ascent of current text line:
    double maxAscent = 0.0;
    // max descent of current line:
    double minDescent = 0.0;
    // max descent of _previous_ line:
    double minDescentPrevious = 0.0;
    // true for the first block of the current line:
    bool firstBlockInLine = true;
    // current line has leading spaces:
    bool leadingSpaces = false;
    // current line has trailing spaces:
    bool trailingSpaces = false;
    // text has leading empty lines:
    bool leadingEmptyLines = false;
    // text has trailing empty lines:
    bool trailingEmptyLines = false;
    int lineCounter = 0;
    QString textBlock;
    QList<QTextLayout::FormatRange> formats;

    bool blockChangedHeightOrFont = false;

    // implicit top level format block:
    QTextCharFormat f;
    f.setForeground(QBrush(QColor()));
    currentFormat.push(f);
    QTextLayout::FormatRange fr;
    fr.start = 0;
    fr.length = 0;
    fr.format = currentFormat.top();
    formats.append(fr);
    blockHeight.push(textHeight);
    blockFont.push(fontName);
    blockBold.push(bold);
    blockItalic.push(italic);
    useCadFont.push(RFontList::isCadFont(fontName));
    openTags.push(QStringList());

    width = 0.0;
    height = 0.0;

    // iterate through all text blocks:
    for (int i=0; i<literals.size(); ++i) {

        // the literal text, e.g. "ABC":
        QString literal = literals.at(i);

        // the formatting _after_ the text, e.g. "\C1;"
        QString formatting;
        if (i<formattings.size()) {
            formatting = formattings.at(i);
        }

//        qDebug() << "block: " << i;
//        qDebug() << "  literal: " << literal;
//        qDebug() << "  literal length: " << literal.length();
//        qDebug() << "  formatting: " << formatting;
//        qDebug() << "  font: " << blockFont.top();
//        qDebug() << "  height: " << blockHeight.top();
//        qDebug() << "  cad font: " << useCadFont.top();
//        qDebug() << "  xCursor: " << xCursor;

        // handle literal:
        textBlock.append(literal);

        if (firstBlockInLine) {
            if (!literal.isEmpty()) {
                if (literal.at(0).isSpace()) {
                    leadingSpaces = true;
                }
            }
            else {
                if (formatting=="\\~") {
                    leadingSpaces = true;
                }
            }
            firstBlockInLine = false;
        }

        bool lineFeed = false;
        bool paragraphFeed = false;
        bool heightChange = false;
        bool stackedText = false;
        bool fontChange = false;
        bool colorChange = false;
        bool blockEnd = false;

        // detect formatting that ends the current text block:
        if (!formatting.isEmpty()) {
            fontChange = QRegExp(rxFontChangeTtf).exactMatch(formatting) ||
                QRegExp(rxFontChangeCad).exactMatch(formatting);
            colorChange = QRegExp(rxColorChangeCustom).exactMatch(formatting) ||
                QRegExp(rxColorChangeIndex).exactMatch(formatting);
            heightChange = QRegExp(rxHeightChange).exactMatch(formatting);
            stackedText = QRegExp(rxStackedText).exactMatch(formatting);
            lineFeed = QRegExp(rxLineFeed).exactMatch(formatting);
            paragraphFeed = QRegExp(rxParagraphFeed).exactMatch(formatting);
            blockEnd = QRegExp(rxEndBlock).exactMatch(formatting);
        }

        bool start = (i==0);
        bool end = (i==literals.size()-1);

        // first line is empty:
        if (textBlock.trimmed().isEmpty() && (lineFeed || paragraphFeed || end)) {
            if (start) {
                leadingEmptyLines = true;
            }
            else if (end) {
                trailingEmptyLines = true;
            }
        }

        // reached a new text block that needs to be rendered separately
        // due to line feed, height change, font change, ...:
        if (target==RichText ||
            lineFeed || paragraphFeed || heightChange || stackedText ||
            fontChange || colorChange || end
            || (blockEnd && blockChangedHeightOrFont)) {

            // render block _before_ format change that requires new block:
            if (textBlock!="") {
                // fix format lengths to match up. each format stops where
                // the next one starts. formatting that is carried over is set
                // again for the new format.
                for (int i=0; i<formats.size(); i++) {
                    int nextStart;
                    if (i<formats.size()-1) {
                        nextStart = formats[i+1].start;
                    }
                    else {
                        nextStart = textBlock.length();
                    }
                    formats[i].length = nextStart - formats[i].start;
                }

                if (target==RichText) {
                    richText += getRichTextForBlock(
                                   textBlock, formats);
                }

                if (target==PainterPaths) {
                    double horizontalAdvance = 0.0;
                    double horizontalAdvanceNoSpacing = 0.0;
                    double ascent = 0.0;
                    double descent = 0.0;
                    QList<RPainterPath> paths;

                    // get painter paths for current text block at height 1.0:
                    paths = getPainterPathsForBlock(
                                textBlock, formats,
                                horizontalAdvance,
                                horizontalAdvanceNoSpacing,
                                ascent, descent);

                    // transform to scale text from 1.0 to current text height:
                    QTransform sizeTransform;
                    sizeTransform.scale(blockHeight.top(), blockHeight.top());

                    // transform for current block due to xCursor position:
                    QTransform blockTransform;
                    blockTransform.translate(xCursor, 0);

                    // combine transforms for current text block:
                    QTransform allTransforms = sizeTransform;
                    allTransforms *= blockTransform;

                    maxAscent = qMax(maxAscent, ascent * blockHeight.top());
                    minDescent = qMin(minDescent, descent * blockHeight.top());

                    // transform paths of current block and append to paths
                    // of current text line:
                    for (int i=0; i<paths.size(); ++i) {
                        RPainterPath p = paths.at(i);
                        p.transform(allTransforms);
                        linePaths.append(p);
                    }

                    xCursor += horizontalAdvance * blockHeight.top();
                }
            }

            // empty text, might be line feed, we need ascent, descent anyway:
            else if (lineFeed || paragraphFeed || end) {
                if (target==PainterPaths) {
                    double horizontalAdvance = 0.0;
                    double horizontalAdvanceNoSpacing = 0.0;
                    double ascent = 0.0;
                    double descent = 0.0;

                    // get painter paths for current text block at height 1.0:
                    getPainterPathsForBlock(
                                "A", QList<QTextLayout::FormatRange>(),
                                horizontalAdvance,
                                horizontalAdvanceNoSpacing,
                                ascent, descent);

                    maxAscent = qMax(maxAscent, ascent * blockHeight.top());
                    minDescent = qMin(minDescent, descent * blockHeight.top());
                }
            }

            // handle stacked text:
            if (stackedText) {
                QRegExp reg;
                reg.setPattern(rxStackedText);
                reg.exactMatch(formatting);

                if (target==PainterPaths) {
                    double horizontalAdvance[2];
                    horizontalAdvance[0] = 0.0;
                    horizontalAdvance[1] = 0.0;
                    double horizontalAdvanceNoSpacing[2];
                    horizontalAdvanceNoSpacing[0] = 0.0;
                    horizontalAdvanceNoSpacing[1] = 0.0;
                    double heightFactor = 0.4;

                    // s==0: superscript, s==1: subscript:
                    for (int s=0; s<=1; ++s) {
                        QString script = reg.cap(s+1);

                        QList<RPainterPath> paths;

                        double ascent = 0.0;
                        double descent = 0.0;

                        QList<QTextLayout::FormatRange> localFormats;

                        QTextLayout::FormatRange fr;
                        fr.start = 0;
                        fr.length = script.length();
                        fr.format = currentFormat.top();
                        localFormats.append(fr);

                        // get painter paths for superscript at height 1.0:
                        paths = getPainterPathsForBlock(
                                    script, localFormats,
                                    horizontalAdvance[s],
                                    horizontalAdvanceNoSpacing[s],
                                    ascent, descent);

                        if (s==0) {
                            maxAscent = qMax(maxAscent, ascent * blockHeight.top() * heightFactor + blockHeight.top()*(1.0-heightFactor));
                        }
                        else {
                            minDescent = qMin(minDescent, descent * blockHeight.top() * heightFactor);
                        }

                        // transform to scale text from 1.0 to current text height * 0.4:
                        QTransform sizeTransform;
                        sizeTransform.scale(blockHeight.top()*heightFactor, blockHeight.top()*heightFactor);

                        // move top text more to the right for italic texts:
                        double xOffset = 0.0;
                        if (s==0 && blockItalic.top()==true) {
                            double y = blockHeight.top()*(1.0-heightFactor);
                            // assume italic means roughly 12 degrees:
                            xOffset = tan(RMath::deg2rad(12)) * y;
                        }

                        // transform for current block due to xCursor position
                        // and top or bottom text position:
                        QTransform blockTransform;
                        blockTransform.translate(xCursor + xOffset,
                                                 s==0 ? blockHeight.top()*(1.0-heightFactor) : 0.0);

                        horizontalAdvance[s] += xOffset / (blockHeight.top() * heightFactor);

                        // combine transforms for current text block:
                        QTransform allTransforms = sizeTransform;
                        allTransforms *= blockTransform;

                        // transform paths of current block and append to paths
                        // of current text line:
                        for (int i=0; i<paths.size(); ++i) {
                            RPainterPath p = paths.at(i);
                            p.transform(allTransforms);
                            linePaths.append(p);
                        }
                    }

                    xCursor += qMax(horizontalAdvance[0], horizontalAdvance[1]) * blockHeight.top() * heightFactor;
                }

                if (target==RichText) {
                    QString super = reg.cap(1);
                    QString sub = reg.cap(2);
                    if (!super.isEmpty()) {
                        richText += QString("<span style=\"vertical-align:super;\">%1</span>").arg(super);
                    }
                    if (!sub.isEmpty()) {
                        richText += QString("<span style=\"vertical-align:sub;\">%1</span>").arg(sub);
                    }
                }
            }

            // prepare for next text block:
            if (lineFeed || paragraphFeed || end) {
                if (!textBlock.isEmpty()) {
                    if (textBlock.at(textBlock.length()-1).isSpace()) {
                        trailingSpaces = true;
                    }
                }
//                else {
//                    if (formatting=="\\~") {
//                        trailingSpaces = true;
//                    }
//                }
            }

            textBlock = "";
            formats.clear();
            QTextLayout::FormatRange fr;
            fr.start = 0;
            fr.length = 0;
            fr.format = currentFormat.top();
            formats.append(fr);

            // handle text line.
            // add all painter paths of the current line to result set of
            // painter paths. apply line feed transformations.
            if (lineFeed || paragraphFeed || end) {
//                qDebug() << "lineFeed: adding text line:";
//                qDebug() << "  maxAscent: " << maxAscent;
//                qDebug() << "  minDescent: " << minDescent;
//                qDebug() << "  minDescentPrevious: " << minDescentPrevious;
//                qDebug() << "got line feed or end";
//                qDebug() << "  trailingSpaces: " << trailingSpaces;

                if (target==RichText) {
                    if (lineFeed || paragraphFeed) {
                        richText += "<br/>";
                    }
                }

                if (lineCounter!=0) {
                    yCursor += (minDescentPrevious - maxAscent) * lineSpacingFactor;
                }

                // calculate line bounding box for alignment without spaces at borders:
                RBox lineBoundingBox;
                for (int i=0; i<linePaths.size(); ++i) {
                    RPainterPath p = linePaths.at(i);
                    lineBoundingBox.growToInclude(p.getBoundingBox());
                }

                double featureSize = lineBoundingBox.getHeight();

                QTransform lineTransform;

                switch (horizontalAlignment) {
                case RS::HAlignAlign:
                case RS::HAlignFit:
                case RS::HAlignLeft:
                    if (!leadingSpaces) {
                        // move completely to the left (left border is 0.0):
                        lineTransform.translate(
                                    -lineBoundingBox.getMinimum().x,
                                    yCursor);
                    }
                    else {
                        lineTransform.translate(0, yCursor);
                    }
                    break;
                case RS::HAlignMid:
                case RS::HAlignCenter:
                    if (!leadingSpaces && !trailingSpaces) {
                        lineTransform.translate(
                                    -(lineBoundingBox.getMinimum().x +
                                      lineBoundingBox.getMaximum().x)/2.0,
                                    yCursor);
                    }
                    else {
                        lineTransform.translate(-xCursor/2.0, yCursor);
                    }
                    break;
                case RS::HAlignRight:
                    if (!trailingSpaces) {
                        lineTransform.translate(-lineBoundingBox.getMaximum().x, yCursor);
                    }
                    else {
                        lineTransform.translate(-xCursor, yCursor);
                    }
                    break;
                }

                width = qMax(width, lineBoundingBox.getMaximum().x - qMin(0.0, lineBoundingBox.getMinimum().x));

                // add current text line to result set:
                QPen pen;
                for (int i=0; i<linePaths.size(); ++i) {
                    RPainterPath p = linePaths[i];
                    if (i==0) {
                        pen = p.getPen();
                        if (pen.style()==Qt::NoPen) {
                           pen = QPen(p.getBrush().color());
                        }
                    }
                    p.transform(lineTransform);
                    p.setFeatureSize(featureSize);
                    painterPaths.append(p);
                    boundingBox.growToInclude(p.getBoundingBox());
                }

                RPainterPath bbPath;
                bbPath.addBox(lineBoundingBox);
                bbPath.transform(lineTransform);
                bbPath.setFeatureSize(-featureSize);
                bbPath.setPen(pen);
                painterPaths.append(bbPath);

                lineCounter++;
                xCursor = 0.0;
                maxAscent = 0.0;
                minDescentPrevious = minDescent;
                minDescent = 0.0;
                linePaths.clear();
                firstBlockInLine = true;
                leadingSpaces = false;
                trailingSpaces = false;
            }
        }

        // handle formatting after text block, that applies either
        // to the next text block(s) or the rest of the current text block:
        if (formatting.isEmpty()) {
            continue;
        }

        QRegExp reg;

        // unicode:
        reg.setPattern(rxUnicode);
        if (reg.exactMatch(formatting)) {
            textBlock += QChar(reg.cap(1).toInt(0, 16));
            continue;
        }

        // curly braket open:
        reg.setPattern(rxCurlyOpen);
        if (reg.exactMatch(formatting)) {
            textBlock += "{";
            continue;
        }

        // curly braket close:
        reg.setPattern(rxCurlyClose);
        if (reg.exactMatch(formatting)) {
            textBlock += "}";
            continue;
        }

        // degree:
        reg.setPattern(rxDegree);
        if (reg.exactMatch(formatting)) {
            textBlock += chDegree;
            continue;
        }

        // plus/minus:
        reg.setPattern(rxPlusMinus);
        if (reg.exactMatch(formatting)) {
            textBlock += chPlusMinus;
            continue;
        }

        // diameter:
        reg.setPattern(rxDiameter);
        if (reg.exactMatch(formatting)) {
            textBlock += chDiameter;
            continue;
        }

        // backslash:
        reg.setPattern(rxBackslash);
        if (reg.exactMatch(formatting)) {
            textBlock += "\\";
            continue;
        }

        // non-breaking space:
        reg.setPattern(rxNonBreakingSpace);
        if (reg.exactMatch(formatting)) {
            if (target==PainterPaths) {
                textBlock += QChar(Qt::Key_nobreakspace);
            }
            if (target==RichText) {
                textBlock += "&nbsp;";
            }
            continue;
        }

        // font change (TTF):
        reg.setPattern(rxFontChangeTtf);
        if (reg.exactMatch(formatting)) {
            blockFont.top() = reg.cap(1);
            blockBold.top() = (reg.cap(2).toInt()!=0);
            blockItalic.top() = (reg.cap(3).toInt()!=0);
            useCadFont.top() = false;
            blockChangedHeightOrFont = true;

            if (target==RichText) {
                QString style;
                style += QString("font-family:%1;").arg(blockFont.top());
                style += QString("font-weight:%1;").arg(blockBold.top() ? "bold" : "normal");
                style += QString("font-style:%1;").arg(blockItalic.top() ? "italic" : "normal");
                richText += QString("<span style=\"%1\">").arg(style);
                openTags.top().append("span");
            }
            continue;
        }

        // font change (CAD):
        reg.setPattern(rxFontChangeCad);
        if (reg.exactMatch(formatting)) {
            blockFont.top() = reg.cap(1);
            useCadFont.top() = true;
            if (xCursor>RS::PointTolerance) {
                RFont* f = RFontList::get(blockFont.top());
                if (f!=NULL && f->isValid()) {
                    xCursor += f->getLetterSpacing() / 9.0;
                }
            }
            blockChangedHeightOrFont = true;

            if (target==RichText) {
                QString style;
                style += QString("font-family:%1;").arg(blockFont.top());
                richText += QString("<span style=\"%1\">").arg(style);
                openTags.top().append("span");
            }
            continue;
        }

        // height change:
        reg.setPattern(rxHeightChange);
        if (reg.exactMatch(formatting)) {
            bool factor = reg.cap(2)=="x";

            if (factor) {
                blockHeight.top() *= reg.cap(1).toDouble();
            }
            else {
                blockHeight.top() = reg.cap(1).toDouble();
            }
            blockChangedHeightOrFont = true;

            if (target==RichText) {
                QString style;
                style += QString("font-size:%1pt;").arg(blockHeight.top() * fontHeightFactor);
                richText += QString("<span style=\"%1\">").arg(style);
                openTags.top().append("span");
            }
            continue;
        }

        QTextLayout::FormatRange fr;
        fr.start = textBlock.length();
        fr.length = 0;

        // start format block:
        reg.setPattern(rxBeginBlock);
        if (reg.exactMatch(formatting)) {
            currentFormat.push(currentFormat.top());
            blockFont.push(blockFont.top());
            blockBold.push(blockBold.top());
            blockItalic.push(blockItalic.top());
            blockHeight.push(blockHeight.top());
            useCadFont.push(useCadFont.top());
            if (target==RichText) {
                openTags.push(QStringList());
            }
            blockChangedHeightOrFont = false;
            continue;
        }

        // end format block:
        reg.setPattern(rxEndBlock);
        if (reg.exactMatch(formatting)) {
            currentFormat.pop();
            fr.format = currentFormat.top();
            formats.append(fr);
            blockFont.pop();
            blockBold.pop();
            blockItalic.pop();
            blockHeight.pop();
            useCadFont.pop();
            blockChangedHeightOrFont = false;

            if (target==RichText) {
                // close all tags that were opened in this block:
                for (int i=openTags.top().size()-1; i>=0; --i) {
                    QString tag = openTags.top().at(i);
                    richText += QString("</%1>").arg(tag);
                }
                openTags.pop();
            }

            continue;
        }

        // color change (indexed):
        reg.setPattern(rxColorChangeIndex);
        if (reg.exactMatch(formatting)) {
            RColor blockColor = RColor::createFromCadIndex(reg.cap(1));
            if (blockColor.isByLayer()) {
                currentFormat.top().setForeground(RColor::CompatByLayer);
            } else if (blockColor.isByBlock()) {
                currentFormat.top().setForeground(RColor::CompatByBlock);
            }
            else {
                currentFormat.top().setForeground(blockColor);
            }
            fr.format = currentFormat.top();
            formats.append(fr);

            if (target==RichText) {
                QString style;
                style += QString("color:%1;").arg(blockColor.name());
                richText += QString("<span style=\"%1\">").arg(style);
                openTags.top().append("span");
            }
            continue;
        }

        // color change (custom):
        reg.setPattern(rxColorChangeCustom);
        if (reg.exactMatch(formatting)) {
            RColor blockColor = RColor::createFromCadCustom(reg.cap(1));
            currentFormat.top().setForeground(blockColor);
            fr.format = currentFormat.top();
            formats.append(fr);

            if (target==RichText) {
                QString style;
                style += QString("color:%1;").arg(blockColor.name());
                richText += QString("<span style=\"%1\">").arg(style);
                openTags.top().append("span");
            }
            continue;
        }
    }

    if (target==PainterPaths) {
        // at this point, the text is at 0/0 with the base line of the
        // first text line at y==0

        // vertical alignment:
        double topLine = qMax(textHeight, boundingBox.getMaximum().y);
        double bottomLine = qMin(0.0, boundingBox.getMinimum().y);

        QTransform globalTransform;
        globalTransform.translate(position.x, position.y);
        globalTransform.rotate(RMath::rad2deg(angle));
        switch (verticalAlignment) {
        case RS::VAlignTop:
            //if (!leadingEmptyLines) {
                globalTransform.translate(0.0, -topLine);
            //}
            break;
        case RS::VAlignMiddle:
            if (leadingEmptyLines || trailingEmptyLines) {
                globalTransform.translate(0.0, -(yCursor+textHeight)/2.0);
            }
            else {
                globalTransform.translate(0.0, -(bottomLine + topLine) / 2.0);
            }
            break;
        case RS::VAlignBottom:
        case RS::VAlignBase:
            if (trailingEmptyLines) {
                globalTransform.translate(0.0, -yCursor);
            }
            else {
                globalTransform.translate(0.0, -bottomLine);
            }
            break;
        }

        height = boundingBox.getHeight();

        // apply global transform for position, angle and vertical alignment:
        boundingBox = RBox();
        for (int i=0; i<painterPaths.size(); ++i) {
            painterPaths[i].transform(globalTransform);
            boundingBox.growToInclude(painterPaths[i].getBoundingBox());
        }
    }

    if (target==RichText) {
        // close all tags that were opened:
        for (int i=openTags.top().size()-1; i>=0; --i) {
            QString tag = openTags.top().at(i);
            richText += QString("</%1>").arg(tag);
        }
    }
}
Ejemplo n.º 3
0
void
TriggerPoint::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
  Q_UNUSED(option);
  Q_UNUSED(widget);

  QRectF rect = boundingRect();
  painter->save();

  BasicBox *box = nullptr;
  if (_abstract->boxID() != NO_ID) {
      if ((box = _scene->getBox(_abstract->boxID())) != nullptr) {
          QPen pen = painter->pen();
          QBrush brush = painter->brush();

          // selection
          if (isSelected()) {
              QPen penBlue(QColor(60,60,255)); // same blue as box selected

              penBlue.setWidth(BasicBox::LINE_WIDTH);
              painter->setPen(penBlue);

              QPainterPath path;
              path = shape();
              painter->drawPath(path);
          }

          pen.setColor(box->color().darker());
          pen.setWidth(BasicBox::LINE_WIDTH / 2);
          painter->setPen(pen);
          if (_scene->playing()) {
              if (!isWaiting()) {
                  drawFlag(painter, QColor("red"));
                }

              else {
                  if(!_scene->triggersQueueList()->isEmpty())
				  {
                      if (_scene->triggersQueueList()->first() == this && !box->isConditioned()) {
                          drawFlag(painter, QColor("green"));
                          this->setFocus();
                      }
                      else {
                          drawFlag(painter, QColor("orange"));
                      }
				  }
              }

              if (_abstract->waiting()) {
                  BasicBox *box = _scene->getBox(_abstract->boxID());
                  box->update();
                  switch (_abstract->boxExtremity()) {
                      case BOX_START:
                        painter->drawText(rect.topRight() + QPointF(0, rect.height() / 2), QString::fromStdString(_abstract->message()));
                        break;

                      case BOX_END:
                        painter->drawText(rect.topLeft() + QPointF(-QString::fromStdString(_abstract->message()).length() * 7, rect.height() / 2), QString::fromStdString(_abstract->message()));
                        break;

                      default:
                        break;
                    }
                }
            }
          else {
              drawFlag(painter, QColor(Qt::darkGray));
            }
        }
    }
  painter->restore();
}
Ejemplo n.º 4
0
void QgsSimpleLineSymbolLayerV2::applyDataDefinedSymbology( QgsSymbolV2RenderContext& context, QPen& pen, QPen& selPen, double& offset )
{
  if ( mDataDefinedProperties.isEmpty() )
    return; // shortcut

  //data defined properties
  QgsExpression* strokeWidthExpression = expression( "width" );
  if ( strokeWidthExpression )
  {
    double scaledWidth = strokeWidthExpression->evaluate( const_cast<QgsFeature*>( context.feature() ) ).toDouble()
                         * QgsSymbolLayerV2Utils::lineWidthScaleFactor( context.renderContext(), mWidthUnit, mWidthMapUnitScale );
    pen.setWidthF( scaledWidth );
    selPen.setWidthF( scaledWidth );
  }

  //color
  QgsExpression* strokeColorExpression = expression( "color" );
  if ( strokeColorExpression )
  {
    pen.setColor( QgsSymbolLayerV2Utils::decodeColor( strokeColorExpression->evaluate( const_cast<QgsFeature*>( context.feature() ) ).toString() ) );
  }

  //offset
  QgsExpression* lineOffsetExpression = expression( "offset" );
  if ( lineOffsetExpression )
  {
    offset = lineOffsetExpression->evaluate( const_cast<QgsFeature*>( context.feature() ) ).toDouble();
  }

  //dash dot vector
  QgsExpression* dashPatternExpression = expression( "customdash" );
  if ( dashPatternExpression )
  {
    double scaledWidth = mWidth * QgsSymbolLayerV2Utils::lineWidthScaleFactor( context.renderContext(), mWidthUnit, mWidthMapUnitScale );
    double dashWidthDiv = mPen.widthF();

    if ( strokeWidthExpression )
    {
      dashWidthDiv = pen.widthF();
      scaledWidth = pen.widthF();
    }

    //fix dash pattern width in Qt 4.8
    QStringList versionSplit = QString( qVersion() ).split( "." );
    if ( versionSplit.size() > 1
         && versionSplit.at( 1 ).toInt() >= 8
         && ( scaledWidth * context.renderContext().rasterScaleFactor() ) < 1.0 )
    {
      dashWidthDiv = 1.0;
    }

    QVector<qreal> dashVector;
    QStringList dashList = dashPatternExpression->evaluate( const_cast<QgsFeature*>( context.feature() ) ).toString().split( ";" );
    QStringList::const_iterator dashIt = dashList.constBegin();
    for ( ; dashIt != dashList.constEnd(); ++dashIt )
    {
      dashVector.push_back( dashIt->toDouble() * QgsSymbolLayerV2Utils::lineWidthScaleFactor( context.renderContext(), mCustomDashPatternUnit, mCustomDashPatternMapUnitScale ) / dashWidthDiv );
    }
    pen.setDashPattern( dashVector );
  }

  //join style
  QgsExpression* joinStyleExpression = expression( "joinstyle" );
  if ( joinStyleExpression )
  {
    QString joinStyleString = joinStyleExpression->evaluate( const_cast<QgsFeature*>( context.feature() ) ).toString();
    pen.setJoinStyle( QgsSymbolLayerV2Utils::decodePenJoinStyle( joinStyleString ) );
  }

  //cap style
  QgsExpression* capStyleExpression = expression( "capstyle" );
  if ( capStyleExpression )
  {
    QString capStyleString = capStyleExpression->evaluate( const_cast<QgsFeature*>( context.feature() ) ).toString();
    pen.setCapStyle( QgsSymbolLayerV2Utils::decodePenCapStyle( capStyleString ) );
  }
}
Ejemplo n.º 5
0
void PreviewWidget::paintEvent(QPaintEvent *event)
{

//#define DEBUG_LAYOUT
#ifdef DEBUG_LAYOUT
    {
        if (mImage.isNull())
            return;

        if (mSheetNum < 0)
            return;

        Sheet *sheet = project->previewSheet(mSheetNum);

        if (!sheet)
            return;

        QPainter painter(this);
        QRectF rect = project->printer()->paperRect();
        painter.fillRect(rect, Qt::white);


        for (int i=0; i< sheet->count(); ++i)
        {
            QPen pen = painter.pen();
            pen.setStyle(Qt::DotLine);
            pen.setColor(Qt::darkGray);
            painter.setPen(pen);
            TransformSpec spec = project->layout()->transformSpec(sheet, i, project->rotation());

            painter.drawRect(spec.rect);
            QFont font = painter.font();
            font.setPixelSize(spec.rect.height() / 2 );
            painter.setFont(font);
            painter.drawText(spec.rect, Qt::AlignCenter, QString("%1").arg(i+1));


            pen.setStyle(Qt::SolidLine);
            pen.setColor(Qt::red);
            painter.setPen(pen);

            switch (spec.rotation)
            {
            case NoRotate:
                painter.drawLine(spec.rect.topLeft(), spec.rect.topRight());
                break;

            case Rotate90:
                painter.drawLine(spec.rect.topRight(), spec.rect.bottomRight());
                break;

            case Rotate180:
                painter.drawLine(spec.rect.bottomLeft(), spec.rect.bottomRight());
                break;

            case Rotate270:
                painter.drawLine(spec.rect.topLeft(), spec.rect.bottomLeft());
                break;
            }
        }
        return;
    }

#endif


    if (mImage.isNull())
        return;

    QSizeF printerSize =  project->printer()->paperRect().size();
    Rotation rotation = project->rotation();

    if (isLandscape(rotation))
        printerSize.transpose();

    mScaleFactor = qMin((this->geometry().width()  - 2.0 * MARGIN_H) * 1.0 / printerSize.width(),
                        (this->geometry().height() - 2.0 * MARGIN_V) * 1.0 / printerSize.height());

    if (mScaleFactor == 0)
    {
        mDrawRect = QRect();
        return;
    }

    QSize size = QSize(printerSize.width()  * mScaleFactor,
                       printerSize.height() * mScaleFactor);

    mDrawRect = QRect(QPoint(0, 0), size);
    mDrawRect.moveCenter(QPoint(0, 0));

    QRectF clipRect = mDrawRect;

    if (mHints.testFlag(Sheet::HintOnlyLeft))
    {
        switch (rotation)
        {
        case NoRotate:  clipRect.setBottom(0); break;
        case Rotate90:  clipRect.setRight(0);  break;
        case Rotate180: clipRect.setBottom(0); break;
        case Rotate270: clipRect.setRight(0);  break;
        }
    }


    if (mHints.testFlag(Sheet::HintOnlyRight))
    {
        switch (rotation)
        {
        case NoRotate:  clipRect.setTop(0);    break;
        case Rotate90:  clipRect.setLeft(0);   break;
        case Rotate180: clipRect.setTop(0);    break;
        case Rotate270: clipRect.setLeft(0);   break;
        }
    }


    QImage img = mImage.scaled(mDrawRect.size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);

    // Draw .....................................
    QPainter painter(this);
    painter.save();
    QPoint center = QRect(0, 0, geometry().width(), geometry().height()).center();
    painter.translate(center);


    if (mHints.testFlag(Sheet::HintSubBooklet))
    {
        painter.save();
        QPoint center = mDrawRect.center();
        QRectF imgRect;

        clipRect = mDrawRect;
        clipRect.setRight(center.x());
        clipRect.adjust(-MARGIN_BOOKLET, 0, -MARGIN_BOOKLET, 0);
        painter.setClipRect(clipRect);

        imgRect = img.rect();
        imgRect.setRight(img.rect().center().x());
        painter.drawImage(clipRect, img, imgRect);
        drawShadow(painter, clipRect);

        clipRect = mDrawRect;
        clipRect.setLeft(center.x());
        clipRect.adjust(MARGIN_BOOKLET, 0, MARGIN_BOOKLET, 0);
        painter.setClipRect(clipRect);

        imgRect = img.rect();
        imgRect.setLeft(img.rect().center().x());
        painter.drawImage(clipRect, img, imgRect);
        drawShadow(painter, clipRect);

        painter.restore();
    }
    else
    {
        painter.save();
        painter.setClipRect(clipRect);
        painter.drawImage(mDrawRect, img);
        drawShadow(painter, clipRect);
        painter.restore();
    }



    if (mHints.testFlag(Sheet::HintDrawFold) && !mHints.testFlag(Sheet::HintSubBooklet))
    {
        QPen pen = painter.pen();
        pen.setStyle(Qt::SolidLine);
        pen.setColor(Qt::lightGray);
        painter.setPen(pen);
        if (isLandscape(rotation))
            painter.drawLine(0, mDrawRect.top(), 0, mDrawRect.bottom());
        else
            painter.drawLine(mDrawRect.left(), 0, mDrawRect.right(), 0);
    }

    painter.restore();

    mDrawRect.moveCenter(center);

    // Draw current page rect ...................
    Sheet *sheet = project->currentSheet();
    if (sheet)
    {
        ProjectPage *curPage = project->currentPage();
        if (curPage)
        {
            painter.save();
            QPen pen = painter.pen();
            pen.setStyle(Qt::DashLine);
            //pen.setColor(QColor(142, 188, 226, 128));
            pen.setColor(QColor(105, 101, 98, 70));
            painter.setPen(pen);
            painter.drawRect(this->pageRect(sheet->indexOfPage(curPage)));
            painter.restore();
        }
    }

//#define DEBUG_CLICK_RECT
#ifdef DEBUG_CLICK_RECT
    {
        Sheet *sheet = project->currentSheet();
        if (sheet)
        {
            ProjectPage *curPage = project->currentPage();
            painter.save();
            for (int i=0; i< sheet->count(); ++i)
            {
                QPen pen = painter.pen();
                pen.setStyle(Qt::DotLine);
                if (sheet->page(i) == curPage)
                    pen.setColor(Qt::red);
                else
                    pen.setColor(QColor(142, 188, 226));
                painter.setPen(pen);
                painter.drawRect(this->pageRect(i));
                painter.drawText(this->pageRect(i).translated(10, 10), QString("%1").arg(i));
            }
            painter.restore();
        }
    }
#endif
}
void QwtErrorPlotCurve::setWidth(double w)
{
	QPen p = pen();
 	p.setWidthF(w);
  	setPen(p);
}
Ejemplo n.º 7
0
int Nightcharts::draw(QPainter *painter)
{
    painter->setRenderHint(QPainter::Antialiasing);
    painter->setPen(Qt::NoPen);
    if (this->ctype==Nightcharts::Pie)
    {
      pW = 0;
      double pdegree = 0;

      //Options
      QLinearGradient gradient(cX+0.5*cW,cY,cX+0.5*cW,cY+cH*2.5);
      gradient.setColorAt(1,Qt::black);


      //Draw
      //pdegree = (360/100)*pieces[i].pPerc;
      if (shadows)
      {
          double sumangle = 0;
          for (int i=0;i<pieces.size();i++)
          {
              sumangle += 3.6*pieces[i].pPerc;
          }
          painter->setBrush(Qt::darkGray);
          painter->drawPie(cX,cY+pW+5,cW,cH,palpha*16,sumangle*16);
      }

      QPen pen;
      pen.setWidth(2);

      for (int i=0;i<pieces.size();i++)
      {
        gradient.setColorAt(0,pieces[i].rgbColor);
        painter->setBrush(gradient);
        pen.setColor(pieces[i].rgbColor);
        painter->setPen(pen);
        pdegree = 3.6*pieces[i].pPerc;
        painter->drawPie(cX,cY,cW,cH,palpha*16,pdegree*16);
        palpha += pdegree;
      }
    }
    else if (this->ctype==Nightcharts::Dpie)
    {
        pW = 50;
        double pdegree = 0;
        QPointF p;

        QLinearGradient gradient(cX-0.5*cW,cY+cH/2,cX+1.5*cW,cY+cH/2);
        gradient.setColorAt(0,Qt::black);
        gradient.setColorAt(1,Qt::white);
        QLinearGradient gradient_side(cX,cY+cH,cX+cW,cY+cH);
        gradient_side.setColorAt(0,Qt::black);

        double sumangle = 0;
        for (int i=0;i<pieces.size();i++)
        {
            sumangle += 3.6*pieces[i].pPerc;
        }
        if (shadows)
        {
            painter->setBrush(Qt::darkGray);
            painter->drawPie(cX,cY+pW+5,cW,cH,palpha*16,sumangle*16);
        }
        int q = GetQuater(palpha+sumangle);

        if (q ==2 || q==3)
        {
            QPointF p = GetPoint(palpha+sumangle);
            QPointF points[4] =
            {
                QPointF(p.x(),p.y()),
                QPointF(p.x(),p.y()+pW),
                QPointF(cX+cW/2,cY+cH/2+pW),
                QPointF(cX+cW/2,cY+cH/2)
            };
            gradient_side.setColorAt(1,pieces[pieces.size()-1].rgbColor);
            painter->setBrush(gradient_side);
            painter->drawPolygon(points,4);
        }
        p = GetPoint(palpha);
        q = GetQuater(palpha);
        if (q ==1 || q==4)
        {
            QPointF points[4] =
            {
                QPointF(p.x(),p.y()),
                QPointF(p.x(),p.y()+pW),
                QPointF(cX+cW/2,cY+cH/2+pW),
                QPointF(cX+cW/2,cY+cH/2)
            };
            gradient_side.setColorAt(1,pieces[0].rgbColor);
            painter->setBrush(gradient_side);
            painter->drawPolygon(points,4);
        }

        for (int i=0;i<pieces.size();i++)
        {
          gradient.setColorAt(0.5,pieces[i].rgbColor);
          painter->setBrush(gradient);
          pdegree = 3.6*pieces[i].pPerc;
          painter->drawPie(cX,cY,cW,cH,palpha*16,pdegree*16);

          double a_ = Angle360(palpha);
          int q_ = GetQuater(palpha);

          palpha += pdegree;

          double a = Angle360(palpha);
          int q = GetQuater(palpha);

          QPainterPath path;
          p = GetPoint(palpha);

          if((q == 3 || q == 4) && (q_ == 3 || q_ == 4))
          {
              // 1)
              if (a>a_)
              {
                  QPointF p_old = GetPoint(palpha-pdegree);
                  path.moveTo(p_old.x()-1,p_old.y());
                  path.arcTo(cX,cY,cW,cH,palpha-pdegree,pdegree);
                  path.lineTo(p.x(),p.y()+pW);
                  path.arcTo(cX,cY+pW,cW,cH,palpha,-pdegree);
              }
              // 2)
              else
              {
                  path.moveTo(cX,cY+cH/2);
                  path.arcTo(cX,cY,cW,cH,180,Angle360(palpha)-180);
                  path.lineTo(p.x(),p.y()+pW);
                  path.arcTo(cX,cY+pW,cW,cH,Angle360(palpha),-Angle360(palpha)+180);
                  path.lineTo(cX,cY+cH/2);

                  path.moveTo(p.x(),p.y());
                  path.arcTo(cX,cY,cW,cH,palpha-pdegree,360-Angle360(palpha-pdegree));
                  path.lineTo(cX+cW,cY+cH/2+pW);
                  path.arcTo(cX,cY+pW,cW,cH,0,-360+Angle360(palpha-pdegree));
              }

          }
          // 3)
          else if((q == 3 || q == 4) && (q_ == 1 || q_ == 2) && a>a_ )
          {
              path.moveTo(cX,cY+cH/2);
              path.arcTo(cX,cY,cW,cH,180,Angle360(palpha)-180);
              path.lineTo(p.x(),p.y()+pW);
              path.arcTo(cX,cY+pW,cW,cH,Angle360(palpha),-Angle360(palpha)+180);
              path.lineTo(cX,cY+cH/2);
          }
          // 4)
          else if((q == 1 || q == 2) && (q_ == 3 || q_ == 4) && a<a_)
          {
              p = GetPoint(palpha-pdegree);
              path.moveTo(p.x(),p.y());
              path.arcTo(cX,cY,cW,cH,palpha-pdegree,360-Angle360(palpha-pdegree));
              path.lineTo(cX+cW,cY+cH/2+pW);
              path.arcTo(cX,cY+pW,cW,cH,0,-360+Angle360(palpha-pdegree));
          }
          // 5)
          else if((q ==1 || q==2) && (q_==1 || q_==2) && a<a_)
          {
              path.moveTo(cX,cY+cH/2);
              path.arcTo(cX,cY,cW,cH,180,180);
              path.lineTo(cX+cW,cY+cH/2+pW);
              path.arcTo(cX,cY+pW,cW,cH,0,-180);
              path.lineTo(cX,cY+cH/2);
          }
          if (!path.isEmpty())
          {
              gradient_side.setColorAt(1,pieces[i].rgbColor);
              painter->setBrush(gradient_side);
              painter->drawPath(path);
          }
        }
    }
    else if (this->ctype==Nightcharts::Histogramm)
    {
        double pDist = 15;
        double pW = (cW-(pieces.size())*pDist)/pieces.size();

        QLinearGradient gradient(cX+cW/2,cY,cX+cW/2,cY+cH);
        gradient.setColorAt(0,Qt::black);
        QPen pen;
        pen.setWidth(3);

        for (int i=0;i<pieces.size();i++)
        {
            if (shadows)
            {
                painter->setPen(Qt::NoPen);
                painter->setBrush(Qt::darkGray);
                painter->drawRect(cX+pDist+i*(pW + pDist)-pDist/2,cY+cH-1,pW,-cH/100*pieces[i].pPerc+pDist/2-5);
            }
            gradient.setColorAt(1,pieces[i].rgbColor);
            painter->setBrush(gradient);
            pen.setColor(pieces[i].rgbColor);
            painter->setPen(pen);
            painter->drawRect(cX+pDist+i*(pW + pDist),cY+cH,pW,-cH/100*pieces[i].pPerc-5);
            QString label = QString::number(pieces[i].pPerc)+"%";
            painter->setPen(Qt::SolidLine);
            painter->drawText(cX+pDist+i*(pW + pDist)+pW/2-painter->fontMetrics().width(label)/2,cY+cH-cH/100*pieces[i].pPerc-painter->fontMetrics().height()/2,label);
        }
        painter->setPen(Qt::SolidLine);
        for (int i=1;i<10;i++)
        {
            painter->drawLine(cX-3,cY+cH/10*i,cX+3,cY+cH/10*i);    //деления по оси Y
            //painter->drawText(cX-20,cY+cH/10*i,QString::number((10-i)*10)+"%");
        }
        painter->drawLine(cX,cY+cH,cX,cY);         //ось Y
        painter->drawLine(cX,cY,cX+4,cY+10);       //стрелки
        painter->drawLine(cX,cY,cX-4,cY+10);
        painter->drawLine(cX,cY+cH,cX+cW,cY+cH);   //ось Х

    }
    return 0;
}
void QgsComposerMapWidget::updateGuiElements()
{
  if ( mComposerMap )
  {
    blockAllSignals( true );

    //width, height, scale
    QRectF composerMapRect = mComposerMap->rect();
    mWidthLineEdit->setText( QString::number( composerMapRect.width() ) );
    mHeightLineEdit->setText( QString::number( composerMapRect.height() ) );
    mScaleLineEdit->setText( QString::number( mComposerMap->scale(), 'f', 0 ) );

    //preview mode
    QgsComposerMap::PreviewMode previewMode = mComposerMap->previewMode();
    int index = -1;
    if ( previewMode == QgsComposerMap::Cache )
    {
      index = mPreviewModeComboBox->findText( tr( "Cache" ) );
      mUpdatePreviewButton->setEnabled( true );
    }
    else if ( previewMode == QgsComposerMap::Render )
    {
      index = mPreviewModeComboBox->findText( tr( "Render" ) );
      mUpdatePreviewButton->setEnabled( true );
    }
    else if ( previewMode == QgsComposerMap::Rectangle )
    {
      index = mPreviewModeComboBox->findText( tr( "Rectangle" ) );
      mUpdatePreviewButton->setEnabled( false );
    }
    if ( index != -1 )
    {
      mPreviewModeComboBox->setCurrentIndex( index );
    }

    //composer map extent
    QgsRectangle composerMapExtent = mComposerMap->extent();
    mXMinLineEdit->setText( QString::number( composerMapExtent.xMinimum(), 'f', 3 ) );
    mXMaxLineEdit->setText( QString::number( composerMapExtent.xMaximum(), 'f', 3 ) );
    mYMinLineEdit->setText( QString::number( composerMapExtent.yMinimum(), 'f', 3 ) );
    mYMaxLineEdit->setText( QString::number( composerMapExtent.yMaximum(), 'f', 3 ) );

    mRotationSpinBox->setValue( mComposerMap->rotation() );

    //keep layer list check box
    if ( mComposerMap->keepLayerSet() )
    {
      mKeepLayerListCheckBox->setCheckState( Qt::Checked );
    }
    else
    {
      mKeepLayerListCheckBox->setCheckState( Qt::Unchecked );
    }

    //draw canvas items
    if ( mComposerMap->drawCanvasItems() )
    {
      mDrawCanvasItemsCheckBox->setCheckState( Qt::Checked );
    }
    else
    {
      mDrawCanvasItemsCheckBox->setCheckState( Qt::Unchecked );
    }

    //overview frame
    int overviewMapFrameId = mComposerMap->overviewFrameMapId();
    mOverviewFrameMapComboBox->setCurrentIndex( mOverviewFrameMapComboBox->findData( overviewMapFrameId ) );

    //grid
    if ( mComposerMap->gridEnabled() )
    {
      mGridCheckBox->setChecked( true );
    }
    else
    {
      mGridCheckBox->setChecked( false );
    }

    mIntervalXSpinBox->setValue( mComposerMap->gridIntervalX() );
    mIntervalYSpinBox->setValue( mComposerMap->gridIntervalY() );
    mOffsetXSpinBox->setValue( mComposerMap->gridOffsetX() );
    mOffsetYSpinBox->setValue( mComposerMap->gridOffsetY() );

    QgsComposerMap::GridStyle gridStyle = mComposerMap->gridStyle();
    if ( gridStyle == QgsComposerMap::Cross )
    {
      mGridTypeComboBox->setCurrentIndex( mGridTypeComboBox->findText( tr( "Cross" ) ) );
    }
    else
    {
      mGridTypeComboBox->setCurrentIndex( mGridTypeComboBox->findText( tr( "Solid" ) ) );
    }

    mCrossWidthSpinBox->setValue( mComposerMap->crossLength() );

    //grid frame
    mFrameWidthSpinBox->setValue( mComposerMap->gridFrameWidth() );
    QgsComposerMap::GridFrameStyle gridFrameStyle = mComposerMap->gridFrameStyle();
    if ( gridFrameStyle == QgsComposerMap::Zebra )
    {
      mFrameStyleComboBox->setCurrentIndex( mFrameStyleComboBox->findText( tr( "Zebra" ) ) );
    }
    else //NoGridFrame
    {
      mFrameStyleComboBox->setCurrentIndex( mFrameStyleComboBox->findText( tr( "No frame" ) ) );
    }

    //grid annotation format
    QgsComposerMap::GridAnnotationFormat gf = mComposerMap->gridAnnotationFormat();
    mAnnotationFormatComboBox->setCurrentIndex(( int )gf );

    //grid annotation position
    initAnnotationPositionBox( mAnnotationPositionLeftComboBox, mComposerMap->gridAnnotationPosition( QgsComposerMap::Left ) );
    initAnnotationPositionBox( mAnnotationPositionRightComboBox, mComposerMap->gridAnnotationPosition( QgsComposerMap::Right ) );
    initAnnotationPositionBox( mAnnotationPositionTopComboBox, mComposerMap->gridAnnotationPosition( QgsComposerMap::Top ) );
    initAnnotationPositionBox( mAnnotationPositionBottomComboBox, mComposerMap->gridAnnotationPosition( QgsComposerMap::Bottom ) );

    //grid annotation direction
    initAnnotationDirectionBox( mAnnotationDirectionComboBoxLeft, mComposerMap->gridAnnotationDirection( QgsComposerMap::Left ) );
    initAnnotationDirectionBox( mAnnotationDirectionComboBoxRight, mComposerMap->gridAnnotationDirection( QgsComposerMap::Right ) );
    initAnnotationDirectionBox( mAnnotationDirectionComboBoxTop, mComposerMap->gridAnnotationDirection( QgsComposerMap::Top ) );
    initAnnotationDirectionBox( mAnnotationDirectionComboBoxBottom, mComposerMap->gridAnnotationDirection( QgsComposerMap::Bottom ) );

    mDistanceToMapFrameSpinBox->setValue( mComposerMap->annotationFrameDistance() );

    if ( mComposerMap->showGridAnnotation() )
    {
      mDrawAnnotationCheckBox->setCheckState( Qt::Checked );
    }
    else
    {
      mDrawAnnotationCheckBox->setCheckState( Qt::Unchecked );
    }

    mCoordinatePrecisionSpinBox->setValue( mComposerMap->gridAnnotationPrecision() );

    QPen gridPen = mComposerMap->gridPen();
    mLineWidthSpinBox->setValue( gridPen.widthF() );
    mLineColorButton->setColor( gridPen.color() );

    blockAllSignals( false );
  }
}
Ejemplo n.º 9
0
Archivo: main.cpp Proyecto: BGmot/Qt
QImage createImage(int width, int height)
{
    QImage image(width, height, QImage::Format_RGB16);
    QPainter painter;
    QPen pen;
    pen.setStyle(Qt::NoPen);
    QBrush brush(Qt::blue);

    painter.begin(&image);
    painter.fillRect(image.rect(), brush);
    brush.setColor(Qt::white);
    painter.setPen(pen);
    painter.setBrush(brush);

    static const QPointF points1[3] = {
        QPointF(4, 4),
        QPointF(7, 4),
        QPointF(5.5, 1)
    };

    static const QPointF points2[3] = {
        QPointF(1, 4),
        QPointF(7, 4),
        QPointF(10, 10)
    };

    static const QPointF points3[3] = {
        QPointF(4, 4),
        QPointF(10, 4),
        QPointF(1, 10)
    };

    painter.setWindow(0, 0, 10, 10);

    int x = 0;
    int y = 0;
    int starWidth = image.width()/3;
    int starHeight = image.height()/3; 

    QRect rect(x, y, starWidth, starHeight);

    for (int i = 0; i < 9; ++i) {

        painter.setViewport(rect);
        painter.drawPolygon(points1, 3);
        painter.drawPolygon(points2, 3);
        painter.drawPolygon(points3, 3);

        if (i % 3 == 2) {
            y = y + starHeight;
            rect.moveTop(y);

            x = 0;
            rect.moveLeft(x);

        } else {
            x = x + starWidth;
            rect.moveLeft(x);
        }
    }

    painter.end();
    return image;
}
Ejemplo n.º 10
0
void ListViewDelegate::paintGraphLane(QPainter* p, int type, int x1, int x2,
                                      const QColor& col, const QColor& activeCol, const QBrush& back) const {

	int h = laneHeight / 2;
	int m = (x1 + x2) / 2;
	int r = (x2 - x1) / 3;
	int d =  2 * r;

	#define P_CENTER m , h
	#define P_0      x2, h      // >
	#define P_90     m , 0      // ^
	#define P_180    x1, h      // <
	#define P_270    m , 2 * h  // v
	#define DELTA_UR 2*(x1 - m), 2*h ,   0*16, 90*16  // -,
	#define DELTA_DR 2*(x1 - m), 2*-h, 270*16, 90*16  // -'
	#define DELTA_UL 2*(x2 - m), 2*h ,  90*16, 90*16  //  ,-
	#define DELTA_DL 2*(x2 - m), 2*-h, 180*16, 90*16  //  '-
	#define CENTER_UR x1, 2*h, 225
	#define CENTER_DR x1, 0  , 135
	#define CENTER_UL x2, 2*h, 315
	#define CENTER_DL x2, 0  ,  45
	#define R_CENTER m - r, h - r, d, d

	static QPen myPen(Qt::black, 2); // fast path here
    static QPen blackSolidThickPen(Qt::black, 2, Qt::SolidLine);
    static QBrush whiteBrush(Qt::white);

	// arc
	switch (type) {
	case JOIN:
	case JOIN_R:
	case HEAD:
	case HEAD_R: {
		QConicalGradient gradient(CENTER_UR);
		gradient.setColorAt(0.375, col);
		gradient.setColorAt(0.625, activeCol);
		myPen.setBrush(gradient);
		p->setPen(myPen);
		p->drawArc(P_CENTER, DELTA_UR);
		break;
	}
	case JOIN_L: {
		QConicalGradient gradient(CENTER_UL);
		gradient.setColorAt(0.375, activeCol);
		gradient.setColorAt(0.625, col);
		myPen.setBrush(gradient);
		p->setPen(myPen);
		p->drawArc(P_CENTER, DELTA_UL);
		break;
	}
	case TAIL:
	case TAIL_R: {
		QConicalGradient gradient(CENTER_DR);
		gradient.setColorAt(0.375, activeCol);
		gradient.setColorAt(0.625, col);
		myPen.setBrush(gradient);
		p->setPen(myPen);
		p->drawArc(P_CENTER, DELTA_DR);
		break;
	}
	default:
		break;
	}

	myPen.setColor(col);
	p->setPen(myPen);

	// vertical line
	switch (type) {
	case ACTIVE:
	case NOT_ACTIVE:
	case MERGE_FORK:
	case MERGE_FORK_R:
	case MERGE_FORK_L:
	case JOIN:
	case JOIN_R:
	case JOIN_L:
	case CROSS:
		p->drawLine(P_90, P_270);
		break;
	case HEAD_L:
	case BRANCH:
		p->drawLine(P_CENTER, P_270);
		break;
	case TAIL_L:
	case INITIAL:
	case BOUNDARY:
	case BOUNDARY_C:
	case BOUNDARY_R:
	case BOUNDARY_L:
		p->drawLine(P_90, P_CENTER);
		break;
	default:
		break;
	}

	myPen.setColor(activeCol);
	p->setPen(myPen);

	// horizontal line
	switch (type) {
	case MERGE_FORK:
	case JOIN:
	case HEAD:
	case TAIL:
	case CROSS:
	case CROSS_EMPTY:
	case BOUNDARY_C:
		p->drawLine(P_180, P_0);
		break;
	case MERGE_FORK_R:
	case BOUNDARY_R:
		p->drawLine(P_180, P_CENTER);
		break;
	case MERGE_FORK_L:
	case HEAD_L:
	case TAIL_L:
	case BOUNDARY_L:
		p->drawLine(P_CENTER, P_0);
		break;
	default:
		break;
	}

	// center symbol, e.g. rect or ellipse
	switch (type) {
	case ACTIVE:
	case INITIAL:
	case BRANCH:
        p->setPen(blackSolidThickPen);
        p->setBrush(whiteBrush);
		p->drawEllipse(R_CENTER);
        p->setPen(Qt::NoPen);
		break;
	case MERGE_FORK:
	case MERGE_FORK_R:
	case MERGE_FORK_L:
        p->setPen(blackSolidThickPen);
        p->setBrush(whiteBrush);
        p->drawEllipse(R_CENTER);
        p->setPen(Qt::NoPen);
		break;
	case UNAPPLIED:
		// Red minus sign
		p->setPen(Qt::NoPen);
		p->setBrush(Qt::red);
		p->drawRect(m - r, h - 1, d, 2);
		break;
	case APPLIED:
		// Green plus sign
		p->setPen(Qt::NoPen);
		p->setBrush(DARK_GREEN);
		p->drawRect(m - r, h - 1, d, 2);
		p->drawRect(m - 1, h - r, 2, d);
		break;
	case BOUNDARY:
		p->setBrush(back);
		p->drawEllipse(R_CENTER);
		break;
	case BOUNDARY_C:
	case BOUNDARY_R:
	case BOUNDARY_L:
		p->setBrush(back);
		p->drawRect(R_CENTER);
		break;
	default:
		break;
	}
	#undef P_CENTER
	#undef P_0
	#undef P_90
	#undef P_180
	#undef P_270
	#undef DELTA_UR
	#undef DELTA_DR
	#undef DELTA_UL
	#undef DELTA_DL
	#undef CENTER_UR
	#undef CENTER_DR
	#undef CENTER_UL
	#undef CENTER_DL
	#undef R_CENTER
}
Ejemplo n.º 11
0
void QgsSimpleLineSymbolLayerV2::applyDataDefinedSymbology( QgsSymbolV2RenderContext& context, QPen& pen, QPen& selPen, double& offset )
{
  //data defined properties
  double scaledWidth = 0;
  QgsExpression* strokeWidthExpression = expression( "width" );
  if ( strokeWidthExpression )
  {
    scaledWidth = strokeWidthExpression->evaluate( const_cast<QgsFeature*>( context.feature() ) ).toDouble()
                  * QgsSymbolLayerV2Utils::lineWidthScaleFactor( context.renderContext(), mWidthUnit );
    pen.setWidthF( scaledWidth );
    selPen.setWidthF( scaledWidth );
  }
  else if ( context.renderHints() & QgsSymbolV2::DataDefinedSizeScale )
  {
    scaledWidth = mWidth * QgsSymbolLayerV2Utils::lineWidthScaleFactor( context.renderContext(), mWidthUnit );
    pen.setWidthF( scaledWidth );
    selPen.setWidthF( scaledWidth );
  }

  //color
  QgsExpression* strokeColorExpression = expression( "color" );
  if ( strokeColorExpression )
  {
    pen.setColor( QgsSymbolLayerV2Utils::decodeColor( strokeColorExpression->evaluate( const_cast<QgsFeature*>( context.feature() ) ).toString() ) );
  }

  //offset
  offset = mOffset;
  QgsExpression* lineOffsetExpression = expression( "offset" );
  if ( lineOffsetExpression )
  {
    offset = lineOffsetExpression->evaluate( const_cast<QgsFeature*>( context.feature() ) ).toDouble();
  }

  //dash dot vector
  QgsExpression* dashPatternExpression = expression( "customdash" );
  if ( dashPatternExpression )
  {
    QVector<qreal> dashVector;
    QStringList dashList = dashPatternExpression->evaluate( const_cast<QgsFeature*>( context.feature() ) ).toString().split( ";" );
    QStringList::const_iterator dashIt = dashList.constBegin();
    for ( ; dashIt != dashList.constEnd(); ++dashIt )
    {
      dashVector.push_back( dashIt->toDouble() * QgsSymbolLayerV2Utils::lineWidthScaleFactor( context.renderContext(), mCustomDashPatternUnit ) / mPen.widthF() );
    }
    pen.setDashPattern( dashVector );
  }

  //join style
  QgsExpression* joinStyleExpression = expression( "joinstyle" );
  if ( joinStyleExpression )
  {
    QString joinStyleString = joinStyleExpression->evaluate( const_cast<QgsFeature*>( context.feature() ) ).toString();
    pen.setJoinStyle( QgsSymbolLayerV2Utils::decodePenJoinStyle( joinStyleString ) );
  }

  //cap style
  QgsExpression* capStyleExpression = expression( "capstyle" );
  if ( capStyleExpression )
  {
    QString capStyleString = capStyleExpression->evaluate( const_cast<QgsFeature*>( context.feature() ) ).toString();
    pen.setCapStyle( QgsSymbolLayerV2Utils::decodePenCapStyle( capStyleString ) );
  }
}
Ejemplo n.º 12
0
void Highscore::addGraphForAllRunsOfOnePerson(QCustomPlot *plot, Person p) {
    plot->plotLayout()->insertRow(0);
    plot->plotLayout()->addElement(0, 0, new QCPPlotTitle(plot, "Alle absolvierten Durchgänge"));

    int runsCount = p.runs.size();
    int xMin = -1;
    int xMax = runsCount+1;
    int yMin = 0;
    double yMax = 0;
    int yMaxErr = 0;

    QVector<double> x(runsCount), y(runsCount), y2(runsCount*11), x2(runsCount*11);
    for(int i = 0; i<runsCount; i++) {
        y[i] = p.runs.at(i).typePoints.size()/ (p.runs.at(i).runScoreTime/60000.0);
        x[i] = i;
        yMax = std::max(y[i],yMax);
        for(double j = 0; j<11; j++) {
            y2[11*i+j] =  p.runs.at(i).runError;
            x2[11*i+j] =  (i-0.02)+(0.004*j);
        }
        yMaxErr = std::max(p.runs.at(i).runError,yMaxErr);

    }
    plot->addGraph(plot->xAxis, plot->yAxis);
    plot->graph(0)->setName("Anschläge / Minute");
    plot->graph(0)->setData(x,y);
    plot->graph(0)->setLineStyle((QCPGraph::LineStyle)(1));
    plot->graph(0)->setScatterStyle(QCPScatterStyle((QCPScatterStyle::ScatterShape)(1)));

    QPen graphPen;
    graphPen.setColor(QColor(200, 50, 0, 85));
    graphPen.setWidthF(2);
    plot->graph(0)->setPen(graphPen);

    plot->addGraph(plot->xAxis, plot->yAxis2);
    plot->graph(1)->setName("Fehler");
    plot->graph(1)->setData(x2,y2);
    plot->graph(1)->setLineStyle((QCPGraph::LineStyle)(5));

    QPen graphPen2;
    graphPen2.setColor(QColor(0, 50, 0, 100));
    graphPen2.setWidthF(3);
    plot->graph(1)->setPen(graphPen2);

    plot->yAxis2->setVisible(true);
    plot->xAxis2->setVisible(true);
    plot->xAxis->setVisible(true);

    plot->xAxis->setLabel("Durchlauf");
    plot->yAxis->setLabel("Anschläge pro Minute");
    plot->yAxis2->setLabel("Fehler");

    plot->xAxis->setRange(xMin, xMax);
    plot->yAxis->setRange(yMin, yMax+1);
    plot->yAxis2->setRange(yMin,yMaxErr*1.5 );
    plot->xAxis2->setRange(xMin, xMax);

    plot->xAxis->setAutoTickStep(false);
    plot->xAxis->setTickStep(1);
    plot->xAxis->setSubTickCount(1);


    plot->xAxis2->setTickLength(0, 0);
    plot->xAxis2->setSubTickLength(0, 0);
    plot->xAxis2->setTickStep(false);
    plot->xAxis2->setAutoTickLabels(false);
    plot->xAxis2->setTickLabels(false);

    plot->yAxis2->setAutoTickStep(false);
    plot->yAxis2->setTickStep(1);
    plot->yAxis2->setSubTickCount(0);
    plot->yAxis2->setTickLength(3, 3);
    plot->yAxis2->setSubTickLength(0, 0);

    plot->graph(0)->setBrush(QBrush(QColor(255,200,20,70)));
}
Ejemplo n.º 13
0
void Highscore::addGraphOneBestToOneActual(QCustomPlot *plot, Run rL, Run rB) {

    plot->legend->setVisible(true);
    plot->legend->setFont(QFont("Helvetica",9));
    plot->setLocale(QLocale(QLocale::English, QLocale::UnitedKingdom));

    int typePointsCount = rB.typePoints.size();
    int xMin = -1;
    int xMax = typePointsCount+1;
    int yMin = 0;
    double yMax = 0;
    int yMaxErr = 0;

    QVector<double> x(typePointsCount), y(typePointsCount), y2(typePointsCount*11), x2(typePointsCount*11);
    for(int i = 0; i<typePointsCount; i++) {
        y[i] = 1/ (rB.typePoints.at(i).timeInMilliSeconds/60000.0);
        x[i] = i;
        yMax = std::max(y[i],yMax);
        for(double j = 0; j<11; j++) {
            y2[11*i+j] =  rB.typePoints.at(i).error;
            x2[11*i+j] =  (i-0.02)+(0.004*j)+0.04;
        }
        yMaxErr = std::max(rB.typePoints.at(i).error,yMaxErr);

    }
    plot->addGraph(plot->xAxis, plot->yAxis);
    plot->graph(0)->setName("Anschläge / Minute");
    plot->graph(0)->setData(x,y);
    plot->graph(0)->setLineStyle((QCPGraph::LineStyle)(1));
    plot->graph(0)->setScatterStyle(QCPScatterStyle((QCPScatterStyle::ScatterShape)(1)));

    QPen graphPen;
    graphPen.setColor(QColor(200, 50, 0, 85));
    graphPen.setWidthF(2);
    plot->graph(0)->setPen(graphPen);

    plot->addGraph(plot->xAxis, plot->yAxis2);
    plot->graph(1)->setName("Fehler");
    plot->graph(1)->setData(x2,y2);
    plot->graph(1)->setLineStyle((QCPGraph::LineStyle)(5));

    QPen graphPen1;
    graphPen1.setColor(QColor(200, 50, 0, 100));
    graphPen1.setWidthF(3);
    plot->graph(1)->setPen(graphPen1);

    //plot->graph(0)->setBrush(QBrush(QColor(255,200,20,70)));

    typePointsCount = rL.typePoints.size();
    xMin = -1;
    xMax = typePointsCount+1;

    QVector<double> x3(typePointsCount), y3(typePointsCount), y4(typePointsCount*11), x4(typePointsCount*11);
    for(int i = 0; i<typePointsCount; i++) {
        y3[i] = 1/ (rL.typePoints.at(i).timeInMilliSeconds/60000.0);
        x3[i] = i;
        yMax = std::max(y3[i],yMax);
        for(double j = 0; j<11; j++) {
            y4[11*i+j] =  rL.typePoints.at(i).error;
            x4[11*i+j] =  (i-0.02)+(0.004*j)-0.04;
        }
        yMaxErr = std::max(rL.typePoints.at(i).error,yMaxErr);

    }
    plot->addGraph(plot->xAxis, plot->yAxis);
    plot->graph(2)->setName("Anschläge / Minute");
    plot->graph(2)->setData(x3,y3);
    plot->graph(2)->setLineStyle((QCPGraph::LineStyle)(1));
    plot->graph(2)->setScatterStyle(QCPScatterStyle((QCPScatterStyle::ScatterShape)(1)));

    QPen graphPen2;
    graphPen2.setColor(QColor(130, 30, 0, 85));
    graphPen2.setWidthF(2);
    plot->graph(2)->setPen(graphPen2);

    plot->addGraph(plot->xAxis, plot->yAxis2);
    plot->graph(3)->setName("Fehler");
    plot->graph(3)->setData(x4,y4);
    plot->graph(3)->setLineStyle((QCPGraph::LineStyle)(5));

    QPen graphPen3;
    graphPen3.setColor(QColor(130, 30, 0, 100));
    graphPen3.setWidthF(3);
    plot->graph(3)->setPen(graphPen3);

    plot->yAxis2->setVisible(true);
    plot->xAxis2->setVisible(true);
    plot->xAxis->setVisible(true);

    plot->xAxis->setLabel("Durchlauf");
    plot->yAxis->setLabel("Anschläge pro Minute");
    plot->yAxis2->setLabel("Fehler");

    plot->xAxis->setRange(xMin, xMax);
    plot->yAxis->setRange(yMin, yMax+1);
    plot->yAxis2->setRange(yMin,yMaxErr*1.5 );
    plot->xAxis2->setRange(xMin, xMax);

    plot->xAxis->setAutoTickStep(false);
    plot->xAxis->setTickStep(1);
    plot->xAxis->setSubTickCount(1);


    plot->xAxis2->setTickLength(0, 0);
    plot->xAxis2->setSubTickLength(0, 0);
    plot->xAxis2->setTickStep(false);
    plot->xAxis2->setAutoTickLabels(false);
    plot->xAxis2->setTickLabels(false);

    plot->yAxis2->setAutoTickStep(false);
    plot->yAxis2->setTickStep(1);
    plot->yAxis2->setSubTickCount(0);
    plot->yAxis2->setTickLength(3, 3);
    plot->yAxis2->setSubTickLength(0, 0);


    //plot->graph(0)->setBrush(QBrush(QColor(255,200,20,70)));
}
Ejemplo n.º 14
0
void Highscore::addGraphForLastRunOfOnePerson(QCustomPlot *plot, Run r) {
    int typePointsCount = r.typePoints.size();
    int xMin = -1;
    int xMax = typePointsCount+1;
    int yMin = 0;
    double yMax = 0;
    int yMaxErr = 0;

    QVector<double> x(typePointsCount), y(typePointsCount), y2(typePointsCount*11), x2(typePointsCount*11);
    for(int i = 0; i<typePointsCount; i++) {
        y[i] = 1/ (r.typePoints.at(i).timeInMilliSeconds/60000.0);
        x[i] = i;
        yMax = std::max(y[i],yMax);
        for(double j = 0; j<11; j++) {
            y2[11*i+j] =  r.typePoints.at(i).error;
            x2[11*i+j] =  (i-0.02)+(0.004*j);
        }
        yMaxErr = std::max(r.typePoints.at(i).error,yMaxErr);

    }
    plot->addGraph(plot->xAxis, plot->yAxis);
    plot->graph(0)->setName("Anschläge / Minute");
    plot->graph(0)->setData(x,y);
    plot->graph(0)->setLineStyle((QCPGraph::LineStyle)(1));
    plot->graph(0)->setScatterStyle(QCPScatterStyle((QCPScatterStyle::ScatterShape)(1)));

    QPen graphPen;
    graphPen.setColor(QColor(200, 50, 0, 85));
    graphPen.setWidthF(2);
    plot->graph(0)->setPen(graphPen);

    plot->addGraph(plot->xAxis, plot->yAxis2);
    plot->graph(1)->setName("Fehler");
    plot->graph(1)->setData(x2,y2);
    plot->graph(1)->setLineStyle((QCPGraph::LineStyle)(5));

    QPen graphPen2;
    graphPen2.setColor(QColor(0, 50, 0, 100));
    graphPen2.setWidthF(3);
    plot->graph(1)->setPen(graphPen2);

    plot->yAxis2->setVisible(true);
    plot->xAxis2->setVisible(true);
    plot->xAxis->setVisible(true);

    plot->xAxis->setLabel("Durchlauf");
    plot->yAxis->setLabel("Anschläge pro Minute");
    plot->yAxis2->setLabel("Fehler");

    plot->xAxis->setRange(xMin, xMax);
    plot->yAxis->setRange(yMin, yMax+1);
    plot->yAxis2->setRange(yMin,yMaxErr*1.5 );
    plot->xAxis2->setRange(xMin, xMax);

    plot->xAxis->setAutoTickStep(false);
    plot->xAxis->setTickStep(1);
    plot->xAxis->setSubTickCount(1);


    plot->xAxis2->setTickLength(0, 0);
    plot->xAxis2->setSubTickLength(0, 0);
    plot->xAxis2->setTickStep(false);
    plot->xAxis2->setAutoTickLabels(false);
    plot->xAxis2->setTickLabels(false);

    plot->yAxis2->setAutoTickStep(false);
    plot->yAxis2->setTickStep(1);
    plot->yAxis2->setSubTickCount(0);
    plot->yAxis2->setTickLength(3, 3);
    plot->yAxis2->setSubTickLength(0, 0);

    plot->graph(0)->setBrush(QBrush(QColor(255,200,20,70)));
}
Ejemplo n.º 15
0
bool DomConvenience::variantToElement(const QVariant& v, QDomElement& e)
{
	bool ok = true;

	clearAttributes(e);

	switch (v.type())
	{
		case QVariant::String:
			e.setTagName("string");
			e.setAttribute("value", v.toString());
			break;
#if 0
		case QVariant::CString:
			e.setTagName("string");
			e.setAttribute("value", v.toString());
			break;
#endif
		case QVariant::Int:
			e.setTagName("int");
			e.setAttribute("value", v.toInt());
			break;
		case QVariant::UInt:
			e.setTagName("uint");
			e.setAttribute("value", v.toUInt());
			break;
		case QVariant::Double:
			e.setTagName("double");
			e.setAttribute("value", v.toDouble());
			break;
		case QVariant::Bool:
			e.setTagName("bool");
			e.setAttribute("value", boolString(v.toBool()));
			break;
		case QVariant::Color:
		{
			e.setTagName("color");
			QColor color = v.value<QColor>();
			e.setAttribute("red", color.red());
			e.setAttribute("green", color.green());
			e.setAttribute("blue", color.blue());
		}
			break;
		case QVariant::Pen:
		{
			e.setTagName("pen");
			QPen pen = v.value<QPen>();
			e.setAttribute("red", pen.color().red());
			e.setAttribute("green", pen.color().green());
			e.setAttribute("blue", pen.color().blue());
			e.setAttribute("style", pen.style());
			e.setAttribute("cap", pen.capStyle());
			e.setAttribute("join", pen.joinStyle());
		}
			break;
		case QVariant::Brush:
		{
			e.setTagName("brush");
			QBrush brush = v.value<QBrush>();
			e.setAttribute("red", brush.color().red());
			e.setAttribute("green", brush.color().green());
			e.setAttribute("blue", brush.color().blue());
			e.setAttribute("style", brush.style());
		}
			break;
		case QVariant::Point:
		{
			e.setTagName("point");
			QPoint point = v.toPoint();
			e.setAttribute("x", point.x());
			e.setAttribute("y", point.y());
		}
			break;
		case QVariant::Rect:
		{
			e.setTagName("rect");
			QRect rect = v.toRect();
			e.setAttribute("x", rect.x());
			e.setAttribute("y", rect.y());
			e.setAttribute("width", rect.width());
			e.setAttribute("height", rect.height());
		}
			break;
		case QVariant::Size:
		{
			e.setTagName("size");
			QSize qsize = v.toSize();
			e.setAttribute("width", qsize.width());
			e.setAttribute("height", qsize.height());
		}
			break;
		case QVariant::Font:
		{
			e.setTagName("font");
			QFont f(v.value<QFont>());
			e.setAttribute("family", f.family());
			e.setAttribute("pointsize", f.pointSize());
			e.setAttribute("bold", boolString(f.bold()));
			e.setAttribute("italic", boolString(f.italic()));
			e.setAttribute("underline", boolString(f.underline()));
			e.setAttribute("strikeout", boolString(f.strikeOut()));
		}
			break;
		case QVariant::SizePolicy:
		{
			e.setTagName("sizepolicy");
			QSizePolicy sp(v.value<QSizePolicy>());
			e.setAttribute("hsizetype", sp.horData());
			e.setAttribute("vsizetype", sp.verData());
			e.setAttribute("horstretch", sp.horStretch());
			e.setAttribute("verstretch", sp.verStretch());
		}
			break;
		case QVariant::Cursor:
			e.setTagName("cursor");
			e.setAttribute("shape", v.value<QCursor>().shape());
			break;

		case QVariant::StringList:
		{
			e.setTagName("stringlist");
			int32_t j;

			QDomNode n;
			QDomNodeList stringNodeList = e.elementsByTagName("string");
			QDomElement stringElem;
			QStringList stringList = v.toStringList();
			QStringList::Iterator it = stringList.begin();

			for (j = 0;
				 ((j < (int32_t)stringNodeList.length()) && (it != stringList.end()));
				 j++)
			{
				// get the current string element
				stringElem = stringNodeList.item(j).toElement();

				// set it to the current string
				variantToElement(QVariant(*it), stringElem);

				// iterate to the next string
				++it;
			}

			// more nodes in previous stringlist then current, remove excess nodes
			if (stringNodeList.count() > stringList.count())
			{
				while (j < (int32_t)stringNodeList.count())
					e.removeChild(stringNodeList.item(j).toElement());
			}
			else if (j < (int32_t)stringList.count())
			{
				while (it != stringList.end())
				{
					// create a new element
					stringElem = m_doc.createElement("string");

					// set it to the currentstring
					variantToElement(QVariant(*it), stringElem);

					// append it to the current element
					e.appendChild(stringElem);

					// iterate to the next string
					++it;
				}
			}
		}
			break;

		case QVariant::KeySequence:
			e.setTagName("key");
			e.setAttribute("sequence", (QString)v.value<QKeySequence>().toString());
			break;

		case QVariant::ByteArray: // this is only for [u]int64_t
		{
			e.setTagName("data");

			// set the value
			e.setAttribute("value", getStringFromByteArray(v.toByteArray()));
		}
			break;

		default:
			qWarning("Don't know how to persist variant of type: %s (%d)!",
					 v.typeName(), v.type());
			ok = false;
			break;
	}

	return ok;
}
Ejemplo n.º 16
0
void
UBBoardView::drawBackground (QPainter *painter, const QRectF &rect)
{
  if (testAttribute (Qt::WA_TranslucentBackground))
    {
      QGraphicsView::drawBackground (painter, rect);
      return;
    }

  bool darkBackground = scene () && scene ()->isDarkBackground ();

  if (darkBackground)
    {
      painter->fillRect (rect, QBrush (QColor (Qt::black)));
    }
  else
    {
      painter->fillRect (rect, QBrush (QColor (Qt::white)));
    }

  if (transform ().m11 () > 0.5)
    {
      QColor bgCrossColor;

      if (darkBackground)
        bgCrossColor = UBSettings::crossDarkBackground;
      else
        bgCrossColor = UBSettings::crossLightBackground;

      if (transform ().m11 () < 1.0)
        {
          int alpha = 255 * transform ().m11 () / 2;
          bgCrossColor.setAlpha (alpha); // fade the crossing on small zooms
        }

      painter->setPen (bgCrossColor);

      if (scene () && scene ()->isCrossedBackground ())
        {
          qreal firstY = ((int) (rect.y () / UBSettings::crossSize)) * UBSettings::crossSize;

          for (qreal yPos = firstY; yPos < rect.y () + rect.height (); yPos += UBSettings::crossSize)
            {
              painter->drawLine (rect.x (), yPos, rect.x () + rect.width (), yPos);
            }

          qreal firstX = ((int) (rect.x () / UBSettings::crossSize)) * UBSettings::crossSize;

          for (qreal xPos = firstX; xPos < rect.x () + rect.width (); xPos += UBSettings::crossSize)
            {
              painter->drawLine (xPos, rect.y (), xPos, rect.y () + rect.height ());
            }
        }
    }

  if (!mFilterZIndex && scene ())
    {
      QSize pageNominalSize = scene ()->nominalSize ();

      if (pageNominalSize.isValid ())
        {
          qreal penWidth = 8.0 / transform ().m11 ();

          QRectF pageRect (pageNominalSize.width () / -2, pageNominalSize.height () / -2
                           , pageNominalSize.width (), pageNominalSize.height ());

          pageRect.adjust (-penWidth / 2, -penWidth / 2, penWidth / 2, penWidth / 2);

          QColor docSizeColor;

          if (darkBackground)
            docSizeColor = UBSettings::documentSizeMarkColorDarkBackground;
          else
            docSizeColor = UBSettings::documentSizeMarkColorLightBackground;

          QPen pen (docSizeColor);
          pen.setWidth (penWidth);
          painter->setPen (pen);
          painter->drawRect (pageRect);
        }
    }
}
Ejemplo n.º 17
0
void PlotCurve::restoreCurveLayout(const QStringList& lst)
{
  QStringList::const_iterator line = lst.begin();
  for (line++; line != lst.end(); ++line){
    QString s = *line;
    if (s == "<Pen>"){
      QPen pen;
      while(s != "</Pen>"){
        s = (*(++line)).stripWhiteSpace();
        if (s.contains("<Color>"))
          pen.setColor(QColor(s.remove("<Color>").remove("</Color>")));
        else if (s.contains("<Style>"))
          pen.setStyle(Graph::getPenStyle(s.remove("<Style>").remove("</Style>").toInt()));
        else if (s.contains("<Width>"))
          pen.setWidthF(s.remove("<Width>").remove("</Width>").toDouble());
      }
      setPen(pen);
    } else if (s == "<Brush>"){
      QBrush brush;
      while(s != "</Brush>"){
        s = (*(++line)).stripWhiteSpace();
        if (s.contains("<Color>"))
          brush.setColor(QColor(s.remove("<Color>").remove("</Color>")));
        else if (s.contains("<Style>"))
          brush.setStyle(PatternBox::brushStyle(s.remove("<Style>").remove("</Style>").toInt()));
      }
      setBrush(brush);
    } else if (s == "<Symbol>"){
      QwtSymbol symbol;
      while(s != "</Symbol>"){
        s = (*(++line)).stripWhiteSpace();
        if (s.contains("<Style>"))
          symbol.setStyle(SymbolBox::style(s.remove("<Style>").remove("</Style>").toInt()));
        else if (s.contains("<Size>"))
          symbol.setSize((QwtSymbol::Style)s.remove("<Size>").remove("</Size>").toInt());
        else if (s == "<SymbolPen>"){
          QPen pen;
          while(s != "</SymbolPen>"){
            s = (*(++line)).stripWhiteSpace();
            if (s.contains("<Color>"))
              pen.setColor(QColor(s.remove("<Color>").remove("</Color>")));
            else if (s.contains("<Style>"))
              pen.setStyle(Graph::getPenStyle(s.remove("<Style>").remove("</Style>").toInt()));
            else if (s.contains("<Width>"))
              pen.setWidthF(s.remove("<Width>").remove("</Width>").toDouble());
          }
          symbol.setPen(pen);
        } else if (s == "<SymbolBrush>"){
          QBrush brush;
          while(s != "</SymbolBrush>"){
            s = (*(++line)).stripWhiteSpace();
            if (s.contains("<Color>"))
              brush.setColor(QColor(s.remove("<Color>").remove("</Color>")));
            else if (s.contains("<Style>"))
              brush.setStyle(PatternBox::brushStyle(s.remove("<Style>").remove("</Style>").toInt()));
          }
          symbol.setBrush(brush);
        }
        setSymbol(symbol);
      }
    } else if (s.contains("<xAxis>"))
      setXAxis(s.remove("<xAxis>").remove("</xAxis>").toInt());
    else if (s.contains("<yAxis>"))
      setYAxis(s.remove("<yAxis>").remove("</yAxis>").toInt());
    else if (s.contains("<Visible>"))
      setVisible(s.remove("<Visible>").remove("</Visible>").toInt());
  }
}
Ejemplo n.º 18
0
void ArrowMarker::draw(QPainter *p, const QwtScaleMap &xMap, const QwtScaleMap &yMap, const QRect &) const
{
	const int x0 = xMap.transform(d_rect.left());
	const int y0 = yMap.transform(d_rect.top());
	const int x1 = xMap.transform(d_rect.right());
	const int y1 = yMap.transform(d_rect.bottom());

	p->save();
	QPen pen = linePen();
	p->setPen(pen);

	QBrush brush = QBrush(pen.color(), Qt::SolidPattern);
	QwtPainter::drawLine(p,x0,y0,x1,y1);
	p->restore();

	if (d_end_arrow)
		{
		p->save();
		p->translate(x1,y1);
		const double t = theta(x0, y0, x1, y1);
		p->rotate(-t);

		QPolygon endArray(3);
		endArray[0] = QPoint(0,0);

		int d=(int)floor(d_head_length*tan(M_PI*d_head_angle/180.0)+0.5);
		endArray[1] = QPoint(-d_head_length,d);
		endArray[2] = QPoint(-d_head_length,-d);

		p->setPen(QPen(pen.color(), pen.width(), Qt::SolidLine));
		if (d_fill_head)
			p->setBrush(brush);

		QwtPainter::drawPolygon(p,endArray);
		p->restore();
		}

	if (d_start_arrow)
		{
		p->save();
		p->translate(x0,y0);
		const double t = theta(x0, y0, x1, y1);
		p->rotate(-t);

		QPolygon startArray(3);
		startArray[0] = QPoint(0,0);

		int d=(int)floor(d_head_length*tan(M_PI*d_head_angle/180.0)+0.5);
		startArray[1] = QPoint(d_head_length,d);
		startArray[2] = QPoint(d_head_length,-d);

		p->setPen(QPen(pen.color(), pen.width(), Qt::SolidLine));
		if (d_fill_head)
			p->setBrush(brush);
		QwtPainter::drawPolygon(p,startArray);
		p->restore();
		}

	if (d_editable) {
		p->save();
		p->setPen(QPen(Qt::black,1,Qt::SolidLine));
		QRect handler(QPoint(0,0), QSize(10,10));
		handler.moveCenter(startPoint());
		p->fillRect(handler, QBrush(Qt::black));
		handler.moveCenter(endPoint());
		p->fillRect(handler, QBrush(Qt::black));
		p->restore();
	}
}
void QwtErrorPlotCurve::setColor(const QColor& c)
{
	QPen p = pen();
  	p.setColor(c);
  	setPen(p);
}
Ejemplo n.º 20
0
void QgsPaperGrid::paint( QPainter* painter, const QStyleOptionGraphicsItem* itemStyle, QWidget* pWidget )
{
  Q_UNUSED( itemStyle );
  Q_UNUSED( pWidget );

  //draw grid
  if ( mComposition )
  {
    if ( mComposition->gridVisible() && mComposition->plotStyle() ==  QgsComposition::Preview
         && mComposition->snapGridResolution() > 0 )
    {
      int gridMultiplyX = static_cast< int >( mComposition->snapGridOffsetX() / mComposition->snapGridResolution() );
      int gridMultiplyY = static_cast< int >( mComposition->snapGridOffsetY() / mComposition->snapGridResolution() );
      double currentXCoord = mComposition->snapGridOffsetX() - gridMultiplyX * mComposition->snapGridResolution();
      double currentYCoord;
      double minYCoord = mComposition->snapGridOffsetY() - gridMultiplyY * mComposition->snapGridResolution();

      painter->save();
      //turn of antialiasing so grid is nice and sharp
      painter->setRenderHint( QPainter::Antialiasing, false );

      if ( mComposition->gridStyle() == QgsComposition::Solid )
      {
        painter->setPen( mComposition->gridPen() );

        //draw vertical lines
        for ( ; currentXCoord <= rect().width(); currentXCoord += mComposition->snapGridResolution() )
        {
          painter->drawLine( QPointF( currentXCoord, 0 ), QPointF( currentXCoord, rect().height() ) );
        }

        //draw horizontal lines
        currentYCoord = minYCoord;
        for ( ; currentYCoord <= rect().height(); currentYCoord += mComposition->snapGridResolution() )
        {
          painter->drawLine( QPointF( 0, currentYCoord ), QPointF( rect().width(), currentYCoord ) );
        }
      }
      else //'Dots' or 'Crosses'
      {
        QPen gridPen = mComposition->gridPen();
        painter->setPen( gridPen );
        painter->setBrush( QBrush( gridPen.color() ) );
        double halfCrossLength = 1;
        if ( mComposition->gridStyle() == QgsComposition::Dots )
        {
          //dots are actually drawn as tiny crosses a few pixels across
          //check QGraphicsView to get current transform
          if ( scene() )
          {
            QList<QGraphicsView*> viewList = scene()->views();
            if ( !viewList.isEmpty() )
            {
              QGraphicsView* currentView = viewList.at( 0 );
              if ( currentView->isVisible() )
              {
                //set halfCrossLength to equivalent of 1 pixel
                halfCrossLength = 1 / currentView->transform().m11();
              }
            }
          }
        }
        else if ( mComposition->gridStyle() == QgsComposition::Crosses )
        {
          halfCrossLength = mComposition->snapGridResolution() / 6;
        }

        for ( ; currentXCoord <= rect().width(); currentXCoord += mComposition->snapGridResolution() )
        {
          currentYCoord = minYCoord;
          for ( ; currentYCoord <= rect().height(); currentYCoord += mComposition->snapGridResolution() )
          {
            painter->drawLine( QPointF( currentXCoord - halfCrossLength, currentYCoord ), QPointF( currentXCoord + halfCrossLength, currentYCoord ) );
            painter->drawLine( QPointF( currentXCoord, currentYCoord - halfCrossLength ), QPointF( currentXCoord, currentYCoord + halfCrossLength ) );
          }
        }
      }
      painter->restore();
    }
  }
}
Ejemplo n.º 21
0
void QgsSimpleLineSymbolLayerV2::applySizeScale( QgsSymbolV2RenderContext& context, QPen& pen, QPen& selPen )
{
  double scaledWidth = mWidth * QgsSymbolLayerV2Utils::lineWidthScaleFactor( context.renderContext(), mWidthUnit, mWidthMapUnitScale );
  pen.setWidthF( scaledWidth );
  selPen.setWidthF( scaledWidth );
}
Ejemplo n.º 22
0
bool CurvesModel::setData(const QModelIndex& index, const QVariant& value, int role)
{
    SolvWidget* solv =  solvers->at(index.row());
    QwtPlotCurve* curve = solv->curve;
    QPen pen = curve->pen(); /// This makes a copy of Pen
    QColor col;
    Qt::PenStyle ps;
    QwtSymbol *symbol;
    QwtSymbol::Style symbolStyle;
    QBrush brush;
    QSize symSize;

    bool ok;
    double lw;
    int ss;
    if( role != Qt::EditRole ) return false;
    switch(index.column()) {
    case 0:// title
        if(value.toString().size() > 1) {
            QString newTitle = value.toString();
            if( newTitle != solv->getTitle() ) {
                solv->setTitle(value.toString());
                emit newdata();
                return true;
            }
        }
        return false;
    case 1:// line color
        col = value.value<QColor>();
        if(pen.color() != col ) {
            pen.setColor(col);
            curve->setPen(pen);
            solv->setColor(col);
            emit newdata();
            return true;
        }
        return false;
    case 2:// line style
        ps = Qt::PenStyle(value.toInt());
        if( ps != pen.style()) {
            pen.setStyle(ps);
            curve->setPen(pen);
            emit newdata();
            return true;
        }
        return false;
    case 3:// line width
        lw = value.toDouble(&ok);
        if(ok && (lw != curve->pen().widthF())) {
            pen.setWidthF(lw);
            curve->setPen(pen);
            emit newdata();
            return true;
        }
        return false;
    case 4:// symbol style
        symbolStyle = QwtSymbol::Style(value.toInt());
        if(curve->symbol() == NULL) {
            if(symbolStyle == QwtSymbol::NoSymbol ) return false;
	    pen.setStyle(Qt::SolidLine);
            symbol = new QwtSymbol(symbolStyle,QBrush(),pen,QSize(7,7));//Qt::transparent
        } else {
            if(curve->symbol()->style() == symbolStyle) return false;
            if(symbolStyle == QwtSymbol::NoSymbol) {
                symbol = NULL;
            } else {
                symbol = new QwtSymbol(symbolStyle,curve->symbol()->brush(),curve->symbol()->pen(),curve->symbol()->size());
            }
        }
        curve->setSymbol(symbol);
        emit newdata();
        return true;
    case 5:// symbol color
        col = value.value<QColor>();
        if(curve->symbol() == NULL || curve->symbol()->style() == QwtSymbol::NoSymbol ) return false;
        if(curve->symbol()->pen().color() == col ) return false;
        pen = curve->symbol()->pen();
        pen.setColor(col);
        symbol = new QwtSymbol(curve->symbol()->style(),curve->symbol()->brush(),pen,curve->symbol()->size());
        curve->setSymbol(symbol);
        emit newdata();
        return true;
    case 6: // symbol size
        ss = value.toInt();
	if(ss < 1) return false;
        if(curve->symbol() == NULL || curve->symbol()->style() == QwtSymbol::NoSymbol ) return false;
        if(curve->symbol()->size().width() == ss ) return false;
        symbol = new QwtSymbol(curve->symbol()->style(),curve->symbol()->brush(),curve->symbol()->pen(),QSize(ss,ss));
        curve->setSymbol(symbol);
        emit newdata();
        return false;
    }
    return QAbstractItemModel::setData(index, value, role);
}
Ejemplo n.º 23
0
QGraphicsEllipseItem *GraphRenderer::addNode(repo::core::model::RepoNode *node, float row, float column)
{
    float spacing = nodeDiameter / 4.0f;

    QPen pen;
    pen.setWidthF(penWidth);
    QBrush brush(Qt::SolidPattern);

    QColor dark;
    QColor light;

    switch (node->getTypeAsEnum())
    {
    case repo::core::model::NodeType::CAMERA :
        dark = Qt::darkMagenta;
        light = Qt::magenta;
        break;
    case repo::core::model::NodeType::MATERIAL :
        dark = Qt::darkRed;
        light = Qt::red;
        break;
    case repo::core::model::NodeType::MESH :
        dark = Qt::darkBlue;
        light = Qt::blue;
        break;
    case repo::core::model::NodeType::METADATA :
        dark = Qt::darkCyan;
        light = Qt::cyan;
        break;
    case repo::core::model::NodeType::REFERENCE :
        dark = repo::gui::primitive::RepoColor::fromHex("#6e8b3d"); // DarkOliveGreen4
        light = repo::gui::primitive::RepoColor::fromHex("#caff70"); // DarkOliveGreen1
        break;
    case repo::core::model::NodeType::REVISION :
        dark = repo::gui::primitive::RepoColor::fromHex("#68228b"); // DarkOrchid4
        light = repo::gui::primitive::RepoColor::fromHex("#bf3eff"); // DarkOrchid1
        break;
    case repo::core::model::NodeType::TEXTURE :
        dark = Qt::darkYellow;
        light = Qt::yellow;
        break;
    case repo::core::model::NodeType::TRANSFORMATION :
        dark = Qt::darkGreen;
        light = Qt::green;
        break;
    case repo::core::model::NodeType::UNKNOWN :
    default :
        dark = Qt::darkGray;
        light = Qt::gray;
    }
    pen.setColor(dark);
    brush.setColor(light);

    qreal x = column * (nodeDiameter + spacing);
    qreal y = row * (nodeDiameter + spacing) * 4;
    QGraphicsEllipseItem *ellipse = addEllipse(
                0, 0, nodeDiameter, nodeDiameter, pen, brush);
    ellipse->setPos(x, y);
    ellipse->setZValue(1.0f);

    //--------------------------------------------------------------------------
    QString toolTip;
    toolTip += tr("_id") + "\t: '" + uuidToQString(node->getUniqueID()) + "',\n";
    toolTip += tr("sid") + "\t: '" + uuidToQString(node->getSharedID()) + "',\n";
    if (!node->getName().empty())
        toolTip += tr("name") + "\t: '" + QString::fromStdString(node->getName()) + "',\n";
    toolTip += tr("type") + "\t: '" + QString::fromStdString(node->getType()) + "'";
    ellipse->setToolTip(toolTip);
    //--------------------------------------------------------------------------
    QVariant var;
    var.setValue(node);
    ellipse->setData(0, var);
    //--------------------------------------------------------------------------
    return ellipse;
}
Ejemplo n.º 24
0
void QtOutline2Rasterizer::rasterize(RasterizedOutline2 &poly,
                                 float scale,
                                 int rast_i,
                                 int rotationNum,
                                 int cellSize)
{

    float rotRad = M_PI*2.0f*float(rast_i) / float(rotationNum);

    //get polygon's BB, rotated according to the input parameter
    Box2f bb;
    vector<Point2f> pointvec = poly.getPoints();
    for(size_t i=0;i<pointvec.size();++i) {
        Point2f pp=pointvec[i];
        pp.Rotate(rotRad);
        bb.Add(pp);
    }

    ///CREATE ITS GRID. The grid has to be a multiple of CELLSIZE because this grid's cells have size CELLSIZE
    //we'll make so that sizeX and sizeY are multiples of CELLSIZE:
    //1) we round it to the next integer
    //2) add the number which makes it a multiple of CELLSIZE (only if it's not multiple already)
    int sizeX = (int)ceil(bb.DimX()*scale);
    int sizeY = (int)ceil(bb.DimY()*scale);
    if (sizeX % cellSize != 0) sizeX += (cellSize - ((int)ceil(bb.DimX()*scale) % cellSize));
    if (sizeY % cellSize != 0) sizeY += (cellSize - ((int)ceil(bb.DimY()*scale) % cellSize));

    //security measure: add a dummy column/row thus making the image bigger, and crop it afterwards
    //(if it hasn't been filled with anything)
    //this is due to the fact that if we have a rectangle which has bb 39.xxx wide, then it won't fit in a 40px wide QImage!! The right side will go outside of the image!! :/
    sizeX+=cellSize;
    sizeY+=cellSize;

    QImage img(sizeX,sizeY,QImage::Format_RGB32);
    QColor backgroundColor(Qt::transparent);
    img.fill(backgroundColor);

    ///SETUP OF DRAWING PROCEDURE
    QPainter painter;
    painter.begin(&img);
    QBrush br;
    br.setStyle(Qt::SolidPattern);
    QPen qp;
    qp.setWidthF(0);
    qp.setColor(Qt::yellow);
    painter.setBrush(br);
    painter.setPen(qp);

    painter.resetTransform();
    painter.translate(QPointF(-(bb.min.X()*scale) , -(bb.min.Y()*scale) ));
    painter.rotate(math::ToDeg(rotRad));
    painter.scale(scale,scale);

    //create the polygon to print it
    QVector<QPointF> points;
    vector<Point2f> newpoints = poly.getPoints();
    for (size_t i = 0; i < newpoints.size(); i++) {
        points.push_back(QPointF(newpoints[i].X(), newpoints[i].Y()));
    }
    painter.drawPolygon(QPolygonF(points));


    //CROPPING: it is enough to check for the (end - cellSize - 1)th row/col of pixels, if they're all black we can eliminate the last 8columns/rows of pixels
    bool cropX = true;
    bool cropY = true;
    for (int j=0; j<img.height(); j++) {
        const uchar* line = img.scanLine(j);
        if (j == img.height() - (cellSize - 1) - 1  ) {
            for (int x=0; x<img.width(); x++) {
                if (((QRgb*)line)[x] != backgroundColor.rgb()) {
                    cropY = false;
                    break;
                }
            }
        }
        else {
            if (((QRgb*)line)[img.width() - (cellSize - 1) - 1] != backgroundColor.rgb()) {
                cropX = false;
                break;
            }
        }
        if (!cropY) break;
    }


    if (cropX || cropY) {
        painter.end();
        img = img.copy(0, 0, img.width() - cellSize * cropX, img.height() - cellSize * cropY);
        painter.begin(&img);
        painter.setBrush(br);
        painter.setPen(qp);
    }


    //draw the poly for the second time, this time it is centered to the image
    img.fill(backgroundColor);

    painter.resetTransform();
    painter.translate(QPointF(-(bb.min.X()*scale) + (img.width() - ceil(bb.DimX()*scale))/2.0, -(bb.min.Y()*scale) + (img.height() - ceil(bb.DimY()*scale))/2.0));
    painter.rotate(math::ToDeg(rotRad));
    painter.scale(scale,scale);
    //create the polygon to print it
    QVector<QPointF> points2;
    vector<Point2f> newpoints2 = poly.getPoints();
    for (size_t i = 0; i < newpoints2.size(); i++) {
        points2.push_back(QPointF(newpoints2[i].X(), newpoints2[i].Y()));
    }
    painter.drawPolygon(QPolygonF(points2));

    //create the first grid, which will then be rotated 3 times.
    //we will reuse this grid to create the rasterizations corresponding to this one rotated by 90/180/270°
    vector<vector<int> > tetrisGrid;
    QRgb yellow = QColor(Qt::yellow).rgb();
    int gridWidth = img.width() / cellSize;
    int gridHeight = img.height() / cellSize;
    int x = 0;
    tetrisGrid.resize(gridHeight);
    for (int k = 0; k < gridHeight; k++) {
        tetrisGrid[k].resize(gridWidth, 0);
    }
    for (int y = 0; y < img.height(); y++) {
        int gridY = y / cellSize;
        const uchar* line = img.scanLine(y);
        x = 0;
        int gridX = 0;
        while(x < img.width()) {
            gridX = x/cellSize;
            if (tetrisGrid[gridY][gridX] == 1) {
                x+= cellSize - (x % cellSize); //align with the next x
                continue;
            }
            if (((QRgb*)line)[x] == yellow) tetrisGrid[gridY][gridX] = 1;
            ++x;
        }
    }

    //create the 4 rasterizations (one every 90°) using the discrete representation grid we've just created
    int rotationOffset = rotationNum/4;
    for (int j = 0; j < 4; j++) {
        if (j != 0)  {
            tetrisGrid = rotateGridCWise(tetrisGrid);
        }
        //add the grid to the poly's vector of grids
        poly.getGrids(rast_i + rotationOffset*j) = tetrisGrid;

        //initializes bottom/left/deltaX/deltaY vectors of the poly, for the current rasterization
        poly.initFromGrid(rast_i + rotationOffset*j);
    }

    painter.end();
}
Ejemplo n.º 25
0
/**
 * Renders the text data into painter paths.
 */
void RTextRenderer::renderSimple() {
    boundingBox = RBox();
    painterPaths.clear();
    richText = "";

    RVector pos = textData.getAlignmentPoint();
    QString text = textData.getEscapedText();
    double textHeight = textData.getTextHeight();
    RS::VAlign verticalAlignment = textData.getVAlign();
    RS::HAlign horizontalAlignment = textData.getHAlign();
    QString fontName = textData.getFontName();
    bool bold = textData.isBold();
    bool italic = textData.isItalic();
    double angle = textData.getAngle();

    // degree:
    text.replace(QRegExp(RTextRenderer::rxDegree), RTextRenderer::chDegree);
    // plus minus:
    text.replace(QRegExp(RTextRenderer::rxPlusMinus), RTextRenderer::chPlusMinus);
    // diameter:
    text.replace(QRegExp(RTextRenderer::rxDiameter), RTextRenderer::chDiameter);

    bool leadingSpaces = false;
    bool trailingSpaces = false;

    if (!text.isEmpty()) {
        if (text.at(0).isSpace()) {
            leadingSpaces = true;
        }
        if (text.at(text.length()-1).isSpace()) {
            trailingSpaces = true;
        }
    }

    // implicit top level format block:
    QTextCharFormat f;
    f.setForeground(QBrush(QColor()));
    currentFormat.push(f);
    QTextLayout::FormatRange fr;
    fr.start = 0;
    fr.length = text.length();
    fr.format = currentFormat.top();
    QList<QTextLayout::FormatRange> formats;
    formats.append(fr);
    blockHeight.push(textHeight);
    blockFont.push(fontName);
    blockBold.push(bold);
    blockItalic.push(italic);
    useCadFont.push(RFontList::isCadFont(blockFont.top()));
    openTags.push(QStringList());

    double horizontalAdvance = 0.0;
    double horizontalAdvanceNoSpacing = 0.0;
    double ascent = 0.0;
    double descent = 0.0;

    // get painter paths for text at height 1.0:
    painterPaths = getPainterPathsForBlock(
                text, formats,
                horizontalAdvance,
                horizontalAdvanceNoSpacing,
                ascent, descent);

    width = horizontalAdvanceNoSpacing * textHeight;

    // transform to scale text from 1.0 to current text height:
    QTransform sizeTransform;
    sizeTransform.scale(textHeight, textHeight);

    // transform paths of text:
    boundingBox = RBox();
    for (int i=0; i<painterPaths.size(); ++i) {
        painterPaths[i].transform(sizeTransform);
        boundingBox.growToInclude(painterPaths[i].getBoundingBox());
    }

    // feature size of a text is its height
    // determines if text is displayed or only bounding box
    double featureSize = boundingBox.getHeight();

    QPen pen;
    for (int i=0; i<painterPaths.size(); ++i) {
        if (i==0) {
            pen = painterPaths[i].getPen();
            if (pen.style()==Qt::NoPen) {
                pen = QPen(painterPaths[i].getBrush().color());
            }
        }
        painterPaths[i].setFeatureSize(featureSize);
    }

    RPainterPath bbPath;
    bbPath.addBox(boundingBox);
    bbPath.setFeatureSize(-featureSize);
    bbPath.setPen(pen);
    painterPaths.append(bbPath);

    //height = boundingBox.getHeight();

    double topLine = textHeight;
    double baseLine = 0.0;
    double bottomLine = descent * textHeight;

    // at this point, the text is at 0/0 with the base line of the
    // first text line at y==0

    double xOffset = 0.0;
    double yOffset = 0.0;

    switch (verticalAlignment) {
    case RS::VAlignTop:
        yOffset = -topLine;
        break;
    case RS::VAlignMiddle:
        yOffset = -textHeight/2.0;
        break;
    case RS::VAlignBase:
        yOffset = -baseLine;
        break;
    case RS::VAlignBottom:
        yOffset = -bottomLine;
        break;
    }

    switch (horizontalAlignment) {
    default:
    case RS::HAlignAlign:
    case RS::HAlignFit:
    case RS::HAlignLeft:
        if (!leadingSpaces) {
            // move completely to the left (left border is 0.0):
            xOffset = -boundingBox.getMinimum().x;
        }
        else {
            xOffset = 0.0;
        }
        break;
    case RS::HAlignMid:
    case RS::HAlignCenter:
        if (!leadingSpaces && !trailingSpaces) {
            xOffset =  -(boundingBox.getMinimum().x +
                          boundingBox.getMaximum().x)/2.0;
        }
        else {
            xOffset = -horizontalAdvance/2.0*textHeight;
        }
        break;
    case RS::HAlignRight:
        if (!trailingSpaces) {
            xOffset = -boundingBox.getMaximum().x;
        }
        else {
            xOffset = -horizontalAdvance*textHeight;
        }
        break;
    }

    height = boundingBox.getHeight();

    QTransform globalTransform;
    globalTransform.translate(pos.x, pos.y);
    globalTransform.rotate(RMath::rad2deg(angle));
    globalTransform.translate(xOffset, yOffset);

    // apply global transform for position, angle and vertical alignment:
    boundingBox = RBox();
    for (int i=0; i<painterPaths.size(); ++i) {
        painterPaths[i].transform(globalTransform);
        boundingBox.growToInclude(painterPaths[i].getBoundingBox());
    }
}
Ejemplo n.º 26
0
void GraphViewEvent::generateCurves(TypeGraph typeGraph, Variable variable)
{
    GraphViewResults::generateCurves(typeGraph, variable);
    
    // ------------------------------------------------
    //  Reset the graph object settings
    // ------------------------------------------------
    mGraph->removeAllCurves();
    mGraph->removeAllZones();
    mGraph->clearInfos();
    mGraph->resetNothingMessage();
    
    mGraph->autoAdjustYScale(mCurrentTypeGraph == eTrace);
    
    QPen defaultPen;
    defaultPen.setWidthF(1);
    defaultPen.setStyle(Qt::SolidLine);
    
    if(mEvent)
    {
        QColor color = mEvent->getColor();
        
        bool isFixedBound = false;
        bool isUnifBound = false;
        EventKnown* bound = 0;
        if(mEvent->type() == Event::eKnown)
        {
            bound = dynamic_cast<EventKnown*>(mEvent);
            if(bound)
            {
                if(bound->knownType() == EventKnown::eFixed)
                    isFixedBound = true;
                else if(bound->knownType() == EventKnown::eUniform)
                    isUnifBound = true;
            }
        }
        
        QString resultsText = ModelUtilities::eventResultsText(mEvent, false);
        QString resultsHTML = ModelUtilities::eventResultsHTML(mEvent, false);
        setNumericalResults(resultsHTML, resultsText);
        
        // ------------------------------------------------
        //  First tab : Posterior distrib
        // ------------------------------------------------
        if(typeGraph == ePostDistrib)
        {
            mGraph->mLegendX = DateUtils::getAppSettingsFormat();
            mGraph->setFormatFunctX(DateUtils::convertToAppSettingsFormatStr);
            mGraph->setFormatFunctY(formatValueToAppSettingsPrecision);
            mGraph->setBackgroundColor(QColor(230, 230, 230));
            
            mTitle = ((mEvent->type()==Event::eKnown) ? tr("Bound ") : tr("Event")) + " : " + mEvent->getName();
            
            // ------------------------------------------------
            //  Possible curves :
            //  - Post Distrib All Chains
            //  - HPD All Chains
            //  - Credibility All Chains
            //  - Post Distrib Chain i
            // ------------------------------------------------
            if(variable == eTheta)
            {
                mGraph->setRangeX(mSettings.mTmin, mSettings.mTmax);                                
                
                if(isFixedBound)
                {                   
                    GraphCurve curveLineBound;
                    curveLineBound.mName = "Post Distrib All Chains";
                    curveLineBound.mPen.setColor(color);
                    curveLineBound.mIsVerticalLine = true;
                    curveLineBound.mVerticalValue = bound->fixedValue();
                    mGraph->addCurve(curveLineBound);
                }
                else if(isUnifBound)
                {                   
                    GraphCurve curveLineStart;
                    curveLineStart.mName = "Post Distrib All Chains";
                    curveLineStart.mPen.setColor(color);
                    curveLineStart.mIsVerticalLine = true;
                    curveLineStart.mVerticalValue = bound->uniformStart();
                    mGraph->addCurve(curveLineStart);

                    GraphCurve curveLineEnd;
                    curveLineEnd.mName = "Post Distrib All Chains";
                    curveLineEnd.mPen.setColor(color);
                    curveLineEnd.mIsVerticalLine = true;
                    curveLineEnd.mVerticalValue = bound->uniformEnd();
                    mGraph->addCurve(curveLineEnd);
                }


                // ------------------------------------
                //  HPD All Chains
                // ------------------------------------
                if(!isFixedBound)
                {
                    // ------------------------------------
                    //  Post Distrib All Chains
                    // ------------------------------------
                    GraphCurve curvePostDistrib;
                    curvePostDistrib.mName = "Post Distrib All Chains";
                    curvePostDistrib.mPen.setColor(color);

                    curvePostDistrib = generateDensityCurve(mEvent->mTheta.fullHisto(),
                                                                           "Post Distrib All Chains",
                                                                           color);
                    mGraph->addCurve(curvePostDistrib);


                    // HPD All Chains
                    GraphCurve curveHPD = generateHPDCurve(mEvent->mTheta.mHPD,
                                                           "HPD All Chains",
                                                           color);
                    mGraph->addCurve(curveHPD);
                }
                
                // ------------------------------------
                //  Post Distrib Chain i
                // ------------------------------------
                for(int i=0; i<mChains.size(); ++i)
                {
                    GraphCurve curvePostDistribChain = generateDensityCurve(mEvent->mTheta.histoForChain(i),
                                                                            "Post Distrib Chain " + QString::number(i),
                                                                            Painting::chainColors[i],
                                                                            Qt::SolidLine,
                                                                            Qt::NoBrush);
                    mGraph->addCurve(curvePostDistribChain);
                }
                
                // ------------------------------------
                //  Theta Credibility
                // ------------------------------------
                GraphCurve curveCred = generateCredibilityCurve(mEvent->mTheta.mCredibility,
                                                                "Credibility All Chains",
                                                                color);
                mGraph->addCurve(curveCred);
            }
            
            
            // ------------------------------------------------
            //  Events don't have std dev BUT we can visualize
            //  an overlay of all dates std dev instead.
            //  Possible curves, FOR ALL DATES :
            //  - Sigma Date i All Chains
            //  - Sigma Date i Chain j
            // ------------------------------------------------
            else if(variable == eSigma)
            {
                mGraph->mLegendX = "";
                mGraph->setFormatFunctX(0);
                mGraph->setFormatFunctY(formatValueToAppSettingsPrecision);
                
                //mGraph->setRangeX(0,mSettings.mTmin + mSettings.mTmax);
                if (mEvent->type()==Event::eKnown) {
                    mTitle = tr("Bound ") + " : " + mEvent->getName();
                }
                else
                    mTitle = tr("Std") + " : " + mEvent->getName();
                
                mGraph->setBackgroundColor(QColor(Qt::white));
                mGraph->autoAdjustYScale(true);

                mGraph->setRangeX(0, mSettings.mTmax - mSettings.mTmin);

                
                for(int i=0; i<mEvent->mDates.size(); ++i)
                {
                    Date& date = mEvent->mDates[i];
                    
                    GraphCurve curve = generateDensityCurve(date.mSigma.fullHisto(),
                                                            "Sigma Date " + QString::number(i) + " All Chains",
                                                            color);
                    
                    mGraph->addCurve(curve);
                    
                    for(int j=0; j<mChains.size(); ++j)
                    {
                        GraphCurve curveChain = generateDensityCurve(date.mSigma.histoForChain(j),
                                                                     "Sigma Date " + QString::number(i) + " Chain " + QString::number(j),
                                                                     Painting::chainColors[j]);
                        mGraph->addCurve(curveChain);
                    }
                }
            }
        }
        // ------------------------------------------------
        //  second tab : History plots
        //  - Trace i
        //  - Q1 i
        //  - Q2 i
        //  - Q3 i
        // ------------------------------------------------
        else if(typeGraph == eTrace && variable == eTheta)
        {
            mGraph->mLegendX = "Iterations";
            mGraph->setFormatFunctX(0);
            mGraph->setFormatFunctY(DateUtils::convertToAppSettingsFormatStr);
            
            generateTraceCurves(mChains, &(mEvent->mTheta));
        }
        // ------------------------------------------------
        //  third tab : Acception rate
        //  - Accept i
        //  - Accept Target
        // ------------------------------------------------
        else if(typeGraph == eAccept && variable == eTheta && mEvent->mMethod == Event::eMHAdaptGauss)
        {
            mGraph->mLegendX = "Iterations";
            mGraph->setFormatFunctX(0);
            mGraph->setFormatFunctY(0);
            mGraph->setRangeY(0, 100);
            
            generateHorizontalLine(44, "Accept Target", QColor(180, 10, 20), Qt::DashLine);
            generateAcceptCurves(mChains, &(mEvent->mTheta));
        }
        // ------------------------------------------------
        //  fourth tab : Autocorrelation
        //  - Correl i
        //  - Correl Limit Lower i
        //  - Correl Limit Upper i
        // ------------------------------------------------
        else if(typeGraph == eCorrel && variable == eTheta && !isFixedBound)
        {
            mGraph->mLegendX = "";
            mGraph->setFormatFunctX(0);
            mGraph->setFormatFunctY(0);
            mGraph->setRangeY(-1, 1);
            
            generateCorrelCurves(mChains, &(mEvent->mTheta));
        }
    }
}
Ejemplo n.º 27
0
void MainWindow::makePlot()
{
    /*
    QRegExp rx("(\\ |\\n)");
    QStringList query = szoveg.split(rx);
    for (int i=0; i<query.size(); i++)
        QMessageBox::information(0, "info", query[i]);

    int szohossz[3];
    for (int i=0; i<3; i++)
        szohossz[i] = query[i].size();
    for (int i=0; i<3; i++)
        QMessageBox::information(0, "info", QString::number(szohossz[i]));*/

    // create empty bar chart objects:
    QCPBars *regen = new QCPBars(ui->customPlot->xAxis, ui->customPlot->yAxis);
    QCPBars *nuclear = new QCPBars(ui->customPlot->xAxis, ui->customPlot->yAxis);
    QCPBars *fossil = new QCPBars(ui->customPlot->xAxis, ui->customPlot->yAxis);
    ui->customPlot->addPlottable(regen);
    ui->customPlot->addPlottable(nuclear);
    ui->customPlot->addPlottable(fossil);
    // set names and colors:
    QPen pen;
    pen.setWidthF(1.2);
    fossil->setName("Fossil fuels");
    pen.setColor(QColor(255, 131, 0));
    fossil->setPen(pen);
    fossil->setBrush(QColor(255, 131, 0, 50));
    nuclear->setName("Nuclear");
    pen.setColor(QColor(1, 92, 191));
    nuclear->setPen(pen);
    nuclear->setBrush(QColor(1, 92, 191, 50));
    regen->setName("Regenerative");
    pen.setColor(QColor(150, 222, 0));
    regen->setPen(pen);
    regen->setBrush(QColor(150, 222, 0, 70));
    // stack bars ontop of each other:
    nuclear->moveAbove(fossil);
    regen->moveAbove(nuclear);

    // prepare x axis with country labels:
    QVector<double> ticks;
    QVector<QString> labels;
    ticks << 1 << 2 << 3 << 4 << 5 << 6 << 7;
    labels << "Japan" << "Germany" << "France" << "UK" << "Italy" << "Canada";
    ui->customPlot->xAxis->setAutoTicks(false);
    ui->customPlot->xAxis->setAutoTickLabels(false);
    ui->customPlot->xAxis->setTickVector(ticks);
    ui->customPlot->xAxis->setTickVectorLabels(labels);
    ui->customPlot->xAxis->setTickLabelRotation(60);
    ui->customPlot->xAxis->setSubTickCount(0);
    ui->customPlot->xAxis->setTickLength(0, 4);
    ui->customPlot->xAxis->grid()->setVisible(true);
    ui->customPlot->xAxis->setRange(0, 8);

    // prepare y axis:
    ui->customPlot->yAxis->setRange(0, 12.1);
    ui->customPlot->yAxis->setPadding(5); // a bit more space to the left border
    ui->customPlot->yAxis->setLabel("Power Consumption in\nKilowatts per Capita (2007)");
    ui->customPlot->yAxis->grid()->setSubGridVisible(false);
    QPen gridPen;
    gridPen.setStyle(Qt::SolidLine);
    gridPen.setColor(QColor(0, 0, 0, 25));
    ui->customPlot->yAxis->grid()->setPen(gridPen);
    gridPen.setStyle(Qt::DotLine);
    ui->customPlot->yAxis->grid()->setSubGridPen(gridPen);

    // Add data:
    QVector<double> fossilData, nuclearData, regenData;
    fossilData  << 0.86*10.5 << 0.83*5.5 << 0.84*5.5 << 0.52*5.8 << 0.89*5.2 << 0.90*4.2 << 0.67*11.2;
    nuclearData << 0.08*10.5 << 0.12*5.5 << 0.12*5.5 << 0.40*5.8 << 0.09*5.2 << 0.00*4.2 << 0.07*11.2;
    regenData   << 0.06*10.5 << 0.05*5.5 << 0.04*5.5 << 0.06*5.8 << 0.02*5.2 << 0.07*4.2 << 0.25*11.2;
    fossil->setData(ticks, fossilData);
    nuclear->setData(ticks, nuclearData);
    regen->setData(ticks, regenData);

    // setup legend:
    ui->customPlot->legend->setVisible(true);
    ui->customPlot->axisRect()->insetLayout()->setInsetAlignment(0, Qt::AlignTop|Qt::AlignHCenter);
    ui->customPlot->legend->setBrush(QColor(255, 255, 255, 200));
    QPen legendPen;
    legendPen.setColor(QColor(130, 130, 130, 200));
    ui->customPlot->legend->setBorderPen(legendPen);
    QFont legendFont = font();
    legendFont.setPointSize(10);
    ui->customPlot->legend->setFont(legendFont);
    ui->customPlot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom);
}
Ejemplo n.º 28
0
void TodoDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
  KColorScheme colorScheme( option.palette.currentColorGroup() );
  QPen pen;
  
//  if( option.state & QStyle::State_Selected ){
//    painter->fillRect(option.rect, option.palette.highlight() );
//  }
  
  QPoint originPoint = option.rect.topLeft();
  originPoint.rx()++;
  originPoint.ry()++;
  
  QMap<QString,QVariant> map( index.data().toMap() );
  
  QStyleOptionViewItem newOption = option;
  if( map["type"] == 1 ){
    switch( map["priority"].toInt() ){
    case 1:
      if( Settings::self()->getUseOwnColor() ){
        newOption.palette.setColor(QPalette::Background, Settings::self()->getPriority1() );
      } else {
        newOption.palette.setColor(QPalette::Background, colorScheme.background(KColorScheme::NegativeBackground).color());
      }
      if( Settings::self()->getUseOwnFontColor() ){
        pen.setColor( Settings::self()->getPriority1Font() );
      }
      painter->fillRect(newOption.rect, newOption.palette.background());
      break;
    case 2:
      if( Settings::self()->getUseOwnColor() ){
        newOption.palette.setColor(QPalette::Background, Settings::self()->getPriority2() );
      } else {
        newOption.palette.setColor(QPalette::Background, colorScheme.background(KColorScheme::NeutralBackground).color());
      }
      if( Settings::self()->getUseOwnFontColor() ){
        pen.setColor( Settings::self()->getPriority2Font() );
      }
      painter->fillRect(newOption.rect, newOption.palette.background());
      break;
    case 3:
      if( Settings::self()->getUseOwnColor() ){
        newOption.palette.setColor(QPalette::Background, Settings::self()->getPriority3() );
      } else {
        newOption.palette.setColor(QPalette::Background, colorScheme.background(KColorScheme::PositiveBackground).color());
      }
      if( Settings::self()->getUseOwnFontColor() ){
        pen.setColor( Settings::self()->getPriority3Font() );
      }
      painter->fillRect(newOption.rect, newOption.palette.background());
      break;
    default:
      newOption.palette.setColor(QPalette::Background, colorScheme.background(KColorScheme::NormalBackground).color());
      break;
    }
    painter->fillRect(newOption.rect, newOption.palette.background());
    //qDebug() << newOption.palette.background().color().toRgb();
  }  
  painter->save();
  QStyledItemDelegate::paint(painter,newOption,index);
  painter->restore();
  
  if( map["type"] == 0 ){
    if( index.column() != 0 ){
      return;
    }
    QString iconName;
    if( view->isExpanded(index) ){
      iconName = "arrow-down";
    } else {
      iconName = "arrow-right";
    }
    QRect iconRect(originPoint, QSize(15,15));
    painter->drawPixmap(iconRect, KIcon(iconName).pixmap(QSize(15,15)) );
    painter->save();
    painter->setFont(boldFont);
    QPoint writePoint( originPoint + QPoint(iconRect.size().width()+5,0) );
    QString text = cutString( map["name"].toString(), QRect( writePoint, newOption.rect.bottomRight() ), boldFont );
    painter->drawText( QRect( writePoint, newOption.rect.bottomRight() ), text );
    painter->restore();
  }
  
  if( map["type"] == 1 ){
    painter->save();
    painter->setPen(pen);
    originPoint.ry()++;
    if( index.column() == 0 ){
      originPoint.rx() += 25; // for the checkbox
      QString text = map["name"].toString();
//      if( map["priority"].toInt() == 4 ){
//        text.prepend("- ");
//      } else {
//        text.prepend( QString::number(map["priority"].toInt()) + " " );
//      }
      text = cutString( text, QRect(originPoint,newOption.rect.bottomRight()), standardFont );
      painter->drawText( QRect(originPoint,newOption.rect.bottomRight()), text );
    } else {
      QString text = cutString( map["date"].toDate().toString(), QRect(originPoint,newOption.rect.bottomRight()), standardFont );
      painter->drawText( QRect(originPoint,newOption.rect.bottomRight()), text);
      if(map["date"].toDate().isNull()){
        painter->drawText( QRect(originPoint,newOption.rect.bottomRight()), "-");
      }
    }
    painter->restore();
  }
}
Ejemplo n.º 29
0
void
QMMLPainter::setLineThickness(float t) { // thickness in px
    QPen pen = p->pen();
    pen.setWidthF(t);
    p->setPen(pen);
}
Ejemplo n.º 30
0
void KMapScene::setupGrid(int cellsRad, int cellsRing, float gridLength, int pathSize, bool usingSmallMap){
	cellsOfRadius = cellsRad;
	cellsOfRing = cellsRing;
	smallMap = usingSmallMap;
	//864 is a refered number of pixel, dont mint why just use it 
	moveStepInMeters = (((float)ImgSize/864))/(float)cellsOfRadius;
	//turn step in meters = 2 * pi / number of cells in each circle
	turnStepInRads = 2*M_PI/(float)cellsRing;
	totalVisits = 0;
	if(pathR != NULL){
		delete pathR;
		delete pathS;
		delete pathO;
		delete pathR2;
		delete pathS2;
		delete pathO2;
		
		for (int r = 0; r < cellsOfRadius; r++){
			delete PolarGrid[r];
			delete cellCenterY[r];
			delete cellCenterX[r];
		}
		delete PolarGrid;
		delete cellCenterX;
		delete cellCenterY;
		for (int r = 0; r < cellsOfRadius+1; r++){
			delete gridImgH[r];
			delete gridImgV[r];
		}
		delete gridImgV;
		delete gridImgH;
		delete targetBall;
		delete targetLine;
	}
	
	
	pathR = new int[pathSize];
	pathS = new int[pathSize];
	pathO = new int[pathSize];
	
	pathR2 = new int[2000];
	pathS2 = new int[2000];
	pathO2 = new int[2000];
	
	pathLength = pathSize;

	PolarGrid = new float*[cellsOfRadius];
	cellCenterX = new float*[cellsOfRadius];
	cellCenterY = new float*[cellsOfRadius];
	for (int r = 0; r < cellsOfRadius; r++){
		PolarGrid[r] = new float[cellsOfRing];
		cellCenterX[r] = new float[cellsOfRing];
		cellCenterY[r] = new float[cellsOfRing];
	}
	
	gridImgH = new int*[cellsOfRadius+1];
	gridImgV = new int*[cellsOfRadius+1];
	for (int r = 0; r < cellsOfRadius+1; r++){
		gridImgH[r] = new int[cellsOfRing];
		gridImgV[r] = new int[cellsOfRing];
	}
	
	for(int i = 0; i < cellsList.size(); i++){
		cellsList.at(i)->setVisible(false);
		delete cellsList.at(i);
	}
	for(int i = 0; i < pathLineList.size(); i++){
		delete pathLineList.at(i);
	}
	for(int i = 0; i < pathEllipseList.size(); i++){
		delete pathEllipseList.at(i);
	}
	for(int i = 0; i < pathSmallLineList.size(); i++){
		delete pathSmallLineList.at(i);
	}
	
	cellsList.clear();
	pathLineList.clear();
	pathEllipseList.clear();
	pathSmallLineList.clear();


	
	for (int r = 0; r < cellsOfRadius; r++){
		for (int s = 0; s < cellsOfRing; s++) {
			QGraphicsPolygonItem *cell = addPolygon (QPolygonF (QRectF() ), QPen (Qt::white), QBrush (Qt::transparent) );
			cellsList.append (cell);
		}
	}
	QPen penForBlueLine (Qt::blue);
	penForBlueLine.setWidth (2);
	//setup up in the background the path line and then in the foreground the robot positions
	for (int ways = 0; ways < pathLength; ways++) {
		QGraphicsLineItem *path = addLine (QLineF(), penForBlueLine);
		pathLineList.append (path);
	}
	QPen penForGreenLine (Qt::green);
	penForGreenLine.setWidth (4);
	for (int ways = 0; ways < pathLength; ways++) {
		QGraphicsEllipseItem *ellipse = addEllipse (QRect(), QPen (Qt::red), QBrush (Qt::blue) );
		pathEllipseList.append(ellipse);
		QGraphicsLineItem *smallLine = addLine (QLineF(), penForGreenLine );
		pathSmallLineList.append(smallLine);
	}
	
	initCoordinates();
	initGrid();
	targetBall = addEllipse (QRect(), QPen (Qt::red), QBrush (Qt::red) );
	targetLine = addLine (QLineF(), penForGreenLine );
	updateObstacles();
}