You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 wordlist to 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
  • 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 incorrect prefix (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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:03:55