如何使用 intersphinx 正确链接到 PyQt5 文档?

2024-03-07

我在尝试链接到时遇到了一些麻烦PyQt5 文档 http://pyqt.sourceforge.net/Docs/PyQt5/ using intersphinx.

尝试交叉引用任何QtCore类(例如QThread)没有像我预期的那样工作。我已经解析了objects.inv可用的here http://pyqt.sourceforge.net/Docs/PyQt5/objects.inv using python -m sphinx.ext.intersphinx objects.inv,其结果如下所示的输出gist https://gist.github.com/jat255/f1c86a41399d26ddf43b70ee8a6d6b92.

不幸的是,在 python 命名空间下没有类,只有几个函数。一切PyQt5- 相关的是sip:class命名空间。尝试使用标准在文档中引用这一点:py:class:语法不链接到任何东西(因为sphinx看不到该引用连接到任何东西),并且使用:sip:class:引起警告Unknown interpreted text role "sip:class",这是有道理的,因为这不是已知的参考代码。

那么,我们如何通过 intersphinx 访问 PyQt 的文档(如果可以的话)?


编辑: 我用这个解决方案创建 python 包:https://pypi.org/project/sphinx-qt-documentation/ https://pypi.org/project/sphinx-qt-documentation/

原答案:

我使用另一种方法来解决这个问题。我创建自定义 sphinx 插件来翻译要使用的即时清单文件sip领域。它允许选择应指向哪个文档(请参阅顶部的文档字符串)。它适用于我的项目,但我不确定它是否支持所有情况。

这个扩展需要sphinx.ext.intersphinx要在 sphinx 扩展中配置的扩展以及PyQt在映射中配置

intersphinx_mapping = {...,
                       "PyQt": ("https://www.riverbankcomputing.com/static/Docs/PyQt5", None)}
"""
This module contains sphinx extension supporting for build PartSeg documentation.

this extensio provides one configuration option:

`qt_documentation` with possibe values:

 * PyQt - linking to PyQt documentation on https://www.riverbankcomputing.com/static/Docs/PyQt5/api/ (incomplete)
 * Qt - linking to Qt documentation on "https://doc.qt.io/qt-5/" (default)
 * PySide - linking to PySide documentation on  "https://doc.qt.io/qtforpython/PySide2/"
"""
import re
from sphinx.application import Sphinx
from sphinx.environment import BuildEnvironment
from docutils.nodes import Element, TextElement
from docutils import nodes
from typing import List, Optional, Dict, Any
from sphinx.locale import _

from sphinx.ext.intersphinx import InventoryAdapter

try:
    from qtpy import QT_VERSION
except ImportError:
    QT_VERSION = None

# TODO add response to
#  https://stackoverflow.com/questions/47102004/how-to-properly-link-to-pyqt5-documentation-using-intersphinx

signal_slot_uri = {
    "Qt": "https://doc.qt.io/qt-5/signalsandslots.html",
    "PySide": "https://doc.qt.io/qtforpython/overviews/signalsandslots.html",
    "PyQt": "https://www.riverbankcomputing.com/static/Docs/PyQt5/signals_slots.html"
}

signal_name = {
    "Qt": "Signal",
    "PySide": "Signal",
    "PyQt": "pyqtSignal"
}

slot_name = {
    "Qt": "Slot",
    "PySide": "Slot",
    "PyQt": "pyqtSlot"
}

signal_pattern = re.compile(r'((\w+\d?\.QtCore\.)|(QtCore\.)|(\.)())?(pyqt)?Signal')
slot_pattern = re.compile(r'((\w+\d?\.QtCore\.)|(QtCore\.)|(\.)())?(pyqt)?Slot')

