Qt 4.8
Classes | Public Types | Public Functions | Private Functions | Properties | Friends | List of all members
QTextLayout Class Reference

The QTextLayout class is used to lay out and render text. More...

#include <qtextlayout.h>

Inheritance diagram for QTextLayout:
QDeclarativeTextLayout

Classes

class  FormatRange
 The QTextLayout::FormatRange structure is used to apply extra formatting information for a specified area in the text layout's content. More...
 

Public Types

enum  CursorMode { SkipCharacters, SkipWords }
 

Public Functions

QList< FormatRangeadditionalFormats () const
 Returns the list of additional formats supported by the text layout. More...
 
void beginLayout ()
 Begins the layout process. More...
 
QRectF boundingRect () const
 The smallest rectangle that contains all the lines in the layout. More...
 
bool cacheEnabled () const
 Returns true if the complete layout information is cached; otherwise returns false. More...
 
void clearAdditionalFormats ()
 Clears the list of additional formats supported by the text layout. More...
 
void clearLayout ()
 Clears the line information in the layout. More...
 
QTextLine createLine ()
 Returns a new text line to be laid out if there is text to be inserted into the layout; otherwise returns an invalid text line. More...
 
Qt::CursorMoveStyle cursorMoveStyle () const
 The cursor movement style of this QTextLayout. More...
 
void draw (QPainter *p, const QPointF &pos, const QVector< FormatRange > &selections=QVector< FormatRange >(), const QRectF &clip=QRectF()) const
 Draws the whole layout on the painter p at the position specified by pos. More...
 
void drawCursor (QPainter *p, const QPointF &pos, int cursorPosition) const
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Draws a text cursor with the current pen at the given position using the painter specified. More...
 
void drawCursor (QPainter *p, const QPointF &pos, int cursorPosition, int width) const
 Draws a text cursor with the current pen and the specified width at the given position using the painter specified. More...
 
void endLayout ()
 Ends the layout process. More...
 
QTextEngineengine () const
 
QFont font () const
 Returns the current font that is used for the layout, or a default font if none is set. More...
 
QList< QGlyphRunglyphRuns () const
 Returns the glyph indexes and positions for all glyphs in this QTextLayout. More...
 
bool isValidCursorPosition (int pos) const
 / Returns true if position pos is a valid cursor position. More...
 
int leftCursorPosition (int oldPos) const
 Returns the cursor position to the left of oldPos, next to it. More...
 
QTextLine lineAt (int i) const
 Returns the {i}-th line of text in this text layout. More...
 
int lineCount () const
 Returns the number of lines in this text layout. More...
 
QTextLine lineForTextPosition (int pos) const
 Returns the line that contains the cursor position specified by pos. More...
 
qreal maximumWidth () const
 The maximum width the layout could expand to; this is essentially the width of the entire text. More...
 
qreal minimumWidth () const
 The minimum width the layout needs. More...
 
int nextCursorPosition (int oldPos, CursorMode mode=SkipCharacters) const
 Returns the next valid cursor position after oldPos that respects the given cursor mode. More...
 
QPointF position () const
 The global position of the layout. More...
 
int preeditAreaPosition () const
 Returns the position of the area in the text layout that will be processed before editing occurs. More...
 
QString preeditAreaText () const
 Returns the text that is inserted in the layout before editing occurs. More...
 
int previousCursorPosition (int oldPos, CursorMode mode=SkipCharacters) const
 Returns the first valid cursor position before oldPos that respects the given cursor mode. More...
 
 QTextLayout ()
 Constructs an empty text layout. More...
 
 QTextLayout (const QString &text)
 Constructs a text layout to lay out the given text. More...
 
 QTextLayout (const QString &text, const QFont &font, QPaintDevice *paintdevice=0)
 Constructs a text layout to lay out the given text with the specified font. More...
 
 QTextLayout (const QTextBlock &b)
 Constructs a text layout to lay out the given block. More...
 
int rightCursorPosition (int oldPos) const
 Returns the cursor position to the right of oldPos, next to it. More...
 
void setAdditionalFormats (const QList< FormatRange > &overrides)
 Sets the additional formats supported by the text layout to formatList. More...
 
void setCacheEnabled (bool enable)
 Enables caching of the complete layout information if enable is true; otherwise disables layout caching. More...
 
void setCursorMoveStyle (Qt::CursorMoveStyle style)
 Set the cursor movement style. More...
 
void setFlags (int flags)
 
void setFont (const QFont &f)
 Sets the layout's font to the given font. More...
 
void setPosition (const QPointF &p)
 Moves the text layout to point p. More...
 
void setPreeditArea (int position, const QString &text)
 Sets the position and text of the area in the layout that is processed before editing occurs. More...
 
void setText (const QString &string)
 Sets the layout's text to the given string. More...
 
void setTextOption (const QTextOption &option)
 Sets the text option structure that controls the layout process to the given option. More...
 
QString text () const
 Returns the layout's text. More...
 
QTextOption textOption () const
 Returns the current text option used to control the layout process. More...
 
 ~QTextLayout ()
 Destructs the layout. More...
 

Private Functions

 QTextLayout (QTextEngine *e)
 

Properties

QTextEngined
 

Friends

class QGraphicsSimpleTextItem
 
class QGraphicsSimpleTextItemPrivate
 
class QPainter
 
class QPSPrinter
 
void qt_format_text (const QFont &font, const QRectF &_r, int tf, const QTextOption *, const QString &str, QRectF *brect, int tabstops, int *tabarray, int tabarraylen, QPainter *painter)
 

Detailed Description

The QTextLayout class is used to lay out and render text.

Note
This class or function is reentrant.

It offers many features expected from a modern text layout engine, including Unicode compliant rendering, line breaking and handling of cursor positioning. It can also produce and render device independent layout, something that is important for WYSIWYG applications.

The class has a rather low level API and unless you intend to implement your own text rendering for some specialized widget, you probably won't need to use it directly.

QTextLayout can be used with both plain and rich text.

QTextLayout can be used to create a sequence of QTextLine instances with given widths and can position them independently on the screen. Once the layout is done, these lines can be drawn on a paint device.

The text to be laid out can be provided in the constructor or set with setText().

The layout can be seen as a sequence of QTextLine objects; use createLine() to create a QTextLine instance, and lineAt() or lineForTextPosition() to retrieve created lines.

Here is a code snippet that demonstrates the layout phase:

int leading = fontMetrics.leading();
qreal height = 0;
textLayout.beginLayout();
while (1) {
QTextLine line = textLayout.createLine();
if (!line.isValid())
break;
line.setLineWidth(lineWidth);
height += leading;
line.setPosition(QPointF(0, height));
height += line.height();
}
textLayout.endLayout();

The text can then be rendered by calling the layout's draw() function:

QPainter painter(this);
textLayout.draw(&painter, QPoint(0, 0));

For a given position in the text you can find a valid cursor position with isValidCursorPosition(), nextCursorPosition(), and previousCursorPosition().

The QTextLayout itself can be positioned with setPosition(); it has a boundingRect(), and a minimumWidth() and a maximumWidth().

See also
QStaticText

Definition at line 105 of file qtextlayout.h.

Enumerations

◆ CursorMode

  • SkipCharacters
  • SkipWords
Enumerator
SkipCharacters 
SkipWords 

Definition at line 153 of file qtextlayout.h.

Constructors and Destructors

◆ QTextLayout() [1/5]

QTextLayout::QTextLayout ( )

Constructs an empty text layout.

See also
setText()

Definition at line 344 of file qtextlayout.cpp.

345 { d = new QTextEngine(); }
QTextEngine * d
Definition: qtextlayout.h:193

◆ QTextLayout() [2/5]

QTextLayout::QTextLayout ( const QString text)

Constructs a text layout to lay out the given text.

Definition at line 350 of file qtextlayout.cpp.

351 {
352  d = new QTextEngine();
353  d->text = text;
354 }
QString text() const
Returns the layout&#39;s text.
QString text
QTextEngine * d
Definition: qtextlayout.h:193

◆ QTextLayout() [3/5]

QTextLayout::QTextLayout ( const QString text,
const QFont font,
QPaintDevice paintdevice = 0 
)

Constructs a text layout to lay out the given text with the specified font.

All the metric and layout calculations will be done in terms of the paint device, paintdevice. If paintdevice is 0 the calculations will be done in screen metrics.

Definition at line 364 of file qtextlayout.cpp.

365 {
366  QFont f(font);
367  if (paintdevice)
368  f = QFont(font, paintdevice);
369  d = new QTextEngine((text.isNull() ? (const QString&)QString::fromLatin1("") : text), f.d.data());
370 }
The QString class provides a Unicode character string.
Definition: qstring.h:83
QString text() const
Returns the layout&#39;s text.
bool isNull() const
Returns true if this string is null; otherwise returns false.
Definition: qstring.h:505
The QFont class specifies a font used for drawing text.
Definition: qfont.h:64
static QString fromLatin1(const char *, int size=-1)
Returns a QString initialized with the first size characters of the Latin-1 string str...
Definition: qstring.cpp:4188
QTextEngine * d
Definition: qtextlayout.h:193

◆ QTextLayout() [4/5]

QTextLayout::QTextLayout ( const QTextBlock block)

Constructs a text layout to lay out the given block.

Warning
This function is not part of the public interface.

Definition at line 379 of file qtextlayout.cpp.

