Python PyQt5将多色打印到明文edi

2024-04-18 07:44:40 发布

您现在位置:Python中文网/ 问答频道 /正文

让这更容易。如何打印到QPlainTextEdit列表

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

每个单词用不同的颜色?你知道吗


Tags: the列表颜色quick单词lazyoverdog
1条回答
网友
1楼 · 发布于 2024-04-18 07:44:40

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

  • 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

相关问题 更多 >