pythonhtmlpyqtqtexteditqtextdocument

Change search path in QTextEdit


I've read about QTextBrowser, where you can add SearchPaths. Is there a way to implement the same thing in QTextEdit?

Background:

I want to load a HTML file in QTextEdit. Using .setHtml it loads the text, but not the images. Any browser loads everything correctly. Example html:

<img src="b69b37f9a55946e38923b760ab86ee71.png" />

I figured out, that Python/Qt can't find the image, because it needs the full path. However, I dont want to save the full path in my html file. (Because later on I might change the location).

If I change the working directory with os.chdir(), it loads the image, but if I change it back, the image isnt shown once again. Also this solutions seems very tricky.


Solution

  • QTextBrowser's searchPaths() method has nothing to do with what you want since it has another goal.


    On the other hand, the relative routes are resolved using the url associated with QTextDocument::DocumentUrl as indicated by 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.

    In addition, this behavior is easily observed in the implementation.

    So the solution is to set the path of the directory where the image is:

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