380 {
381  d = new QTextEngine();
382  d->block = block;
383 }
QTextBlock block
QTextEngine * d
Definition: qtextlayout.h:193

◆ ~QTextLayout()

QTextLayout::~QTextLayout ( )

Destructs the layout.

Definition at line 388 of file qtextlayout.cpp.

389 {
390  if (!d->stackEngine)
391  delete d;
392 }
QTextEngine * d
Definition: qtextlayout.h:193

◆ QTextLayout() [5/5]

QTextLayout::QTextLayout ( QTextEngine e)
inlineprivate

Definition at line 183 of file qtextlayout.h.

183 : d(e) {}
QTextEngine * d
Definition: qtextlayout.h:193

Functions

◆ additionalFormats()

QList< QTextLayout::FormatRange > QTextLayout::additionalFormats ( ) const

Returns the list of additional formats supported by the text layout.

See also
setAdditionalFormats(), clearAdditionalFormats()

Definition at line 551 of file qtextlayout.cpp.

Referenced by QSyntaxHighlighterPrivate::applyFormatChanges().

552 {
553  QList<FormatRange> formats;
554  if (!d->specialData)
555  return formats;
556 
557  formats = d->specialData->addFormats;
558 
560  return formats;
561 
562  const QTextFormatCollection *collection = d->formats();
563 
564  for (int i = 0; i < d->specialData->addFormatIndices.count(); ++i)
565  formats[i].format = collection->charFormat(d->specialData->addFormatIndices.at(i));
566 
567  return formats;
568 }
QTextCharFormat charFormat(int index) const
Definition: qtextformat_p.h:85
int count(const T &t) const
Returns the number of occurrences of value in the vector.
Definition: qvector.h:742
SpecialData * specialData
QList< QTextLayout::FormatRange > addFormats
const T & at(int i) const
Returns the item at index position i in the vector.
Definition: qvector.h:350
QVector< int > addFormatIndices
bool isEmpty() const
Returns true if the vector has size 0; otherwise returns false.
Definition: qvector.h:139
QTextFormatCollection * formats() const
QTextEngine * d
Definition: qtextlayout.h:193
The QList class is a template class that provides lists.
Definition: qdatastream.h:62

◆ beginLayout()

void QTextLayout::beginLayout ( )

Begins the layout process.

See also
endLayout()

Definition at line 645 of file qtextlayout.cpp.

Referenced by QPainterPath::addText(), QDeclarativeTextLayout::beginLayout(), QCommandLinkButtonPrivate::descriptionHeight(), QItemDelegatePrivate::doTextLayout(), QSvgText::draw(), QTextDocumentLayoutPrivate::drawListItem(), QRawFont::fromFont(), QPlainTextDocumentLayout::layoutBlock(), QTextDocumentLayoutPrivate::layoutBlock(), QStaticTextPrivate::paintText(), qt_format_text(), setupTextLayout(), QLineControl::updateDisplayText(), QCommonStylePrivate::viewItemSize(), and viewItemTextLayout().

646 {
647 #ifndef QT_NO_DEBUG
649  qWarning("QTextLayout::beginLayout: Called while already doing layout");
650  return;
651  }
652 #endif
653  d->invalidate();
654  d->clearLineData();
655  d->itemize();
657 }
void clearLineData()
LayoutData * layoutData
Q_CORE_EXPORT void qWarning(const char *,...)
void itemize() const
void invalidate()
QTextEngine * d
Definition: qtextlayout.h:193

◆ boundingRect()

QRectF QTextLayout::boundingRect ( ) const

The smallest rectangle that contains all the lines in the layout.

Definition at line 934 of file qtextlayout.cpp.

Referenced by QTextDocumentLayout::blockBoundingRect(), QPlainTextDocumentLayout::blockBoundingRect(), QTextDocumentLayoutPrivate::drawBlock(), QTextDocumentLayoutPrivate::hitTest(), QTextDocumentLayoutPrivate::layoutBlock(), QTextDocumentLayoutPrivate::layoutFlow(), and QStaticTextPrivate::paintText().

935 {
936  if (d->lines.isEmpty())
937  return QRectF();
938 
939  QFixed xmax, ymax;
940  QFixed xmin = d->lines.at(0).x;
941  QFixed ymin = d->lines.at(0).y;
942 
943  for (int i = 0; i < d->lines.size(); ++i) {
944  const QScriptLine &si = d->lines[i];
945  xmin = qMin(xmin, si.x);
946  ymin = qMin(ymin, si.y);
947  QFixed lineWidth = si.width < QFIXED_MAX ? qMax(si.width, si.textWidth) : si.textWidth;
948  xmax = qMax(xmax, si.x+lineWidth);
949  // ### shouldn't the ascent be used in ymin???
950  ymax = qMax(ymax, si.y+si.height());
951  }
952  return QRectF(xmin.toReal(), ymin.toReal(), (xmax-xmin).toReal(), (ymax-ymin).toReal());
953 }
Q_DECL_CONSTEXPR const T & qMin(const T &a, const T &b)
Definition: qglobal.h:1215
#define QFIXED_MAX
Definition: qfixed_p.h:158
QFixed textWidth
QFixed height() const
Q_DECL_CONSTEXPR const T & qMax(const T &a, const T &b)
Definition: qglobal.h:1217
The QRectF class defines a rectangle in the plane using floating point precision. ...
Definition: qrect.h:511
QScriptLineArray lines
const T & at(int i) const
Returns the item at index position i in the vector.
Definition: qvector.h:350
qreal toReal() const
Definition: qfixed_p.h:77
bool isEmpty() const
Returns true if the vector has size 0; otherwise returns false.
Definition: qvector.h:139
int size() const
Returns the number of items in the vector.
Definition: qvector.h:137
QTextEngine * d
Definition: qtextlayout.h:193
static qreal toReal(Register *reg, int type, bool *ok=0)

◆ cacheEnabled()

bool QTextLayout::cacheEnabled ( ) const

Returns true if the complete layout information is cached; otherwise returns false.

See also
setCacheEnabled()

Definition at line 601 of file qtextlayout.cpp.

602 {
603  return d->cacheGlyphs;
604 }
QTextEngine * d
Definition: qtextlayout.h:193

◆ clearAdditionalFormats()

void QTextLayout::clearAdditionalFormats ( )

Clears the list of additional formats supported by the text layout.

See also
additionalFormats(), setAdditionalFormats()

Definition at line 575 of file qtextlayout.cpp.

576 {
578 }
void setAdditionalFormats(const QList< FormatRange > &overrides)
Sets the additional formats supported by the text layout to formatList.
The QList class is a template class that provides lists.
Definition: qdatastream.h:62

◆ clearLayout()

void QTextLayout::clearLayout ( )

Clears the line information in the layout.

Since
4.4

After having called this function, lineCount() returns 0.

Definition at line 690 of file qtextlayout.cpp.

Referenced by QDeclarativeTextLayout::clearLayout(), QTextBlock::clearLayout(), and QPlainTextDocumentLayoutPrivate::relayout().

691 {
692  d->clearLineData();
693 }
void clearLineData()
QTextEngine * d
Definition: qtextlayout.h:193

◆ createLine()

QTextLine QTextLayout::createLine ( )

Returns a new text line to be laid out if there is text to be inserted into the layout; otherwise returns an invalid text line.

The text layout creates a new line object that starts after the last line in the layout, or at the beginning if the layout is empty. The layout maintains an internal cursor, and each line is filled with text from the cursor position onwards when the QTextLine::setLineWidth() function is called.

Once QTextLine::setLineWidth() is called, a new line can be created and filled with text. Repeating this process will lay out the whole block of text contained in the QTextLayout. If there is no text left to be inserted into the layout, the QTextLine returned will not be valid (isValid() will return false).

Definition at line 842 of file qtextlayout.cpp.

Referenced by QPainterPath::addText(), QCommandLinkButtonPrivate::descriptionHeight(), QItemDelegatePrivate::doTextLayout(), QSvgText::draw(), QTextDocumentLayoutPrivate::drawListItem(), QRawFont::fromFont(), QPlainTextDocumentLayout::layoutBlock(), QTextDocumentLayoutPrivate::layoutBlock(), QStaticTextPrivate::paintText(), qt_format_text(), setupTextLayout(), QLineControl::updateDisplayText(), QCommonStylePrivate::viewItemSize(), and viewItemTextLayout().

843 {
844 #ifndef QT_NO_DEBUG
846  qWarning("QTextLayout::createLine: Called without layouting");
847  return QTextLine();
848  }
849 #endif
851  return QTextLine();
852 
853  int l = d->lines.size();
854  if (l && d->lines.at(l-1).length < 0) {
856  }
857  int from = l > 0 ? d->lines.at(l-1).from + d->lines.at(l-1).length + d->lines.at(l-1).trailingSpaces : 0;
858  int strlen = d->layoutData->string.length();
859  if (l && from >= strlen) {
860  if (!d->lines.at(l-1).length || d->layoutData->string.at(strlen - 1) != QChar::LineSeparator)
861  return QTextLine();
862  }
863 
864  QScriptLine line;
865  line.from = from;
866  line.length = -1;
867  line.justified = false;
868  line.gridfitted = false;
869 
870  d->lines.append(line);
871  return QTextLine(l, d);
872 }
unsigned short trailingSpaces
const QChar at(int i) const
Returns the character at the given index position in the string.
Definition: qstring.h:698
int length() const
Returns the number of characters in this string.
Definition: qstring.h:696
The QTextLine class represents a line of text inside a QTextLayout.
Definition: qtextlayout.h:197
LayoutData * layoutData
void setNumColumns(int columns)
Lays out the line.
void append(const T &t)
Inserts value at the end of the vector.
Definition: qvector.h:573
Q_CORE_EXPORT void qWarning(const char *,...)
QScriptLineArray lines
const T & at(int i) const
Returns the item at index position i in the vector.
Definition: qvector.h:350
QFactoryLoader * l
signed int length
int size() const
Returns the number of items in the vector.
Definition: qvector.h:137
#define INT_MAX
QTextEngine * d
Definition: qtextlayout.h:193

