QWebView 不加载外部 CSS
我正在使用 QWebView 来显示一些内容,并且我想使用自定义 CSS 来美化输出。我发现我可以使用 QWebSettings.setUserStyleSheetUrl() 方法将我自己的 CSS 加载到视图中。 .css
文件与我的主程序位于同一目录中。
self.webview = QWebView(MainWindow)
self.webview.settings().setUserStyleSheetUrl(QUrl.fromLocalFile("myCustom.css"))
但是,当我使用 setHtml()
将内容添加到页面时,自定义样式不会加载。我已经测试过 CSS 可以正确应用于标准浏览器中的 HTML。
知道我做错了什么吗?
I am using a QWebView to display some content and I want to use custom CSS to spruce up the output. I found that I can use the QWebSettings.setUserStyleSheetUrl()
method to load my own CSS into the view. The .css
file is in the same directory as my main program.
self.webview = QWebView(MainWindow)
self.webview.settings().setUserStyleSheetUrl(QUrl.fromLocalFile("myCustom.css"))
However, the custom stylings don't load when I add the content to the page using setHtml()
. I have tested that the CSS is properly applying to the HTML in a standard browser.
Any idea what I am doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 Qt 中,外部文件的所有路径都必须是绝对路径,而不是相对路径。
为了解决这个问题,我添加了以下更改:
并且一切正常。希望这会对将来的人有所帮助,并节省他们几个小时的调试时间。
In Qt, all paths to external files need to be ABSOLUTE paths, not relative ones.
To fix the problem, I add to make the following change:
And everything worked correctly. Hopefully this will help someone in the future and save them a few hours debugging.
那不是真的。下面的代码对我有用。
相对路径是相对于当前工作目录进行解释的,该目录不必与可执行文件的目录相同。
That's not true. The code below works for me.
Relative paths are interpreted relative to the current working directory which need not be the same as executable's directory.
我刚刚遇到这个问题,所以我将在这里发布我的测试片段;该代码片段在与 python 脚本相同的目录中生成自己的 .html 和 .css 文件;并且从同一目录调用脚本进行测试。
至少在
python
/PyQt4
中,似乎 - 事实上 - 只有绝对路径可以与setHtml
一起使用。测试代码可以:
QWebView
吐出一些错误消息;发现当 QTWebKit 加载页面失败时如何获取详细的错误消息?,但无法让它工作]);setHtml
方法似乎显示样式文本仅适用于规范c3
,其中使用file://
+ 绝对路径。 (编辑:只是想指出这篇文章中的建议,“尝试arora(QtWebKit 之上的一个非常简单的包装);如果它有效,那么它就是您的代码。如果它不起作用,它的网站。”对于双重检查行为非常有帮助)这是测试脚本的设置:
脚本是:
qtwebkit-test.py
I just ran into this, so I'll post my test snippet here; the snippet generates its own .html and .css file in the same directory as the python script; and the script was called from the same directory for testing.
At least in
python
/PyQt4
, it seems that - indeed - it is only absolute paths that work withsetHtml
.The test code can either:
QWebView
to spit out some error messages; found How to get detailed error message when QTWebKit fails to load a page?, but cannot get it to work]);The
setHtml
method seems to show styled text only with specificationc3
, wherefile://
+ absolute path is used. (EDIT: just wanted to note that the suggestion in this post, to "try arora (a very simple wrapping on top of QtWebKit); if it works, its your code. if it doesn't, its the website." was very helpful for double-checking behaviour)This is the setup the script was tested on:
The script is:
qtwebkit-test.py