3

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?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Halloween
  • 388
  • 3
  • 15

1 Answers1

6

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

eyllanesc
  • 235,170
  • 19
  • 170
  • 241