◆ cursorMoveStyle()

Qt::CursorMoveStyle QTextLayout::cursorMoveStyle ( ) const

The cursor movement style of this QTextLayout.

Since
4.8

The default is Qt::LogicalMoveStyle.

See also
setCursorMoveStyle()

Definition at line 635 of file qtextlayout.cpp.

◆ draw()

void QTextLayout::draw ( QPainter p,
const QPointF pos,
const QVector< FormatRange > &  selections = QVector<FormatRange>(),
const QRectF clip = QRectF() 
) const

Draws the whole layout on the painter p at the position specified by pos.

The rendered layout includes the given selections and is clipped within the rectangle specified by clip.

Definition at line 1074 of file qtextlayout.cpp.

Referenced by QDeclarativeTextLayout::draw(), QSvgText::draw(), QLineControl::draw(), QTextDocumentLayoutPrivate::drawBlock(), QTextDocumentLayoutPrivate::drawListItem(), QGraphicsSimpleTextItem::paint(), QPlainTextEdit::paintEvent(), QStaticTextPrivate::paintText(), and QDeclarativeTextLayout::prepare().

1075 {
1076  if (d->lines.isEmpty())
1077  return;
1078 
1079  if (!d->layoutData)
1080  d->itemize();
1081 
1082  QPointF position = pos + d->position;
1083 
1084  QFixed clipy = (INT_MIN/256);
1085  QFixed clipe = (INT_MAX/256);
1086  if (clip.isValid()) {
1087  clipy = QFixed::fromReal(clip.y() - position.y());
1088  clipe = clipy + QFixed::fromReal(clip.height());
1089  }
1090 
1091  int firstLine = 0;
1092  int lastLine = d->lines.size();
1093  for (int i = 0; i < d->lines.size(); ++i) {
1094  QTextLine l(i, d);
1095  const QScriptLine &sl = d->lines[i];
1096 
1097  if (sl.y > clipe) {
1098  lastLine = i;
1099  break;
1100  }
1101  if ((sl.y + sl.height()) < clipy) {
1102  firstLine = i;
1103  continue;
1104  }
1105  }
1106 
1107  QPainterPath excludedRegion;
1108  QPainterPath textDoneRegion;
1109  for (int i = 0; i < selections.size(); ++i) {
1110  FormatRange selection = selections.at(i);
1111  const QBrush bg = selection.format.background();
1112 
1113  QPainterPath region;
1114  region.setFillRule(Qt::WindingFill);
1115 
1116  for (int line = firstLine; line < lastLine; ++line) {
1117  const QScriptLine &sl = d->lines[line];
1118  QTextLine tl(line, d);
1119 
1120  QRectF lineRect(tl.naturalTextRect());
1121  lineRect.translate(position);
1122  lineRect.adjust(0, 0, d->leadingSpaceWidth(sl).toReal(), 0);
1123 
1124  bool isLastLineInBlock = (line == d->lines.size()-1);
1125  int sl_length = sl.length + (isLastLineInBlock? 1 : 0); // the infamous newline
1126 
1127 
1128  if (sl.from > selection.start + selection.length || sl.from + sl_length <= selection.start)
1129  continue; // no actual intersection
1130 
1131  const bool selectionStartInLine = sl.from <= selection.start;
1132  const bool selectionEndInLine = selection.start + selection.length < sl.from + sl_length;
1133 
1134  if (sl.length && (selectionStartInLine || selectionEndInLine)) {
1135  addSelectedRegionsToPath(d, line, position, &selection, &region, clipIfValid(lineRect, clip));
1136  } else {
1137  region.addRect(clipIfValid(lineRect, clip));
1138  }
1139 
1140  if (selection.format.boolProperty(QTextFormat::FullWidthSelection)) {
1141  QRectF fullLineRect(tl.rect());
1142  fullLineRect.translate(position);
1143  fullLineRect.setRight(QFIXED_MAX);
1144  if (!selectionEndInLine)
1145  region.addRect(clipIfValid(QRectF(lineRect.topRight(), fullLineRect.bottomRight()), clip));
1146  if (!selectionStartInLine)
1147  region.addRect(clipIfValid(QRectF(fullLineRect.topLeft(), lineRect.bottomLeft()), clip));
1148  } else if (!selectionEndInLine
1149  && isLastLineInBlock
1151  region.addRect(clipIfValid(QRectF(lineRect.right(), lineRect.top(),
1152  lineRect.height()/4, lineRect.height()), clip));
1153  }
1154 
1155  }
1156  {
1157  const QPen oldPen = p->pen();
1158  const QBrush oldBrush = p->brush();
1159 
1160  p->setPen(selection.format.penProperty(QTextFormat::OutlinePen));
1161  p->setBrush(selection.format.brushProperty(QTextFormat::BackgroundBrush));
1162  p->drawPath(region);
1163 
1164  p->setPen(oldPen);
1165  p->setBrush(oldBrush);
1166  }
1167 
1168 
1169 
1170  bool hasText = (selection.format.foreground().style() != Qt::NoBrush);
1171  bool hasBackground= (selection.format.background().style() != Qt::NoBrush);
1172 
1173  if (hasBackground) {
1174  selection.format.setProperty(ObjectSelectionBrush, selection.format.property(QTextFormat::BackgroundBrush));
1175  // don't just clear the property, set an empty brush that overrides a potential
1176  // background brush specified in the text
1177  selection.format.setProperty(QTextFormat::BackgroundBrush, QBrush());
1178  selection.format.clearProperty(QTextFormat::OutlinePen);
1179  }
1180 
1181  selection.format.setProperty(SuppressText, !hasText);
1182 
1183  if (hasText && !hasBackground && !(textDoneRegion & region).isEmpty())
1184  continue;
1185 
1186  p->save();
1187  p->setClipPath(region, Qt::IntersectClip);
1188 
1189  for (int line = firstLine; line < lastLine; ++line) {
1190  QTextLine l(line, d);
1191  l.draw(p, position, &selection);
1192  }
1193  p->restore();
1194 
1195  if (hasText) {
1196  textDoneRegion += region;
1197  } else {
1198  if (hasBackground)
1199  textDoneRegion -= region;
1200  }
1201 
1202  excludedRegion += region;
1203  }
1204 
1205  QPainterPath needsTextButNoBackground = excludedRegion - textDoneRegion;
1206  if (!needsTextButNoBackground.isEmpty()){
1207  p->save();
1208  p->setClipPath(needsTextButNoBackground, Qt::IntersectClip);
1209  FormatRange selection;
1210  selection.start = 0;
1211  selection.length = INT_MAX;
1212  selection.format.setProperty(SuppressBackground, true);
1213  for (int line = firstLine; line < lastLine; ++line) {
1214  QTextLine l(line, d);
1215  l.draw(p, position, &selection);
1216  }
1217  p->restore();
1218  }
1219 
1220  if (!excludedRegion.isEmpty()) {
1221  p->save();
1222  QPainterPath path;
1223  QRectF br = boundingRect().translated(position);
1224  br.setRight(QFIXED_MAX);
1225  if (!clip.isNull())
1226  br = br.intersected(clip);
1227  path.addRect(br);
1228  path -= excludedRegion;
1229  p->setClipPath(path, Qt::IntersectClip);
1230  }
1231 
1232  for (int i = firstLine; i < lastLine; ++i) {
1233  QTextLine l(i, d);
1234  l.draw(p, position);
1235  }
1236  if (!excludedRegion.isEmpty())
1237  p->restore();
1238 
1239 
1240  if (!d->cacheGlyphs)
1241  d->freeMemory();
1242 }
static void addSelectedRegionsToPath(QTextEngine *eng, int lineNumber, const QPointF &pos, QTextLayout::FormatRange *selection, QPainterPath *region, QRectF boundingRect)
bool isEmpty() const
Returns true if either there are no elements in this path, or if the only element is a MoveToElement;...
Definition: qpainterpath.h:392
qreal y() const
Returns the y-coordinate of the rectangle&#39;s top edge.
Definition: qrect.h:667
void drawPath(const QPainterPath &path)
Draws the given painter path using the current pen for outline and the current brush for filling...
Definition: qpainter.cpp:3502
QPointF position() const
The global position of the layout.
#define QFIXED_MAX
Definition: qfixed_p.h:158
bool isValid() const
Returns true if the rectangle is valid, otherwise returns false.
Definition: qrect.h:661
The QPainterPath class provides a container for painting operations, enabling graphical shapes to be ...
Definition: qpainterpath.h:67
static QRectF clipIfValid(const QRectF &rect, const QRectF &clip)
The QPointF class defines a point in the plane using floating point precision.
Definition: qpoint.h:214
The QTextLine class represents a line of text inside a QTextLayout.
Definition: qtextlayout.h:197
void restore()
Restores the current painter state (pops a saved state off the stack).
Definition: qpainter.cpp:1620
Flags flags() const
Returns the flags associated with the option.
Definition: qtextoption.h:121
QRectF boundingRect() const
The smallest rectangle that contains all the lines in the layout.
LayoutData * layoutData
QRectF intersected(const QRectF &other) const
Returns the intersection of this rectangle and the given rectangle.
Definition: qrect.h:818
QFixed height() const
static QFixed fromReal(qreal r)
Definition: qfixed_p.h:70
The QPen class defines how a QPainter should draw lines and outlines of shapes.
Definition: qpen.h:64
void setRight(qreal pos)
Sets the right edge of the rectangle to the given x coordinate.
Definition: qrect.h:672
void save()
Saves the current painter state (pushes the state onto a stack).
Definition: qpainter.cpp:1590
void setFillRule(Qt::FillRule fillRule)
Sets the fill rule of the painter path to the given fillRule.
const QPen & pen() const
Returns the painter&#39;s current pen.
Definition: qpainter.cpp:4152
The QRectF class defines a rectangle in the plane using floating point precision. ...
Definition: qrect.h:511
static bool isEmpty(const char *str)
qreal height() const
Returns the height of the rectangle.
Definition: qrect.h:710
void addRect(const QRectF &rect)
Adds the given rectangle to this path as a closed subpath.
QScriptLineArray lines
#define SuppressBackground
Definition: qtextlayout.cpp:74
void itemize() const
QTextOption option
void translate(qreal dx, qreal dy)
Moves the rectangle dx along the x-axis and dy along the y-axis, relative to the current position...
Definition: qrect.h:716
const T & at(int i) const
Returns the item at index position i in the vector.
Definition: qvector.h:350
const QBrush & brush() const
Returns the painter&#39;s current brush.
Definition: qpainter.cpp:4232
The QBrush class defines the fill pattern of shapes drawn by QPainter.
Definition: qbrush.h:76
#define ObjectSelectionBrush
Definition: qtextlayout.cpp:72
#define SuppressText
Definition: qtextlayout.cpp:73
QPointF position
void setBrush(const QBrush &brush)
Sets the painter&#39;s brush to the given brush.
Definition: qpainter.cpp:4171
void setPen(const QColor &color)
Sets the painter&#39;s pen to have style Qt::SolidLine, width 0 and the specified color.
Definition: qpainter.cpp:4047
QFactoryLoader * l
qreal toReal() const
Definition: qfixed_p.h:77
signed int length
qreal y() const
Returns the y-coordinate of this point.
Definition: qpoint.h:287
void freeMemory()
bool isEmpty() const
Returns true if the vector has size 0; otherwise returns false.
Definition: qvector.h:139
void setClipPath(const QPainterPath &path, Qt::ClipOperation op=Qt::ReplaceClip)
Enables clipping, and sets the clip path for the painter to the given path, with the clip operation...
Definition: qpainter.cpp:3365
QRectF translated(qreal dx, qreal dy) const
Returns a copy of the rectangle that is translated dx along the x axis and dy along the y axis...
Definition: qrect.h:740
int size() const
Returns the number of items in the vector.
Definition: qvector.h:137
bool isNull() const
Returns true if the rectangle is a null rectangle, otherwise returns false.
Definition: qrect.h:655
#define INT_MAX
QTextEngine * d
Definition: qtextlayout.h:193
QFixed leadingSpaceWidth(const QScriptLine &line)

