【问题标题】:How to fix PySide2 QPixmapCache.find() DeprecationWarning?如何修复 PySide2 QPixmapCache.find() DeprecationWarning?
【发布时间】:2019-08-13 20:02:22
【问题描述】:

我目前正在将一个大型应用程序从 Py2/PySide 1.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),建议的修复方法是什么?

【问题讨论】:

    标签: python python-3.x pyside2 deprecation-warning


    【解决方案1】:

    正如@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
    

    【讨论】:

      【解决方案2】:

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

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

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

      • 查找(str) -> QPixmap

      • 查找(QPixmapCache.Key) -> QPixmap

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

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

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

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

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

      【讨论】:

        【解决方案3】:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-02-19
          • 2020-06-08
          • 2021-08-02
          • 2021-05-25
          • 2019-06-28
          • 1970-01-01
          • 2019-02-18
          • 1970-01-01
          相关资源
          最近更新 更多