Reputation: 9624
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
Upvotes: 1
Views: 910
Reputation: 53173
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?'''
Upvotes: 2
Reputation: 2801
Use QTextEdit.textCursor
to get the cursor, then use QTextCursor.setCharFormat
to set format.
resultbox = QtGui.QTextEdit()
text = 'example'
if condition1:
resultbox.append(text) '''Append text to resultbox in default color.'''
elif condition2:
resultbox.textCursor().setCharFormat(specialFormat)
resultbox.append(text) '''Append the text in say, red and not the default black. How?'''
resultbox.textCursor().setCharFormat(defaultFormat)
Or you can use QTextEdit.insertHtml
to insert some HTML code into text, which you can specify the color by style
attribute.
Upvotes: 1