◆ drawCursor() [1/2]

void QTextLayout::drawCursor ( QPainter painter,
const QPointF position,
int  cursorPosition 
) const

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Draws a text cursor with the current pen at the given position using the painter specified.

The corresponding position within the text is specified by cursorPosition.

Definition at line 1252 of file qtextlayout.cpp.

Referenced by QLineControl::draw(), QTextDocumentLayoutPrivate::drawBlock(), QTextDocumentLayoutPrivate::drawFrame(), and QPlainTextEdit::paintEvent().

1253 {
1254  drawCursor(p, pos, cursorPosition, 1);
1255 }
void drawCursor(QPainter *p, const QPointF &pos, int cursorPosition) const
This is an overloaded member function, provided for convenience. It differs from the above function o...

◆ drawCursor() [2/2]

void QTextLayout::drawCursor ( QPainter painter,
const QPointF position,
int  cursorPosition,
int  width 
) const

Draws a text cursor with the current pen and the specified width at the given position using the painter specified.

The corresponding position within the text is specified by cursorPosition.

Definition at line 1264 of file qtextlayout.cpp.

1265 {
1266  if (d->lines.isEmpty())
1267  return;
1268 
1269  if (!d->layoutData)
1270  d->itemize();
1271 
1272  QPointF position = pos + d->position;
1273 
1274  cursorPosition = qBound(0, cursorPosition, d->layoutData->string.length());
1275  int line = d->lineNumberForTextPosition(cursorPosition);
1276  if (line < 0)
1277  line = 0;
1278  if (line >= d->lines.size())
1279  return;
1280 
1281  QTextLine l(line, d);
1282  const QScriptLine &sl = d->lines[line];
1283 
1284  qreal x = position.x() + l.cursorToX(cursorPosition);
1285 
1286  int itm;
1287 
1288  if (d->visualCursorMovement()) {
1289  if (cursorPosition == sl.from + sl.length)
1290  cursorPosition--;
1291  itm = d->findItem(cursorPosition);
1292  } else
1293  itm = d->findItem(cursorPosition - 1);
1294 
1295  QFixed base = sl.base();
1296  QFixed descent = sl.descent;
1297  bool rightToLeft = d->isRightToLeft();
1298  if (itm >= 0) {
1299  const QScriptItem &si = d->layoutData->items.at(itm);
1300  if (si.ascent > 0)
1301  base = si.ascent;
1302  if (si.descent > 0)
1303  descent = si.descent;
1304  rightToLeft = si.analysis.bidiLevel % 2;
1305  }
1306  qreal y = position.y() + (sl.y + sl.base() - base).toReal();
1307  bool toggleAntialiasing = !(p->renderHints() & QPainter::Antialiasing)
1308  && (p->transform().type() > QTransform::TxTranslate);
1309  if (toggleAntialiasing)
1310  p->setRenderHint(QPainter::Antialiasing);
1311 #if defined(QT_MAC_USE_COCOA)
1312  // Always draw the cursor aligned to pixel boundary.
1313  x = qRound(x);
1314 #endif
1315  p->fillRect(QRectF(x, y, qreal(width), (base + descent + 1).toReal()), p->pen().brush());
1316  if (toggleAntialiasing)
1317  p->setRenderHint(QPainter::Antialiasing, false);
1318  if (d->layoutData->hasBidi) {
1319  const int arrow_extent = 4;
1320  int sign = rightToLeft ? -1 : 1;
1321  p->drawLine(QLineF(x, y, x + (sign * arrow_extent/2), y + arrow_extent/2));
1322  p->drawLine(QLineF(x, y+arrow_extent, x + (sign * arrow_extent/2), y + arrow_extent/2));
1323  }
1324  return;
1325 }
bool isRightToLeft() const
double qreal
Definition: qglobal.h:1193
int lineNumberForTextPosition(int pos)
int length() const
Returns the number of characters in this string.
Definition: qstring.h:696
The QPointF class defines a point in the plane using floating point precision.
Definition: qpoint.h:214
int findItem(int strPos) const
The QTextLine class represents a line of text inside a QTextLayout.
Definition: qtextlayout.h:197
QScriptItemArray items
LayoutData * layoutData
static const uint base
Definition: qurl.cpp:268
qreal x() const
Returns the x-coordinate of this point.
Definition: qpoint.h:282
static int sign(int x)
The QLineF class provides a two-dimensional vector using floating point precision.
Definition: qline.h:212
The QRectF class defines a rectangle in the plane using floating point precision. ...
Definition: qrect.h:511
unsigned short bidiLevel
QScriptLineArray lines
void itemize() const
const T & at(int i) const
Returns the item at index position i in the vector.
Definition: qvector.h:350
QFixed descent
QFixed descent
QPointF position
Q_DECL_CONSTEXPR const T & qBound(const T &min, const T &val, const T &max)
Definition: qglobal.h:1219
QFactoryLoader * l
signed int length
qreal y() const
Returns the y-coordinate of this point.
Definition: qpoint.h:287
QFixed base() const
bool isEmpty() const
Returns true if the vector has size 0; otherwise returns false.
Definition: qvector.h:139
int size() const
Returns the number of items in the vector.
Definition: qvector.h:137
bool visualCursorMovement() const
QTextEngine * d
Definition: qtextlayout.h:193
Q_DECL_CONSTEXPR int qRound(qreal d)
Definition: qglobal.h:1203
static qreal toReal(Register *reg, int type, bool *ok=0)
QScriptAnalysis analysis

◆ endLayout()

void QTextLayout::endLayout ( )

Ends the layout process.

See also
beginLayout()

Definition at line 664 of file qtextlayout.cpp.

Referenced by QPainterPath::addText(), QCommandLinkButtonPrivate::descriptionHeight(), QItemDelegatePrivate::doTextLayout(), QSvgText::draw(), QTextDocumentLayoutPrivate::drawListItem(), QRawFont::fromFont(), QPlainTextDocumentLayout::layoutBlock(), QTextDocumentLayoutPrivate::layoutBlock(), QStaticTextPrivate::paintText(), qt_format_text(), setupTextLayout(), QLineControl::updateDisplayText(), QCommonStylePrivate::viewItemSize(), and viewItemTextLayout().