def missing_reference(app: Sphinx, env: BuildEnvironment, node: Element, contnode: TextElement
                      ) -> Optional[nodes.reference]:
    """Linking to Qt documentation."""
    target: str = node['reftarget']
    inventories = InventoryAdapter(env)
    objtypes = None  # type: Optional[List[str]]
    if node['reftype'] == 'any':
        # we search anything!
        objtypes = ['%s:%s' % (domain.name, objtype)
                    for domain in env.domains.values()
                    for objtype in domain.object_types]
        domain = None
    else:
        domain = node.get('refdomain')
        if not domain:
            # only objects in domains are in the inventory
            return None
        objtypes = env.get_domain(domain).objtypes_for_role(node['reftype'])
        if not objtypes:
            return None
        objtypes = ['%s:%s' % (domain, objtype) for objtype in objtypes]
    if target.startswith("PySide2"):
        head, tail = target.split(".", 1)
        target = "PyQt5." + tail
    obj_type_name = "sip:{}".format(node.get("reftype"))
    if obj_type_name not in inventories.named_inventory["PyQt"]:
        return None
    target_list = [target, "PyQt5." + target]
    target_list += [name + "." + target for name in inventories.named_inventory["PyQt"]["sip:module"].keys()]
    if signal_pattern.match(target):
        uri = signal_slot_uri[app.config.qt_documentation]
        dispname = signal_name[app.config.qt_documentation]
        version = QT_VERSION
    elif slot_pattern.match(target):
        uri = signal_slot_uri[app.config.qt_documentation]
        dispname = slot_name[app.config.qt_documentation]
        version = QT_VERSION
    else:
        for target_name in target_list:
            if target_name in inventories.main_inventory[obj_type_name]:
                proj, version, uri, dispname = inventories.named_inventory["PyQt"][obj_type_name][target_name]
                print(node)  # print nodes with unresolved references
                break
        else:
            return None
        if app.config.qt_documentation == "Qt":
            html_name = uri.split("/")[-1]
            uri = "https://doc.qt.io/qt-5/" + html_name
        elif app.config.qt_documentation == "PySide":
            html_name = "/".join(target.split(".")[1:]) + ".html"
            uri = "https://doc.qt.io/qtforpython/PySide2/" + html_name

    # remove this line if you would like straight to pyqt documentation
    if version:
        reftitle = _('(in %s v%s)') % (app.config.qt_documentation, version)
    else:
        reftitle = _('(in %s)') % (app.config.qt_documentation,)
    newnode = nodes.reference('', '', internal=False, refuri=uri, reftitle=reftitle)
    if node.get('refexplicit'):
        # use whatever title was given
        newnode.append(contnode)
    else:
        # else use the given display name (used for :ref:)
        newnode.append(contnode.__class__(dispname, dispname))
    return newnode


