PySide6.QtGui.QTextLayout¶
- class QTextLayout¶
- The - QTextLayoutclass is used to lay out and render text. More_…- Synopsis¶- Methods¶- def - __init__()
- def - beginLayout()
- def - boundingRect()
- def - cacheEnabled()
- def - clearFormats()
- def - clearLayout()
- def - createLine()
- def - draw()
- def - drawCursor()
- def - endLayout()
- def - font()
- def - formats()
- def - glyphRuns()
- def - lineAt()
- def - lineCount()
- def - maximumWidth()
- def - minimumWidth()
- def - position()
- def - setFlags()
- def - setFont()
- def - setFormats()
- def - setPosition()
- def - setPreeditArea()
- def - setRawFont()
- def - setText()
- def - setTextOption()
- def - text()
- def - textOption()
 - Note - This documentation may contain snippets that were automatically translated from C++ to Python. We always welcome contributions to the snippet translation. If you see an issue with the translation, you can also let us know by creating a ticket on https:/bugreports.qt.io/projects/PYSIDE - Detailed Description¶- Warning - This section contains snippets that were automatically translated from C++ to Python and may contain errors. - 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. - QTextLayoutcan be used with both plain and rich text.- QTextLayoutcan be used to create a sequence of- QTextLineinstances 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 - QTextLineobjects; use- createLine()to create a- QTextLineinstance, and- lineAt()or- lineForTextPosition()to retrieve created lines.- Here is a code snippet that demonstrates the layout phase: - leading = fontMetrics.leading() height = 0 textLayout.setCacheEnabled(True) textLayout.beginLayout() while True: line = textLayout.createLine() if not 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:- painter = QPainter(self) textLayout.draw(painter, QPoint(0, 0)) - It is also possible to draw each line individually, for instance to draw the last line that fits into a widget elided: - painter = QPainter(self) fontMetrics = painter.fontMetrics() lineSpacing = fontMetrics.lineSpacing() y = 0 textLayout = QTextLayout(content, painter.font()) textLayout.beginLayout() while True: line = textLayout.createLine() if not line.isValid(): break line.setLineWidth(width()) nextLineY = y + lineSpacing if height() >= nextLineY + lineSpacing: line.draw(painter, QPoint(0, y)) y = nextLineY else: lastLine = content.mid(line.textStart()) elidedLastLine = fontMetrics.elidedText(lastLine, Qt.ElideRight, width()) painter.drawText(QPoint(0, y + fontMetrics.ascent()), elidedLastLine) line = textLayout.createLine() break textLayout.endLayout() - For a given position in the text you can find a valid cursor position with - isValidCursorPosition(),- nextCursorPosition(), and- previousCursorPosition().- The - QTextLayoutitself can be positioned with- setPosition(); it has a- boundingRect(), and a- minimumWidth()and a- maximumWidth().- See also - class GlyphRunRetrievalFlag¶
- (inherits - enum.Flag) GlyphRunRetrievalFlag specifies flags passed to the- glyphRuns()functions to determine which properties of the layout are returned in the- QGlyphRunobjects. Since each property will consume memory and may require additional allocations, it is a good practice to only request the properties you will need to access later.- Constant - Description - QTextLayout.RetrieveGlyphIndexes - Retrieves the indexes in the font which correspond to the glyphs. - QTextLayout.RetrieveGlyphPositions - Retrieves the relative positions of the glyphs in the layout. - QTextLayout.RetrieveStringIndexes - Retrieves the indexes in the original string that correspond to each of the glyphs. - QTextLayout.RetrieveString - Retrieves the original source string from the layout. - QTextLayout.RetrieveAll - Retrieves all available properties of the layout. - See also - Added in version 6.5. 
 - class CursorMode¶
- Constant - Description - QTextLayout.SkipCharacters - QTextLayout.SkipWords 
 - __init__()¶
 - Constructs an empty text layout. - See also - __init__(text)
- Parameters:
- text – str 
 
 - Constructs a text layout to lay out the given - text.- __init__(b)
- Parameters:
- b – - QTextBlock
 
 - Constructs a text layout to lay out the given - text.- __init__(text, font[, paintdevice=None])
