在 QTextEdit 中更改搜索路径

Change search path in QTextEdit

我读过有关 QTextBrowser 的文章,您可以在其中添加 SearchPaths。有没有办法在 QTextEdit 中实现同样的功能?

背景:

我想在 QTextEdit 中加载一个 HTML 文件。使用 .setHtml 它加载文本,但不加载图像。任何浏览器都能正确加载所有内容。 例子 html:

<img src="b69b37f9a55946e38923b760ab86ee71.png" />

我发现 Python/Qt 找不到图像,因为它需要完整路径。但是,我不想在 html 文件中保存完整路径。 (因为稍后我可能会更改位置)。

如果我使用 os.chdir() 更改工作目录,它会加载图像,但如果我将其更改回来,则图像不会再次显示。此外,此解决方案似乎非常棘手。

QTextBrowser 的searchPaths() 方法与您想要的无关,因为它有另一个目标。


另一方面,使用与 QTextDocument::DocumentUrl 关联的 url 解析相对路由,如 the docs:

所示

QTextDocument::DocumentTitle 0 The title of the document.
QTextDocument::DocumentUrl   1 The url of the document. The loadResource() function uses this url as the base when loading relative resources.

此外,这种行为很容易在 the implementation 中观察到。

所以解决方法是设置图片所在目录的路径:

import sys

from PyQt5 import QtCore, QtGui, QtWidgets

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)

    w = QtWidgets.QTextEdit()
    w.resize(640, 480)
    w.show()

    directory = "/path/of/image_directory"
    w.document().setMetaInformation(
        QtGui.QTextDocument.DocumentUrl,
        QtCore.QUrl.fromLocalFile(directory).toString() + "/",
    )

    HTML = """<img src="b69b37f9a55946e38923b760ab86ee71.png"/>"""
    w.setHtml(HTML)

    sys.exit(app.exec_())