如何在QWebEngineView中设置背景图片

How to set a background image in QWebEngineView

我正在使用 QtWebEngineWidgets 中的 QWebEngineView 来显示图像,我想将其作为背景图像。但它没有显示任何内容。我该怎么做?

我也尝试了 QtWebKitWidgets 的 QWebView,但它仍然不起作用。

这是我的代码:

    view = QtWebEngineWidgets.QWebEngineView()
    html = """
    <html>
        <head>
            <style>
                body{background-image:url("D:\house.jpg");}
            </style>
        </head>
        <body></body>
    </html>"""

    view.setHtml(html)

我希望视图显示图像 house.jpg 作为背景,但它只显示白色 window

您必须指定 baseUrl:

view.setHtml(html, baseUrl='file://')

否则,它不会猜测如何处理 D:\... 地址。 在 linux 上测试,足以解决问题。

还要注意 windows 下的 \ 将被解释。为了安全起见写成html = r""" ... """,为了验证保存到file.html。

void QWebEnginePage::setHtml(const QString &html, const QUrl &baseUrl = QUrl())

Sets the content of this page to html. baseUrl is optional and used to resolve relative URLs in the document, such as referenced images or stylesheets.

测试于 Windows。

import sys
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5.QtCore import QTimer, QDateTime, QUrl

html = """
<html>
  <head>
    <meta charset="utf-8">
    <title>background-image</title>
    <style>
      body {
        background-image: url('file:///D:/_Qt/Python-Examples/_PyQt5/Image/logo.png');
        background-color: #c7b39b;               
      }
      p {
        color: #f00;
        font: bold italic 20pt 'Comic Sans MS';
      }
    </style>
  </head>
  <body>
    <p>Hello World</p>
  </body>
</html>
"""

def append():
    some_html = "<p>{}</p>".format(QDateTime.currentDateTime().toString())
    page.runJavaScript("document.body.innerHTML += '{}'".format(some_html)
    )


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

    view = QWebEngineView()

    timer = QTimer()
    timer.timeout.connect(append)
    page = view.page()
    page.loadFinished.connect(lambda: timer.start(1000))

    page.setHtml(html, baseUrl=QUrl('file://'))                   # <---

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