我刚遇到这个,所以我将在这里发布我的测试片段;该片段在与 python 脚本相同的目录中生成自己的 .html 和 .css 文件;并且从同一目录调用脚本进行测试。
至少在python
/PyQt4
中,似乎 - 实际上 -只有绝对路径才能使用setHtml
。
测试代码可以:
该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()