- Parameters:
- text – str 
- font – - QFont
- paintdevice – - QPaintDevice
 
 
 - Constructs a text layout to lay out the given - textwith the specified- font.- All the metric and layout calculations will be done in terms of the paint device, - paintdevice. If- paintdeviceis- Nonethe calculations will be done in screen metrics.- beginLayout()¶
 - Begins the layout process. - Warning - This will invalidate the layout, so all existing - QTextLineobjects that refer to the previous contents should now be discarded.- See also - The smallest rectangle that contains all the lines in the layout. - cacheEnabled()¶
- Return type:
- bool 
 
 - Returns - trueif the complete layout information is cached; otherwise returns- false.- See also - clearFormats()¶
 - Clears the list of additional formats supported by the text layout. - See also - clearLayout()¶
 - Clears the line information in the layout. After having called this function, - lineCount()returns 0.- Warning - This will invalidate the layout, so all existing - QTextLineobjects that refer to the previous contents should now be discarded.- 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 - setLineWidth()function is called.- Once - 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- QTextLinereturned will not be valid (isValid() will return false).- cursorMoveStyle()¶
- Return type:
 
 - The cursor movement style of this - QTextLayout. The default is Qt::LogicalMoveStyle.- See also - draw(p, pos[, selections=list()[, clip=QRectF()]])¶
 - Draws the whole layout on the painter - pat the position specified by- pos. The rendered layout includes the given- selectionsand is clipped within the rectangle specified by- clip.- This is an overloaded function. - Draws a text cursor with the current pen at the given - positionusing the- painterspecified. The corresponding position within the text is specified by- cursorPosition.- drawCursor(p, pos, cursorPosition, width)
 - Draws a text cursor with the current pen and the specified - widthat the given- positionusing the- painterspecified. The corresponding position within the text is specified by- cursorPosition.- endLayout()¶
 - Ends the layout process. - See also - Returns the current font that is used for the layout, or a default font if none is set. - See also - formats()¶
- Return type:
- .list of QTextLayout.FormatRange 
 
 - Returns the list of additional formats supported by the text layout. - See also - glyphRuns([from=-1[, length=-1]])¶
- Parameters:
- from – int 
- length – int 
 
- Return type:
- .list of QGlyphRun 
 
 - This is an overloaded function. - Returns the glyph indexes and positions for all glyphs corresponding to the - lengthcharacters starting at the position- fromin this- QTextLayout. This is an expensive function, and should not be called in a time sensitive context.- If - fromis less than zero, then the glyph run will begin at the first character in the layout. If- lengthis less than zero, it will span the entire string from the start position.- Note - This is equivalent to calling glyphRuns(from, length, QTextLayout::GlyphRunRetrievalFlag::GlyphIndexes | QTextLayout::GlyphRunRetrievalFlag::GlyphPositions). - See also - glyphRuns(from, length, flags)
- Parameters:
- from – int 
- length – int 
- flags – Combination of - GlyphRunRetrievalFlag
 
- Return type:
- .list of QGlyphRun 
 
 - This is an overloaded function. - Returns the glyph indexes and positions for all glyphs corresponding to the - lengthcharacters starting at the position- fromin this- QTextLayout. This is an expensive function, and should not be called in a time sensitive context.- If - fromis less than zero, then the glyph run will begin at the first character in the layout. If- lengthis less than zero, it will span the entire string from the start position.- The - retrievalFlagsspecifies which properties of the- QGlyphRunwill be retrieved from the layout. To minimize allocations and memory consumption, this should be set to include only the properties that you need to access later.- See also - isValidCursorPosition(pos)¶
