Search code examples
pythonqtpython-2.7pyqt4qtextedit

How can I set selectively set the foreground color of a text in PyQt4


So, I have a QtGui.QTextEdit that I want to append with text based on some condition. For eg:

resultbox = QtGui.QTextEdit()
text = 'example'
if condition1:
    resultbox.append(text) '''Append text to resultbox in default color.'''
elif condition2:
    resultbox.append(text) '''Append the text in say, red and not the default black. How?'''

I am looking for something like a setForegroundColor(QtColor) method on QString(text) that will allow me to set the foreground color for the text.

I tried to work with stylehseets in PyQt4 by setting a color for the QTextEdit, but that won't allow me to selectively color the text, right?

Is there a way I can accomplish this?

Thanks


Solution

  • QTextEdit can handle regular html content, so you could use the following to achieve your desire:

    resultbox = QtGui.QTextEdit()
    text = 'example'
    if condition1:
        resultbox.insertText(text) '''Append text to resultbox in default color.'''
    elif condition2:
        resultbox.insertHtml(QString("<font color=\"red\">%1</font>").arg(text)) '''Append the text in say, red and not the default black. How?'''