如何修复PySide2QPixmapCache.find文件()折旧警告?

2024-09-28 21:52:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在将一个大型应用程序从Py2/pyside1.2.4移植到Py3/PySide2 5.13.0,并发现了一个与使用QPixmapCache.find(key, pixmap)相关的DeprecationWarning。你知道吗

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)
  • 有两个static PySide2.QtGui.QPixmapCache.find(key, pixmap)
    • 其中一个列为已弃用。你知道吗
    • 另一个不是。你知道吗
  • 似乎没有关于现代用法的建议。(或者我没找到)。你知道吗

那么,对于不推荐使用的PySide2.QtGui.QPixmapCache.find(key, pixmap),建议采用什么修复方法呢?你知道吗


Tags: topathkey应用程序ispy3find建议
3条回答

建议的修复方法是避免将pixmap作为第二个参数传递给find,因为实际上并不需要它(见下文)。因此,您的代码应该简单地更改为:

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

包含第二个参数的方法似乎是PySide2中的一个bug(或错误特性)。它可能只应该实现这两个重载:

  • find(str) -> QPixmap

  • find(QPixmapCache.Key) -> QPixmap

其他方法更具体的C++,它们当前定义如下:

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

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

这里的第二个参数是一个指针,Qt将该指针设置为找到的pixmap。必须在C++中这样做,因为没有办法返回一个^ {< 2CD> }的元组,正如Python中可能已经做过的那样。同样,在PySide中实现这样的方法也没有什么意义,因为Python中没有指针。(我猜不推荐使用的方法在传入的参数上使用类似于QPixmap.swap的东西来获得类似的行为)。你知道吗

当前API/文档中的混乱应该在PySide bug tracker上报告。作为参考,PyQt5只实现上面显示的前两个方法,这似乎是最python的方式。很难找到一个好的理由来解释为什么应该包含任何其他重载(除了向后兼容性)。你知道吗

因此实际上,单参数版本PySide2.QtGui.QPixmapCache.find(key)也会引发一个DeprecationWarning。最后,它必须以@eyllanesc建议的方式修复,这在我的情况下有点不方便,因为我事先从散列数据生成了密钥。两个答案都投了赞成票,并接受了@eyllanesc的答案。谢谢!你知道吗

正如@ekhumoro指出的那样,它看起来像一个bug,但是下面的方法目前使用QPixmapCache::键工作:

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

相关问题 更多 >