Namespaces

Variants
Actions

Please note that as of October 24, 2014, the Nokia Developer Wiki will no longer be accepting user contributions, including new entries, edits and comments, as we begin transitioning to our new home, in the Windows Phone Development Wiki. We plan to move over the majority of the existing entries over the next few weeks. Thanks for all your past and future contributions.

在QML 中使用cache 优化程序性能

From Wiki
Jump to: navigation, search
Article Metadata

代码示例
文章
liuting 在 04 Jan 2012 创建
最后由 renlin 在 11 Jul 2012 编辑

Contents

介绍

QML 提供了非常方便的方法去访问网络资源,例如我们可以通过设置image elemnent的URL属性去从网络加载图片,但是我们会发现网络资源总是重复加载,对于桌面应用,网络速度较快,重复加载可能不是一个问题,但对于在移动设备上的应用,网络连接较慢,且开销较大,我们就不得不考虑使用cache 避免重复加载的问题,每个 QDeclarativeView 用一个 QDeclarativeEngine 实例化对象去实例化QML component. QDeclarativeEngine用 QDeclarativeNetworkAccessManagerFactory去 创建QNetworkAccessManagers,为了使用CACHE,我们需要重写 QDeclarativeNetworkAccessManagerFactory 的 create方法,下面我门用通过代码来看具体的实现过程.

代码实现

首先我们需要定义一个类派生自QDeclarativeNetworkAccessManagerFactory,具体代码如下:

#ifndef NETWORKACCESSMANAGERFACTORY_H
#define NETWORKACCESSMANAGERFACTORY_H
 
#include <QDeclarativeNetworkAccessManagerFactory>
#include <QNetworkAccessManager>
 
class NetworkAccessManagerFactory : public QDeclarativeNetworkAccessManagerFactory
{
public:
explicit NetworkAccessManagerFactory();
 
virtual QNetworkAccessManager* create(QObject* parent);
};
 
#endif // NETWORKACCESSMANAGERFACTORY_H

接下来我们需要实现create方法,在其中创建cache

NetworkAccessManagerFactory::NetworkAccessManagerFactory() :
QDeclarativeNetworkAccessManagerFactory()
{
}
 
QNetworkAccessManager* NetworkAccessManagerFactory::create(QObject* parent)
{
QNetworkAccessManager* manager = new QNetworkAccessManager(parent);
QNetworkDiskCache* diskCache = new QNetworkDiskCache(parent);
 
QString dataPath = QDesktopServices::storageLocation(QDesktopServices::CacheLocation);
QDir().mkpath(dataPath);
diskCache->setCacheDirectory(dataPath);
diskCache->setMaximumCacheSize(10*1024*1024);
 
manager->setCache(diskCache);
 
return manager;
}

最后我们再看下在QML 中如何实现 cache,在main.cpp中添加如下代码:

NetworkAccessManagerFactory factory;
QmlApplicationViewer viewer;
viewer.engine()->setNetworkAccessManagerFactory(&factory);
viewer.setMainQmlFile(QLatin1String("qml/QmlNetworkCache/main.qml"));
viewer.showExpanded();
int retval = app.exec();
// Clear the cache at exi
viewer.engine()->networkAccessManager()->cache()->clear();
return retval;

运行效果

程序运行的结果如上图所示,如果我们不使用CACHE 运行这个例子,我们将发现当点击LISTVIEW中的ITEM ,IAMGE将会被重复加栽.<\r> Qmlnetworkcache.png

代码下载

相关连接

This page was last modified on 11 July 2012, at 03:20.
548 page views in the last 30 days.

Was this page helpful?

Your feedback about this content is important. Let us know what you think.

 

Thank you!

We appreciate your feedback.

×