CSS doesn't work in QWebEngineView.setHtml()

我的未来我决定 提交于 2021-01-28 08:20:22

问题


I have a string obtained from rendering a Jinja template. In the template I have the absolute path to the css file. For example:

<link rel='stylesheet' href="C:\Users\User\project\reports\template\css">

But, when I set the html in QWebEngineView only appear the plain HTML, without CSS. How can I make to detect the css reference?

This is my code

class WidgetEdificioCirsoc(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()

        self._tab_edificio = widgets.TabEdificio()
        self._webview = QtWebEngineWidgets.QWebEngineView()
        layout_horizontal_principal = QtWidgets.QHBoxLayout()
        layout_horizontal_principal.addWidget(self._tab_edificio)
        layout_horizontal_principal.addWidget(self._webview)
        self.setLayout(layout_horizontal_principal)

    def calcular(self):
        edificio = self._tab_edificio()
        reporte = edificio.reporte.html() # Generate the string
        self._webview.setHtml(reporte) # Set the string

回答1:


QWebEngineView when you use setHtml() method does not handle the urls, a workaround is to load the css using javascript as shown below:

.
├── main.py
└── css
    └── styles.css

main.py

from PyQt5 import QtWebEngineWidgets, QtWidgets, QtCore

def loadCSS(view, path, name):
    path = QtCore.QFile(path)
    if not path.open(QtCore.QFile.ReadOnly | QtCore.QFile.Text):
        return
    css = path.readAll().data().decode("utf-8")
    SCRIPT = """
    (function() {
    css = document.createElement('style');
    css.type = 'text/css';
    css.id = "%s";
    document.head.appendChild(css);
    css.innerText = `%s`;
    })()
    """ % (name, css)

    script = QtWebEngineWidgets.QWebEngineScript()
    view.page().runJavaScript(SCRIPT, QtWebEngineWidgets.QWebEngineScript.ApplicationWorld)
    script.setName(name)
    script.setSourceCode(SCRIPT)
    script.setInjectionPoint(QtWebEngineWidgets.QWebEngineScript.DocumentReady)
    script.setRunsOnSubFrames(True)
    script.setWorldId(QtWebEngineWidgets.QWebEngineScript.ApplicationWorld)
    view.page().scripts().insert(script)


HTML = """
<!DOCTYPE html>
<html>
<head>
</head>
<body>

<h1>I am formatted with a style sheet</h1>
<p>Me too!</p>

</body>
</html>
"""

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    view = QtWebEngineWidgets.QWebEngineView()
    view.setHtml(HTML, QtCore.QUrl("index.html"))

    loadCSS(view, "css/styles.css", "script1")

    view.show()
    sys.exit(app.exec_())

css/styles.css

body {
    background-color: lightblue;
}

h1 {
    color: white;
    text-align: center;
}

p {
    font-family: verdana;
    font-size: 20px;
}



来源:https://stackoverflow.com/questions/51388443/css-doesnt-work-in-qwebengineview-sethtml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!