{{class|KPixmapCache}} provides disk-caching of QPixmaps. If you're using SVGs or generating pixmaps from some data, you might consider using it as it eliminates the need to generate the same pixmaps over and over again.

{{class|KPixmapCache}} provides disk-caching of QPixmaps. If you're using SVGs or generating pixmaps from some data, you might consider using it as it eliminates the need to generate the same pixmaps over and over again.

Latest revision as of 09:17, 14 July 2012

Contents

KPixmapCache provides disk-caching of QPixmaps. If you're using SVGs or generating pixmaps from some data, you might consider using it as it eliminates the need to generate the same pixmaps over and over again.

Once that is done you can easily retrieve and insert images with insert() and find() methods:

QPixmap pix("file1.png");
cache->insert("file1.png", pix);QPixmap pix2;if(cache->find("file2.png", pix2)){// The pixmap was loaded from cache.}else{// Pixmap was not found in the cache.// Load and insert it:
pix2 =QPixmap("file2.png");
cache->insert("file2.png", pix2);}

Often you need to make sure the cache is up-to-date and you're not using obsolete pixmaps. For this, the cache provides timestamp() method. By default it returns time when the cache was created, but you can set your own timestamp with setTimestamp() method.

// Our data
MyDataObject data;// Make sure the cache is up to dateif(cache->timestamp()< data.timestamp()){// Data is newer than the cache// Thus the cache is obsolete, delete and reinitialize it
cache->discard();}// Here the cache is always recent enoughQPixmap visualizedData;QString key("data-visualization");// Try to find the visualization from the cacheif(!cache->find(key, visualizedData)){// Visualization is not in the cache, recreate it...
visualizedData = createVisualization(data);// ...and put the resulting image into cache
cache->insert(key, visualizedData);}// Show the visualizedData pixmap to user

This example creates a visual representation of some data. If the data is more recent than the cache, then contents of the cache are deleted using the discard() method. Next, we check if cache already contains the necessary pixmap. If it does, then there is no need to recreate it from the data (which might be expensive).