Ejemplo n.º 1
0
 bool addLine(QTextLine &line) {
     if (line.height() > 20)
         m_y += line.height();
     else
         m_y += 14.4;
     return false;
 }
Ejemplo n.º 2
0
void YTDelegate::layoutText(QTextLayout& textLayout, QString text, QSize constraint) const
{
    QTextOption textOption(Qt::AlignJustify);
    textLayout.setTextOption(textOption);
    textLayout.setText(text);
    textLayout.beginLayout();
    int lHeight = 0;
    while(true){
        QTextLine line = textLayout.createLine();
        if(!line.isValid())
            break;
        line.setLineWidth(constraint.width());
        line.setPosition(QPointF(0, lHeight));
        if(lHeight + line.height() > constraint.height())
        {
            QTextLine lastLine = textLayout.lineAt(textLayout.lineCount() - 2);
            QString lastString = text.mid(lastLine.textStart());
            QFontMetrics fm(textLayout.font());
            text.chop(lastString.length());
            text += fm.elidedText(lastString, Qt::ElideRight, constraint.width()-1);
            textLayout.endLayout();
            layoutText(textLayout, text, constraint);
            return;
        }
        lHeight += line.height();
        lHeight += line.leading();
    }
    textLayout.endLayout();
}
Ejemplo n.º 3
0
void TestDocumentLayout::placeAnchoredFrame3()
{
    // basic inline frame that acts like a really big character
    initForNewTest(QString(loremIpsum));
    MockShape *picture = new MockShape();
    picture->setSize(QSizeF(100, 100));
    KTextAnchor *anchor = new KTextAnchor(picture);
    anchor->setAlignment(KTextAnchor::VerticalOffset);
    anchor->setAlignment(KTextAnchor::HorizontalOffset);
    QTextCursor cursor(doc);
    KInlineTextObjectManager *manager = new KInlineTextObjectManager();
    layout->setInlineTextObjectManager(manager);
    MockLayoutState *state = new MockLayoutState(doc);
    layout->setLayout(state);
    state->shape = shape1;
    manager->insertInlineObject(cursor, anchor);
    layout->layout();

/*
    I have two goals with 'offset'.
    One is that I want to be able to change the baseline of my anchored object.
    The other is that OOo / ODF allows me to have an arbitairy distance from my anchor
    so I can place something at the center of my page or whatever.

    So what about I switch from the first to the latter based on the font height.
        If my offset 'x' != 0,  make the image floating.
        If my offset 'y' is such that it would be above or below my line; make floating.
*/

    QTextLayout *lay = doc->begin().layout();
    QVERIFY(lay->lineCount() >= 2);
    QTextLine line = lay->lineAt(0);
    QCOMPARE(line.descent(), (qreal) 100);
    QCOMPARE(line.position(), QPointF());
    line = lay->lineAt(1);
    QVERIFY(line.height() < 20);

    // now move the character which makes it a shape to run around and no longer
    // a big character.
    anchor->setOffset(QPointF(50, 20));
    layout->layout();

    lay = doc->begin().layout();
    QVERIFY(lay->lineCount() >= 2);
    line = lay->lineAt(0);
    QVERIFY(line.height() < 20);
    QCOMPARE(line.position(), QPointF());
    line = lay->lineAt(1);
    QVERIFY(line.height() < 20);
    QCOMPARE(line.position().x(), 0.);
    QVERIFY(qAbs(line.position().y() - 14.4) <  0.125);
}
Ejemplo n.º 4
0
void KTextDocumentLayout::Private::adjustSize()
{
    if (parent->resizeMethod() == KTextDocument::NoResize)
        return;

    if (parent->shapes().isEmpty())
        return;
    // Limit auto-resizing to the first shape only (there won't be more
    // with auto-resizing turned on, unless specifically set)
    KShape *shape = parent->shapes().first();

    // Determine the maximum width of all text lines
    qreal width = 0;
    for (QTextBlock block = parent->document()->begin(); block.isValid(); block = block.next()) {
        // The block layout's wrap mode must be QTextOption::NoWrap, thus the line count
        // of a valid block must be 1 (otherwise this resizing scheme wouldn't work)
        Q_ASSERT(block.layout()->lineCount() == 1);
        QTextLine line = block.layout()->lineAt(0);
        width = qMax(width, line.naturalTextWidth());
    }

    // Use position and height of last text line to calculate height
    QTextLine line = parent->document()->lastBlock().layout()->lineAt(0);
    qreal height = line.position().y() + line.height();

    shape->setSize(QSizeF(width, height));
}
Ejemplo n.º 5
0
static void calculateBoundingRect( QTextDocument *document, int startPosition, int endPosition,
                                   QRectF &rect )
{
    const QTextBlock startBlock = document->findBlock( startPosition );
    const QRectF startBoundingRect = document->documentLayout()->blockBoundingRect( startBlock );

    const QTextBlock endBlock = document->findBlock( endPosition );
    const QRectF endBoundingRect = document->documentLayout()->blockBoundingRect( endBlock );

    QTextLayout *startLayout = startBlock.layout();
    QTextLayout *endLayout = endBlock.layout();

    int startPos = startPosition - startBlock.position();
    int endPos = endPosition - endBlock.position();
    const QTextLine startLine = startLayout->lineForTextPosition( startPos );
    const QTextLine endLine = endLayout->lineForTextPosition( endPos );

    double x = startBoundingRect.x() + startLine.cursorToX( startPos );
    double y = startBoundingRect.y() + startLine.y();
    double r = endBoundingRect.x() + endLine.cursorToX( endPos );
    double b = endBoundingRect.y() + endLine.y() + endLine.height();

    const QSizeF size = document->size();
    rect = QRectF( x / size.width(), y / size.height(),
                   (r - x) / size.width(), (b - y) / size.height() );
}
Ejemplo n.º 6
0
//virtual
void	PixButton::redoLabelTextLayout()
{
	//TODO: somewhat wasteful. If there is no label, should just exit early and leave a layout that will be left unrendered by paint()
	m_textLayoutObject.clearLayout();
	m_textLayoutObject.setText(m_label);
	m_textLayoutObject.setFont(m_textFont);
	QTextOption textOpts;
	textOpts.setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
	textOpts.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
	m_textLayoutObject.setTextOption(textOpts);

	QFontMetrics textFontMetrics(m_textFont);
	int leading = textFontMetrics.leading();
	int rise = textFontMetrics.ascent();
	qreal height = 0;

	m_textLayoutObject.beginLayout();
	while (height < m_labelMaxGeom.height()) {
		QTextLine line = m_textLayoutObject.createLine();
		if (!line.isValid())
			break;
		line.setLineWidth(m_labelMaxGeom.width());
		if (m_textLayoutObject.lineCount() > 1)
		{
			height += leading;
		}
		line.setPosition(QPointF(0, height));
		height += line.height();
	}
	height = qMin((quint32)DimensionsGlobal::roundUp(height),(quint32)m_labelMaxGeom.height());
	height = DimensionsGlobal::roundDown(height) - (DimensionsGlobal::roundDown(height) % 2);	//force to an even #
	m_textLayoutObject.endLayout();
	//TODO: PIXEL-ALIGN
	m_labelGeom = DimensionsGlobal::realRectAroundRealPoint(QSizeF(m_textLayoutObject.boundingRect().width(),height)).toAlignedRect();
}
Ejemplo n.º 7
0
void PluginListDelegate::drawDisplay(QPainter* painter, const QStyleOptionViewItem &option, const QRect &rect, const QString &text) const
{
    QTextDocument textDocument;
    textDocument.setHtml(text);

    QTextLayout textLayout(textDocument.begin());
    textLayout.setFont(option.font);

    const int textMargin = QApplication::style()->pixelMetric(QStyle::PM_FocusFrameHMargin, 0) + 1;
    QRect textRect = rect.adjusted(textMargin, 0, -textMargin, 0); // remove width padding

    textLayout.beginLayout();
    qreal height = 0;
    while (1) {
        QTextLine line = textLayout.createLine();
        if (!line.isValid()) {
            break;
        }

        line.setLineWidth(textRect.width());
        height += 3;
        line.setPosition(QPoint(0, height));
        height += line.height();
    }
    textLayout.endLayout();

    textLayout.draw(painter, QPointF(textRect.left(), textRect.top()));
}
Ejemplo n.º 8
0
void paint_QTextLayout(QPainter &p, bool useCache)
{
    static bool first = true;
    static QTextLayout *textLayout[lines];
    if (first) {
        for (int i = 0; i < lines; ++i) {
            textLayout[i] = new QTextLayout(strings[i]);
            int leading = p.fontMetrics().leading();
            qreal height = 0;
            qreal widthUsed = 0;
            textLayout[i]->setCacheEnabled(useCache);
            textLayout[i]->beginLayout();
            while (1) {
                QTextLine line = textLayout[i]->createLine();
                if (!line.isValid())
                    break;

                line.setLineWidth(lineWidth);
                height += leading;
                line.setPosition(QPointF(0, height));
                height += line.height();
                widthUsed = qMax(widthUsed, line.naturalTextWidth());
            }
            textLayout[i]->endLayout();
        }
        first = false;
    }
    for (int i = 0; i < count; ++i) {
        for (int j = 0; j < lines; ++j) {
            textLayout[j]->draw(&p, QPoint(0, j*spacing));
        }
    }
}
Ejemplo n.º 9
0
void TextLabel::layoutText(QTextLayout &layout, const QString &text, const QSize &constraints)
{
    QFontMetrics metrics(layout.font());
    int leading = metrics.leading();
    int height = 0;
    int maxWidth = constraints.width();
    int widthUsed = 0;
    int lineSpacing = metrics.lineSpacing();
    QTextLine line;

    layout.setText(text);

    layout.beginLayout();
    while ((line = layout.createLine()).isValid()) {
        height += leading;

        // Make the last line that will fit infinitely long.
        // drawTextLayout() will handle this by fading the line out
        // if it won't fit in the constraints.
        if (height + 2 * lineSpacing > constraints.height()) {
            line.setPosition(QPoint(0, height));
            break;
        }

        line.setLineWidth(maxWidth);
        line.setPosition(QPoint(0, height));

        height += int(line.height());
        widthUsed = int(qMax(qreal(widthUsed), line.naturalTextWidth()));
    }
    layout.endLayout();
}
Ejemplo n.º 10
0
int KTextDocumentLayout::hitTestIterated(QTextFrame::iterator begin, QTextFrame::iterator end, const QPointF &point, Qt::HitTestAccuracy accuracy) const
{
    int position = -1;
    QTextFrame::iterator it = begin;
    for (it = begin; it != end; ++it) {
        QTextBlock block = it.currentBlock();
        QTextTable *table = qobject_cast<QTextTable*>(it.currentFrame());
        QTextFrame *subFrame = it.currentFrame();

        if (table) {
            QTextTableCell cell = m_state->hitTestTable(table, point);
            if (cell.isValid()) {
                position = hitTestIterated(cell.begin(), cell.end(), point,
                                accuracy);
                if (position == -1)
                    position = cell.lastPosition();
                return position;
            }
            continue;
        } else if (subFrame) {
            position = hitTestIterated(subFrame->begin(), subFrame->end(), point, accuracy);
            if (position != -1)
                return position;
            continue;
        } else {
            if (!block.isValid())
                continue;
        }
        // kDebug(32500) <<"hitTest[" << point.x() <<"," << point.y() <<"]";
        QTextLayout *layout = block.layout();
        if (point.y() > layout->boundingRect().bottom()) {
            // just skip this block. position = block.position() + block.length() - 1;
            continue;
        }
        for (int i = 0; i < layout->lineCount(); i++) {
            QTextLine line = layout->lineAt(i);
            // kDebug(32500) <<" + line[" << line.textStart() <<"]:" << line.y() <<"-" << line.height();
            if (point.y() > line.y() + line.height()) {
                position = line.textStart() + line.textLength();
                continue;
            }
            if (accuracy == Qt::ExactHit && point.y() < line.y()) // between lines
                return -1;
            if (accuracy == Qt::ExactHit && // left or right of line
                    (point.x() < line.x() || point.x() > line.x() + line.width()))
                return -1;
            if (point.x() > line.width() && layout->textOption().textDirection() == Qt::RightToLeft) {
                // totally right of RTL text means the position is the start of the text.
                return block.position() + line.textStart();
            }
            return block.position() + line.xToCursor(point.x());
        }
    }
    return -1;
}
Ejemplo n.º 11
0
void TextLabel::drawTextLayout(QPainter *painter, const QTextLayout &layout, const QRect &rect)
{
    if (rect.width() < 1 || rect.height() < 1) {
        return;
    }

    QPixmap pixmap(rect.size());
    pixmap.fill(Qt::transparent);

    QPainter p(&pixmap);
    p.setPen(painter->pen());

    // Create the alpha gradient for the fade out effect
    QLinearGradient alphaGradient(0, 0, 1, 0);
    alphaGradient.setCoordinateMode(QGradient::ObjectBoundingMode);
    if (layout.textOption().textDirection() == Qt::LeftToRight) {
        alphaGradient.setColorAt(0, QColor(0, 0, 0, 255));
        alphaGradient.setColorAt(1, QColor(0, 0, 0, 0));
    } else {
        alphaGradient.setColorAt(0, QColor(0, 0, 0, 0));
        alphaGradient.setColorAt(1, QColor(0, 0, 0, 255));
    }

    QFontMetrics fm(layout.font());
    int textHeight = layout.lineCount() * fm.lineSpacing();

    QPointF position(0, (rect.height() - textHeight) / 2);
    QList<QRect> fadeRects;
    int fadeWidth = 30;

    // Draw each line in the layout
    for (int i = 0; i < layout.lineCount(); i++) {
        QTextLine line = layout.lineAt(i);
        line.draw(&p, position);

        // Add a fade out rect to the list if the line is too long
        if (line.naturalTextWidth() > rect.width())
        {
            int x = int(qMin(line.naturalTextWidth(), (qreal)pixmap.width())) - fadeWidth;
            int y = int(line.position().y() + position.y());
            QRect r = QStyle::visualRect(layout.textOption().textDirection(), pixmap.rect(),
                                         QRect(x, y, fadeWidth, int(line.height())));
            fadeRects.append(r);
        }
    }

    // Reduce the alpha in each fade out rect using the alpha gradient
    if (!fadeRects.isEmpty()) {
        p.setCompositionMode(QPainter::CompositionMode_DestinationIn);
        foreach (const QRect &rect, fadeRects) {
            p.fillRect(rect, alphaGradient);
        }
Ejemplo n.º 12
0
// Origin: Qt
static void viewItemTextLayout ( QTextLayout &textLayout, int lineWidth, qreal &height, qreal &widthUsed )
{
	height = 0;
	widthUsed = 0;
	textLayout.beginLayout();
	while ( true )
	{
		QTextLine line = textLayout.createLine();
		if ( !line.isValid() )
			break;
		line.setLineWidth ( lineWidth );
		line.setPosition ( QPointF ( 0, height ) );
		height += line.height();
		widthUsed = qMax ( widthUsed, line.naturalTextWidth() );
	}
	textLayout.endLayout();
}
Ejemplo n.º 13
0
static int layoutText(QTextLayout *layout, int maxWidth) {
    qreal height = 0;
    int textWidth = 0;
    layout->beginLayout();
    while (true) {
        QTextLine line = layout->createLine();
        if (!line.isValid()) {
            break;
        }
        line.setLineWidth(maxWidth);
        line.setPosition(QPointF(0, height));
        height += line.height();
        textWidth = qMax(textWidth, qRound(line.naturalTextWidth() + 0.5));
    }
    layout->endLayout();
    return textWidth;
}
// copied from QItemDelegate for drawDisplay
QSizeF doTextLayout(QTextLayout *textLayout, int lineWidth)
{
    qreal height = 0;
    qreal widthUsed = 0;
    textLayout->beginLayout();
    while (true) {
        QTextLine line = textLayout->createLine();
        if (!line.isValid())
            break;
        line.setLineWidth(lineWidth);
        line.setPosition(QPointF(0, height));
        height += line.height();
        widthUsed = qMax(widthUsed, line.naturalTextWidth());
    }
    textLayout->endLayout();
    return QSizeF(widthUsed, height);
}
Ejemplo n.º 15
0
QSizeF QItemDelegatePrivate::doTextLayout(int lineWidth) const
{
    qreal height = 0;
    qreal widthUsed = 0;
    textLayout.beginLayout();
    while (true) {
        QTextLine line = textLayout.createLine();
        if (!line.isValid())
            break;
        line.setLineWidth(lineWidth);
        line.setPosition(QPointF(0, height));
        height += line.height();
        widthUsed = qMax(widthUsed, line.naturalTextWidth());
    }
    textLayout.endLayout();
    return QSizeF(widthUsed, height);
}
Ejemplo n.º 16
0
void CodeEditor::paintEvent(QPaintEvent* event)
{
    QPlainTextEdit::paintEvent(event);

    QPainter painter(viewport());
    painter.setPen(Qt::darkGray);

    QTextBlock block = firstVisibleBlock();

    QRectF rect;

    do {

        if (!block.isVisible())
            continue;

        rect = blockBoundingGeometry(block).translated(contentOffset());

        QTextLine line = block.layout()->lineAt(0);

        if (config->whitespaces) {
            QString txt = block.text();

            for (int i = 0; i < txt.length(); i++) {
                // rect.x() <- учитывая горизонтальный скролинг
                QPoint point(rect.x() + line.cursorToX(i), rect.y() + line.ascent());

                if (txt[i] == ' ')
                    painter.drawText(point, QChar(0x00b7));
                else if (txt[i] == '\t')
                    painter.drawText(point, QChar(0x21b9));
            }
        }

        int state = block.userState();

        if (!(state & Error) && state & Folded) {
            QRect collapseRect(rect.x() + line.rect().x() + line.naturalTextWidth() + FONTWIDTH * 2,
                               rect.y() + 2, FONTWIDTH * 6, line.height() - 4);

            painter.drawText(collapseRect, Qt::AlignCenter, state & Comment ? "...;" : "...)");
            painter.drawRoundedRect(collapseRect, 4, 6);
        }

    } while ((block = block.next()).isValid() && rect.y() < viewport()->height());
}
Ejemplo n.º 17
0
QSize QDeclarativeTextPrivate::setupTextLayout(QTextLayout *layout)
{
    Q_Q(QDeclarativeText);
    layout->setCacheEnabled(true);

    int height = 0;
    qreal widthUsed = 0;
    qreal lineWidth = 0;

    //set manual width
    if ((wrap || elideMode != QDeclarativeText::ElideNone) && q->widthValid())
        lineWidth = q->width();

    layout->beginLayout();

    while (1) {
        QTextLine line = layout->createLine();
        if (!line.isValid())
            break;

        if ((wrap || elideMode != QDeclarativeText::ElideNone) && q->widthValid())
            line.setLineWidth(lineWidth);
    }
    layout->endLayout();

    int x = 0;
    for (int i = 0; i < layout->lineCount(); ++i) {
        QTextLine line = layout->lineAt(i);
        widthUsed = qMax(widthUsed, line.naturalTextWidth());
        line.setPosition(QPointF(0, height));
        height += int(line.height());

        if (!cache) {
            if (hAlign == QDeclarativeText::AlignLeft) {
                x = 0;
            } else if (hAlign == QDeclarativeText::AlignRight) {
                x = q->width() - (int)line.naturalTextWidth();
            } else if (hAlign == QDeclarativeText::AlignHCenter) {
                x = (q->width() - (int)line.naturalTextWidth()) / 2;
            }
            line.setPosition(QPoint(x, (int)line.y()));
        }
    }

    return QSize(qCeil(widthUsed), height);
}
void Window::paintEvent(QPaintEvent *event)
{
//! [0]
    QTextLayout textLayout(text, font);
    qreal margin = 10;
    qreal radius = qMin(width()/2.0, height()/2.0) - margin;
    QFontMetrics fm(font);

    qreal lineHeight = fm.height();
    qreal y = 0;

    textLayout.beginLayout();

    while (1) {
        // create a new line 
        QTextLine line = textLayout.createLine();
        if (!line.isValid())
            break;

        qreal x1 = qMax(0.0, pow(pow(radius,2)-pow(radius-y,2), 0.5));
        qreal x2 = qMax(0.0, pow(pow(radius,2)-pow(radius-(y+lineHeight),2), 0.5));
        qreal x = qMax(x1, x2) + margin;
        qreal lineWidth = (width() - margin) - x;

        line.setLineWidth(lineWidth);
        line.setPosition(QPointF(x, margin+y));
        y += line.height();
    }

    textLayout.endLayout();

    QPainter painter;
    painter.begin(this);
    painter.setRenderHint(QPainter::Antialiasing);
    painter.fillRect(rect(), Qt::white);
    painter.setBrush(QBrush(Qt::black));
    painter.setPen(QPen(Qt::black));
    textLayout.draw(&painter, QPoint(0,0));

    painter.setBrush(QBrush(QColor("#a6ce39")));
    painter.setPen(QPen(Qt::black));
    painter.drawEllipse(QRectF(-radius, margin, 2*radius, 2*radius));
    painter.end();
//! [0]
}
Ejemplo n.º 19
0
void CodeEditor::mouseMoveEvent(QMouseEvent* event)
{
    QTextBlock block = findBlockByY(event->pos().y());

    QRect collapseRect;

    if (block.isValid()) {
        QRectF    rect = blockBoundingGeometry(block).translated(contentOffset());
        QTextLine line = block.layout()->lineAt(0);

        collapseRect = QRect(rect.x() + line.rect().x() + line.naturalTextWidth() + FONTWIDTH * 2,
                             rect.y() + 2, FONTWIDTH * 6, line.height() - 4);
    }

    int state = block.userState();

    if (!(state & Error) && state & Folded && collapseRect.contains(event->pos())) {
        pointedBlock = block;

        viewport()->setCursor(Qt::PointingHandCursor);

        QString str;

        while ((block = block.next()).isValid() && !block.isVisible()) {

            if (str.count() > 1)
                str += "\n";

            if (block.blockNumber() - pointedBlock.blockNumber() > 50) {
                str += "..."; // "\n...";
                break;
            }

            str += block.text();
        }

        QToolTip::showText(event->globalPos(), str, this);
    } else {
        pointedBlock = QTextBlock();
        viewport()->setCursor(Qt::IBeamCursor);
    }

    QPlainTextEdit::mouseMoveEvent(event);
}
Ejemplo n.º 20
0
void StyledLabel::layout()
{
    qreal h = 0;
    qreal w = contentsRect().width();

    _layout.beginLayout();
    forever {
        QTextLine line = _layout.createLine();
        if (!line.isValid())
            break;
        line.setLineWidth(w);
        line.setPosition(QPointF(0, h));
        h += line.height();
    }
    _layout.endLayout();

    updateSizeHint();
    updateToolTip();
    update();
}
qreal QmlConsoleItemDelegate::layoutText(QTextLayout &tl, int width,
                                         bool *showFileLineInfo) const
{
    qreal height = 0;
    tl.beginLayout();
    while (true) {
        QTextLine line = tl.createLine();

        if (!line.isValid())
            break;
        line.setLeadingIncluded(true);
        line.setLineWidth(width);
        if (width < line.naturalTextWidth() && showFileLineInfo)
            *showFileLineInfo = false;
        line.setPosition(QPoint(0, height));
        height += line.height();
    }
    tl.endLayout();
    return height;
}
Ejemplo n.º 22
0
void PluginListDelegate::drawDisplay(QPainter* painter, const QStyleOptionViewItem &option, const QRect &rect, const QString &text) const
{
    QPalette::ColorGroup cg = option.state & QStyle::State_Enabled ? QPalette::Normal : QPalette::Disabled;

    if (cg == QPalette::Normal && !(option.state & QStyle::State_Active)) {
        cg = QPalette::Inactive;
    }

    if (option.state & QStyle::State_Selected) {
        painter->fillRect(rect, option.palette.brush(cg, QPalette::Highlight));
        painter->setPen(option.palette.color(cg, QPalette::HighlightedText));
    }
    else {
        painter->setPen(option.palette.color(cg, QPalette::Text));
    }

    QTextDocument textDocument;
    textDocument.setHtml(text);

    QTextLayout textLayout(textDocument.begin());
    textLayout.setFont(option.font);

    const int textMargin = QApplication::style()->pixelMetric(QStyle::PM_FocusFrameHMargin, 0) + 1;
    QRect textRect = rect.adjusted(textMargin, 0, -textMargin, 0); // remove width padding

    textLayout.beginLayout();
    qreal height = 0;
    QTextLine line = textLayout.createLine();

    while (line.isValid()) {
        line.setLineWidth(textRect.width());
        height += 3;
        line.setPosition(QPoint(0, height));
        height += line.height();

        line = textLayout.createLine();
    }

    textLayout.endLayout();
    textLayout.draw(painter, QPointF(textRect.left(), textRect.top()));
}
Ejemplo n.º 23
0
//virtual
void	PageTab::redoLabelTextLayout()
{
	//TODO: somewhat wasteful. If there is no label, should just exit early and leave a layout that will be left unrendered by paint()
	m_textLayoutObject.clearLayout();;
	//TODO: Need a real fix later instead of localizing the labels at runtime
	QString m_tabLabelLocalized = fromStdUtf8(LOCALIZED(m_tabLabel.toStdString()));
	m_textLayoutObject.setText(m_tabLabelLocalized);

//	int fontSize = qBound(4,(int)((qreal)(m_labelMaxGeom.height())*0.5),24) -2;
//	fontSize = fontSize - (fontSize % 2);
//	m_textFont.setPixelSize(fontSize);
	m_textLayoutObject.setFont(m_textFont);
	QTextOption textOpts;
	textOpts.setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
	textOpts.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
	m_textLayoutObject.setTextOption(textOpts);

	QFontMetrics textFontMetrics(m_textFont);
	int leading = textFontMetrics.leading();
	int rise = textFontMetrics.ascent();
	qreal height = 0;

	m_textLayoutObject.beginLayout();
	while (height < m_labelMaxGeom.height()) {
		QTextLine line = m_textLayoutObject.createLine();
		if (!line.isValid())
			break;
		line.setLineWidth(m_labelMaxGeom.width());
		if (m_textLayoutObject.lineCount() > 1)
		{
			height += leading;
		}
		line.setPosition(QPointF(0, height));
		height += line.height();
	}
	height = qMin((quint32)DimensionsGlobal::roundUp(height),(quint32)m_labelMaxGeom.height());
	height = DimensionsGlobal::roundDown(height) - (DimensionsGlobal::roundDown(height) % 2);	//force to an even #
	m_textLayoutObject.endLayout();
	//TODO: PIXEL-ALIGN
	m_labelGeom = DimensionsGlobal::realRectAroundRealPoint(QSizeF(m_textLayoutObject.boundingRect().width(),height)).toAlignedRect();
}
Ejemplo n.º 24
0
QStringList
StatusEventItemDelegate::layoutText(const QString &text,
                                    const QFont &font,
                                    int maxLineWidth,
                                    int maxLines,
                                    int *textHeight)
{
  QTextLayout textLayout(text, font);
  QFontMetrics fontMetrics(font);
  QStringList lines;
  qreal height = 0.0;

  textLayout.beginLayout();
  while (lines.size() < maxLines) {
    QTextLine line = textLayout.createLine();
    if (! line.isValid())
      break;
    if (maxLines <= 0 || lines.size() < maxLines-1) {
      // Wrap the current line at or below the maximum line width
      line.setLineWidth(maxLineWidth);
      lines.append(text.mid(line.textStart(), line.textLength()));
    } else {
      // Set the line width beyond the max line width, and then elide it
      // so the user has a visible indication that the full message is
      // longer than what is visible.
      line.setLineWidth(2 * maxLineWidth);
      lines.append(fontMetrics.elidedText(text.mid(line.textStart()),
                                          Qt::ElideRight,
                                          maxLineWidth));
    }
    height += fontMetrics.leading() + line.height();
  }
  textLayout.endLayout();

  if (textHeight)
    *textHeight = qRound(height);

  return lines;
}
Ejemplo n.º 25
0
// Calculates the height of the description text based on widget width
int QCommandLinkButtonPrivate::descriptionHeight(int widgetWidth) const
{
    // Calc width of actual paragraph
    int lineWidth = widgetWidth - textOffset() - rightMargin();

    qreal descriptionheight = 0;
    if (!description.isEmpty()) {
        QTextLayout layout(description);
        layout.setFont(descriptionFont());
        layout.beginLayout();
        while (true) {
            QTextLine line = layout.createLine();
            if (!line.isValid())
                break;
            line.setLineWidth(lineWidth);
            line.setPosition(QPointF(0, descriptionheight));
            descriptionheight += line.height();
        }
        layout.endLayout();
    }
    return qRound(descriptionheight);
}
Ejemplo n.º 26
0
void FadingMultilineLabel::positionLayouts()
{
	QFontMetricsF fm = fontMetrics();
	qreal lineHeight = fm.height();

	delete textLayout_;
	textLayout_ = 0;

	textLayout_ = new QTextLayout(text_, font());
	textLayout_->setTextOption(textOption_);
	// textLayout_->setAdditionalFormats(formats[p]);
	textLayout_->beginLayout();

	qreal x = 0.0;
	qreal y = 0.0;
	qreal ymax = 0.0;

	fadeOuts_.clear();
	QTextLine line = textLayout_->createLine();

	while (line.isValid()) {
		line.setPosition(QPointF(x, y));
		line.setLineWidth(width());

		if (line.naturalTextWidth() > width()) {
			fadeOuts_ << QRect(x, y, width(), lineHeight);
		}

		y += line.height();
		line = textLayout_->createLine();
	}

	textLayout_->endLayout();

	sizeHint_ = QSize(width(), y);
	updateGeometry();
}
Ejemplo n.º 27
0
void TestDocumentLayout::placeAnchoredFrame2()
{
    QFETCH(int, horizontalAlignment);
    QFETCH(int, verticalAlignment);
    QFETCH(QPointF, startPosition);
    QFETCH(QPointF, imagePosition);

    initForNewTest(QString(loremIpsum));
    MockShape *picture = new MockShape();
    picture->setSize(QSizeF(198, 400));
    KTextAnchor *anchor = new KTextAnchor(picture);
    anchor->setAlignment(KTextAnchor::AnchorHorizontal(horizontalAlignment));
    anchor->setAlignment(KTextAnchor::AnchorVertical(verticalAlignment));
    picture->setPosition(startPosition);
    QTextCursor cursor(doc);

    KInlineTextObjectManager *manager = new KInlineTextObjectManager();
    layout->setInlineTextObjectManager(manager);
    MockLayoutState *state = new MockLayoutState(doc);
    layout->setLayout(state);
    state->shape = shape1;
    manager->insertInlineObject(cursor, anchor);
    QCOMPARE(cursor.position(), 1);
    layout->layout();

    QCOMPARE(picture->parent(), shape1);
    QCOMPARE(picture->position(), imagePosition);

    // test if rest of text is below picture.
    QTextLayout *lay = doc->begin().layout();
    QVERIFY(lay->lineCount() >= 1);
    QTextLine line = lay->lineForTextPosition(1); // the first char of real text.
    QVERIFY(line.isValid());
    // qDebug() << line.y() << line.height();
    QVERIFY(line.y() + line.height() >= 412); // test that text is below image
}
Ejemplo n.º 28
0
QSize TaskDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QStyleOptionViewItemV4 opt = option;
    initStyleOption(&opt, index);


    QFontMetrics fm(option.font);
    QSize s;
    s.setWidth(option.rect.width());
    const QAbstractItemView * view = qobject_cast<const QAbstractItemView *>(opt.widget);
    TaskModel *model = static_cast<TaskModel *>(view->model());
    int width = opt.rect.width() - model->sizeOfFile() - model->sizeOfLineNumber() - 12 - 22;
    if (view->selectionModel()->currentIndex() == index) {
        QString description = index.data(TaskModel::Description).toString();
        // Layout the description
        int leading = fm.leading();
        int height = 0;
        QTextLayout tl(description);
        tl.beginLayout();
        while (true) {
            QTextLine line = tl.createLine();
            if (!line.isValid())
                break;
            line.setLineWidth(width);
            height += leading;
            line.setPosition(QPoint(0, height));
            height += static_cast<int>(line.height());
        }
        tl.endLayout();

        s.setHeight(height + leading + fm.height() + 3);
    } else {
        s.setHeight(fm.height() + 3);
    }
    return s;
}
Ejemplo n.º 29
0
/// Calculate single line layout for given text with specified font.
/// This function automatically add ellipsis text if the naural width
/// is larger than given region.
/// \layout The result layout.
/// \font The font object.
/// \string The text needs to be layouted.
/// \align Alignment.
/// \rect The region.
/// \ellipsis Add ellipse to left or right if necessary.
/// Returns the line height.
int calculateSingleLineLayout(QTextLayout & layout,
                              const QFont & font,
                              const QString & string,
                              const Qt::Alignment align,
                              const QRect & rect,
                              const Qt::TextElideMode ellipsis)
{
    QFontMetrics fm(font);

    // Check if we need to add ellipsis.
    QString result_string = string;
    int width = ellipsisText(string, fm, rect.width(),
                             ellipsis, result_string);

    // Construct the layout.
    layout.clearLayout();
    layout.setCacheEnabled(false);
    layout.setText(result_string);
    layout.setFont(font);
    layout.beginLayout();
    QTextLine line = layout.createLine();
    if (line.isValid())
    {
        line.setLineWidth(rect.width());
    }
    layout.endLayout();

    // Calculate the position.
    int x = rect.left();
    int y = rect.top();
    int h = static_cast<int>(line.height());

    if (align & Qt::AlignHCenter)
    {
        x = ((rect.width() - width) >> 1) + x;
    }
Ejemplo n.º 30
0
void Msg::ShowMsg(const QString str)
{
    mUpdateRect = boundingRect();

    mLay->setText(str);
    int leading = -3;
    qreal h = 0;
    qreal maxw = 0;
    qreal maxh = 0;
    mLay->beginLayout();

    while (1)
    {
        QTextLine line = mLay->createLine();
        if (!line.isValid())
        {
            break;
        }

        line.setLineWidth(280);
        h += leading;
        line.setPosition(QPointF(0, h));
        h += line.height();
        maxw = qMax(maxw, line.naturalTextWidth());
    }
    mLay->endLayout();

    float ypos = 4 + (70 - mLay->boundingRect().height()) / 2;

    maxw = qMax(mUpdateRect.width(), mLay->boundingRect().width());
    maxh = qMax(mUpdateRect.height(), mLay->boundingRect().height() + ypos);

    mUpdateRect = QRectF(0, 0, maxw, maxh + ypos);

    update(boundingRect());
}