I am writing a simple WebView app in QT 5.2. The website I am using is a bit heavy, therefore I need to cache it. But the problem is that when clicking on a page and visiting sub pages, I am getting QIODevice::read: device not open
errors. At the end I end up with a blank, white page. Where did I go wrong?
Here's the code:
WebsiteWidget::WebsiteWidget(QWidget *parent) :
QWidget(parent)
{
m_url = QUrl("http://www.google.com/");
QWebSettings::globalSettings()->setAttribute(QWebSettings::DeveloperExtrasEnabled, true);
QWebSettings::globalSettings()->setAttribute(QWebSettings::LocalStorageEnabled, true);
QWebSettings::globalSettings()->setAttribute(QWebSettings::JavascriptEnabled, true);
QWebSettings::globalSettings()->setAttribute(QWebSettings::PluginsEnabled, true);
m_websiteContentLayout = new QHBoxLayout();
m_webView = new QWebView(this);
QNetworkAccessManager* manager = new QNetworkAccessManager(this);
QNetworkDiskCache* diskCache = new QNetworkDiskCache(this);
QString location = QStandardPaths::writableLocation(QStandardPaths::CacheLocation);
diskCache->setCacheDirectory(location);
manager->setCache(diskCache);
m_webView->page()->setNetworkAccessManager(manager);
m_webView->page()->settings()->setMaximumPagesInCache(10);
QNetworkRequest request = QNetworkRequest();
request.setAttribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferCache);
request.setUrl(m_url);
connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*)));
manager->get(request);
m_websiteContentLayout->addWidget(m_webView);
m_websiteContentLayout->setContentsMargins(0, 0, 0, 0);
this->setLayout(m_websiteContentLayout);
}
void WebsiteWidget::replyFinished(QNetworkReply* reply)
{
QByteArray data=reply->readAll();
QString str(data);
if(reply->url() == m_url)
{
m_webView->setHtml(str, reply->url());
}
}
For me it was a problem with redirects (like www.xbox.com gives you xbox.com:80/en-US/) which gave me a response with 0 bytes length, just a header. I needed to handle that as well.