使用 Python PyQt5 的 QTextDocument 类可以方便地读取包含图片和格式的 HTML 文件,并将其显示在 QTextEdit 控件中。以下是一个示例代码,演示如何使用 setHtml 接口将 HTML 内容设置为 QTextDocument 对象,并最终显示在 QTextEdit 控件上。

from PyQt5.QtWidgets import QApplication, QTextEdit
from PyQt5.QtGui import QTextDocument

# 读取 .html 文件中的内容
with open('file.html', 'r') as file:
    html_content = file.read()

# 创建 QTextDocument 对象
document = QTextDocument()

# 使用 setHtml 接口设置 HTML 内容
document.setHtml(html_content)

# 创建 QTextEdit 对象,并将 QTextDocument 对象设置为其文档
text_edit = QTextEdit()
text_edit.setDocument(document)

# 显示窗口
app = QApplication([])
text_edit.show()
app.exec_()

在上面的代码中,需要将 'file.html' 替换为实际的 .html 文件路径。然后使用 setHtml 接口将读取到的 HTML 内容设置到 QTextDocument 对象中。最后,将 QTextDocument 对象设置为 QTextEdit 的文档,即可显示 HTML 内容。

Python PyQt5 使用 QTextDocument 显示带图片和格式的 HTML 文件

原文地址: https://www.cveoy.top/t/topic/pY8v 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录