QWebView不加载外部CSS

4 投票
3 回答
7579 浏览
提问于 2025-04-15 19:32

我正在使用QWebView来显示一些内容,并且想用自定义的CSS来美化输出。我发现可以用QWebSettings.setUserStyleSheetUrl()这个方法把自己的CSS加载到视图中。这个.css文件和我的主程序在同一个文件夹里。

self.webview = QWebView(MainWindow)
self.webview.settings().setUserStyleSheetUrl(QUrl.fromLocalFile("myCustom.css"))

不过,当我用setHtml()方法把内容添加到页面时,自定义的样式并没有加载。我已经测试过,CSS在普通浏览器中能正常应用到HTML上。

你知道我哪里做错了吗?

3 个回答

1

我刚遇到这个问题,所以我把我的测试代码放在这里;这个代码会在和python脚本同一个文件夹里生成自己的.html和.css文件;而且这个脚本是在同一个文件夹里测试的。

至少在 pythonPyQt4 中,似乎只有绝对路径才能和 setHtml 一起正常工作。

测试代码可能会有以下几种情况:

  • 完全失败(完全空白 [在这种情况下,我真希望 QWebView 能给我一些错误信息;我找到了一些方法 来获取详细的错误信息,但我无法让它工作]);
  • 显示内容但没有css样式;
  • 或者显示带样式的内容:

compare_qtwebkit-test.py

setHtml 方法似乎只有在使用 c3 这个指定时,才能显示带样式的文本,这时需要用到 file:// 加上绝对路径。 (补充:我想提一下,这篇文章中提到的建议,去试试 arora(一个非常简单的QtWebKit封装);如果它能工作,那就是你的代码有问题。如果不行,那就是网站的问题。)

这是测试脚本的设置:

$ lsb_release --description --codename 
Description:    Ubuntu 11.04
Codename:   natty

$ apt-show-versions -r python-qt4
python-qt4/natty uptodate 4.8.3-2
python-qt4-dbus/natty uptodate 4.8.3-2

$ apt-show-versions -r libqtwebkit4
libqtwebkit4/natty uptodate 2.1~really2.0.2-0ubuntu1

$ python --version
Python 2.7.1+

脚本是:

qtwebkit-test.py

#!/usr/bin/env python

# portions from:
# http://pysnippet.blogspot.com/2010/01/more-fun-with-qwebkit.html

import sys
import os
from PyQt4 import QtCore
from PyQt4 import QtGui
from PyQt4 import QtWebKit

global htmltext

def GenerateFiles():
  global htmltext

  print "GenerateFiles running"

  csstext = """
  body {
    background-color: #058;
    margin: 0px;
    color: red;
  }
  """

  css_file = open("test.css", "w")
  css_file.write(csstext)
  css_file.close()


  htmltextTop = """
  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  <html>
  <head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  """

  htmltextBottom = """
  <title>qtwebkit-test</title>
  </head>
  <body>
  <h1>HEADING</h1>
  <p>Just to test ....</p>
  <p>.... and test some more</p>
  </body>
  </html>
  """

  cssopen = '<link rel="stylesheet" type="text/css" href="'
  cssclose = '">'

  # c1
  cssfile = "test.css"
  # c2
  #~ cssfile = os.path.abspath(os.path.dirname(__file__)) + "/" + "test.css"
  # c3
  #~ cssfile = "file://" + os.path.abspath(os.path.dirname(__file__)) + "/" + "test.css"
  # c4
  #~ cssfile = "qrc://" + os.path.abspath(os.path.dirname(__file__)) + "/" + "test.css"
  # c5 (empty)
  #~ cssfile = ""

  cssline = cssopen + cssfile + cssclose

  #~ htmltext = htmltextTop + htmltextBottom      # without css
  htmltext = htmltextTop + cssline + htmltextBottom

  html_file = open("test.html", "w")
  html_file.write(htmltext)
  html_file.close()


def main():
  global htmltext

  GenerateFiles()
  qApp = QtGui.QApplication(sys.argv)

  webView = QtWebKit.QWebView()

  # l1
  #~ webView.load(QtCore.QUrl.fromLocalFile("test.html")) # fails

  # l2
  #~ webView.load(QtCore.QUrl.fromLocalFile("./test.html")) # fails

  # l3
  #~ webView.load(QtCore.QUrl.fromLocalFile(os.path.abspath(os.path.dirname(__file__)) + "/" + "test.html")) # this works with #c1-#c3

  # setHtml
  #print htmltext
  webView.setHtml(htmltext) # works with #c3 (rest are unstyled)

  webView.show()
  webView.resize(500, 400)
  webView.setWindowTitle(__file__)
  sys.exit(qApp.exec_())


if __name__ == "__main__":
    main()
1

在Qt中,所有指向外部文件的路径都需要是绝对路径,而不是相对路径。

这并不完全正确。下面的代码对我来说是有效的。

#include <QtCore>
#include <QtGui>
#include <QtWebKit>

int main(int argc, char ** argv)
{
    QApplication app(argc, argv);

    QMainWindow mainWindow;

    QWebView* webView = new QWebView(&mainWindow);
    webView->settings()->setUserStyleSheetUrl(QUrl::fromLocalFile("google.css"));

    QFile source("google.html");
    source.open(QIODevice::ReadOnly);
    webView->page()->mainFrame()->setHtml(QString::fromUtf8(source.readAll().constData()));

    mainWindow.setCentralWidget(webView);
    mainWindow.show();

    return app.exec();
}

这个.css文件和我的主程序在同一个文件夹里。

相对路径是根据当前工作目录来解释的,而这个工作目录不一定和程序的目录是一样的。

8

在Qt中,所有指向外部文件的路径都需要是绝对路径,而不是相对路径。

为了解决这个问题,我做了以下更改:

path = os.getcwd()
self.webview.settings().setUserStyleSheetUrl(QUrl.fromLocalFile(path + "/myCustom.css"))

然后一切都正常工作了。希望这能帮助将来的人,节省他们几个小时的调试时间。

撰写回答