PyQt5实现QTextBrowser文本多色显示:错误单词标红
Got it, let's tackle this problem step by step. Here's how you can display your word list in QTextBrowser with misspelled words highlighted in red:
Solution for Highlighting Misspelled Words in QTextBrowser
Since QTextBrowser supports rich text (HTML), we can leverage HTML color tags to make misspelled words stand out in red. Below is a practical implementation using PyQt6 (this works similarly for PyQt5/PySide2/PySide6):
Step-by-Step Implementation
- First, iterate through your
wordlistto build an HTML string:- Wrap misspelled words (in your case, those starting with
incorrect) with<font color="red">...</font>tags - Leave correctly spelled words as plain text
- Wrap misspelled words (in your case, those starting with
- Feed the generated HTML into QTextBrowser using its
setHtml()method
Complete Code Snippet
from PyQt6.QtWidgets import QApplication, QTextBrowser, QWidget, QVBoxLayout import sys # Your original word list wordlist = ['correct1', 'correct2', 'incorrect1', 'correct3', 'incorrect2'] app = QApplication(sys.argv) main_window = QWidget() layout = QVBoxLayout(main_window) # Initialize the QTextBrowser widget text_browser = QTextBrowser() # Build the formatted HTML content formatted_content = "" for word in wordlist: if word.startswith('incorrect'): # Wrap misspelled words in red font tag formatted_content += f"<font color='red'>{word}</font><br>" else: # Add correct words as plain text formatted_content += f"{word}<br>" # Set the HTML content to the text browser text_browser.setHtml(formatted_content) layout.addWidget(text_browser) main_window.show() sys.exit(app.exec())
Quick Notes
- If your method of identifying misspelled words isn't just the
incorrectprefix (e.g., using a predefined set of misspelled terms), adjust the condition like this:misspelled_words = {'incorrect1', 'incorrect2'} for word in wordlist: if word in misspelled_words: formatted_content += f"<font color='red'>{word}</font><br>" else: formatted_content += f"{word}<br>" - The
<br>tag adds a line break after each word, so each entry appears on its own line in the QTextBrowser.
内容的提问来源于stack exchange,提问作者Ishara Dayarathna
相关产品推荐
相关产品推荐

