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

PyQt5如何在QTextEdit单行中显示彩色文本及自定义词间空格

PyQt5 QTextEdit 追加自定义样式文本实现方案

你的需求可以通过调整富文本字符串格式直接实现,核心修改点如下:

  • 仅对需要特殊样式的"two"单词使用<span>标签控制样式,不要用<pre>包裹整行,避免覆盖你提前配置的全局文本样式
  • 8个连续空格使用&nbsp;HTML实体占位,规避HTML自动合并连续空格的特性,兼容性更强

修正后的完整代码如下:

import sys
from PyQt5.QtWidgets import *
from PyQt5 import QtCore
from PyQt5.QtCore import pyqtSignal
                
class App(QWidget):
    update_message = QtCore.pyqtSignal(str)
    def __init__(self):
        super().__init__()
        self.initUI()
        self.update_message.connect(self.updateText)

    def initUI(self):
        self.setWindowTitle("ZM")
        vlayout  = QVBoxLayout()
        self.bt4 = QPushButton("test command")
        
        self.textEdit = QTextEdit()
        self.textEdit.setStyleSheet("background:lightgray; font-family:Helvetica; color:green; font: 18px; white-space:pre")
        self.textEdit.setReadOnly(True)
        self.textEdit.document().setMaximumBlockCount(100)
        self.textEdit.setText('hello')
 
        vlayout.addWidget(self.textEdit)
        vlayout.addWidget(self.bt4)
        self.setLayout(vlayout)
 
        self.bt4.clicked.connect(self.test_command)

        self.resize(1000,800)
        self.show()
    
    def updateText(self, text):
        self.textEdit.append(text)

    def test_command(self):
        # 仅two加蓝色加粗样式,8个&nbsp;对应8个空格
        command = "I have <span style='color:blue; font-weight:bold;'>two</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;books."
        self.update_message.emit(command)
            
if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = App()
    sys.exit(app.exec_())

如果你更习惯直接输入空格,只要你保留当前QTextEdit样式表中white-space:pre的配置,也可以直接在"two"和"books"之间输入8个普通空格,效果一致。

内容的提问来源于stack exchange,提问作者sunynor

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 10:42:04