PySide6 QTextEdit Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
# The QTextEdit class provides a widget that is used 
# to edit and display both plain and rich text.

import sys

from PySide6.QtGui import QTextCursor, QTextCharFormat, QColor
from PySide6.QtWidgets import (QApplication,
    QWidget, QVBoxLayout, QTextEdit, QLabel)


class Window(QWidget):
    
    def __init__(self):

        super().__init__()

        layout = QVBoxLayout()
        self.setLayout(layout)
        
        # 1 - Create the text edit widget
        
        self.text_edit = QTextEdit()
        
        self.previous_cursor = None
        self.previous_format = None
        
        # QTextEdit supports markdown and HTML:
        
        markdown = '''
# Heading

**This line is bold**<br/>
*This line is italic*<br/>
_This line is underlined_<br/>
You can use 
<span style="color:maroon">
Ctrl-c, Ctrl-v</span> 
and other standard key bindings.<br/>
Right click brings up the context menu. 
'''
        self.text_edit.setMarkdown(markdown)
        
        # 3 - Connect signals with the slots
        
        self.text_edit.cursorPositionChanged.connect(
            self.on_cursor_position_changed)
        self.text_edit.textChanged.connect(
            self.on_text_changed)
        
        self.markdown_label = QLabel()
        self.markdown_label.setText(markdown)
        self.stats_label = QLabel()
        
        layout.addWidget(self.text_edit)
        layout.addWidget(self.markdown_label)
        layout.addWidget(self.stats_label)
    
    # 2 - Write the slot methods.     
    
    def on_text_changed(self):
        self.markdown_label.setText(
            self.text_edit.toMarkdown())        
   
    def on_cursor_position_changed(self):

        if not self.previous_cursor is None:
            self.previous_cursor.setCharFormat(
                self.previous_format)

        cursor = self.text_edit.textCursor()
        cursor.select(QTextCursor.WordUnderCursor)

        self.previous_cursor = cursor
        self.previous_format = cursor.charFormat()
        word = cursor.selectedText()

        format = QTextCharFormat()
        format.setBackground(QColor('lightsteelblue'))
        cursor.mergeCharFormat(format)
        
        self.stats_label.setText(f'Current word: {word}')


if __name__ == '__main__':

    if not QApplication.instance():
        app = QApplication(sys.argv)
    else:
        app = QApplication.instance()

    main_window = Window()
    main_window.show()

    sys.exit(app.exec())

QTextEdit is a ready-made rich text editor you can use in your applications. The text can be described using markdown or a subset of HTML. It comes with scrollbars, a right-click menu and standard keyboard shortcuts. To use QTextEdit in your application

  1. Create a QTextEdit object. One of the QTextEdit constructors accepts initial text which is interpreted as HTML.

  2. Write the slot methods. You can access the plain text from the QTextObject using its toPlainText() method. You can access the styled text using the toMarkdown() and toHtml() methods. You can access the underlying QTextDocument using the document() method.

  3. Connect the signals with the slots. In this example we highlight the word under cursor using QTextCursor.selection() and QTextCharFormat. To restore the previous formatting we keep track