I am trying to display a fragment of the string in the desired color. I set the color in the format method. It is displayed only in the print () function. Why is not displayed in the rows of PyQt5 widgets? enter image description here

from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QTextEdit, QLabel import sys app = QApplication(sys.argv) window = QWidget() window.resize(300, 100) word = "{blue}{0}{endcolor} {1}"\ .format("-ABC def-", "1111", blue='\033[96m', endcolor='\033[0m') print(word) txt = QTextEdit(word) lbl = QLabel(word) vbox = QVBoxLayout() vbox.addWidget(txt) vbox.addWidget(lbl) window.setLayout(vbox) window.show() sys.exit(app.exec_()) 

1 answer 1

Because, in QLabel and QTextEdit for colored text, you need to write HTML, and in the console, the color stood out just because it is a console:

 word = '<font color="blue">{0}</font> {1}'.format("-ABC def-", "1111") 

Result:

enter image description here

  • Thank! If I specify the width and color in the format method, why is the width not working? word = '<font color="red">{0:15}</font> {1:15}'.format("-ABC def-", "1111") - Frantisek
  • because, this is HTML, and there extra spaces are ignored, so each space needs to be replaced by &nbsp; , or in a special tag to display your text: htmlbook.ru/html/pre - gil9red
  • Thank! I would not have thought that it was a html, I was sure that the PyQt feature. - František
  • Then mark the answer as correct - gil9red
  • "because it is a console", which supports VT100 terminal sequences (which should be specifically included on Windows or something like the colorama module used). It is possible to implement colorama for QTextEdit. QTextEdit and colored bash-like output emulation - jfs