Search code examples
pythonpyqt5qt-designerqlineedittextcolor

I want to add a color for the text for every new line added PyQt5


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?


Solution

  • 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.