QNetworkDiskCache Class▲
-
Header: QNetworkDiskCache
-
Since: Qt 4.5
-
qmake: QT += network
-
Inherits: QAbstractNetworkCache
Detailed Description▲
QNetworkDiskCache stores each url in its own file inside of the cacheDirectory using QDataStream. Files with a text MimeType are compressed using qCompress. Data is written to disk only in insert() and updateMetaData().
Currently you cannot share the same cache files with more than one disk cache.
QNetworkDiskCache by default limits the amount of space that the cache will use on the system to 50MB.
Note you have to set the cache directory before it will work.
A network disk cache can be enabled by:
QNetworkAccessManager *
manager =
new
QNetworkAccessManager(this
);
QNetworkDiskCache *
diskCache =
new
QNetworkDiskCache(this
);
diskCache-&
gt;setCacheDirectory("cacheDir"
);
manager-&
gt;setCache(diskCache);
When sending requests, to control the preference of when to use the cache and when to use the network, consider the following:
// do a normal request (preferred from network, as this is the default)
QNetworkRequest request(QUrl(QString("http://qt-project.org"
)));
manager-&
gt;get(request);
// do a request preferred from cache
QNetworkRequest request2(QUrl(QString("http://qt-project.org"
)));
request2.setAttribute(QNetworkRequest::
CacheLoadControlAttribute, QNetworkRequest::
PreferCache);
manager-&
gt;get(request2);
To check whether the response came from the cache or from the network, the following can be applied:
void
replyFinished(QNetworkReply *
reply) {
QVariant fromCache =
reply-&
gt;attribute(QNetworkRequest::
SourceIsFromCacheAttribute);
qDebug() &
lt;&
lt; "page from cache?"
&
lt;&
lt; fromCache.toBool();
}
Member Function Documentation▲
[explicit] QNetworkDiskCache::QNetworkDiskCache(QObject *parent = nullptr)▲
Creates a new disk cache. The parent argument is passed to QAbstractNetworkCache's constructor.
[virtual] QNetworkDiskCache::~QNetworkDiskCache()▲
Destroys the cache object. This does not clear the disk cache.
QString QNetworkDiskCache::cacheDirectory() const▲
[override virtual] qint64 QNetworkDiskCache::cacheSize() const▲
Reimplements: QAbstractNetworkCache::cacheSize() const.
[override virtual] void QNetworkDiskCache::clear()▲
Reimplements: QAbstractNetworkCache::clear().