PyQt5-CSS在QWebEngineView.setHtml()中不起作用

时间:2018-07-17 18:52:20

标签: python-3.x pyqt5

我有一个通过渲染Jinja模板获得的字符串。在模板中,我具有css文件的绝对路径。例如:

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

但是,当我在QWebEngineView中设置html时,仅显示纯HTML,没有CSS。 我该如何检测CSS参考?

这是我的代码

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 个答案:

答案 0 :(得分:1)

QWebEngineView当您使用setHtml()方法无法处理网址时,一种解决方法是使用javascript加载CSS,如下所示:

.
├── 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;
}

here