Changing a single strings color within a QTextEdit

2020-03-19 03:22发布

问题:

I am working on a GUI developed via PyQt and Qt4. Within my GUI I have a QTextEdit that has various data written to. Is there a way in which I can manipulate the color of one word within the QTextEdit?

For example

redText = "I want this text red"
self.myTextEdit.write(redText)
blackText = "And this text black"
self.myTextEdit.append(blackText)

Is this possible? If so, how could I do this?

Regards,

sudo!!

回答1:

You should provide a rich text for it. It can be done by creating a <span> tag and setting the color property to an RGB value :

redText = "<span style=\" font-size:8pt; font-weight:600; color:#ff0000;\" >"
redText.append("I want this text red")
redText.append("</span>")
self.myTextEdit.write(redText)

blackText = "<span style=\" font-size:8pt; font-weight:600; color:#000000;\" >"
blackText.append("And this text black")
blackText.append("</span>")
self.myTextEdit.append(blackText)


回答2:

After some research into other methods people have used, I figured it out and wanted to share. I tried the ".setHtml" function with the QTextEdit, but it didn't work.

I figured out you can change the text color, add your text and then change it again and any text that's added after you've changed the color turns to that color, but nothing else.

Here's an example.

redColor = QColor(255, 0, 0)
blackColor = QColor(0, 0, 0)

self.myTextEdit.setTextColor(redColor)

redText = "I want this text red"
self.myTextEdit.write(redText)


self.myTextEdit.setTextColor(blackColor)

blackText = "And this text black"
self.myTextEdit.append(blackText)

And also, I want to add. ".write" and ".append" functions don't work for my "QTextEdit" class. Not sure if yours do, but what worked for me was the ".insertPlainText" function. Just convert your string to a "QString" like so

blackText = QString(blackText)


回答3:

The answer of Nejat works for me by replacing ".append()" with "+=" :

redText = "<span style=\" font-size:8pt; font-weight:600; color:#ff0000;\" >"
redText += "I want this text red"
redText += "</span>"
self.myTextEdit.write(redText)

blackText = "<span style=\" font-size:8pt; font-weight:600; color:#000000;\" >"
blackText += "And this text black")
blackText += "</span>"
self.myTextEdit.append(blackText)