def setup(app: Sphinx) -> Dict[str, Any]:
    app.connect('missing-reference', missing_reference)
    app.add_config_value('qt_documentation', "Qt", True)
    return {
        'version': "0.9",
        'env_version': 1,
        'parallel_read_safe': True
    }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 intersphinx 正确链接到 PyQt5 文档? 的相关文章

  • 如何指定聚类的距离函数?

    我想对给定距离的点进行聚类 奇怪的是 似乎 scipy 和 sklearn 聚类方法都不允许指定距离函数 例如 在sklearn cluster AgglomerativeClustering 我唯一可以做的就是输入一个亲和力矩阵 这将非常
  • 将 yerr/xerr 绘制为阴影区域而不是误差线

    在 matplotlib 中 如何将误差绘制为阴影区域而不是误差条 例如 而不是 忽略示例图中各点之间的平滑插值 这需要进行一些手动插值 或者只是获得更高分辨率的数据 您可以使用pyplot fill between https matpl
  • McNemar 在 Python 中的测试以及分类机器学习模型的比较 [关闭]

    Closed 此问题正在寻求书籍 工具 软件库等的推荐 不满足堆栈溢出指南 help closed questions 目前不接受答案 有没有用 Python 实现的好的 McNemar 测试 我在 Scipy stats 或 Scikit
  • 如何为未捕获的异常处理程序编写单元测试

    我有一个函数可以捕获uncaught例外情况 如下 有没有办法编写一个单元测试来执行uncaught exception handler 功能正常 但测试正常退出 import logging def config logger logge
  • 如何在python中附加两个字节?

    说你有b x04 and b x00 你如何将它们组合起来b x0400 使用Python 3 gt gt gt a b x04 gt gt gt b b x00 gt gt gt a b b x04 x00
  • 尝试从网页Python和BeautifulSoup获取编码

    我试图从网页检索字符集 这会一直改变 目前我使用 beautifulSoup 来解析页面 然后从标题中提取字符集 这工作正常 直到我遇到一个网站 到目前为止 我的代码以及与其他页面一起使用的代码是 def get encoding soup
  • 将 C++ 指针作为参数传递给 Cython 函数

    cdef extern from Foo h cdef cppclass Bar pass cdef class PyClass cdef Bar bar def cinit self Bar b bar b 这总是会给我类似的东西 Can
  • 使用 Pytest 的参数化添加测试功能的描述

    当其中一个测试失败时 可以在测试正在测试的内容的参数化中添加描述 快速了解测试失败的原因 有时您不知道测试失败的原因 您必须查看代码 通过每个测试的描述 您就可以知道 例如 pytest mark parametrize num1 num2
  • OpenCV 跟踪器:模型未在函数 init 中初始化

    在视频的第一帧 我运行一个对象检测器 它返回对象的边界框 如下所示
  • 在Python中读取tiff标签

    我正在尝试用 Python 读取 tiff 文件的标签 该文件是 RGB 的uint16每个通道的值 我目前正在使用tifffile import tifffile img tifffile imread file tif 然而 img是一
  • PIL.Image.open和tf.image.decode_jpeg返回值的区别

    我使用 PIL Image open 和 tf image decode jpeg 将图像文件解析为数组 但发现PIL Image open 中的像素值与tf image decode jpeg不一样 为什么会出现这种情况 Thanks 代
  • 为正则表达式编写解析器

    即使经过多年的编程 我很羞愧地说我从未真正完全掌握正则表达式 一般来说 当问题需要正则表达式时 我通常可以 在一堆引用语法之后 想出一个合适的正则表达式 但我发现自己越来越频繁地使用这种技术 所以 自学并理解正则表达式properly 我决
  • 无法在 PyCharm 版本 9.3.3 中安装 NumPy。 Python版本3.8.2

    在 PyCharm 中安装 NumPy 时出错 尝试安装 Microsoft Visual C 14 0 还是行不通 NumPy 正在通过命令安装pip3 install numpy在 cmd 终端中 但是当尝试将其安装在 PyCharm
  • 将字符串中的随机字符转换为大写

    我尝试随机附加文本字符串 这样就不只是有像这样的输出 gt gt gt david 我最终会得到类似的东西 gt gt gt DaViD gt gt gt dAviD 我现在的代码是这样的 import random import stri
  • 根据多个阈值将 SciPy 分层树状图切割成簇

    我想将 SciPy 的树状图切割成多个具有多个阈值的簇 我尝试过使用 fcluster 但它只能削减一个阈值 例如 这是我从另一个问题中摘取的一段代码 import pandas data pandas DataFrame total ru
  • 仅允许正小数

    在我的 Django 模型中 我创建了一个如下所示的小数字段 price models DecimalField u Price decimal places 2 max digits 12 显然 价格为负或零是没有意义的 有没有办法将小数
  • PyQt5:如何使QThread返回数据到主线程

    I am a PyQt 5 4 1 1初学者 我的Python是3 4 3 这是我尝试遵循的many https mayaposch wordpress com 2011 11 01 how to really truly use qthr
  • 将时间添加到日期时间

    我有一个像这样的日期字符串 然后使用strptime 所以就像这样 my time datetime datetime strptime 07 05 15 m d Y 现在我想添加 23 小时 59 分钟my time 我努力了 timed
  • 在matlab中,如何读取python pickle文件?

    在 python 中 我生成了一个 p 数据文件 pickle dump allData open myallData p wb 现在我想在Matlab中读取myallData p 我的Matlab安装在Windows 8下 其中没有Pyt
  • 如何通过点击复制 folium 地图上的标记位置?

    I am able to print the location of a given marker on the map using folium plugins MousePosition class GeoMap def update

随机推荐