PySide6.QtGui.QTextCursor¶
- class QTextCursor¶
The
QTextCursor
class offers an API to access and modify QTextDocuments. More…Synopsis¶
Methods¶
def
__init__()
def
anchor()
def
atBlockEnd()
def
atBlockStart()
def
atEnd()
def
atStart()
def
beginEditBlock()
def
block()
def
blockFormat()
def
blockNumber()
def
charFormat()
def
clearSelection()
def
columnNumber()
def
createList()
def
currentFrame()
def
currentList()
def
currentTable()
def
deleteChar()
def
document()
def
endEditBlock()
def
hasSelection()
def
insertBlock()
def
insertFragment()
def
insertFrame()
def
insertHtml()
def
insertImage()
def
insertList()
def
insertMarkdown()
def
insertTable()
def
insertText()
def
isCopyOf()
def
isNull()
def
movePosition()
def
__ne__()
def
__lt__()
def
__le__()
def
__eq__()
def
__gt__()
def
__ge__()
def
position()
def
select()
def
selectedText()
def
selection()
def
selectionEnd()
def
selectionStart()
def
setBlockFormat()
def
setCharFormat()
def
setPosition()
def
swap()
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¶
Text cursors are objects that are used to access and modify the contents and underlying structure of text documents via a programming interface that mimics the behavior of a cursor in a text editor.
QTextCursor
contains information about both the cursor’s position within aQTextDocument
and any selection that it has made.QTextCursor
is modeled on the way a text cursor behaves in a text editor, providing a programmatic means of performing standard actions through the user interface. A document can be thought of as a single string of characters. The cursor’s currentposition()
then is always either between two consecutive characters in the string, or else before the very first character or after the very last character in the string. Documents can also contain tables, lists, images, and other objects in addition to text but, from the developer’s point of view, the document can be treated as one long string. Some portions of that string can be considered to lie within particular blocks (e.g. paragraphs), or within a table’s cell, or a list’s item, or other structural elements. When we refer to “current character” we mean the character immediately before the cursorposition()
in the document. Similarly, the “current block” is the block that contains the cursorposition()
.A
QTextCursor
also has ananchor()
position. The text that is between theanchor()
and theposition()
is the selection. Ifanchor()
==position()
there is no selection.The cursor position can be changed programmatically using
setPosition()
andmovePosition()
; the latter can also be used to select text. For selections seeselectionStart()
,selectionEnd()
,hasSelection()
,clearSelection()
, andremoveSelectedText()
.If the
position()
is at the start of a block,atBlockStart()
returnstrue
; and if it is at the end of a block,atBlockEnd()
returns true. The format of the current character is returned bycharFormat()
, and the format of the current block is returned byblockFormat()
.Formatting can be applied to the current text document using the
setCharFormat()
,mergeCharFormat()
,setBlockFormat()
andmergeBlockFormat()
functions. The ‘set’ functions will replace the cursor’s current character or block format, while the ‘merge’ functions add the given format properties to the cursor’s current format. If the cursor has a selection, the given format is applied to the current selection. Note that when only a part of a block is selected, the block format is applied to the entire block. The text at the current character position can be turned into a list usingcreateList()
.Deletions can be achieved using
deleteChar()
,deletePreviousChar()
, andremoveSelectedText()
.Text strings can be inserted into the document with the
insertText()
function, blocks (representing new paragraphs) can be inserted withinsertBlock()
.Existing fragments of text can be inserted with
insertFragment()
but, if you want to insert pieces of text in various formats, it is usually still easier to useinsertText()
and supply a character format.Various types of higher-level structure can also be inserted into the document with the cursor:
Lists are ordered sequences of block elements that are decorated with bullet points or symbols. These are inserted in a specified format with
insertList()
.Tables are inserted with the
insertTable()
function, and can be given an optional format. These contain an array of cells that can be traversed using the cursor.Inline images are inserted with
insertImage()
. The image to be used can be specified in an image format, or by name.Frames are inserted by calling
insertFrame()
with a specified format.
Actions can be grouped (i.e. treated as a single action for undo/redo) using
beginEditBlock()
andendEditBlock()
.Cursor movements are limited to valid cursor positions. In Latin writing this is between any two consecutive characters in the text, before the first character, or after the last character. In some other writing systems cursor movements are limited to “clusters” (e.g. a syllable in Devanagari, or a base letter plus diacritics). Functions such as
movePosition()
anddeleteChar()
limit cursor movement to these valid positions.See also
- class MoveMode¶
Constant
Description
QTextCursor.MoveAnchor
Moves the anchor to the same position as the cursor itself.
QTextCursor.KeepAnchor
Keeps the anchor where it is.
If the
anchor()
is kept where it is and theposition()
is moved, the text in between will be selected.
- class MoveOperation¶
Constant
Description
QTextCursor.NoMove
Keep the cursor where it is
QTextCursor.Start
Move to the start of the document.
QTextCursor.StartOfLine
Move to the start of the current line.
QTextCursor.StartOfBlock
Move to the start of the current block.
QTextCursor.StartOfWord
Move to the start of the current word.
QTextCursor.PreviousBlock
Move to the start of the previous block.
QTextCursor.PreviousCharacter
Move to the previous character.
QTextCursor.PreviousWord
Move to the beginning of the previous word.
QTextCursor.Up
Move up one line.
QTextCursor.Left
Move left one character.
QTextCursor.WordLeft
Move left one word.
QTextCursor.End
Move to the end of the document.
QTextCursor.EndOfLine
Move to the end of the current line.
QTextCursor.EndOfWord
Move to the end of the current word.
QTextCursor.EndOfBlock
Move to the end of the current block.
QTextCursor.NextBlock
Move to the beginning of the next block.
QTextCursor.NextCharacter
Move to the next character.
QTextCursor.NextWord
Move to the next word.
QTextCursor.Down
Move down one line.
QTextCursor.Right
Move right one character.
QTextCursor.WordRight
Move right one word.
QTextCursor.NextCell
Move to the beginning of the next table cell inside the current table. If the current cell is the last cell in the row, the cursor will move to the first cell in the next row.
QTextCursor.PreviousCell
Move to the beginning of the previous table cell inside the current table. If the current cell is the first cell in the row, the cursor will move to the last cell in the previous row.
QTextCursor.NextRow
Move to the first new cell of the next row in the current table.
QTextCursor.PreviousRow
Move to the last cell of the previous row in the current table.
See also
- class SelectionType¶
This enum describes the types of selection that can be applied with the
select()
function.Constant
Description
QTextCursor.Document
Selects the entire document.
QTextCursor.BlockUnderCursor
Selects the block of text under the cursor.
QTextCursor.LineUnderCursor
Selects the line of text under the cursor.
QTextCursor.WordUnderCursor
Selects the word under the cursor. If the cursor is not positioned within a string of selectable characters, no text is selected.
- __init__()¶
Constructs a null cursor.
- __init__(document)
- Parameters:
document –
QTextDocument
Constructs a cursor pointing to the beginning of the
document
.- __init__(frame)
- Parameters:
frame –
QTextFrame
Constructs a cursor pointing to the beginning of the
frame
.- __init__(block)
- Parameters:
block –
QTextBlock
Constructs a cursor pointing to the beginning of the
block
.- __init__(cursor)
- Parameters:
cursor –
QTextCursor
Constructs a new cursor that is a copy of
cursor
.- anchor()¶
- Return type:
int
Returns the anchor position; this is the same as
position()
unless there is a selection in which caseposition()
marks one end of the selection and anchor() marks the other end. Just like the cursor position, the anchor position is between characters.- atBlockEnd()¶
- Return type:
bool
Returns
true
if the cursor is at the end of a block; otherwise returnsfalse
.See also
- atBlockStart()¶
- Return type:
bool
Returns
true
if the cursor is at the start of a block; otherwise returnsfalse
.See also
- atEnd()¶
- Return type:
bool
Returns
true
if the cursor is at the end of the document; otherwise returnsfalse
.See also
- atStart()¶
- Return type:
bool
Returns
true
if the cursor is at the start of the document; otherwise returnsfalse
.See also
- beginEditBlock()¶
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Indicates the start of a block of editing operations on the document that should appear as a single operation from an undo/redo point of view.
For example:
cursor = QTextCursor(textDocument) cursor.beginEditBlock() cursor.insertText("Hello") cursor.insertText("World") cursor.endEditBlock() textDocument.undo()
The call to undo() will cause both insertions to be undone, causing both “World” and “Hello” to be removed.
It is possible to nest calls to beginEditBlock and
endEditBlock
. The top-most pair will determine the scope of the undo/redo operation.See also
- block()¶
- Return type:
Returns the block that contains the cursor.
- blockCharFormat()¶
- Return type:
Returns the block character format of the block the cursor is in.
The block char format is the format used when inserting text at the beginning of an empty block.
See also
- blockFormat()¶
- Return type:
Returns the block format of the block the cursor is in.
See also
- blockNumber()¶
- Return type:
int
Returns the number of the block the cursor is in, or 0 if the cursor is invalid.
Note that this function only makes sense in documents without complex objects such as tables or frames.
- charFormat()¶
- Return type:
Returns the format of the character immediately before the cursor
position()
. If the cursor is positioned at the beginning of a text block that is not empty then the format of the character immediately after the cursor is returned.See also
- clearSelection()¶
Clears the current selection by setting the anchor to the cursor position.
Note that it does not delete the text of the selection.
See also
- columnNumber()¶
- Return type:
int
Returns the position of the cursor within its containing line.
Note that this is the column number relative to a wrapped line, not relative to the block (i.e. the paragraph).
You probably want to call
positionInBlock()
instead.See also
This is an overloaded function.
Creates and returns a new list with the given
style
, making the cursor’s current paragraph the first list item.The style to be used is defined by the
Style
enum.See also
- createList(format)
- Parameters:
format –
QTextListFormat
- Return type:
Creates and returns a new list with the given
format
, and makes the current paragraph the cursor is in the first list item.See also
- currentFrame()¶
- Return type:
Returns a pointer to the current frame. Returns
None
if the cursor is invalid.See also
Returns the current list if the cursor
position()
is inside a block that is part of a list; otherwise returnsNone
.See also
- currentTable()¶
- Return type:
Returns a pointer to the current table if the cursor
position()
is inside a block that is part of a table; otherwise returnsNone
.See also
- deleteChar()¶
If there is no selected text, deletes the character at the current cursor position; otherwise deletes the selected text.
- deletePreviousChar()¶
If there is no selected text, deletes the character before the current cursor position; otherwise deletes the selected text.
See also
- document()¶
- Return type:
Returns the document this cursor is associated with.
- endEditBlock()¶
Indicates the end of a block of editing operations on the document that should appear as a single operation from an undo/redo point of view.
See also
- hasComplexSelection()¶
- Return type:
bool
Returns
true
if the cursor contains a selection that is not simply a range fromselectionStart()
toselectionEnd()
; otherwise returnsfalse
.Complex selections are ones that span at least two cells in a table; their extent is specified by
selectedTableCells()
.- hasSelection()¶
- Return type:
bool
Returns
true
if the cursor contains a selection; otherwise returnsfalse
.- insertBlock()¶
Inserts a new empty block at the cursor
position()
with the currentblockFormat()
andcharFormat()
.See also
- insertBlock(format)
- Parameters:
format –
QTextBlockFormat
This is an overloaded function.
Inserts a new empty block at the cursor
position()
with block formatformat
and the currentcharFormat()
as block char format.See also
- insertBlock(format, charFormat)
- Parameters:
format –
QTextBlockFormat
charFormat –
QTextCharFormat
This is an overloaded function.
Inserts a new empty block at the cursor
position()
with block formatformat
andcharFormat
as block char format.See also
- insertFragment(fragment)¶
- Parameters:
fragment –
QTextDocumentFragment
Inserts the text
fragment
at the currentposition()
.- insertFrame(format)¶
- Parameters:
format –
QTextFrameFormat
- Return type:
Inserts a frame with the given
format
at the current cursorposition()
, moves the cursorposition()
inside the frame, and returns the frame.If the cursor holds a selection, the whole selection is moved inside the frame.
See also
- insertHtml(html)¶
- Parameters:
html – str
Inserts the text
html
at the currentposition()
. The text is interpreted as HTML.Note
When using this function with a style sheet, the style sheet will only apply to the current block in the document. In order to apply a style sheet throughout a document, use
setDefaultStyleSheet()
instead.- insertImage(name)¶
- Parameters:
name – str
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
This is an overloaded function.
Convenience method for inserting the image with the given
name
at the currentposition()
.img = QImage() textDocument.addResource(QTextDocument.ImageResource, QUrl("myimage"), img) cursor.insertImage("myimage")
- insertImage(format)
- Parameters:
format –
QTextImageFormat
Inserts the image defined by
format
at the currentposition()
.- insertImage(image[, name=""])
- Parameters:
image –
QImage
name – str
This is an overloaded function.
Convenience function for inserting the given
image
with an optionalname
at the currentposition()
.- insertImage(format, alignment)
- Parameters:
format –
QTextImageFormat
alignment –
Position
This is an overloaded function.
Inserts the image defined by the given
format
at the cursor’s current position with the specifiedalignment
.See also
This is an overloaded function.
Inserts a new block at the current position and makes it the first list item of a newly created list with the given
style
. Returns the created list.See also
- insertList(format)
- Parameters:
format –
QTextListFormat
- Return type:
Inserts a new block at the current position and makes it the first list item of a newly created list with the given
format
. Returns the created list.See also
- insertMarkdown(markdown[, features=QTextDocument.MarkdownDialectGitHub])¶
- Parameters:
markdown – str
features – Combination of
MarkdownFeature
Inserts the
markdown
text at the currentposition()
, with the specified Markdownfeatures
. The default is GitHub dialect.- insertTable(rows, cols)¶
- Parameters:
rows – int
cols – int
- Return type:
This is an overloaded function.
Creates a new table with the given number of
rows
andcolumns
, inserts it at the current cursorposition()
in the document, and returns the table object. The cursor is moved to the beginning of the first cell.There must be at least one row and one column in the table.
See also
- insertTable(rows, cols, format)
- Parameters:
rows – int
cols – int
format –
QTextTableFormat
- Return type:
Creates a new table with the given number of
rows
andcolumns
in the specifiedformat
, inserts it at the current cursorposition()
in the document, and returns the table object. The cursor is moved to the beginning of the first cell.There must be at least one row and one column in the table.
See also
- insertText(text)¶
- Parameters:
text – str
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Inserts
text
at the current position, using the current character format.If there is a selection, the selection is deleted and replaced by
text
, for example:cursor.clearSelection() cursor.movePosition(QTextCursor.NextWord, QTextCursor.KeepAnchor) cursor.insertText("Hello World")
This clears any existing selection, selects the word at the cursor (i.e. from
position()
forward), and replaces the selection with the phrase “Hello World”.Any ASCII linefeed characters (\n) in the inserted text are transformed into unicode block separators, corresponding to
insertBlock()
calls.See also
- insertText(text, format)
- Parameters:
text – str
format –
QTextCharFormat
This is an overloaded function.
Inserts
text
at the current position with the givenformat
.- isCopyOf(other)¶
- Parameters:
other –
QTextCursor
- Return type:
bool
Returns
true
if this cursor andother
are copies of each other, i.e. one of them was created as a copy of the other and neither has moved since. This is much stricter than equality.See also
operator=()
operator==()
- isNull()¶
- Return type:
bool
Returns
true
if the cursor is null; otherwise returnsfalse
. A null cursor is created by the default constructor.- joinPreviousEditBlock()¶
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Like
beginEditBlock()
indicates the start of a block of editing operations that should appear as a single operation for undo/redo. However unlikebeginEditBlock()
it does not start a new block but reverses the previous call toendEditBlock()
and therefore makes following operations part of the previous edit block created.For example:
cursor = QTextCursor(textDocument) cursor.beginEditBlock() cursor.insertText("Hello") cursor.insertText("World") cursor.endEditBlock() # ... cursor.joinPreviousEditBlock() cursor.insertText("Hey") cursor.endEditBlock() textDocument.undo()
The call to undo() will cause all three insertions to be undone.
See also
- keepPositionOnInsert()¶
- Return type:
bool
Returns whether the cursor should keep its current position when text gets inserted at the position of the cursor.
The default is false;
See also
- mergeBlockCharFormat(modifier)¶
- Parameters:
modifier –
QTextCharFormat
Modifies the block char format of the current block (or all blocks that are contained in the selection) with the block format specified by
modifier
.See also
- mergeBlockFormat(modifier)¶
- Parameters:
modifier –
QTextBlockFormat
Modifies the block format of the current block (or all blocks that are contained in the selection) with the block format specified by
modifier
.See also
- mergeCharFormat(modifier)¶
- Parameters:
modifier –
QTextCharFormat
Merges the cursor’s current character format with the properties described by format
modifier
. If the cursor has a selection, this function applies all the properties set inmodifier
to all the character formats that are part of the selection.See also
- movePosition(op[, arg__2=QTextCursor.MoveMode.MoveAnchor[, n=1]])¶
- Parameters:
op –
MoveOperation
arg__2 –
MoveMode
n – int
- Return type:
bool
Moves the cursor by performing the given
operation
n
times, using the specifiedmode
, and returnstrue
if all operations were completed successfully; otherwise returnsfalse
.For example, if this function is repeatedly used to seek to the end of the next word, it will eventually fail when the end of the document is reached.
By default, the move operation is performed once (
n
= 1).If
mode
isKeepAnchor
, the cursor selects the text it moves over. This is the same effect that the user achieves when they hold down the Shift key and move the cursor with the cursor keys.See also
- __ne__(rhs)¶
- Parameters:
rhs –
QTextCursor
- Return type:
bool
Returns
true
if theother
cursor is at a different position in the document as this cursor; otherwise returnsfalse
.- __lt__(rhs)¶
- Parameters:
rhs –
QTextCursor
- Return type:
bool
Returns
true
if theother
cursor is positioned later in the document than this cursor; otherwise returnsfalse
.- __le__(rhs)¶
- Parameters:
rhs –
QTextCursor
- Return type:
bool
Returns
true
if theother
cursor is positioned later or at the same position in the document as this cursor; otherwise returns false.- __eq__(rhs)¶
- Parameters:
rhs –
QTextCursor
- Return type:
bool
Returns
true
if theother
cursor is at the same position in the document as this cursor; otherwise returnsfalse
.- __gt__(rhs)¶
- Parameters:
rhs –
QTextCursor
- Return type:
bool
Returns
true
if theother
cursor is positioned earlier in the document than this cursor; otherwise returnsfalse
.- __ge__(rhs)¶
- Parameters:
rhs –
QTextCursor
- Return type:
bool
Returns
true
if theother
cursor is positioned earlier or at the same position in the document as this cursor; otherwise returns false.- position()¶
- Return type:
int
Returns the absolute position of the cursor within the document. The cursor is positioned between characters.
Note
The “characters” in this case refer to the string of QChar objects, i.e. 16-bit Unicode characters, and the position is considered an index into this string. This does not necessarily correspond to individual graphemes in the writing system, as a single grapheme may be represented by multiple Unicode characters, such as in the case of surrogate pairs, linguistic ligatures or diacritics.
- positionInBlock()¶
- Return type:
int
Returns the relative position of the cursor within the block. The cursor is positioned between characters.
This is equivalent to
position() - block().position()
.Note
The “characters” in this case refer to the string of QChar objects, i.e. 16-bit Unicode characters, and the position is considered an index into this string. This does not necessarily correspond to individual graphemes in the writing system, as a single grapheme may be represented by multiple Unicode characters, such as in the case of surrogate pairs, linguistic ligatures or diacritics.
See also
- removeSelectedText()¶
If there is a selection, its content is deleted; otherwise does nothing.
See also
- select(selection)¶
- Parameters:
selection –
SelectionType
Selects text in the document according to the given
selection
.- selectedTableCells()¶
- Return type:
PyObject
If the selection spans over table cells,
firstRow
is populated with the number of the first row in the selection,firstColumn
with the number of the first column in the selection, andnumRows
andnumColumns
with the number of rows and columns in the selection. If the selection does not span any table cells the results are harmless but undefined.- selectedText()¶
- Return type:
str
Returns the current selection’s text (which may be empty). This only returns the text, with no rich text formatting information. If you want a document fragment (i.e. formatted rich text) use
selection()
instead.Note
If the selection obtained from an editor spans a line break, the text will contain a Unicode U+2029 paragraph separator character instead of a newline
\n
character. Use QString::replace() to replace these characters with newlines.- selection()¶
- Return type:
Returns the current selection (which may be empty) with all its formatting information. If you just want the selected text (i.e. plain text) use
selectedText()
instead.Note
Unlike
toPlainText()
,selectedText()
may include special unicode characters such as QChar::ParagraphSeparator.See also
- selectionEnd()¶
- Return type:
int
Returns the end of the selection or
position()
if the cursor doesn’t have a selection.See also
- selectionStart()¶
- Return type:
int
Returns the start of the selection or
position()
if the cursor doesn’t have a selection.See also
- setBlockCharFormat(format)¶
- Parameters:
format –
QTextCharFormat
Sets the block char format of the current block (or all blocks that are contained in the selection) to
format
.See also
- setBlockFormat(format)¶
- Parameters:
format –
QTextBlockFormat
Sets the block format of the current block (or all blocks that are contained in the selection) to
format
.See also
- setCharFormat(format)¶
- Parameters:
format –
QTextCharFormat
Sets the cursor’s current character format to the given
format
. If the cursor has a selection, the givenformat
is applied to the current selection.See also
- setKeepPositionOnInsert(b)¶
- Parameters:
b – bool
Defines whether the cursor should keep its current position when text gets inserted at the current position of the cursor.
If
b
is true, the cursor keeps its current position when text gets inserted at the positing of the cursor. Ifb
is false, the cursor moves along with the inserted text.The default is false.
Note that a cursor always moves when text is inserted before the current position of the cursor, and it always keeps its position when text is inserted after the current position of the cursor.
See also
Moves the cursor to the absolute position in the document specified by
pos
using aMoveMode
specified bym
. The cursor is positioned between characters.Note
The “characters” in this case refer to the string of QChar objects, i.e. 16-bit Unicode characters, and
pos
is considered an index into this string. This does not necessarily correspond to individual graphemes in the writing system, as a single grapheme may be represented by multiple Unicode characters, such as in the case of surrogate pairs, linguistic ligatures or diacritics. For a more generic approach to navigating the document, usemovePosition()
, which will respect the actual grapheme boundaries in the text.See also
- setVerticalMovementX(x)¶
- Parameters:
x – int
Sets the visual x position for vertical cursor movements to
x
.The vertical movement x position is cleared automatically when the cursor moves horizontally, and kept unchanged when the cursor moves vertically. The mechanism allows the cursor to move up and down on a visually straight line with proportional fonts, and to gently “jump” over short lines.
A value of -1 indicates no predefined x position. It will then be set automatically the next time the cursor moves up or down.
See also
- Parameters:
b – bool
Sets visual navigation to
b
.Visual navigation means skipping over hidden text paragraphs. The default is false.
See also
- swap(other)¶
- Parameters:
other –
QTextCursor
Swaps this text cursor instance with
other
. This function is very fast and never fails.- verticalMovementX()¶
- Return type:
int
Returns the visual x position for vertical cursor movements.
A value of -1 indicates no predefined x position. It will then be set automatically the next time the cursor moves up or down.
See also
- Return type:
bool
Returns
true
if the cursor does visual navigation; otherwise returnsfalse
.Visual navigation means skipping over hidden text paragraphs. The default is false.
See also