如何修复 PySide2 QPixmapCache.find() DeprecationWarning?

How to fix PySide2 QPixmapCache.find() DeprecationWarning?

我目前正在将一个大型应用程序从 Py2/PySide 1.2.4 移植到 Py3/PySide2 5.13.0,我发现了一个与使用相关的 DeprecationWarningQPixmapCache.find(key, pixmap).

c:\path\to\module.py:220: DeprecationWarning: QPixmapCache.find(const QString & key, QPixmap & pixmap) is deprecated
  if (QPixmapCache.find("image_key", pixmap) is False):

我想修复这个弃用警告,但是 documentation 不是很有用,因为它:

那么,对于 PySide2.QtGui.QPixmapCache.find(key, pixmap) 的弃用用法,建议的修复方法是什么?

建议的解决方法是避免将像素图作为第二个参数传递给 find,因为它并不是真正需要的(见下文)。所以你的代码应该简单地更改为:

pixmap = QPixmapCache.find("image_key")
if pixmap is None:
    ...

包含带有第二个参数的方法似乎是 PySide2 中的错误(或功能不全)。它可能应该只实现这两个重载:

  • find(str) -> QPixmap

  • find(QPixmapCache.Key) -> QPixmap

其他方法更特定于 C++,目前它们的定义如下:

  • find(const QString &key, QPixmap *pixmap) -> bool

  • find(const QPixmapCache::Key &key, QPixmap *pixmap) -> bool

此处的第二个参数是一个 指针,Qt 将其设置为找到的像素图。它必须在 C++ 中以这种方式完成,因为无法 return 一个 (bool, QPixmap) 的元组,就像在 Python 中可能已经完成的那样。同样的道理,在 PySide 中实现这样的方法意义不大,因为 Python 中没有指针。 (我猜不推荐使用的方法在传入的参数上使用类似 QPixmap.swap 的东西来获得类似的行为)。

当前 API/documentation 中的混乱应该在 PySide bug tracker 上报告。作为参考,PyQt5 只实现了上面显示的前两个方法,这似乎是最 pythonic 的做事方式。很难找到为什么应该包含任何其他重载的充分理由(除了向后兼容)。

正如 @ekhumoro 指出的那样,它看起来像是一个错误,但以下方法目前使用 QPixmapCache::Key:

from PySide2 import QtGui

if __name__ == '__main__':
    import sys

    app = QtGui.QGuiApplication(sys.argv)

    filename = "test.png"

    key = QtGui.QPixmapCache.Key()
    pm  = QtGui.QPixmap()

    for i in range(100):
        pix = QtGui.QPixmapCache.find(key)
        if pix is None:
            pm.load(filename)
            key = QtGui.QPixmapCache.insert(pm)
            print("load from filename")
        else:
            pm = pix

输出:

load from filename

所以实际上单参数版本 PySide2.QtGui.QPixmapCache.find(key) 也会引发 DeprecationWarning。最后,它必须按照@eyllanesc 提议的方式进行修复,这对我来说有点不方便,因为我事先从散列数据生成了密钥。赞成这两个答案并接受了@eyllanesc 的答案。谢谢!