QTextDocument:如何从缓存中删除资源

QTextDocument: How to remove a resource from cache

我的程序使用几个不同的 QTextBrowser 向用户显示内容。其中一些内容带有图像。我将其从文件加载到 QPixmaps 并将它们添加到要显示的文本文档中。

假设这样的代码:

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 />" );

后来我不再需要浏览器了,所以删除它:

browser->deleteLater();

现在我的问题是:如何从缓存中删除添加到此已删除浏览器的资源?

QTextDocumentdocument 提到:

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.

因此,在我关闭应用程序之前,资源一直保留在缓存中。但是我需要事先清除它,因为有很多资源被添加到缓存中,应用程序可能会连续几天运行。

缓存的资源附加到 QTextDocument 实例(不是全局缓存),并且会在文档被销毁或调用 QTextDocument::clear() 时被释放。在源码中可以看到:

  • 1: QTextDocument::resource 调用 loadResource 实际读取文件内容。
  • 2: loadResource 将资源内容存储在 cachedResources 成员

由于这是与 QTextDocument 实例关联的私有 class 的成员,因此它将具有相同的生命周期。