665 {
666 #ifndef QT_NO_DEBUG
668  qWarning("QTextLayout::endLayout: Called without beginLayout()");
669  return;
670  }
671 #endif
672  int l = d->lines.size();
673  if (l && d->lines.at(l-1).length < 0) {
675  }
677  if (!d->cacheGlyphs)
678  d->freeMemory();
679 }
The QTextLine class represents a line of text inside a QTextLayout.
Definition: qtextlayout.h:197
LayoutData * layoutData
void setNumColumns(int columns)
Lays out the line.
Q_CORE_EXPORT void qWarning(const char *,...)
QScriptLineArray lines
const T & at(int i) const
Returns the item at index position i in the vector.
Definition: qvector.h:350
QFactoryLoader * l
signed int length
void freeMemory()
int size() const
Returns the number of items in the vector.
Definition: qvector.h:137
#define INT_MAX
QTextEngine * d
Definition: qtextlayout.h:193

◆ engine()

QTextEngine * QTextLayout::engine ( ) const
inline
Warning
This function is not part of the public interface.

Returns the text engine used to render the text layout.

Definition at line 180 of file qtextlayout.h.

Referenced by QPainterPath::addText(), QTextBlockData::invalidate(), QTextCursorPrivate::movePosition(), and qt_format_text().

180 { return d; }
QTextEngine * d
Definition: qtextlayout.h:193

◆ font()

QFont QTextLayout::font ( ) const

Returns the current font that is used for the layout, or a default font if none is set.

See also
setFont()

Definition at line 412 of file qtextlayout.cpp.

Referenced by QDeclarativeTextLayout::prepare(), and QTextControlPrivate::rectForPosition().

413 {
414  return d->font();
415 }
QFont font(const QScriptItem &si) const
QTextEngine * d
Definition: qtextlayout.h:193

◆ glyphRuns()

QList< QGlyphRun > QTextLayout::glyphRuns ( ) const

Returns the glyph indexes and positions for all glyphs in this QTextLayout.

This is an expensive function, and should not be called in a time sensitive context.

Since
4.8
See also
draw(), QPainter::drawGlyphRun()

Definition at line 1059 of file qtextlayout.cpp.

Referenced by QRawFont::fromFont().

1060 {
1061  QList<QGlyphRun> glyphs;
1062  for (int i=0; i<d->lines.size(); ++i)
1063  glyphs += QTextLine(i, d).glyphs(-1, -1);
1064 
1065  return glyphs;
1066 }
QList< QGlyphRun > glyphs(int from, int length) const
Returns the glyph indexes and positions for all glyphs in this QTextLine which reside in QScriptItems...
The QTextLine class represents a line of text inside a QTextLayout.
Definition: qtextlayout.h:197
QScriptLineArray lines
int size() const
Returns the number of items in the vector.
Definition: qvector.h:137
QTextEngine * d
Definition: qtextlayout.h:193
The QList class is a template class that provides lists.
Definition: qdatastream.h:62

◆ isValidCursorPosition()

bool QTextLayout::isValidCursorPosition ( int  pos) const

/ Returns true if position pos is a valid cursor position.

In a Unicode context some positions in the text are not valid cursor positions, because the position is inside a Unicode surrogate or a grapheme cluster.

A grapheme cluster is a sequence of two or more Unicode characters that form one indivisible entity on the screen. For example the latin character `' can be represented in Unicode by two characters, `A' (0x41), and the combining diaresis (0x308). A text cursor can only validly be positioned before or after these two characters, never between them since that wouldn't make sense. In indic languages every syllable forms a grapheme cluster.

Definition at line 818 of file qtextlayout.cpp.

819 {
820  const HB_CharAttributes *attributes = d->attributes();
821  if (!attributes || pos < 0 || pos > (int)d->layoutData->string.length())
822  return false;
823  return attributes[pos].charStop;
824 }
int length() const
Returns the number of characters in this string.
Definition: qstring.h:696
LayoutData * layoutData
const HB_CharAttributes * attributes() const
QTextEngine * d
Definition: qtextlayout.h:193

◆ leftCursorPosition()

int QTextLayout::leftCursorPosition ( int  oldPos) const

Returns the cursor position to the left of oldPos, next to it.

Since
4.8

The position is dependent on the visual position of characters, after bi-directional reordering.

See also
rightCursorPosition(), previousCursorPosition()

Definition at line 796 of file qtextlayout.cpp.

Referenced by QTextDocumentPrivate::leftCursorPosition().

797 {
798  int newPos = d->positionAfterVisualMovement(oldPos, QTextCursor::Left);
799 // qDebug("%d -> %d", oldPos, newPos);
800  return newPos;
801 }
int positionAfterVisualMovement(int oldPos, QTextCursor::MoveOperation op)
QTextEngine * d
Definition: qtextlayout.h:193

◆ lineAt()

QTextLine QTextLayout::lineAt ( int  i) const

◆ lineCount()

int QTextLayout::lineCount ( ) const

◆ lineForTextPosition()

QTextLine QTextLayout::lineForTextPosition ( int  pos) const

Returns the line that contains the cursor position specified by pos.

See also
isValidCursorPosition(), lineAt()

Definition at line 899 of file qtextlayout.cpp.

Referenced by QAccessibleTextWidget::characterRect(), QTextCursor::columnNumber(), currentTextLine(), QTextDocumentLayoutPrivate::drawBlock(), QTextCursorPrivate::movePosition(), QPlainTextEdit::paintEvent(), QTextControlPrivate::rectForPosition(), QTextControl::selectionRect(), and QTextCursorPrivate::setX().

900 {
901  int lineNum = d->lineNumberForTextPosition(pos);
902  return lineNum >= 0 ? lineAt(lineNum) : QTextLine();
903 }
int lineNumberForTextPosition(int pos)
The QTextLine class represents a line of text inside a QTextLayout.
Definition: qtextlayout.h:197
QTextLine lineAt(int i) const
Returns the {i}-th line of text in this text layout.
QTextEngine * d
Definition: qtextlayout.h:193

◆ maximumWidth()

qreal QTextLayout::maximumWidth ( ) const

The maximum width the layout could expand to; this is essentially the width of the entire text.

Warning
This function only returns a valid value after the layout has been done.
See also
minimumWidth()

Definition at line 978 of file qtextlayout.cpp.

Referenced by QTextDocumentLayoutPrivate::layoutBlock().

979 {
980  return d->maxWidth.toReal();
981 }
QFixed maxWidth
qreal toReal() const
Definition: qfixed_p.h:77
QTextEngine * d
Definition: qtextlayout.h:193

◆ minimumWidth()

qreal QTextLayout::minimumWidth ( ) const

The minimum width the layout needs.

This is the width of the layout's smallest non-breakable substring.

Warning
This function only returns a valid value after the layout has been done.
See also
maximumWidth()

Definition at line 964 of file qtextlayout.cpp.

Referenced by QTextDocumentLayoutPrivate::layoutBlock().

965 {
966  return d->minWidth.toReal();
967 }
qreal toReal() const
Definition: qfixed_p.h:77
QFixed minWidth
QTextEngine * d
Definition: qtextlayout.h:193

◆ nextCursorPosition()

int QTextLayout::nextCursorPosition ( int  oldPos,
CursorMode  mode = SkipCharacters 
) const

Returns the next valid cursor position after oldPos that respects the given cursor mode.

Returns value of oldPos, if oldPos is not a valid cursor position.

See also
isValidCursorPosition(), previousCursorPosition()

Definition at line 702 of file qtextlayout.cpp.

Referenced by QLineControl::del(), QTextDocumentPrivate::nextCursorPosition(), and QLineControl::selectWordAtPos().

703 {
704  const HB_CharAttributes *attributes = d->attributes();
705  int len = d->block.isValid() ? d->block.length() - 1
706  : d->layoutData->string.length();
707  Q_ASSERT(len <= d->layoutData->string.length());
708  if (!attributes || oldPos < 0 || oldPos >= len)
709  return oldPos;
710 
711  if (mode == SkipCharacters) {
712  oldPos++;
713  while (oldPos < len && !attributes[oldPos].charStop)
714  oldPos++;
715  } else {
716  if (oldPos < len && d->atWordSeparator(oldPos)) {
717  oldPos++;
718  while (oldPos < len && d->atWordSeparator(oldPos))
719  oldPos++;
720  } else {
721  while (oldPos < len && !d->atSpace(oldPos) && !d->atWordSeparator(oldPos))
722  oldPos++;
723  }
724  while (oldPos < len && d->atSpace(oldPos))
725  oldPos++;
726  }
727 
728  return oldPos;
729 }
bool atWordSeparator(int position) const
int length() const
Returns the number of characters in this string.
Definition: qstring.h:696
LayoutData * layoutData
#define Q_ASSERT(cond)
Definition: qglobal.h:1823
const HB_CharAttributes * attributes() const
int length() const
Returns the length of the block in characters.
QTextBlock block
bool isValid() const
Returns true if this text block is valid; otherwise returns false.
Definition: qtextobject.h:208
QTextEngine * d
Definition: qtextlayout.h:193

◆ position()

QPointF QTextLayout::position ( ) const

The global position of the layout.

