Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python PyQt5 print multi-color to plaintextedit

To make this easier. How would I print to a QPlainTextEdit the list

['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog'] 

using a different color for each word?

like image 382
Halloween Avatar asked Feb 22 '26 12:02

Halloween


1 Answers

To change the color of the text you can use:

  • QTextCharFormat:
import random
from PyQt5 import QtCore, QtGui, QtWidgets


if __name__ == "__main__":
    import sys

    names = ["The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"]

    app = QtWidgets.QApplication(sys.argv)

    w = QtWidgets.QPlainTextEdit()
    w.show()

    # save format
    old_format = w.currentCharFormat()

    for name in names:
        color = QtGui.QColor(*random.sample(range(255), 3))

        color_format = w.currentCharFormat()
        color_format.setForeground(color)
        w.setCurrentCharFormat(color_format)
        w.insertPlainText(name + "\n")

    # restore format
    w.setCurrentCharFormat(old_format)

    sys.exit(app.exec_())

enter image description here

  • Html
import random
from PyQt5 import QtCore, QtGui, QtWidgets


if __name__ == "__main__":
    import sys

    names = ["The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"]

    app = QtWidgets.QApplication(sys.argv)

    w = QtWidgets.QPlainTextEdit()
    w.show()

    for name in names:
        color = QtGui.QColor(*random.sample(range(255), 3))

        html = """<font color="{}"> {} </font>""".format(color.name(), name)
        w.appendHtml(html)

    sys.exit(app.exec_())

enter image description here

like image 98
eyllanesc Avatar answered Feb 25 '26 02:02

eyllanesc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!