-1

I am trying to figure out how to color the text using TextEdit in a line Edit, but for any new text I will choose the color. Let's say if it is an error I want it to be red or for warning I want it to be yellow and in a normal case to remain black. Also if there is a possibility to highlight the text in color red let's say.

self.main_window.textEdit.append(get_proj)

I am using the command above to append the text in the QlineEdit, is there something I can use with TextEdit to color the text?

Mihai
  • 19
  • 1
  • 5

1 Answers1

3

The question is quite ambiguous since you are using both the terms QLineEdit and QTextEdit which are essentially two different type of widgets, I'm assuming its QTextEdit widget since QLineEdit does not have an associated method named append.

QTextEdit supports rich text, so you can use css styling with html for the texts in QTextEdit. You can append different rich texts with different styles. For ease, you can just create some formatted texts, and pass the corresponding text to the format method of python string for such formatted texts to create such rich texts, and append it to QTextEdit. Consider below example for your use case:

import sys
from PyQt5.QtWidgets import QTextEdit, QApplication

if __name__=='__main__':
    app = QApplication([])
    textEdit = QTextEdit()
    # Create formatted strings
    errorFormat = '<span style="color:red;">{}</span>'
    warningFormat = '<span style="color:orange;">{}</span>'
    validFormat = '<span style="color:green;">{}</span>'
    # Append different texts
    textEdit.append(errorFormat.format('This is erroneous text'))
    textEdit.append(warningFormat.format('This is warning text'))
    textEdit.append(validFormat.format('This is a valid text'))

    textEdit.show()
    sys.exit(app.exec_())

enter image description here

Additionally, if you want to color code the text for each new lines, QTextEdit has a textChanged signal, you can connect it to a method where you read the new line from QTextEdit and check for the validity of the text, and set the color accordingly.

ThePyGuy
  • 17,779
  • 5
  • 18
  • 45
  • This is working very good, i just tested :) and yes i use QTextEdit but the information is written in a line edit so my mistake. 1 more question would be how to do the same thing but to set the background color of the text like it would be highlighted? is this possible? – Mihai Sep 02 '21 at 14:54
  • 1
    @Mihai If that's a mistake, I suggest you to [edit](https://stackoverflow.com/posts/69032042/edit) the question and use the proper terms only in order to avoid ambiguity for future readers. – ThePyGuy Sep 02 '21 at 14:56
  • just edited my answer to fit both questions. – Mihai Sep 02 '21 at 15:04
  • 1
    Nice answer. I like how you used orange for warning instead of yellow. Yellow is very hard to see on white background. – bfris Sep 02 '21 at 16:01
  • @bfris, yeah default `yellow` is very bright and barely visible. – ThePyGuy Sep 02 '21 at 16:02