- Parameters:
- pos – int 
- Return type:
- bool 
 
 - Returns - trueif position- posis 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 diaeresis (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. - leftCursorPosition(oldPos)¶
- Parameters:
- oldPos – int 
- Return type:
- int 
 
 - Returns the cursor position to the left of - oldPos, next to it. It’s dependent on the visual position of characters, after bi-directional reordering.- Returns the - i-th line of text in this text layout.- See also - lineCount()¶
- Return type:
- int 
 
 - Returns the number of lines in this text layout. - See also - Returns the line that contains the cursor position specified by - pos.- See also - maximumWidth()¶
- Return type:
- float 
 
 - 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()¶
- Return type:
- float 
 
 - 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 - nextCursorPosition(oldPos[, mode=QTextLayout.CursorMode.SkipCharacters])¶
- Parameters:
- oldPos – int 
- mode – - CursorMode
 
- Return type:
- int 
 
 - Returns the next valid cursor position after - oldPosthat respects the given cursor- mode. Returns value of- oldPos, if- oldPosis not a valid cursor position.- The global position of the layout. This is independent of the bounding rectangle and of the layout process. - See also - preeditAreaPosition()¶
- Return type:
- int 
 
 - Returns the position of the area in the text layout that will be processed before editing occurs. - See also - preeditAreaText()¶
- Return type:
- str 
 
 - Returns the text that is inserted in the layout before editing occurs. - See also - previousCursorPosition(oldPos[, mode=QTextLayout.CursorMode.SkipCharacters])¶
- Parameters:
- oldPos – int 
- mode – - CursorMode
 
- Return type:
- int 
 
 - Returns the first valid cursor position before - oldPosthat respects the given cursor- mode. Returns value of- oldPos, if- oldPosis not a valid cursor position.- rightCursorPosition(oldPos)¶
- Parameters:
- oldPos – int 
- Return type:
- int 
 
 - Returns the cursor position to the right of - oldPos, next to it. It’s dependent on the visual position of characters, after bi-directional reordering.- See also - setCacheEnabled(enable)¶
- Parameters:
- enable – bool 
 
 - Enables caching of the complete layout information if - enableis true; otherwise disables layout caching. Usually- QTextLayoutthrows 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 - setCursorMoveStyle(style)¶
- Parameters:
- style – - CursorMoveStyle
 
 - Sets the visual cursor movement style to the given - style. If the- QTextLayoutis 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 - setFlags(flags)¶
- Parameters:
- flags – int 
 
 - Sets the layout’s font to the given - font. The layout is invalidated and must be laid out again.- See also - setFormats(overrides)¶
- Parameters:
- overrides – .list of QTextLayout.FormatRange 
 
 - Sets the additional formats supported by the text layout to - formats. The formats are applied with preedit area text in place.- See also - Moves the text layout to point - p.- See also - setPreeditArea(position, text)¶
- Parameters:
- position – int 
- text – str 
 
 
 - Sets the - positionand- textof the area in the layout that is processed before editing occurs. The layout is invalidated and must be laid out again.- See also - setText(string)¶
- Parameters:
- string – str 
 
 - Sets the layout’s text to the given - string. The layout is invalidated and must be laid out again.- Notice that when using this - QTextLayoutas part of a- QTextDocumentthis method will have no effect.- See also - setTextOption(option)¶
- Parameters:
- option – - QTextOption
 
 - Sets the text option structure that controls the layout process to the given - option.- See also - text()¶
- Return type:
- str 
 
 - Returns the layout’s text. - See also - textOption()¶
- Return type:
 
 - Returns the current text option used to control the layout process. - See also - class FormatRange¶
- Synopsis¶- Methods¶- Note - This documentation may contain snippets that were automatically translated from C++ to Python. We always welcome contributions to the snippet translation. If you see an issue with the translation, you can also let us know by creating a ticket on https:/bugreports.qt.io/projects/PYSIDE - Detailed Description¶- PySide6.QtGui.QTextLayout.FormatRange.start¶
 - PySide6.QtGui.QTextLayout.FormatRange.length¶
 - PySide6.QtGui.QTextLayout.FormatRange.format¶
 - __ne__(rhs)¶
- Parameters:
- rhs – - FormatRange
- Return type:
- bool 
 
 - Returns true if any of the - start,- length, or- formatfields in- lhsand- rhscontain different values respectively.- __eq__(rhs)¶
- Parameters:
- rhs – - FormatRange
- Return type:
- bool 
 
 - Returns true if the - start,- length, and- formatfields in- lhsand- rhscontain the same values respectively.