2
votes

My program is using several different QTextBrowsers to show contents to user. Some of these contents have images. which I load from file into QPixmaps and add them to the text document to show.

Suppose a code like this:

QTextBrowser* browser = new QTextBrowser(this);
//Codes to add the browser to GUI
QPixmap pix;
pix.load(file_address);

browser->document()->addResource(QTextDocument::ImageResource, QUrl("url://Test1"), pix);
browser->setHtml( "<img src='url://Test1' width=120 height=90 />" );

Later on, I no longer need the browser, so delete it:

browser->deleteLater();

Now my problem is: how can I remove resources that were added to this deleted browser, from cache?

QTextDocument's document mentions that:

void QTextDocument::addResource(int type, const QUrl & name, const QVariant & resource) Adds the resource resource to the resource cache, using type and name as identifiers.

So, the resource remains in cache until I close the application. But I need to clear it beforehand, because there are lots of resources being added to the cache, and the app could be running for several days in a row.

1

1 Answers

1
votes

Cached resources are attached to the QTextDocument instance (not a global cache), and will be freed when the document is destroyed, or when QTextDocument::clear() is called. You can see in the source code:

  • 1: QTextDocument::resource calls loadResource to actually read the file contents.
  • 2: loadResource stores the resource contents in the cachedResources member

As this is a member of the private class associated with the QTextDocument instance, it will have the same lifetime.