PyQt (Python + Qt) learning essay: the plain text editor QPlainTextEdit function

I. Overview

QPlainTextEdit is an advanced document editor component for plain text, with specific optimizations to support processing of large documents and quick response to user input. QPlainTextEdit processes text by paragraphs and characters. The paragraph is a formatted string. The line breaks on the interface will be carried out in units of whole words according to the width of the editing component. By default, a line break in plain text represents a paragraph. The document consists of zero or more paragraphs. Each character in a paragraph has its own attributes, such as font and color.

PyQt's text processing provides a series of rich classes, including QTextDocument, QTextCharFormat, QTextCursor, QTextBlock, QTextList, QTextFrame, QTextTable, QTextBlockFormat, QTextListFormat, QTextFrameFormat, QTextTableFormat, etc. If you want to introduce clearly, it takes more time, so this part Do not expand to introduce. It is recommended that you follow the two articles below:

2. Properties

The properties of QPlainTextEdit in Designer can be set as follows:
Insert picture description here
You can see that the properties of QPlainTextEdit and many of QTextEdit are the same.

  • tabChangesFocus: The tabChangesFocus property controls whether the tab key changes focus or is accepted as input. In some cases, text editing should not allow users to use the Tab key to enter tabs or change indentation, because this will break the focus chain, the default value is False, and can be accessed through tabChangesFocus () and setTabChangesFocus ()
  • documentTitle: The documentTitle attribute holds the document title. By default, for newly created empty documents, this property contains an empty string. Can be accessed through the methods documentTitle (), setDocumentTitle ().
  • undoRedoEnabled: The undoRedoEnabled property is used to control whether undo and redo are enabled. It is enabled by default, and can be accessed through the methods isUndoRedoEnabled (), setUndoRedoEnabled ()
  • lineWrapMode: The lineWrapMode property is used to control the line break mode. Its type is the enumerated type QPlainTextEdit.LineWrapMode. The default value is WidgetWidth, which means that the line breaks on the right side of the editor in word units. The line break appears in a blank space to maintain the integrity of the entire word. You can call the methods lineWrapMode (), setLineWrapMode () to access this property. If you don't use word as unit to wrap, you need to call setWordWrapMode to change the word wrapping strategy. If the line break mode is set to NoWrap, no line breaks will occur.
  • readOnly: readOnly is used to control whether the editor is read-only, the default is False, can be accessed through isReadOnly (), setReadOnly ()
  • plainText: The plainText attribute is the text content in the editor, which can be accessed through the methods toPlainText () and setPlainText (). When the text content is changed through setPlainText, the textChanged () signal is also triggered
  • overwriteMode: The overwriteMode attribute is used to control whether the user input text replaces the existing text. If True, the input character replaces the current character one by one starting from the current cursor position. If False, the input character is inserted at the cursor. The default value is False, which can be accessed through the methods overwriteMode (), setOverwriteMode ()
  • tabStopWidth: The tabStopWidth property is used to control the number of pixels moved when the tab key is entered in the editor. The default value is 80 pixels, which can be accessed through the methods tabStopWidth () and setTabStopWidth (), but this property is the following in Qt 5.10 and later versions. Replaced by tabStopDistance, there is no such property in the 5.13 document, but in fact, the class method is still supported. The only difference between tabStopWidth and tabStopDistance is that the former is an integer and the latter is a floating point number, which is more precise. The value is also linked. The change of tabStopWidth directly changes the value of tabStopDistance to tabStopWidth. If the value of tabStopDistance changes, the rounded value of tabStopDistance is used as the value of tabStopWidth. The resulting codes tabStopDistance and tabStopWidth will be set, which is different from QTextEdit
  • cursorWidth: cursorWidth is used to set the width of the pixel of the editor cursor, the default value is 1, can be accessed through the methods cursorWidth (), setCursorWidth ()
  • textInteractionFlags: The textInteractionFlags property is used to control how the editor responds to user input. Its type is Qt.TextInteractionFlags, which is used to control whether the editor can select text by keyboard or mouse, whether it can be edited, whether the link is accessed by mouse or keyboard, etc. The default value Depending on whether the editor is read-only, it can be accessed through the textInteractionFlags () and setTextInteractionFlags () methods. For specific enumeration type values, refer to the official documentation
  • maximumBlockCount: The maximumBlockCount property is used to control the maximum number of document blocks in the editor. If the number of document blocks exceeds the value when the value of this property is set, the excess number of blocks will be removed from the beginning of the document. If the value is 0 or a negative number indicates that the number of blocks of the document is not limited, the default value is 0, the value of this property can be accessed through the methods maximumBlockCount (), setMaximumBlockCount ()
    Note : The block is the unit of the text editor to process the file, a document It consists of a series of blocks, which are represented by QTextBlock objects. QTextBlockFormat is used to control the format characteristic information of blocks. The type of blocks can be text segments, tables, lists, images, etc.
  • backgroundVisible: The backgroundVisible property is used to control whether the background palette is visible outside the document. If it is set to True, the part of the editor viewport that is not covered by text will also use the palette to draw the background, or not to draw. This feature allows users to intuitively distinguish between document areas drawn using the primary colors of the palette and any blank areas not covered by the document. As shown:
    Insert picture description here
  • centerOnScroll: The centerOnScroll property keeps whether the cursor should be centered on the screen. If set to True, plain text editing will scroll the document vertically so that the cursor is visible in the center of the viewport. This also allows text editing to scroll below the end of the document. Otherwise, if set to False, plain text editing will scroll as little as possible to ensure the cursor is visible. The default value is False, which can be accessed through the methods centerOnScroll (), setCenterOnScroll ()
  • placeholderText: placeholderText is a placeholder for the editor. When there is no text in the editor, it is displayed in gray in the editor. Once the input character is automatically cleared, it can be accessed through the methods placeholderText (), setPlaceholderText ()

