/// 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; }
void QStaticTextPrivate::paintText(const QPointF &topLeftPosition, QPainter *p) { bool preferRichText = textFormat == Qt::RichText || (textFormat == Qt::AutoText && Qt::mightBeRichText(text)); if (!preferRichText) { QTextLayout textLayout; textLayout.setText(text); textLayout.setFont(font); textLayout.setTextOption(textOption); textLayout.setCacheEnabled(true); qreal leading = QFontMetricsF(font).leading(); qreal height = -leading; textLayout.beginLayout(); while (1) { QTextLine line = textLayout.createLine(); if (!line.isValid()) break; if (textWidth >= 0.0) line.setLineWidth(textWidth); height += leading; line.setPosition(QPointF(0.0, height)); height += line.height(); } textLayout.endLayout(); actualSize = textLayout.boundingRect().size(); textLayout.draw(p, topLeftPosition); } else { QTextDocument document; #ifndef QT_NO_CSSPARSER QColor color = p->pen().color(); document.setDefaultStyleSheet(QString::fromLatin1("body { color: #%1%2%3 }") .arg(QString::number(color.red(), 16), 2, QLatin1Char('0')) .arg(QString::number(color.green(), 16), 2, QLatin1Char('0')) .arg(QString::number(color.blue(), 16), 2, QLatin1Char('0'))); #endif document.setDefaultFont(font); document.setDocumentMargin(0.0); #ifndef QT_NO_TEXTHTMLPARSER document.setHtml(text); #else document.setPlainText(text); #endif if (textWidth >= 0.0) document.setTextWidth(textWidth); else document.adjustSize(); document.setDefaultTextOption(textOption); p->save(); p->translate(topLeftPosition); QAbstractTextDocumentLayout::PaintContext ctx; ctx.palette.setColor(QPalette::Text, p->pen().color()); document.documentLayout()->draw(p, ctx); p->restore(); if (textWidth >= 0.0) document.adjustSize(); // Find optimal size actualSize = document.size(); } }