{
  "schemaVersion": "0.11.0",
  "canonical": "https://www.pystone.net/notes/python-qt-resource-system/",
  "atlas": "https://www.pystone.net/?node=python-qt-resource-system#knowledge-atlas",
  "markdown": "https://www.pystone.net/notes/python-qt-resource-system.md",
  "context": "https://www.pystone.net/notes/python-qt-resource-system.context.json",
  "knowledgeVersion": "224c990773de.5fa8af6e39fa",
  "build": {
    "siteCommit": "224c990773de166d23a886306577dd90379529ce",
    "notesCommit": "5fa8af6e39fa3891d1b9b4832bfa6c4e0ecaaf0a",
    "builtAt": "1970-01-01T00:00:00.000Z",
    "version": "224c990773de.5fa8af6e39fa"
  },
  "id": "note:python-qt-resource-system",
  "slug": "python-qt-resource-system",
  "title": "Python Qt Resource System的使用",
  "type": "note",
  "visibility": "public",
  "idStability": "rename-stable",
  "author": {
    "name": "Perrin Yong",
    "profile": "https://www.pystone.net/profile/"
  },
  "publisher": {
    "name": "Perrin Yong",
    "profile": "https://www.pystone.net/profile/"
  },
  "aliases": [],
  "summary": "Python Qt Resource System的使用 The Qt resource system is a platform independent mechanism for storing binary files in the application's executable. This is useful if your application always needs a certain set of files …",
  "contentRole": "unspecified",
  "isMoc": false,
  "mocRecognition": "none",
  "generated": false,
  "attribution": "unspecified",
  "domain": "10-计算机、信息技术与工程",
  "tags": [],
  "mocs": [],
  "contentHash": "41e21d4d852723d2be93263a3242bfc7b4245b1dedb1890d6a60db48be16c320",
  "assets": [
    {
      "reference": "assets/image-20240204123453364.png",
      "url": "/media/cc5d4decc41ae0041c5d.png",
      "mediaType": "image/png",
      "contentHash": "cc5d4decc41ae0041c5d30452c24f87a31acb589b54d3e49b45072498a66b5a4",
      "byteLength": 39538,
      "width": 878,
      "height": 350
    },
    {
      "reference": "assets/image-20240204123914189.png",
      "url": "/media/46baaea41f0c03249e67.png",
      "mediaType": "image/png",
      "contentHash": "46baaea41f0c03249e675175a00e9a1d45689a42c6cc67718cc46ec3df149830",
      "byteLength": 39472,
      "width": 869,
      "height": 366
    },
    {
      "reference": "assets/image-20240204125058844.png",
      "url": "/media/be891a9204ef488f2fd6.png",
      "mediaType": "image/png",
      "contentHash": "be891a9204ef488f2fd6b7f69636a1aec0b58f005c0ed904e2b7f9bacd240c14",
      "byteLength": 2826,
      "width": 283,
      "height": 59
    }
  ],
  "headings": [
    {
      "depth": 1,
      "text": "Python Qt Resource System的使用",
      "anchor": "python-qt-resource-system的使用",
      "citation": "https://www.pystone.net/notes/python-qt-resource-system/#python-qt-resource-system%E7%9A%84%E4%BD%BF%E7%94%A8"
    },
    {
      "depth": 2,
      "text": "基本用法",
      "anchor": "基本用法",
      "citation": "https://www.pystone.net/notes/python-qt-resource-system/#%E5%9F%BA%E6%9C%AC%E7%94%A8%E6%B3%95"
    },
    {
      "depth": 2,
      "text": "资源的初始化与清除",
      "anchor": "资源的初始化与清除",
      "citation": "https://www.pystone.net/notes/python-qt-resource-system/#%E8%B5%84%E6%BA%90%E7%9A%84%E5%88%9D%E5%A7%8B%E5%8C%96%E4%B8%8E%E6%B8%85%E9%99%A4"
    },
    {
      "depth": 2,
      "text": "利用qrc管理和读取资源文件",
      "anchor": "利用qrc管理和读取资源文件",
      "citation": "https://www.pystone.net/notes/python-qt-resource-system/#%E5%88%A9%E7%94%A8qrc%E7%AE%A1%E7%90%86%E5%92%8C%E8%AF%BB%E5%8F%96%E8%B5%84%E6%BA%90%E6%96%87%E4%BB%B6"
    },
    {
      "depth": 2,
      "text": "进阶用法",
      "anchor": "进阶用法",
      "citation": "https://www.pystone.net/notes/python-qt-resource-system/#%E8%BF%9B%E9%98%B6%E7%94%A8%E6%B3%95"
    },
    {
      "depth": 2,
      "text": "rcc的用法",
      "anchor": "rcc的用法",
      "citation": "https://www.pystone.net/notes/python-qt-resource-system/#rcc%E7%9A%84%E7%94%A8%E6%B3%95"
    },
    {
      "depth": 2,
      "text": "根据语言切换资源",
      "anchor": "根据语言切换资源",
      "citation": "https://www.pystone.net/notes/python-qt-resource-system/#%E6%A0%B9%E6%8D%AE%E8%AF%AD%E8%A8%80%E5%88%87%E6%8D%A2%E8%B5%84%E6%BA%90"
    },
    {
      "depth": 2,
      "text": "压缩",
      "anchor": "压缩",
      "citation": "https://www.pystone.net/notes/python-qt-resource-system/#%E5%8E%8B%E7%BC%A9"
    },
    {
      "depth": 2,
      "text": "Thanks",
      "anchor": "thanks",
      "citation": "https://www.pystone.net/notes/python-qt-resource-system/#thanks"
    }
  ],
  "claims": [],
  "outgoing": [],
  "incoming": [
    {
      "id": "note:application-and-cloud-engineering",
      "title": "应用开发与云端工程",
      "url": "https://www.pystone.net/notes/application-and-cloud-engineering/",
      "atlas": "https://www.pystone.net/?node=application-and-cloud-engineering#knowledge-atlas",
      "label": "应用开发与云端工程",
      "origin": "explicit",
      "humanReviewed": true,
      "context": "桌面应用开发中的“Python Qt Resource System的使用”导航项",
      "citation": "https://www.pystone.net/notes/application-and-cloud-engineering/#%E6%A1%8C%E9%9D%A2%E5%BA%94%E7%94%A8%E5%BC%80%E5%8F%91"
    }
  ],
  "contentMarkdown": "# Python Qt Resource System的使用\nThe Qt resource system is a platform-independent mechanism for storing binary files in the application's executable. This is useful if your application always needs a certain set of files (icons, translation files, etc.) and you don't want to run the risk of losing the files.\n\n在封装到exe文件时，UI资源文件需要再拷贝一份到dist路径下，不方便。\n使用qrc文件管理资源文件，并利用pyrcc5命令将qrc文件转为py文件，供Python使用。\n\nqrc文件是XML格式的资源配置文件，记录了硬盘上的文件和对应的资源名称。\n\n**由于qrc文件中的路径为相对路径，因此，qrc 文件中包含的资源文件必须位于.qrc文件所在路径或其子路径下。**\n\n\nqrc文件内容示例：\n\n```xml\n<RCC>\n  <qresource prefix=\"test_imgs\">\n    <file>images/blue_1.png</file>\n    <file>images/blue_2.png</file>\n  </qresource></RCC>\n```\n\n## 基本用法\n\n1. 使用QT Designer，可以在Resource Brower中，点击编辑按钮，对qrc进行编辑，配置qrc引用的资源的前缀和路径。\n![](assets/image-20240204123453364.png)\n\n2. 使用pyside6-rcc，将qrc编译成py脚本，即可将资源编译到py文件当中。\n\n```bat\nset RCC_EXE=C:\\Users\\[redacted-user]\\miniconda3\\envs\\python38\\Scripts\\pyside6-rcc.exe\nset RCC_SRC1=E:\\0-UWAGameCI\\4-Recorder\\ExperimentalBuild\\myapp\\res1.qrc\nset RCC_SRC2=E:\\0-UWAGameCI\\4-Recorder\\ExperimentalBuild\\myapp\\res2.qrc\n\n\"%RCC_EXE%\" -o E:\\0-UWAGameCI\\4-Recorder\\ExperimentalBuild\\myapp\\res1_rc.py \"%RCC_SRC1%\"\n\"%RCC_EXE%\" -o E:\\0-UWAGameCI\\4-Recorder\\ExperimentalBuild\\myapp\\res2_rc.py \"%RCC_SRC2%\"\n```\n\n3. 在代码中，通过导入资源对应的py文件，即可使用qrc中引用的资源。\n\n```python\nimport res1_rc\n## 或者\nimport res2_rc\n```\n\n 可以在Python代码中直接使用资源，也可以在QSS中引用资源。引用方式相同，不需要绑定qrc文件。\n```python\nself.label.setPixmap(QPixmap(\":/test_imgs/images/blue_2.png\"))\n```\n\n```css\nQLabel#label_1 {\n    background-image: url(:/test_imgs/images/green_1.png);\n    border: 2px solid red;\n    color: blue;\n}\n\nQLabel#label_2 {\n    background-image: url(:/test_imgs/images/green_2.png);\n    border: 2px solid green;\n    color: blue;\n}\n```\n\n```xml\n<qresource prefix=\"icons\">\n\t<file alias=\"Py_ico\">Icons/Python_icon.ico</file>\n</qresource>\n```\n\n```python\nicon = QPixmap(\":/icons/Py_ico\")\n```\n\n* 可将不同资源在不同的qrc文件中引用，分别进行编译、导入。使用方法完全相同，在导入资源后，只需要使用资源的路径即可，不需要指定是哪个qrc文件中的资源。\n![](assets/image-20240204123914189.png)\n\n\n* 在资源被加载后，执行使用资源文件的代码才会有效。如果QSS当中引用了qrc中的资源，那么在资源的_rc.py文件被加载后，需要重新调用setStyleSheet，才能生效。\n\n## 资源的初始化与清除\n\nqrc生成的_rc.py文件包括两个函数，分别用于资源数据的注册和清除。\n![](assets/image-20240204125058844.png)\n* 资源被注册后才可以被程序使用。\n* 资源被清除后，程序引用的资源不会被立即删除。但是后续的程序再引用资源时，资源会丢失。\n可使用以下代码对当前的资源进行注册或清除：\n```python\n\nimport res1_rc\nimport res2_rc\n\ndef switch_rc(self, rc_name):\n    if rc_name == \"res1_rc\":\n        res2_rc.qCleanupResources()\n        res1_rc.qInitResources()\n    elif rc_name == \"res2_rc\":\n        res1_rc.qCleanupResources()\n        res2_rc.qInitResources()\n```\n\n该方案只用于帮助对资源系统的理解，应该没有实际意义。\n\n## 利用qrc管理和读取资源文件\n\n```python\nfrom PySide6.QtCore import QFile, QIODevice\n\ndef get_about_text():\n\t# 使用Qt风格读取文本文件\n\tabout_file = QFile(\":/texts/About_Text\") # 使用Qt中的QFile类\n\tabout_file.open(QIODevice.ReadOnly | QIODevice.Text) # 打开文件\n\tabout_text = str(about_file.readAll(), encoding=\"utf-8\") # 读取文件，并将 QBtyeArray 转为 str\n\tabout_file.close()\n\treturn about_text\n```\n\n## 进阶用法\n## rcc的用法\n\n```shell\n$ pyside6-rcc --help\nUsage: /path/to/your/python3/site-packages/PySide6/Qt/libexec/rcc [options] inputs\nQt Resource Compiler version 6.4.1\n\nOptions:\n-h, --help 显示关于命令行选项的帮助\n--help-all 显示包括Qt独有选项在内的所有帮助\n-v, --version 显示版本信息\n-o, --output <file> 将输出写入到 <file> 中，而不是 stdout 中\n-t, --temp <file> 为大资源文件使用临时文件 <file>\n--name <name> 用 <name> 创建一个外部初始化函数\n--root  用根目录  作为资源访问路径的前缀\n--compress-algo <algo> 使用 <algo> 算法压缩输入文件([zlib], none)\n--compress <level> 按 <level> 级别压缩输入文件\n--no-compress 禁用所有压缩，等同于 --compress-algo=none\n--no-zstd 禁止使用 zstd 压缩\n--threshold <level> 衡量是否值得进行压缩的阈值\n--binary 输出一个作为动态资源使用的二进制文件\n-g, --generator <cpp|python|python2> 选择生成器\n--pass <number> Pass number for big resources\n--namespace 关闭命名空间宏\n--verbose 启用 verbose 模式\n--list 只列出 .qrc 文件条目，不生成代码\n--list-mapping 只输出 .qrc 中定义的资源路径与文件系统路径的\n映射，不生成代码\n-d, --depfile <file> 向 <file> 中写入一个包含 .qrc 依赖项的 depfile\n--project 输出一个包含当前目录下所有文件的资源文件\n--format-version <number> 写入 RCC 格式的版本\nArguments:\ninputs 输入文件 (*.qrc)\n```\n\n\n## 根据语言切换资源\n\n```xml\n<qresource>\n\t<file>cut.jpg</file>\n</qresource>\n<qresource lang=\"fr\">\n\t<file alias=\"cut.jpg\">cut_fr.jpg</file>\n</qresource>\n```\n当系统语言为其他语言时，Qt 程序将会使用文件 `cut.jpg`；而当系统语言为法语时，会自动替换为 `cut_fr.jpg`。\n\n## 压缩\nrcc 会尝试压缩内容以优化硬盘空间使用。默认情况下，它将进行启发式检查以确认是否值得压缩。如果不能充分压缩，则将直接存储非压缩的内容。可以使用 `-threshold` [选项](https://muzing.top/posts/75a2283d/#rcc-%E5%91%BD%E4%BB%A4%E8%A1%8C%E9%80%89%E9%A1%B9)控制此判断的阈值。例如，默认情况下阈值为 70，表示只有在压缩后的文件比原文件小 70%（不超过原文件大小的 30%）时才有必要压缩。\n```shell\nrcc -threshold 25 myresources.qrc\n```\n\n在某些情况下也可以关闭压缩功能。一种常见情况是，某些资源已经是压缩后的格式（例如 `.png` 文件），再次压缩几乎不会进一步减小文件体积，但会占用 CPU 成本。另一种情况是，硬盘空间非常充裕，期望应用程序在运行时可以将内容存储在干净的内存页中。在[命令行](https://muzing.top/posts/75a2283d/#rcc-%E5%91%BD%E4%BB%A4%E8%A1%8C%E9%80%89%E9%A1%B9)中添加 `-no-compress` 命令以关闭压缩。\n\n```shell\nrcc -no-compress myresources.qrc\n```\n\n\nhttps://blog.csdn.net/qq_32892383/article/details/108867482?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522163876323716780261931301%2522%252C%2522scm%2522%253A%252220140713.130102334..%2522%257D&request_id=163876323716780261931301&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~top_positive~default-1-108867482.first_rank_v2_pc_rank_v29&utm_term=%E5%AE%89%E8%A3%85pyqt5&spm=1018.2226.3001.4187\n\nhttps://blog.csdn.net/gongjianbo1992/article/details/105361880\n\nhttps://muzing.top/posts/75a2283d/\n\nhttps://www.youtube.com/watch?v=9srbSGYnfM8\n\nhttps://www.bilibili.com/video/BV19s411b7gH/?spm_id_from=333.337.search-card.all.click&vd_source=37d77b0c4f47ce9562d64df16c394303\n\nhttps://www.bilibili.com/video/BV1Hz411e7Kx/?spm_id_from=333.337.search-card.all.click&vd_source=37d77b0c4f47ce9562d64df16c394303\n\n\n## Thanks\nhttps://blog.csdn.net/qq_26915769/article/details/84535106\n\nhttps://doc.qt.io/qtforpython-6/tutorials/basictutorial/qrcfiles.html\n\nhttps://muzing.top/posts/75a2283d/\n"
}