Three, important methods

The following complex methods will introduce the calling grammar, and the uncomplicated methods will not introduce the calling grammar. You can check the official documentation:

  • appendHtml () method: slot method, used to add a section of html text at the end of the editor. Although QPlainTextEdit is a plain text editor, it can also parse html messages. After adding the html message using the appendHtml method, the parsed content is displayed on the interface.
Case:

Use appendHtml and appendPlainText to add the same html message

  html = '''<link  href="https://blog.csdn.net/LaoYuanPython"/><title>老猿Python</title><div>老猿Python网址:https://blog.csdn.net/LaoYuanPython</div>'''
  self.plainTextEdit.appendHtml(html)
  self.plainTextEdit.appendPlainText('\n************************************************\n')
  self.plainTextEdit.appendPlainText(html)

The interface display effect after execution is as follows:
Insert picture description here

  • appendPlainText (): slot method, used to add a section of plain text at the end of the editor
  • blockCount () method: used to obtain the number of blocks in the document, the number of blocks in the empty document is 1
  • canPaste () method: used to return whether you can paste text from the clipboard into the editor
  • clear () method: slot method, clear all text in the editor, redo / undo history will also be cleared
  • copy () method: slot method, used to copy the selected text in the editor to the clipboard
  • cut () method: slot method, used to copy the selected text in the editor to the clipboard and delete it
  • createStandardContextMenu () method:
    This method is used to create the pop-up menu displayed when the right mouse button is used in the editor, but there are two calling methods with and without parameters, and the parameter is popped up at the specified position in the document. In this way, different shortcut menus will pop up in different positions of the editor. Call syntax:createStandardContextMenu()、createStandardContextMenu(QPoint position)
  • The currentCharFormat () method: returns the current character format, whose type is QTextCharFormat, and QTextCharFormat is used to control the text format in QTextEdit (the storage type of these texts is QTextDocument objects, which can be obtained through the QTextEdit document () method. Not detailed in this article), these text format control information is used to specify some visual format of the text, just like the visual format control information in hypertext
  • The cursorForPosition () method: returns the QTextCursor text cursor object at the specified position. The QTextCursor text cursor is a programming interface that simulates the behavior of the cursor in the text editor. It is used to access and modify the content of the text document and the object of the underlying structure. QTextCursor contains information about the position of the cursor in QTextDocument and any choices it makes. QTextCursor is modeled according to the behavior of the text cursor in a text editor. It provides a programming method for performing standard operations through the user interface.
  • document () method: The document method returns the QTextDocument document management object that the text editor depends on, through which the text can be enriched, and the document object of the text editor can be changed by calling the setDocument method
  • ensureCursorVisible () method: Use this method to ensure that the cursor in the editor is visible, and you can scroll the text if it is not currently visible
  • find () method: find the specified string in the editor, call the syntax:
  • bool find(str exp, QTextDocument.FindFlags options =
    QTextDocument.FindFlags())
  • bool find(QRegExp exp, QTextDocument.FindFlags options =
    QTextDocument.FindFlags())

