PyQt6(没有pyrcc)如何提供资源?

How can resources be provided in PyQt6 (which has no pyrcc)?

documentation for PyQt6 表示

Support for Qt’s resource system has been removed (i.e. there is no pyrcc6).

鉴于此,PyQt6应用程序应该如何提供资源?

PyQt 邮件列表上已经 some discussion 发现了这个问题。

维护者不再对维护 pyrcc 感兴趣,因为他认为考虑到 python 已经使用多个文件,它不会提供任何主要好处。

最简单的解决方案可能是使用 QDir 的静态方法 setSearchPaths() or addSearchPath()

不同之处在于,资源将使用用于上述方法的前缀加载。

考虑到之前的情况:

icon = QtGui.QIcon(':/icons/myicon.png')

现在会变成这样:

# somewhere at the beginning of your program
QtCore.QDir.addSearchPath('icons', 'path_to_icons/')

icon = QtGui.QIcon('icons:myicon.png')

共识似乎是应该使用现有的 python 设施而不是 pyrrc。因此资源将直接存储在文件系统中(可能在存档文件中),然后使用 importlib.resources (python >= 3.7), or pkg_resources, or a third-party solution like importlib_resources 定位。这究竟如何映射到 pyrcc 的现有用途可能会因应用程序而异,因此需要进行一些实验才能找到最佳方法。

有关如何使用这些设施的更多详细信息,请参阅:

  • How to read a (static) file from inside a Python package?

当我开始使用 PyQt6 时,我发现缺少对 Qt6 资源的完全支持。 特别是在使用设计器并将图像用于按钮、标签等时。 我尝试了 addSearchPath,但仍然必须编辑生成的 .py 模板。 经过一些研究,我发现使用 importlab 是解决我问题的最佳方法。

我制作了简单的脚本,它使用 .qrc 文件并使用 importpath 生成 .py 模板。

例如改变:

icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap(":/icons/icon1.png"), QtGui.QIcon.Mode.Normal, QtGui.QIcon.State.Off)

至:

icon = QtGui.QIcon()
with path("myPackage.resources.icons", "icon1.png") as f_path:
    icon.addPixmap(QtGui.QPixmap(str(f_path)), QtGui.QIcon.Mode.Normal, QtGui.QIcon.State.Off)

这是 GitLab 回购的 link:https://github.com/domarm-comat/pyqt6rc

或通过 pip 安装:

python3 -m pip install pyqt6rc