Mypy 在 PyQT 中的每个 connect() 上显示“Callable ...没有属性“connect”

问题描述

使用PyQt5写代码,使用mypy查找类型错误。但是 mypy 在每个 connect() 上都会发现错误,例如在这个简单文件上:

from PyQt5 import QtWidgets

class TestClass(QtWidgets.QDialog):
    def __init__(self) -> None:
        super().__init__()
        self.accepted.connect(self.accept)

我有 mypy 错误1.py:6: error: "Callable[[],None]" has no attribute "connect"

有什么办法可以解释mypy它是正确的代码吗?我不想对他使用“忽略”评论...

解决方法

为 PyQt5 安装 PyQt5-stubs 类型的存根。

>mypy test.py
test.py:6: error: "Callable[[],None]" has no attribute "connect"
Found 1 error in 1 file (checked 1 source file)

>pip install PyQt5-stubs
Collecting PyQt5-stubs
  Downloading PyQt5_stubs-5.15.2.0-py3-none-any.whl (371 kB)
     |████████████████████████████████| 371 kB 3.3 MB/s
Installing collected packages: PyQt5-stubs
Successfully installed PyQt5-stubs-5.15.2.0

>mypy test.py
Success: no issues found in 1 source file