Since
4.2

This is independent of the bounding rectangle and of the layout process.

See also
setPosition()

Definition at line 916 of file qtextlayout.cpp.

Referenced by QTextDocumentLayout::blockBoundingRect(), QAccessibleTextWidget::characterRect(), QTextDocumentLayoutPrivate::drawBlock(), QTextDocumentLayoutPrivate::drawListItem(), flowPosition(), QTextDocumentLayoutPrivate::hitTest(), QTextDocumentLayoutPrivate::layoutBlock(), and QTextDocumentLayoutPrivate::layoutFlow().

917 {
918  return d->position;
919 }
QPointF position
QTextEngine * d
Definition: qtextlayout.h:193

◆ preeditAreaPosition()

int QTextLayout::preeditAreaPosition ( ) const

Returns the position of the area in the text layout that will be processed before editing occurs.

See also
preeditAreaText()

Definition at line 500 of file qtextlayout.cpp.

Referenced by QSyntaxHighlighterPrivate::applyFormatChanges(), QTextDocumentLayoutPrivate::drawBlock(), QPlainTextEdit::paintEvent(), and QTextControlPrivate::rectForPosition().

501 {
502  return d->specialData ? d->specialData->preeditPosition : -1;
503 }
SpecialData * specialData
QTextEngine * d
Definition: qtextlayout.h:193

◆ preeditAreaText()

QString QTextLayout::preeditAreaText ( ) const

Returns the text that is inserted in the layout before editing occurs.

See also
preeditAreaPosition()

Definition at line 510 of file qtextlayout.cpp.

Referenced by QSyntaxHighlighterPrivate::applyFormatChanges(), QTextDocumentLayoutPrivate::drawBlock(), QTextDocumentLayout::hitTest(), QPlainTextEdit::paintEvent(), QDeclarativeTextEdit::positionAt(), QTextControlPrivate::rectForPosition(), and QTextControlPrivate::sendMouseEventToInputContext().

511 {
512  return d->specialData ? d->specialData->preeditText : QString();
513 }
SpecialData * specialData
The QString class provides a Unicode character string.
Definition: qstring.h:83
QTextEngine * d
Definition: qtextlayout.h:193

◆ previousCursorPosition()

int QTextLayout::previousCursorPosition ( int  oldPos,
CursorMode  mode = SkipCharacters 
) const

Returns the first valid cursor position before oldPos that respects the given cursor mode.

Returns value of oldPos, if oldPos is not a valid cursor position.

See also
isValidCursorPosition(), nextCursorPosition()

Definition at line 738 of file qtextlayout.cpp.

Referenced by QTextDocumentPrivate::previousCursorPosition(), and QLineControl::selectWordAtPos().

739 {
740  const HB_CharAttributes *attributes = d->attributes();
741  if (!attributes || oldPos <= 0 || oldPos > d->layoutData->string.length())
742  return oldPos;
743 
744  if (mode == SkipCharacters) {
745  oldPos--;
746  while (oldPos && !attributes[oldPos].charStop)
747  oldPos--;
748  } else {
749  while (oldPos && d->atSpace(oldPos-1))
750  oldPos--;
751 
752  if (oldPos && d->atWordSeparator(oldPos-1)) {
753  oldPos--;
754  while (oldPos && d->atWordSeparator(oldPos-1))
755  oldPos--;
756  } else {
757  while (oldPos && !d->atSpace(oldPos-1) && !d->atWordSeparator(oldPos-1))
758  oldPos--;
759  }
760  }
761 
762  return oldPos;
763 }
bool atWordSeparator(int position) const
int length() const
Returns the number of characters in this string.
Definition: qstring.h:696
LayoutData * layoutData
const HB_CharAttributes * attributes() const
bool atSpace(int position) const
QTextEngine * d
Definition: qtextlayout.h:193

◆ rightCursorPosition()

int QTextLayout::rightCursorPosition ( int  oldPos) const

Returns the cursor position to the right of oldPos, next to it.

Since
4.8

The position is dependent on the visual position of characters, after bi-directional reordering.

See also
leftCursorPosition(), nextCursorPosition()

Definition at line 777 of file qtextlayout.cpp.

Referenced by QTextDocumentPrivate::rightCursorPosition().

778 {
779  int newPos = d->positionAfterVisualMovement(oldPos, QTextCursor::Right);
780 // qDebug("%d -> %d", oldPos, newPos);
781  return newPos;
782 }
int positionAfterVisualMovement(int oldPos, QTextCursor::MoveOperation op)
QTextEngine * d
Definition: qtextlayout.h:193

◆ setAdditionalFormats()

void QTextLayout::setAdditionalFormats ( const QList< FormatRange > &  formatList)

Sets the additional formats supported by the text layout to formatList.

See also
additionalFormats(), clearAdditionalFormats()

Definition at line 521 of file qtextlayout.cpp.

Referenced by QSyntaxHighlighterPrivate::applyFormatChanges(), QSvgText::draw(), QTextControlPrivate::inputMethodEvent(), QGraphicsSimpleTextItem::paint(), and QLineControl::processInputMethodEvent().

522 {
523  if (formatList.isEmpty()) {
524  if (!d->specialData)
525  return;
526  if (d->specialData->preeditText.isEmpty()) {
527  delete d->specialData;
528  d->specialData = 0;
529  } else {
530  d->specialData->addFormats = formatList;
532  }
533  } else {
534  if (!d->specialData) {
537  }
538  d->specialData->addFormats = formatList;
540  }
541  if (d->block.docHandle())
544 }
SpecialData * specialData
QList< QTextLayout::FormatRange > addFormats
bool isEmpty() const
Returns true if the list contains no items; otherwise returns false.
Definition: qlist.h:152
void documentChange(int from, int length)
int position() const
Returns the index of the block&#39;s first character within the document.
void clear()
Removes all the elements from the vector and releases the memory used by the vector.
Definition: qvector.h:347
bool isEmpty() const
Returns true if the string has no characters; otherwise returns false.
Definition: qstring.h:704
void resetFontEngineCache()
int length() const
Returns the length of the block in characters.
void indexAdditionalFormats()
QTextBlock block
QVector< int > addFormatIndices
QTextDocumentPrivate * docHandle() const
Definition: qtextobject.h:283
QTextEngine * d
Definition: qtextlayout.h:193

◆ setCacheEnabled()

void QTextLayout::setCacheEnabled ( bool  enable)

Enables caching of the complete layout information if enable is true; otherwise disables layout caching.

Usually QTextLayout throws most of the layouting information away after a call to endLayout() to reduce memory consumption. If you however want to draw the laid out text directly afterwards enabling caching might speed up drawing significantly.

See also
cacheEnabled()

Definition at line 590 of file qtextlayout.cpp.

Referenced by QPainterPath::addText(), QTextDocumentLayoutPrivate::drawListItem(), qt_format_text(), and setupTextLayout().

591 {
592  d->cacheGlyphs = enable;
593 }
QTextEngine * d
Definition: qtextlayout.h:193

◆ setCursorMoveStyle()

void QTextLayout::setCursorMoveStyle ( Qt::CursorMoveStyle  style)

Set the cursor movement style.

Since
4.8

If the QTextLayout is backed by a document, you can ignore this and use the option in QTextDocument, this option is for widgets like QLineEdit or custom widgets without a QTextDocument. Default value is Qt::LogicalMoveStyle.

See also
cursorMoveStyle()

Definition at line 619 of file qtextlayout.cpp.

620 {
621  d->visualMovement = style == Qt::VisualMoveStyle ? true : false;
622 }
uint visualMovement
QTextEngine * d
Definition: qtextlayout.h:193

◆ setFlags()

void QTextLayout::setFlags ( int  flags)
Warning
This function is not part of the public interface.

Definition at line 987 of file qtextlayout.cpp.

988 {
989  if (flags & Qt::TextJustificationForced) {
991  d->forceJustification = true;
992  }
993 
995  d->ignoreBidi = true;
997  }
998 }
uint forceJustification
void setAlignment(Qt::Alignment alignment)
Sets the option&#39;s text alignment to the specified alignment.
Definition: qtextoption.h:148
void setTextDirection(Qt::LayoutDirection aDirection)
Sets the direction of the text layout defined by the option to the given direction.
Definition: qtextoption.h:99
QTextOption option
QTextEngine * d
Definition: qtextlayout.h:193

◆ setFont()

void QTextLayout::setFont ( const QFont font)

Sets the layout's font to the given font.

The layout is invalidated and must be laid out again.

See also
font()

Definition at line 400 of file qtextlayout.cpp.

Referenced by QCommandLinkButtonPrivate::descriptionHeight(), QStaticTextPrivate::paintText(), QCommonStylePrivate::viewItemDrawText(), and QCommonStylePrivate::viewItemSize().

401 {
402  d->fnt = font;
404 }
QFont font() const
Returns the current font that is used for the layout, or a default font if none is set...
void resetFontEngineCache()
QTextEngine * d
Definition: qtextlayout.h:193

◆ setPosition()

void QTextLayout::setPosition ( const QPointF p)

Moves the text layout to point p.

See also
position()

Definition at line 926 of file qtextlayout.cpp.

Referenced by QTextDocumentLayoutPrivate::drawListItem(), QTextDocumentLayoutPrivate::layoutBlock(), and QTextDocumentLayoutPrivate::layoutFlow().

