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

标签 python python-3.x pyqt pyqt5 qwebengineview

我有一个通过渲染 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

最佳答案

QWebEngineView 当您使用 setHtml() 方法不处理 url 时,解决方法是使用 javascript 加载 css,如下所示:

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

ma​​in.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;
}

enter image description here

关于python - CSS 在 QWebEngineView.setHtml() 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51388443/

相关文章:

python - Python告诉我语法错误,请解释

python - 使用 os.scandir() 引发 AttributeError : __exit__

python - 调试: Crawled (404) <GET >

python - 如何获取当前类对象的引用?

python - 在 PlotWidget GUI 中运行实时 pyqtgraph

python - pyqt 和 qt 设计器的最小示例 qtreeview

python - 模拟补丁不适用于 __init__.py 中的类

python - 使用动态键创建 pydantic 模型

python - Subprocess.call 或 Subprocess.Popen 不能使用 PATH (Linux/Windows) 中的可执行文件

python - 在 python 中使用 selenium 选择复选框