1

I want to append a sentence in the QTextEdit of QWidget, such as "I have two books." The word "two" will be blue and bold. And there will be eight spaces between "two" and "books". But I don't know how to do it. Here is an example.

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import QColor, QFont, QTextCharFormat
from PyQt5 import QtCore
from PyQt5.QtCore import Qt, 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):
        command = "I have <pre style='color:blue'><b> two </b>        books.</pre>"
        self.update_message.emit(command)
            
if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = App()
    sys.exit(app.exec_())
Eladtopaz
  • 1,036
  • 1
  • 6
  • 21
sunynor
  • 11
  • 2
  • I think you should see this: https://stackoverflow.com/questions/24033222/editable-multi-color-qlineedit – CCCC Sep 04 '21 at 06:46
  • It's for C++. Is there an easy way for PyQt? – sunynor Sep 04 '21 at 08:01
  • Can you please explain more specifically? – Ali Saad Sep 05 '21 at 21:05
  • Your question is unclear to me. Is the `
    ` tag used only for example purpose, or do you really want to display preformatted text? In the latter case, why don't you use something like this? `"I have 
    two        books.
    "` Otherwise, since HTML ignores multiple spaces, just use the [Non-breaking space](https://en.wikipedia.org/wiki/Non-breaking_space) entity: `"I have two        books."`
    – musicamante Sep 05 '21 at 23:50
  • Your second idea works in my program. Thanks for your comment :) – sunynor Sep 06 '21 at 00:47

0 Answers0