PyQt (Python + Qt) learning essay: detailed explanation of the rich text editor QTextEdit function

I. Overview

QTextEdit is an advanced WYSIWYG document viewer and editor, supports rich text format using HTML4 style tags, and can display images, lists, and tables.

PyQt's rich text processing provides a series of rich classes, including QTextEdit, QTextDocument, QTextCharFormat, QTextCursor, QTextBlock, QTextList, QTextFrame, QTextTable, QTextBlockFormat, QTextListFormat, QTextFrameFormat, QTextTableFormat, etc. If you want to introduce clearly, it takes more time At the same time, in view of the processing aspects of HTML, the powerful functions of the BeautifulSoup module in Python can be used for parsing and editing (see the topic of the old ape Python crawler ), so this section will not be described in detail. Recommend everyone to understand the following articles:

2. Properties

Text editing The properties that QTextEdit can set in Designer are as follows:
Insert picture description here

  • autoFormatting: The autoFormatting property is used to control the automatic formatting function. Its type is the enumeration type AutoFormattingFlag. The default value is AutoNone, which is not available. When set to AutoBulletList, when the user enters an asterisk ("*" ) Or when you press the Enter key in an existing list item, a bulleted list is automatically created. The setting of AutoAll is currently the same as AutoBulletList, and there may be more expansions in the future. This property can be accessed using the methods autoFormatting () and setAutoFormatting ().
  • 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 the tabChangesFocus () and setTabChangesFocus () methods
  • documentTitle: The documentTitle attribute retains the document title parsed from the text (via HTML tags )。默认情况下,对于新创建的空文档,此属性包含空字符串。可以通过方法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-wrap mode. Its type is the enumerated type QTextEdit.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 set the line break mode to FixedPixelWidth or FixedColumnWidth, you also need to call the setLineWrapColumnOrWidth () method to set the line break pixel width or character width.
  • readOnly: readOnly is used to control whether the editor is read-only, the default is False, can be accessed through isReadOnly (), setReadOnly ()
  • html: The html attribute provides an interface to convert the text in the editor into html text. In fact, a html formatted text with complete head, html, body and other tag elements is set here. If the content is incomplete or the syntax is incorrect Will use the default html text instead. Use toHtml () to insert the text in the editor into the body of the html text corresponding to the html attribute, and the corresponding label may be added according to the content of the text displayed by the editor, so if you want to enter HTML text in the editor, the html document Do not enter the relevant label text in the basic format. It is useless if you enter it, because the editor will treat all relevant manual input content as plain text. This property can be modified using setHtml (), but instead of simply replacing the input content with the value of the property, the content of the parameter is parsed and unlabeled and stored in the editor, similar to the browser reading the html document. At the same time, the basic frame format of the standard HTML document of non-display content is saved in the html attribute. During the period, the html tag in a large number of parameters will be removed. If the content of the div tag is pure text, the div may not be saved. The text is used as Ordinary text shows that this div tag will not be restored when toHtml is called again, but it may be replaced with a p tag. The specific situation is more complicated, and the old ape has not studied it carefully
  • 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 tabStopDistance to the value of tabStopWidth. If the value of tabStopDistance changes, the rounded value of tabStopDistance is used as the value of tabStopWidth. The final generated code uses tabStopDistance
  • acceptRichText: The acceptRichText property is used to control whether the editor accepts the user's rich text insertion (for example, through the clipboard or drag and drop). When this property is set to False text, the editor only accepts plain text input from the user. The default value is True, which can be accessed through the acceptRichText () and setAcceptRichText () methods
  • 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 Depends on whether the editor is read-only or derived QTextBrowser object, can be accessed through the textInteractionFlags (), setTextInteractionFlags () method, the specific enumeration type value refer to the official documentation
  • 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 ()

In addition to the properties that can be set in Designer, QLineEdit also has a plainText property:

  • plainText: The plainText attribute is used to save the plain text in the editor. Calling toPlainText () will return the plain text in the editor. If the text editor has other content types (such as html tags), calling toPlainText () will not convert the content to Plain text, the only exception is to replace & nbsp (non-break space, & nbsp means 1 space in HTML) with a space, and you can call setPlainText () to modify the value of this property. Please refer to " PyQt (Python + Qt) Learning Essay: The Difference Between SetText, SetHtml, SetPlainText of QTextEdit "

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:

  • append method
    append method is a slot method, this method is to add a section of text corresponding to the parameter at the end of the editor, the format of this section of text is the same as the section where the current cursor is. Call syntax:append(str text)
  • 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
  • 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 a specified position in the document, so that Different shortcut menus will pop up at different locations in 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. About QTextCharFormat and QTextDocument objects 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 richly manipulated
  • 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

  • insertHtml () method: Insert the given text according to the HTML text into the current position
  • 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)
  • setTextBackgroundColor () method: setTextBackgroundColor is a slot method, set the background color, you can get the corresponding value through the textBackgroundColor () method
  • setTextColor () method: setTextColor is a slot method, set the text color, you can get the corresponding value through textColor ()
    • 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

  • 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
  • currentCharFormatChanged (QTextCharFormat f): This signal is emitted when the current text format control is changed
  • cursorPositionChanged (): emit this signal when the cursor position changes
  • 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

V. Summary

QTextEdit is a WYSIWYG rich text editor, you can use setHtml () to set or replace text, you can use clear () to delete the entire text. The text itself can be inserted using the QTextCursor class or using the convenient functions insertHtml (), insertPlainText (), append () or paste (). QTextCursor can also insert complex objects (such as tables or lists) into the document. By default, text editing is blanked to fit text editing components.
The text objects in QTextEdit depend on the QTextDocument class for management. The QTextDocument class can perform rich operations on texts 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 Lao Ape.

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/105607665