Question

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());
    }
}
Was it helpful?

Solution 2

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.

OTHER TIPS

I've got the offline storage working after I made:

webView->settings()->setAttribute(QWebSettings::LocalStorageEnabled, true); webView->settings()->enablePersistentStorage(QDir::homePath());

Other settings (setOfflineStorageDefaultQuota e.t.c.) seem to be optional. (one may want to change homePath to something better like tmpPath etc)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top