QWebView doesn't load any external resources if it loads a html-file from qresources
As described in the title my problem is that qwebview doesn't load a html file correctly if it resides in my resources. It loads it perfectly if I load it from outside of the resources as normal local file. But this is not an option for me. I would like to bundle the file with the application.
EDIT: By the way, I'm talkin' about external resources from the web. (e.g. http://host.org/somejavascript.js) Thanks fo开发者_开发技巧r any help
Please take a look at the second parameter of
void QWebView::setHtml ( const QString & html, const QUrl & baseUrl = QUrl() )
According to documentation:
External objects such as stylesheets or images referenced in the HTML document are located relative to baseUrl.
Below is code that works for me.
#include <QtCore/QFile>
#include <QtCore/QUrl>
#include <QtGui/QApplication>
#include <QtGui/QMainWindow>
#include <QtWebKit/QWebView>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QMainWindow window;
QWebView webview(&window);
QFile source(":/google.com.html");
source.open(QIODevice::ReadOnly);
webview.setHtml(QString::fromUtf8(source.readAll().constData()), QUrl("http://google.com"));
window.setCentralWidget(&webview);
window.show();
return app.exec();
}
External URLs must have a schema to make them external, otherwise "external.org/script.js" looks for "script.js" under the "external.org/" sub-path, "http://external.org/script.js" is an absolute URL.
Edit:
Say you have this HTML file as the resource ":/file.html" and it is coppied from "http://example.com/":
<html>
<head>
<title>My HTML</title>
<script type="text/javascript" src="/code.js"></scipt>
</head>
<body>
<img href="/image.jpg" />
</body>
</html>
Then to display this correctly you would need to do the following:
QFile res(":/file.html");
res.open(QIODevice::ReadOnly|QIODevice::Text);
my_webview.setHtml(res.readAll(), QUrl("http://example.com/");
That way, WebKit knows where to fetch "code.js" and "image.jpg" from. Using QWebView::load()
will not work, as the root URL will be some internal URL, the one starting with qrc://, and WebKit will look for "code.js" and "image.jpg" in your applications resources. Basically, you can only use load()
when all the relative URLs in the document come from the same place as the URL is pointing to. And if you used load(QUrl("qrc:///file.html"));
in the case above, the URL (qrc:///file.html
) is pointing to your resource system.
If you want to also include your resources in the HTML, you can use the qrc:// URLs in the HTML file.
精彩评论