927 {
928  d->position = p;
929 }
QPointF position
QTextEngine * d
Definition: qtextlayout.h:193

◆ setPreeditArea()

void QTextLayout::setPreeditArea ( int  position,
const QString text 
)

Sets the position and text of the area in the layout that is processed before editing occurs.

See also
preeditAreaPosition(), preeditAreaText()

Definition at line 470 of file qtextlayout.cpp.

Referenced by QTextControlPrivate::inputMethodEvent().

471 {
472  if (text.isEmpty()) {
473  if (!d->specialData)
474  return;
475  if (d->specialData->addFormats.isEmpty()) {
476  delete d->specialData;
477  d->specialData = 0;
478  } else {
481  }
482  } else {
483  if (!d->specialData)
487  }
488  d->invalidate();
489  d->clearLineData();
490  if (d->block.docHandle())
492 }
void clearLineData()
QPointF position() const
The global position of the layout.
SpecialData * specialData
The QString class provides a Unicode character string.
Definition: qstring.h:83
QList< QTextLayout::FormatRange > addFormats
bool isEmpty() const
Returns true if the list contains no items; otherwise returns false.
Definition: qlist.h:152
void documentChange(int from, int length)
int position() const
Returns the index of the block&#39;s first character within the document.
QString text() const
Returns the layout&#39;s text.
bool isEmpty() const
Returns true if the string has no characters; otherwise returns false.
Definition: qstring.h:704
int length() const
Returns the length of the block in characters.
QTextBlock block
void invalidate()
QTextDocumentPrivate * docHandle() const
Definition: qtextobject.h:283
QTextEngine * d
Definition: qtextlayout.h:193

◆ setText()

void QTextLayout::setText ( const QString string)

Sets the layout's text to the given string.

The layout is invalidated and must be laid out again.

Notice that when using this QTextLayout as part of a QTextDocument this method will have no effect.

See also
text()

Definition at line 426 of file qtextlayout.cpp.

Referenced by QStaticTextPrivate::paintText(), QLineControl::updateDisplayText(), QCommonStylePrivate::viewItemDrawText(), and QCommonStylePrivate::viewItemSize().

427 {
428  d->invalidate();
429  d->clearLineData();
430  d->text = string;
431 }
void clearLineData()
void invalidate()
QString text
QTextEngine * d
Definition: qtextlayout.h:193

◆ setTextOption()

void QTextLayout::setTextOption ( const QTextOption option)

◆ text()

QString QTextLayout::text ( ) const

Returns the layout's text.

See also
setText()

Definition at line 438 of file qtextlayout.cpp.

Referenced by QGraphicsSimpleTextItem::paint(), QLineControl::updateDisplayText(), and QCommonStylePrivate::viewItemDrawText().

439 {
440  return d->text;
441 }
QString text
QTextEngine * d
Definition: qtextlayout.h:193

◆ textOption()

QTextOption QTextLayout::textOption ( ) const

Returns the current text option used to control the layout process.

See also
setTextOption()

Definition at line 459 of file qtextlayout.cpp.

Referenced by QSvgText::draw(), and QTextDocumentLayoutPrivate::layoutFlow().

460 {
461  return d->option;
462 }
QTextOption option
QTextEngine * d
Definition: qtextlayout.h:193

Friends and Related Functions

◆ QGraphicsSimpleTextItem

Definition at line 189 of file qtextlayout.h.

◆ QGraphicsSimpleTextItemPrivate

Definition at line 188 of file qtextlayout.h.

◆ QPainter

friend class QPainter
friend

Definition at line 186 of file qtextlayout.h.

◆ QPSPrinter

friend class QPSPrinter
friend

Definition at line 187 of file qtextlayout.h.

◆ qt_format_text

void qt_format_text ( const QFont font,
const QRectF _r,
int  tf,
const QTextOption opt,
const QString str,
QRectF brect,
int  tabstops,
int *  tabarray,
int  tabarraylen,
QPainter painter 
)
friend

Definition at line 8458 of file qpainter.cpp.

