The QTextEdit widget in PyQt6 provides a powerful multi-line text editor that supports plain text, rich text (HTML), and advanced formatting. It is commonly used for input fields, document editors, and text displays.
In this tutorial, we’ll cover:
1. Basics of QTextEdit
The QTextEdit widget is a multi-line text editor that can display or accept plain text and rich text.
Example: Basic QTextEdit Setup
from PyQt6.QtWidgets import QApplication, QMainWindow, QTextEdit def main(): app = QApplication([]) window = QMainWindow() window.setWindowTitle("Basic QTextEdit Example") window.setGeometry(100, 100, 400, 300) text_edit = QTextEdit(window) text_edit.setGeometry(50, 50, 300, 200) window.show() app.exec() if __name__ == "__main__": main()
Output:
- A window with a blank multi-line text editor.
2. Setting and Retrieving Text
You can use setText() to set the content and toPlainText() to retrieve plain text.
Example: Set and Get Plain Text
text_edit = QTextEdit(window) text_edit.setGeometry(50, 50, 300, 200) # Set text text_edit.setText("Welcome to PyQt6 QTextEdit!") # Get text print(text_edit.toPlainText())
3. Rich Text and HTML
QTextEdit supports HTML for displaying rich text.
Example: Setting Rich Text
text_edit = QTextEdit(window) text_edit.setGeometry(50, 50, 300, 200) # Set rich text with HTML text_edit.setHtml("<h1>Welcome</h1><p style='color:blue;'>This is PyQt6 QTextEdit.</p>")
4. Formatting Text
You can format text programmatically using the QTextCursor or setFont(), setAlignment(), etc.
Example: Bold, Italic, and Underlined Text
from PyQt6.QtGui import QTextCursor text_edit = QTextEdit(window) text_edit.setGeometry(50, 50, 300, 200) # Insert formatted text cursor = text_edit.textCursor() cursor.insertHtml("<b>Bold Text</b> <i>Italic Text</i> <u>Underlined Text</u>")
Example: Center-Aligned Text
text_edit.setAlignment(Qt.AlignmentFlag.AlignCenter) text_edit.setText("This text is center-aligned.")
5. Handling Signals for Interactions
The QTextEdit widget provides signals for handling user interactions:
- textChanged: Triggered when the text is modified.
- cursorPositionChanged: Triggered when the cursor position changes.
Example: Handling textChanged
def on_text_changed(): print("Text has been changed!") text_edit.textChanged.connect(on_text_changed)
Example: Handling cursorPositionChanged
def on_cursor_position_changed(): cursor = text_edit.textCursor() print(f"Cursor Position: {cursor.position()}") text_edit.cursorPositionChanged.connect(on_cursor_position_changed)
6. Read-Only QTextEdit
To make QTextEdit read-only, use setReadOnly(True).
Example: Read-Only Mode
text_edit = QTextEdit(window) text_edit.setGeometry(50, 50, 300, 200) text_edit.setText("This text cannot be edited.") text_edit.setReadOnly(True)
7. Styling QTextEdit with CSS
You can customize the appearance of QTextEdit using the setStyleSheet() method.
Example: Custom Style
text_edit.setStyleSheet(""" QTextEdit { background-color: lightyellow; color: darkgreen; font-size: 16px; border: 2px solid darkblue; border-radius: 5px; } """)
8. Practical Examples
Example 1: Word Counter
from PyQt6.QtWidgets import QApplication, QMainWindow, QTextEdit, QLabel def update_word_count(): text = text_edit.toPlainText() word_count = len(text.split()) label.setText(f"Word Count: {word_count}") app = QApplication([]) window = QMainWindow() window.setWindowTitle("Word Counter Example") window.setGeometry(100, 100, 400, 300) text_edit = QTextEdit(window) text_edit.setGeometry(50, 50, 300, 200) text_edit.textChanged.connect(update_word_count) label = QLabel("Word Count: 0", window) label.setGeometry(50, 260, 200, 30) window.show() app.exec()
Output:
- Updates the word count dynamically as the user types.
Example 2: Simple Text Editor
from PyQt6.QtWidgets import QApplication, QMainWindow, QTextEdit, QPushButton, QVBoxLayout, QWidget def save_content(): with open("output.txt", "w") as file: file.write(text_edit.toPlainText()) print("Content saved to output.txt") app = QApplication([]) window = QMainWindow() window.setWindowTitle("Simple Text Editor") window.setGeometry(100, 100, 500, 400) central_widget = QWidget(window) layout = QVBoxLayout(central_widget) text_edit = QTextEdit() layout.addWidget(text_edit) save_button = QPushButton("Save") save_button.clicked.connect(save_content) layout.addWidget(save_button) window.setCentralWidget(central_widget) window.show() app.exec()
Output:
- Allows the user to type and save the text content to a file.
Example 3: Highlight Search Term
from PyQt6.QtWidgets import QApplication, QMainWindow, QTextEdit, QLineEdit, QPushButton from PyQt6.QtGui import QTextCursor def highlight_text(): text = search_box.text() cursor = text_edit.textCursor() cursor.movePosition(QTextCursor.MoveOperation.Start) while cursor.find(text): cursor.mergeCharFormat(highlight_format) app = QApplication([]) window = QMainWindow() window.setWindowTitle("Highlight Search Term") window.setGeometry(100, 100, 500, 400) text_edit = QTextEdit(window) text_edit.setGeometry(50, 50, 400, 200) text_edit.setText("This is a QTextEdit widget. You can search and highlight text.") search_box = QLineEdit(window) search_box.setGeometry(50, 270, 200, 30) search_box.setPlaceholderText("Enter search term...") highlight_button = QPushButton("Highlight", window) highlight_button.setGeometry(270, 270, 100, 30) highlight_button.clicked.connect(highlight_text) highlight_format = QTextCursor().charFormat() highlight_format.setBackground(Qt.GlobalColor.yellow) window.show() app.exec()
Output:
- Highlights all occurrences of the search term in the text editor.
Summary
In this tutorial, we covered:
- Basics of QTextEdit: Creating and configuring the widget.
- Setting and Retrieving Text: Handling plain and rich text.
- Formatting: Using rich text and programmatic text formatting.
- Signals: Handling user interactions like textChanged.
- Read-Only Mode: Making the widget non-editable.
- Styling: Customizing appearance with CSS.
- Practical Examples: Building a word counter, text editor, and search highlighter.
The QTextEdit widget is versatile, making it ideal for applications that require text input or display. Mastering its features allows you to create interactive and visually appealing text-based interfaces in PyQt6.