QTextLayout Class

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

Header: #include <QTextLayout>
qmake: QT += gui

Note: All functions in this class are reentrant.

Public Types

struct FormatRange
enum CursorMode { SkipCharacters, SkipWords }

Detailed Description

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.setCacheEnabled(true);
 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.

Member Type Documentation

enum QTextLayout::CursorMode

ConstantValue
QTextLayout::SkipCharacters0
QTextLayout::SkipWords1