1

为了使这更容易。我将如何打印到 QPlainTextEdit 列表

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

为每个单词使用不同的颜色?

4

1 回答 1

3

要更改文本的颜色,您可以使用:

  • QTextChar 格式:
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_())

在此处输入图像描述

  • 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_())

在此处输入图像描述

于 2019-09-07T23:25:36.250 回答