简体   繁体   English

Python PyQt5打印多色到plaintextedit

[英]Python PyQt5 print multi-color to plaintextedit

To make this easier. 为了使这更容易。 How would I print to a QPlainTextEdit the list 我将如何打印到QPlainTextEdit列表

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

using a different color for each word? 每个单词使用不同的颜色?

To change the color of the text you can use: 要更改可以使用的文本颜色:

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

在此输入图像描述

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

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM