QWebView doesn't load any external resources if it loads a html-file from qresources

Deadly 提交于 2019-12-23 09:41:01

问题


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 for any help


回答1:


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();
}



回答2:


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.



来源:https://stackoverflow.com/questions/5126294/qwebview-doesnt-load-any-external-resources-if-it-loads-a-html-file-from-qresou

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!