The exp can be a regular string or a regular expression of the QRegExp type, where options are used to specify whether to search forward or backward, whether to match case or whole word when searching, please refer to the official documentation for specific values . When exp is a regular expression, the option to match the case is ignored, but the regular expression controls whether to match the case

  • insertPlainText () method: Insert the text given by the parameter into the current position
  • moveCursor () method: control the cursor movement in the editor, call syntax:, moveCursor(operation, mode = QTextCursor.MoveAnchor)where operation is the enumeration type QTextCursor.MoveOperation, used to control the cursor movement method, such as moving to the beginning of the document, moving to the beginning of the line, etc., specific values Refer to the official documentation, mode is the enumeration type QTextCursor.MoveMode, for specific values, refer to the official documentation
  • paste () method: paste is the slot method, copy the text of the clipboard to the current position
  • redo () and undo () methods: undo and redo are slot methods. After the undo () method is executed, you can use redo to re-execute the last operation
  • selectAll () method: selectAll is a slot method to select all text
  • setCurrentCharFormat () method: set text format control information, call syntax:setCurrentCharFormat(QTextCharFormat format)
  • The setTextCursor () method: The setTextCursor method is used to set the currently visible cursor object. The calling syntax:, The setTextCursor(QTextCursor cursor)current cursor object can be obtained by the textCursor () method
  • zoomIn (), zoomOut () methods: both are slot methods, enlarge or reduce the size of the text font specified parameter size, the basic font size can be set by setFontPointSize

Fourth, the signal

  • blockCountChanged (int newBlockCount): This signal is emitted when the number of blocks in the text changes, the parameter is the latest block number
  • copyAvailable (bool yes): This signal is emitted when the text is selected or deselected, indicating whether it can be copied, yes is True for selection, False when deselected
  • cursorPositionChanged (): emit this signal when the cursor position changes
  • modificationChanged (bool changed): This signal is emitted when the content of the document changes (including the content of the document caused by undo and redo operations)
  • redoAvailable (bool available): This signal is emitted when the state of redo changes
  • : selectionChanged (): emit this signal when the selected text changes
  • textChanged (): emit this signal when the text content changes
  • undoAvailable (bool available): This signal is emitted when the state of undo changes
  • updateRequest (QRect rect, int dy): This signal is sent when the text document needs to update the specified rect area. If the text is scrolling, rect will cover the entire viewport. If the text is scrolled vertically, dy carries the scrolled viewport pixels. The purpose of this signal is to support additional components in the plain text editing subclass, such as displaying line numbers, breakpoints, or other additional information.

V. Summary

Many functions of QPlainTextEdit support the same technology as QTextEdit. Like QTextEdit, the text objects in QPlainTextEdit depend on the QTextDocument class for management. The QTextDocument class can perform rich operations on text with the help of QTextCursor. However, due to limited time and space, this article does not introduce QTextDocument and QTextCursor in detail. You can refer to the reference documents or official website documents provided by the old ape in the overview section.

Old Ape Python, learn Python from Old Ape!

Published 779 original articles · praised 3478 · 430,000 views +

Guess you like

Origin blog.csdn.net/LaoYuanPython/article/details/105610233