【问题标题】:"QPushButton" has no attribute "clicked" according to mypy根据 mypy,\"QPushButton\" 没有属性 \"clicked\"
【发布时间】:2023-02-01 17:35:43
【问题描述】:

当我使用 --strict 标志运行 mypy 时,它会抱怨“QPushButton”没有属性“clicked”。 Pycharm 也抱怨这个问题。尽管如此,代码运行良好。例如:

import sys

from PySide6.QtWidgets import QApplication, QPushButton, QVBoxLayout, QWidget


class Window(QWidget):
    def __init__(self) -> None:
        super().__init__()
        self.setWindowTitle("My App")
        self.resize(500, 500)
        layout = QVBoxLayout()
        self.btn = QPushButton("Click Me")
        self.btn.clicked.connect(self.btn_clicked)
        layout.addWidget(self.btn)
        self.setLayout(layout)
        self.show()

    def btn_clicked(self) -> None:
        print("Button clicked")


app = QApplication(sys.argv)
w = Window()
w.show()
sys.exit(app.exec())

运行 mypy . --strict 会引发以下错误:

example.py:13: error: "QPushButton" has no attribute "clicked"
Found 1 error in 1 file (checked 1 source file)

我正在做的事情是不好的做法吗?大多数在线文档,包括 Qt 的官方 Python 文档,都说以这种方式将按钮连接到函数。

如果这不是坏习惯,有没有办法让 Pycharm 和 mypy 不抱怨这种连接按钮的方式?

【问题讨论】:

  • 不要过于执着于“代码纯度”。一个语法检查器,尽管它很聪明,但它仍然是一个程序,并且可能是“错误的”。这种方法是绝对正确的,问题是你可能遗漏了存根:github.com/stlehmann/PyQt5-stubs
  • ...当然,您可以在 PyCharm 的“检查”中禁用此检查。
  • 请参阅以下问题:PYSIDE-1603 和 PYSIDE-1675。并注意 mypy 只是一个静态类型检查器,因此它报告的任何所谓的“错误”都与运行时行为无关。

标签: python qt pyqt pyside mypy


【解决方案1】:

正如@noEmbryo 和@ekhumoro 在 cmets 中所写的那样:

我正在做的事情是不好的做法吗?

不。您按照官方文档进行操作是正确的。问题是为 PySide 生成的类型中存在错误。 PySide/Qt 是用 C++ 编写的,并且只为它生成了 Python 绑定。

对 Python 的类型支持是相当新的,并且仍在积极开发中。 所以通常你会不时遇到麻烦使用它。 这也意味着没有直接的方法将 C++ 类型信息转换为 Python 类型信息。

有没有办法让 Pycharm 和 mypy 不抱怨这种连接按钮的方式?

是的。存在三种可能性:

  1. 等到错误在 PySide 中修复(即在版本 6.5.0 中,但如果你查看 related issue,还有一些旧版本的反向移植)

  2. 忽略给定的错误(因为它在 PySide 的上游没有修复)

            self.btn.clicked.connect(self.btn_clicked)  # type: ignore[attr-defined]
    
    1. 围绕 Button 创建一个 Wrapper 来告诉类型检查器,clicked 属性确实存在。 使用 typing.Any 告诉类型检查器,clicked 属性实际上可以是任何东西。所以类型检查器并没有真正检查它使用了什么。
    import typing
    import sys
    
    from PySide6.QtWidgets import QApplication, QPushButton, QVBoxLayout, QWidget
    
    class QPushButtonWithSignals(QPushButton):
        """Remove attributes below once Signal typing issues are fixed upstream"""
        clicked: typing.Any
        # Add other missing Signal here if used
    
    
    class Window(QWidget):
        def __init__(self) -> None:
            super().__init__()
            self.setWindowTitle("My App")
            self.resize(500, 500)
            layout = QVBoxLayout()
            self.btn = QPushButtonWithSignals("Click Me")
            self.btn.clicked.connect(self.btn_clicked)
    …
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-19
    • 1970-01-01
    • 2021-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    相关资源
    最近更新 更多