8462 {
8463 
8464  Q_ASSERT( !((tf & ~Qt::TextDontPrint)!=0 && option!=0) ); // we either have an option or flags
8465 
8466  if (option) {
8467  tf |= option->alignment();
8468  if (option->wrapMode() != QTextOption::NoWrap)
8469  tf |= Qt::TextWordWrap;
8470 
8471  if (option->flags() & QTextOption::IncludeTrailingSpaces)
8473 
8474  if (option->tabStop() >= 0 || !option->tabArray().isEmpty())
8475  tf |= Qt::TextExpandTabs;
8476  }
8477 
8478  // we need to copy r here to protect against the case (&r == brect).
8479  QRectF r(_r);
8480 
8481  bool dontclip = (tf & Qt::TextDontClip);
8482  bool wordwrap = (tf & Qt::TextWordWrap) || (tf & Qt::TextWrapAnywhere);
8483  bool singleline = (tf & Qt::TextSingleLine);
8484  bool showmnemonic = (tf & Qt::TextShowMnemonic);
8485  bool hidemnmemonic = (tf & Qt::TextHideMnemonic);
8486 
8488  if (tf & Qt::TextForceLeftToRight)
8489  layout_direction = Qt::LeftToRight;
8490  else if (tf & Qt::TextForceRightToLeft)
8491  layout_direction = Qt::RightToLeft;
8492  else if (option)
8493  layout_direction = option->textDirection();
8494  else if (painter)
8495  layout_direction = painter->layoutDirection();
8496  else
8497  layout_direction = Qt::LeftToRight;
8498 
8499  tf = QStyle::visualAlignment(layout_direction, QFlag(tf));
8500 
8501  bool isRightToLeft = layout_direction == Qt::RightToLeft;
8502  bool expandtabs = ((tf & Qt::TextExpandTabs) &&
8503  (((tf & Qt::AlignLeft) && !isRightToLeft) ||
8504  ((tf & Qt::AlignRight) && isRightToLeft)));
8505 
8506  if (!painter)
8507  tf |= Qt::TextDontPrint;
8508 
8509  uint maxUnderlines = 0;
8510  int numUnderlines = 0;
8511  QVarLengthArray<int, 32> underlinePositions(1);
8512 
8513  QFontMetricsF fm(fnt);
8514  QString text = str;
8515  int offset = 0;
8516 start_lengthVariant:
8517  bool hasMoreLengthVariants = false;
8518  // compatible behaviour to the old implementation. Replace
8519  // tabs by spaces
8520  int old_offset = offset;
8521  for (; offset < text.length(); offset++) {
8522  QChar chr = text.at(offset);
8523  if (chr == QLatin1Char('\r') || (singleline && chr == QLatin1Char('\n'))) {
8524  text[offset] = QLatin1Char(' ');
8525  } else if (chr == QLatin1Char('\n')) {
8526  text[offset] = QChar::LineSeparator;
8527  } else if (chr == QLatin1Char('&')) {
8528  ++maxUnderlines;
8529  } else if (chr == QLatin1Char('\t')) {
8530  if (!expandtabs) {
8531  text[offset] = QLatin1Char(' ');
8532  } else if (!tabarraylen && !tabstops) {
8533  tabstops = qRound(fm.width(QLatin1Char('x'))*8);
8534  }
8535  } else if (chr == QChar(ushort(0x9c))) {
8536  // string with multiple length variants
8537  hasMoreLengthVariants = true;
8538  break;
8539  }
8540  }
8541 
8542  int length = offset - old_offset;
8543  if ((hidemnmemonic || showmnemonic) && maxUnderlines > 0) {
8544  underlinePositions.resize(maxUnderlines + 1);
8545 
8546  QChar *cout = text.data() + old_offset;
8547  QChar *cin = cout;
8548  int l = length;
8549  while (l) {
8550  if (*cin == QLatin1Char('&')) {
8551  ++cin;
8552  --length;
8553  --l;
8554  if (!l)
8555  break;
8556  if (*cin != QLatin1Char('&') && !hidemnmemonic)
8557  underlinePositions[numUnderlines++] = cout - text.data() - old_offset;
8558  }
8559  *cout = *cin;
8560  ++cout;
8561  ++cin;
8562  --l;
8563  }
8564  }
8565 
8566  // no need to do extra work for underlines if we don't paint
8567  if (tf & Qt::TextDontPrint)
8568  numUnderlines = 0;
8569 
8570  underlinePositions[numUnderlines] = -1;
8571  qreal height = 0;
8572  qreal width = 0;
8573 
8574  QString finalText = text.mid(old_offset, length);
8575  QStackTextEngine engine(finalText, fnt);
8576  if (option) {
8577  engine.option = *option;
8578  }
8579 
8580  if (engine.option.tabStop() < 0 && tabstops > 0)
8581  engine.option.setTabStop(tabstops);
8582 
8583  if (engine.option.tabs().isEmpty() && ta) {
8584  QList<qreal> tabs;
8585  for (int i = 0; i < tabarraylen; i++)
8586  tabs.append(qreal(ta[i]));
8587  engine.option.setTabArray(tabs);
8588  }
8589 
8590  engine.option.setTextDirection(layout_direction);
8591  if (tf & Qt::AlignJustify)
8592  engine.option.setAlignment(Qt::AlignJustify);
8593  else
8594  engine.option.setAlignment(Qt::AlignLeft); // do not do alignment twice
8595 
8596  if (!option && (tf & Qt::TextWrapAnywhere))
8598 
8599  if (tf & Qt::TextJustificationForced)
8600  engine.forceJustification = true;
8601  QTextLayout textLayout(&engine);
8602  textLayout.setCacheEnabled(true);
8603  textLayout.engine()->underlinePositions = underlinePositions.data();
8604 
8605  if (finalText.isEmpty()) {
8606  height = fm.height();
8607  width = 0;
8608  tf |= Qt::TextDontPrint;
8609  } else {
8610  qreal lineWidth = 0x01000000;
8611  if (wordwrap || (tf & Qt::TextJustificationForced))
8612  lineWidth = qMax<qreal>(0, r.width());
8613  if(!wordwrap)
8615  textLayout.engine()->ignoreBidi = bool(tf & Qt::TextDontPrint);
8616  textLayout.beginLayout();
8617 
8618  qreal leading = fm.leading();
8619  height = -leading;
8620 
8621  while (1) {
8622  QTextLine l = textLayout.createLine();
8623  if (!l.isValid())
8624  break;
8625 
8626  l.setLineWidth(lineWidth);
8627  height += leading;
8628  l.setPosition(QPointF(0., height));
8629  height += l.height();
8630  width = qMax(width, l.naturalTextWidth());
8631  if (!dontclip && !brect && height >= r.height())
8632  break;
8633  }
8634  textLayout.endLayout();
8635  }
8636 
8637  qreal yoff = 0;
8638  qreal xoff = 0;
8639  if (tf & Qt::AlignBottom) {
8640  yoff = r.height() - height;
8641  } else if (tf & Qt::AlignVCenter) {
8642  yoff = (r.height() - height)/2;
8643  if (painter) {
8645  if (type <= QTransform::TxScale) {
8646  // do the rounding manually to work around inconsistencies
8647  // in the paint engines when drawing on floating point offsets
8648  const qreal scale = painter->transform().m22();
8649  if (scale != 0)
8650  yoff = -qRound(-yoff * scale) / scale;
8651  }
8652  }
8653  }
8654  if (tf & Qt::AlignRight) {
8655  xoff = r.width() - width;
8656  } else if (tf & Qt::AlignHCenter) {
8657  xoff = (r.width() - width)/2;
8658  if (painter) {
8659  QTransform::TransformationType type = painter->transform().type();
8660  if (type <= QTransform::TxScale) {
8661  // do the rounding manually to work around inconsistencies
8662  // in the paint engines when drawing on floating point offsets
8663  const qreal scale = painter->transform().m11();
8664  if (scale != 0)
8665  xoff = qRound(xoff * scale) / scale;
8666  }
8667  }
8668  }
8669  QRectF bounds = QRectF(r.x() + xoff, r.y() + yoff, width, height);
8670 
8671  if (hasMoreLengthVariants && !(tf & Qt::TextLongestVariant) && !r.contains(bounds)) {
8672  offset++;
8673  goto start_lengthVariant;
8674  }
8675  if (brect)
8676  *brect = bounds;
8677 
8678  if (!(tf & Qt::TextDontPrint)) {
8679  bool restore = false;
8680  if (!dontclip && !r.contains(bounds)) {
8681  restore = true;
8682  painter->save();
8683  painter->setClipRect(r, Qt::IntersectClip);
8684  }
8685 
8686  for (int i = 0; i < textLayout.lineCount(); i++) {
8687  QTextLine line = textLayout.lineAt(i);
8688 
8689  qreal advance = line.horizontalAdvance();
8690  xoff = 0;
8691  if (tf & Qt::AlignRight) {
8692  QTextEngine *eng = textLayout.engine();
8693  xoff = r.width() - advance -
8694  eng->leadingSpaceWidth(eng->lines[line.lineNumber()]).toReal();
8695  }
8696  else if (tf & Qt::AlignHCenter)
8697  xoff = (r.width() - advance) / 2;
8698 
8699  line.draw(painter, QPointF(r.x() + xoff, r.y() + yoff));
8700  }
8701 
8702  if (restore) {
8703  painter->restore();
8704  }
8705  }
8706 }
QTextEngine * engine() const
Definition: qtextlayout.h:180
int type
Definition: qmetatype.cpp:239
double qreal
Definition: qglobal.h:1193
const QTransform & transform() const
Returns the world transformation matrix.
Definition: qpainter.cpp:9558
qreal horizontalAdvance() const
Returns the horizontal advance of the text.
void setPosition(const QPointF &pos)
Moves the line to position pos.
const QChar at(int i) const
Returns the character at the given index position in the string.
Definition: qstring.h:698
The QFlag class is a helper data type for QFlags.
Definition: qglobal.h:2289
void setClipRect(const QRectF &, Qt::ClipOperation op=Qt::ReplaceClip)
Enables clipping, and sets the clip region to the given rectangle using the given clip operation...
Definition: qpainter.cpp:2801
int length() const
Returns the number of characters in this string.
Definition: qstring.h:696
The QPointF class defines a point in the plane using floating point precision.
Definition: qpoint.h:214
The QTextLine class represents a line of text inside a QTextLayout.
Definition: qtextlayout.h:197
void restore()
Restores the current painter state (pops a saved state off the stack).
Definition: qpainter.cpp:1620
qreal m22() const
Returns the vertical scaling factor.
Definition: qtransform.h:253
void setLineWidth(qreal width)
Lays out the line with the given width.
The QString class provides a Unicode character string.
Definition: qstring.h:83
#define Q_ASSERT(cond)
Definition: qglobal.h:1823
TransformationType type() const
Returns the transformation type of this matrix.
uint forceJustification
bool isValid() const
Returns true if this text line is valid; otherwise returns false.
Definition: qtextlayout.h:201
The QChar class provides a 16-bit Unicode character.
Definition: qchar.h:72
QChar * data()
Returns a pointer to the data stored in the QString.
Definition: qstring.h:710
qreal tabStop() const
Returns the distance in device units between tab stops.
Definition: qtextoption.h:124
void save()
Saves the current painter state (pushes the state onto a stack).
Definition: qpainter.cpp:1590
Q_DECL_CONSTEXPR const T & qMax(const T &a, const T &b)
Definition: qglobal.h:1217
void setAlignment(Qt::Alignment alignment)
Sets the option&#39;s text alignment to the specified alignment.
Definition: qtextoption.h:148
void append(const T &t)
Inserts value at the end of the list.
Definition: qlist.h:507
TransformationType
Definition: qtransform.h:68
QString text() const
Returns the layout&#39;s text.
The QRectF class defines a rectangle in the plane using floating point precision. ...
Definition: qrect.h:511
bool isEmpty() const
Returns true if the string has no characters; otherwise returns false.
Definition: qstring.h:704
static Qt::LayoutDirection layout_direction
qreal height() const
Returns the height of the rectangle.
Definition: qrect.h:710
int lineNumber() const
Returns the position of the line in the text engine.
Definition: qtextlayout.h:243
LayoutDirection
Definition: qnamespace.h:1580
unsigned int uint
Definition: qglobal.h:996
void setTextDirection(Qt::LayoutDirection aDirection)
Sets the direction of the text layout defined by the option to the given direction.
Definition: qtextoption.h:99
QScriptLineArray lines
QTextOption option
QList< Tab > tabs() const
Returns a list of tab positions defined for the text layout.
Qt::LayoutDirection layoutDirection() const
Returns the layout direction used by the painter when drawing text.
Definition: qpainter.cpp:8729
QString mid(int position, int n=-1) const Q_REQUIRED_RESULT
Returns a string that contains n characters of this string, starting at the specified position index...
Definition: qstring.cpp:3706
void setTabArray(QList< qreal > tabStops)
Sets the tab positions for the text layout to those specified by tabStops.
The QTextLayout class is used to lay out and render text.
Definition: qtextlayout.h:105
static Qt::Alignment visualAlignment(Qt::LayoutDirection direction, Qt::Alignment alignment)
Transforms an alignment of Qt::AlignLeft or Qt::AlignRight without Qt::AlignAbsolute into Qt::AlignLe...
Definition: qstyle.cpp:2149
unsigned short ushort
Definition: qglobal.h:995
qreal naturalTextWidth() const
Returns the width of the line that is occupied by text.
QFactoryLoader * l
void setWrapMode(WrapMode wrap)
Sets the option&#39;s text wrap mode to the given mode.
Definition: qtextoption.h:109
The QFontMetricsF class provides font metrics information.
Definition: qfontmetrics.h:145
The QLatin1Char class provides an 8-bit ASCII/Latin-1 character.
Definition: qchar.h:55
void draw(QPainter *p, const QPointF &point, const QTextLayout::FormatRange *selection=0) const
Draws a line on the given painter at the specified position.
qreal height() const
Returns the line&#39;s height.
Q_DECL_CONSTEXPR int qRound(qreal d)
Definition: qglobal.h:1203
void setTabStop(qreal tabStop)
Sets the default distance in device units between tab stops to the value specified by tabStop...
Definition: qtextoption.h:154
QFixed leadingSpaceWidth(const QScriptLine &line)
qreal m11() const
Returns the horizontal scaling factor.
Definition: qtransform.h:237
static qreal toReal(Register *reg, int type, bool *ok=0)
The QList class is a template class that provides lists.
Definition: qdatastream.h:62
QFixed width(int charFrom, int numChars) const

Properties

◆ d

QTextEngine* QTextLayout::d
private

Definition at line 193 of file qtextlayout.h.


The documentation for this class was generated from the following files: